aboutsummaryrefslogtreecommitdiff
path: root/src/ast.c
blob: d0a50302213f1166626ac8d9c25ed8fb36f3226f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#include "../include/ast.h"
#include "../include/parser.h"
#include "../include/std/log.h"
#include "../include/std/hash.h"
#include <assert.h>

#define throw(result) do { longjmp(context->env, (result)); } while(0)
#define throw_if_error(result) \
do { \
    int return_if_result; \
    return_if_result = (result); \
    if((return_if_result) != 0) \
        throw(return_if_result); \
} while(0)

static void ast_resolve(Ast *self, AstCompilerContext *context);

Ast ast_none() {
    Ast ast;
    ast.value.func_decl = NULL;
    ast.type = AST_NONE;
    ast.resolve_status = AST_NOT_RESOLVED;
    ast.resolved_type = NULL;
    return ast;
}

void ast_init(Ast *self, void *value, AstType type) {
    self->value.data = value;
    self->type = type;
    self->resolve_status = AST_NOT_RESOLVED;
    self->resolved_type = NULL;
}

BufferView ast_get_name(Ast *self) {
    BufferView name;
    switch(self->type) {
        case AST_NONE:
        case AST_FUNCTION_DECL:
        case AST_STRUCT_DECL:
        case AST_IMPORT:
        case AST_STRING:
        case AST_NUMBER:
        case AST_BINOP:
            name = create_buffer_view_null();
            break;
        case AST_LHS:
            name = self->value.lhs_expr->var_name;
            break;
        case AST_FUNCTION_CALL:
            name = self->value.func_call->func.name;
            break;
        case AST_VARIABLE:
            name = self->value.variable->name;
            break;
        case AST_STRUCT_FIELD:
            name = self->value.struct_field->name;
            break;
    }
    return name;
}

static BufferView ast_get_code_reference(Ast *self) {
    return ast_get_name(self);
}

int funcdecl_init(FunctionDecl *self, Scope *parent, ScopedAllocator *allocator) {
    self->ssa_func_index = 0;
    return scope_init(&self->body, parent, allocator);
}

int funccall_init(FunctionCall *self, BufferView name, ScopedAllocator *allocator) {
    variable_init(&self->func, name);
    return buffer_init(&self->args, allocator);
}

int structdecl_init(StructDecl *self, Scope *parent, ScopedAllocator *allocator) {
    return scope_init(&self->body, parent, allocator);
}

void structfield_init(StructField *self, BufferView name, BufferView type_name) {
    self->name = name;
    variable_init(&self->type, type_name);
}

int lhsexpr_init(LhsExpr *self, bool is_pub, bool is_const, BufferView var_name, ScopedAllocator *allocator) {
    self->is_pub = is_pub;
    self->is_const = is_const;
    variable_init(&self->type, create_buffer_view_null());
    self->var_name = var_name;
    self->rhs_expr = ast_none();
    if(is_pub && allocator)
        return_if_error(scoped_allocator_create_mutex(allocator, &self->mutex));
    else
        self->mutex = NULL;
    return 0;
}

void import_init(Import *self, BufferView path) {
    self->path = path;
    self->file_scope = NULL;
}

int string_init(String *self, BufferView str) {
    /* TODO: Convert special characters. For example \n should be converted to binary newline etc */
    self->str = str;
    return 0;
}

void number_init(Number *self, i64 value, bool is_integer) {
    self->value.integer = value;
    self->is_integer = is_integer;
}

void variable_init(Variable *self, BufferView name) {
    self->name = name;
}

void binop_init(Binop *self) {
    self->lhs = ast_none();
    self->rhs = ast_none();
    self->type = BINOP_ADD;
    self->grouped = bool_false;
}

int scope_init(Scope *self, Scope *parent, ScopedAllocator *allocator) {
    return_if_error(buffer_init(&self->ast_objects, allocator));
    return_if_error(hash_map_init(&self->named_objects, allocator, sizeof(Ast), hash_compare_string, amal_hash_string));
    self->parent = parent;
    return 0;
}

