본문 바로가기

3-2/컴파일러개론

[컴파일러개론 실습] 4. tinyPythonPrintListener

import org.antlr.v4.runtime.tree.TerminalNode;

public class tinyPythonPrintListener extends tinyPythonBaseListener {
    static int tab = 0;

    void printTab() {
        for (int i = 0; i < 4*tab; i++) {
            System.out.print(" ");
        }
    }

    @Override public void enterStmt(tinyPythonParser.StmtContext ctx) {
        printTab();
    }

    @Override public void enterSuite(tinyPythonParser.SuiteContext ctx) {
        ++tab;
    }

    @Override public void exitSuite(tinyPythonParser.SuiteContext ctx) {
        --tab;
    }

    @Override public void enterTest(tinyPythonParser.TestContext ctx) {
        System.out.print(" ");
    }

    @Override public void enterPrint_arg(tinyPythonParser.Print_argContext ctx) {
        System.out.print(" ");
    }

    @Override public void enterComp_op(tinyPythonParser.Comp_opContext ctx) {
        System.out.print(" ");
    }
    @Override public void exitComp_op(tinyPythonParser.Comp_opContext ctx) {
        System.out.print(" ");
    }

    @Override public void visitTerminal(TerminalNode node) {
        String cur = node.getText();

        if (node.getSymbol().getType() == tinyPythonParser.EOF) return;

        if (cur.equals("elif") || cur.equals("else")) printTab();

        if (cur.equals("+") || cur.equals("-") || cur.equals("*") || cur.equals("/") || cur.equals("=")) {
            System.out.print(" "+cur+" ");
        } else if (cur.equals("def") || cur.equals(",") || cur.equals("return")) {
            System.out.print(cur+" ");
        } else {
            System.out.print(cur);
        }
    }
}

 

'3-2 > 컴파일러개론' 카테고리의 다른 글

[컴파일러개론 실습] 1. 엄랭 to C 컴파일러  (1) 2023.09.13