def consume_command(self): opcode = self.current_opcode = self.next_byte() command = self.get_matching_command(opcode) self.pending_tokens.append(token("address", self.program_counter)) self.pending_tokens.append(token("opcode", command.mnemonic)) for operand in command.operands: self.consume_operand(operand) self.pending_tokens.append(token("eoi")) self.tokens.extend(self.pending_tokens) self.pending_tokens = [] self.leftover_bytes = []
def consume_operand(self, operand): terminal = operand if operand == "addr11": address = (self.current_opcode & 0b11100000) << 3 address += self.next_byte() value = address elif operand == "addr16": address = self.next_byte() << 8 address += self.next_byte() value = address elif operand == "register": register = self.current_opcode & 0b00000111 value = register elif operand == "a": terminal = "sfr" value = "a" elif operand == "bit": value = self.next_byte() elif operand == "offset": value = self.next_byte() elif operand == "imm8": terminal = "immediate" value = self.next_byte() elif operand == "indirect": value = self.current_opcode & 0b00000001 else: raise Exception("Unknown operand {}".format(operand)) self.pending_tokens.append(token(terminal, value))
def isApproved(self, token_name): token_contract = token(token_name, web3).createContract() max_amount = self.MAX_APPROVAL_INT approved_amount = token_contract.functions.allowance( self.account, self.urouter_address).call() if approved_amount == max_amount: return True else: return False
def consume_byte_source(self): while True: try: self.consume_command() except ByteSourceExhausted: if self.pending_tokens: address_token = self.pending_tokens[0] assert address_token.terminal is "address" self.tokens.append(address_token) for byte in self.leftover_bytes: self.tokens.append(token("raw_byte", byte)) self.pending_tokens = [] self.leftover_bytes = [] break
def approve(self, token_name): nonce = web3.eth.getTransactionCount(self.account) my_token = token(token_name, web3) contract = my_token.createContract() spender = self.urouter_address max_amount = self.MAX_APPROVAL_INT tx = contract.functions.approve(spender, max_amount).buildTransaction({ 'nonce': nonce, 'from': self.account, 'gasPrice': self.gasPrice, 'gas': self.gasLimit }) signed_tx = web3.eth.account.signTransaction(tx, self.pkey) tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction) return tx_hash
async def reload_cog(ctx, extension): try: for _ in range(2): bot.unload_extension(f'Command.{extension.capitalize()}') bot.load_extension(f'Command.{extension.capitalize()}') await ctx.send(f'{extension} recarregada com sucesso!') except Exception as e: print(e) await ctx.send(f'Erro em recarregar {extension.capitalize()}.') @bot.command(name='reload_all') @Checks.is_owner() async def reload_cog_all(ctx): try: for filename in os.listdir('./Command'): if filename.endswith('.py'): bot.unload_extension(f'Command.{filename[:-3]}') bot.load_extension(f'Command.{filename[:-3]}') await ctx.send('Extensões carregadas com sucesso') except Exception as e: print(e) await ctx.send('Erro em recarregar as extensões.') for filename in os.listdir('./Command'): if filename.endswith('.py'): bot.load_extension(f'Command.{filename[:-3]}') bot.run(token())
def structureOptions(current): # Definindo que as variáveis globais podem ser modificadas dentro do escopo global state global lexem global row global column global i # Loop infinito até que retorne um estado ou token while 1: if state == 1: if current == ' ' or current == '\t' or current == '\n' or current == '\r': break elif current.isdigit(): lexem += current state = 13 break elif current.isalpha(): lexem += current state = 16 break elif current == '=': state = 2 break elif current == '!': state = 3 break elif current == '>': state = 4 break elif current == '<': state = 5 break # Retornando Token do símbolo de adição elif current == '+': state = 1 return token("OP_AD", "+", row, column) # Retornando Token do símbolo de subtração elif current == '-': state = 1 return token("OP_MIN", "-", row, column) # Retornando Token do símbolo de multiplicação elif current == "*": state = 1 return token("OP_MUL", "*", row, column) # Retornando Token do símbolo de ponto e vírgula elif current == ';': state = 1 return token("SMB_SEM", ";", row, column) # Retornando Token do símbolo de vírgula elif current == ',': state = 1 return token("SMB_COM", ",", row, column) # Retornando Token do símbolo de abre parênteses elif current == '(': state = 1 return token("SMB_OPA", "(", row, column) # Retornando Token do símbolo de fecha parênteses elif current == ')': state = 1 return token("SMB_CPA", ")", row, column) # Retornando Token do símbolo de abre chaves elif current == '{': state = 1 return token("SMB_OBC", "{", row, column) # Retornando Token do símbolo de fecha chaves elif current == '}': state = 1 return token("SMB_CBC", "}", row, column) elif current == "'": state = 6 break elif current == '"': state = 8 break elif current == '/': state = 9 break # Retornando Token de erro léxico else: state = 1 return ErrorMessage("LEXIC ERROR", "Unknown character", row, column) break if state == 2: # Retonando Token do símbolo de igual igual if current == '=': state = 1 return token("OP_EQ", "==", row, column) # Retornando Token do símbolo de atribuição igual else: state = 1 i -= 1 column -= 1 return token("OP_ASS", "=", row, column) if state == 3: # Retornando Token do símbolo de diferente if current == '=': state = 1 return token("OP_NE", "!=", row, column) # Retornando Token de erro léxico else: state = 1 return ErrorMessage("LEXIC ERROR", "incomplete token", row, column) if state == 4: # Retornando Token do símbolo de maior igual if current == '=': state = 1 return token("OP_GE", ">=", row, column) # Retornando Token do símbolo de maior else: state = 1 i -= 1 column -= 1 return token("OP_GT", ">", row, column) if state == 5: # Retornando Token do símbolo de menor igual if current == '=': state = 1 return token("OP_LE", "<=", row, column) # Retornando Token do símbolo de menor else: state = 1 i -= 1 column -= 1 return token("OP_LT", "<", row, column) if state == 6: if current.isalpha: lexem += current state = 7 break # Retornando Token de erro léxico else: state = 1 return ErrorMessage("LEXIC ERROR", "Expecting character", row, column) if state == 7: # Retornando Token de char if current == "'": state = 1 tokenHelper = token("CON_CHAR", lexem, row, column) lexem = '' return tokenHelper # Retornando Token de erro léxico else: state = 1 return ErrorMessage("LEXIC ERROR", "Expecting character", row, column) if state == 8: # Retornando Token de string if current == '"': state = 1 tokenHelper = token("LIT", lexem, row, column) lexem = '' return tokenHelper elif current == '\n': return ErrorMessage("LEXIC ERROR", "Expecting character", row, column) else: lexem += current state = 8 break if state == 9: if current == '/': state = 10 break elif current == '*': state = 11 break else: state = 1 return token("OP_DIV", "/", row, column) if state == 10: if current != '\n': state = 10 break else: state = 1 if state == 11: if current == '*': state = 12 return None else: state = 11 return None if state == 12: if current == '/': state = 1 break elif current == '*': state = 12 return None else: state = 11 return None if state == 13: if current.isdigit(): lexem += current state = 13 break elif current == '.': lexem += current state = 14 break # Retornando Token de um inteiro else: state = 1 tokenHelper = token("CON_NUM", lexem, row, column) i -= 1 column -= 1 lexem = '' return tokenHelper if state == 14: if current.isdigit(): lexem += current state = 15 break # Retornando Token de um número decimal else: state = 1 i -= 1 column -= 1 lexem = lexem.replace('.', '') tokenHelper = token("CON_NUM", lexem, row, column) lexem = '' return tokenHelper if state == 15: if current.isdigit(): lexem += current state = 15 break # Retornando Token de um número decimal else: state = 1 i -= 1 column -= 1 tokenHelper = token("CON_NUM", lexem, row, column) lexem = '' return tokenHelper if state == 16: if current.isalpha() or current.isdigit(): lexem += current state = 16 break # Retornando Token de uma variável else: state = 1 column -= 1 tokenHelper = token("ID", lexem, row, column) lexem = '' return tokenHelper
tokenHelper = structureOptions(line[i]) # Testa se o token não está vazio if tokenHelper != None: # Se o token for do tipo ID, verifica se ele está na tabela de símbolos, se não estiver adiciona if tokenHelper.getTag() == "ID": print(Ts.getToken(tokenHelper)) Ts.addSymbolTable(tokenHelper) # Verifica se o token tem um erro léxico e exibe ele elif tokenHelper.getTag() == "LEXIC_ERROR": print(tokenHelper) # Se não entrar nas outras condições apenas exibe else: i += 1 print(tokenHelper) else: i += 1 # Verifica se teve o último token, caso não, retorna erro (Resolvendo problema de comentário não fechando antes do EOF) if tokenHelper == None: print(ErrorMessage("LEXIC ERROR", "Expecting character", row, column)) # Exibe o token de final de arquivo print(token("EOF", "EOF", row, column + 1)) # Exibindo a tabela de símbolos #print("\nTABELA DE SIMBOLOS") #print(Ts)
def __init__(self): self.symbolTable.append(token("KW", "program", 0, 0)) self.symbolTable.append(token("KW", "if", 0, 0)) self.symbolTable.append(token("KW", "else", 0, 0)) self.symbolTable.append(token("KW", "while", 0, 0)) self.symbolTable.append(token("KW", "write", 0, 0)) self.symbolTable.append(token("KW", "read", 0, 0)) self.symbolTable.append(token("KW", "num", 0, 0)) self.symbolTable.append(token("KW", "char", 0, 0)) self.symbolTable.append(token("KW", "not", 0, 0)) self.symbolTable.append(token("KW", "or", 0, 0)) self.symbolTable.append(token("KW", "and", 0, 0))
def getToken(self, tokenAux): for tsToken in self.symbolTable: if tokenAux.getValue() == tsToken.getValue(): return token(tokenAux.getTag(), tokenAux.getValue(), tokenAux.getRow(), tokenAux.getColumn()) return tokenAux