aboutsummaryrefslogtreecommitdiff
path: root/src/parser.c
blob: 9da914709b5b704b831a240d8131dafe89c2ce1d (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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
#include "../include/parser.h"
#include "../include/ast.h"
#include "../include/compiler.h"
#include "../include/std/misc.h"
#include "../include/std/file.h"
#include "../include/std/mem.h"
#include "../include/std/log.h"
#include "../include/std/alloc.h"
#include "../include/std/hash.h"

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define throw(result) do { throw_debug_msg; longjmp(self->parse_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)

#define VAR_MAX_LEN UINT8_MAX
#define FUNC_MAX_PARAMS 128
#define FUNC_MAX_RETURN_TYPES 128
#define FUNC_MAX_ARGS FUNC_MAX_PARAMS

static CHECK_RESULT Ast* parser_parse_rhs(Parser *self);
static CHECK_RESULT Ast* parser_parse_body(Parser *self);
static CHECK_RESULT StructField* parser_parse_struct_body(Parser *self);
static CHECK_RESULT Ast* parser_parse_rhs_binop(Parser *self);
static void parser_parse_var_type(Parser *self, VariableType *result);
static void parser_parse_var_type_def(Parser *self, VariableType *result);
static void parser_queue_file(Parser *self, BufferView path, ParserFileScopeReference **parser_file_scope);

int parser_init(Parser *self, amal_compiler *compiler, ArenaAllocator *allocator) {
    self->allocator = allocator;
    self->compiler = compiler;
    self->ssa = NULL;
    self->started = bool_false;
    self->error.index = 0;
    self->error.str = NULL;
    self->error_context = ERROR_CONTEXT_NONE;
    self->index = 0;
    return_if_error(structdecl_init(&self->struct_decl, &compiler->root_scope, allocator));
    lhsexpr_init(&self->file_decl, DECL_FLAG_EXTERN | DECL_FLAG_PUB | DECL_FLAG_CONST, create_buffer_view_null());
    return_if_error(ast_create(self->allocator, &self->struct_decl, AST_STRUCT_DECL, &self->file_decl.rhs_expr));
    return_if_error(buffer_init(&self->imports, allocator));
    return_if_error(hash_map_init(&self->imports_by_name, allocator, sizeof(usize), hash_map_compare_string, amal_hash_string));
    self->current_scope = &self->struct_decl.body;
    self->has_func_parent = bool_false;
    self->bytecode = NULL;
    return PARSER_OK;
}

static bool parser_is_current_scope_file_scope(Parser *self) {
    return self->current_scope == &self->struct_decl.body;
}

/*
BODY_LOOP = BODY* @end_token
*/
static void parser_parse_body_loop(Parser *self, Scope *scope, Token end_token) {
    int result;
    for(;;) {
        Ast *body_obj;
        bool is_end_token;
        throw_if_error(tokenizer_consume_if(&self->tokenizer, end_token, &is_end_token));
        if(is_end_token)
            break;
        
        body_obj = parser_parse_body(self);
        result = scope_add_child(scope, body_obj);
        if(result == 0) {
            continue;
        } else if(result == AST_ERR_DEF_DUP) {
            /* TODO: Convert ast type to string for error message */
            BufferView obj_name;
            obj_name = ast_get_name(body_obj);
            self->error = tokenizer_create_error(&self->tokenizer, 
                                                tokenizer_get_code_reference_index(&self->tokenizer, obj_name.data),
                                                "Variable with the name %.*s was declared twice in the same scope", obj_name.size, obj_name.data);
            self->error_context = ERROR_CONTEXT_NONE;
            throw(result);
        } else {
            throw(result);
        }
    }
}

/*
STRUCT_BODY_LOOP = '{' STRUCT_BODY* '}'
*/
static void parser_parse_struct_body_loop(Parser *self, StructDecl *struct_decl) {
    int result;
    throw_if_error(tokenizer_accept(&self->tokenizer, TOK_OPEN_BRACE));
    for(;;) {
        StructField *struct_field;
        bool is_end_token;
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_CLOSING_BRACE, &is_end_token));
        if(is_end_token)
            break;
        
        struct_field = parser_parse_struct_body(self);
        result = structdecl_add_field(struct_decl, struct_field, self->allocator);
        if(result == 0) {
            continue;
        } else if(result == AST_ERR_DEF_DUP) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                tokenizer_get_code_reference_index(&self->tokenizer, struct_field->name.data),
                                                "Variable with the name %.*s was declared twice in the struct", struct_field->name.size, struct_field->name.data);
            self->error_context = ERROR_CONTEXT_NONE;
            throw(result);
        } else {
            throw(result);
        }
    }
}

