Download Delphi Yacc & Lex A parser generator toolset for Delphi and
Transcript
3.6
Grammar Rules and Actions
3 DELPHI YACC
name : symbol ... ;
The left-hand side of a rule must be an identifier (which denotes a nonterminal symbol). The righthand side may be an arbitrary (possibly empty) sequence of nonterminal and terminal symbols
(including literals enclosed in single quotes). The terminating semicolon may also be omitted. Different rules for the same left-hand side symbols may be written using the | character to separate
the different alternatives:
name : symbol ...
| symbol ...
...
;
For instance, to specify a simple grammar for arithmetic expressions, you may write:
%left ’+’ ’-’
%left ’*’ ’/’
%token NUM
%%
expr : expr ’+’
| expr ’-’
| expr ’*’
| expr ’/’
| ’(’ expr
| NUM
;
expr
expr
expr
expr
’)’
(The %left definitions at the beginning of the grammar are needed to specify the precedence and
associativity of the operator symbols. This will be discussed in more detail in Section Ambigious
Grammars.)
Grammar rules may contain actions – Delphi statements enclosed in { } – to be executed as the
corresponding rules are recognized. Furthermore, rules may return values, and access values
returned by other rules. These “semantic” values are written as $$ (value of the left-hand side
nonterminal) and $i (value of the ith right-hand side symbol). They are kept on a special value
stack which is maintained automatically by the parser.
Values associated with terminal symbols must be set by the lexical analyzer (more about this in
Section Lexical Analysis). Actions of the form $$ := $1 can frequently be omitted, since it is the
default action assumed by Delphi Yacc for any rule that does not have an explicit action.
By default, the semantic value type provided by Yacc is Integer. You can also put a declaration
like
%{
type YYSType = Real;
%}
into the definitions section of your Yacc grammar to change the default value type. However, if
you have different value types, the preferred method is to use type definitions as discussed in
Section Definitions. When such type definitions are given, Delphi Yacc handles all the necessary
10