Compare commits

...

19 Commits

Author SHA1 Message Date
4baeaff705 Add rest of typechecking 2026-04-13 18:26:47 +03:00
8314fe2b61 Use binops for codegen as well 2026-04-13 18:24:07 +03:00
1037024730 Add binops for typechecker 2026-04-13 18:18:25 +03:00
d6b730945c Check binops 2026-04-13 18:17:33 +03:00
bb4d1c6045 Add binops 2026-04-13 18:11:54 +03:00
9791c9c8da Add binops.h and binops.cpp 2026-04-13 18:00:47 +03:00
e3e0cd9f9f Check return type as well 2026-04-13 17:25:36 +03:00
3f4b8569ea Fix bug with parameter typechecking 2026-04-13 17:23:53 +03:00
185f25d412 Typecheck parameter types 2026-04-13 17:21:07 +03:00
a901806dfb Add a function to test if types are equal 2026-04-13 17:09:50 +03:00
8ec4e538f5 Fix a bug, add type kind 2026-04-13 16:56:33 +03:00
cf965dd47a Fix some bugs 2026-04-13 16:50:29 +03:00
5ed26f4139 Perform typechecking 2026-04-13 01:22:14 +03:00
85dbce112f Fill typechecking methods 2026-04-13 01:08:34 +03:00
d11da4d1e6 Make expressions return type on typecheck 2026-04-13 00:55:38 +03:00
902610aaea Add statement typecheckings 2026-04-13 00:54:14 +03:00
44c9e31556 Make types in the AST be shared_ptr 2026-04-13 00:40:05 +03:00
e45f120f1c Add typecheck-functions to AST 2026-04-13 00:35:14 +03:00
5706a81098 Separate errors to own header-file 2026-04-13 00:24:18 +03:00
13 changed files with 530 additions and 75 deletions

View File

@ -15,7 +15,16 @@ separate_arguments(LLVM_DEFINITIONS_LIST NATIVE_COMMAND ${LLVM_DEFINITIONS})
add_definitions(${LLVM_DEFINITIONS_LIST})
# Executable
add_executable(${PROJECT_NAME} src/main.cpp src/tokens.cpp src/parsing.cpp src/ast.cpp src/codegen.cpp src/types.cpp)
add_executable(${PROJECT_NAME}
src/main.cpp
src/tokens.cpp
src/parsing.cpp
src/ast.cpp
src/codegen.cpp
src/types.cpp
src/typechecker.cpp
src/binops.cpp
)
target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20)
target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Weffc++ -Wextra -Wpedantic -Werror)

View File

