Home > Software engineering >  C# lambda functions parsing in ANTLR
C# lambda functions parsing in ANTLR

Time:05-10

What would be the grammar for parsing C# lambda expressions with ANTLR? I'm trying to come up with one that would successfully parse at the very least a single-line lambda expression with immediate assignment, e.g. Action actionSingleLine = () => Console.WriteLine("Non-returning lambda");

So far I have something like this:

grammar Lambda;

input: line EOF;
line: type name equals lbrackets LAMBDASIGN body ';';
type: ACTION;
name: FUNCNAME;
equals: EQ;
lbrackets: BRACKETS;
body: TEXT;

fragment A : 'A';
fragment C : 'c';
fragment T : 't';
fragment I : 'i';
fragment O : 'o';
fragment N : 'n';
fragment LPAR: '(';
fragment RPAR: ')';

ACTION: 'Action' ;
EQ : '=' ;
BRACKETS: LPAR RPAR;
LAMBDASIGN: EQ '>';
FUNCNAME: ([a-z] | [A-Z])  ;

TEXT: 'Console.WriteLine("Non-returning lambda")';

WS : (' '|'\t')  -> skip;

And the tree I get is as follows: And the tree I get is as follows:

CodePudding user response:

The grammar you posted accepts your example input:

enter image description here

Note that the lexer rule BRACKETS: LPAR RPAR; should be removed because when a space is placed between the parenthesis:

Action actionSingleLine = ( ) => Console.WriteLine("Non-returning lambda");

it will not be parsed correctly. Better to remove the lexer rule and use LPAR RPAR directly in your parser rule:

grammar Lambda;

input: line EOF;
line: type name equals LPAR RPAR LAMBDASIGN body ';';
type: ACTION;
name: FUNCNAME;
equals: EQ;
body: TEXT;

LPAR: '(';
RPAR: ')';

ACTION: 'Action' ;
EQ : '=' ;
LAMBDASIGN: EQ '>';
FUNCNAME: ([a-z] | [A-Z])  ;

TEXT: 'Console.WriteLine("Non-returning lambda")';

WS : (' '|'\t')  -> skip;
  • Related