How to build an interpreter for a small language? [closed]

二次信任 提交于 2019-12-05 20:10:38
mantrid

I think using ANTLR, JavaCC, SampleCC or other parser generator tools would be using a sledgehammer to crack a nut. if there is no recursion in grammar definition just a few methods would be sufficient. the following code gives a basic idea (it may not compile or work, I wrote it from scratch as an illustration how to start):

public int parse(String input) {
Scanner scanner = new Scanner(input);

    return consumeLine(scanner);
}

public int consumeLine(Scanner scanner) {
    if( scanner.hasNext("(") ) {
        return consumeExpression(scanner);

    } else if( scanner.hasNext("IF") ) {
        return consumeIf(scanner);
    }
}


public int consumeExpression(Scanner scanner) {
    scanner.next("(");
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    String op = scanner.next("[+-/*]");
    scanner.next(")");

    if( "+".equals(op) ) {
        return a + b;

    } else if( "-".equals(op) ) {
        return a - b;
    } ...

    throw new RuntimeException("parsing error");
}

public int consumeIf(Scanner scanner) {
    scanner.next("IF");
    int exp1 = consumeExpression(scanner);
    int exp2 = consumeExpression(scanner);
    int exp3 = consumeExpression(scanner);
    int exp4 = consumeExpression(scanner);

    if( exp1 < 0 ) {
        return exp2;
    } else if( exp1 == 0 ) {
        return exp3;
    } ...

    throw new RuntimeException("should not be here (TM)");
}

You can use stack based algorithms to process postfix expressions. A simple idea would be to push integers on a stack and when you encounter a operator , pop the integers from stack and perform the operation mentioned by the operator like + , - .

It is easy with javacc if you are into java. You can mention your tokens and what to do with them in a compact and easy way, then when it is compiled it generates all the code in java source required to perform the logic.

javacc intro

javacc faq

I recommend you use C++ and the boost spirit library....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!