def run_typecheck_test(test, compiler: Compiler) -> bool: astparser = Parser() ast = compiler.parse(test, astparser) if len(astparser.errors) > 0: return False tc = TypeChecker() compiler.visit(ast, tc) ast_json = ast.toJSON() with test.with_suffix(".py.ast.typed").open("r") as f: correct_json = json.load(f) return ast_equals(ast_json, correct_json)
def start(self): # print(self.stmts().stmt1.block) s = self.stmts() # begin = s.newlabel() # after = s.newlabel() # s.emitlabel(begin) # s.gen(begin, after) # s.emitlabel(after) # print(self.top.__dict__) # Print tree print('\nTREE') print(str(s.__dict__)) compiler = Compiler(self.top, s) compiler.compile()
def run_code(text): """text should be a valid c program, code runner will compile and run the program and return its output run code will throw any exceptions thrown by the compilation attempt if it fails The code will receive no input for the run and should output to std.out""" lex = Lexer(text) pars = Parser(lex) comp = Compiler(pars) asm_code = comp.compile() directory_path = os.path.dirname(os.path.realpath(__file__)) os.chdir(directory_path) asm_file_name = 'temp_asm_file.asm' obj_file_name = 'temp_asm_file.obj' executable_file_name = "output_executable.exe" asm_file = open(asm_file_name, 'w') asm_file.write(asm_code) asm_file.close() p = subprocess.Popen(["nasm", "-fwin32", asm_file_name], stdout=subprocess.PIPE) out, err = p.communicate() time.sleep(.5) p = subprocess.Popen([ "gcc", "-m32", obj_file_name, "-o", os.path.join(directory_path, executable_file_name) ], stdout=subprocess.PIPE) out, err = p.communicate() time.sleep(.5) p = subprocess.Popen([os.path.join(directory_path, executable_file_name)], stdout=subprocess.PIPE) out, err = p.communicate() time.sleep(.5) out = out.decode("utf-8") return out
def main(): compiler = Compiler() compiler.compile(code) print("-------- Original ---------") print(compiler.lang_ast()) print("\n-------- __main__ ---------") print(compiler.c_ast()) with open("test.cc", "w") as f: f.write(str(compiler.c_ast())) for fname in compiler.generated_files(): print("\n-------- {} ---------".format(fname)) with open(fname, "r") as f: print(f.read())
def run_parse_test(test, compiler: Compiler, bad=True) -> bool: # if bad=True, then test cases prefixed with bad are expected to fail astparser = Parser() ast = compiler.parse(test, astparser) # check that parsing error exists if bad and test.name.startswith("bad"): return len(astparser.errors) > 0 if len(astparser.errors) > 0: return False ast_json = ast.toJSON() try: with test.with_suffix(".py.ast").open("r") as f: correct_json = json.load(f) return ast_equals(ast_json, correct_json) except: with test.with_suffix(".py.ast.typed").open("r") as f: correct_json = json.load(f) return ast_equals(ast_json, correct_json)
def __init__(self, program=None): self._indput = {} self._output = {f'o': 0 for k in range(1)} self._registers = {f'r{k}': 0 for k in range(15)} self._pc = 0 self._no_inst = 0 self._program = [] self.mips_len = None if program: mips = Compiler().compile(program) self.parse(mips) self.mips_len = len(self._program) print() print("================================================") print(program) print("------------------------------------------------") print(mips) print() pass
# Generated from Grammar/low.g4 by ANTLR 4.8 from antlr4 import * from io import StringIO from typing.io import TextIO import sys from compiler.compiler import Compiler from compiler.function import Function from memory.memory import Memory from memory.constants import MemoryConstants from semantics.types import Types compiler = Compiler() def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\65") buf.write("\u0167\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23") buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30") buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36") buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%") buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.") buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64") buf.write("\t\64\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3") buf.write("\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3") buf.write("\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\6\3\6\3\6\3\6") buf.write("\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\t\3\t\3")
def __init__(self, filename): outCPUfn = "" for ln in open(filename).read().split("\n"): if ln.startswith("#outfilename"): tmp = ln.split(" ")[1:] outCPUfn = " ".join(tmp) self.file_interpreter = Compiler(filename).low_level_file_interpreter compiled = "\n".join(self.file_interpreter.compiled) if compiled[-1] == "\n": compiled = compiled[0:-1] #compiled.replace("32221","") #compiled = re.sub(r'32221 [0-9]{1,3}', '32221 50', compiled) # this will also trigger read output for X,Y in addr[71] compiled = re.sub(r'-1 9999 ([0-9]{1,3});', r'-1 A71 \1; Writing start', compiled) #compiled = re.sub(r'9999 ([0-9]{1,3}) ([0-9]{1,3});', r'A71 \1 \2; Reading first 4 bits of A71 into action', compiled) # OR 9998 A43 44; --> #compiled = re.sub(r'OR 9998 (A[0-9]{1,3}) [0-9]{1,3};', r'MLZ -1 \1 71; Writing X,Y into bottom 12 bits of A71 and trashing old A71', compiled) #MLZ -1 9997 44; #compiled = re.sub(r'9997 ([0-9]{1,3});', r'A71 \1; Reading A71 for output to teams ', compiled) #AND 9996 4095 44;; --> #AND 9996 4095 71; #compiled = re.sub(r'9996 65520 [0-9]{1,3};', r'A71 65520 71; Clearing action but leaving XY in controller A71', compiled) cnt = 3 final_out = "" linecnt = 0 total_lines = len(compiled.split("\n")) for ln in compiled.split("\n"): linecnt += 1 if re.match(r'(^[1]?[0-9]|2[0-5])\. MLZ -1 0 [1-4]?[0-9]{1,3};.*', ln): tmp_line = re.sub( r'([1-4]?[0-9]{1,2}\. MLZ -1) 0 ([1-4]?[0-9]{1,3});.*', r'\1 A\2 \2', ln) #tmp_line = ln final_out += f"{tmp_line} \n" # 23. SUB 333 333 22; # 24. SUB 444 444 24; elif re.match(r'.*SUB 333 333.*', ln): tmp_line = re.sub( r'([1-4]?[0-9]{1,2}\. )SUB 333 333 ([1-4]?[0-9]{1,3});.*', r'\1XOR A\2 A24 \2;', ln) final_out += f"{tmp_line} \n" elif re.match(r'(^[1]?[0-9]|2[0-5])\. SUB 444 444 24', ln): tmp_line = re.sub( r'([1-4]?[0-9]{1,2}\. )SUB 444 444 ([1-4]?[0-9]{1,3});.*', rf'\1MNZ A22 {total_lines-4} 0;', ln) final_out += f"{tmp_line} \n" else: final_out += f"{ln} \n" compiled = final_out open("out.asm", "w").write(compiled) print(compiled) if len(outCPUfn) > 1 and len(sys.argv) >= 3: env = os.environ gollyfp = sys.argv[2] env["outfilename"] = outCPUfn subprocess.Popen([gollyfp, "../CreateROM.py"], env=env)
def ret(self): self.cur_sub, self.instructions = self.return_stack.pop() def load_sub(self, name): self.cur_sub = name self.load_chunk('__top__') def load_chunk(self, name): self.instructions = list(self.subs[self.cur_sub][name]) if __name__ == '__main__': import argparse from compiler.compiler import Compiler from compiler.preprocessor import Preprocessor from compiler.lexer import Lexer from compiler.parser_ import Parser parser = argparse.ArgumentParser() parser.add_argument('file', help="C File", type=argparse.FileType('r')) args = parser.parse_args() with args.file as f: pre = Preprocessor(f.read(), f.name) parser = Parser(Lexer(pre.transform())) compiler = Compiler() assembly = compiler.compile_program(parser.parse_program()) e = Emulator(assembly) e.run()
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys sys.path.append(os.path.abspath('../..')) from compiler.compiler import Compiler from compiler.backends import * from compiler.utility import circuit_drawer, save_results compiler = Compiler(get_coupling(qx5)) # It's possible to compile and run on a simulator instead of a real backend, if you want cobj = compiler.compile(16, qx5, algo='envariance') # To draw circuit without running it, uncomment next line and comment the others # circuit_drawer(cobj['circuit'], filename='envariance') robj = compiler.run(cobj, backend=qx5) circuit_drawer(robj['ran_qasm'], filename='envariance') results = robj['results'] save_results(results, 'envariance.txt', directory='Data/envariance')
"""Module that runs self written 'C' language compiler for file 'source.c' This compiler is written using 'rply' project 'https://github.com/alex/rply' For proper work of my compiler you need to install 'rply' from github manually because on PYPI there is older version. """ from compiler.compiler import Compiler from config import PATH_TO_SOURCE_FILE, PATH_TO_OUTPUT_FILE cmp = Compiler(PATH_TO_SOURCE_FILE, PATH_TO_OUTPUT_FILE) cmp.compile() cmp.print_abstract_syntax_tree() input("\nProgram has finished. To exit press <Enter>\n")
from ast.visualizer import Visualizer from parser_ import Parser from lexer import Lexer from compiler.compiler import Compiler code = """ void main(){ if(4 >= 3){printf("Hurray");} } """ lex = Lexer(text=code) lex2 = Lexer(text=code) parser = Parser(lexer=lex) parser2 = Parser(lexer=lex2) comp = Compiler(parser=parser) viz = Visualizer(parser=parser2) print(comp.compile()) viz.visualize()
temp = cur; cur = prev + cur; prev = temp; counter = counter + 1; } printf("%d ", cur); x = x +1; } } """ from tests.system_tests.code_runner import run_code from lexer import Lexer from parser_ import Parser from compiler.compiler import Compiler from ast.visualizer import Visualizer l = Lexer(code2) p = Parser(l) c = Compiler(p) print("=" * 10) print(c.compile()) print("=" * 10) l = Lexer(code2) p = Parser(l) v = Visualizer(p) print(run_code(code2)) v.visualize()
import sys from parser.parser import Parser from compiler.compiler import Compiler from analyzer.analyzer import Analyzer BUILTINS_FILE = "src/runtime/builtins_signatures" if __name__ == '__main__': if len(sys.argv) != 3: puts( "Error! Provide source and target files as argunents to this script" ) exit(1) code_file = sys.argv[1] target_file = sys.argv[2] builtins = BUILTINS_FILE ast = Parser(code_file, [builtins]).parse() if Analyzer().validate(ast): Compiler(target_file).compile(ast)
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys sys.path.append(os.path.abspath('../..')) from compiler.compiler import Compiler from compiler.backends import * from compiler.utility import circuit_drawer, save_results logging.getLogger('compiler.compiler').setLevel(logging.DEBUG) compiler = Compiler(get_coupling(qx5)) # Oracle can be specified by alias: # '00' equals a '00..0000' oracle # '10' equals a '10..1010' oracle # '11' equals a '11..1111' oracle # # Remember that if the backend has 16 qubit, parity will run on 15 qubits because one is used as ancilla cobj = compiler.compile(15, qx5, algo='parity', oracle='10') # To draw circuit without running it, uncomment next line and comment the others # circuit_drawer(cobj['circuit'], filename='parity') robj = compiler.run(cobj, backend=qx5) circuit_drawer(robj['ran_qasm'], filename='parity_10') results = robj['results'] save_results(results, 'parity_10.txt', directory='Data/parity_10/') # Oracle can also be explicitly set if custom_mode is True
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys sys.path.append(os.path.abspath('../..')) from compiler.compiler import Compiler from compiler.backends import * from compiler.utility import circuit_drawer, save_results logging.getLogger('compiler.compiler').setLevel(logging.DEBUG) compiler = Compiler(get_coupling(qx5)) # It's possible to compile and run on a simulator instead of a real backend, if you want cobj = compiler.compile(16, qx5) # To draw circuit without running it, uncomment next line and comment the others # circuit_drawer(cobj['circuit'], filename='ghz') robj = compiler.run(cobj, backend=qx5, shots=10) circuit_drawer(robj['ran_qasm'], filename='ghz') results = robj['results'] save_results(results, 'ghz.txt', directory='Data/ghz/')
from colorama import Back from compiler.compiler import Compiler from runtime.runtime import Runtime source = open("sample1.aspl") source = source.read() print("SOURCE IS: ", source) compiler = Compiler() code = compiler.compile(source) print(Back.RED) for line in code: print(line) print(Back.RESET) runtime = Runtime() runtime.run(code)
def main(): parser = argparse.ArgumentParser(description='Chocopy frontend') parser.add_argument('-t', dest='typecheck', action='store_false', help='do not typecheck the AST') parser.add_argument('-o', dest='output', action='store_false', help="output AST to stdout instead of to a JSON file") parser.add_argument('--test-all', dest='testall', action='store_true', help="run all test cases") parser.add_argument('--test-parse', dest='testparse', action='store_true', help="run parser test cases") parser.add_argument('--test-tc', dest='testtc', action='store_true', help="run typechecker test cases") parser.add_argument('infile', nargs='?', type=str, default=None) parser.add_argument('outfile', nargs='?', type=str, default=None) args = parser.parse_args() compiler = Compiler() if args.testall: run_all_tests(compiler) return if args.testparse: run_parse_tests(compiler) return if args.testtc: run_typecheck_tests(compiler) return infile = args.infile outfile = args.outfile if args.infile == None: print("Error: must specify input file") parser.print_help() return if args.outfile is None: if args.typecheck: outfile = infile + ".ast.typed" else: outfile = infile + ".ast" astparser = Parser() tree = compiler.parse(infile, astparser) if len(astparser.errors) > 0: for e in astparser.errors: print(e) elif args.typecheck: tc = TypeChecker() compiler.visit(tree, tc) if len(tc.errors) > 0: for e in astparser.errors: print(e) if args.output: ast_json = tree.toJSON() with open(outfile, "w") as f: json.dump(ast_json, f) else: if isinstance(tree, Node): print(json.dumps(tree.toJSON()))