Exemplo n.º 1
0
def _runsource(source):
    try:
        lexer = Lexer(source)
        parser = Parser(lexer)
        tree = parser.parse()
        semantic_analyzer = SemanticAnalyzer()
        semantic_analyzer.visit(tree)
    except Exception as e:
        print(e)
        return

    # print(semantic_analyzer.symtab)
    interpreter = Interpreter(tree)
    result = interpreter.interpret()
    if not result:
        result = "pass"
    transpiled_source = "def USER_PROGRAM():\n" + '\n'.join(map(lambda c: '\t' + c, result.split('\n'))) + \
        "\nGLOBAL_MEMORY = OrderedDict()\nUSER_PROGRAM()"

    #print(transpiled_source)
    codeobj = compile(transpiled_source, 'submodule', 'exec')
    try:
        exec(codeobj, globals())
    except Exception as e:
        print("Runtime exception of type {} occurred:\n{}".format(type(e).__name__, \
        '\n'.join(map(lambda c: '>\t' + c, str(e).split('\n')))))
Exemplo n.º 2
0
 def test_hasMoreCommands(self):
     buf = StringIO(u"  \n")
     parser = Parser(buf)
     self.assertFalse(parser.hasMoreCommands())
     buf = StringIO(u"//注释行\n@123")
     parser = Parser(buf)
     self.assertTrue(parser.hasMoreCommands())
     parser = Parser("test.asm")
     self.assertFalse(parser.hasMoreCommands())
Exemplo n.º 3
0
 def test_advance(self):
     buf = StringIO()
     with self.assertRaisesRegexp(ValueError, "has no command.*"):
         parser = Parser(buf)
         parser.advance()
     buf = StringIO(u"@123")
     parser = Parser(buf)
     parser.advance()
Exemplo n.º 4
0
 def run(self, source):
     parser = Parser()
     parser.compile(self.functions, source, self.code)
     self._run(self.code)
Exemplo n.º 5
0
 def _parse(self, input_stream):
     return Parser().parse(Lexer(input_stream))
Exemplo n.º 6
0
from compiler import Lexer, Parser
from collections.abc import Iterable

nodes = [
    'VAR', 'CONST', 'RET', 'EXPR', 'FUNC', 'UNOP', 'BINOP', 'BIN_PROD',
    'BIN_DIV', 'BIN_XOR', 'FACTOR', 'TERM', 'DECL', 'STMT', 'ID', 'TERNARY',
    'BLOCK', 'ANNOUNCEMENT', 'CALL', 'EXOR', 'LESS', 'MORE', 'ELESS', 'EMORE',
    'AND', 'EQUAL', 'PROG'
]

file = 'lab1.c'
lex = Lexer(file)
lexems = lex.next_token()
pars = Parser(lexems)
ast = pars.parse()

print("#" * 30)
for i in lexems:
    print(i)


def tree_ast(ast, n):
    if ast is None:
        return
    print(' ' * 2 * n, nodes[ast.kind], end=" ")
    if ast.value:
        print(ast.value)
    else:
        print(" ")
    if ast.op2:
        print(' ' * 2 * (n + 1), "op2:")
