There is an alternative way to write the action handler code that
is more in the style of traditional parser generators like Bison or Yacc.
The action code is written immediately beneath the grammar rule whose reduction
causes that action to be executed. An advantage of this is that actions written
like this are anonymous, and do not need
entries in an actions
section of the grammar description.
In this alternative format, the action function code is written inline with the grammar rules. Instead of finishing a grammar rule with an '=' sign and a comma-separated list of function names, we follow the grammar rule immediately with C# code enclosed in curly braces.
As with the previously-described named action handlers, we can use dollar identifiers to refer to
the values associated with each token in the grammar rule. The same positional
rules apply. The value associated with the first token on the right hand side of
the rule is given the name $0
, while the (N+1)th token is given the name
$N
. The only extension to the rules for dollar identifiers is that
the special identifier $$
refers to the value to be returned for
the reduced non-terminal token.
The code below is equivalent to the action handlers described in the inline action section elsewhere in this documentation. Notice that the content of the action handler functions is now an integral part of the grammar description:
adjectives:
adjectives ADJECTIVE
{
// Code equivalent to AppendAdjective
if (AdjectiveList == null)
AdjectiveList = new List<string>();
AdjectiveList.Add($1.ToString());
$$ = AdjectiveList.Count;
// Code equivalent to BumpAdjectives
AdjectivesCount++;
}
|
;
This inline style for writing action function code is permitted for both inline and offline parsers. An arguable disadvantage of the style above is that the automatic syntax checking and intellisense provided by Visual Studio and other compiler tools will not know how to interpret the code in a grammar input file.