Exemplo n.º 1
0
    def __init__(self, lexer: _Lexer):
        """SymbolTable constructor.

        Takes lexer or tokens argument to get the collection of tokens. Prioritizes parser if both are provided.

        Args:
            lexer: The lexer for generating collections of token.
        """
        super().__init__()
        self.__tokens = lexer.tokens()
        self.__current_token = None
        self.__next_token = None
        self._advance()
        self._advance()
        self._generate()
Exemplo n.º 2
0
def main():
    print("Mini Java Compiler")

    if len(sys.argv) < 2:
        sys.exit("Error: Compiler needs source file as argument.")

    with pathlib.Path(sys.argv[1]).resolve().open(mode="r") as f:
        buffer = f.read()

    target_dir = pathlib.Path(__file__).parent.joinpath("../dumps")
    target_dir.mkdir(parents=True, exist_ok=True)

    print(f"{'':-<50}\nLexer Test")

    lexer = Lexer(buffer)

    with target_dir.joinpath("./tokens.txt").open("w") as f:
        print(f"{'Position':10}{'Stream':<10}{'Token name':20}{'Value':20}", file=f)
        for token in lexer.tokens():
            print(token, file=f)
    print("Lexing completed.")

    print(f"{'':-<50}\nSymbol Table Test")
    symtable = SymbolTable(lexer)
    with target_dir.joinpath("./symtable.json").open("w") as f:
        json.dump(symtable.data, f, indent=4)
    print("Symbol table completed.")

    print(f"{'':-<50}\nParser Test")
    parser = Parser(lexer)
    ast = parser.program()
    print("Parsing completed.")

    print(f"{'':-<50}\nCode Generator Test")
    code_gen = CodeGen(ast)
    code = code_gen.generate_code()
    with target_dir.joinpath("./output.c").open("w") as f:
        print(code, file=f)
    print("Code generation completed.")