def main(): # 主机名 ip 序列号 ipall_dict = {} for x in xrange(1, 2): ip_msg = [] ip = "10.10.10.%d" % x # 获取连接对象 agent = ssh_agent.SSHAgent().ssh(ip) # 执行相关的命令, 定义好的命令 cmd = command.Command(agent) results = cmd.load() print "#######################" print results print "#######################" # 执行解析, 注意每个命令的结果不一样,需要不同的解析方式 ps = mparser.Parser(cmd) res_parse = ps.parse() print "#######################" print res_parse print "#######################" # 存储结果,可以是文本,数据库,其他 st = store.Store(ps) st.store()
def main(): #Untuk Membaca file test secara langsung content = "" with open('test.lang', 'r') as file: content = file.read() #print(content) #memanggil kelas lexer dan initiliazed lex = lexer.Lexer(content) tokens = lex.token() parse = mparser.Parser(tokens) parse.parse()
def process(self, option_file): try: ast = mparser.Parser(open(option_file, 'r').read()).parse() except coredata.MesonException as me: me.file = option_file raise me if not isinstance(ast, mparser.CodeBlockNode): e = OptionException('Option file is malformed.') e.lineno = ast.lineno() raise e for cur in ast.lines: try: self.evaluate_statement(cur) except Exception as e: e.lineno = cur.lineno e.colno = cur.colno e.file = os.path.join('meson_options.txt') raise e
def main(): # read the current main source code in test.lang and store it in variable content = "" with open('m.Lang', 'r') as file: content = file.read() # print(content) ################## Lexar ######################## # we call the lexer class and initialize it with the source code lex = lexer.Lexer(content) # we now call the tokenize method tokens = lex.tokenize() ################### Parse ###################### parse = mparser.Parser(tokens) parse.parse() print('mLang start')
def main(): arguments_length = len(sys.argv) if arguments_length == 1: import p_shell p_shell.shell() arg = sys.argv if arg[1] in ["--version", "-V"]: print('Pulzar', __version__) quit() #If file doesnt have .plz file extension, it will raise an error if arg[1][-4:] != ".plz": print("FileError at file '{}':\nMust be .plz file".format(arg[1])) quit() # Looks for second argument elif arguments_length == 2: with open(arg[1], "r") as f: code = f.read() #Lexer lex = lexer.Lexer(code) tokens = lex.tokenize() #Parser parse = mparser.Parser(tokens, False) ast = parse.parse(tokens) if ast[2] == True: # There was an error quit() obj = generator.Generation( ast[0], ast[1], False, arg[1] ) # 1 parameter: ast; 2 parameter: isConsole (True or False) gen = obj.generate() exec(gen) return elif arguments_length > 2 and arg[arguments_length - 1] in ["-t", "--tools"]: with open(arg[1], "r", encoding="utf-8") as f: code = f.read() print("ORIGINAL CODE:") print(code) #Lexer print("-------------- LEXICAL ANALYSYS ---------------------\n") lex = lexer.Lexer(code) tokens = lex.tokenize() print(tokens) #Parser print(22 * "-" + " PARSER " + 22 * "-") parse = mparser.Parser(tokens, True) ast = parse.parse(tokens) if ast[2] == True: # There was an error return print("Abstract Syntax Tree:") print(ast[0]) print(17 * "-" + "CODE GENERATION" + 18 * "-") obj = generator.Generation( ast[0], ast[1], False, arg[1]) # 1 parameter: ast; 2 parameter: isConsole (True or False) gen = obj.generate() print(gen) print("#" * 21, "OUTPUT", "#" * 21) exec(gen) return elif arguments_length > 2 and ("-c" in sys.argv or "--compile" in sys.argv ) and ("-t" not in sys.argv or "--tools" not in sys.argv): import subprocess with open(arg[1], "r", encoding="utf-8") as f: code = f.read() print("ORIGINAL CODE:") print(code) # Lexer print("-------------- LEXICAL ANALYSYS ---------------------\n") lex = lexer.Lexer(code) tokens = lex.tokenize() print(tokens) # Parser print(22 * "-" + " PARSER " + 22 * "-") parse = mparser.Parser(tokens, True) ast = parse.parse(tokens) if ast[2] == True: return print("Abstract Syntax Tree:") print(ast[0]) print(17 * "-" + "CODE GENERATION" + 18 * "-") obj = generator.Generation( ast[0], ast[1], True, arg[1]) # 1 parameter: ast; 2 parameter: isConsole (True or False) gen = obj.generate() print(gen) print("#" * 21, "OUTPUT", "#" * 21) f = open(arg[1][:-4] + ".cpp", 'w') f.write(gen) f.close() if subprocess.call([ "g++", f"{arg[1][:-4]}.cpp", "-o", f"{arg[1][:-4]}" ]) == 0: #If there is no compilation error of generated c++ code if "-r" in sys.argv or "--run" in sys.argv: PATH = os.getcwd() filename = arg[1][:-4].split('/') os.chdir("".join([str(i) + "/" for i in filename[:-1]])) if platform.system() == 'Windows': subprocess.call([f"{filename[-1]}.exe"], shell=True) else: subprocess.call([f"{filename[-1]}.out"], shell=True) os.system(f"cd {PATH}") else: print("Compilation successful") else: print("Compilation errors")
def main(): print(' ________________________________________ ') print('| ___ ____ _ _ ____ |') print('| |__] |__| |\/| [__ |') print('| | | | | | ___] |') print('|________________________________________|') print('|___________v 1.1 (29/10/2019)___________|') print('|_____Por: Alejandro Aguilar Frausto_____|') print('|________________________________________|') #------------------------------------ # Lectura de archivo #------------------------------------ archivoEncontrado = False while not archivoEncontrado: archivo = input("\nNombre de archivo a traducir (.pams):\n ") if not '.pams' in archivo: archivo += '.pams' try: with open(archivo, 'r') as file: fuente = file.read() archivoEncontrado = True except: print("Archivo inválido o no encontrado. Verifique que se encuentre entest la carpeta raíz de este script y la extensión '.pams' corresponda.") print('\n||||||||||||||||||||| ENTRADA ||||||||||||||||||||| \n') print(fuente) print('\n||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') # -------------------------------------- # LEXER # -------------------------------------- print('||||||||||||||||||||| LEXER LOG ||||||||||||||||||||| \n') lex = lexer.Lexer() tokens = lex.generarTokens(fuente) print(*tokens, sep = "\n") print('\n||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') # -------------------------------------- # PARSER # -------------------------------------- print('||||||||||||||||||||| PARSER LOG |||||||||||||||||||| \n') Parser = parser.Parser(tokens) source_ast = Parser.parse(tokens) print(source_ast) print('\n||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') # -------------------------------------- # Generacion de Código Traducido # -------------------------------------- generador_codigo = objgen.generadorObjetos(source_ast) exec_string = generador_codigo.identifica_objetos() # -------------------------------------- # Salida a Python # -------------------------------------- print('||||||||||||||||||| CODIGO TRADUCIDO |||||||||||||||||| \n') print(exec_string) print('\n|||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') # -------------------------------------- # Ejecución # -------------------------------------- print('||||||||||||||||||||||| EJECUCIÓN |||||||||||||||||||||||| \n') exec(exec_string) print('\n|||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') # -------------------------------------- # Generacion de archivo de python # -------------------------------------- print('\n|||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') archivo = archivo.replace('.pams', '') f = open(archivo + ".py", "w") f.write(exec_string) f.close() print("Archivo '" + archivo + ".py' creado con exito") print('\n|||||||||||||||||||||||||||||||||||||||||||||||||||||||| \n') input("")
def shell(): init(convert=True) print(Fore.WHITE + "(c) Brian Turza 2018 - 20 Pulzar v0.4\n ") print(Fore.WHITE + "Welcome to \n") print(Fore.GREEN, result) print(Fore.WHITE + "Type 'help()' for more information") symbol_tree = "" stack = "" command = "" def checkAssignment(command): for token in command.split(): if token == "=": return True return False while command != "exit()" or command != "quit()": command = input(">") if command == "": continue if command in ["help", "help()"]: print("basic bulitin functions:") print("echo - prints value or text with new line") print("print - To print value or text without new line") print("system - equivalent to os.system from python") print("----------------------------------------------") print("list of keywords:") print("if\nelseif\nelse\nfor\nwhile\nfunc\nclass\n") print("Exit screen by commands exit or exit()") print("for more open https://docs.pulzar.org") elif command == "symbol_tree()": print(symbol_tree) elif command == "exit" or command == "exit()" or command == "quit()": quit() else: if "var" in command or "str" in command or "int" in command or "bool" in command or "complex" in command: lex = lexer.Lexer(f"Program Console;\n{command}") tokens = lex.tokenize() # Parser parse = mparser.Parser(tokens, False) ast = parse.parse(tokens) error = ast[2] if error == False: symbol_tree += command + "\n" elif checkAssignment(command) == True: symbol_tree += command + "\n" elif "func" in command and "{" in command: temp = "" while temp != "}": temp = input(" ") command += "\n" + temp stack += command + "\n" elif "if" in command or "elseif" in command or "else" in command or "for" in command or "while" in command: temp = "" while temp != "}": temp = input(" ") command += "\t" + temp + "\n" code = f"Program Console;\n{symbol_tree}{stack}{command}" lex = lexer.Lexer(code) tokens = lex.tokenize() # Parser parse = mparser.Parser(tokens, False) ast = parse.parse(tokens) error = ast[2] if error == False: obj = generator.Generation(ast[0], ast[1], False, '') gen = obj.generate() try: # mycode exec(gen) except Exception as exc: print(gen) print("Error at line 1:") print(exc) else: def checkExpression(command): math_sym = "0123456789" + "".join( [operator for operator in constants.OPERATORS]) for symbol in command.split(): if symbol in constants.KEYWORDS or symbol in constants.BUILT_IN or symbol == "=": return False elif isinstance(symbol, str) or isinstance( symbol, list ) or symbol in math_sym or symbol in constants.SPECIAL_OPERATORS: continue return True if checkExpression(command): command = f"echo {command}" code = "Program Console;\n" + symbol_tree + stack + command # Lexer lex = lexer.Lexer(code) tokens = lex.tokenize() # Parser parse = mparser.Parser(tokens, False) ast = parse.parse(tokens) error = ast[2] if error == False: obj = generator.Generation(ast[0], ast[1], False, '') gen = obj.generate() try: # mycode exec(gen) except Exception as exc: print("Error at line 1:") print(exc)