-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.c
1577 lines (1383 loc) · 40.3 KB
/
parser.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
/*********************************************
* Program : parser.c
* Authors : Roman Dobiáš - xdobia11
* Adrián Tomašov - xtomas32
* Jozef Urbanovský - xurban66
* Adam Šulc - xsulca00
* Kristián Barna - xbarna02
* Skupina : 2BIB(2016)
* Created : 01.10.2016
* Compiled: gcc 4.9.2
* Project : IFJ16
*
* Notes : Implementation of parser
********************************************/
#include "parser.h"
#include <stdio.h>
#include <string.h>
#include "scanner.h"
#include "interpret.h"
#include "ial.h"
#include "error.h"
#include "op-parser.h"
// global instance of Table of symbols
stab_t *staticSym = NULL;
// instruction tape carrying user's program
instruction_list_t* insProgram = NULL;
// instruction tape used to inicialize static vars
instruction_list_t* insInit = NULL;
// global flag to detect the order of pass
int isSecondPass = 0;
// global name of class we are wrapped in
char* parser_class = NULL;
// global name of function we are parsing in
char* parser_fun = NULL;
// global counter used to compare lexical order of parsing symbol
unsigned int current_rank = 0;
// global counter to determine the count of local variables
// and is neccessary to set correct stack offset of local variables
int localVariablesCount = 0;
/******************************************************************************
HEADERS
******************************************************************************/
int implicitConversion(int src, int dest);
int class_definition_list();
int type_specifier(int* type);
int iteration_statement();
int jump_statement();
int definition();
int block_items_list();
int compound_statement();
int function_parameters_list(data_t*);
int statement();
int parameter_definition();
int function_arguments_list(data_t**);
int builtin_print();
void generateStore(data_t* dest, data_t* src);
/******************************************************************************
SYNTACTIC UTILS
******************************************************************************/
int isTokenKeyword(int desiredKeyword)
{
return (getLastToken() == TOK_KEYWORD && getTokInt() == desiredKeyword);
}
int isIdentifier()
{
return (getLastToken() == TOK_ID
|| getLastToken() == TOK_SPECIAL_ID);
}
int isTokenTypeSpecifier()
{
return (getLastToken() == TOK_KEYWORD && (
getTokInt() == KW_INT ||
getTokInt() == KW_DOUBLE||
getTokInt() == KW_STRING));
}
// Static expressions are special cases of expressions as their code is
// generated to insInit instead of insProgram
int parse_static_expr(data_t* sym, bool generate)
{
// update current symbol lexical order
current_rank = sym->rank;
instruction_list_t* tmp = NULL;
if(generate)
{
// swap instruction lists
tmp = insProgram;
insProgram = insInit;
insInit = tmp;
}
int type = parse_expression(generate, false);
if(generate)
sym->is_inicialized = 1;
if(generate)
{
if(implicitConversion(type, sym->type) == 0)
error_and_die(SEMANTIC_TYPE_ERROR, "Invalid conversion");
generateStore(sym, NULL);
// swap instruction lists
tmp = insProgram;
insProgram = insInit;
insInit = tmp;
}
return type;
}
/******************************************************************************
SEMANTIC UTILS
******************************************************************************/
// Hack to ensure detection of uninicialized static symbols
// -> change the type of all uninicialized symbols (required by intepreter)
void fixStaticVars()
{
stab_element_t *current;
if (staticSym!= NULL)
{
for (unsigned i = 0; i < staticSym->stab_size; i++) {
current = staticSym->arr[i];
while(current) {
if(current->stab_content.is_inicialized != 1 &&
current->stab_content.data.data.i == UNINITIALIZED)
{
int type = current->stab_content.data.arg_type;
switch(type)
{
case INTEGER:
case DOUBLE:
case STRING:
// SET it to uninit data
//printf("Reseting %s\n", current->stab_key);
current->stab_content.data.arg_type += 7;
break;
default:
break;
}
}
current = current->stab_next;
}
}
}
}
// Verify if types are compatible
// Allowed conversions:
// type -> same type
// int -> double
// 0 = fail
int implicitConversion(int src, int dest)
{
if(src == dest)
return 1;
// int -> double
if(src == INTEGER && dest == DOUBLE)
return 1;
// the rest is incorrect
return 0;
}
// Return ON_TOP symbol, used in interpret codes to access the top of stack
argument_var_t* getStackTop()
{
// create the symbol just once and return its handle anytime afterwards
static argument_var_t* top = NULL;
if(top)
return top;
data_t stackTop;
stackTop.data.arg_type = ON_TOP;
stackTop.data.data.i = 0;
stackTop.is_inicialized = 1;
data_t* dttop = stable_add_variadic(staticSym,stackTop, 1,"ifj16.on_top");
if(dttop)
top = &dttop->data;
return top;
}
// Generates a STORE operation (assign)
// assign SRC to DEST
// src = if src is NULL, the top of stack is taken into account and POP is generated
void generateStore(data_t* dest, data_t* src)
{
argument_var_t* src_sym = (src != NULL) ? (&src->data) : (getStackTop());
create_and_add_instruction(insProgram, INST_STORE, &dest->data, src_sym, 0);
if(src_sym->arg_type == ON_TOP)
create_and_add_instruction(insProgram, INST_POP,0,0,0);
}
// Generates a code which will call Main.run
void generateIntro()
{
data_t* run = stable_search_variadic(staticSym, 1, "Main.run");
argument_var_t* item = (run != NULL)?(&run->data):NULL;
create_and_add_instruction(insProgram, INST_CALL, item,0,
(argument_var_t*) 0x6);
create_and_add_instruction(insProgram, INST_HALT, 0,0,0);
}
int isSymbolFunction(data_t* sym)
{
if(sym != NULL)
if(sym->data.arg_type == INSTRUCTION)
return 1;
return 0;
}
// Generates a sequence of code which will call either user function
// or built-in one, and clean the stack afterwards
void generateFunctionCall(data_t* func,data_t* retSym)
{
// memory address to receive the return value
argument_var_t* retVal = (retSym != NULL)?(&retSym->data):NULL;
argument_var_t* callType = NULL;
// if VOID function is specified, then throw the return value away after return
if(func->type == VOID)
callType = (argument_var_t*) VOID;
if(!func)
return;
// get the type of called function
switch(func->data.data.i)
{
case BUILTIN_READ:
switch(func->type)
{
case INTEGER:
create_and_add_instruction(insProgram, INST_READ_INT, retVal,0,0);
break;
case DOUBLE:
create_and_add_instruction(insProgram, INST_READ_DOUBLE, retVal,0,0);
break;
case STRING:
create_and_add_instruction(insProgram, INST_READ_STRING, retVal,0,0);
break;
}
break;
case BUILTIN_LEN:
create_and_add_instruction(insProgram, INST_CALL_LEN, retVal,0,0);
break;
case BUILTIN_SUBSTR:
create_and_add_instruction(insProgram, INST_CALL_SUBSTR, retVal,0,0);
break;
case BUILTIN_CMP:
create_and_add_instruction(insProgram, INST_CALL_CMP, retVal,0,0);
break;
case BUILTIN_FIND:
create_and_add_instruction(insProgram, INST_CALL_FIND, retVal,0,0);
break;
case BUILTIN_SORT:
create_and_add_instruction(insProgram, INST_CALL_SORT, retVal,0,0);
break;
default:
create_and_add_instruction(insProgram, INST_CALL, &func->data,retVal,callType);
}
// now generates the stack clean up
data_t* ptrParam = func->next_param;
while(ptrParam)
{
// for each formal parameter in function definition, generate a pop
create_and_add_instruction(insProgram, INST_POP, 0,0,0);
ptrParam = ptrParam->next_param;
}
}
// Sets up a default class symbol data
void fillClassData(data_t* data)
{
data->is_inicialized = 1;
data->type = INTEGER;
data->data.arg_type = INTEGER;
data->data.data.i = PLACEHOLDER_CLASS;
}
// Sets up a default function symbol data
void fillFunctionData(data_t* data,int type)
{
data->is_inicialized = 1;
data->type = type;
data->data.arg_type = INSTRUCTION;
data->data.data.instruction = NULL;
data->next_param = NULL;
}
// Sets up a default static symbol data
void fillStaticVarData(data_t* data,int type)
{
data->type = type;
data->data.arg_type = type;
data->data.data.i = UNINITIALIZED;
data->is_inicialized = 0;
data->next_param = NULL;
}
// Initialize symbol's data if necessary
void inicializeData(data_t* data)
{
if(data->type == STRING)
{
data->data.data.s = str_init();
}
}
// Sets up a default local variable with position 'stackPos' at the stack
void fillLocalVarData(data_t* data,int type, int stackPos)
{
data->is_inicialized = 1;
data->type = type;
data->data.arg_type = STACK_EBP;
data->data.data.i = stackPos;
data->next_param = NULL;
}
// This utility function creates an unique constat in Table of symbols
data_t* createConstant(int type, int iVal, double dVal, char* cVal)
{
static int constNum = 0;
char buffer[255];
// create a new unique symbol name for constant
snprintf(buffer,254,"%d",constNum++);
data_t const_data;
fillStaticVarData(&const_data,type);
const_data.is_inicialized = 1;
switch(type)
{
case INTEGER:
const_data.data.data.i = iVal;
break;
case DOUBLE:
const_data.data.data.d = dVal;
break;
case STRING:
inicializeData(&const_data);
str_append_chars(&const_data.data.data.s, cVal);
break;
}
return stable_add_variadic(staticSym, const_data,2, "ifj16.const", buffer);
}
// Generates an unique label in table of symbols, append it into instruction tape
// and returns a handle
data_t* generateLabel(instruction_list_t* list)
{
static int labelCounter = 0;
instruction_item_t* itemLabel = create_and_add_instruction(list, INST_LABEL, 0,0,0);
data_t dataLbl;
fillFunctionData(&dataLbl,VOID);
dataLbl.data.data.instruction = itemLabel;
char buff[100];
snprintf(buff,99,"%u", labelCounter++);
return stable_add_variadic(staticSym,dataLbl, 3, "ifj16", "labels", buff);
}
// Fill the Table of symbols with signatures of builtin functions and with
// reserved class 'ifj16'
void addBuiltInToTable(stab_t* table)
{
data_t data, *ptr;
// class IFJ16
fillClassData(&data);
stable_add_var(table, "ifj16",data);
// print
fillFunctionData(&data,VOID);
data.data.data.i = BUILTIN_PRINT;
stable_add_variadic(table,data,2,"ifj16","print");
// readInt
fillFunctionData(&data,INTEGER);
data.data.data.i = BUILTIN_READ;
stable_add_variadic(table,data,2,"ifj16","readInt");
// readDouble
fillFunctionData(&data,DOUBLE);
data.data.data.i = BUILTIN_READ;
stable_add_variadic(table,data,2,"ifj16","readDouble");
// readString
fillFunctionData(&data,STRING);
data.data.data.i = BUILTIN_READ;
stable_add_variadic(table,data,2,"ifj16","readString");
// length
fillLocalVarData(&data,STRING, -2);
ptr = stable_add_variadic(table,data,3,"ifj16","length","s");
fillFunctionData(&data,INTEGER);
data.data.data.i = BUILTIN_LEN;
data.next_param = ptr;
stable_add_variadic(table,data,2,"ifj16","length");
// substr
fillLocalVarData(&data,INTEGER, -2);
ptr = stable_add_variadic(table,data,3,"ifj16","substr","n");
fillLocalVarData(&data,INTEGER, -3);
data.next_param = ptr;
ptr = stable_add_variadic(table,data,3,"ifj16","substr","i");
fillLocalVarData(&data,STRING, -4);
data.next_param = ptr;
ptr = stable_add_variadic(table,data,3,"ifj16","substr","s");
fillFunctionData(&data,STRING);
data.next_param = ptr;
data.data.data.i = BUILTIN_SUBSTR;
stable_add_variadic(table,data,2,"ifj16","substr");
//compare
fillLocalVarData(&data,STRING, -2);
ptr = stable_add_variadic(table,data,3,"ifj16","compare","s2");
fillLocalVarData(&data,STRING, -3);
data.next_param = ptr;
ptr = stable_add_variadic(table,data,3,"ifj16","compare","s1");
fillFunctionData(&data,INTEGER);
data.next_param = ptr;
data.data.data.i = BUILTIN_CMP;
stable_add_variadic(table,data,2,"ifj16","compare");
// find
fillLocalVarData(&data,STRING, -2);
ptr = stable_add_variadic(table,data,3,"ifj16","find","s");
fillLocalVarData(&data,STRING, -3);
data.next_param = ptr;
ptr = stable_add_variadic(table,data,3,"ifj16","find","search");
fillFunctionData(&data,INTEGER);
data.next_param = ptr;
data.data.data.i = BUILTIN_FIND;
stable_add_variadic(table,data,2,"ifj16","find");
//sort
fillLocalVarData(&data,STRING, -2);
ptr = stable_add_variadic(table,data,3,"ifj16","sort","s");
fillFunctionData(&data,STRING);
data.next_param = ptr;
data.data.data.i = BUILTIN_SORT;
stable_add_variadic(table,data,2,"ifj16","sort");
}
// A debug utility used to print data type
char* type2str(int type)
{
static char* str[] = {"INTEGER","DOUBLE","STRING",NULL,NULL,NULL,"VOID"};
return str[type];
}
// Set correct stack positions for function formal parameters
// Note: Pascal-like calling convention is utilized in our project. Thus,
// in order to set correct position, one must wait untill all params are
// parsed and then set correct stack offsets to all parameters
void util_correctParamList(data_t* func)
{
data_t* ptr = func->next_param;
if(!ptr)
return;
int offset = 0;
while(ptr)
{
if(ptr->next_param == NULL)
offset = ptr->data.data.i + 2;
ptr = ptr->next_param;
}
ptr = func->next_param;
while(ptr)
{
ptr->data.data.i -= offset;
ptr = ptr->next_param;
}
}
///////////////////////////////////////////////////////////////////////////////
// Parsing functions
///////////////////////////////////////////////////////////////////////////////
/*<expr> -> expression
<expr> -> eps
*/
/*
<type-specifier> -> String
<type-specifier> -> int
<type-specifier> -> double
<type-specifier> -> void
*/
int type_specifier(int* out_type)
{
getToken();
switch(getTokInt())
{
default:
return SYN_ERR;
case KW_INT:
*out_type = INTEGER;
break;
case KW_DOUBLE:
*out_type = DOUBLE;
break;
case KW_STRING:
*out_type = STRING;
break;
}
return SYN_OK;
}
//<more-next> -> expression
//<more-next> -> <identifier> ( <function-parameters-list> )
int more_next(data_t* var)
{
getToken();
int isIdent = isIdentifier();
if(getToken() == TOK_LEFT_PAR && isIdent)
{
ungetToken();
int isPrint = !strcmp(getTokString(),"ifj16.print");
// is it a ID = ifj16.print() case ?
if(isPrint)
{
getToken();
builtin_print();
// NOTE: it's a semantic error in any case, just check out the syntax
error_and_die(RUNTIME_UNINITIALIZED,"Assigned void function to variable.");
} else
{
char* callName = getTokString();
data_t* func = NULL, *data = NULL;
if(isSecondPass)
{
if(getLastToken() == TOK_ID)
func = stable_search_variadic(staticSym, 2, parser_class, getTokString());
else
func = stable_search_variadic(staticSym, 1, getTokString());
if(!func)
error_and_die(SEMANTIC_ERROR,"Function '%s' not found.",getTokString());
// TODO: verify ERROR code in this special case
if(!isSymbolFunction(func))
error_and_die(SEMANTIC_ERROR,"Expecting '%s' to be function", getTokString());
if(implicitConversion(func->type, var->type) == 0)
error_and_die(RUNTIME_UNINITIALIZED,"Function call type dismatch [%s]",callName);
data = func->next_param;
}
getToken();
if(function_arguments_list(&data) == SYN_ERR)
return SYN_ERR;
if(data != NULL)
error_and_die(SEMANTIC_TYPE_ERROR,"Too few arguments in funciton call [%s]",callName);
if(getToken() != TOK_RIGHT_PAR)
error_and_die(SYNTAX_ERROR,"Expected )");
if(isSecondPass)
{
generateFunctionCall(func,var);
}
}
return SYN_OK;
} else {
ungetToken();
ungetToken();
int type = parse_expression(isSecondPass, false);
//GEN("Verify if result of expr can be assigned. If do, generate assign");
if(isSecondPass)
{
if(implicitConversion(type,var->type) == 0)
error_and_die(SEMANTIC_TYPE_ERROR, "Invalid conversion");
generateStore(var, NULL);
}
}
return SYN_OK;
}
// builtin_print is a special case of function call which supports
// a concatenation as an argument
int builtin_print()
{
int paramCount = 0;
if(getToken() == TOK_RIGHT_PAR)
error_and_die(SEMANTIC_TYPE_ERROR,"Expected a term or concatenation");
ungetToken();
do {
data_t* var = NULL;
int res = getToken();
if(isSecondPass)
{
switch(res)
{
case TOK_ID:
var = stable_search_variadic(staticSym, 3, parser_class,parser_fun,getTokString());
if(!var)
var = stable_search_variadic(staticSym, 2, parser_class,getTokString());
if(!var)
error_and_die(SEMANTIC_ERROR, "Undefined variable '%s'",getTokString());
break;
case TOK_SPECIAL_ID:
var = stable_search_variadic(staticSym,1, getTokString());
if(!var)
error_and_die(SEMANTIC_ERROR, "Undefined variable '%s'",getTokString());
break;
case TOK_CONST:
var = createConstant(INTEGER, getTokInt(), 0,NULL);
break;
case TOK_DOUBLECONST:
var = createConstant(DOUBLE, 0, getTokDouble(),NULL);
break;
case TOK_LITERAL:
var = createConstant(STRING, 0, 0,getTokString());
break;
default:
error_and_die(SYNTAX_ERROR,"Expected an identifier or a constant.");
}
if(!var)
error_and_die(INTERNAL_ERROR,"Failed to create constant");
if(var->data.arg_type == INSTRUCTION)
error_and_die(SEMANTIC_ERROR, "Expected variable, got function symbol");
// now generate PUSH
create_and_add_instruction(insProgram, INST_PUSH, &var->data,0,0);
paramCount++;
} else {
switch(res)
{
case TOK_ID:
case TOK_SPECIAL_ID:
case TOK_CONST:
case TOK_DOUBLECONST:
case TOK_LITERAL:
break;
default:
error_and_die(SYNTAX_ERROR,"Expected an identifier or a constant.");
}
}
res = getToken();
if(res == TOK_RIGHT_PAR)
break;
if(res != TOK_PLUS)
error_and_die(SYNTAX_ERROR,"Expected +");
} while (1);
if(isSecondPass)
{
data_t* varCount = createConstant(INTEGER, paramCount, 0,NULL);
create_and_add_instruction(insProgram, INST_CALL_PRINT, &varCount->data,0,0);
while(paramCount-- > 0)
create_and_add_instruction(insProgram,INST_POP, 0,0,0);
}
if(getToken() != TOK_DELIM)
error_and_die(SYNTAX_ERROR,"Expected ;");
return SYN_OK;
}
//<next> -> = <more-next>
//<next> -> ( <function-parameters-list> )
int next(data_t* symbol,char* id)
{
int isPrint = !strcmp(getTokString(),"ifj16.print");
switch(getToken())
{
case TOK_ASSIGN:
if(more_next(symbol) == SYN_ERR)
return SYN_ERR;
if(getToken() != TOK_DELIM)
error_and_die(SYNTAX_ERROR,"Expected ;");
return SYN_OK;
case TOK_LEFT_PAR:
if(isPrint)
{
return builtin_print();
} else {
//GEN("Check if symbol '%s' is defined", getTokString());
if(isSecondPass)
{
if(!isSymbolFunction(symbol))
error_and_die(SEMANTIC_ERROR, "Expected a function symbol.");
}
data_t* dt = NULL;
if(isSecondPass)
dt = symbol->next_param;
if(function_arguments_list(&dt) == SYN_ERR)
return SYN_ERR;
if(dt != NULL)
error_and_die(SEMANTIC_TYPE_ERROR,"Too few arguments in funciton call [%s]",id);
//GEN("Generate a function call INSTR");
if(getToken() != TOK_RIGHT_PAR)
error_and_die(SYNTAX_ERROR,"Expected )");
if(getToken() != TOK_DELIM)
error_and_die(SYNTAX_ERROR,"Expected ;");
if(isSecondPass)
{
generateFunctionCall(symbol,NULL);
}
return SYN_OK;
}
}
error_and_die(SYNTAX_ERROR,"Expected = or (");
return SYN_ERR;
}
//<jump-statement> -> return <expression> ;
int jump_statement()
{
getToken();
if(!isTokenKeyword(KW_RETURN))
error_and_die(SYNTAX_ERROR,"Expected return");
int hasExpression = 1;
if(getToken() == TOK_DELIM)
hasExpression = 0;
ungetToken();
data_t* fn = stable_search_variadic(staticSym, 2, parser_class, parser_fun);
if(isSecondPass)
{
if(!fn)
error_and_die(INTERNAL_ERROR,"Can't get the handle of function");
if(fn->type == VOID && hasExpression)
{
error_and_die(SEMANTIC_TYPE_ERROR, "Void function can't return an expr");
}
if(fn->type != VOID && !hasExpression)
{
error_and_die(SEMANTIC_TYPE_ERROR, "Missing return value");
}
}
int type = 0;
if(hasExpression)
{
type = parse_expression(isSecondPass, false);
}
if(isSecondPass)
{
if(fn->type == VOID)
{
create_and_add_instruction(insProgram,INST_RET, 0,0,0);
} else {
//TODO: use expression
if(implicitConversion(type,fn->type) == 0)
error_and_die(SEMANTIC_TYPE_ERROR, "Invalid conversion");
create_and_add_instruction(insProgram,INST_RET, getStackTop() ,0,0);
}
}
if(getToken() != TOK_DELIM)
error_and_die(SYNTAX_ERROR,"Expected ; at the end of return statement.");
//GEN("Generate RETURN instruction and expression");
return SYN_OK;
}
//<iteration-statement> -> while ( expression ) <statement>
int iteration_statement()
{
instruction_item_t* skipJump = NULL;
data_t* lblTest = NULL;
getToken();
if(!isTokenKeyword(KW_WHILE))
error_and_die(SYNTAX_ERROR,"Expected return");
//GEN("Generate WHILE.test label");
if(isSecondPass)
{
lblTest= generateLabel(insProgram);
}
if(getToken() != TOK_LEFT_PAR)
error_and_die(SYNTAX_ERROR,"Expected (");
parse_expression(isSecondPass, true);
if(getToken() != TOK_RIGHT_PAR)
error_and_die(SYNTAX_ERROR,"Expected )");
if(isSecondPass)
{
skipJump = create_and_add_instruction(insProgram, INST_JZ,0,getStackTop(),0);
create_and_add_instruction(insProgram, INST_POP,0,0,0);
//GEN("Generate COMPARE and JUMP test");
}
if(statement() == SYN_ERR)
return SYN_ERR;
if(isSecondPass)
{
//GEN("Generate WHILE_SKIP label and altern CMP jmp addres");
create_and_add_instruction(insProgram, INST_JMP, &lblTest->data,0,0);
data_t* lblSkip = generateLabel(insProgram);
create_and_add_instruction(insProgram, INST_POP,0,0,0);
// now altern compare to jmp to skip
skipJump->instruction.addr1 = &lblSkip->data;
}
return SYN_OK;
}
//<selection-statement> -> if ( expression ) <statement> __else <statement__
int selection_statement()
{
instruction_item_t* selection = NULL;
instruction_item_t* endJmp = NULL;
data_t* lblElse = NULL;
data_t* lblSkip = NULL;
getToken();
if(isTokenKeyword(KW_IF))
{
if(getToken() != TOK_LEFT_PAR)
error_and_die(SYNTAX_ERROR,"Expected (");
parse_expression(isSecondPass, true);
if(isSecondPass)
{
//GEN("Generate a CMP and JUMP.");
selection = create_and_add_instruction(insProgram, INST_JZ, 0,getStackTop(),0);
create_and_add_instruction(insProgram, INST_POP,0,0,0);
}
if(getToken() != TOK_RIGHT_PAR)
error_and_die(SYNTAX_ERROR,"Expected )");
if(statement() == SYN_ERR)
return SYN_ERR;
if(isSecondPass)
{
//GEN("Generate a JMP.");
// jump to the end of IF-ELSE
endJmp = create_and_add_instruction(insProgram, INST_JMP, 0,0,0);
//GEN("Generate a IF_ELSE label and altern JMP");
lblElse = generateLabel(insProgram);
// altern the jmp after condition to jmp to ELSE branch
selection->instruction.addr1 = &lblElse->data;
create_and_add_instruction(insProgram, INST_POP,0,0,0);
}
getToken();
if(!isTokenKeyword(KW_ELSE))
{
ungetToken();
// its OK, no ELSE
if(isSecondPass)
{
//GEN("Generate a IF_SKIP label and altern JMP.");
lblSkip = generateLabel(insProgram);
// altern JMP after first compound to jmp to the end
endJmp->instruction.addr1 = &lblSkip->data;
}
return SYN_OK;
//error_and_die(SYNTAX_ERROR,"Expected else");
}
if(statement() == SYN_ERR)
return SYN_ERR;
if(isSecondPass)
{
//GEN("Generate a IF_SKIP label and altern JMP.");
lblSkip = generateLabel(insProgram);
// altern JMP after first compound to jmp to the end
endJmp->instruction.addr1 = &lblSkip->data;
}
return SYN_OK;
}
error_and_die(SYNTAX_ERROR,"Expected IF");
return SYN_ERR;
}
//<assign-statement> -> <identifier> <next> ;
int assign_statement()
{
getToken();
if(isIdentifier())
{
char* assign_id = getTokString();
data_t* symbol = NULL;
//GEN("Check if variable '%s' is defined", getTokString());
if(isSecondPass)
{
if(getLastToken() == TOK_ID)
{
symbol = stable_search_variadic(staticSym,3,parser_class,parser_fun,getTokString());
if(!symbol)
symbol = stable_search_variadic(staticSym,2,parser_class,getTokString());
} else {
symbol = stable_search_variadic(staticSym,1,getTokString());
}
if(!symbol)
error_and_die(SEMANTIC_ERROR,"Symbol %s is missing",getTokString());
}
return next(symbol,assign_id);
}
error_and_die(SYNTAX_ERROR,"Expected identifier or full-identifier.");
return SYN_ERR;
}
//<compound-statement> -> { <block-items-list> }
int compound_statement()
{
if(getToken() != TOK_LEFT_BRACE)
error_and_die(SYNTAX_ERROR,"Expected {");
if(block_items_list() == SYN_ERR)
return SYN_ERR;
if(getToken() != TOK_RIGHT_BRACE)
error_and_die(SYNTAX_ERROR,"Expected {");
return SYN_OK;
}
//<block-items-list> -> <block-item> <block-items-list>
//<block-items-list> -> eps
int block_items_list()
{
int type = getToken();
if(type == TOK_EOF)
error_and_die(SYNTAX_ERROR,"Missing }");
if(type == TOK_RIGHT_BRACE)
{
ungetToken();
return SYN_OK;
}
ungetToken();
if(statement() == SYN_ERR)
return SYN_ERR;
return block_items_list();
}
//<statement> -> <jump-statement>
//<statement> -> <iteration-statement>
//<statement> -> <selection-statement>
//<statement> -> <assign-statement>
//<statement> -> <compound-statement>
int statement()
{
int type = getToken();
int val = getTokInt();
ungetToken();
switch(type)
{
case TOK_KEYWORD:
{
switch(val)
{
case KW_RETURN:
return jump_statement();
case KW_IF:
return selection_statement();
case KW_WHILE:
return iteration_statement();
default:
error_and_die(SYNTAX_ERROR,"Got keyword, Expected if, while or return");
}
}
case TOK_ID:
case TOK_SPECIAL_ID:
return assign_statement();
case TOK_LEFT_BRACE:
return compound_statement();
default:
break;