SmaCC icon indicating copy to clipboard operation
SmaCC copied to clipboard

Abusing scanner states for polymorphic grammar rules

Open cdlm opened this issue 6 years ago • 1 comments

Feature suggestion: writing a grammar rule in terms of tokens that have different definitions depending on the scanner state…

%states default insideBraces insideParens;

insideBraces <any> : [^{}]+ ;
insideBraces <leftDelimiter> : \{ ;
insideBraces <rightDelimiter> : \} ;

insideParens <any> : [^()]+ ;
insideParens <leftDelimiter> : \( ;
insideParens <rightDelimiter> : \) ;

# this rule would only be used when the scanner is in one of the two states above
DelimitedContent
    : <any> 'content' {{}}
    | <leftDelimiter> 'content'
        DelimitedContent 'content' *
        <rightDelimiter> 'content' {{}}
;

cdlm avatar Nov 05 '18 15:11 cdlm

After discussion with @ToshRaka I got a working parser by duplicating the rule into ParenthesizedContent and BracedContent, and the <any> tokens into <notBraces> and <notParens>.

cdlm avatar Nov 05 '18 15:11 cdlm