Nick Sabalausky Wrote:

> "Nick Sabalausky" <[email protected]> wrote in message 
> news:[email protected]...
> > I've been trying to make a grammar for the Haxe langauge, and I've been 
> > having a hell of a time emulating it's expression-based if/if-else (as 
> > opposed to statement-based as in D). I'm sure a big part of it is my 
> > inexperience with writing grammars, but I've also been starting to wonder 
> > if it's impossible to do context-free. For those unfamiliar, here's how 
> > the relevant parts in Haxe work:
> >
> > ------------------------------------------
> ....
> > ------------------------------------------
> >
> > So, anyone know if a grammar that handles this would need to be 
> > context-sensitive? Or am I just *really* bad at this? ;)
> >
> 
> I guess the key I'm looking for is this:
> 
> // With "if" being an expr, not a stmt:
> foo = if(blah) bar = 1;
> foo = if(blah) bar = 1; else bar = 2;
> 
> If I make assignment bind tighter than the "if expressions", then I can't 
> support "foo = if...", I can only support "foo = (if...)"
> 
> But if I make the "if expressions" bind tighter than assignment, then I 
> can't seem to solve the dangling-else conflict without introducing other 
> ambiguities.
> 
> Anyway, I'm not really looking to get an exact solution, just wondering if 
> there's something about it that causes it to be impossible for a 
> context-free grammar.
> 

I don't know what your parser implementation looks like, but assuming it uses 
Statement and Expression base classes, and your assignment statements are in 
the form "LValueExpression = Expression;", this is how I would structure it:

class IfStatement : Statement {
    Expression _expr;
    Expression _elseExpr
    ...
}
class IfExpression : Expression {
    IfStatement _stmt;
    ...
}

Where ... contains your semantics analysis and either machine code or byte code 
generation.

Your parser first detects an assignment statement, has the lvalue expression 
node, and now begins to parse the assigned expression, which it detects to be 
an IfExpression. That expression generates its own underlying IfStatement which 
spans the ; else tokens too, resulting in both your if and else being part of 
your IfExpression, the later being used in your AssignStatement.

I could toy more with the idea, but this is definitely where I would start 
experimenting.

Reply via email to