/*
FUNC_PARAM = TOK_IDENTIFIER VAR_TYPE_DEF
*/
static CHECK_RESULT bool parser_parse_function_parameter(Parser *self, FunctionParameter *result) {
    bool match;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_IDENTIFIER, &match));
    if(!match)
        return bool_false;

    result->name = self->tokenizer.value.identifier;
    parser_parse_var_type_def(self, &result->type);
    if(result->type.type == VARIABLE_TYPE_NONE) {
        self->error = tokenizer_create_error(&self->tokenizer,
                                             tokenizer_get_error_index(&self->tokenizer),
                                             "Expected ':' after parameter name");
        throw(PARSER_UNEXPECTED_TOKEN);
    }

    return bool_true;
}

/*
FUNC_PARAMS = FUNC_PARAM (',' FUNC_PARAM)*
*/
static void parser_parse_function_parameters(Parser *self, FunctionSignature *func_sig) {
    for(;;) {
        FunctionParameter func_param;
        bool match;
        int result;

        function_parameter_init(&func_param);
        if(!parser_parse_function_parameter(self, &func_param)) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                 tokenizer_get_error_index(&self->tokenizer),
                                                 "Expected closure parameter");
            throw(PARSER_UNEXPECTED_TOKEN);
        }

        result = function_signature_add_parameter(func_sig, &func_param);
        if(result == AST_ERR_DEF_DUP) {
            self->error = tokenizer_create_error(&self->tokenizer, 
                                                 tokenizer_get_code_reference_index(&self->tokenizer, func_param.name.data),
                                                 "Parameter with name %.*s was defined twice for the function", func_param.name.size, func_param.name.data);
            self->error_context = ERROR_CONTEXT_NONE;
            throw(result);
        } else if(result != 0) {
            throw(result);
        }
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_COMMA, &match));
        if(!match)
            return;
    }
}

/*
FUNC_RETURN_TYPES = VAR_TYPE (',' VAR_TYPE)*
*/
static void parser_parse_function_return_types(Parser *self, FunctionSignature *func_sig) {
    int return_type_index;
    return_type_index = 0;
    for(;;) {
        VariableType var_type;
        bool match;

        parser_parse_var_type(self, &var_type);
        if(var_type.type == VARIABLE_TYPE_NONE) {
            /* If function has no return types */
            if(return_type_index == 0)
                break;
            self->error = tokenizer_create_error(&self->tokenizer,
                                                 tokenizer_get_error_index(&self->tokenizer),
                                                 "Expected type or closure signature");
            throw(PARSER_UNEXPECTED_TOKEN);
        }
        throw_if_error(function_signature_add_return_type(func_sig, &var_type));
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_COMMA, &match));
        if(!match)
            break;
        ++return_type_index;
    }

    if (buffer_get_size(&func_sig->parameters, FunctionParameter) > FUNC_MAX_PARAMS) {
        self->error = tokenizer_create_error(&self->tokenizer,
                                             tokenizer_get_error_index(&self->tokenizer),
                                             "A closure can't have more than %d parameters", FUNC_MAX_PARAMS);
        throw(PARSER_ERR);
    }

    if (buffer_get_size(&func_sig->return_types, FunctionReturnType) > FUNC_MAX_RETURN_TYPES) {
        self->error = tokenizer_create_error(&self->tokenizer,
                                             tokenizer_get_error_index(&self->tokenizer),
                                             "A closure can't have more than %d return values", FUNC_MAX_RETURN_TYPES);
        throw(PARSER_ERR);
    }
}

/*
FUNC_SIGNATURE = 'fn' ('(' FUNC_PARAMS? ') FUNC_RETURN_TYPES? ')?
*/
static CHECK_RESULT FunctionSignature* parser_parse_function_signature(Parser *self) {
    FunctionSignature *signature;
    bool match;

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(FunctionSignature), (void**)&signature));
    throw_if_error(function_signature_init(signature, self->allocator));

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_FN, &match));
    if(!match)
        return NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_OPEN_PAREN, &match));
    if(match) {
        bool has_closing_paren;
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_CLOSING_PAREN, &has_closing_paren));
        if(!has_closing_paren) {
            parser_parse_function_parameters(self, signature);
            throw_if_error(tokenizer_accept(&self->tokenizer, TOK_CLOSING_PAREN));
        }
        parser_parse_function_return_types(self, signature);
    }

    return signature;
}

/*
VAR_TYPE = TOK_IDENTIFIER|FUNC_SIGNATURE
*/
void parser_parse_var_type(Parser *self, VariableType *result) {
    bool match;

    result->type = VARIABLE_TYPE_NONE;
    result->value.variable = NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_IDENTIFIER, &match));
    if(match) {
        result->type = VARIABLE_TYPE_VARIABLE;
        throw_if_error(arena_allocator_alloc(self->allocator, sizeof(Variable), (void**)&result->value.variable));
        variable_init(result->value.variable, self->tokenizer.value.identifier);
        return;
    }

    result->value.signature = parser_parse_function_signature(self);
    if(result->value.signature)
        result->type = VARIABLE_TYPE_SIGNATURE;
}

