[antlr-interest] Using rewrite rules with conditionals...

Elijah Epifanov lists at xmart.ws
Wed Jun 6 03:21:35 PDT 2007


Hi, I think this will do the job (start rule is now 
optional_size_qualifier):

optional_size_qualifier
: size_qualifier -> size_qualifier
| -> SIZE_DEFAULT
;

size_qualifier
: '.' ( 'u' | 'U' )? size_postfix -> size_postfix
;

size_postfix
: ( 'b' | 'B' ) -> SIZE_8
| ( 'w' | 'W' ) -> SIZE_16
| ( 'l' | 'L' ) -> SIZE_32
| ( 'q' | 'Q' ) -> SIZE_64
;

Cameron Esfahani wrote:
> I had the following construct in my parser:
> 
> size_qualifier
> : '.' ( 'u' | 'U' )? ( 'b' | 'B' ) -> SIZE_8
> | '.' ( 'u' | 'U' )? ( 'w' | 'W' ) -> SIZE_16
> | '.' ( 'u' | 'U' )? ( 'l' | 'L' ) -> SIZE_32
> | '.' ( 'u' | 'U' )? ( 'q' | 'Q' ) -> SIZE_64
> ;
> 
> number_size
> : NUMBER size_qualifier?
> ;
> 
> The idea is that I'll encode in the AST the size of the number.  But, if 
> the input doesn't supply one, then I want to put in a default size: 
> SIZE_DEFAULT.
> 
> This is the only thing I could come up with:
> 
> size_qualifier
> : '.' ( 'u' | 'U' )? ( 'b' | 'B' ) -> SIZE_8
> | '.' ( 'u' | 'U' )? ( 'w' | 'W' ) -> SIZE_16
> | '.' ( 'u' | 'U' )? ( 'l' | 'L' ) -> SIZE_32
> | '.' ( 'u' | 'U' )? ( 'q' | 'Q' ) -> SIZE_64
> ;
> 
> number_size
> : NUMBER size_qualifier -> ^( size_qualifier NUMBER )
> | NUMBER -> ^( SIZE_DEFAULT NUMBER )
> ;
> 
> It seems to work, but I'm wondering if there is a better way of doing 
> it?  If size_qualifier exists, then encode that into the tree, if not, 
> use something I supply.
> 
> Cameron Esfahani
> dirty at apple.com <mailto:dirty at apple.com>
> 
> "With or without religion, good people can behave well and bad people 
> can do evil; but for good people to do evil - that takes religion."
> 
> Steven Weinberg
> 
> 
> 


More information about the antlr-interest mailing list