-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
1419 lines (1099 loc) · 38.3 KB
/
Copy pathMain.java
File metadata and controls
1419 lines (1099 loc) · 38.3 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
import core.all.Tuple;
import core.intermediate.Assembly;
import core.intermediate.TresDirCode;
import core.symbol.Symbol;
import core.symbol.SymbolTable;
import java_cup.runtime.ComplexSymbolFactory;
import java_cup.runtime.ComplexSymbolFactory.ComplexSymbol;
import java_cup.runtime.SymbolFactory;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
interface Expr {
Object run(HashMap<String, Object> hm);
String generateCode(c3Direcciones codeGen);
}
interface Condition {
boolean test(Expr e1, Expr e2, HashMap<String, Object> hm);
}
interface Operator {
int count(Expr e1, Expr e2, HashMap<String, Object> hm);
}
interface SimpleInstruction {
void run(HashMap<String, Object> hm);
}
interface WhileInstructionI extends SimpleInstruction {
void run(HashMap<String, Object> hm);
}
interface IfInstructionI extends SimpleInstruction {
void run(HashMap<String, Object> hm);
}
public class Main {
private HashMap<String, Object> hm = new HashMap<>();
private MainInstructionList instructionList;
public Main(MainInstructionList instructionList) {
this.instructionList = instructionList;
}
public void exec() {
instructionList.run(hm);
}
static public void main(String argv[]) {
try {
long tInicio = System.currentTimeMillis();
Lexer l = new Lexer(new FileReader(argv[0]));
long tFin = System.currentTimeMillis();
System.out.println("Tiempo de ejecución del lexer: " + (tFin - tInicio) + " milisegundos");
SymbolFactory sf = new ComplexSymbolFactory();
parser p = new parser(l, sf);
Object result = p.parse().value;
// Guardar los tokens en un archivo
saveTokensFile(l.tokens);
// Guardar la tabla de símbolos en un archivo
saveSymbolTableFile(p.getSymbolTable());
//Back-end
TresDirCode tresDirCode = new TresDirCode();
Assembly assembly = new Assembly(tresDirCode, p.getSymbolTable());
if (result instanceof Main) {
((Main) result).exec();
} else {
System.err.println("Error: El parser no devolvió una instancia válida de Main.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Metodo para guardar la tabla de simbolos en un archivo
@SuppressWarnings("unused")
private static void saveSymbolTableFile(SymbolTable symbolTable) {
symbolTable.writeToFile("symbolTable.txt");
}
// Método para guardar los tokens en un archivo
private static void saveTokensFile(ArrayList<ComplexSymbol> tokens) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("TokensFitxer.txt"));
for (int i = 0; i < tokens.size(); i++) {
writer.write(tokens.get(i).getName() + "\n");
}
writer.close();
} catch (IOException err) {
System.out.println(err);
}
}
}
class FileOutputInstruction implements SimpleInstruction {
Expr file, content;
public FileOutputInstruction(Expr s, Expr s2) {
this.file = s;
this.content = s2;
}
public void run(HashMap<String, Object> hm) {
Object fileoutput = file.run(hm);
Object contentoutput = content.run(hm);
if (fileoutput instanceof String && contentoutput instanceof String) {
int unused = writeToFile((String) fileoutput, (String) contentoutput);
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
}
}
private int writeToFile(String fileName, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
writer.write(content);
writer.newLine();
return content.getBytes(StandardCharsets.UTF_8).length + System.lineSeparator().getBytes(StandardCharsets.UTF_8).length;
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
System.exit(1);
return -1;
}
}
}
class TupleExpression implements Expr {
Expr e1, e2;
public TupleExpression(Expr e1, Expr e2) {
this.e1 = e1;
this.e2 = e2;
}
public Object run(HashMap<String, Object> hm) {
Object value1 = e1.run(hm);
Object value2 = e2.run(hm);
return new Tuple(Arrays.asList(value1, value2)); // Crea una lista de los valores
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Genera el código intermedio para las dos expresiones
String temp1 = e1.generateCode(codeGen);
String temp2 = e2.generateCode(codeGen);
// Crear un temporal para la tupla
String tupleTemp = codeGen.newTemp();
// Generar la instrucción que define la tupla
codeGen.addInstruction("TUPLE", temp1, temp2, tupleTemp);
// Retornar el temporal que contiene la tupla
return tupleTemp;
}
}
class ConstIntExpression extends IntExpression {
private final int value;
public ConstIntExpression(int value) {
super(value);
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return Integer.toString(value);
}
}
class ConstStringExpression extends StringExpression {
private final String value;
public ConstStringExpression(String value) {
super(value);
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "\"" + value + "\"";
}
}
class ConstBooleanExpression extends BooleanExpression {
private final boolean value;
public ConstBooleanExpression(boolean value) {
super(value, true); // El segundo argumento indica que es una constante
this.value = value;
}
public boolean getValue() {
return value;
}
@Override
public String toString() {
return Boolean.toString(value);
}
}
/**
* VARS
*/
class ID implements Expr {
String name;
public ID(String s) {
name = s;
}
public String getName() {
return name;
}
public Object run(HashMap<String, Object> hm) {
return hm.get(name);
}
public String generateCode(c3Direcciones codeGen) {
return name; // El nombre de la variable es el código intermedio en este caso.
}
}
class AssignInstruction implements SimpleInstruction {
String name;
Expr val;
public AssignInstruction(String i, Expr e) {
name = i;
val = e;
}
public void run(HashMap<String, Object> hm) {
hm.put(name, val.run(hm));
}
public void generateCode(TresDirCode codeGen) {
String result = name;
}
}
class FunctionCallInstruction implements SimpleInstruction {
private String functionName;
private List<Object> arguments; // Argumentos para la llamada
public FunctionCallInstruction(String functionName, List<Object> arguments) {
this.functionName = functionName;
this.arguments = arguments;
}
@Override
public void run(HashMap<String, Object> hm) {
// Acceder a la tabla de símbolos global
SymbolTable symbolTable = SymbolTable.getInstance();
if (symbolTable == null) {
System.err.println("SymbolTable not found.");
return;
}
// Buscar la función en la tabla de símbolos
Symbol functionSymbol = symbolTable.get(functionName);
if (functionSymbol == null) {
System.err.println("Function " + functionName + " not found.");
return;
}
// Obtener la lista de parámetros de la función
List<String> params = functionSymbol.getParams();
if (params.size() != arguments.size()) {
System.err.println("Argument count mismatch for function: " + functionName);
return;
}
// Crear un nuevo contexto de ejecución para esta función
HashMap<String, Object> localContext = new HashMap<>(hm);
// Asignar los valores de los parámetros a las variables locales
for (int i = 0; i < params.size(); i++) {
localContext.put(params.get(i), arguments.get(i));
}
// Ejecutar las instrucciones de la función
InstructionList functionInstructions = (InstructionList) functionSymbol.getValue();
functionInstructions.run(localContext);
}
}
/**
* OPERATORS
*/
class PlusOperator implements Operator {
public int count(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 + (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String toString() {
return "PLUS";
}
}
class TimesOperator implements Operator {
public int count(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 * (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String toString() {
return "TIMES";
}
}
class MinusOperator implements Operator {
public int count(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 - (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String toString() {
return "MINUS";
}
}
class DivideOperator implements Operator {
public int count(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
if ((Integer) v2 == 0) {
System.out.println("Error: division by zero");
System.exit(1);
}
return (Integer) v1 / (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String toString() {
return "DIVIDE";
}
}
class ModeOperator implements Operator {
public int count(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
if ((Integer) v2 == 0) {
System.out.println("Error: division by zero");
System.exit(1);
}
return (Integer) v1 % (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String toString() {
return "MODE";
}
}
class PreIncrementExpression implements Expr {
Expr e;
public PreIncrementExpression(Expr e) {
this.e = e;
}
public Object run(HashMap<String, Object> hm) {
Object v = e.run(hm);
if (v instanceof Integer) {
return ((Integer) v) + 1;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Generamos un nuevo temporal para la expresión
String temp = codeGen.newTemp();
// Obtenemos el código intermedio de la expresión e
String exprCode = e.generateCode(codeGen);
// Cargamos el valor de la expresión en el temporal
codeGen.addInstruction("LOAD", exprCode, "", temp); // Cargamos el valor en un temporal
// Incrementamos el valor del temporal
String incrementedTemp = codeGen.newTemp();
codeGen.addInstruction("ADD", temp, "1", incrementedTemp); // Incremento de 1
// Almacenamos el valor incrementado de vuelta en la variable o temporal
codeGen.addInstruction("STORE", incrementedTemp, "", exprCode); // Guardamos el nuevo valor
return exprCode; // Retornamos el nombre de la variable o temporal actualizado
}
}
class PreDecrementExpression implements Expr {
Expr e;
public PreDecrementExpression(Expr e) {
this.e = e;
}
public Object run(HashMap<String, Object> hm) {
Object v = e.run(hm);
if (v instanceof Integer) {
return ((Integer) v) - 1;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Generamos un nuevo temporal para la expresión
String temp = codeGen.newTemp();
// Obtenemos el código intermedio de la expresión e
String exprCode = e.generateCode(codeGen);
// Cargamos el valor de la expresión en el temporal
codeGen.addInstruction("LOAD", exprCode, "", temp); // Cargamos el valor en un temporal
// Decrementamos el valor del temporal
String decrementedTemp = codeGen.newTemp();
codeGen.addInstruction("SUB", temp, "1", decrementedTemp); // Decremento de 1
// Almacenamos el valor decrementado de vuelta en la variable o temporal
codeGen.addInstruction("STORE", decrementedTemp, "", exprCode); // Guardamos el nuevo valor
return exprCode; // Retornamos el nombre de la variable o temporal actualizado
}
}
class OperatorExpression implements Expr {
Expr e, e2;
Operator o;
public OperatorExpression(Expr e, Operator o, Expr e2) {
this.e = e;
this.e2 = e2;
this.o = o;
}
public Object run(HashMap<String, Object> hm) {
return o.count(e, e2, hm);
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Generar código para la primera expresión
String temp1 = e.generateCode(codeGen); // Código para la primera expresión
// Generar código para la segunda expresión
String temp2 = e2.generateCode(codeGen); // Código para la segunda expresión
// Crear un nuevo temporal para almacenar el resultado de la operación
String resultTemp = codeGen.newTemp();
// Dependiendo del operador, generar el código intermedio
// Aquí, usamos el operador que tiene el objeto 'o'. Puede ser suma, resta, multiplicación, etc.
String operatorCode = o.toString();
// Añadir la instrucción correspondiente para realizar la operación
codeGen.addInstruction(operatorCode, temp1, temp2, resultTemp);
// Retornar el temporal que contiene el resultado
return resultTemp;
}
}
/**
* INT OPERATIONS
*/
class IntExpression implements Expr {
int value;
public IntExpression(int e) {
value = e;
}
public int getValue() {
return value;
}
public Object run(HashMap<String, Object> hm) {
return value;
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Crear un nuevo temporal para almacenar el valor de la expresión
String resultTemp = codeGen.newTemp();
// Generar la instrucción de asignación
// Asignar el valor entero directamente al temporal
codeGen.addInstruction("ASSIGN", Integer.toString(value), "", resultTemp);
// Retornar el temporal que contiene el valor del entero
return resultTemp;
}
}
class IntEnterExpression implements Expr {
public Object run(HashMap<String, Object> hm) {
java.util.Scanner in = new java.util.Scanner(System.in);
return in.nextInt();
}
public String generateCode(c3Direcciones codeGen) {
// Crear un nuevo temporal para almacenar el valor leído
String resultTemp = codeGen.newTemp();
// Generar la instrucción que simula leer un entero desde la entrada
// Supongamos que la operación de entrada se representa como "READ" en el código intermedio
codeGen.addInstruction("READ", "", "", resultTemp);
// Retornar el temporal que contiene el valor leído
return resultTemp;
}
}
class PIntExpression implements Expr {
Expr expr;
public PIntExpression(Expr e) {
expr = e;
}
public Object run(HashMap<String, Object> hm) {
return expr.run(hm);
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Llamamos al generateCode de la expresión interna (expr) para generar el código intermedio
return expr.generateCode(codeGen);
}
}
class UMinusExpression implements Expr {
Expr e;
public UMinusExpression(Expr e) {
this.e = e;
}
public Object run(HashMap<String, Object> hm) {
Object v = e.run(hm);
if (v instanceof Integer) {
return -((Integer) v);
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Primero generamos el código para la expresión interna (e)
String temp = e.generateCode(codeGen); // Aquí obtenemos el código intermedio de e
// Crear un nuevo nombre para el temporal donde se almacenará el resultado de la operación unaria
String tempResult = codeGen.newTemp();
// Agregar la instrucción de código intermedio para la operación de negación
codeGen.addInstruction("-", temp, null, tempResult);
return tempResult; // Retornamos el nombre del temporal donde se almacena el resultado
}
}
class STRLengthExpression implements Expr {
Expr e;
public STRLengthExpression(Expr e) {
this.e = e;
}
public Object run(HashMap<String, Object> hm) {
Object v = e.run(hm);
if (v instanceof String) {
return ((String) v).length();
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Generamos el código para la expresión interna
String temp = e.generateCode(codeGen);
// Creamos un nuevo temporal para almacenar el resultado
String tempResult = codeGen.newTemp();
// Agregamos la instrucción para obtener la longitud de la cadena
codeGen.addInstruction("strlen", temp, null, tempResult);
// Retornamos el temporal con el resultado
return tempResult;
}
}
class STRPositionExpression implements Expr {
Expr e, e2;
public STRPositionExpression(Expr e, Expr e2) {
this.e = e;
this.e2 = e2;
}
public Object run(HashMap<String, Object> hm) {
Object v1 = e.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof String && v2 instanceof String) {
String s = (String) v1;
String s2 = (String) v2;
int pos = s.indexOf(s2);
return (pos != -1) ? pos + 1 : 0;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return 0;
}
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Generamos el código para las expresiones internas
String temp1 = e.generateCode(codeGen); // Temporal para la cadena principal
String temp2 = e2.generateCode(codeGen); // Temporal para la subcadena
// Creamos un temporal para almacenar el resultado
String tempResult = codeGen.newTemp();
// Agregamos la instrucción para buscar la posición de la subcadena
codeGen.addInstruction("strpos", temp1, temp2, tempResult);
// Retornamos el temporal con el resultado
return tempResult;
}
}
/**
* CONDITIONS
*/
class EqCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
// Comparar enteros
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 == (Integer) v2;
}
// Comparar booleanos
else if (v1 instanceof Boolean && v2 instanceof Boolean) {
return (Boolean) v1 == (Boolean) v2;
}
// Manejo de error para tipos incorrectos
else {
System.out.println("Error: wrong objects type for equality comparison");
System.exit(1);
return false;
}
}
}
class LtCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 < (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class LeCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 <= (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class GtCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 > (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class GeCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 >= (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class NeCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof Integer && v2 instanceof Integer) {
return (Integer) v1 != (Integer) v2;
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class StrEqCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof String && v2 instanceof String) {
return ((String) v1).equals((String) v2);
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class StrNotEqCond implements Condition {
public boolean test(Expr e1, Expr e2, HashMap<String, Object> hm) {
Object v1 = e1.run(hm);
Object v2 = e2.run(hm);
if (v1 instanceof String && v2 instanceof String) {
return !((String) v1).equals((String) v2);
} else {
System.out.println("Error: wrong objects type");
System.exit(1);
return false;
}
}
}
class BoolExpression2 implements Expr {
Boolean value;
public BoolExpression2(Boolean e) {
value = e;
}
public boolean getValue() {
return value;
}
public Object run(HashMap<String, Object> hm) {
return value;
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Creamos un temporal para almacenar el valor booleano
String tempResult = codeGen.newTemp();
// Agregamos la instrucción para asignar el valor booleano al temporal
codeGen.addInstruction("assign", value.toString(), null, tempResult);
// Retornamos el temporal que contiene el valor booleano
return tempResult;
}
}
/**
* BOOLEAN OPERATIONS
*/
class BooleanExpression implements Expr {
Boolean value;
Boolean isConst = false;
// Constructor with both parameters
public BooleanExpression(Boolean e, Boolean isConst) {
if (isConst && e == null) {
System.out.println("Error: null value for constant");
System.exit(1);
}
this.value = e;
this.isConst = isConst;
}
// Constructor with only the value parameter, defaults isConst to false
public BooleanExpression(Boolean e) {
if (isConst && e == null) {
System.out.println("Error: null value for constant");
System.exit(1);
}
this.value = e;
}
public Object run(HashMap<String, Object> hm) {
return value;
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Crear un temporal para almacenar el valor booleano
String tempResult = codeGen.newTemp();
// Determinar si el valor es una constante
String boolValue = value != null ? value.toString() : "null";
if (isConst) {
// Agregar instrucción de asignación como constante
codeGen.addInstruction("assign_const", boolValue, null, tempResult);
} else {
// Agregar instrucción de asignación regular
codeGen.addInstruction("assign", boolValue, null, tempResult);
}
// Retornar el temporal que contiene el valor booleano
return tempResult;
}
}
class ConditionBooleanExpression implements Expr {
Expr e, e2;
Condition c;
public ConditionBooleanExpression(Expr e, Condition c, Expr e2) {
this.e = e;
this.c = c;
this.e2 = e2;
}
public Object run(HashMap<String, Object> hm) {
return c.test(e, e2, hm);
}
@Override
public String generateCode(c3Direcciones codeGen) {
// Generar código para las expresiones e y e2
String temp1 = e.generateCode(codeGen);
String temp2 = e2.generateCode(codeGen);
// Crear un temporal para almacenar el resultado de la condición
String tempResult = codeGen.newTemp();
// Obtener el operador de la condición