/*
VAR_TYPE_DEF = ':' VAR_TYPE
*/
void parser_parse_var_type_def(Parser *self, VariableType *result) {
    bool match;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_COLON, &match));
    if(!match) {
        result->type = VARIABLE_TYPE_NONE;
        result->value.variable = NULL;
        return;
    }

    parser_parse_var_type(self, result);
    if(result->type == VARIABLE_TYPE_NONE) {
        self->error = tokenizer_create_error(&self->tokenizer,
                                             tokenizer_get_error_index(&self->tokenizer),
                                             "Expected type or closure signature");
        throw(PARSER_UNEXPECTED_TOKEN);
    }
}

/*
LHS_DECLARATION = ('extern'|'export')? 'pub'? 'const'|'var' TOK_IDENTIFIER VAR_TYPE_DEF?
*/
static CHECK_RESULT LhsExpr* parser_parse_declaration_lhs(Parser *self) {
    LhsExpr *result;
    DeclFlag decl_flag;
    bool is_extern;
    bool is_export;
    bool is_pub;
    bool is_const;
    BufferView var_name;
    decl_flag = DECL_FLAG_NONE;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_EXTERN, &is_extern));
    if(is_extern) {
        decl_flag |= DECL_FLAG_EXTERN;
        if(self->has_func_parent) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                tokenizer_get_error_index(&self->tokenizer),
                                                "Only declarations in global structs can be extern");
            throw(PARSER_UNEXPECTED_TOKEN);
        }
    } else {
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_EXPORT, &is_export));
        if(is_export) {
            decl_flag |= DECL_FLAG_EXPORT;
            if(self->has_func_parent) {
                self->error = tokenizer_create_error(&self->tokenizer,
                                                    tokenizer_get_error_index(&self->tokenizer),
                                                    "Only declarations in global structs can be exported");
                throw(PARSER_UNEXPECTED_TOKEN);
            }
        }
    }

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_PUB, &is_pub));
    if(is_pub) {
        decl_flag |= DECL_FLAG_PUB;
        if(self->has_func_parent) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                tokenizer_get_error_index(&self->tokenizer),
                                                "Only declarations in global structs can be public");
            throw(PARSER_UNEXPECTED_TOKEN);
        }
    }

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_CONST, &is_const));
    if(is_const) {
        decl_flag |= DECL_FLAG_CONST;
    } else {
        bool isVar;

        if(is_extern || is_export) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                tokenizer_get_error_index(&self->tokenizer),
                                                "Extern and exported variables have to be declared with \"const\"");
            throw(PARSER_UNEXPECTED_TOKEN);
        }

        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_VAR, &isVar));
        if(!isVar)
            return NULL;
    }

    throw_if_error(tokenizer_accept(&self->tokenizer, TOK_IDENTIFIER));
    var_name = self->tokenizer.value.identifier;
    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(LhsExpr), (void**)&result));
    lhsexpr_init(result, decl_flag, var_name);

    if(var_name.size > VAR_MAX_LEN) {
        self->error = tokenizer_create_error(&self->tokenizer,
                                             tokenizer_get_code_reference_index(&self->tokenizer, var_name.data),
                                             "Variable name can't be longer than %d", VAR_MAX_LEN);
        throw(PARSER_ERR);
    }

    parser_parse_var_type_def(self, &result->type);
    return result;
}

/*

CLOSURE = FUNC_SIGNATURE '{' BODY_LOOP '}'
*/
static CHECK_RESULT FunctionDecl* parser_parse_closure(Parser *self) {
    FunctionSignature *signature;
    FunctionDecl *result;
    bool prev_has_func_parent;

    signature = parser_parse_function_signature(self);
    if(!signature)
        return NULL;

    /*
        TODO: Implement function declaration inside other functions.
        Such functions should be moved to the file scope in the bytecode generation
    */
    assert(parser_is_current_scope_file_scope(self) && "TODO: Implement function declaration inside other functions.");

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(FunctionDecl), (void**)&result));
    throw_if_error(funcdecl_init(result, signature, self->current_scope, self->allocator));
    signature->func_decl = result;
    result->body.function_signature = signature;

    self->current_scope = &result->body;
    prev_has_func_parent = self->has_func_parent;
    self->has_func_parent = bool_true;
    throw_if_error(tokenizer_accept(&self->tokenizer, TOK_OPEN_BRACE));
    parser_parse_body_loop(self, self->current_scope, TOK_CLOSING_BRACE);
    self->current_scope = result->body.parent;
    self->has_func_parent = prev_has_func_parent;
    return result;
}

