Make strings be char[n]

This commit is contained in:
Sofia 2026-04-14 17:01:08 +03:00
parent 26779414a7
commit d3f0a730fd
4 changed files with 24 additions and 3 deletions

View File

@ -53,6 +53,24 @@ namespace types {
std::shared_ptr<Type> casted_ty, std::shared_ptr<Type> casted_ty,
std::shared_ptr<Type> target_ty) { std::shared_ptr<Type> target_ty) {
if (casted_ty->m_kind == types::TypeKind::Array && target_ty->m_kind == types::TypeKind::Pointer) {
auto array_ty = dynamic_cast<types::ArrayType*>(casted_ty.get());
auto ptr_ty = dynamic_cast<types::PointerType*>(target_ty.get());
if (!types_equal(array_ty->m_inner, ptr_ty->m_inner))
return {};
return CastDefinition{ casted_ty, target_ty, true,
[](codegen::Builder& builder, std::shared_ptr<Type> target, llvm::Value* value) {
auto ptr_ty = dynamic_cast<types::PointerType*>(target.get());
std::vector<llvm::Value*> indices {};
indices.push_back(llvm::ConstantInt::get(
builder.builder->getInt32Ty(),
0
));
return builder.builder->CreateGEP(ptr_ty->m_inner->codegen(builder), value, indices, "cast_gep");
} };
}
for (auto& cast : casts) { for (auto& cast : casts) {
if (types_equal(cast.casted_ty, casted_ty) && types_equal(cast.target_ty, target_ty)) { if (types_equal(cast.casted_ty, casted_ty) && types_equal(cast.target_ty, target_ty)) {
return cast; return cast;

View File

@ -26,8 +26,10 @@ namespace AST {
} }
codegen::StackValue StringLiteralExpression::codegen(codegen::Builder& builder, codegen::Scope&) { codegen::StackValue StringLiteralExpression::codegen(codegen::Builder& builder, codegen::Scope&) {
auto stack_type = new types::ArrayType{
auto stack_type = new types::PointerType{ std::make_unique<types::FundamentalType>(types::FundamentalTypeKind::Char) }; std::make_unique<types::FundamentalType>(types::FundamentalTypeKind::Char),
static_cast<uint32_t>(this->m_value.size()) + 1
};
auto str = llvm::StringRef{ this->m_value.c_str() }; auto str = llvm::StringRef{ this->m_value.c_str() };

View File

@ -89,7 +89,7 @@ namespace AST {
auto char_ty = std::shared_ptr<types::Type>{ auto char_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Char } new types::FundamentalType{ types::FundamentalTypeKind::Char }
}; };
auto ptr_ty = new types::PointerType{ char_ty }; auto ptr_ty = new types::ArrayType{ char_ty, static_cast<uint32_t>(this->m_value.size()) + 1 };
return std::shared_ptr<types::Type>{ptr_ty}; return std::shared_ptr<types::Type>{ptr_ty};
} }

1
test.c
View File

@ -17,6 +17,7 @@ int main() {
somelist[0] = 15; somelist[0] = 15;
somelist[1] = 20; somelist[1] = 20;
somelist[2] = 25;
return somelist[0]; return somelist[0];
} }