@ -1,14 +1,16 @@
#ifndef AST_H
#define AST_H
#include "codegen.h"
#include "types.h"
#include "tokens.h"
#include <string>
#include <vector>
#include <memory>
#include "codegen.h"
#include "types.h"
#include "binops.h"
#include "tokens.h"
#include "typechecker.h"
namespace AST {
class Node {
public:
@ -23,12 +25,18 @@ namespace AST {
public:
Expression(token::Metadata meta) : Node{ meta } {}
virtual codegen::StackValue codegen(codegen::Builder& builder, codegen::Scope& scope) = 0;
virtual std::shared_ptr<types::Type> typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>> expected_ty
) = 0;
};
class Statement : public Node {
public:
Statement(token::Metadata meta) : Node{ meta } {}
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) = 0;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) = 0;
};
class IntLiteralExpression : public Expression {
@ -39,6 +47,11 @@ namespace AST {
virtual ~IntLiteralExpression() override = default;
virtual std::string formatted() override;
virtual codegen::StackValue codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual std::shared_ptr<types::Type> typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>> expected_ty
) override;
};
class StringLiteralExpression : public Expression {
@ -49,6 +62,11 @@ namespace AST {
virtual ~StringLiteralExpression() override = default;
virtual std::string formatted() override;
virtual codegen::StackValue codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual std::shared_ptr<types::Type> typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>> expected_ty
) override;
};
class ValueReferenceExpression : public Expression {
@ -59,6 +77,11 @@ namespace AST {
virtual ~ValueReferenceExpression() override = default;
virtual std::string formatted() override;
virtual codegen::StackValue codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual std::shared_ptr<types::Type> typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>> expected_ty
) override;
};
class BinaryOperationExpression : public Expression {
@ -80,6 +103,11 @@ namespace AST {
virtual ~BinaryOperationExpression() override = default;
virtual std::string formatted() override;
virtual codegen::StackValue codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual std::shared_ptr<types::Type> typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>> expected_ty
) override;
};
class FunctionCallExpression : public Expression {
@ -98,6 +126,11 @@ namespace AST {
virtual ~FunctionCallExpression() override = default;
virtual std::string formatted() override;
virtual codegen::StackValue codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual std::shared_ptr<types::Type> typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>> expected_ty
) override;
};
@ -111,17 +144,18 @@ namespace AST {
virtual ~ReturnStatement() override = default;
virtual std::string formatted() override;
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) override;
};
class InitializationStatement : public Statement {
private:
std::unique_ptr<types::Type> m_type;
std::shared_ptr<types::Type> m_type;
std::string m_name;
std::optional<std::unique_ptr<Expression>> m_expr;
public:
InitializationStatement(
token::Metadata meta,
std::unique_ptr<types::Type> ty,
std::shared_ptr<types::Type> ty,
std::string name,
std::optional<std::unique_ptr<Expression>> expr)
: Statement{ meta }
@ -132,6 +166,7 @@ namespace AST {
virtual ~InitializationStatement() override = default;
virtual std::string formatted() override;
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) override;
};
class ExpressionStatement : public Statement {
@ -144,6 +179,7 @@ namespace AST {
virtual ~ExpressionStatement() override = default;
virtual std::string formatted() override;
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) override;
};
class IfStatement : public Statement {
@ -164,32 +200,34 @@ namespace AST {
virtual ~IfStatement() override = default;
virtual std::string formatted() override;
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) override;
};
class TopLevelStatement : public Node {
public:
TopLevelStatement(token::Metadata meta) : Node{ meta } {}
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) = 0;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) = 0;
};
class Function : public TopLevelStatement {
private:
std::unique_ptr<types::Type> m_return_ty;
std::vector<std::pair<std::optional<std::string>, std::unique_ptr<types::Type>>> m_params;
std::shared_ptr<types::Type> m_return_ty;
std::vector<std::pair<std::optional<std::string>, std::shared_ptr<types::Type>>> m_params;
bool m_is_vararg;
std::string m_name;
std::optional<std::vector<std::unique_ptr<Statement>>> m_statements;
public:
Function(
token::Metadata meta,
std::unique_ptr<types::Type> return_ty,
std::vector<std::pair<std::optional<std::string>, std::unique_ptr<types::Type>>> params,
std::shared_ptr<types::Type> return_ty,
std::vector<std::pair<std::optional<std::string>, std::shared_ptr<types::Type>>> params,
bool is_vararg,
std::string name,
std::optional<std::vector<std::unique_ptr<Statement>>> statements)
: TopLevelStatement{ meta }
, m_return_ty{ std::move(return_ty) }
, m_params{ std::move(params) }
, m_return_ty{ return_ty }
, m_params{ params }
, m_is_vararg{ is_vararg }
, m_name{ name }
, m_statements{ std::move(statements) } {
@ -197,6 +235,7 @@ namespace AST {
virtual ~Function() override = default;
virtual std::string formatted() override;
virtual void codegen(codegen::Builder& builder, codegen::Scope& scope) override;
virtual void typecheck(typecheck::State& state, typecheck::Scope& scope) override;
};
}

63
src/binops.cpp Normal file
View File

@ -0,0 +1,63 @@
#include "binops.h"
namespace types {
std::vector<BinopDefinition> create_binops() {
std::vector<BinopDefinition> definitions{};
auto int_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Int } };
auto char_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Char } };
auto bool_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Bool } };
for (auto& ty : { int_ty, char_ty, bool_ty }) {
// Arithmetic binops
definitions.push_back(BinopDefinition{
ty, types::BinOp::Add, ty,
ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateAdd(lhs, rhs, "add");
} });
definitions.push_back(BinopDefinition{
ty, types::BinOp::Sub, ty,
ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateSub(lhs, rhs, "sub");
} });
// Comparisons
definitions.push_back(BinopDefinition{
ty, types::BinOp::LessThan, ty,
bool_ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateICmpSLE(lhs, rhs, "icmpsle");
} });
definitions.push_back(BinopDefinition{
ty, types::BinOp::GreaterThan, ty,
bool_ty, [](codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs) {
return builder.builder->CreateICmpSGT(lhs, rhs, "icmpsgt");
} });
}
return definitions;
}
std::optional<BinopDefinition> find_binop(
std::vector<BinopDefinition>& binops,
std::shared_ptr<types::Type> lhs,
BinOp op,
std::shared_ptr<types::Type> rhs) {
for (auto& binop : binops) {
if (binop.op != op) {
continue;
}
if (!types_equal(lhs, binop.lhs) || !types_equal(rhs, binop.rhs)) {
continue;
}
return binop;
}
return {};
}
}

