It's hard to tell without seeing the grammer.

It sounds like you have rules like:

cast : '(' type ')'
type : IDENTIFIER
     | type '*'

expr : '(' expr ')'
     | IDENTIFIER
     | expr '*' expr

This would cause the conflict that you say, because it must decide at the
'*' whether to reduce IDENTIFIER to type or expr, and once it's made that
decision, there's no turning back.

Writing the grammer something like the following allows the parser to
postpone the decision until the token after the '*'.

cast : '(' IDENTIFIER ')'
     | '(' type ')'

type : IDENTIFIER '*'
     | type '*'

Note that there is still an ambiguity with (b), which could be an expression
or a cast.  I don't know if this can be disambiguated based on the token
following the ')'.  If so, you could have a cast_or_expr rule that is
defined as '(' IDENTIFIER ')' and then have both cast and expr include the
cast_or_expr rule.

Good luck!

-Bruce

On Tue, Aug 4, 2009 at 12:23 PM, Gabriel Gambetta <
[email protected]> wrote:

>
> I'm writing a parser for a subset of C++. I know it's extremely hard
> to do correctly, but I'm not trying to do it correctly - just good
> enough to do some "smarter search and replace" on some code. That is,
> I don't need the AST to capture every little detail of the program.
>
> That said, I'm having trouble with ambiguity in the grammar. In
> particular, I can't parse both of these correctly :
>
>        A = (B*C);
>        A = (int)C;
>
> When the parser sees B* it doesn't know whether it's the beginning of
> an expression or a cast. It assumes it's a cast so it gets confused by
> the C token.
>
> I'm not sure why is this ambiguous, since the cast ends with a ), not
> with an expression. I'm not an expert in parsers, as you can see.
>
> I don't know whether to fix the grammar (or how), or to handle this
> with an error token and somehow manipulate the parser stack to force
> it to go for the correct interpretation (I don't know exactly how to
> do this, either).
>
> Any help or comments will be extremely appreciated.
>
> Thanks,
> --Gabriel
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"ply-hack" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/ply-hack?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to