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
 '''
1
 '''
2
     intermediario(token, argumentos, posicao inicial que deseja converter para assembler, posição final, valor inicial das Labels dos loops, texto final)
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
         if 'inteiro' in token[i][0]:
13
         if 'inteiro' in token[i][0]:
14
+            if (args.lgc):
15
+                print ("Inteiro identificado:")
10
             texto.extend(variaveis(token,i))
16
             texto.extend(variaveis(token,i))
11
         elif 'leia' in token[i][0]:
17
         elif 'leia' in token[i][0]:
18
+            if (args.lgc):
19
+                print ("leia identificado:")
12
             texto.append('LEIA '+token[i+2][1])
20
             texto.append('LEIA '+token[i+2][1])
13
         elif 'escreva' in token[i][0]:
21
         elif 'escreva' in token[i][0]:
22
+            if (args.lgc):
23
+                print ("escreva identificado:")
14
             texto.append('ESCREVA '+ token[i+2][1])
24
             texto.append('ESCREVA '+ token[i+2][1])
15
         elif 'recebe' in token[i][0]:
25
         elif 'recebe' in token[i][0]:
26
+            if (args.lgc):
27
+                print ("Atribuição identificada:")
16
             exp=[]
28
             exp=[]
17
             from infixtoposfix import infixToPostfix
29
             from infixtoposfix import infixToPostfix
18
             exp.append(infixToPostfix(expressao(token, i)))
30
             exp.append(infixToPostfix(expressao(token, i)))
19
             simpleexpre(exp,token[i-1][1],texto)
31
             simpleexpre(exp,token[i-1][1],texto)
20
         elif 'enquanto' in token[i][0]:
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
         elif 'se' == token[i][0]:
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
         elif '}' in token[i][1]:
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
         i=i+1
62
         i=i+1
35
 
63
 
36
     with open('intermediario.s','w') as f:
64
     with open('intermediario.s','w') as f:
65
+        if (args.lgc):
66
+            print ("Escrevendo no arquivo:")
37
         f.write('\n'.join(texto))
67
         f.write('\n'.join(texto))
38
 def simpleexpre(exp,var,texto):
68
 def simpleexpre(exp,var,texto):
39
     '''
69
     '''
41
     SUB dest,src1,src2	dest = src1 - src2
71
     SUB dest,src1,src2	dest = src1 - src2
42
     ADDI dest,src1,I	dest = src1 + I
72
     ADDI dest,src1,I	dest = src1 + I
43
     MUL dest,src1,src2	dest = src1 × src2
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
     t=1
76
     t=1
47
     exp=exp[0].split()
77
     exp=exp[0].split()
78
         l+=1
108
         l+=1
79
     return var
109
     return var
80
 def gerarcodigo(token,args):
110
 def gerarcodigo(token,args):
81
-    texto=[]
82
     '''
111
     '''
83
     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)
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
     texto=[]
118
     texto=[]
119
+    if (args.lgc):
120
+        print ("Gerando código final")
89
     with open('intermediario.s','r') as f:
121
     with open('intermediario.s','r') as f:
90
-        texto=f.readlines()
122
+        texto=f.read().splitlines()
91
     i=0
123
     i=0
92
     final=[]
124
     final=[]
93
     db=[]
125
     db=[]
94
     msg=-1
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
     final.append('main:')
143
     final.append('main:')
99
 
144
 
100
     while i < len(texto):
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
             if '"' in texto[i]:
152
             if '"' in texto[i]:
103
                 msg += 1
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
             else:
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
         i+=1
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
         final.extend(db)
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
             numero += word
27
             numero += word
28
     return (''.join(numero))
28
     return (''.join(numero))
29
 
29
 
30
-def initsintatico(token, args):
30
+def initsintatico(token, args,erro):
31
     import os
31
     import os
32
     if not(os.path.isfile('dicionario1.dtc')and os.path.isfile('dicionario2.dtc')):
32
     if not(os.path.isfile('dicionario1.dtc')and os.path.isfile('dicionario2.dtc')):