39
src/binops.h Normal file
View File

@ -0,0 +1,39 @@
#ifndef BINOP_H
#define BINOP_H
#include <memory>
#include "types.h"
namespace types {
enum class BinOp {
Assignment,
Add,
Sub,
LessThan,
GreaterThan,
};
int operator_precedence(BinOp& op);
std::string format_operator(BinOp& op);
struct BinopDefinition {
std::shared_ptr<Type> lhs;
BinOp op;
std::shared_ptr<Type> rhs;
std::shared_ptr<Type> result;
llvm::Value* (*codegen)(codegen::Builder& builder, llvm::Value* lhs, llvm::Value* rhs);
};
std::vector<BinopDefinition> create_binops();
std::optional<BinopDefinition> find_binop(
std::vector<BinopDefinition>& binops,
std::shared_ptr<types::Type> lhs,
BinOp op,
std::shared_ptr<types::Type> rhs);
}
#endif

View File

@ -1,6 +1,7 @@
#include "codegen.h"
#include "ast.h"
#include "types.h"
#include "errors.h"
#include <llvm/IR/Module.h>
#include <llvm/IR/Verifier.h>
@ -10,7 +11,7 @@
namespace codegen {
Scope Scope::with_lvalue() {
return Scope{ this->values, true };
return Scope{ this->binops, this->values, true };
}
}
@ -53,7 +54,7 @@ namespace AST {
}
}
else {
throw codegen::Error("Value " + this->m_name + " not found", this->m_meta);
throw CompileError("Value " + this->m_name + " not found", this->m_meta);
}
}
@ -66,32 +67,23 @@ namespace AST {
case types::BinOp::Assignment:
builder.builder->CreateStore(rhs.value, lhs.value, false);
return rhs;
case types::BinOp::Add:
return codegen::StackValue{
lhs.ty->add(builder, lhs.value, rhs.value),
lhs.ty
};
case types::BinOp::Sub:
return codegen::StackValue{
lhs.ty->sub(builder, lhs.value, rhs.value),
lhs.ty
};
case types::BinOp::LessThan:
return codegen::StackValue{
lhs.ty->lt(builder, lhs.value, rhs.value),
std::make_shared<types::FundamentalType>(types::FundamentalTypeKind::Bool),
};
case types::BinOp::GreaterThan:
return codegen::StackValue{
lhs.ty->gt(builder, lhs.value, rhs.value),
std::make_shared<types::FundamentalType>(types::FundamentalTypeKind::Bool),
};
default:
throw codegen::Error("invalid binop", this->m_meta);
auto binop = types::find_binop(
scope.binops,
lhs.ty,
this->m_binop,
rhs.ty);
if (binop) {
return codegen::StackValue{
binop->codegen(builder, lhs.value, rhs.value),
binop->result
};
}
throw CompileError("invalid binop", this->m_meta);
}
}
catch (std::runtime_error& error) {
throw codegen::Error(error.what(), this->m_meta);
throw CompileError(error.what(), this->m_meta);
}
}
@ -140,7 +132,7 @@ namespace AST {
builder.builder->CreateStore(value.value, ptr, false);
}
scope.values[this->m_name] = codegen::StackValue{ ptr, std::move(this->m_type) };
scope.values[this->m_name] = codegen::StackValue{ ptr, this->m_type };
}
void IfStatement::codegen(codegen::Builder& builder, codegen::Scope& scope) {
@ -180,11 +172,11 @@ namespace AST {
void Function::codegen(codegen::Builder& builder, codegen::Scope& scope) {
std::shared_ptr<types::Type> ret_ty_ptr{ std::move(this->m_return_ty) };
std::shared_ptr<types::Type> ret_ty_ptr{ this->m_return_ty };
std::vector<std::shared_ptr<types::Type>> param_ty_ptrs{};
for (auto& param : this->m_params) {
param_ty_ptrs.push_back(std::move(param.second));
param_ty_ptrs.push_back(param.second);
}
auto fn_ty_ptr = std::shared_ptr<types::Type>{ new types::FunctionType{ ret_ty_ptr, param_ty_ptrs, this->m_is_vararg } };

View File

@ -8,22 +8,18 @@
#include "builder.h"
#include "types.h"
#include "binops.h"
#include "tokens.h"
namespace codegen {
class Error : public std::runtime_error {
public:
token::Metadata m_meta;
Error(std::string text, token::Metadata meta)
: std::runtime_error{ text }, m_meta{ meta } {}
};
struct StackValue {
llvm::Value* value = nullptr;
std::shared_ptr<types::Type> ty = nullptr;
};
struct Scope {
std::vector<types::BinopDefinition>& binops;
std::map<std::string, StackValue> values;
bool is_lvalue;

15
src/errors.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef ERRORS_H
#define ERRORS_H
#include <memory>
#include "tokens.h"
class CompileError : public std::runtime_error {
public:
token::Metadata m_meta;
CompileError(std::string text, token::Metadata meta)
: std::runtime_error{ text }, m_meta{ meta } {}
};
#endif

View File

@ -19,6 +19,7 @@
#include "tokens.h"
#include "parsing.h"
#include "errors.h"
std::string read_file(std::string_view filepath) {
std::ifstream input{ std::string{filepath} };
@ -94,16 +95,41 @@ std::optional<CompileOutput> compile(std::string_view in_filename) {
{}
};
codegen::Scope scope{};
// Perform static analysis
typecheck::State typecheck_state{};
typecheck_state.binops = types::create_binops();
typecheck::Scope typecheck_scope{};
for (auto& tls : statements) {
std::cout << tls->formatted() << std::endl;
tls->typecheck(typecheck_state, typecheck_scope);
}
if (typecheck_state.errors.size() > 0) {
std::cerr << "Errors while typechecking:" << std::endl;
for (auto& error : typecheck_state.errors) {
std::cerr << " " << error.what() << std::endl;
std::cerr << " at " << error.m_meta.start.line + 1 << ":" << error.m_meta.start.col + 1;
std::cerr << " to " << error.m_meta.end.line + 1 << ":" << error.m_meta.end.col + 1 << std::endl;
}
return {};
}
codegen::Scope cg_scope{
.binops = typecheck_state.binops,
.values = {},
.is_lvalue = false,
};
// Compile parsed output
try {
for (auto& tls : statements) {
std::cout << tls->formatted() << std::endl;
tls->codegen(builder, scope);
tls->codegen(builder, cg_scope);
}
}
catch (codegen::Error& error) {
catch (CompileError& error) {
std::cerr << "FATAL: " << error.what() << std::endl;
std::cerr << " at " << error.m_meta.start.line + 1 << ":" << error.m_meta.start.col + 1;
std::cerr << " to " << error.m_meta.end.line + 1 << ":" << error.m_meta.end.col + 1 << std::endl;

View File

@ -7,7 +7,7 @@ namespace parsing {
namespace {
Result<std::unique_ptr<AST::Expression>, std::string> parse_expression(token::TokenStream& stream);
Result<std::unique_ptr<types::Type>, std::string> parse_type(token::TokenStream& stream) {
Result<std::shared_ptr<types::Type>, std::string> parse_type(token::TokenStream& stream) {
token::TokenStream inner{ stream };
try {
auto token = inner.expect(token::Type::Ident);
@ -15,19 +15,19 @@ namespace parsing {
// TODO eventually make this be potentially more than one word
std::string type_name = token.content;
std::unique_ptr<types::Type> returned{};
std::shared_ptr<types::Type> returned{};
if (type_name == "int") {
auto ty = new types::FundamentalType{ types::FundamentalTypeKind::Int };
returned = std::unique_ptr<types::Type>{ ty };
returned = std::shared_ptr<types::Type>{ ty };
}
else if (type_name == "char") {
auto ty = new types::FundamentalType{ types::FundamentalTypeKind::Char };
returned = std::unique_ptr<types::Type>{ ty };
returned = std::shared_ptr<types::Type>{ ty };
}
else if (type_name == "void") {
auto ty = new types::FundamentalType{ types::FundamentalTypeKind::Void };
returned = std::unique_ptr<types::Type>{ ty };
returned = std::shared_ptr<types::Type>{ ty };
}
else {
throw std::runtime_error("Expected type name, got " + type_name);
@ -36,7 +36,7 @@ namespace parsing {
while (inner.peek().type == token::Type::Symbol && inner.peek().content == "*") {
inner.next();
auto ty = new types::PointerType{ std::move(returned) };
returned = std::unique_ptr<types::Type>{ ty };
returned = std::shared_ptr<types::Type>{ ty };
}
@ -274,7 +274,7 @@ namespace parsing {
auto name_token = inner.expect(token::Type::Ident);
inner.expect(token::Type::Symbol, "(");
std::vector<std::pair<std::optional<std::string>, std::unique_ptr<types::Type>>> params;
std::vector<std::pair<std::optional<std::string>, std::shared_ptr<types::Type>>> params;
bool is_vararg = false;
while (inner.peek().content != ")") {
if (params.size() > 0) {

214
src/typechecker.cpp Normal file
View File

@ -0,0 +1,214 @@
#include "typechecker.h"
#include "ast.h"
#include "errors.h"
#include "result.h"
namespace {
enum class TypecheckRes {
Ok,
Castable,
};
Result<TypecheckRes, std::string> check_type(std::shared_ptr<types::Type> checked, std::shared_ptr<types::Type> target) {
if (types::types_equal(checked, target)) {
return TypecheckRes::Ok;
}
return std::string{ "Types " + checked->formatted() + " and " + target->formatted() + " incompatible" };
}
std::unique_ptr<AST::Expression> handle_res(
std::unique_ptr<AST::Expression> expr,
Result<TypecheckRes, std::string> res,
typecheck::State& state) {
if (res.ok()) {
auto result = res.unwrap();
if (result == TypecheckRes::Ok) {
return expr;
}
else {
state.errors.push_back(CompileError("Casting not yet implemented", expr->m_meta));
return expr;
}
}
else {
state.errors.push_back(CompileError(res.unwrap_err(), expr->m_meta));
return expr;
}
}
}
namespace AST {
std::shared_ptr<types::Type> IntLiteralExpression::typecheck(
typecheck::State&,
typecheck::Scope&,
std::optional<std::shared_ptr<types::Type>>
) {
return std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Int }
};
}
std::shared_ptr<types::Type> StringLiteralExpression::typecheck(
typecheck::State&,
typecheck::Scope&,
std::optional<std::shared_ptr<types::Type>>
) {
auto char_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Char }
};
auto ptr_ty = new types::PointerType{ char_ty };
return std::shared_ptr<types::Type>{ptr_ty};
}
std::shared_ptr<types::Type> ValueReferenceExpression::typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>>
) {
if (scope.symbols.find(this->m_name) != scope.symbols.end()) {
return scope.symbols[this->m_name];
}
state.errors.push_back(CompileError("Value " + this->m_name + " not defined", this->m_meta));
return std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Void }
};
}
std::shared_ptr<types::Type> BinaryOperationExpression::typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>>
) {
auto lhs_ty = this->m_lhs->typecheck(state, scope, {});
auto rhs_ty = this->m_rhs->typecheck(state, scope, {});
if (this->m_binop == types::BinOp::Assignment) {
return lhs_ty;
}
auto binop = types::find_binop(
state.binops,
lhs_ty,
this->m_binop,
rhs_ty
);
if (binop) {
return binop->result;
}
// TODO check for binops that may be implicitly castable
state.errors.push_back(CompileError(
"No suitable binop between "
+ lhs_ty->formatted() + " "
+ types::format_operator(this->m_binop) + " "
+ rhs_ty->formatted(),
this->m_meta));
return std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Void } };
}
std::shared_ptr<types::Type> FunctionCallExpression::typecheck(
typecheck::State& state,
typecheck::Scope& scope,
std::optional<std::shared_ptr<types::Type>>
) {
auto expr_ty = this->m_fn_expr->typecheck(state, scope, {});
if (expr_ty->m_kind != types::TypeKind::Function) {
state.errors.push_back(CompileError("Tried calling a non-function", this->m_meta));
return std::shared_ptr<types::Type> {
new types::FundamentalType{ types::FundamentalTypeKind::Void }
};
}
auto fn_ty = dynamic_cast<types::FunctionType*>(expr_ty.get());
if (this->m_args.size() < fn_ty->m_param_tys.size()) {
state.errors.push_back(CompileError("too few arguments", this->m_meta));
}
else if (this->m_args.size() > fn_ty->m_param_tys.size() && !fn_ty->m_vararg) {
state.errors.push_back(CompileError("too many arguments", this->m_meta));
}
else {
for (int i = 0; i < static_cast<int>(this->m_args.size()); i++) {
if (i < static_cast<int>(fn_ty->m_param_tys.size())) {
auto expected_param_ty = fn_ty->m_param_tys[i];
auto param_ty = this->m_args[i]->typecheck(state, scope, expected_param_ty);
auto check_res = check_type(param_ty, expected_param_ty);
this->m_args[i] = handle_res(std::move(this->m_args[i]), check_res, state);
}
else {
this->m_args[i]->typecheck(state, scope, {});
}
}
}
return fn_ty->m_ret_ty;
}
void ReturnStatement::typecheck(typecheck::State& state, typecheck::Scope& scope) {
auto res_ty = this->m_expr->typecheck(state, scope, scope.return_ty);
if (scope.return_ty) {
auto check_res = check_type(res_ty, *scope.return_ty);
this->m_expr = handle_res(std::move(this->m_expr), check_res, state);
}
}
void InitializationStatement::typecheck(typecheck::State& state, typecheck::Scope& scope) {
if (this->m_expr) {
(*this->m_expr)->typecheck(state, scope, this->m_type);
}
scope.symbols[this->m_name] = this->m_type;
}
void ExpressionStatement::typecheck(typecheck::State& state, typecheck::Scope& scope) {
this->m_expr->typecheck(state, scope, {});
}
void IfStatement::typecheck(typecheck::State& state, typecheck::Scope& scope) {
auto bool_ty = std::shared_ptr<types::Type>{
new types::FundamentalType{ types::FundamentalTypeKind::Bool } };
auto expr_ty = this->m_condition->typecheck(state, scope, bool_ty);
auto check_res = check_type(expr_ty, bool_ty);
this->m_condition = handle_res(std::move(this->m_condition), check_res, state);
this->m_then->typecheck(state, scope);
if (this->m_else) {
(*this->m_else)->typecheck(state, scope);
}
}
void Function::typecheck(typecheck::State& state, typecheck::Scope& scope) {
auto return_ty = this->m_return_ty;
std::vector<std::shared_ptr<types::Type>> param_tys{};
for (auto& param : this->m_params) {
param_tys.push_back(param.second);
}
auto function_ty = new types::FunctionType{ return_ty, param_tys, this->m_is_vararg };
scope.symbols[this->m_name] = std::shared_ptr<types::Type>{ function_ty };
typecheck::Scope inner{ scope };
inner.return_ty = return_ty;
for (auto& param : this->m_params) {
if (param.first) {
inner.symbols[*param.first] = param.second;
}
}
if (this->m_statements) {
for (auto& statement : *this->m_statements) {
statement->typecheck(state, inner);
}
}
}
}

22
src/typechecker.h Normal file
View File

@ -0,0 +1,22 @@
#ifndef TYPECHECK_H
#define TYPECHECK_H
#include <map>
#include "types.h"
#include "binops.h"
#include "errors.h"
namespace typecheck {
struct Scope {
std::map<std::string, std::shared_ptr<types::Type>> symbols;
std::optional<std::shared_ptr<types::Type>> return_ty;
};
struct State {
std::vector<types::BinopDefinition> binops;
std::vector<CompileError> errors;
};
}
#endif

View File

@ -2,6 +2,7 @@
#include <sstream>
#include "types.h"
#include "binops.h"
namespace types {
int operator_precedence(BinOp& op) {
@ -165,4 +166,44 @@ namespace types {
this->m_inner
);
}
bool types_equal(std::shared_ptr<types::Type> type1, std::shared_ptr<types::Type> type2) {
if (type1->m_kind != type2->m_kind)
return false;
if (type1->m_kind == TypeKind::Fundamental) {
auto ty1 = dynamic_cast<FundamentalType*>(type1.get());
auto ty2 = dynamic_cast<FundamentalType*>(type2.get());
return ty1->m_ty == ty2->m_ty;
}
else if (type1->m_kind == TypeKind::Function) {
auto ty1 = dynamic_cast<FunctionType*>(type1.get());
auto ty2 = dynamic_cast<FunctionType*>(type2.get());
if (!types_equal(ty1->m_ret_ty, ty2->m_ret_ty))
return false;
if (ty1->m_vararg != ty2->m_vararg)
return false;
if (ty1->m_param_tys.size() != ty2->m_param_tys.size())
return false;
for (int i = 0; i < static_cast<int>(ty1->m_param_tys.size()); i++) {
auto param1 = ty1->m_param_tys[i];
auto param2 = ty2->m_param_tys[i];
if (!types_equal(param1, param2))
return false;
}
return true;
}
else if (type1->m_kind == TypeKind::Pointer) {
auto ty1 = dynamic_cast<PointerType*>(type1.get());
auto ty2 = dynamic_cast<PointerType*>(type2.get());
return types_equal(ty1->m_inner, ty2->m_inner);
}
else {
return false;
}
}
}

View File

@ -7,17 +7,12 @@
#include <memory>
namespace types {
enum class BinOp {
Assignment,
Add,
Sub,
LessThan,
GreaterThan,
enum class TypeKind {
Fundamental,
Function,
Pointer,
};
int operator_precedence(BinOp& op);
std::string format_operator(BinOp& op);
enum FundamentalTypeKind {
Int,
Bool,
@ -27,6 +22,8 @@ namespace types {
class Type {
public:
TypeKind m_kind;
Type(TypeKind kind) : m_kind{ kind } {}
virtual ~Type() = default;
virtual std::string formatted() = 0;
virtual llvm::Type* codegen(codegen::Builder& builder) = 0;
@ -39,10 +36,9 @@ namespace types {
};
class FundamentalType : public Type {
private:
FundamentalTypeKind m_ty;
public:
FundamentalType(FundamentalTypeKind kind) : m_ty{ kind } {}
FundamentalTypeKind m_ty;
FundamentalType(FundamentalTypeKind kind) : Type(TypeKind::Fundamental), m_ty{ kind } {}
virtual ~FundamentalType() override = default;
virtual std::string formatted() override;
virtual llvm::Type* codegen(codegen::Builder& builder) override;
@ -55,13 +51,15 @@ namespace types {
class FunctionType : public Type {
private:
public:
std::shared_ptr<Type> m_ret_ty;
std::vector<std::shared_ptr<Type>> m_param_tys;
bool m_vararg;
public:
FunctionType(std::shared_ptr<Type> ret_ty, std::vector<std::shared_ptr<Type>> param_tys, bool vararg)
: m_ret_ty{ std::move(ret_ty) }, m_param_tys{ std::move(param_tys) }, m_vararg{ vararg } {
: Type(TypeKind::Function)
, m_ret_ty{ std::move(ret_ty) }
, m_param_tys{ std::move(param_tys) }
, m_vararg{ vararg } {
}
virtual ~FunctionType() override = default;
virtual std::string formatted() override;
@ -73,17 +71,18 @@ namespace types {
class PointerType : public Type {
private:
std::shared_ptr<Type> m_inner;
public:
std::shared_ptr<Type> m_inner;
PointerType(std::shared_ptr<Type> inner)
: m_inner{ std::move(inner) } {
: Type(TypeKind::Pointer), m_inner{ std::move(inner) } {
}
virtual ~PointerType() override = default;
virtual std::string formatted() override;
virtual llvm::Type* codegen(codegen::Builder& builder) override;
virtual std::pair<llvm::Value*, std::shared_ptr<Type>> load(codegen::Builder& builder, llvm::Value* ptr) override;
};
bool types_equal(std::shared_ptr<types::Type> type1, std::shared_ptr<types::Type> type2);
}
#endif