Browse Source

Add files via upload

Nicolas T. Cuerbas 6 years ago
parent
commit
82d35bd48c
No account linked to committer's email address
6 changed files with 289 additions and 113 deletions
  1. 202
    44
      Geracaodecodigo.py
  2. 2
    2
      beuty.py
  3. 9
    14
      lexical.py
  4. 20
    13
      selection.py
  5. 51
    28
      semantico.py
  6. 5
    12
      sintatico.py

+ 202
- 44
Geracaodecodigo.py View File

@@ -1,39 +1,69 @@
1 1
 '''
2 2
     intermediario(token, argumentos, posicao inicial que deseja converter para assembler, posição final, valor inicial das Labels dos loops, texto final)
3 3
 '''
4
-def intemerdiario(token,args, inicio, fim, loop,condicional, texto):
5
-    L=loop
6
-    C=condicional
7
-    i=inicio
8
-    while i < fim :
4
+def intemerdiario(token,args):
5
+    if (args.lgc):
6
+        print ("Gerando código intermediário")
7
+    L=0
8
+    C=0
9
+    pilha=[]
10
+    i=0
11
+    texto=[]
12
+    while i < len(token) :
9 13
         if 'inteiro' in token[i][0]:
14
+            if (args.lgc):
15
+                print ("Inteiro identificado:")
10 16
             texto.extend(variaveis(token,i))
11 17
         elif 'leia' in token[i][0]:
18
+            if (args.lgc):
19
+                print ("leia identificado:")
12 20
             texto.append('LEIA '+token[i+2][1])
13 21
         elif 'escreva' in token[i][0]:
22
+            if (args.lgc):
23
+                print ("escreva identificado:")
14 24
             texto.append('ESCREVA '+ token[i+2][1])
15 25
         elif 'recebe' in token[i][0]:
26
+            if (args.lgc):
27
+                print ("Atribuição identificada:")
16 28
             exp=[]
17 29
             from infixtoposfix import infixToPostfix
18 30
             exp.append(infixToPostfix(expressao(token, i)))
19 31
             simpleexpre(exp,token[i-1][1],texto)
20 32
         elif 'enquanto' in token[i][0]:
21
-            texto.append(f'_L{L}: if {token[i+2][1]}'+ (' >' if '<' in token[i+3][1] else ' <')+f' {token[i+4][1]} goto _L{L+1} ')
22
-            i=intemerdiario(token, args, i+6, fim, L+1, C, texto)
23
-            texto.append(f'_L{L+1}:')
24
-            L=L+i
25
-            C=L
33
+            if (args.lgc):
34
+                print ("função enquanto identificado:")
35
+            texto.append(f'_L{L}: if {token[i+2][1]}'+ (' >=' if '<' in token[i+3][1] else ' <=')+f' {token[i+4][1]} goto _L{L+1} ')
36
+            pilha.append(f'_L{L+1}')
37
+            L+=2
26 38
         elif 'se' == token[i][0]:
27
-            texto.append(f'_C{C}: if {token[i+2][1]}' + (' >' if '<' in token[i+3][1] else ' <')+f' {token[i+4][1]} goto _C{C+1}')
28
-            i=intemerdiario(token, args, i+6, fim, L, C+1, texto)
29
-            texto.append(f'_C{L+1}:')
30
-            C = C + i
31
-            L = C
39
+            if (args.lgc):
40
+                print ("\'se\' identificado:")
41
+            texto.append(f'_C{C}: if {token[i+2][1]}' + (' =>' if '<' in token[i+3][1] else ' <=')+f' {token[i+4][1]} goto _C{C+1}')
42
+            pilha.append(f'_C{C + 1}')
43
+            C += 2
44
+        elif 'senao' == token[i][0]:
45
+            if (args.lgc):
46
+                print ("\'senao\' identificado:")
47
+            pilha.append(f'{int(texto[-1].split("_C")[1].split(":")[0])-1}')
32 48
         elif '}' in token[i][1]:
33
-            return i
49
+            if 'L' in pilha[-1]:
50
+                p= pilha.pop()
51
+                texto.append(f'goto _L{int(p.split("_L")[1])-1}')
52
+                texto.append(f'{p}:')
53
+            elif 'C' in pilha[-1]:
54
+                p = pilha.pop()
55
+                texto.append(f'goto EXIT_C{int(p.split("_C")[1]) - 1}')
56
+                texto.append(f'{p}:')
57
+                if 'senao' not in  token[i+1][0]:
58
+                    texto.append (f'EXIT_C{int(p.split("_C")[1])-1}:')
59
+            elif pilha[-1]:
60
+                texto.append(f'EXIT_C{pilha.pop()}:')
61
+        #print (pilha)
34 62
         i=i+1
35 63
 
36 64
     with open('intermediario.s','w') as f:
65
+        if (args.lgc):
66
+            print ("Escrevendo no arquivo:")
37 67
         f.write('\n'.join(texto))
38 68
 def simpleexpre(exp,var,texto):
39 69
     '''
@@ -41,7 +71,7 @@ def simpleexpre(exp,var,texto):
41 71
     SUB dest,src1,src2	dest = src1 - src2
42 72
     ADDI dest,src1,I	dest = src1 + I
43 73
     MUL dest,src1,src2	dest = src1 × src2
44
-    DIV[U] dest,src1,src2	dest = src1/src2
74
+    DIV dest,src1,src2	dest = src1/src2
45 75
     '''
46 76
     t=1
47 77
     exp=exp[0].split()
@@ -78,47 +108,175 @@ def variaveis(token,i):
78 108
         l+=1
79 109
     return var
80 110
 def gerarcodigo(token,args):
81
-    texto=[]
82 111
     '''
83 112
     intermediario(token, args, posicao inicial que deseja converter para assembler, posição final, valor inicial das Labels dos loops, valor inicial das Labels dos condicionais)
84 113
     '''
85
-    intemerdiario(token, args, 0, len(token), 0, 0, texto)
86
-    gerar()
87
-def gerar():
114
+    intemerdiario(token, args)
115
+    gerar(args)
116
+def gerar(args):
117
+    nome = args.filename.split('.')[0]
88 118
     texto=[]
119
+    if (args.lgc):
120
+        print ("Gerando código final")
89 121
     with open('intermediario.s','r') as f:
90
-        texto=f.readlines()
122
+        texto=f.read().splitlines()
91 123
     i=0
92 124
     final=[]
93 125
     db=[]
94 126
     msg=-1
95
-    final.append('format ELF64 executable 3')
96
-    final.append('segment readable executable')
97
-    final.append('entry main')
127
+    if (args.lgc):
128
+        print ("Gerando cabeçalho")
129
+    final.append(';flat assembler  version 1.73.02')
130
+    final.append(f';fasm {nome}.asm')
131
+    final.append(f';ld -lc -e main -dynamic-linker /lib/ld-linux.so.2  {nome}.o -o {nome} -m elf_i386')
132
+    final.append(';OS: Ubuntu 18.04.1 LTS x86_64 ')
133
+    final.append(';Kernel: 4.15.0-42-generic ')
134
+    final.append(';CPU: Intel i5-2520M (4) @ 3.200GHz\n')
135
+    final.append(f'format ELF')
136
+    final.append('public main as \'main\' ')
137
+    final.append('extrn \'exit\'as exit')
138
+    final.append('extrn \'printf\' as printf')
139
+    final.append('extrn \'scanf\'as scanf\n')
140
+
141
+    final.append('section \'.text\' executable')
142
+
98 143
     final.append('main:')
99 144
 
100 145
     while i < len(texto):
101
-        if 'ESCREVA' in texto[i]:
146
+        if (args.lgc):
147
+            print ("Gerando o comando escreva")
148
+        if 'INTEIRO' in texto[i].split()[0]:
149
+            db.append(f'{texto[i].split()[1]} dd 0')
150
+        if 'ESCREVA' in texto[i].split('"')[0]:
151
+            final.append(';Impressão na tela')
102 152
             if '"' in texto[i]:
103 153
                 msg += 1
104
-                size = texto[i].strip('ESCREVA')
105
-                size = size.strip('\n').replace('"','')
106
-                final.append(f'lea rdi, [msg{msg}]')
107
-                final.append(f'mov rax, {len(size)}')
108
-                final.append(f'mov rdx, rax')
109
-                final.append(f'mov rsi, rdi')
110
-                final.append(f'mov rdi, 1')
111
-                final.append(f'mov rax, 1')
112
-                final.append(f'syscall')
113
-                db.extend([f'msg{msg} db \'{size.strip()}\', 10,0'])
154
+                text = texto[i].split('ESCREVA')[1]
155
+                text= text.strip()
156
+                text= "".join(text)
157
+                text = text.replace('\"', '')
158
+                if (args.lgc):
159
+                    print ("Gerando comandos para o escrever uma mensagem")
160
+                final.append(f'push msg{msg}')
161
+                final.append(f'call printf')
162
+                final.append(f'add esp, 4\n')
163
+
164
+                txt=text.replace('\\n', '\',10,0,\'')
165
+                db.append(f'msg{msg} db \'{txt}\', 0,0')
114 166
             else:
115
-                print ()
167
+                if (args.lgc):
168
+                    print ("Gerando comandos para o escrever uma variavel")
169
+                expre = texto[i].split()
170
+                final.append(f'push {"["+expre[1]+"]" if expre[1].isidentifier() else expre[1] }')
171
+                final.append(f'push formatacao')
172
+                final.append(f'call printf')
173
+                final.append(f'add esp, 4\n')
174
+        if 'LEIA' in texto[i].split()[0]:
175
+            if (args.lgc):
176
+                print ("Gerando o comando leia")
177
+            final.append(';Ler do Teclado')
178
+            final.append(f'push {texto[i].split()[1]}')
179
+            final.append(f'push formatacao')
180
+            final.append(f'call scanf')
181
+            final.append(f'add esp, 8\n')
182
+        if 'if' in texto[i]:
183
+            '''
184
+            je - jump if op1 = op2 (op1 is "equal to" op2)
185
+            ja - jump if op1 > op2 (op1 is "above" op2)
186
+            jb - jump if op1 < op2 (op1 is "below" op2)
187
+            jae - jump if op1 >= op2 (op1 is "above or equal to" op2)
188
+            jbe - jump if op1 <= op2 (op1 is "below or equal to" op2) 
189
+            '''
190
+            if (args.lgc):
191
+                print ("Comando condicional/repetição identificado")
192
+                print ("Gerando os comandos condicões/repetição")
193
+            expre=texto[i].split()
194
+            final.append(';Label')
195
+            final.append(f'{expre[0]}')
196
+            #final.append(f'xor eax,eax')
197
+            final.append(f'xor ebx, ebx')
198
+            final.append(f'mov eax, {"["+expre[2]+"]" if expre[2].isidentifier() else expre[2] }')
199
+            final.append(f'mov ebx, {"["+expre[4]+"]" if expre[4].isidentifier() else expre[4] }')
200
+            final.append(f'cmp eax, ebx')
201
+            final.append(f'j{"ae" if ">=" is expre[3] else "be"} {expre[6]}')
202
+        if 'goto' in texto[i].split()[0]:
203
+            final.append(f'jmp {texto[i].split()[1]}')
204
+        if len(texto[i].split())<2:
205
+            final.append(f'{texto[i]}')
206
+        if len(texto[i].split())>2:
207
+            if (args.lgc):
208
+                print ("Comando de atribuição identificado")
209
+                print ("Gerando...")
210
+            if ':=' in texto[i].split()[1]:
211
+                expre = texto[i].split()
212
+                if len(expre)==3:
213
+                    if (args.lgc):
214
+                        print ("Comando de atribuição para com um valor")
215
+                        print ("Gerando...")
216
+                    final.append(f';Atribuição')
217
+                    final.append(f'mov eax,[{expre[0]}]')
218
+                    final.append(f'mov eax, {"["+expre[2]+"]" if expre[2].isidentifier() else expre[2] }')
219
+                    final.append(f'mov [{expre[0]}],eax')
220
+                    final.append(f'xor eax,eax\n')
221
+                elif '+' is expre[4]:
222
+                    if (args.lgc):
223
+                        print ("Comando de soma")
224
+                        print ("Gerando...")
225
+                    final.append(f';Adicção')
226
+                    final.append(f'mov eax, {"["+expre[2]+"]" if expre[2].isidentifier() else expre[2] }')
227
+                    final.append(f'mov edx, {"["+expre[3]+"]" if expre[3].isidentifier() else expre[3] }')
228
+                    final.append(f'add eax, edx')
229
+                    final.append(f'mov {"["+expre[0]+"]"}, eax')
230
+                    final.append(f'xor eax,eax\n')
231
+                elif '-' is expre[4]:
232
+                    if (args.lgc):
233
+                        print ("Comando de subtração")
234
+                        print ("Gerando...")
235
+                    final.append(f';Subtração')
236
+                    final.append(f'mov eax, {"["+expre[2]+"]" if expre[2].isidentifier() else expre[2] }')
237
+                    final.append(f'mov edx, {"["+expre[3]+"]" if expre[3].isidentifier() else expre[3] }')
238
+                    final.append(f'sub eax, edx')
239
+                    final.append(f'mov {"["+expre[0]+"]"}, eax')
240
+                    final.append(f'xor eax,eax\n')
241
+                elif '*' is expre[4]:
242
+                    if (args.lgc):
243
+                        print ("Comando de multiplicação")
244
+                        print ("Gerando...")
245
+                    final.append(f';Multiplicação')
246
+                    final.append(f'mov eax, {"[" + expre[2] + "]" if expre[2].isidentifier() else expre[2] }')
247
+                    final.append(f'mov edx, {"[" + expre[3] + "]" if expre[3].isidentifier() else expre[3] }')
248
+                    final.append(f'imul eax, edx')
249
+                    final.append(f'mov {"[" + expre[0] + "]"}, eax')
250
+                    final.append(f'xor eax,eax\n')
251
+                elif '/' is expre[4]:
252
+                    if (args.lgc):
253
+                        print ("Comando de divisão")
254
+                        print ("Gerando...")
255
+                    final.append(f';Divisao')
256
+                    final.append(f'xor edx, edx')
257
+                    final.append(f'mov ebx, {"[" + expre[2] + "]" if expre[2].isidentifier() else expre[2] }')
258
+                    final.append(f'mov eax, {"[" + expre[2] + "]" if expre[2].isidentifier() else expre[2] }')
259
+                    final.append(f'div ebx')
260
+                    final.append(f'mov {"[" + expre[0] + "]"}, eax')
261
+                    final.append(f'xor eax,eax\n')
262
+
116 263
         i+=1