/*
STRUCT = 'struct' '{' STRUCT_BODY_LOOP '}'
*/
static CHECK_RESULT StructDecl* parser_parse_struct_decl(Parser *self) {
    StructDecl *result;
    bool match;
    result = NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_STRUCT, &match));
    if(!match)
        return result;

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(StructDecl), (void**)&result));
    throw_if_error(structdecl_init(result, self->current_scope, self->allocator));

    self->current_scope = &result->body;
    parser_parse_struct_body_loop(self, result);
    self->current_scope = result->body.parent;
    return result;
}

/*
FUNC_ARGS = (RHS_START)? (',' RHS_START)* ')'
*/
static void parser_parse_function_args(Parser *self, FunctionCall *func_call) {
    bool first_arg = bool_true;
    int arg_index = 0;

    for(;;) {
        Ast *arg_expr;
        bool is_end_token;

        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_CLOSING_PAREN, &is_end_token));
        if(is_end_token)
            break;
        
        if(!first_arg)
            throw_if_error(tokenizer_accept(&self->tokenizer, TOK_COMMA));
        first_arg = bool_false;
        
        arg_expr = parser_parse_rhs(self);
        throw_if_error(buffer_append(&func_call->args, &arg_expr, sizeof(arg_expr)));
        ++arg_index;
        if (arg_index > FUNC_MAX_ARGS) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                 tokenizer_get_error_index(&self->tokenizer),
                                                 "A closure can't take more than %d arguments", FUNC_MAX_ARGS);
            throw(PARSER_ERR);
        }
    }
}

/*
VARIABLE = TOK_IDENTIFIER
FUNC_CALL_OR_VARIABLE = VARIABLE ('(' FUNC_ARGS ')')?
*/
static CHECK_RESULT Ast* parser_parse_function_call_or_variable(Parser *self) {
    Ast *result;
    bool match;
    BufferView identifier;
    FunctionCall *func_call;
    result = NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_IDENTIFIER, &match));
    if(!match)
        return result;
    
    identifier = self->tokenizer.value.identifier;
    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_OPEN_PAREN, &match));
    if(!match) {
        Variable *variable;
        throw_if_error(arena_allocator_alloc(self->allocator, sizeof(Variable), (void**)&variable));
        variable_init(variable, identifier);
        throw_if_error(ast_create(self->allocator, variable, AST_VARIABLE, &result));
        return result;
    }
    
    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(FunctionCall), (void**)&func_call));
    throw_if_error(funccall_init(func_call, self->tokenizer.value.identifier, self->allocator));
    throw_if_error(ast_create(self->allocator, func_call, AST_FUNCTION_CALL, &result));
    /* Ends after TOK_CLOSING_PAREN */
    parser_parse_function_args(self, func_call);
    return result;
}

/*
IMPORT = IMPORT_SYMBOL
*/
static CHECK_RESULT Import* parser_parse_import(Parser *self) {
    Import *result;
    bool match;
    result = NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_IMPORT, &match));
    if(!match)
        return result;
    
    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(Import), (void**)&result));
    import_init(result, self->tokenizer.value.string);
    return result;
}

/*
ELSE_IF_STATEMENT = 'else' ('if' RHS_BINOP)? ('{' BODY_LOOP '}')|BODY
*/
static CHECK_RESULT ElseIfStatement* parser_parse_else_if_statement(Parser *self) {
    ElseIfStatement *result;
    bool match;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_ELSE, &match));
    if(!match)
        return NULL;

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(ElseIfStatement), (void**)&result));
    throw_if_error(else_if_statement_init(result, self->current_scope, self->allocator));

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_IF, &match));
    if(match)
        result->condition = parser_parse_rhs_binop(self);

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_OPEN_BRACE, &match));
    if(match) {
        parser_parse_body_loop(self, &result->body, TOK_CLOSING_BRACE);
    } else {
        Ast *body_obj;
        body_obj = parser_parse_body(self);
        throw_if_error(scope_add_child(&result->body, body_obj));
    }

    return result;
}

static void parser_parse_else_if_statement_loop(Parser *self, IfStatement *if_stmt) {
    ElseIfStatement *else_if_stmt = NULL;
    for(;;) {
        ElseIfStatement *next_else_if;
        next_else_if = parser_parse_else_if_statement(self);
        if(!next_else_if)
            break;

        if(!else_if_stmt)
            if_stmt->else_if_stmt = next_else_if;
        else
            else_if_stmt->next_else_if_stmt = next_else_if;

        /* else statement that has no condition can't be followed by another else statement */
        if(!next_else_if->condition)
            break;
        else_if_stmt = next_else_if;
    }
}

