Go to the first, previous, next, last section, table of contents.
We already know how to use {}
to include literal TOM code in a
rule. When you want to add code to the parser class outside of a rule,
things are different. Since such code can only be a method, such
methods can be added as an extension to the parser class, using another
source file. However, this is not all that convenient, and extending a
class within the same unit is not considered to be elegant.
gp
provides the compound %%...%%
construct to define
methods. At any top-level location in the grammar, such a compound may
be used to declare or define methods. Before the %instance
has
been seen, any method defined is a class method. After the
%instance
, the method is an instance method.
Example `ex7' starts with a class method void note int
.
%class ex7 %% <doc> Print the {tok}. This is a class method. </doc> void note int tok { [[[stdio out] print ("next token: ", byte (tok))] nl]; } %%
Although the instance definition can remain empty, a %instance
is
needed to indicate that the next method definition between
%%...%%
is an instance method.
%instance %% <doc> Pass to the same method of our class. </doc> void note int tok { [isa note tok]; } %%
The grammar itself is rather silly, but demonstrates that the method
that we defined can be invoked. The token
argument is an
instance variable of the gps.Parser
class; it holds the current
token.
language: expr*; expr: { [self note token]; } [ '(' expr* ')' | '[' expr* ']' | '{' expr* '}' ] ;
Go to the first, previous, next, last section, table of contents.