117
-    final.append('xor rdi,rdi')
118
-    final.append('mov rax, 60')
119
-    final.append('syscall')
120
-    if(msg>-1):
121
-        final.append('segment readable writable')
264
+    final.append('sair:')
265
+    final.append('push 0')
266
+    final.append('call exit\n')
267
+
268
+    if(len(db)>0):
269
+        final.append('section \'.data\' writeable')
270
+        final.append('formatacao db \'%d\' , 0')
122 271
         final.extend(db)
123
-    with open('final.fasm','w') as f:
124
-        f.write('\n'.join(final))
272
+
273
+    with open(nome+'.asm','w') as f:
274
+        f.write('\n'.join(final))
275
+    import os
276
+    if args.lgc:
277
+        print (f"Compilando arquivo fonte: {args.filename}")
278
+    os.system(f'fasm {nome}.asm')
279
+    os.system(f'ld -lc -e main -dynamic-linker /lib/ld-linux.so.2  {nome}.o -o {nome} -m elf_i386')
280
+    if args.lgc:
281
+        print (f"Arquivo executavel pronto: {nome}")
282
+        print ("pronto")

+ 2
- 2
beuty.py View File

@@ -27,7 +27,7 @@ def separar(palavra):
27 27
             numero += word
28 28
     return (''.join(numero))