/*
IF_STATEMENT = 'if' RHS_BINOP ('{' BODY_LOOP '}')|BODY ELSE_IF_STATEMENT*
*/
static CHECK_RESULT IfStatement* parser_parse_if_statement(Parser *self) {
    IfStatement *result;
    bool match;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_IF, &match));
    if(!match)
        return NULL;

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(IfStatement), (void**)&result));
    throw_if_error(if_statement_init(result, self->current_scope, self->allocator));

    result->condition = parser_parse_rhs_binop(self);

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_OPEN_BRACE, &match));
    if(match) {
        parser_parse_body_loop(self, &result->body, TOK_CLOSING_BRACE);
    } else {
        Ast *body_obj;
        body_obj = parser_parse_body(self);
        throw_if_error(scope_add_child(&result->body, body_obj));
    }

    parser_parse_else_if_statement_loop(self, result);
    return result;
}

/*
WHILE_STATEMENT = 'while' RHS_BINOP ('{' BODY_LOOP '}')|BODY
*/
static CHECK_RESULT WhileStatement* parser_parse_while_statement(Parser *self) {
    WhileStatement *result;
    bool match;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_WHILE, &match));
    if(!match)
        return NULL;

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(WhileStatement), (void**)&result));
    throw_if_error(while_statement_init(result, self->current_scope, self->allocator));

    result->condition = parser_parse_rhs_binop(self);

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_OPEN_BRACE, &match));
    if(match) {
        parser_parse_body_loop(self, &result->body, TOK_CLOSING_BRACE);
    } else {
        Ast *body_obj;
        body_obj = parser_parse_body(self);
        throw_if_error(scope_add_child(&result->body, body_obj));
    }

    return result;
}

static CHECK_RESULT Ast* parser_parse_number(Parser *self) {
    Ast *result;
    bool match;
    Number *number;
    result = NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_NUMBER, &match));
    if(!match)
        return result;
    
    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(Number), (void**)&number));
    number_init(number, self->tokenizer.value.integer, self->tokenizer.number_is_integer,
        create_buffer_view(self->tokenizer.code.data + self->tokenizer.prev_index, self->tokenizer.index - self->tokenizer.prev_index));
    throw_if_error(ast_create(self->allocator, number, AST_NUMBER, &result));
    return result;
}

/*
RHS_S = STRING | NUMBER | FUNC_CALL_OR_VARIABLE
*/
static CHECK_RESULT Ast* parser_parse_rhs_single_expr(Parser *self) {
    Ast *result;
    bool match;
    result = NULL;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_STRING, &match));
    if(match) {
        String *string;
        throw_if_error(arena_allocator_alloc(self->allocator, sizeof(String), (void**)&string));
        throw_if_error(string_init(string, self->tokenizer.value.string));
        throw_if_error(ast_create(self->allocator, string, AST_STRING, &result));
        return result;
    }

    result = parser_parse_number(self);
    if(result)
        return result;

    result = parser_parse_function_call_or_variable(self);
    if(result)
        return result;

    self->error = tokenizer_create_error(&self->tokenizer,
                                        tokenizer_get_error_index(&self->tokenizer),
                                        "Expected string, variable or function call");
    throw(PARSER_UNEXPECTED_TOKEN);
}

/*
RHS_BINOP_OPT_PAREN = RHS_S | '(' RHS_BINOP ')'
*/
static CHECK_RESULT Ast* parser_parse_rhs_binop_opt_paren(Parser *self) {
    Ast *result;
    bool match;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_OPEN_PAREN, &match));
    if(!match)
        return parser_parse_rhs_single_expr(self);

    result = parser_parse_rhs_binop(self);
    throw_if_error(tokenizer_accept(&self->tokenizer, TOK_CLOSING_PAREN));
    if(result->type == AST_BINOP)
        result->value.binop->grouped = bool_true;
    return result;
}

/*
RHS_BINOP = RHS_BINOP_OPT_PAREN (TOK_BINOP RHS_BINOP_OPT_PAREN)?

Note: Parantheses count has to match for the beginning paranthesis and the ending parenthesis.
*/
Ast* parser_parse_rhs_binop(Parser *self) {
    bool match;
    Ast *result;
    Ast *lhs;
    Ast *rhs;
    BinopType binop_type;
    Binop *binop;

    lhs = parser_parse_rhs_binop_opt_paren(self);
    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_BINOP, &match));
    if(!match)
        return lhs;
    binop_type = self->tokenizer.value.binop_type;

    rhs = parser_parse_rhs_binop(self);
    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(Binop), (void**)&binop));
    binop_init(binop);
    binop->type = binop_type;
    binop->lhs = lhs;
    binop->rhs = rhs;
    throw_if_error(ast_create(self->allocator, binop, AST_BINOP, &result));
    return result;
}