Exemplo n.º 7
0
def test(textname, resultsname, testname0, keyname0, testname1, keyname1):
    text = open(textname, 'r').read()

    testresults = open(resultsname, 'a')

    testresults.write("TESTING %s:\n" % textname)
    makeFacility = True
    makeImitation = True

    testresults.write("makeFacility...\n")
    if makeFacility:
        testresults.write("\tLexer...\n")
        facility_lexer = Lexer.Lexer(text)

        testresults.write("\tParser...\n")
        facility_parser = Parser.Parser(facility_lexer)

        testresults.write("\tCompiler...\n")
        facility_compiler = Facility_Domain_Compiler.Facility_Domain_Compiler(
            facility_parser)
        result = facility_compiler.interpret()[0]

        fc_file = open(testname0, 'w')
        fc_file.write("%s" % result)
        testlines = result.strip().splitlines()

        keylines = open(keyname0, 'r').read().strip().splitlines()

        difflinecount = 0
        # Print diffs of the files if they aren't equal
        for line in difflib.unified_diff(keylines,
                                         testlines,
                                         fromfile=keyname0,
                                         tofile=testname0,
                                         lineterm=''):
            if (difflinecount == 0):
                testresults.write("--------- FAILED ---------\nDIFF:\n")
            testresults.write("%s\n" % line)
            difflinecount += 1

        # No diffs, so must be same file
        if (difflinecount == 0):
            testresults.write("--------- PASSED ---------\n\n")

    testresults.write("makeImitation...\n")
    if makeImitation:
        testresults.write("\tLexer...\n")
        imitation_lexer = Lexer.Lexer(text)

        testresults.write("\tParser...\n")
        imitation_parser = Parser.Parser(imitation_lexer)

        testresults.write("\tCompiler...\n")
        imitation_compiler = Imitation_Compiler.Imitation_Compiler(
            imitation_parser)
        result = imitation_compiler.interpret()

        ic_file = open(testname1, 'w')
        ic_file.write("%s" % result)
        testlines = result.strip().splitlines()

        keylines = open(keyname1, 'r').read().strip().splitlines()

        difflinecount = 0
        # Print diffs of the files if they aren't equal
        for line in difflib.unified_diff(keylines,
                                         testlines,
                                         fromfile=keyname1,
                                         tofile=testname1,
                                         lineterm=''):
            if (difflinecount == 0):
                testresults.write("--------- FAILED ---------\nDIFF:\n")
            testresults.write("%s\n" % line)
            difflinecount += 1

        # No diffs, so must be same file
        if (difflinecount == 0):
            testresults.write("--------- PASSED ---------\n\n")
Exemplo n.º 8
0
 def test_jmp(self):
     buf = StringIO(u"D;JEQ")
     parser = Parser(buf)
     parser.advance()
     self.assertEqual(parser.jmp(), "JEQ")
Exemplo n.º 9
0
 def test_comp(self):
     buf = StringIO(u"M=A")
     parser = Parser(buf)
     parser.advance()
     self.assertEqual(parser.comp(), "A")
Exemplo n.º 10
0
 def test_dest(self):
     buf = StringIO()
     buf.write(u"M=1\n")
     buf.write(u"A;1\n")
     buf.write(u"ASD=1\n")
     buf.seek(0)
     parser = Parser(buf)
     parser.advance()
     self.assertEqual(parser.dest(), "M")
     with self.assertRaisesRegexp(ValueError, "Syntax error.*"):
         parser.advance()
         parser.dest()
     with self.assertRaisesRegexp(ValueError, "Syntax error.*"):
         parser.advance()
         parser.dest()
Exemplo n.º 11
0
 def test_symbol(self):
     buf = StringIO(u"(LABEL)")
     parser = Parser(buf)
     parser.advance()
     self.assertEqual(parser.symbol(), "LABEL")
     buf = StringIO(u"@LABEL")
     parser = Parser(buf)
     parser.advance()
     self.assertEqual(parser.symbol(), "LABEL")
     buf = StringIO(u"@2")
     parser = Parser(buf)
     parser.advance()
     self.assertEqual(parser.symbol(), "2")
Exemplo n.º 12
0
    def test_commandType(self):
        buf = StringIO()
        buf.write(u"@123\n")
        buf.write(u"//\n")

        buf.write(u"(TEST_LABEL)\n")
        buf.write(u"AM=1\n")
        buf.write(u"0;JMP\n")
        buf.seek(0)
        parser = Parser(buf)
        parser.advance()
        self.assertEqual(parser.commandType(), Parser.A_COMMAND)
        parser.advance()
        self.assertEqual(parser.commandType(), Parser.L_COMMAND)
        parser.advance()
        self.assertEqual(parser.commandType(), Parser.C_COMMAND)
        parser.advance()
        self.assertEqual(parser.commandType(), Parser.C_COMMAND)