forked from vojone/IFJ21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser_topdown.c
2231 lines (1735 loc) · 70.8 KB
/
parser_topdown.c
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
/******************************************************************************
* IFJ21
* parser_topdown.c
*
* Authors: Radek Marek (xmarek77), Vojtěch Dvořák (xdvora3o),
* Juraj Dědič (xdedic07), Tomáš Dvořák (xdvora3r)
*
* Purpose: Source file for recursive descent parser
* (For more documentation parser_topdown.h)
*
* Last change: 8. 12. 2021
*****************************************************************************/
/**
* @file parser-topdown.c
* @brief Source file for recursive descent parser
* @note For more documentation about functions and structures @see parser_topdown.h
*
* @authors Radek Marek (xmarek77), Vojtěch Dvořák (xdvora3o),
* Juraj Dědič (xdedic07), Tomáš Dvořák (xdvora3r)
*/
#include "parser_topdown.h"
#define RULESET_GLOBAL_LENGTH 4 /**< Number of rules that can be used for parsing rules in global scopes */
rule_t * get_global_rule(size_t index) {
if(index >= RULESET_GLOBAL_LENGTH) { //Safety check
return NULL;
}
static rule_t ruleset_global[RULESET_GLOBAL_LENGTH] = {
{parse_function_dec, {KEYWORD, UNSET, "global"}, true },
{parse_function_def, {KEYWORD, UNSET, "function"}, true },
{parse_global_identifier, {IDENTIFIER, UNSET, NULL}, false},
{EOF_global_rule, {EOF_TYPE, UNSET, NULL}, false},
};
return &ruleset_global[index];
}
#define RULESET_INSIDE_LENGTH 8 /**< Number of rules that can be used for parsing rules in local scopes */
rule_t * get_inside_rule(size_t index) {
if(index >= RULESET_INSIDE_LENGTH) { //Safety check
return NULL;
}
static rule_t ruleset_inside[RULESET_INSIDE_LENGTH] = {
{parse_local_var, {KEYWORD, UNSET, "local"}, true },
{parse_if, {KEYWORD, UNSET, "if"}, true },
{parse_else, {KEYWORD, UNSET, "else"}, true },
{parse_while, {KEYWORD, UNSET, "while"}, true },
{parse_return, {KEYWORD, UNSET, "return"}, true },
{parse_end, {KEYWORD, UNSET, "end"}, true },
{parse_identifier, {IDENTIFIER, UNSET, NULL}, false },
{EOF_fun_rule, {EOF_TYPE, UNSET, NULL}, false },
};
return &ruleset_inside[index];
}
void to_outer_ctx(parser_t *parser) {
if(!symtabs_is_empty(&parser->sym.symtab_st)) { //There must by something in the stack
destroy_tab(&parser->sym.symtab);
parser->sym.symtab = symtabs_pop(&parser->sym.symtab_st);
}
}
void to_inner_ctx(parser_t *parser) {
symtabs_push(&parser->sym.symtab_st, parser->sym.symtab); //Save copy of old symtab to the stack of symtabs
symtab_t new_ctx; //Create and init new symtab
init_tab(&new_ctx);
new_ctx.parent_ind = symtabs_get_top_ind(&parser->sym.symtab_st); //Save reference to the parent symtab
parser->sym.symtab = new_ctx;
}
bool is_global_ctx(parser_t *parser) {
return symtabs_is_empty(&(parser->sym.symtab_st));
}
int parser_setup(parser_t *parser, scanner_t *scanner) {
parser->scanner = scanner;
//Initialization of symbol tables
symtab_t global_tab;
init_tab(&global_tab);
parser->sym.global = global_tab;
symtab_t symbol_tab;
init_tab(&symbol_tab);
parser->sym.symtab = symbol_tab;
//Initialization of variables and flags in parser structure
parser->decl_cnt = 0;
parser->cond_cnt = 0;
parser->loop_cnt = 0;
parser->reached_EOF = false;
parser->found_return = false;
parser->return_code = PARSE_SUCCESS;
//Initialization of internal reprezentation for code generator
prog_t dst_code;
init_new_prog(&dst_code);
parser->dst_code = dst_code;
if(!symtabs_stack_init(&parser->sym.symtab_st) ||
!tok_stack_init(&parser->decl_func) ||
!instr_stack_init(&parser->dst_code.cycle_stack)) {
int_error("Error during parser initialization!");
return INTERNAL_ERROR;
}
return EXIT_SUCCESS;
}
void parser_dtor(parser_t *parser) {
destroy_tab(&parser->sym.symtab);
destroy_tab(&parser->sym.global);
while(!symtabs_is_empty(&(parser->sym.symtab_st))) { //Free all symbol tables inside stack
symtab_t current = symtabs_pop(&(parser->sym.symtab_st));
destroy_tab(¤t);
}
symtabs_stack_dtor(&(parser->sym.symtab_st));
tok_stack_dtor(&(parser->decl_func));
instr_stack_dtor(&parser->dst_code.cycle_stack);
}
int check_if_defined(parser_t *parser) {
while(!tok_is_empty(&parser->decl_func)) {
token_t func_id = tok_pop(&parser->decl_func);
char *func_name = get_attr(&func_id, parser->scanner);
tree_node_t * symbol = search(&parser->sym.global, func_name);
if(symbol) { //Just for safety
if(symbol->data.status == DECLARED) {
if(symbol->data.was_used) { //Function was declared and called but not defined
error_semantic(parser, "Function '\033[1;33m%s\033[0m' was declared, called but not defined!", func_name);
return SEMANTIC_ERROR_DEFINITION;
}
else {
warn(parser, "Function '\033[1;33m%s\033[0m' was declared, but is not used nor defined!", func_name);
return PARSE_SUCCESS;
}
}
}
}
return PARSE_SUCCESS;
}
bool safe_increment(size_t *cnt) {
if(*cnt == SIZE_MAX) { //Prevent overflow
return false;
}
else {
(*cnt)++;
return true;
}
}
//<program> -> <global-statement-list>
int parse_program(parser_t *parser) {
//scanner_init(scanner);
generate_init(&parser->dst_code);
int res = PARSE_SUCCESS;
res = parse_require(parser); //Check prolog (there MUST be require "ifj21")
//Run parsing
res = (res == PARSE_SUCCESS) ? global_statement_list(parser) : res;
debug_print("Finished! return code: %i, at: (%lu, %lu)\n", res, parser->scanner->cursor_pos[ROW], parser->scanner->cursor_pos[COL]);
res = (res == PARSE_SUCCESS) ? check_if_defined(parser) : res;
//check which builtin functions are called
generate_builtin(&parser->dst_code,&parser->sym.global);
parser_dtor(parser);
if(parser->return_code != 0) {
res = parser->return_code;
}
//Print generated code
if(res == PARSE_SUCCESS && parser->return_code == PARSE_SUCCESS) {
print_program(&parser->dst_code);
}
program_dtor(&parser->dst_code);
return res;
}
//<global-statement-list> -> <global-statement> <global-statement-list>
int global_statement_list(parser_t *parser) {
int ret = PARSE_SUCCESS;
ret = global_statement(parser);
if(ret != PARSE_SUCCESS)
return ret;
if(parser->reached_EOF)
return PARSE_SUCCESS;
return global_statement_list(parser);
}
//<statement-list> -> <statement> <statement-list>
int statement_list(parser_t *parser) {
int ret = statement(parser);
if(ret != PARSE_SUCCESS) {
return ret;
}
token_t t = lookahead(parser->scanner);
if(is_error_token(&t, &ret)) {
return ret;
}
if(compare_token(t, KEYWORD)) {
if(compare_token_attr(parser, t, KEYWORD, "end")) {
debug_print("got end\n");
return PARSE_SUCCESS;
}
else if(compare_token_attr(parser, t, KEYWORD, "else")) {
debug_print("got else\n");
return PARSE_SUCCESS;
}
}
return statement_list(parser);
}
int global_statement(parser_t *parser) {
debug_print("parsing next global statement...\n");
token_t t = lookahead(parser->scanner);
int res = EXPRESSION_SUCCESS;
if(is_error_token(&t, &res)) {
return res;
}
//Get the apropriate rule
rule_t* rule_to_use = determine_rule(parser, t, get_global_rule);
if(rule_to_use == NULL) {
return SYNTAX_ERROR;
}
//Call the right function
res = rule_to_use->rule_function(parser);
//If there is (null) instead the first token of the rule, it means that the rule is using only token type and not attribute
debug_print("global statement %s returned code %i\n", rule_to_use->rule_first.attr, res);
return res;
}
int statement(parser_t *parser) {
debug_print("parsing next statement...\n");
token_t t = lookahead(parser->scanner);
int res = EXPRESSION_SUCCESS;
if(is_error_token(&t, &res)) {
return res;
}
//get the apropriate rule
rule_t* rule_to_use = determine_rule(parser, t, get_inside_rule);
if(rule_to_use == NULL) {
return SYNTAX_ERROR;
}
//call the right function
res = rule_to_use->rule_function(parser);
//if there is (null) instead the first token of the rule, it means that the rule is using only token type and not attribute
debug_print("statement %s returned code %i\n", rule_to_use->rule_first.attr, res);
return res;
}
bool is_convertable(sym_dtype_t var_type, sym_dtype_t r_side_type) {
return var_type == NUM && r_side_type == INT;
}
bool is_valid_assign(prog_t *dst_code, sym_dtype_t var_type, sym_dtype_t r_side_type) {
if(var_type == r_side_type || r_side_type == NIL) { //Types are same or rvalue type is nil
return true;
}
else if(var_type == NUM && r_side_type == INT) { //Types can be implicitly converted
return true;
}
else {
return false;
}
}
int assignment_parse_id(parser_t *parser, token_t *t,
string_t *id_types, tok_stack_t *var_names) {
//Try to find identifier in symbol table (or in parent symbol table)
char * id_str = get_attr(t, parser->scanner);
tree_node_t * symbol = deep_search(&parser->sym.symtab_st, &parser->sym.symtab, id_str);
if(!symbol || symbol->data.type != VAR) {
error_semantic(parser, "Undeclared variable \033[1;33m%s\033[0m!", id_str);
return SEMANTIC_ERROR_DEFINITION;
}
else {
//push it to the var name stack for code generation
tok_push(var_names, *t);
app_char(dtype_to_char(symbol->data.dtype), id_types);
set_var_status(symbol, DEFINED);
return PARSE_SUCCESS;
}
}
int assignment_lside(parser_t *parser, token_t* start_id,
string_t *id_types, tok_stack_t *var_names) {
size_t id_number = 0;
token_t t = *start_id;
bool foundAssignmentOp = false;
int res = EXPRESSION_SUCCESS;
while(!foundAssignmentOp) {
//First token is already read at the beginning, so we check wheter we are at the beginning
if(id_number != 0) {
t = get_next_token(parser->scanner);
if(is_error_token(&t, &res)) {
return res;
}
}
//The next token should be identifier
if(t.token_type == IDENTIFIER) {
id_number++;
res = assignment_parse_id(parser, &t, id_types, var_names);
if(res != PARSE_SUCCESS) {
return res;
}
}
else {
error_unexpected_token(parser, "IDENTIFIER", t);
return SYNTAX_ERROR;
}
//Comma should follow, or assignment operator
t = get_next_token(parser->scanner);
if(is_error_token(&t, &res)) {
return res;
}
if(compare_token_attr(parser, t, SEPARATOR, ",")) {
//Ok, next token should be mext identifier
}
else if(compare_token_attr(parser, t, OPERATOR, "=")) {
foundAssignmentOp = true;
}
else {
error_unexpected_token(parser, "SEPARATOR ',' or OPERATOR '='", t);
return SYNTAX_ERROR;
}
}
return PARSE_SUCCESS;
}
void prog_stack_deep_dtor(prog_stack_t *prog) {
while(!prog_is_empty(prog)) {
prog_t cur = prog_pop(prog);
program_dtor(&cur);
}
prog_stack_dtor(prog);
}
int assignment_expr(size_t *cnt, parser_t *parser,
string_t *id_types, string_t *rside,
bool *was_f_called, prog_stack_t *expr_progs) {
size_t id_number = len(id_types);
prog_t cur_expr;
init_new_prog(&cur_expr); //Pointers are stored in program stack, so dont care about leaks
string_t ret_types;
if(str_init(&ret_types) != STR_SUCCESS) {
return INTERNAL_ERROR;
}
//check for valid expression
debug_print("Calling precedence parser...\n");
int expr_retval = parse_expression(parser->scanner, &parser->sym, &ret_types, was_f_called, &cur_expr);
debug_print("RET_TYPES: %s\n", to_str(&ret_types));
debug_print("%d %d\n", *cnt, id_number);
size_t u = 0;
if(expr_retval == EXPRESSION_SUCCESS && *cnt < id_number) {
for(; to_str(&ret_types)[u] != '\0' && u + *cnt < id_number; u++) { //If there is only function, it can return more than one values
sym_dtype_t cur_dtype = char_to_dtype(to_str(&ret_types)[u]);
sym_dtype_t should_be = char_to_dtype(id_types->str[*cnt + u]);
if(!is_valid_assign(&cur_expr, should_be, cur_dtype)) { //Type checking in (multiple) assignment
str_dtor(&ret_types);
program_dtor(&cur_expr);
if(!(*was_f_called)) {
error_semantic(parser, "Type of variable is not compatible with rvalue of assignment!");
return SEMANTIC_ERROR_ASSIGNMENT;
}
else {
error_semantic(parser, "Return type of function in assignment is not compatible with variable!");
return SEMANTIC_ERROR_PARAMETERS;
}
}
else {
if(app_char(to_str(&ret_types)[u], rside) != STR_SUCCESS) {
str_dtor(&ret_types);
program_dtor(&cur_expr);
return INTERNAL_ERROR;
}
//Assignment is ok
}
if(lookahead_token_attr(parser, SEPARATOR, ",")) { //If there is, after function call, only first return value is used
generate_dump_values(&cur_expr, 1, len(&ret_types) - 1);
u = 1;
break;
}
}
if(u < len(&ret_types) && !lookahead_token_attr(parser, SEPARATOR, ",")) { //Discard values that won't be used from stack
generate_dump_values(&cur_expr, u, len(&ret_types) - u);
}
if(!prog_push(expr_progs, cur_expr)) { //Saving expression code to stack
str_dtor(&ret_types);
return INTERNAL_ERROR;
}
*cnt += u; //Increment rside value counter by return type amount
}
else if(expr_retval == EXPRESSION_SUCCESS) {
program_dtor(&cur_expr);
}
else {
debug_print("Error while parsing expression for multiple assignment\n");
program_dtor(&cur_expr);
str_dtor(&ret_types);
return expr_retval;
}
str_dtor(&ret_types);
return PARSE_SUCCESS;
}
int assignment_rside(parser_t *parser, string_t *id_types, string_t *rside) {
size_t id_number = len(id_types); //Number of values is length of string with datatypes characters
bool f_call = false;
prog_stack_t expr_progs;
if(!prog_stack_init(&expr_progs)) {
return INTERNAL_ERROR;
}
size_t i = 0;
int ret = EXPRESSION_SUCCESS;
bool found_end = false;
while(!found_end) {
token_t t = lookahead(parser->scanner);
if(is_error_token(&t, &ret)) {
prog_stack_deep_dtor(&expr_progs);
return ret;
}
if(!is_expression(parser, t)) {
prog_stack_deep_dtor(&expr_progs);
error_semantic(parser, "Missing rvalue in assignment (expected expression)!");
return SEMANTIC_ERROR_ASSIGNMENT;
}
ret = assignment_expr(&i, parser, id_types, rside, &f_call, &expr_progs);
if(ret != PARSE_SUCCESS) {
prog_stack_deep_dtor(&expr_progs);
return ret;
}
t = lookahead(parser->scanner);
if(is_error_token(&t, &ret)) {
prog_stack_deep_dtor(&expr_progs);
return ret;
}
if(compare_token_attr(parser, t, SEPARATOR, ",")) {
//Ok
get_next_token(parser->scanner);
}
else {
found_end = true;
if(i < id_number) {
prog_stack_deep_dtor(&expr_progs);
if(f_call) {
error_semantic(parser, "Function in assignment doesn't return enough values!");
return SEMANTIC_ERROR_PARAMETERS;
}
else {
error_semantic(parser, "Missing rvalue in assignment!");
return SEMANTIC_ERROR_ASSIGNMENT;
}
}
}
}
while(!prog_is_empty(&expr_progs)) { //Apends expression to main program (to evaluate it from right to left)
prog_t cur = prog_pop(&expr_progs);
app_prog(&parser->dst_code, &cur);
}
prog_stack_deep_dtor(&expr_progs);
return PARSE_SUCCESS;
}
//<assignment> -> <id-list> = <expression-list>
int assignment(parser_t *parser, token_t t) {
token_t var_id = t;
debug_print("var id: %s\n", get_attr(&var_id, parser->scanner));
string_t id_types;
if(str_init(&id_types) != STR_SUCCESS) {
return INTERNAL_ERROR;
}
//Push names to the stack in lside
tok_stack_t var_names;
if(!tok_stack_init(&var_names)) {
str_dtor(&id_types);
return INTERNAL_ERROR;
}
int retval = assignment_lside(parser, &var_id, &id_types, &var_names);
debug_print("found %i assignment with types %s ...\n", len(&id_types), to_str(&id_types));
string_t rside_types;
if(str_init(&rside_types) != STR_SUCCESS) {
str_dtor(&id_types);
return INTERNAL_ERROR;
}
retval = (retval == PARSE_SUCCESS) ? assignment_rside(parser, &id_types, &rside_types) : retval;
//Generate assignment of the values on stack
if(!tok_revert(&var_names)) {
retval = INTERNAL_ERROR;
}
size_t cnt = 0;
while(!tok_is_empty(&var_names)) {
token_t name_token = tok_pop(&var_names);
string_t name_unique = get_unique_name(&parser->sym.symtab_st, &parser->sym.symtab, &name_token, parser->scanner);
if(is_convertable(char_to_dtype(to_str(&id_types)[cnt]), char_to_dtype(to_str(&rside_types)[cnt]))) {
impl_int2num(&parser->dst_code);
}
cnt++;
generate_assign_value(&parser->dst_code, name_unique.str);
}
//generate_multiple_assignment(&parser->dst_code, &parser->sym.symtab_st, &parser->sym.symtab, &var_names, parser->scanner);
str_dtor(&rside_types);
str_dtor(&id_types);
tok_stack_dtor(&var_names);
return retval;
}
sym_dtype_t keyword_to_dtype(token_t * t, scanner_t *sc) {
if (str_cmp(get_attr(t, sc), "string") == 0) {
return STR;
}
else if(str_cmp(get_attr(t, sc), "integer") == 0) {
return INT;
}
else if(str_cmp(get_attr(t, sc), "number") == 0) {
return NUM;
}
else if(str_cmp(get_attr(t, sc), "nil") == 0) {
return NIL;
}
//If it is not valid data type it returns implicitly INT type
return INT;
}
char *dtype_to_keyword(sym_dtype_t dtype) {
char *result;
switch (dtype)
{
case INT:
result = "integer";
break;
case NUM:
result = "number";
break;
case STR:
result = "string";
break;
default:
result = "";
break;
}
return result;
}
//Inserts variable into current symbol table
void ins_var(parser_t *parser, token_t *id_token,
sym_status_t status, sym_dtype_t dtype) {
char *f_name = get_attr(parser->curr_func_id, parser->scanner);
size_t cur_f_len = strlen(f_name);
char *orig_name = get_attr(id_token, parser->scanner);
//Making unique name for target code
string_t var_name;
str_init(&var_name);
str_cpy_tostring(&var_name, f_name, cur_f_len); //'name_of_current_function'
app_char('$', &var_name); //'name_of_current_function'$
app_str(&var_name, orig_name); //'name_of_current_function'$'name_of_variable_in_ifj21'
app_char('$', &var_name); //'name_of_current_function'$'name_of_variable_in_ifj21'$
char conv_buff[DECLARATION_COUNTER_MAX_LEN];
snprintf(conv_buff, DECLARATION_COUNTER_MAX_LEN, "%ld", parser->decl_cnt);
app_str(&var_name, conv_buff);
sym_data_t symdata_var = {.name = var_name, .type = VAR,
.dtype = dtype, .status = status};
debug_print("Putting %s into symbol table... its name is %s and status is %d\n", orig_name, to_str(&var_name), status);
insert_sym(&parser->sym.symtab, orig_name, symdata_var); //Finall putting the variable into symbol table
}
void set_var_status(tree_node_t *var, sym_status_t new_stat) {
if(var) {
var->data.status = new_stat; //The most direct way without searching in any symtab
}
}
void set_use_flag(tree_node_t *symbol, bool new_s) {
if(symbol) {
symbol->data.was_used = new_s;
}
}
//<value-assignment>
int local_var_assignment(parser_t *parser, sym_status_t *status,
sym_dtype_t dtype, token_t *var_id) {
if(lookahead_token_attr(parser, OPERATOR, "=")) {
//Delete it temporarly, because it is hiding same name variables in outer scope (they can be used in initialization)
delete_sym(&parser->sym.symtab, get_attr(var_id, parser->scanner));
get_next_token(parser->scanner);
//If there is = we check the value assignment
debug_print("Calling precedence parser...\n");
char *id_char = get_attr(var_id, parser->scanner);
string_t ret_types;
str_init(&ret_types);
bool was_f_called;
int return_val = parse_expression(parser->scanner, &parser->sym, &ret_types, &was_f_called, &parser->dst_code);
if(return_val != EXPRESSION_SUCCESS) { //Check of return code of parsing expression
str_dtor(&ret_types);
return return_val;
}
else {
*status = DEFINED; //Ok
}
if(!is_valid_assign(&parser->dst_code, dtype, prim_dtype(&ret_types))) { //Check of data type compatibility in initialization
error_semantic(parser, "Incompatible data types in initialization of variable '\033[1;33m%s\033[0m'\n", id_char);
str_dtor(&ret_types);
return SEMANTIC_ERROR_ASSIGNMENT;
}
str_dtor(&ret_types);
ins_var(parser, var_id, *status, dtype); //After initialization, it must be inserted to the symtable again
//Generate assigment code
char * unique_name = get_unique_name(&parser->sym.symtab_st, &parser->sym.symtab, var_id, parser->scanner).str;
generate_assign_value(&parser->dst_code,unique_name);
}
return PARSE_SUCCESS;
}
//: [type]
int local_var_datatype(parser_t *p, token_t *curr_tok, sym_dtype_t *var_type) {
//Should be a comma
bool comma = check_next_token_attr(p, SEPARATOR, ":");
if(!comma) {
return SYNTAX_ERROR;
}
//Should be a data type
*curr_tok = get_next_token(p->scanner);
int ret = EXPRESSION_SUCCESS;
if(is_error_token(curr_tok, &ret)) {
return ret;
}
//Determining data type of declared variable
if(!is_datatype(p, *curr_tok)) {
error_unexpected_token(p, "datatype", *curr_tok);
return SYNTAX_ERROR;
}
else {
*var_type = keyword_to_dtype(curr_tok, p->scanner);
}
return PARSE_SUCCESS;
}
//local [id] : [type] <value-assignment>
int parse_local_var(parser_t *parser) {
//Go one token forward
get_next_token(parser->scanner);
//Should be identifier
token_t t = get_next_token(parser->scanner);
int retval = EXPRESSION_SUCCESS;
if(is_error_token(&t, &retval)) {
return retval;
}
token_t var_id = t;
sym_dtype_t var_type;
sym_status_t status = DECLARED;
if(!compare_token(t, IDENTIFIER)) {
error_unexpected_token(parser, "identifier", t);
return SYNTAX_ERROR;
}
//There must be data type
retval = local_var_datatype(parser, &t, &var_type);
if(retval != EXPRESSION_SUCCESS) {
return retval;
}
if(search(&parser->sym.symtab, get_attr(&var_id, parser->scanner))) { //Variable is declared in current scope
error_semantic(parser, "Redeclaration of variable \033[1;33m%s\033[0m!",
get_attr(&var_id, parser->scanner));
return SEMANTIC_ERROR_DEFINITION;
}
if(search(&parser->sym.global, get_attr(&var_id, parser->scanner))) { //Variable is declared in global scope
error_semantic(parser, "Name of variable \033[1;33m%s\033[0m is colliding with function name!",
get_attr(&var_id, parser->scanner));
return SEMANTIC_ERROR_DEFINITION;
}
//Insert to symtab and generate code
ins_var(parser, &var_id, status, var_type);
generate_declare_variable(&parser->dst_code, &parser->sym.symtab_st, &parser->sym.symtab, &var_id, parser->scanner);
//There can be a value assignment
retval = (retval == PARSE_SUCCESS) ? local_var_assignment(parser, &status, var_type, &var_id) : retval;
//Incrementation of declaration counter to declare unique var names in target code
if(!safe_increment(&parser->decl_cnt)) {
return INTERNAL_ERROR;
}
return retval;
}
//<prolog> -> require "ifj21"
int parse_require(parser_t *parser) {
//Go one token forward
token_t t = get_next_token(parser->scanner);
int ret = EXPRESSION_SUCCESS;
if(is_error_token(&t, &ret)) {
return ret;
}
if(compare_token_attr(parser, t, KEYWORD, "require")) {
//require is Ok, check string after
t = get_next_token(parser->scanner);
if(is_error_token(&t, &ret)) {
return ret;
}
if(compare_token_attr(parser, t, STRING, "\"ifj21\"")) {
return PARSE_SUCCESS;
}
else {
error_semantic(parser, "Required \"ifj21\" in prolog!");
return SEMANTIC_ERROR_OTHER;
}
}
else {
error_unexpected_token(parser, "require", t);
}
return SYNTAX_ERROR;
}
void ins_func(parser_t *parser, token_t *id_token, sym_data_t *data) {
char *f_name = get_attr(id_token, parser->scanner); //Pointer to string that contains name of function
size_t id_len = strlen(f_name);
//There is no need to creation original name of function (it always must be original in whole program)
str_cpy_tostring(&data->name, f_name, id_len);
debug_print("Putting %s into symbol table... its name is %s and (status: %d, ret_types: %s, params: %s)\n", f_name, to_str(&data->name), data->status, to_str(&data->ret_types), to_str(&data->params));
insert_sym(&parser->sym.global, f_name, *data);
}
//<type-list> -> : [type] <type-list-1>
int func_dec_returns(parser_t *parser, string_t *returns) {
if(lookahead_token_attr(parser, SEPARATOR, ":")) {
//Will just get the ':'
debug_print("parsing function return types...\n");
token_t t = get_next_token(parser->scanner);
int retval = EXPRESSION_SUCCESS;
if(is_error_token(&t, &retval)) {
return retval;
}
bool finished = false;
while(!finished) {
//Should be datatype
t = get_next_token(parser->scanner);
if(is_error_token(&t, &retval)) {
return retval;
}
if(!is_datatype(parser, t)) {
error_unexpected_token(parser, "data type", t);
finished = true;
return SYNTAX_ERROR;
}
else {
sym_dtype_t dtype = keyword_to_dtype(&t, parser->scanner);
char dtype_c = dtype_to_char(dtype);
app_char(dtype_c, returns);
}
//If there is no comma we should be at the end of the list
bool comma = lookahead_token_attr(parser, SEPARATOR, ",");
if(!comma) {
finished = true;
}
else {
//We go one token forward
get_next_token(parser->scanner);
}
}
}
return PARSE_SUCCESS;
}
//(<param-list>)
int func_dec_params(parser_t *parser, string_t *params) {
if(!check_next_token_attr(parser, SEPARATOR, "("))
return SYNTAX_ERROR;
if(is_datatype(parser, lookahead(parser->scanner))) {
debug_print("parsing function param types...\n");
bool finished = false;
int retval = EXPRESSION_SUCCESS;
while(!finished) {
//Should be datatype
token_t t = get_next_token(parser->scanner);
if(is_error_token(&t, &retval)) {
return retval;
}
if(!is_datatype(parser, t)) {
error_unexpected_token(parser, "data type", t);
finished = true;
return SYNTAX_ERROR;
}
else {
sym_dtype_t dtype = keyword_to_dtype(&t, parser->scanner);
char type_c = dtype_to_char(dtype);
app_char(type_c, params);
}
//If there is no comma we should be at the end of the list
bool comma = lookahead_token_attr(parser, SEPARATOR, ",");
if(!comma) {
finished = true;
}
else {
//We go one token forward
get_next_token(parser->scanner);
}
}
}
if(!check_next_token_attr(parser, SEPARATOR, ")")) {
return SYNTAX_ERROR;
}
return PARSE_SUCCESS;
}
//<global-statement> -> global [id] : function(<param-list>) <type-list>
int parse_function_dec(parser_t *parser) {
//This token is just 'global' we skip it
get_next_token(parser->scanner);
//This is function ID
int retval = EXPRESSION_SUCCESS;
token_t id_fc = get_next_token(parser->scanner);
if(is_error_token(&id_fc, &retval)) {
return retval;
}
//Puts builtin function into symtable