/*
RHS = RHS_BINOP ';'

Note: Parantheses count has to match for the beginning paranthesis and the ending parenthesis.
*/
Ast* parser_parse_rhs(Parser *self) {
    /* TODO: If binop only contains one expression, then use that directly for @rhs_expr */
    Ast *result;
    result = parser_parse_rhs_binop(self);

    /* TODO: Implement this */
    /*binop_reorder_by_precedence(binop);*/
    return result;
}

static bool type_requires_semicolon_at_end(AstType type) {
    /* TODO: Check for tables */
    return type != AST_FUNCTION_DECL && type != AST_STRUCT_DECL && type != AST_IF_STATEMENT;
}

/*
BODY_SEMICOLON = ';'

Note: Semicolon is not required for closures, structs and tables
*/
static void parser_parse_body_semicolon(Parser *self, Ast *expr) {
    if(expr->type == AST_BINOP) {
        bool match;
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_SEMICOLON, &match));
        if(!match) {
            /* TODO: Specify all the binop characters instead of "binop" which doesn't make sense for the user */
            self->error = tokenizer_create_error(&self->tokenizer,
                                                tokenizer_get_error_index(&self->tokenizer),
                                                "Expected ';' or binop");
            throw(PARSER_UNEXPECTED_TOKEN);
        }
        return;
    }

    if(type_requires_semicolon_at_end(expr->type))
        throw_if_error(tokenizer_accept(&self->tokenizer, TOK_SEMICOLON));
}

/* CONDITIONAL = (IF_STATEMENT|WHILE_STATEMENT)? */
static CHECK_RESULT Ast* parser_parse_conditional(Parser *self) {
    Ast *result;
    IfStatement *if_stmt;
    WhileStatement *while_stmt;

    if_stmt = parser_parse_if_statement(self);
    if(if_stmt) {
        throw_if_error(ast_create(self->allocator, if_stmt, AST_IF_STATEMENT, &result));
        self->error_context = ERROR_CONTEXT_NONE;
        return result;
    }

    while_stmt = parser_parse_while_statement(self);
    if(while_stmt) {
        throw_if_error(ast_create(self->allocator, while_stmt, AST_WHILE_STATEMENT, &result));
        self->error_context = ERROR_CONTEXT_NONE;
        return result;
    }

    return NULL;
}

/*
LHS_RHS = CLOSURE|STRUCT|IMPORT
*/
static Ast* parser_parse_lhs_rhs(Parser *self, LhsExpr *lhs_expr) {
    Ast *result;
    FunctionDecl *func_decl;
    StructDecl *struct_decl;
    Import *import;

    func_decl = parser_parse_closure(self);
    if(func_decl) {
        if(buffer_get_size(&func_decl->signature->return_types, FunctionReturnType) > 1 && (LHS_EXPR_IS_EXTERN(lhs_expr) || LHS_EXPR_IS_EXPORT(lhs_expr))) {
            self->error = tokenizer_create_error(&self->tokenizer,
                                                 tokenizer_get_code_reference_index(&self->tokenizer, lhs_expr->var_name.data),
                                                 "Extern and export closures can only have one return value");
            throw(PARSER_ERR);
        }
        throw_if_error(ast_create(self->allocator, func_decl, AST_FUNCTION_DECL, &result));
        func_decl->lhs_expr = lhs_expr;
        return result;
    }
    
    struct_decl = parser_parse_struct_decl(self);
    if(struct_decl) {
        throw_if_error(ast_create(self->allocator, struct_decl, AST_STRUCT_DECL, &result));
        return result;
    }

    import = parser_parse_import(self);
    if(import) {
        parser_queue_file(self, import->path, &import->file_scope);
        throw_if_error(ast_create(self->allocator, import, AST_IMPORT, &result));
        parser_parse_body_semicolon(self, result);
        return result;
    }

    return NULL;
}

/*
RETURN = 'return' RHS
*/
static ReturnExpr* parser_parse_return(Parser *self) {
    bool match;
    ReturnExpr *result;

    throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_RETURN, &match));
    if(!match)
        return NULL;

    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(ReturnExpr), (void**)&result));
    return_expr_init(result, parser_parse_rhs(self));
    return result;
}

