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();
}
}
switchstatement instead of a transition table (array). But you still need to know all of the parser states and how to transition between them (hint: the top of the stack is the parser's current state that youswitchon.)exp ::= id | number | (exp exp exp). Then, when you're evaluating expressions (after you've parsed them), you can complain semantic errors like a number in the function position.(oper exp exp), with anoperruleoper -> '+' | '-' | '*' | '/'?