An Irony grammar class is a C# class derived from Irony.Parsing.Grammar
that defines the grammar for a language.
The overall structure can be easily done by templating so it is not worth not worth discussing. We will concentrate on the actual work that is performed in its constructor:
- Decalare and initialize variables for terminals
- Decalare and initialize variables for non-terminals
- Defines rules
- Mark transients, punctuations and operators
- Other optional configuration (i.e. language flag)
Sarcasm automatically generates code to complete the first 4 tasks. In this article we will talk about some implementation details.
There are 2 ways to intialize a terminal in Sarcasm's syntax: string literal or C# method/constructor call.
ADD = "+";
ID = new IdentifierTerminal("ID");
In both cases, the code generation is straight forward:
var ADD = ToTerm("+");
var ID = new IdentifierTerminal("ID);
Array intialization is simple too:
OP = ["+", "-", "*", "/"];
var OP = ToTerm("+") | ToTerm("-") | ToTerm("*") | ToTerm("/");
// Name it
OP.Name = "OP";
If AST node type is specified:
NumberNode NUMBER = new NumberTerminal();
is translated into:
var NUMBER = new NumberTerminal();
NUMBER.AstConfig.NodeType = typeof(NumberNode);
All non-terminals must appear at the left hand side of a production rule exactly once. Otherwise the grammar will be incomplete because the parser will have no idea how to continue expanding a non terminals.