/*
BODY =  (LHS_DECLARATION ';') |
        (LHS_DECLARATION '=' LHS_RHS|(RHS BODY_SEMICOLON)) |
        CONDITIONAL |
        (RHS ';'|('=' RHS BODY_SEMICOLON))
*/
Ast* parser_parse_body(Parser *self) {
    Ast *result;
    LhsExpr *lhs_expr;
    ReturnExpr *return_expr;
    Ast *rhs_expr;

    lhs_expr = parser_parse_declaration_lhs(self);
    if(lhs_expr) {
        bool match;

        throw_if_error(ast_create(self->allocator, lhs_expr, AST_LHS, &result));
        if(LHS_EXPR_IS_EXTERN(lhs_expr)) {
            throw_if_error(tokenizer_accept(&self->tokenizer, TOK_SEMICOLON));
            if (lhs_expr->type.type == VARIABLE_TYPE_NONE) {
                self->error = tokenizer_create_error(&self->tokenizer, tokenizer_get_code_reference_index(&self->tokenizer, lhs_expr->var_name.data), "An extern variable can't be declared without a type");
                throw(PARSER_UNEXPECTED_TOKEN);
            }
            return result;
        } else {
            throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_SEMICOLON, &match));
            if(match) {
                if(lhs_expr->type.type == VARIABLE_TYPE_SIGNATURE) {
                    self->error = tokenizer_create_error(&self->tokenizer, tokenizer_get_code_reference_index(&self->tokenizer, lhs_expr->var_name.data), "Expected function declaration. Only extern functions can have empty declarations.");
                    throw(PARSER_UNEXPECTED_TOKEN);
                } else if (lhs_expr->type.type == VARIABLE_TYPE_NONE) {
                    /* TODO: Allow this for non-const variables */
                    self->error = tokenizer_create_error(&self->tokenizer, tokenizer_get_code_reference_index(&self->tokenizer, lhs_expr->var_name.data), "A variable can't be declared without a type or assignment");
                    throw(PARSER_UNEXPECTED_TOKEN);
                } else if(LHS_EXPR_IS_CONST(lhs_expr)) {
                    self->error = tokenizer_create_error(&self->tokenizer, tokenizer_get_code_reference_index(&self->tokenizer, lhs_expr->var_name.data), "A const variable can't be declared without assignment");
                    throw(PARSER_UNEXPECTED_TOKEN);
                }
                return result;
            }
        }

        throw_if_error(tokenizer_accept(&self->tokenizer, TOK_EQUALS));

        lhs_expr->rhs_expr = parser_parse_lhs_rhs(self, lhs_expr);
        if(lhs_expr->rhs_expr)
            return result;
    } else {
        self->error_context = ERROR_CONTEXT_NO_LHS;
        result = parser_parse_conditional(self);
        if(result)
            return result;
    }

    if(self->has_func_parent) {
        return_expr = parser_parse_return(self);
        if(return_expr) {
            throw_if_error(tokenizer_accept(&self->tokenizer, TOK_SEMICOLON));
            throw_if_error(ast_create(self->allocator, return_expr, AST_RETURN, &result));
            return result;
        }
    }

    self->error_context = ERROR_CONTEXT_RHS_STANDALONE;
    rhs_expr = parser_parse_rhs(self);
    self->error_context = ERROR_CONTEXT_NONE;
    /* Variable declaration with lhs and rhs */
    if(lhs_expr) {
        lhs_expr->rhs_expr = rhs_expr;
    } else {
        bool match;
        throw_if_error(tokenizer_consume_if(&self->tokenizer, TOK_EQUALS, &match));
        /* Variable assignment */
        if(match) {
            AssignmentExpr *assign_expr;
            throw_if_error(arena_allocator_alloc(self->allocator, sizeof(AssignmentExpr), (void**)&assign_expr));
            throw_if_error(ast_create(self->allocator, assign_expr, AST_ASSIGN, &result));
            assign_expr->lhs_expr = rhs_expr;

            self->error_context = ERROR_CONTEXT_RHS_STANDALONE;
            assign_expr->rhs_expr = parser_parse_rhs(self);
            self->error_context = ERROR_CONTEXT_NONE;
        } else {
            /* Only rhs (for example function call, binop etc...) */
            result = rhs_expr;
        }
    }

    parser_parse_body_semicolon(self, rhs_expr);
    return result;
}

/*
STRUCT_BODY = TOK_IDENTIFIER VAR_TYPE_DEF ';'
*/
StructField* parser_parse_struct_body(Parser *self) {
    BufferView var_name;
    VariableType var_type;
    StructField *struct_field;

    throw_if_error(tokenizer_accept(&self->tokenizer, TOK_IDENTIFIER));
    var_name = self->tokenizer.value.identifier;
    parser_parse_var_type_def(self, &var_type);
    if(var_type.type == VARIABLE_TYPE_NONE) {
        self->error = tokenizer_create_error(&self->tokenizer,
                                             tokenizer_get_error_index(&self->tokenizer),
                                             "Expected ':' after struct field name");
        throw(PARSER_UNEXPECTED_TOKEN);
    }
    throw_if_error(tokenizer_accept(&self->tokenizer, TOK_SEMICOLON));
    throw_if_error(arena_allocator_alloc(self->allocator, sizeof(StructField), (void**)&struct_field));
    structfield_init(struct_field, var_name, &var_type);
    return struct_field;
}