29 29
 
30
-def initsintatico(token, args):
30
+def initsintatico(token, args,erro):
31 31
     import os
32 32
     if not(os.path.isfile('dicionario1.dtc')and os.path.isfile('dicionario2.dtc')):
33 33
         save()
@@ -35,7 +35,7 @@ def initsintatico(token, args):
35 35
     from sintatico import analisadorsintatico
36 36
     dict_tabela1 = load("dicionario1.dtc")
37 37
     dict_tabela2 = load("dicionario2.dtc")
38
-    analisadorsintatico(dict_tabela1, dict_tabela2, token, args)
38
+    analisadorsintatico(dict_tabela1, dict_tabela2, token, args,erro)
39 39
 
40 40
 def load(filename):
41 41
     import pickle

+ 9
- 14
lexical.py View File

@@ -1,6 +1,6 @@
1 1
 import collections
2 2
 import re
3
-def tokenize(code,args):
3
+def tokenize(code,args,erro):
4 4
     token = collections.namedtuple('Token', ['tipo', 'lexema', 'linha', 'coluna'])
5 5
     token_especificacao = [
6 6
         ('inicio'       ,r'\{'), #inicio {
@@ -9,8 +9,8 @@ def tokenize(code,args):
9 9
         ('f_parentese'  ,r'\)'), #parentese de fechamento
10 10
         ('leia'         ,r'leia'), #leia
11 11
         ('escreva'      ,r'escreva'), #escreva
12
+        ('senao', r'senao'),  # senao
12 13
         ('se'           ,r'se'), #se
13
-        ('senao'        ,r'senao'), #senao
14 14
         ('enquanto'     ,r'enquanto'), #enquanto
15 15
         ('programa'     ,r'programa'), #programa
16 16
         ('fimprograma'  ,r'fimprograma'), #fimprograma
@@ -44,20 +44,15 @@ def tokenize(code,args):
44 44
         elif tipo == 'tab':
45 45
             pass
46 46
         elif tipo == 'ERRO':
47
-
48
-            from colorama import Fore, Style
49
-            t=Fore.CYAN+'########################################################'
50
-            print(t)
51
-            print(f'{valor!r} não esperado na linha {linha} e coluna {coluna}\a\a')
52
-            print(t)
53
-            print(f'Erro lexico')
54
-            args.lt=False
47
+            erro.append('########################################################')
48
+            erro.append(f'Erro lexico')
49
+            erro.append(f'{valor!r} não esperado na linha {linha} e coluna {coluna}')
55 50
             if valor == '"':
56
-                print(f'" de fechamento não encontrada'+Style.RESET_ALL)
51
+                erro.append(f'" de fechamento não encontrada')
57 52
             else:
58
-                print(f'caracter desconhecido')
59
-                print(Style.RESET_ALL)
53
+                erro.append(f'caracter desconhecido')
60 54
             pass
55
+
61 56
         coluna = mo.start() - linha_inicia
62 57
         if (tipo != 'ERRO') and (tipo != 'Linha') and (tipo != 'WS'):
63
-            yield token(tipo, valor, linha, coluna)
58
+            yield token(tipo, valor, linha, coluna)

+ 20
- 13
selection.py View File

@@ -1,19 +1,26 @@
1 1
 def opction(args):
2 2
     token = []
3
+    erro = []
3 4
     if args.tudo:
4 5
         args.lt=True
5 6
         args.ls=True
6 7
         args.lse=True
7 8
         args.lgc=True
8 9
     if args.lt:
9
-        vlt(args.filename,token,args)
10
+        vlt(args.filename,token,args,erro)
10 11
     else:
11
-        lt(args.filename,token,args)
12
-    ls(token,args)
13
-    lse(token,args)
14
-    lgc(token,args)
12
+        lt(args.filename,token,args,erro)
13
+    ls(token,args,erro)
14
+    lse(token,args,erro)
15
+    if len(erro)>0:
16
+        for e in erro:
17
+            print(e)
18
+        if (args.lgc):
19
+            print ("Não foi possivel iniciar a geração de código por causa de erro no código fonte.")
20
+    else:
21
+        lgc(token, args)
15 22
 
16
-def vlt(filename,token,args):
23
+def vlt(filename,token,args, erro):
17 24
     from lexical import tokenize
18 25
     print ('#' * 80)
19 26
     file = open(filename, "r")
@@ -21,24 +28,24 @@ def vlt(filename,token,args):
21 28
     file.close()
22 29
     print('{:15}'.format('Token'), '{:29}'.format('Lexema'), '{:10}'.format('Linha'), '{:10}'.format('Coluna'))
23 30
     i = 0
24
-    for tok in tokenize(arquivo,args):
31
+    for tok in tokenize(arquivo,args, erro):
25 32
         token.append(tok)
26 33
         print('{:15}'.format(token[i][0]), '{:20.11}'.format(token[i][1]), '{:10}'.format(token[i][2]),
27 34
               '{:10}'.format(token[i][3]))
28 35
         i += 1
29
-def lt(filename, token, args):
36
+def lt(filename, token, args, erro):
30 37
     from lexical import tokenize
31 38
     file = open(filename, "r")
32 39
     arquivo = file.read()
33 40
     file.close()
34
-    for tok in tokenize(arquivo,args):
41
+    for tok in tokenize(arquivo,args,erro):
35 42
         token.append(tok)
36
-def ls(token,args):
43
+def ls(token,args,erro):
37 44
     from beuty import initsintatico
38
-    initsintatico(token,args)
39
-def lse(token,args):
45
+    initsintatico(token,args,erro)
46
+def lse(token,args,erro):
40 47
     from semantico import semantico
41
-    semantico(token,args)
48
+    semantico(token,args,erro)
42 49
 def lgc(token,args):
43 50
     from  Geracaodecodigo import gerarcodigo
44 51
     gerarcodigo(token,args)

+ 51
- 28
semantico.py View File

@@ -1,19 +1,49 @@
1
-def semantico(token, args):
2
-    Avariaveis(token, args)
3
-def divisao(token, args, lista):
1
+def semantico(token, args, erro):
2
+    Avariaveis(token, args,erro)
3
+def divisao(token, args, lista,erro):
4 4
     linha = []
5
+    i=0
5 6
     if args.lse:
6 7
         print("Verificando Divisão por Zero.")
7
-
8
-def verificando(lista):
9
-    for exp in lista.values():
10
-        if 'î' not in exp:
8
+    while (i < len(token)):
9
+        if 'recebe' in token[i][0]:
10
+            j=i+1
11
+            variavel = token[i-1][1]
11 12
             try:
12
-                eval(''.join(exp))
13
-            except ZeroDivisionError:
14
-                from colorama import Style
15
-                Color()
16
-                print (f' Divisão por Zero {exp} '+ Style.RESET_ALL)
13
+                while not 'fim_linha' in token[j][0]:
14
+                    if (str(token[j][1][0])).isdigit():
15
+                        linha.append(str(token[j][1][0]))
16
+                    else:
17
+                        linha.append(token[j][1])
18
+                    j+=1
19
+            except IndexError:
20
+                break
21
+            if verificando(variavel, linha, lista, erro):
22
+                erro.append(f'linha:{token[i][2]}')
23
+            linha.clear()
24
+        i+=1
25
+
26
+def verificando(variavel, linha, lista,erro):
27
+    i=0
28
+    antigo=''.join(linha)
29
+    while i<len(linha):
30
+        if linha[i].isidentifier:
31
+            if linha[i] in lista:
32
+                linha[i]=lista[linha[i]]
33
+            else:
34
+                pass
35
+        i+=1
36
+    try:
37
+        expre=''.join(linha)
38
+        eval(expre)
39
+    except ZeroDivisionError:
40
+        erro.append('########################################################')
41
+        erro.append('Erro semantico:')
42
+        erro.append(f'Divisão por Zero {antigo}')
43
+        return 1
44
+    lista[variavel]=str(eval(''.join(linha)))
45
+    return 0
46
+
17 47
 def trocandoValores(lista,a,key):
18 48
     import re
19 49
     for exp in lista.keys():
@@ -21,7 +51,7 @@ def trocandoValores(lista,a,key):
21 51
             a=re.sub(r''+exp, (''.join(lista[exp])),''.join(a))
22 52
     lista[key] = ''.join(a)
23 53
 
24
-def Avariaveis(token, args):
54
+def Avariaveis(token, args,erro):
25 55
     variaveis = {}
26 56
     if args.lse:
27 57
         print ('#' * 80)
@@ -30,10 +60,11 @@ def Avariaveis(token, args):
30 60
     for var in token:
31 61
         if 'id' in var and var[2] == 2:
32 62
             if var[1] not in variaveis:
33
-                variaveis[var[1]] = 'î'
63
+                variaveis[var[1]] = '0'
34 64
             else:
35
-                Color()
36
-                print(f'\'{var[1]}\' declaração duplicada: ' + reset(var))
65
+                erro.append('########################################################')
66
+                erro.append('Erro semantico:')
67
+                erro.append(f'\'{var[1]}\' declaração duplicada: ')
37 68
 
38 69
     if args.lse:
39 70
         print("Variaveis declaradas: ")
@@ -44,15 +75,7 @@ def Avariaveis(token, args):
44 75
     for code in token:
45 76
         if 'id' in code:
46 77
             if not (code[1] in variaveis):
47
-                Color();
48
-                print(f'Variavel \'{code[1]}\' não declarado: ' + reset(code))
49
-    divisao(token, args, variaveis)
50
-
51
-def Color():
52
-    from colorama import Fore, Back
53
-    print(Fore.CYAN + 'Erro semantico:')
54
-
55
-
56
-def reset(linha):
57
-    from colorama import Style
58
-    return f'linha{linha[2]} : coluna{linha[3]}' + Style.RESET_ALL
78
+                erro.append('########################################################')
79
+                erro.append('Erro semantico:')
80
+                erro.append(f'Variavel \'{code[1]}\' não declarado: linha{code[2]} : coluna{code[3]}')
81
+    divisao(token, args, variaveis, erro)

+ 5
- 12
sintatico.py View File

@@ -1,4 +1,4 @@
1
-def analisadorsintatico(dict1, dict2, programa, args):
1
+def analisadorsintatico(dict1, dict2, programa, args,erro):
2 2
     pilha = ["<INICIO>"]#inicializa a pilha com o Não terminal inicial
3 3
     if args.ls : #Se verdadeiro mostra a mensagem a seguir
4 4
         print ('#'*80)
@@ -48,17 +48,10 @@ def analisadorsintatico(dict1, dict2, programa, args):
48 48
                 else:
49 49
                     # se top não for um não terminal ele apenas adciona o topo da pilha
50 50
                     a.extend(token[pilha[-1]])
51
-                from colorama import Fore, Style
52
-                t = Fore.CYAN +"Erro Sintatico ".upper()#imprimi bunitinho
53
-                print(t)
54
-                print(f"\'{programa[i][1]}\' inesperado linha {programa[i][2]}, coluna {programa[i][3]}")#
55
-                space = " "*int(programa[i][3])
56
-                texto = []
57
-                with open(args.filename, 'r') as f:
58
-                    for i in range(programa[i][2]):
59
-                        texto = f.readline()
60
-                print(texto+space+'^')
61
-                print(f"Era esperado: {' '.join(a)}"+Style.RESET_ALL)
51
+                erro.append('########################################################')
52
+                erro.append('Erro sintático')
53
+                erro.append(f"\'{programa[i-1][1]}\' inesperado linha {programa[i-1][2]}, coluna {programa[i-1][3]}")#
54
+                erro.append(f"Era esperado: {' '.join(a)}")
62 55
                 args.ls = False
63 56
                 break
64 57
     if args.ls:#Se for True imprime a mensagem

Loading…
Cancel
Save