int file_scope_reference_init(FileScopeReference *self, BufferView canonical_path, ScopedAllocator *allocator) {
    char null_terminator;
    null_terminator = '\0';
    self->scope = NULL;

    return_if_error(buffer_init(&self->canonical_path, allocator));
    return_if_error(buffer_append(&self->canonical_path, canonical_path.data, canonical_path.size));
    return_if_error(buffer_append(&self->canonical_path, &null_terminator, 1));
    /* To exclude null-terminator character from size but not from data */
    self->canonical_path.size -= 1;
    return 0;
}

int scope_add_child(Scope *self, Ast *child) {
    Ast existing_child;
    bool child_already_exists;

    /* TODO: Implement for parameter */
    if(child->type == AST_LHS) {
        BufferView var_name;
        var_name = child->value.lhs_expr->var_name;
        child_already_exists = hash_map_get(&self->named_objects, var_name, &existing_child);
        if(child_already_exists)
            return AST_ERR_DEF_DUP;

        cleanup_if_error(hash_map_insert(&self->named_objects, var_name, child));
    }
    cleanup_if_error(buffer_append(&self->ast_objects, child, sizeof(Ast)));
    return 0;

    cleanup:
    return AST_ERR;
}

void scope_resolve(Scope *self, AstCompilerContext *context) {
    Ast *ast;
    Ast *ast_end;

    ast = buffer_start(&self->ast_objects);
    ast_end = buffer_end(&self->ast_objects);
    context->scope = self;
    for(; ast != ast_end; ++ast) {
        ast_resolve(ast, context);
    }
    context->scope = self->parent;
}

static LhsExpr* scope_get_resolved_variable(Scope *self, AstCompilerContext *context, BufferView name) {
    Ast result;
    bool exists;
    Scope *prev_scope;

    assert(self);
    exists = hash_map_get(&self->named_objects, name, &result);
    if(!exists) {
        if(self->parent)
            return scope_get_resolved_variable(self->parent, context, name);

        tokenizer_print_error(&context->parser->tokenizer,
                              tokenizer_get_code_reference_index(&context->parser->tokenizer, name.data),
                              "Undefined reference to variable \"%.*s\"", name.size, name.data);
        throw(AST_ERR);
    }

    /*
    Need to change scope here because we are changing the visible scope
    and the ast object may be in another scope than the current 
    resolving ast.
    */
    prev_scope = context->scope;
    context->scope = self;
    ast_resolve(&result, context);
    context->scope = prev_scope;

    assert(result.type == AST_LHS);
    return result.value.lhs_expr;
}

/* @resolved_type is the same field as the ast resolved_type for the variable @self */
static void variable_resolve(Variable *self, AstCompilerContext *context, LhsExpr **resolved_type) {
    /* TODO: Verify this is correct in all cases */
    *resolved_type = scope_get_resolved_variable(context->scope, context, self->name);
}

static void lhsexpr_resolve(Ast *self, AstCompilerContext *context) {
    LhsExpr *lhs_expr;
    lhs_expr = self->value.lhs_expr;

    if(lhs_expr->type.name.data)
        variable_resolve(&lhs_expr->type, context, &self->resolved_type);
    self->resolve_status = AST_RESOLVED;
    ast_resolve(&lhs_expr->rhs_expr, context);

    if(self->resolved_type &&
       lhs_expr->rhs_expr.type != AST_NONE &&
       self->resolved_type != lhs_expr->rhs_expr.resolved_type) {
        tokenizer_print_error(&context->parser->tokenizer,
                              tokenizer_get_code_reference_index(&context->parser->tokenizer, ast_get_code_reference(self).data),
                              "Variable type and variable assignment type (right-hand side) do not match");
        throw(AST_ERR);
    }
    self->resolved_type = lhs_expr->rhs_expr.resolved_type;
}

/* LhsExpr has to be resolved before this is called */
static Scope* lhsexpr_get_scope(LhsExpr *self) {
    switch(self->rhs_expr.type) {
        case AST_FUNCTION_DECL:
            return &self->rhs_expr.value.func_decl->body;
        case AST_STRUCT_DECL:
            return &self->rhs_expr.value.struct_decl->body;
        case AST_IMPORT:
            return self->rhs_expr.value.import->file_scope->scope;
        default:
            break;
    }
    assert(bool_false && "Expected lhsexpr_get_scope to only be called for function decl and struct decl");
    return NULL;
}