33
         save()
33
         save()
35
     from sintatico import analisadorsintatico
35
     from sintatico import analisadorsintatico
36
     dict_tabela1 = load("dicionario1.dtc")
36
     dict_tabela1 = load("dicionario1.dtc")
37
     dict_tabela2 = load("dicionario2.dtc")
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
 def load(filename):
40
 def load(filename):
41
     import pickle
41
     import pickle

+ 9
- 14
lexical.py View File

1
 import collections
1
 import collections
2
 import re
2
 import re
3
-def tokenize(code,args):
3
+def tokenize(code,args,erro):
4
     token = collections.namedtuple('Token', ['tipo', 'lexema', 'linha', 'coluna'])
4
     token = collections.namedtuple('Token', ['tipo', 'lexema', 'linha', 'coluna'])
5
     token_especificacao = [
5
     token_especificacao = [
6
         ('inicio'       ,r'\{'), #inicio {
6
         ('inicio'       ,r'\{'), #inicio {
9
         ('f_parentese'  ,r'\)'), #parentese de fechamento
9
         ('f_parentese'  ,r'\)'), #parentese de fechamento
10
         ('leia'         ,r'leia'), #leia
10
         ('leia'         ,r'leia'), #leia
11
         ('escreva'      ,r'escreva'), #escreva
11
         ('escreva'      ,r'escreva'), #escreva
12
+        ('senao', r'senao'),  # senao
12
         ('se'           ,r'se'), #se
13
         ('se'           ,r'se'), #se
13
-        ('senao'        ,r'senao'), #senao
14
         ('enquanto'     ,r'enquanto'), #enquanto
14
         ('enquanto'     ,r'enquanto'), #enquanto
15
         ('programa'     ,r'programa'), #programa
15
         ('programa'     ,r'programa'), #programa
16
         ('fimprograma'  ,r'fimprograma'), #fimprograma
16
         ('fimprograma'  ,r'fimprograma'), #fimprograma
44
         elif tipo == 'tab':
44
         elif tipo == 'tab':
45
             pass
45
             pass
46
         elif tipo == 'ERRO':
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
             if valor == '"':
50
             if valor == '"':
56
-                print(f'" de fechamento não encontrada'+Style.RESET_ALL)
51
+                erro.append(f'" de fechamento não encontrada')
57
             else:
52
             else:
58
-                print(f'caracter desconhecido')
59
-                print(Style.RESET_ALL)
53
+                erro.append(f'caracter desconhecido')
60
             pass
54
             pass
55
+
61
         coluna = mo.start() - linha_inicia
56
         coluna = mo.start() - linha_inicia
62
         if (tipo != 'ERRO') and (tipo != 'Linha') and (tipo != 'WS'):
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
 def opction(args):
1
 def opction(args):
2
     token = []
2
     token = []
3
+    erro = []
3
     if args.tudo:
4
     if args.tudo:
4
         args.lt=True
5
         args.lt=True
5
         args.ls=True
6
         args.ls=True
6
         args.lse=True
7
         args.lse=True
7
         args.lgc=True
8
         args.lgc=True
8
     if args.lt:
9
     if args.lt:
9
-        vlt(args.filename,token,args)
10
+        vlt(args.filename,token,args,erro)
10
     else:
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
     from lexical import tokenize
24
     from lexical import tokenize
18
     print ('#' * 80)
25
     print ('#' * 80)
19
     file = open(filename, "r")
26
     file = open(filename, "r")
21
     file.close()
28
     file.close()
22
     print('{:15}'.format('Token'), '{:29}'.format('Lexema'), '{:10}'.format('Linha'), '{:10}'.format('Coluna'))
29
     print('{:15}'.format('Token'), '{:29}'.format('Lexema'), '{:10}'.format('Linha'), '{:10}'.format('Coluna'))
23
     i = 0
30
     i = 0
24
-    for tok in tokenize(arquivo,args):
31
+    for tok in tokenize(arquivo,args, erro):
25
         token.append(tok)
32
         token.append(tok)
26
         print('{:15}'.format(token[i][0]), '{:20.11}'.format(token[i][1]), '{:10}'.format(token[i][2]),
33
         print('{:15}'.format(token[i][0]), '{:20.11}'.format(token[i][1]), '{:10}'.format(token[i][2]),
27
               '{:10}'.format(token[i][3]))
34
               '{:10}'.format(token[i][3]))
28
         i += 1
35
         i += 1
29
-def lt(filename, token, args):
36
+def lt(filename, token, args, erro):
30
     from lexical import tokenize
37
     from lexical import tokenize
31
     file = open(filename, "r")
38
     file = open(filename, "r")
32
     arquivo = file.read()
39
     arquivo = file.read()
33
     file.close()
40
     file.close()
34
-    for tok in tokenize(arquivo,args):
41
+    for tok in tokenize(arquivo,args,erro):
35
         token.append(tok)
42
         token.append(tok)
36
-def ls(token,args):
43
+def ls(token,args,erro):
37
     from beuty import initsintatico
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
     from semantico import semantico
47
     from semantico import semantico
41
-    semantico(token,args)
48
+    semantico(token,args,erro)
42
 def lgc(token,args):
49
 def lgc(token,args):
43
     from  Geracaodecodigo import gerarcodigo
50
     from  Geracaodecodigo import gerarcodigo
44
     gerarcodigo(token,args)
51
     gerarcodigo(token,args)

+ 51
- 28
semantico.py View File

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
     linha = []
4
     linha = []
5
+    i=0
5
     if args.lse:
6
     if args.lse:
6
         print("Verificando Divisão por Zero.")
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
             try:
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
 def trocandoValores(lista,a,key):
47
 def trocandoValores(lista,a,key):
18
     import re
48
     import re
19
     for exp in lista.keys():
49
     for exp in lista.keys():
21
             a=re.sub(r''+exp, (''.join(lista[exp])),''.join(a))
51
             a=re.sub(r''+exp, (''.join(lista[exp])),''.join(a))
22
     lista[key] = ''.join(a)
52
     lista[key] = ''.join(a)
23
 
53
 
24
-def Avariaveis(token, args):
54
+def Avariaveis(token, args,erro):
25
     variaveis = {}
55
     variaveis = {}
26
     if args.lse:
56
     if args.lse:
27
         print ('#' * 80)
57
         print ('#' * 80)
30
     for var in token:
60
     for var in token:
31
         if 'id' in var and var[2] == 2:
61
         if 'id' in var and var[2] == 2:
32
             if var[1] not in variaveis:
62
             if var[1] not in variaveis:
33
-                variaveis[var[1]] = 'î'
63
+                variaveis[var[1]] = '0'
34
             else:
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
     if args.lse:
69
     if args.lse:
39
         print("Variaveis declaradas: ")
70
         print("Variaveis declaradas: ")
44
     for code in token:
75
     for code in token:
45
         if 'id' in code:
76
         if 'id' in code:
46
             if not (code[1] in variaveis):
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
-def analisadorsintatico(dict1, dict2, programa, args):
1
+def analisadorsintatico(dict1, dict2, programa, args,erro):
2
     pilha = ["<INICIO>"]#inicializa a pilha com o Não terminal inicial
2
     pilha = ["<INICIO>"]#inicializa a pilha com o Não terminal inicial
3
     if args.ls : #Se verdadeiro mostra a mensagem a seguir
3
     if args.ls : #Se verdadeiro mostra a mensagem a seguir
4
         print ('#'*80)
4
         print ('#'*80)
48
                 else:
48
                 else:
49
                     # se top não for um não terminal ele apenas adciona o topo da pilha
49
                     # se top não for um não terminal ele apenas adciona o topo da pilha
50
                     a.extend(token[pilha[-1]])
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
                 args.ls = False
55
                 args.ls = False
63
                 break
56
                 break
64
     if args.ls:#Se for True imprime a mensagem
57
     if args.ls:#Se for True imprime a mensagem

Loading…
Cancel
Save