[antlr-interest] Creating a simple expression language
Ivar Refsdal
refsdal.ivar at gmail.com
Wed Dec 24 07:08:17 PST 2008
>
> Hi Ivar,
>
> Thanks for the response. The Dragon book is good, isn't it? I skimmed
> it last year, but probably need to go through it again and do more of
> the exercises this time. Ditto Programming Language Pragmatics by
> Michael Scott and Essentials of Programming Languages. I am doing the
> latter at the moment, exercises and all, but it's Scheme, so it's
> great, but not immediately applicable to using ANTLR.
>
> I think I'm fairly happy with the grammar in terms of it parsing my
> expected input. Doubtless I will refine it as my understanding grows.
> Where I'm stuck is how to evaluate my AST; i.e. Eval.g is where I'm
> not sure how to procee, rather than Expr.g.
>
> I think k=1 is the right choice. My understanding is that you want the
> smallest possible value of k for performance reasons. You can use a
> higher value (ideally scoped by production) to resolve ambiguities,
> etc; but you should always strive to resolve that by using
> left-factoring, semantic or syntactic predicate. Similarly for
> backtracking; it's powerful and useful, but there are other options.
>
> So in summary, I'm still stuck and looking for an example of how to
> register and execute my functions. I intuitively feel that my
> tree-walking approach is wrong, but I'm not sure what the idiomatic,
> best-practice for ANTLR would be.
>
> Cheers,
>
> James
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>
Hi James,
Thanks for your response.
I had a second go (without any tree things as I'm not familiar with
that yet):
http://pastie.org/pastes/346265
this input:
square(add( add(5,5,5), add(2,2,2)))
should give this output:
method: add [5, 5, 5] -> 15
method: add [2, 2, 2] -> 6
method: add [15, 6] -> 21
method: square [21] -> 441
The functions look like this:
class PublicFunctions {
public Integer square(Integer x) { return x*x; }
public Integer addfive(Integer x) { return x+5; }
public Integer add(Integer...arguments) {
Integer sum = new Integer(0);
for (Integer x : arguments) {
sum+= x;
}
return sum;
}
}
It's just a small modification of this grammar:
http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator
fn=ID '(' (fexpr=expr { args.add( new Integer($fexpr.value)); } // is there a better way to do this?
(',' aexpr=expr { args.add( new Integer($aexpr.value)); } )* // is there a better way to do this?
)? ')'
{
I tried using var+=expr, but couldn't get it to work... Any tips?
Any tips on Java coding style is also appreciated... :)
Good luck and happy holidays :-)
Ivar
More information about the antlr-interest
mailing list