/*
ROOT = BODY_LOOP
*/
int parser_parse_buffer(Parser *self, BufferView code_buffer, BufferView buffer_name) {
    int result;
    self->file_decl.var_name = buffer_name;
    throw_if_error(tokenizer_init(&self->tokenizer, self->allocator, code_buffer, buffer_name, &self->compiler->options));
    result = setjmp(self->parse_env);
    if(result == 0)
        parser_parse_body_loop(self, &self->struct_decl.body, TOK_END_OF_FILE);
    else if(self->error.str != NULL) {
        switch(self->error_context) {
            case ERROR_CONTEXT_NONE:
                tokenizer_print_error_object(&self->tokenizer, &self->error);
                break;
            case ERROR_CONTEXT_RHS_STANDALONE:
                /* TODO: Only show "return" in error message if @self->has_func_parent */
                tokenizer_print_error(&self->tokenizer, self->tokenizer.prev_index, "Expected string, variable, closure, struct, function call, import or return");
                break;
            case ERROR_CONTEXT_NO_LHS:
                tokenizer_print_error(&self->tokenizer, self->tokenizer.prev_index, "Expected variable declaration, string, variable or function call");
                break;
            default:
                assert(bool_false && "Error context handling not implemented");
                break;
        }
    }
    if(result != 0)
        amal_log_error("Failed, reason: %d", result);
    return result;
}

int parser_parse_file(Parser *self, BufferView filepath) {
    Buffer file_content;
    return_if_error(buffer_init(&file_content, self->allocator));
    assert(!self->started && "Parser can't be reused. Create a new parser.");
    self->started = bool_true;
    assert(filepath.size > 0 && filepath.data[filepath.size] == '\0');
    return_if_error(read_whole_file(filepath.data, &file_content));
    return parser_parse_buffer(self, create_buffer_view(file_content.data, file_content.size), filepath);
}

static CHECK_RESULT int file_path_join(BufferView directory, BufferView file, char **result_path) {
    /*                                        '/'             '\0'                    */
    return_if_error(am_malloc(directory.size + 1 + file.size + 1, (void**)result_path));
    am_memcpy(*result_path, directory.data, directory.size);
    (*result_path)[directory.size] = '/';
    am_memcpy(*result_path + directory.size + 1, file.data, file.size);
    (*result_path)[directory.size + 1 + file.size] = '\0';
    return 0;
}

/*
Path can be path to included library path (or system library path) in which case
the path separator is a dot, otherwise the path separator is forward slash '/'
*/
void parser_queue_file(Parser *self, BufferView path, ParserFileScopeReference **parser_file_scope) {
    /* TODO: Parse special path (to include library path with dots) */
    FileScopeReference *file_scope;
    BufferView file_directory;
    char *path_relative;
    int result;

    file_directory = file_get_parent_directory(self->tokenizer.code_name);
    throw_if_error(file_path_join(file_directory, path, &path_relative));
    /* We want buffer to be null-terminated but null character should not be included for the size */
    result = amal_compiler_internal_load_file(self->compiler, path_relative, &file_scope);
    if(result != 0) {
        self->error = tokenizer_create_error(&self->tokenizer, 
                                             tokenizer_get_code_reference_index(&self->tokenizer, path.data),
                                             "Failed to while parsing path %s (invalid path?)", path_relative);
        am_free(path_relative);
        throw(result);
    }
    am_free(path_relative);

    {
        usize parser_file_scope_index;
        int num_imports;
        BufferView import_path_canonical = create_buffer_view(file_scope->canonical_path.data, file_scope->canonical_path.size);

        if(hash_map_get(&self->imports_by_name, import_path_canonical, &parser_file_scope_index)) {
            *parser_file_scope = buffer_get(&self->imports, parser_file_scope_index, sizeof(ParserFileScopeReference*));
            return;
        }

        num_imports = buffer_get_size(&self->imports, ParserFileScopeReference*);
        if(num_imports == 254) {
            self->error = tokenizer_create_error(&self->tokenizer, 
                                                 tokenizer_get_error_index(&self->tokenizer),
                                                 "One file can't have more than 255 imports");
            throw(PARSER_ERR);
        }

        throw_if_error(arena_allocator_alloc(self->allocator, sizeof(ParserFileScopeReference*), (void**)parser_file_scope));
        (*parser_file_scope)->file_scope_ref = file_scope;
        (*parser_file_scope)->import_index = num_imports;
        throw_if_error(buffer_append(&self->imports, parser_file_scope, sizeof(ParserFileScopeReference*)));
        throw_if_error(hash_map_insert(&self->imports_by_name, import_path_canonical, &parser_file_scope_index));
    }
}