问题
I'm trying to design a simple language is similar to lips, schema. I have written its lexer(tokenizer). I can seperate into operators, identifiers etc. But I try now writing parser. For this, just one example is enough for me. Can someone give me an example in java code just for the example? Besides, everyone mentions of usage antlr. Can someone who attempts to use antlr show an example using my example in this question?
- –
EXP -> EXPI | EXPB
- –
EXPI -> (+ EXPI EXPI) | (- EXPI EXPI) | (* EXPI EXPI) | (/ EXPI EXPI) | Id | IntegerValue | (Id EXPLIST)
- –
EXPB -> (and EXPB EXPB)
if my input is (+ 1 2)
, I hope to get as output
- START-> INPUT
- -> EXP
- -> EXPI
- -> (+ EXPI EXPI)
- -> (+ EXPI Id)
- -> (+ Id Id)
It is about LR(shift-reduce parsing). I have a simple example that I don't know whether I can modify the code or not for the parsing. But, a point catches my attention, stack usage is proper for LR algorithm. Doesn't it ?
import java.util.Stack;
public class SmallLisp {
Stack<String> stack;
public SmallLisp(){
String[] tokens = new String[]{"(","+","2","(","+","3","2",")",")",};
stack = new Stack<String>();
for (int i=0;i<tokens.length;i++){
stack.push(tokens[i]);
if(tokens[i].equals(")")) Interprete();
}
}
public void Interprete(){
String tok;
Stack<String> callStack = new Stack<String>();
tok = stack.pop(); /* This is the ) character */
while(!(tok=stack.pop()).equals("(")){
callStack.push(tok);
}
Call(callStack);
}
public void Call(Stack<String> callStack){
String func = callStack.pop(); /* This is the operator or function */
if(func.equals("+")) {
double result = Plus(callStack);
stack.push(String.valueOf(result));
}
//if(func.equals("-")) Minus(callStack);
}
public double Plus(Stack<String> callStack){
double a = Double.parseDouble(callStack.pop());
double b = Double.parseDouble(callStack.pop());
System.out.println("Answer is "+(a+b));
return(a+b);
}
public static void main(String[] args) {
new SmallLisp();
}
}
回答1:
If you want to avoid to write your own Parser you could use ANTLR
This is a parser generator that does all the work for you if you support it with a valid grammar.
If you still want to write it yourself you could still use ANTLR to see how they create their parser/lexers.
来源:https://stackoverflow.com/questions/34432136/writing-parser-of-a-simple-language