-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.y
More file actions
1026 lines (888 loc) · 31.7 KB
/
Copy pathparser.y
File metadata and controls
1026 lines (888 loc) · 31.7 KB
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
%code requires{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {
marca , // marca comienzo bloque
procedimiento , // si es subprograma (requiere parametros in entradaTS)
variable , // si es variable
parametro_formal , // si es para metro formal
} tipoEntrada ;
typedef enum {
entero ,
real ,
caracter ,
booleano ,
lista, //(requiere dimensiones,and tam_dimension1,tam_dimension2 (depending on if dimensiones is 2 or not) in entradaTS)
desconocido ,
no_asignado,
tipo_error // Para errores semánticos
} dtipo ;
typedef struct {
int atrib ; // Atributo del símbolo (si tiene )
char * lexema ; // Nombre del lexema
int dim;
int tam_dim[2]; // Tamaño de las dimensiones si es lista
dtipo tipo ; // Tipo del sí mbolo
} atributos ;
typedef struct {
tipoEntrada entrada ;
char * nombre ;
dtipo tipoDato ;
unsigned int parametros ;
unsigned int dimensiones ;
int TamDimen1 ;
int TamDimen2 ;
} entradaTS ;
#define YYSTYPE atributos
#define DEBUG_PARSER 0
void insert_var_declaration(const char *name,int dim1, int dim2);
void insert_proced(const char *name);
void insert_proced_param(const char *name, dtipo dt);
void count_params();
void start_call_check(const char *name);
void check_actual_param(dtipo actualType);
void end_call_check();
int process_var(const char *name);
int get_dim(const char *name);
dtipo get_type(const char *name);
int compatible(atributos a, atributos b, int active_error);
void toggle_declaration_mode(int mode);
void var_router(const char *name, int dim1, int dim2, atributos *result);
void get_array_sizes(const char *name, int *dim1, int *dim2);
void insert_array_declaration(const char *name, int dim1, int dim2);
void print_symbol_table();
void define_type(dtipo dt);
void insert_begin_block();
void remove_previous_block();
dtipo check_binary_logical(dtipo tipo1, dtipo tipo2, const char* op);
dtipo check_unary_add(atributos tipo);
dtipo check_unary_not(atributos tipo);
dtipo check_binary_arith(atributos a, atributos b, const char *op);
void binary_arithmetic_router(atributos a,char * op, atributos op_atrib, atributos b, atributos *result);
char* dtipo_to_string(dtipo t);
}
%{
#include <stdio.h>
/* Firmas estándar para conectar con Flex */
int yylex(void);
void yyerror(const char *s);
FILE* leer_archivo(int argc, char *argv[]);
/* Contadores de errores */
int g_syntax_errors = 0;
int g_lex_errors = 0;
int g_sem_errors = 0;
int is_declaration = 0; // Modo declaración activado/desactivado
%}
/* ---- Declaración de tokens ---- */
%token IF THEN ELSE WHILE DO UNTIL
%token NOM_ENTRADA NOM_SALIDA
%token ENTERO REAL BOOLEAN
%token PIZQ PDER CORIZQ CORDER IBLOQ FBLOQ COM PYC DOLLAR
%token TIPO CADENA PROC
%token IDENT
%token ASSIGN
%token AND OR XOR
%token OP_EQ
%token OP_REL
%token OP_ADD
%token OP_MUL
%token NOT
/* Modo de error “verboso”: Bison generará mensajes tipo:
“syntax error, unexpected X, expecting A or B ...” */
%define parse.error verbose
/* Activa información de localización (YYLTYPE y yylloc); Asi podemos saber la linea tanto en lexer.l como en parser.y -> yylineno */
%locations
/* ---- Precedencias ----
THEN < ELSE (por estar %prec THEN en la rama sin ELSE).
*/
%precedence THEN
%precedence ELSE
/* Operadores de menor a mayor precedencia; también resuelven ambigüedades
de expresiones (p.e., + vs *), y definen asociatividad (left/right). */
%left OR
%left XOR
%left AND
%left OP_EQ
%left OP_REL
%left OP_ADD
%left OP_MUL
%right UNARY_PREC /* unarios: +x, ~x (se marcan con %prec UNARY_PREC) */
%%
/* ================= GRAMÁTICA ================ */
programa
: declar_variables_globales declar_de_proceds bloque
;
declar_variables_globales
: variables_globales
| /* vacío */
;
variables_globales
: variables_globales {toggle_declaration_mode(1);} linea_declar {toggle_declaration_mode(0);}
| {toggle_declaration_mode(1);} linea_declar {toggle_declaration_mode(0);}
;
bloque
: IBLOQ {insert_begin_block();} declar_variables_locales sentencias FBLOQ {remove_previous_block();}
;
declar_variables_locales
: variables_locales
| /* vacío */
;
variables_locales
: variables_locales {toggle_declaration_mode(1);}linea_declar {toggle_declaration_mode(0);}
| {toggle_declaration_mode(1);} linea_declar {toggle_declaration_mode(0);}
;
lista_variables
: lista_variables COM ident_var
| lista_variables error ident_var
| ident_var
;
lista_con_tipo
: lista_variables TIPO {define_type($2.atrib); }
| lista_variables error {define_type(tipo_error);}
;
linea_declar
: DOLLAR lista_con_tipo PYC
| DOLLAR lista_con_tipo error
;
declar_de_proceds
: declar_de_proceds declar_proced
| /* vacío */
;
declar_proced
: cabecera_subprog bloque
;
lista_params_opt
: lista_params
| /* vacío */
| error
;
lista_params
: lista_params COM IDENT TIPO {insert_proced_param($3.lexema,$4.atrib);}
| IDENT TIPO {insert_proced_param($1.lexema,$2.atrib);}
;
cabecera_subprog
: PROC IDENT {insert_proced($2.lexema);} PIZQ lista_params_opt PDER {count_params();}
;
sentencias
: sentencias sentencia
| sentencia
;
sentencia
: bloque
| sentencia_if
| sentencia_while
| sentencia_do_until PYC
| sentencia_entrada PYC
| sentencia_salida PYC
| llamada_proced PYC
| sentencia_asignacion PYC
| declar_proced
| error
;
llamada_proced
: IDENT {start_call_check($1.lexema);} PIZQ lista_expresiones_o_cadena PDER {end_call_check();}
;
sentencia_asignacion
: ident_var ASSIGN expresion {compatible($1, $3,1);}
;
sentencia_if
: IF PIZQ expresion PDER THEN sentencia %prec THEN
{if ($3.tipo != desconocido && $3.tipo != booleano) {
fprintf(stderr, "Error semantico (línea %d): La expresión de la sentencia IF debe ser de tipo booleano\n", yylloc.first_line);
g_sem_errors++;
}}
| IF PIZQ expresion PDER THEN sentencia ELSE sentencia
{if ($3.tipo != desconocido && $3.tipo != booleano) {
fprintf(stderr, "Error semantico (línea %d): La expresión de la sentencia IF debe ser de tipo booleano\n", yylloc.first_line);
g_sem_errors++;
}}
;
sentencia_while
: WHILE PIZQ expresion PDER sentencia
{if ($3.tipo != desconocido && $3.tipo != booleano) {
fprintf(stderr, "Error semantico (línea %d): La expresión de la sentencia WHILE debe ser de tipo booleano\n", yylloc.first_line);
g_sem_errors++;
}}
;
sentencia_do_until
: DO bloque UNTIL PIZQ expresion PDER // cambiado por hani, el do debe tener un bloque no un parantesis
;
lista_expresiones_o_cadena
: lista_expresiones_o_cadena COM expresion_o_cadena
| expresion_o_cadena
;
expresion_o_cadena
: expresion { check_actual_param($1.tipo);}
| CADENA {check_actual_param(caracter);}
;
sentencia_entrada
: NOM_ENTRADA lista_variables // Tendremos que usar otra regla semantica porque no tienen la misma funcionalidad
;
sentencia_salida
: NOM_SALIDA lista_expresiones_o_cadena
;
ident_var
: IDENT {var_router($1.lexema,-1,-1,&$$);}
| IDENT CORIZQ ENTERO CORDER {var_router($1.lexema,$3.atrib,-1,&$$);}
| IDENT CORIZQ ENTERO CORDER CORIZQ ENTERO CORDER {var_router($1.lexema,$3.atrib,$6.atrib,&$$);}
;
expresion
: PIZQ expresion PDER
{
$$.tipo = $2.tipo;
$$.dim = $2.dim;
$$.tam_dim[0] = $2.tam_dim[0];
$$.tam_dim[1] = $2.tam_dim[1];
}
| OP_ADD expresion %prec UNARY_PREC
{
$$.tipo = check_unary_add($2);
$$.dim = $2.dim;
$$.tam_dim[0] = $2.tam_dim[0];
$$.tam_dim[1] = $2.tam_dim[1];
}
| NOT expresion %prec UNARY_PREC
{
$$.tipo = check_unary_not($2);
$$.dim = $2.dim;
$$.tam_dim[0] = $2.tam_dim[0];
$$.tam_dim[1] = $2.tam_dim[1];
}
| expresion OP_MUL expresion
{ binary_arithmetic_router($1,"OP_MUL",$2,$3,&$$); }
| expresion OP_ADD expresion
{ binary_arithmetic_router($1,"OP_ADD",$2,$3,&$$); }
| expresion OP_REL expresion
{ check_binary_arith($1, $3, "<>"); $$.dim = 0; $$.tipo = booleano; }
| expresion OP_EQ expresion
{ check_binary_arith($1, $3, "=="); $$.dim = 0; $$.tipo = booleano; }
| expresion AND expresion { $$.tipo = check_binary_logical($1.tipo, $3.tipo, "AND"); $$.dim = 0; }
| expresion XOR expresion { $$.tipo = check_binary_logical($1.tipo, $3.tipo, "XOR"); $$.dim = 0; }
| expresion OR expresion { $$.tipo = check_binary_logical($1.tipo, $3.tipo, "OR"); $$.dim = 0; }
| ident_var {$$ = $1;}
| ENTERO { $$.tipo = entero; $$.dim = 0; }
| BOOLEAN{ $$.tipo = booleano; $$.dim = 0; }
| REAL {$$.tipo = real; $$.dim = 0;}
| error
;
%%
/* ================= C ================ */
#define MAX_TS 500
unsigned int TOPE = 0 ; // Tope de la pila
unsigned int Subprog ; // Indicador de comienzo de bloque de un subprog
unsigned int nParam = 0; /* nº de parámetros del proc actual */
int checking_call = 0; /* 1 si estamos comprobando una llamada */
int current_proc_index = -1;
int call_arg_index = 0;
entradaTS TS[ MAX_TS ] ; // Pila de la tabla de sí mbolos
// A partir de ahora , cada símbolo tiene
// una estructura de tipo atributos
int is_declared(const char *name, int unique_in_block){ // 0 if not, 1 if declared
for(int i = TOPE - 1; i >= 0; i--){ //RESTAR PARA MÁS COMPORTAMIENTO DE PILA
//for(unsigned int i=0; i<TOPE; i++){
if(TS[i].entrada == marca && unique_in_block){
break;
}
if(TS[i].nombre != NULL && strcmp(TS[i].nombre, name) == 0){
return 1;
}
}
return 0;
}
void toggle_declaration_mode(int mode){
is_declaration = mode;
}
void var_router(const char *name, int dim1, int dim2, atributos *result){
result->lexema = strdup(name);
if(is_declaration){
// Declaration mode: set dimensions based on syntax
result->dim = (dim1 > 0 ? 1 : 0) + (dim2 > 0 ? 1 : 0);
result->tam_dim[0] = (dim1 > 0 ? dim1 : 0);
result->tam_dim[1] = (dim2 > 0 ? dim2 : 0);
insert_var_declaration(name, dim1, dim2);
// Type will be assigned later by define_type()
result->tipo = no_asignado;
} else {
// Access mode: reduce dimensions based on indexing
process_var(name);
int original_dim = get_dim(name);
int accessed_dims = (dim1 >= 0 ? 1 : 0) + (dim2 >= 0 ? 1 : 0);
// Validate array access
if (original_dim == 0 && accessed_dims > 0) {
fprintf(stderr, "Error semantico (línea %d): Variable '%s' no es un array\n",
yylloc.first_line, name);
g_sem_errors++;
} else if (accessed_dims > original_dim) {
fprintf(stderr, "Error semantico (línea %d): Demasiados índices para variable '%s' (tiene %d dimensiones, se acceden %d)\n",
yylloc.first_line, name, original_dim, accessed_dims);
g_sem_errors++;
}
// Calculate resulting dimension
result->dim = original_dim - accessed_dims;
result->tipo = get_type(name);
// Get original array sizes
int orig_size1, orig_size2;
get_array_sizes(name, &orig_size1, &orig_size2);
if (result->dim == original_dim) {
// No indexing: copy full size
result->tam_dim[0] = orig_size1;
result->tam_dim[1] = orig_size2;
}
else if (original_dim == 2 && accessed_dims == 1) {
// a[i] of 2D => 1D array with size = second dimension
result->tam_dim[0] = orig_size2;
result->tam_dim[1] = 0;
}
else {
// scalar or indexing reduces array to scalar
result->tam_dim[0] = 0;
result->tam_dim[1] = 0;
}
}
}
int is_numeric_type(dtipo t){
return (t == entero || t == real);
}
void arithmetic_sum_mul(atributos a, atributos b,atributos *result) {
/* printf("Arithmetic sum/mul called with types %d and %d, dims %d and %d and sizes [%d,%d] and [%d,%d]\n", a.tipo, b.tipo, a.dim, b.dim, a.tam_dim[0], a.tam_dim[1], b.tam_dim[0], b.tam_dim[1]); */
if (a.tipo == b.tipo && is_numeric_type(b.tipo) ) {
result->tipo = a.tipo;
if(a.dim > b.dim && b.dim == 0)
{
result->dim = a.dim;
result->tam_dim[0] = a.tam_dim[0];
result->tam_dim[1] = a.tam_dim[1];
}
else if ((a.dim < b.dim && a.dim == 0))
{
result->dim = b.dim;
result->tam_dim[0] = b.tam_dim[0];
result->tam_dim[1] = b.tam_dim[1];
}
else if (a.dim == b.dim)
{
if (a.tam_dim[0] != b.tam_dim[0] || a.tam_dim[1] != b.tam_dim[1]) {
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): No se puede hacer la operación con tamaños/dimensiones de listas incompatibles %s : (%d,%d) y %s (%d,%d)\n", yylloc.first_line, dtipo_to_string(a.tipo), a.tam_dim[0], a.tam_dim[1],dtipo_to_string(a.tipo), b.tam_dim[0], b.tam_dim[1]);
g_sem_errors++;
return;
}
result->dim = b.dim;
result->tam_dim[0] = b.tam_dim[0];
result->tam_dim[1] = b.tam_dim[1];
}
else
{
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): No se puede hacer la operación con tamaños/dimensiones de listas incompatibles %s : (%d,%d) y %s (%d,%d)\n", yylloc.first_line, dtipo_to_string(a.tipo), a.tam_dim[0], a.tam_dim[1],dtipo_to_string(a.tipo), b.tam_dim[0], b.tam_dim[1]);
g_sem_errors++;
}
}
else {
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): Tipos incompatibles para suma/arithmetic_sum\n", yylloc.first_line);
g_sem_errors++;
}
}
void arithmetic_min_div(atributos a,atributos b, atributos *result) {
if (a.tipo == b.tipo && is_numeric_type(b.tipo) ) {
result->tipo = a.tipo;
if(a.dim > b.dim && b.dim == 0)
{
result->dim = a.dim;
result->tam_dim[0] = a.tam_dim[0];
result->tam_dim[1] = a.tam_dim[1];
}
else if ((a.dim < b.dim && a.dim == 0))
{
result->dim = b.dim;
result->tam_dim[0] = b.tam_dim[0];
result->tam_dim[1] = b.tam_dim[1];
}
else if (a.dim == b.dim)
{
if (a.tam_dim[0] != b.tam_dim[0] || a.tam_dim[1] != b.tam_dim[1]) {
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): No se puede hacer la operación con tamaños/dimensiones de listas incompatibles %s : (%d,%d) y %s (%d,%d)\n", yylloc.first_line, dtipo_to_string(a.tipo), a.tam_dim[0], a.tam_dim[1],dtipo_to_string(a.tipo), b.tam_dim[0], b.tam_dim[1]);
g_sem_errors++;
return;
}
result->dim = b.dim;
result->tam_dim[0] = b.tam_dim[0];
result->tam_dim[1] = b.tam_dim[1];
}
else{
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): No se puede restar una lista de un valor\n", yylloc.first_line);
g_sem_errors++;
}
}
else {
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): Tipos incompatibles para resta/arithmetic_subtraction\n", yylloc.first_line);
g_sem_errors++;
}
}
void arithmetic_mat_mul(atributos a, atributos b, atributos *result) {
if (a.tipo == b.tipo && is_numeric_type(b.tipo) ) {
if(a.dim == 2 && b.dim ==2)
{
if(a.tam_dim[1] == b.tam_dim[0])
{
result->tipo = a.tipo;
result->dim = 2;
result->tam_dim[0] = a.tam_dim[0];
result->tam_dim[1] = b.tam_dim[1];
}
else
{
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): Dimensiones incompatibles para multiplicación de matrices ( [x][%d] ** [%d][y] )\n", yylloc.first_line, a.tam_dim[1], b.tam_dim[0]);
g_sem_errors++;
}
}
else
{
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): Ambos operandos deben ser matrices para multiplicación de matrices\n", yylloc.first_line);
g_sem_errors++;
}
}
else {
result->tipo = desconocido; // No puede haber mezclas
fprintf(stderr, "Error semantico (línea %d): Tipos incompatibles para multiplicación de matrices\n", yylloc.first_line);
g_sem_errors++;
}
}
void binary_arithmetic_router(atributos a,char * op, atributos op_atrib, atributos b, atributos *result) {
// op_mul.atrib 0 : *, 1: /, 2: mat_mul (**)
// op_add.atrib 0: +, 1: -
// op_rel.atrib 0: <=, 1: >=, 2: <, 3: >
// op_eq.atrib 0: ==, 1: !=
// Determine operation type based on operator
if (strcmp(op, "OP_MUL") == 0) {
if (op_atrib.atrib == 0) { // Multiplication
arithmetic_sum_mul(a, b, result);
}
else if (op_atrib.atrib == 1) { // Division
arithmetic_min_div(a, b, result);
}
else if (op_atrib.atrib == 2) { // Matrix Multiplication
arithmetic_mat_mul(a, b, result);
}
}
else if (strcmp(op, "OP_ADD") == 0) {
if (op_atrib.atrib == 0) { // Addition
arithmetic_sum_mul(a, b, result);
}
else if (op_atrib.atrib == 1) { // Subtraction
arithmetic_min_div(a, b, result);
}
}
}
int process_var(const char *name){
// Primero, tenemos que ver si esta declarada.
if (!is_declared(name, 0)){
fprintf(stderr, "Error semantico (línea %d): Variable '%s' no declarada\n", yylloc.first_line, name);
g_sem_errors++;
return 1;
}
for(int i = TOPE - 1; i >= 0; i--){
if(TS[i].nombre != NULL && strcmp(TS[i].nombre, name) == 0 &&
(TS[i].entrada == variable || TS[i].entrada == parametro_formal)){
yylval.tipo = TS[i].tipoDato; // Realmente esto no hace nada ni sirve para nada.
break;
}
}
// Despues tendremos que asignar algunos atributos por ejemplo para la expresion etc. pero mas adelante
return 0;
}
int compatible(atributos a, atributos b, int active_error){
if(a.tipo == b.tipo && a.dim == b.dim){
if (a.tam_dim[0] != b.tam_dim[0] || a.tam_dim[1] != b.tam_dim[1]) {
if (active_error) {
fprintf(stderr, "Error semantico (línea %d): No se puede asignar: tamaños/dimensiones incompatibles (%d,%d) y (%d,%d)\n", yylloc.first_line, a.tam_dim[0], a.tam_dim[1], b.tam_dim[0], b.tam_dim[1]);
g_sem_errors++;
}
return 0;
}
return 1;
}
else if (active_error) {
fprintf(stderr, "Error semantico (línea %d): Tipos o dimensiones incompatibles para asignacion (%s , %s), (%d , %d)\n", yylloc.first_line, dtipo_to_string(a.tipo), dtipo_to_string(b.tipo), a.dim, b.dim);
g_sem_errors++;
}
return 0;
}
void insert_ts(tipoEntrada tE, char *nombre, dtipo dt, unsigned int parameters,
unsigned int dimensiones, int TamDimen1, int TamDimen2) {
// printf("asdf");
// Check if table is full
if (TOPE >= MAX_TS) {
fprintf(stderr, "Error: Tabla de símbolos llena\n");
return;
}
//printf("TOPE: %d\n", TOPE);
// Create entry
TS[TOPE].entrada = tE;
TS[TOPE].nombre = (nombre != NULL) ? strdup(nombre) : NULL;
TS[TOPE].tipoDato = dt;
TS[TOPE].parametros = 0;
TS[TOPE].dimensiones = dimensiones;
TS[TOPE].TamDimen1 = TamDimen1;
TS[TOPE].TamDimen2 = TamDimen2;
// Set fields based on tipoEntrada
switch (tE) {
case procedimiento:
// Procedures require 'parametros' field
TS[TOPE].parametros = parameters;
break;
case variable:
case parametro_formal:
// Variables can be lists (arrays)
if (dt == lista) {
TS[TOPE].dimensiones = dimensiones;
if (dimensiones >= 1) {
TS[TOPE].TamDimen1 = TamDimen1;
}
if (dimensiones == 2) {
TS[TOPE].TamDimen2 = TamDimen2;
}
}
break;
case marca:
// Marca doesn't need any additional fields
break;
}
TOPE++;
print_symbol_table();
}
void insert_proced(const char *name){ // Same with the one below.
//¿Atoi parameters? ¿Debería contar el número de parametros?
// Needs to be updated lol
if (is_declared(name, 1)){ // Podemos cambiarla para que sea 0.
fprintf(stderr, "Error semantico (línea %d): Procedimiento '%s' ya declarado en este bloque\n", yylloc.first_line, name);
g_sem_errors++;
return;
}
insert_ts(procedimiento, (char *)name, desconocido, 0, 0, 0, 0);
}
void insert_proced_param(const char *name, dtipo dt){
// Tiene que comparar solo con los parámetros formales del procedimiento actual.
/* if(is_declared(name, 1)){
fprintf(stderr, "Error: Parámetro formal '%s' ya declarado\n", name);
return;
} */
insert_ts(parametro_formal, (char*)name, dt, 0, 0, 0, 0);
}
void count_params(){
// Counts the number of parameters for the last inserted procedure
if (TOPE == 0) {
fprintf(stderr, "Error semantico (línea %d): Tabla de símbolos vacía al contar parámetros\n", yylloc.first_line);
g_sem_errors++;
return;
}
int count = 0;
for (int i = TOPE - 1; i >= 0; i--) {
if (TS[i].entrada == procedimiento) {
TS[i].parametros = count;
break;
}
if (TS[i].entrada == parametro_formal) {
count++;
}
}
}
int lookup_symbol(const char *name) {
if (!name) return -1;
for (int i = (int)TOPE - 1; i >= 0; --i) {
if (TS[i].nombre && strcmp(TS[i].nombre, name) == 0) {
return i;
}
}
return -1;
}
void get_array_sizes(const char *name, int *dim1, int *dim2){
int idx = lookup_symbol(name);
if (idx < 0) {
*dim1 = 0;
*dim2 = 0;
return;
}
*dim1 = TS[idx].TamDimen1;
*dim2 = TS[idx].TamDimen2;
}
void start_call_check(const char *name) {
checking_call = 0;
current_proc_index = -1;
call_arg_index = 0;
int idx = lookup_symbol(name);
if (idx < 0) {
printf("Error semantico (línea %d): Identificador '%s' no declarado o fuera de su ambito\n", yylloc.first_line, name);
g_sem_errors++;
return;
}
if (TS[idx].entrada != procedimiento) {
printf("Error semantico (línea %d): Identificador '%s' no es un procedimiento\n", yylloc.first_line, name);
g_sem_errors++;
return;
}
checking_call = 1;
current_proc_index = idx;
call_arg_index = 0;
}
void check_actual_param(dtipo actualType) {
if (!checking_call || current_proc_index < 0) return;
unsigned int nformals = TS[current_proc_index].parametros;
if ((unsigned int)call_arg_index >= nformals) {
/* Demasiados parámetros */
printf("Error semantico (línea %d): Demasiados parámetros en llamada a procedimiento '%s', ( esperado %u, obtenido %u )\n",
yylloc.first_line, TS[current_proc_index].nombre, nformals, call_arg_index + 1);
g_sem_errors++;
return;
}
unsigned int formal_idx = current_proc_index + 1 + call_arg_index;
dtipo formalType = TS[formal_idx].tipoDato;
if (formalType != desconocido && actualType != desconocido &&
formalType != actualType) {
printf("Error semantico (línea %d): Tipo de parámetro %d en llamada a procedimiento '%s' "
"no coincide (esperado %s, obtenido %s)\n",
yylloc.first_line,
call_arg_index + 1,
TS[current_proc_index].nombre,
dtipo_to_string(formalType),
dtipo_to_string(actualType)
);
g_sem_errors++;
}
call_arg_index++;
}
void end_call_check() {
if (!checking_call || current_proc_index < 0) return;
unsigned int nformals = TS[current_proc_index].parametros;
if ((unsigned int)call_arg_index < nformals) {
printf("Error semantico (línea %d): Llamada a procedimiento '%s' con menos argumentos (%d) de los esperados (%u)\n",
yylloc.first_line, TS[current_proc_index].nombre, call_arg_index, nformals);
g_sem_errors++;
}
checking_call = 0;
current_proc_index = -1;
call_arg_index = 0;
}
void insert_var_declaration(const char *name,int dim1, int dim2){ // I don't know if I should have the parameter as the name or somehow the lexema from the attribute.
if(is_declared(name, 1)){
fprintf(stderr, "Error semantico (línea %d): Variable '%s' ya declarada en este bloque\n", yylloc.first_line, name);
g_sem_errors++;
return;
}
for (int i = TOPE -1; i >= 0; i--) {
if (TS[i].entrada == procedimiento) {
break;
}
else if (TS[i].entrada == parametro_formal) {
if (strcmp(TS[i].nombre, name) == 0) {
fprintf(stderr, "Error semantico (línea %d): Variable '%s' ya declarada en la cabecera del subprograma\n", yylloc.first_line, name);
g_sem_errors++;
return;
}
}
}
int dims = (dim1 > 0 ? 1: 0) + (dim2 > 0 ? 1 : 0);
dim1 = (dim1 > 0 ? dim1 : 0);
dim2 = (dim2 > 0 ? dim2 : 0);
insert_ts(variable, (char*)name, no_asignado, 0, dims, dim1, dim2);
}
int get_dim(const char *name){
int idx = lookup_symbol(name);
if (idx < 0) {
return -1;
}
return TS[idx].dimensiones;
}
dtipo get_type(const char *name){
int idx = lookup_symbol(name);
if (idx < 0) {
return desconocido;
}
return TS[idx].tipoDato;
}
void define_type(dtipo dt){
// Assigns a type for the previously declared variables that have type as no_asignado (like ) $ a,b,c,d int
if (dt == tipo_error) {
fprintf(stderr, "Error semantico (línea %d): No se ha especificado tipo de la lista de variables\n", yylloc.first_line);
g_sem_errors++;
}
for(int i = (int)TOPE - 1; i >= 0 && TS[i].entrada != marca; i--){
if(TS[i].tipoDato == no_asignado){
TS[i].tipoDato = dt;
}
}
print_symbol_table();
}
void insert_begin_block(){
// Inserts a mark to indicate the beginning of a new block
if (TOPE >= MAX_TS) {
fprintf(stderr, "Error: Tabla de símbolos llena\n");
return;
}
insert_ts(marca, NULL, desconocido, 0, 0, 0, 0);
}
//NUEVO
void remove_previous_block() {
if (TOPE == 0) {
return;
}
// Primero se busca la última marca
int ultima_marca = -1;
for (int i = TOPE - 1; i >= 0; i--) {
if (TS[i].entrada == marca) {
ultima_marca = i;
break;
}
}
// Si no se encuentra ninguna marca, no hay bloque que eliminar
if (ultima_marca == -1) {
return;
}
// Se liberan las entradas del bloque
for (unsigned int i = ultima_marca + 1; i < TOPE; i++) {
if (TS[i].nombre != NULL) {
free(TS[i].nombre);
TS[i].nombre = NULL;
}
}
// Ajustar el TOPE
TOPE = ultima_marca;
print_symbol_table();
}
void remove_ts(){
if (TOPE == 0) {
fprintf(stderr, "Error: Tabla de símbolos vacía\n");
return;
}
TOPE--;
}
void print_symbol_table() {
if (!DEBUG_PARSER) return;
printf("\n=== TABLA DE SÍMBOLOS ===\n");
printf("TOPE: %u\n", TOPE);
for (unsigned int i = 0; i < TOPE; i++) {
printf("[%u] ", i);
switch (TS[i].entrada) {
case marca:
printf("MARCA\n");
break;
case procedimiento:
printf("PROC: %s (params: %u)\n",
TS[i].nombre ? TS[i].nombre : "NULL",
TS[i].parametros);
break;
case variable:
printf("VAR: %s (tipo: %d, dims: %u, dim1: %u, dim2: %u)\n",
TS[i].nombre ? TS[i].nombre : "NULL",
TS[i].tipoDato,
TS[i].dimensiones,
TS[i].TamDimen1,
TS[i].TamDimen2);
break;
case parametro_formal:
printf("PARAM: %s (tipo: %d)\n",
TS[i].nombre ? TS[i].nombre : "NULL",
TS[i].tipoDato);
break;
}
}
printf("=========================\n\n");
}
void yyerror(const char *s) {
g_syntax_errors++;
fprintf(stderr, "Error sintáctico (línea %d): %s\n", yylloc.first_line, s);
}
FILE* leer_archivo(int argc, char *argv[]) {
FILE *f = NULL;
if (argc > 1) {
f = fopen(argv[1], "r");
if (!f) {
fprintf(stderr, "Error: Archivo '%s' no encontrado\n", argv[1]);
exit(1);
} else {
printf("\nLeyendo fichero '%s'\n", argv[1]);
}
} else {
printf("\nLeyendo entrada standard.\n");
}
return f;
}
dtipo check_binary_logical(dtipo tipo1, dtipo tipo2, const char* op) {
if (tipo1 == booleano && tipo2 == booleano) {
return booleano;
} else {
fprintf(stderr, "Error semántico (línea %d): Operación '%s' requiere operandos booleanos\n",
yylloc.first_line, op);
g_sem_errors++;
return desconocido;
}
}
dtipo check_unary_add(atributos a){
dtipo tipo = a.tipo;
if(a.dim == 0 && (tipo == entero || tipo == real)){
return tipo;
} else {
fprintf(stderr, "Error semantico (línea %d): Las operaciones unarias requieren operando numérico no un ( %s ) \n", yylloc.first_line, dtipo_to_string(a.tipo));
g_sem_errors++;
return desconocido;
}
}
dtipo check_unary_not(atributos a){
dtipo tipo = a.tipo;
if(a.dim == 0 && tipo == booleano){
return tipo;
} else {
fprintf(stderr, "Error semantico (línea %d): La operación NOT requiere operando booleano no un ( %s )\n", yylloc.first_line, dtipo_to_string(a.tipo));
g_sem_errors++;
return desconocido;
}
}
dtipo check_binary_arith(atributos a, atributos b, const char *op) {
if (compatible(a,b,0) && is_numeric_type(a.tipo) ) {
if (a.tipo == real) return real;
return entero;
} else {
fprintf(stderr, "Error semantico (línea %d): Operación '%s' requiere operandos numéricos no ( %s, %s )\n", yylloc.first_line, op, dtipo_to_string(a.tipo), dtipo_to_string(b.tipo));
g_sem_errors++;
return desconocido;
}
}
char *dtipo_to_string(dtipo t){
switch(t){
case entero: return "entero";
case real: return "real";
case caracter: return "caracter";
case booleano: return "booleano";
case lista: return "lista";
case desconocido: return "desconocido";