-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
2080 lines (1882 loc) · 77.1 KB
/
Main.java
File metadata and controls
2080 lines (1882 loc) · 77.1 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
/*
Compiladores/2022.1
Grupo:
@Giulia Chiucchi
@Gustavo Gomes
@Stephanie Silva
*/
import java.util.*;
import java.io.*;
/*Criacao da classe para a representacao de um simbolo da linguagem*/
class Simbolo {
private String lexema = "";
private String tipo = "";
private String classe = "";
private String endereco = "";
private int tamanho = 0;
private String valor = "";
private String token;
public Simbolo() {
this.lexema = "";
this.tipo = "";
this.classe = "";
this.endereco = "";
this.tamanho = 0;
this.valor = "";
this.token = "";
}
public Simbolo(String token, String lexema, String tipo, String classe, String endereco, int tamanho, String valor) {
this.lexema = lexema;
this.token = token;
this.tipo = tipo;
this.classe = classe;
this.endereco = endereco;
this.tamanho = tamanho;
this.valor = valor;
}
public String getToken() {
return this.token;
}
public String getLexema() {
return this.lexema;
}
public String getTipo() {
return this.tipo;
}
public String getClasse() {
return this.classe;
}
public int getTamanho() {
return this.tamanho;
}
public String getValor() {
return this.valor;
}
public String getEndereco() {
return this.endereco;
}
public void setToken(String token) {
this.token = token;
}
public void setLexema(String lexema) {
this.lexema = lexema;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public void setClasse(String classe) {
this.classe = classe;
}
public void setTamanho(int tamanho) {
this.tamanho = tamanho;
}
public void setValor(String valor) {
this.valor = valor;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
}
public class Main {
private static ArrayList<String> linhasArquivo;
private static Simbolo token = new Simbolo();
private static String[] file = readFile();
static BufferedReader arquivo; // pode tirar, nao?
private static int linhas = 1;
private static int index = 0;
private static boolean error = false;
private static int numLinhasArquivo;
private static int endAtual;
private static int rotulo = 0;
private static int temp = 0;
private static File arquivoSaida;
private static String declarations = "section .data \nM: \nresb 10000h";
private static String code = "section .text \nglobal _start\n_start:\n";
// Declaracao dos caracteres que fazem parte dos tokens da linguagem
private static String[] alfabeto_simbolos = { "_", ".", ",", ";", "(", ")", "[", "]", "+", "-", "'", "\"",
"%", "!", ">", "<", "=", "*", "/" };
// Declaracao dos caracteres reservados da linguagem que nao podem ser
// declaradas ou atribuidas durante o programa, exceto o TRUE e FALSE
private static String[] alfabeto_reservadas = { "const", "integer", "char", "while", "if", "real", "else", "and",
"or", "not", "begin", "end", "readln", "string", "write", "writeln", "TRUE", "FALSE", "boolean", "==", "!=",
">=", "<=", "//" };
// Declaracao dos caracteres permitidos na linguagem que podem ser usados em
// comentarios, strings e char
private static String[] alfabeto_caracteres = { " ", "_", ".", ",", ";", ":", "(", ")", "[", "]", "{", "}", "+", "-",
"\"", "'", "/", "\\", "@", "&", "%", "!", "?", ">", "<", "=", "*" };
// Declaracao das letras permitidas nas constantes hexadecimais
private static String[] letras_hexa = { "A", "B", "C", "D", "E", "F" };
private static String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
public static HashMap<String, Simbolo> tabela = new HashMap<>();
// Letras permitidas na linguagem
public static boolean isLetter(char c) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
return true;
else
return false;
}
public static String[] readFile() {
String result = "";
int auxLinha = 1;
try {
linhasArquivo = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int t = br.read(); t != -1; t = br.read()) {
if ((char) t == '\n') {
result = result + (char) t;
auxLinha += 1; // Variavel para ter controle de quantas linhas tem no arquivo, mesmo as nulas
linhasArquivo.add(result);
} else if ((char) t == '\r') {
} else {
char aux = (char) t;
result = result + aux;
}
}
if (result.charAt(result.length() - 1) != '\n') {// Formatacao para leitura correta de todos os tokens,
// sinaliza que o fim do arquivo foi atingido
result = result + '\n';
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
String results[] = new String[2]; // Formatacao do retorno da funcao, que retorna o arquivo lido e a quantidade de
// linhas
results[0] = result;
results[1] = Integer.toString(auxLinha);
return results;
}
//Criação do arquivo para escrita dos comandos em assembly
public static void createFile(){
try {
arquivoSaida = new File("arquivoSaida.asm");
if (!arquivoSaida.createNewFile()) {
new FileOutputStream(arquivoSaida).close();
}
} catch (IOException e) {
}
}
public static void writeDeclaration(String conteudo){
declarations+= conteudo;
}
public static void writeCode(String conteudo){
code += conteudo;
}
public static Simbolo searchTabela(String lexema) {
return tabela.get(lexema); // retorna null se nao estiver presente
}
public static boolean searchAlfabeto(char tok, String[] alfabeto) {
boolean result = false;
for (int i = 0; i < alfabeto.length; i++) {
if (alfabeto[i].charAt(0) == tok) {
result = true;
}
}
return result;
}
public static boolean isCaractere(String str) {
if (str.length() != 3) return false;
if(str.charAt(0) == '\''
&& (str.charAt(1) >= 0 && str.charAt(1) <= 255)
&& str.charAt(2) == '\'')
return true;
return false;
}
public static boolean isHexa(String str) {
if (str.length() == 3) {
if (searchAlfabeto(str.charAt(0), hex)) {
if (searchAlfabeto(str.charAt(1), hex)) {
if (str.charAt(2) == 'h') {
return true;
}
}
}
}
return false;
}
public static String isNumero(String str) {
if(str.contains(".")){
try {
Double.parseDouble(str);
return "real";
} catch (Exception e) {
return "";
}
}else{
try {
Integer.parseInt(str);
return "integer";
} catch (NumberFormatException nfe) {
return "";
}
}
}
public static void addTabela(Simbolo token) {
tabela.put(token.getLexema(),token);
}
public static void removeTabela(Simbolo token) {
tabela.remove(token.getLexema());
}
public static char lerChar(int i) {
return file[0].charAt(i);
}
/* ANALISADOR LEXICO */
public static Simbolo analisadorLexico() {
Simbolo simbolo = new Simbolo();
int estado = 0;
String lex = "";
numLinhasArquivo = Integer.parseInt(file[1]);
// Enquanto for um estado valido, o analisador lexico ira procurar por um token
while (estado != -1) {
// Se for tentando ler um caracter depois do fim de arquivo, dispara um erro
if (index >= file[0].length() && error == false) {
error = true;
estado = -1;
if (numLinhasArquivo < linhas) { // Formatacao da linha, quando o erro de fim de arquivo aparece na linha
// antes do EOF
linhas--;
}
System.out.print((linhas) + "\nfim de arquivo nao esperado.");
break;
}
if (index >= file[0].length()) {
estado = -1;
break;
}
char c = file[0].charAt(index);
// Se o caracter lido nao pertencer a linguagem, dispara um erro
if (searchAlfabeto(c, alfabeto_caracteres) == false && isLetter(c) == false && Character.isDigit(c) == false
&& c != '\n' && c != '\r') {
error = true;
System.out.print((linhas) + "\ncaractere invalido.");
index = file[0].length();
} else {
switch (estado) {
case 0:
// Constante Hexadecimal ou Identificador
if (searchAlfabeto(c, letras_hexa)) {
lex += c;
index++;
estado = 11;
// Identificador ou Palavra reservada
} else if (c == '_' || isLetter(c)) {
lex += c;
index++;
simbolo.setToken("id");
estado = 10;
// Numero real ou numero inteiro ou constante hexadecimal
} else if (Character.isDigit(c)) {
lex += c;
index++;
estado = 21;
// Comparadores de grandeza (maior,menor,igual, maiorigual,menorigual) ou
// atribuicao
} else if (c == '=' || c == '<' || c == '>') {
lex += c;
index++;
estado = 4;
// Diferente
} else if (c == '!') {
lex += c;
index++;
estado = 5;
// Divisao ou quociente da divisao de 2 inteiros
} else if (c == '/') {
lex += c;
index++;
estado = 6;
// Caracter
} else if (c == '\'') {
lex += c;
index++;
estado = 7;
// String
} else if (c == '"') {
lex += c;
index++;
estado = 9;
// Operadores
} else if (c == ',' || c == '-' || c == '+' || c == '*' || c == ';' || c == '%' || c == '('
|| c == ')' || c == '[' || c == ']') {
lex += c;
simbolo.setToken(lex);
simbolo.setLexema(lex);
index++;
estado = 30;
// Ponto flutuante
} else if (c == '.') {
lex += c;
index++;
estado = 19;
// Comentario
} else if (c == '{') {
lex += c;
index++;
estado = 1;
// Delimitador de token
} else if (c == ' ') {
estado = 0;
index++;
// Delimitador de token
} else if (c == '\n' || c == '\r') {
estado = 0;
linhas++;
index++;
if (index >= file[0].length()) {
estado = -1;
}
// Caracter nao pertencente a nenhum token
} else {
if (lex.length() == 0) {
lex += c;
}
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
error = true;
estado = -1;
}
break;
// Comentario: casos de 1 a 3
case 1:
if (c == '*') {
estado = 2;
index++;
lex += c;
} else {
error = true;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
estado = -1;
break;
}
break;
case 2:
if (c == '*') {
estado = 3;
index++;
lex += c;
} else if (isLetter(c) || Character.isDigit(c) || searchAlfabeto(c, alfabeto_caracteres) == true
|| c == ' ' || c == '\n' || c == '\r') { // Enquanto o comentario nao achar um * e ler um
// caracter ou delimitador valido na linguagem
index++;
if (c == '\n' || c == '\r')
linhas++;
lex += c;
estado = 2;
} else {
error = true;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
estado = -1;
}
break;
case 3:
if (c == '*') { // Pode-se ler 0 ou mais * dentro de um comentario
estado = 3;
index++;
lex += c;
} else if (c != '*' && c != '}') { // Volta para o estado 2 pois o comentario ainda nao foi finalizado
estado = 2;
index++;
lex += c;
if (c == '\n' || c == '\r')
linhas++;
} else if (c == '}') { // Fechamento do comentario
estado = 0;
index++;
lex = "";
} else {
error = true;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
}
break;
// >= <= == > < =
case 4:
if (c == '=') { // Adiciona o = aos simbolos <,> ou =
lex += c;
simbolo.setToken(lex);
simbolo.setLexema(lex);
index++;
estado = 30;
} else { // Leu apenas os simbolos >, < ou =
simbolo.setToken(lex);
simbolo.setLexema(lex);
estado = 30;
}
break;
// !=
case 5:
if (c == '=') {
lex += c;
simbolo.setToken(lex);
simbolo.setLexema(lex);
index++;
estado = 30;
} else if (c != '=') { // O caracter ! deve ser obrigatoriamente seguido por um '=', se isso nao
// ocorrer dispara um erro
error = true;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
lex = "";
estado = -1;
}
break;
// / ou //
case 6:
if (c == '/') {
lex += c;
index++;
simbolo.setToken(lex);
simbolo.setLexema(lex);
estado = 30;
} else {
simbolo.setToken(lex);
simbolo.setLexema(lex);
estado = 30;
}
break;
// Char
case 7:
if ((searchAlfabeto(c, alfabeto_caracteres) || Character.isDigit(c) || isLetter(c)) // Char so pode
// ser composto de
// letras, digitos
// ou caracteres
// validos na
// linguagem
&& c != ' ') {
lex += c;
index++;
estado = 8;
} else {
error = true;
if ((c == '\n' || c == '\r') && (index + 1) == file[0].length()) { // Se exister uma quebra de
// linha
// logo antes do arquivo acabar
// dispara-se um erro
System.out.print((linhas) + "\nfim de arquivo nao esperado.");
index = file[0].length();
lex = "";
estado = -1;
} else {
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
lex = "";
estado = -1;
}
}
break;
case 8:
if (c == '\'') { // Fechamento do char
lex += c;
simbolo.setToken("const");
simbolo.setLexema(lex);
index++;
estado = 30;
} else {
error = true;
if ((c == '\n' || c == '\r') && (index + 1) == file[0].length()) {// Se exister uma quebra de linha
// logo antes do arquivo acabar
// dispara-se um erro
System.out.print((linhas) + "\nfim de arquivo nao esperado.");
index = file[0].length();
lex = "";
estado = -1;
} else {
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
lex = "";
estado = -1;
}
}
break;
// string
case 9:
if (c != '"'
&& (searchAlfabeto(c, alfabeto_caracteres) || Character.isDigit(c) || isLetter(c))) { // String
// so pode
// ser
// composto
// de
// letras,
// digitos
// ou
// caracteres
// validos
// na
// linguagem,
// exceto
// aspas
lex += c;
index++;
estado = 9;
} else if (c == '"') { // Fechamento da string
lex += c;
simbolo.setToken("const");
simbolo.setLexema(lex);
index++;
estado = 30;
} else {
error = true;
estado = -1;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
lex = "";
}
break;
// identificador ou palavra reservada
case 10:
if ((c == '_' || isLetter(c) || Character.isDigit(c))) {
lex += c;
index++;
estado = 10;
} else if (c != '_' && isLetter(c) == false && Character.isDigit(c) == false) { // Leitura de um
// caracter nao mais
// pertencente ao ID
// ou palavra
// reservada
if (searchTabela(lex) == null) { // Verifica se é uma palavra reservada, se retornar null na busca
// da tabela de simbolos é um ID
simbolo.setToken("id");
simbolo.setLexema(lex);
} else {
if (lex.equals("TRUE") || lex.equals("FALSE")) { // das palavras reservadas, o TRUE e ELSE sao
// constantes
simbolo.setToken("const");
simbolo.setLexema(lex);
} else {
simbolo = searchTabela(lex);
simbolo.setLexema(lex);
}
}
estado = 30;
}
break;
// Constante hexadecimal ou identificador, casos 11, 16, 18
case 11:
if (searchAlfabeto(c, letras_hexa) || Character.isDigit(c)) { // Verifica se é uma das letras
// hexadecimal ou um numero para decidir
// se é um ID ou nao
lex += c;
index++;
estado = 16;
} else if (isLetter(c) || c == '_') { // Verificou que os caracteres lidos podem fazer parte de um ID
// e nao mais uma const hexadecimal
lex += c;
index++;
estado = 10;
} else { // Verificou que foi encontrado um ID
estado = 30;
simbolo.setToken("id");
simbolo.setLexema(lex);
}
break;
case 16:
if (c == 'h') { // Possivel const hexadecimal encontrada, vai para o estado 18 para confirmar se
// é um ID ou uma const
lex += c;
index++;
estado = 18;
} else if ((c == '_' || isLetter(c) || Character.isDigit(c))) {// Verificou que os caracteres lidos
// podem fazer parte de um ID e nao
// mais uma const hexadecimal
lex += c;
index++;
estado = 10;
} else { // Verificou que foi encontrado um ID
estado = 30;
simbolo.setToken("id");
simbolo.setLexema(lex);
}
break;
case 18:
if ((c == '_' || isLetter(c) || Character.isDigit(c))) { // Verificacao que os caracteres sendo lidos
// podem fazer parte de um ID
lex += c;
index++;
estado = 10;
} else { // Confirmacao que é uma const hexadecimal
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
}
break;
case 19:// Verificacao de const hexadecimal ou numero, casos 19,20,21,22,23,24
if (Character.isDigit(c)) {// Numero iniciado com ponto, se nao achar um numero depois do '.'
// dispara-se um erro
lex += c;
index++;
estado = 20;
} else {
error = true;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
lex = "";
estado = -1;
}
break;
case 20:
if (Character.isDigit(c)) { // Leitura de um numero interio ou real
lex += c;
index++;
estado = 20;
} else {
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
}
break;
case 21:
if (c == '.') { // Verificacao se é um numero real, inteiro ou const hexadecimal
lex += c;
index++;
estado = 20;
} else if (Character.isDigit(c)) {
lex += c;
index++;
estado = 22;
} else if (searchAlfabeto(c, letras_hexa)) {
lex += c;
index++;
estado = 23;
} else { // Encontrou um numero
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
}
break;
case 22:
if (c == '.') {// Verificacao se é um numero real ou inteiro
lex += c;
index++;
estado = 20;
} else if (Character.isDigit(c)) {
lex += c;
index++;
estado = 24;
} else if (c == 'h') {// Encontrou uma constante hexadecimal comecada por digito
lex += c;
index++;
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
} else {
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
}
break;
case 23:
if (c == 'h') {// Encontrou uma constante hexadecimal composta do por 1 digito e uma letra
// hexadecimal
lex += c;
index++;
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
} else {
error = true;
System.out.print((linhas) + "\nlexema nao identificado [" + lex + "].");
index = file[0].length();
lex = "";
estado = -1;
}
break;
case 24:
if (c == '.') {// Verificacao se é um numero real ou inteiro
lex += c;
index++;
estado = 20;
} else if (Character.isDigit(c)) {
lex += c;
index++;
estado = 24;
} else {
estado = 30;
simbolo.setToken("const");
simbolo.setLexema(lex);
}
break;
case 30: // Estado final de aceitacao de um token, devolve o lexema lido para o
// analisador sintatico
lex = "";
estado = -1;
break;
}
}
}
return simbolo;
}
/* ANALISADOR SINTATICO E SEMANTICO*/
// Metodo do CasaToken para identificar se o token lido corresponde as regras da
// gramatica
public static void ct(String token_esperado) {
if (token.getToken().equals(token_esperado)) {
token = analisadorLexico();
} else if (token.getToken().equals("") && error == false) {
if (numLinhasArquivo < linhas) { // Formatacao da linha, quando o erro de fim de arquivo aparece na linha antes
// do EOF
linhas--;
}
System.out.print((linhas) + "\nfim de arquivo nao esperado.");
error = true;
System.exit(0);
} else {
if (error == false) {
error = true;
System.out.println(linhas);
System.out.print("token nao esperado [" + token.getToken() + "].");
System.exit(0);
}
}
}
public static int NovoRotulo() {
int aux = rotulo;
rotulo += 1;
return aux;
}
public static int NovoTemp(int bytes) {
int aux = temp;
temp += bytes;
return aux;
}
/*
* Gramatica S-> {Declaracao}* {Comandos}* EoF
*/
public static void S() {
token = analisadorLexico();
try {
// Enquanto for uma declaracao ou comando
while (token.getToken().equals("integer") || token.getToken().equals("const")
|| token.getToken().equals("char") || token.getToken().equals("real")
|| token.getToken().equals("string") || token.getToken().equals("boolean") || token.getToken()
.equals("id")
|| token.getToken().equals("while") || token.getToken().equals("if")
|| token.getToken().equals(";") || token.getToken().equals("readln")
|| token.getToken().equals("writeln") || token.getToken().equals("write")) {
// Identifica os tokens que sao declaracoes
while (token.getToken().equals("integer") || token.getToken().equals("const")
|| token.getToken().equals("char") || token.getToken().equals("real")
|| token.getToken().equals("string") || token.getToken().equals("boolean")) {
Declaracao();
}
// Identifica os tokens que sao comandos
while (token.getToken().equals("id") || token.getToken().equals("while") || token.getToken().equals("if")
|| token.getToken().equals(";") || token.getToken().equals("readln")
|| token.getToken().equals("writeln") || token.getToken().equals("write")) {
Comandos();
}
// Se for um token que nao inicia nem declaracao ou comando dispara-se um erro
while (token.getToken().equals("end") || token.getToken().equals("begin")) {
error = true;
System.out.println(linhas);
System.out.print("token nao esperado [" + token.getToken() + "].");
System.exit(0);
}
}
} catch (Exception e) {
}
}
public static Simbolo addEndereco(Simbolo simbolo, int bytes, String instrucao){
simbolo.setEndereco(endAtual + "h");
endAtual+= bytes;
writeDeclaration(instrucao+"\n");
return simbolo;
}
/*
* Declaracao -> Variaveis | Constantes
*/
public static void Declaracao() {
if (token.getToken().equals("integer") || token.getToken().equals("char") || token.getToken().equals("real")
|| token.getToken().equals("string") || token.getToken().equals("boolean")) {
Variaveis();
} else if (token.getToken().equals("const")) {
Constantes();
}
}
/*
* VARIAVEIS {(int | char | boolean | real | string) id1[ = [-] constante] {,id2[ = [-] constante ] }* ;}
*/
public static void Variaveis() {
while (token.getToken().equals("integer") || token.getToken().equals("char") || token.getToken().equals("real")
|| token.getToken().equals("string") || token.getToken().equals("boolean")) {
if (token.getToken().equals("integer")) {
ct("integer");
Simbolo id1;
Simbolo id2;
Simbolo exp;
id1 = searchTabela(token.getLexema()); //Procura de o id ja foi declarado anteriormente
if (id1 == null) {
id1 = token;
id1.setClasse("var"); //Iniciacao da classe e tipo do token, alem de fazer a traducao para os comandos de assembly
id1.setTipo("integer");
id1 = addEndereco(id1, 4, "resd 1");
ct("id");
addTabela(id1);
if (token.getToken().equals("=")) {
ct("=");
if (token.getToken().equals("-")) {
ct("-");
}
exp = Exp();
if (exp.getTipo().equals("integer")) {
id1.setValor(exp.getLexema());
} else {
System.out.print(linhas + "\ntipos incompativeis.");
System.exit(0);
}
}
} else {
System.out.print(linhas + "\nidentificador ja declarado [" + token.getLexema() + "].");
System.exit(0);
}
while (token.getToken().equals(",")) {
ct(",");
id2 = searchTabela(token.getLexema());
if (id2 == null) {
id2 = token;
id2.setClasse("var");
id2.setTipo("integer");
id2 = addEndereco(id2, 4, "resd 1");
ct("id");
addTabela(id2);
} else {
System.out.print(linhas + "\nidentificador ja declarado [" + token.getLexema() + "].");
System.exit(0);
}
if (token.getToken().equals("=")) {
ct("=");
if (token.getToken().equals("-")) {
ct("-");
}
exp = Exp();
if (exp.getTipo().equals("integer")) {
id2.setValor(exp.getLexema());
} else {
System.out.print(linhas + "\ntipos incompativeis.");
System.exit(0);
}
}
}
ct(";");
} else if (token.getToken().equals("char")) {
ct("char");
Simbolo id1;
Simbolo id2;
Simbolo exp;
id1 = searchTabela(token.getLexema());
if (id1 == null) {
id1 = token;
id1.setClasse("var");
id1.setTipo("char");
id1 = addEndereco(id1, 1, "resb 1");
ct("id");
addTabela(id1);
if (token.getToken().equals("=")) {
ct("=");
if (token.getToken().equals("-")){
System.out.print(linhas + "\ntipos incompativeis.");
System.exit(0);
}
exp = Exp();
if (exp.getTipo().equals("char")) {
id1.setValor(exp.getLexema());
} else {
System.out.print(linhas + "\ntipos incompativeis.");
System.exit(0);
}
}
} else {
System.out.print(linhas + "\nidentificador ja declarado [" + token.getLexema() + "].");
System.exit(0);
}
while (token.getToken().equals(",")) {
ct(",");
id2 = searchTabela(token.getLexema());
if (id2 == null) {
id2 = token;
id2.setClasse("var");
id2.setTipo("char");
id2 = addEndereco(id2, 1, "resb 1");