'C# lambda functions parsing in ANTLR
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;
Solution 1:[1]
The grammar you posted accepts your example input:
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bart Kiers |


