-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsintatic.cpp
670 lines (600 loc) · 14.4 KB
/
sintatic.cpp
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
/**
* @Nome: Cassiano Henrique Aparecido Rodrigues
* @Matricula: 201020891
* @Sistema Operacional: Manjaro Linux (5.13.19-2-MANJARO-x86_64)
* @Compilador: gcc (GCC) 12.1.0
*
* Using ISO C++17 (C++17) -- apply with -std=c++17 flag
*/
#include "lexical.h"
#include <queue>
#include <regex>
#include <locale>
#define CURRENT_TOKEN std::get<2>(queueTokens.front())
#define IS_IDENTIFIER std::regex_match(CURRENT_TOKEN, std::regex("IDENTIFIER_.*"))
#define IS_NUMBER std::regex_match(CURRENT_TOKEN, std::regex("NUMBER_.*"))
std::queue<std::tuple<int, int, std::string>> queueTokens;
// Headers das funções
// -------------------
// Análise Sintática
void sintaticAnalysis();
// Funções auxiliares:
void identifyToken(char &next_char);
void fillQueueWithTokens();
void next(); // Pula para o próximo elemento da fila
void throwError(std::string message);
// Funções de análise sintática
void program();
void block();
void partDeclaration();
void declaration();
void type();
void listIdentifier();
void auxDeclaration();
void declarationProcedure();
void declarationFunction();
void partDeclarationSubroutine();
void formalParameters();
void sectionFormalParameters();
void partSectionFormalParameters();
void listIdentifierFormalParameters();
void endSectionFormalParameters();
void compoundStatement();
void statement();
void statementWithoutLabel();
void assignment();
void callProcedure();
void ifStatement();
void whileStatement();
void expression();
void simpleExpression();
void optionalExpression();
void relationalExpression();
void term();
void factor();
void factorWithExpression();
// -------------------
// Funções auxiliares
// -------------------
void identifyToken(char &next_char)
{
std::string token = "";
while (next_char != ' ')
{
// Enquanto o carácter não for um espaço, vai capturar a palavra
if (next_char != '\t' && next_char != '\n')
token += next_char;
proximo(next_char);
}
// A cada palavra capturada, vai ser inserido no topo da pilha com seu número de linha e coluna
// column_number é a coluna do carácter atual, e é decrementado o número de colunas usadas para o tamanho do token (fica mais próximo do real)
queueTokens.push(std::make_tuple(line_number, column_number - token.size(), token));
}
void fillQueueWithTokens()
{
char next_char;
// Preencher pilha de tokens com os tokens do arquivo
try
{
int line_number = 1;
do
{
proximo(next_char);
identifyToken(next_char);
} while (read_file.good());
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
}
void throwError(std::string message, std::tuple<int, int, std::string> token)
{
// Imprime a mensagem de erro e a linha e coluna do token que gerou o erro, mais a mensagem de erro;
throw std::runtime_error("Erro na linha " + std::to_string(std::get<0>(token)) + " coluna " + std::to_string(std::get<1>(token)) + ": " + message + '\n');
}
void next(std::string token, int type)
{
if (type == 1) // Nomeados, verifica o tipo
{
std::string tokenType = std::regex_replace(token, std::regex("_.*"), "");
std::string currentTokenType = std::regex_replace(CURRENT_TOKEN, std::regex("_.*"), "");
if (tokenType == currentTokenType)
{
// Avança para o próximo elemento da fila:
queueTokens.pop();
}
else
{
// Token não é o esperado, deve-se gerar um erro:
throwError("(next): Esperado " + token + " encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
else
{ // Não nomeados verifica o token
if (std::regex_match(CURRENT_TOKEN, std::regex(token)))
{
// Avança para o próximo elemento da fila:
queueTokens.pop();
}
else
{
// Token não é o esperado, deve-se gerar um erro:
throwError("(next): Esperado " + token + " encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
}
// -------------------
void statement()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("NUMBER_.*")))
{
next("NUMBER", 1);
next("SS_COLON", 2); // dois pontos
}
statementWithoutLabel();
}
void program()
{
std::tuple<int, int, std::string> currentToken = queueTokens.front();
if (std::regex_match(std::get<2>(currentToken), std::regex("RW_PROGRAM")))
{
next("RW_PROGRAM", 2);
next("IDENTIFIER", 1);
next("SS_SEMICOLON", 2);
block();
next("SS_DOT", 2);
}
else
{
throwError("Erro sintático - Esperado 'PROGRAM' encontrado " + std::get<2>(currentToken), queueTokens.front());
}
}
void block()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_VAR")))
{
partDeclaration();
}
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_PROCEDURE|RW_FUNCTION")))
{
partDeclarationSubroutine();
}
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_BEGIN")))
{
compoundStatement();
}
}
void partDeclaration()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_VAR")))
{
next("RW_VAR", 2);
declaration();
}
else
{
throwError("Erro sintático - Esperado 'VAR' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void declaration()
{
if (IS_IDENTIFIER)
{
next("IDENTIFIER", 1);
listIdentifier();
}
else
{
throwError("Erro sintático - Esperado um identificador encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void listIdentifier()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_COMMA")))
{
next("SS_COMMA", 2);
declaration();
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("SS_COLON")))
{
next("SS_COLON", 2);
type();
next("SS_SEMICOLON", 2);
auxDeclaration();
}
else
{
throwError("Erro sintático - Esperado ',' ou ';' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void type()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_INTEGER|RW_BOOLEAN")))
{
next("RW_INTEGER|RW_BOOLEAN", 2);
}
else
{
throwError("Erro sintático - Esperado 'INTEGER' ou 'BOOLEAN' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void auxDeclaration()
{
if (IS_IDENTIFIER)
{
next("IDENTIFIER", 1);
declaration();
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("RW_PROCEDURE|RW_FUNCTION|RW_BEGIN")))
{
block();
}
else
{
throwError("Erro sintático - Esperado 'IDENTIFIER' ou 'PROCEDURE' ou 'FUNCTION' ou 'BEGIN' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void partDeclarationSubroutine()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_PROCEDURE")))
{
next("RW_PROCEDURE", 2);
declarationProcedure();
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("RW_FUNCTION")))
{
next("RW_FUNCTION", 2);
declarationFunction();
}
else
{
throwError("Erro sintático - Esperado 'PROCEDURE' ou 'FUNCTION' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void declarationProcedure()
{
if (IS_IDENTIFIER)
{
next("IDENTIFIER", 1);
formalParameters();
next("SS_SEMICOLON", 2);
block();
}
else
{
throwError("Erro sintático - Esperado 'IDENTIFIER' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void declarationFunction()
{
if (IS_IDENTIFIER)
{
next("IDENTIFIER", 1);
formalParameters();
next("SS_COLON", 2);
next("IDENTIFIER", 1);
next("SS_SEMICOLON", 2);
block();
}
else
{
throwError("Erro sintático - Esperado 'IDENTIFIER' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void formalParameters()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_OPEN_PARENTHESIS")))
{
next("SS_OPEN_PARENTHESIS", 2);
sectionFormalParameters();
next("SS_CLOSE_PARENTHESIS", 2);
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("SS_COLON")))
{
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("SS_SEMICOLON")))
{
}
else
{
throwError("Erro sintático - Esperado '(' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void sectionFormalParameters()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_VAR")))
{
next("RW_VAR", 2);
partSectionFormalParameters();
}
else if (IS_IDENTIFIER)
{
partSectionFormalParameters();
}
else
{
throwError("Erro sintático - Esperado 'IDENTIFIER' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void partSectionFormalParameters()
{
if (IS_IDENTIFIER)
{
next("IDENTIFIER", 1);
listIdentifierFormalParameters();
}
else
{
throwError("Erro sintático - Esperado 'IDENTIFIER' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void listIdentifierFormalParameters()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_COMMA")))
{
next("SS_COMMA", 2);
partSectionFormalParameters(); // + Mais um identificador
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("SS_COLON")))
{
next("SS_COLON", 2);
next("IDENTIFIER", 1);
endSectionFormalParameters();
}
else
{
throwError("Erro sintático - Esperado ',' ou ':' ou ';' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void endSectionFormalParameters()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_SEMICOLON")))
{
next("SS_SEMICOLON", 2);
partSectionFormalParameters(); // + Mais um identificador
}
}
void compoundStatement()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_BEGIN")))
{
next("RW_BEGIN", 2);
statement();
while (std::regex_match(CURRENT_TOKEN, std::regex("SS_SEMICOLON")))
{
next("SS_SEMICOLON", 2);
statement();
}
next("RW_END", 2);
}
else
{
throwError("Erro sintático - Esperado BEGIN encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void statementWithoutLabel()
{
if (IS_IDENTIFIER)
{
next("IDENTIFIER", 1);
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_ASSIGN")))
{
assignment();
}
else
{
callProcedure();
}
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("RW_END")))
{
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("RW_BEGIN")))
{
compoundStatement();
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("RW_IF")))
{
ifStatement();
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("RW_WHILE")))
{
whileStatement();
}
else
{
throwError("Erro sintático - Esperado um comando, encontrado: " + CURRENT_TOKEN, queueTokens.front());
}
}
void assignment()
{
if (!std::regex_match(CURRENT_TOKEN, std::regex("SS_ASSIGN")))
{
throwError("Erro sintático - Esperado ':=' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
next("SS_ASSIGN", 2);
expression();
}
void callProcedure()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_OPEN_PARENTHESIS")))
{
next("SS_OPEN_PARENTHESIS", 2);
expression();
next("SS_CLOSE_PARENTHESIS", 2);
}
}
void ifStatement()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_IF")))
{
next("RW_IF", 2);
expression();
next("RW_THEN", 2);
statementWithoutLabel();
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_ELSE")))
{
next("RW_ELSE", 2);
statementWithoutLabel();
}
}
else
{
throwError("Erro sintático - Esperado 'if' encontrado " + CURRENT_TOKEN, queueTokens.front());
}
}
void factor()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_NOT")))
{
// *: Verificar se é um factor "not <factor>"
next("RW_NOT", 2);
}
if (IS_IDENTIFIER)
{ // *: <identifier>
next("IDENTIFIER", 1);
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("NUMBER_.*")))
{ // *: <number>
next("NUMBER", 1);
}
else if (std::regex_match(CURRENT_TOKEN, std::regex("SS_OPEN_PARENTHESIS")))
{ // *: ( <expression> )
next("SS_OPEN_PARENTHESIS", 2);
expression();
next("SS_CLOSE_PARENTHESIS", 2);
}
else
{
throwError("Fator inválido", queueTokens.front());
}
}
void factorWithExpression()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_MULTIPLY|SS_DIVIDE|RW_DIV|RW_AND")))
{
next("SS_MULTIPLY|SS_DIVIDE|RW_DIV|RW_AND", 2);
factor();
}
}
void term()
{
factor();
factorWithExpression();
}
void simpleExpression()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_PLUS|SS_MINUS")))
{
next("SS_PLUS|SS_MINUS", 2);
}
term();
optionalExpression();
}
void optionalExpression()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_PLUS|SS_MINUS|RW_OR")))
{
next("SS_PLUS|SS_MINUS|RW_OR", 2);
term();
}
}
void relationalExpression()
{
std::string isRelation = "SS_LESS|SS_GREATER|SS_EQUAL|SS_NOT_EQUAL";
if (std::regex_match(CURRENT_TOKEN, std::regex(isRelation)))
{
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_GREATER|SS_LESS")))
{
next("SS_LESS|SS_GREATER", 2);
if (std::regex_match(CURRENT_TOKEN, std::regex("SS_EQUAL")))
{
next("SS_EQUAL", 2);
}
}
else
{
next(isRelation, 2);
}
simpleExpression();
}
}
void expression()
{
simpleExpression();
relationalExpression();
}
void whileStatement()
{
if (std::regex_match(CURRENT_TOKEN, std::regex("RW_WHILE")))
{
next("RW_WHILE", 2);
expression();
next("RW_DO", 2);
statementWithoutLabel();
}
else
{
throwError("While inválido", queueTokens.front());
}
}
// -------------------
// Análise Sintática
// -------------------
void sintaticAnalysis()
{
program();
}
// -------------------
main()
{
setlocale(LC_ALL, "pt");
std::string input_file_name;
std::cout << "O arquivo de entrada está na mesma pasta do executável? (Y/n)" << '\n';
if (std::toupper(std::cin.get()) == 'N')
{
std::cout << "Digite o nome do arquivo de entrada: (sem \".txt\")" << '\n';
std::cin >> input_file_name;
}
else
{
std::cout << "Digite o caminho completo do arquivo de entrada: (sem \".txt\")" << '\n';
std::cin >> input_file_name;
}
read_file.open(input_file_name + ".txt");
output_file.open("output.txt");
char next_char;
proximo(next_char);
try
{
do
{
write_output(lexical_analysis(next_char));
} while (read_file.good());
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
read_file.close();
output_file.close();
line_number = 1;
column_number = 1;
read_file.open("output.txt");
try
{
fillQueueWithTokens();
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
}
read_file.close();
// Pilha de tokens vai estar preenchida com os tokens do arquivo
// Agora, vai ser feita a análise sintática
sintaticAnalysis();
printf("\n\nAnálise sintática concluída!\n");
system("pause");
return 0;
}