static void import_resolve(Ast *self, AstCompilerContext *context) {
    Import *import;
    import = self->value.import;
    (void)import;
    (void)self;
    (void)context;
    /* TODO: Convert all scopes to structs and set import->resolved_type to import->file_scope->scope; */
}

static void funcdecl_resolve(Ast *self, AstCompilerContext *context) {
    /* TODO: Implement */
    FunctionDecl *func_decl;
    assert(self->type == AST_FUNCTION_DECL);
    func_decl = self->value.func_decl;
    self->resolve_status = AST_RESOLVED;
    scope_resolve(&func_decl->body, context);
}

static void funccall_resolve(Ast *self, AstCompilerContext *context) {
    FunctionCall *func_call;
    Ast *ast;
    Ast *ast_end;

    func_call = self->value.func_call;
    variable_resolve(&func_call->func, context, &self->resolved_type);

    ast = buffer_start(&func_call->args);
    ast_end = buffer_end(&func_call->args);
    for(; ast != ast_end; ++ast) {
        ast_resolve(ast, context);
    }
}

static void structdecl_resolve(Ast *self, AstCompilerContext *context) {
    /* TODO: What to do with resolved_type? */
    StructDecl *struct_decl;
    struct_decl = self->value.struct_decl;
    scope_resolve(&struct_decl->body, context);
}

static void structfield_resolve(Ast *self, AstCompilerContext *context) {
    /* TODO: Implement */
    StructField *struct_field;
    struct_field = self->value.struct_field;
    variable_resolve(&struct_field->type, context, &self->resolved_type);
}

static void binop_resolve(Binop *self, AstCompilerContext *context) {
    /* TODO: Implement */
    ast_resolve(&self->lhs, context);
    if(self->rhs.type == AST_VARIABLE) {
        Scope *prev_scope;
        assert(self->lhs.resolved_type);
        prev_scope = context->scope;
        context->scope = lhsexpr_get_scope(self->lhs.resolved_type);
        assert(context->scope);
        ast_resolve(&self->rhs, context);
        context->scope = prev_scope;
    } else {
        ast_resolve(&self->rhs, context);
    }
}

void ast_resolve(Ast *self, AstCompilerContext *context) {
    /* 
    TODO: Move these to the types that need checks for recursive dependency (function declaration, struct declaration)
    For function declaration, it should be marked as resolved when the signature has been resolved
    instead of the whole function declaration including the body
    because the body can have function call that calls functions that are resolving
    or even recursive function call, which should be allowed.
    */
    if(self->resolve_status == AST_RESOLVED) {
        return;
    } else if(self->resolve_status == AST_RESOLVING) {
        tokenizer_print_error(&context->parser->tokenizer,
                              tokenizer_get_code_reference_index(&context->parser->tokenizer, ast_get_code_reference(self).data),
                              "Found recursive dependency");
        throw(AST_ERR);
    }

    self->resolve_status = AST_RESOLVING;
    switch(self->type) {
        case AST_NONE:
        case AST_NUMBER:
            /* Nothing to resolve for numbers */
            break;
        case AST_FUNCTION_DECL:
            funcdecl_resolve(self, context);
            break;
        case AST_FUNCTION_CALL:
            funccall_resolve(self, context);
            break;
        case AST_STRUCT_DECL:
            structdecl_resolve(self, context);
            break;
        case AST_STRUCT_FIELD:
            structfield_resolve(self, context);
            break;
        case AST_LHS:
            lhsexpr_resolve(self, context);
            break;
        case AST_IMPORT:
            /* TODO: When @import(...).data syntax is added, implement the resolve for it */
            import_resolve(self, context);
            break;
        case AST_STRING:
            /* TODO: Convert special combinations. For example \n to newline */
            break;
        case AST_VARIABLE:
            variable_resolve(self->value.variable, context, &self->resolved_type);
            break;
        case AST_BINOP:
            binop_resolve(self->value.binop, context);
            break;
    }
    /* TODO: See comment at the top of this function */
    self->resolve_status = AST_RESOLVED;
}