Replies: 1 comment 3 replies
|
Hi and thanks for this example! In this case, it is actually "good" that the parser isn't greedy. Otherwise, you would encounter a private Parser<Expression> expression() { return lazy(() -> sum); }
private final Parser<Expression> atom = choice(
number.map(NumberExpression::new),
identifier.map(VariableExpression::new),
expression().between(literal("("), literal(")"))
);
private final Parser<Expression> sum = atom.separate1(literal("+")).map(
summands -> summands.stream().reduce(SumExpression::new).get()
);Here, we use the private final Parser<Expression> sum = chainLeft1(atom, literal("+").map(ignore -> SumExpression::new));The idea of these combinators is to separate the first parser (in this case In the future, I may also change the API such that we can write |
Uh oh!
There was an error while loading. Please reload this page.
Hi there, i was trying to implement a simple "calculator language", to parse code like this:
Defining the parsing was pretty easy, in particular i defined expressions like usually done in AST for compilers:
The parsers are defined like this:
The problem is: when i parse something like
print 10+x, it gives an error because it reads the 10 as a NumberExpression and then doesn't know what to do with "+", infact the error is:Failure: syntax error in Example Input at line 1 and column 13: unexpected character '+'So is there a way to tell the system to try and be eager with the "sum" expression instead of returning the NumberExpression?
I've tried to change the order of the choice() elements, bringing sum to the front, but now the parser crashes with a stack overflow.
Here's the full example:
All reactions