Chapter 20: Grammar Definition
This chapter provides a detailed reference for defining and extending grammar. While §19 introduced the parser, verb directives, and token types at a practical level, this chapter examines the underlying mechanisms: formal syntax, grammar table encoding, token-type internals, custom parsing routines, action linkage, and a complete catalog of the standard library's grammar entries.
20.1 The Verb Directive in Detail
As introduced in §19.2, the Verb directive declares one or more synonym words
and associates them with grammar lines. This section presents the full formal
syntax and the finer points of its semantics.
Formal Syntax
verb-definition →
'Verb' 'meta'? word-list grammar-line+ ';'
word-list → verb-word+
verb-word → SINGLE-QUOTED-WORD
grammar-line →
'*' token* '->' action-name 'reverse'? 'meta'?
token →
SINGLE-QUOTED-WORD ! literal preposition
| SINGLE-QUOTED-WORD '/' ... ! alternative prepositions
| elementary-token ! noun, held, multi, etc.
| noun '=' routine ! filter token
| 'scope' '=' routine ! scope token
| attribute-name ! attribute filter
| routine ! general parsing routine
action-name → IDENTIFIER ! must have a corresponding Sub routine
Synonym Sharing
All words listed in the word-list share the same grammar table entry. The
compiler creates a single grammar table and points every synonym's dictionary
entry at it. This means Verb 'take' 'grab' 'seize' does not create three
separate grammars - it creates one grammar with three dictionary words leading
to it. Changing the grammar of any one synonym affects all of them; to split one
synonym away, use Extend only (§20.2).
The meta Modifier
When the word meta appears immediately after Verb, every grammar line in
that directive produces a meta action - one that operates on the game system
rather than the game world (see §18.5). Meta actions are not intercepted by
before/after handlers and are not affected by Darkness or other
world-state checks. In the standard library, all system commands (save,
restore, quit, score, etc.) are declared with Verb meta.
Per-Line Meta (6.43+)
Compiler version 6.43 introduces the $GRAMMAR_META_FLAG setting. When enabled
(e.g. by passing $GRAMMAR_META_FLAG=1 on the command line, or by writing
$GRAMMAR_META_FLAG=1; in source before the first grammar declaration),
individual grammar lines can be marked meta independently, allowing a single
verb to mix meta and non-meta actions:
! Compile with $GRAMMAR_META_FLAG=1
Verb 'load'
* noun -> Push
* 'game' -> Restore meta;
In this mode, the compiler sorts action numbers so all meta actions get lower
values than non-meta actions. The system constant #highest_meta_action_number
returns the highest action number that is flagged as meta, or -1 if no meta
actions exist. Game code can test this at runtime:
if (action <= ) {
print "This is a meta action.^";
}
To test whether the feature is available at compile time, use
#ifdef GRAMMAR_META_FLAG (the $ is part of the setting name on the command
line, not part of the constant the compiler defines).
20.2 The Extend Directive
As introduced in §19.4, the Extend directive adds grammar lines to an existing
verb or modifies its grammar. This section details the full syntax and the
precise effect of each placement modifier.
Formal Syntax
extend-definition →
'Extend' 'only'? word-list modifier? grammar-line+ ';'
modifier → 'first' | 'last' | 'replace'
When no modifier is given, last is the default - new lines are appended after
existing ones.
Placement Modifiers
last (default): Appends the new grammar lines after all existing lines for
the verb. The parser tries original lines first, then the new ones.
first: Inserts the new grammar lines before all existing lines. The parser
tries the new lines first, which is useful when overriding default behavior
without removing it:
Extend 'look' first
* 'through' noun -> PeekThrough;
replace: Removes all existing grammar lines for the verb and substitutes
the new ones. The original grammar is discarded entirely:
Extend 'score' replace
* -> Score
* 'full' -> FullScore;
only: Splits one or more synonym words away from their shared grammar
table, giving them a new independent grammar. This is the mechanism for making a
single synonym behave differently from its siblings:
! 'x' normally shares grammar with 'examine', 'check', etc.
! Split it away and give it additional grammar:
Extend only 'x' first
* noun 'with' held -> ExamineWith;
After this directive, x has its own grammar table - initially a copy of the
original - with the new line prepended. The other synonyms (examine, check,
etc.) are unaffected.
Extend with meta (6.43+)
When $GRAMMAR_META_FLAG=1 is active, Extend supports the same per-line
meta keyword as Verb:
Extend 'load'
* 'game' -> Restore meta;
Common Extension Idioms
Adding a preposition variant to an existing verb:
Extend 'cut'
* noun 'with' held -> Cut;
Overriding a verb completely with replace:
Extend 'jump' replace
* -> Jump
* 'over' noun -> JumpOver
* 'across' noun -> JumpOver;
20.3 Grammar Lines and Token Types (Internal Details)
§19.3 describes grammar tokens from the game author's perspective. This section documents the internal constants and data structures that the compiler and parser use to represent them.
Token Type Constants
The parser defines seven token type constants in parser.h; six appear in
author-written grammar, while ILLEGAL_TT = 0 is used internally. Every token
in a grammar line is classified into one of these:
| Constant | Value | Meaning |
|---|---|---|
ILLEGAL_TT |
0 | Internal sentinel; not used in author grammar |
ELEMENTARY_TT |
1 | A built-in noun-phrase token (see below) |
PREPOSITION_TT |
2 | A literal dictionary word, e.g. 'into' |
ROUTINE_FILTER_TT |
3 | A filter routine, e.g. noun=CagedCreature |
ATTR_FILTER_TT |
4 | An attribute filter, e.g. edible |
SCOPE_TT |
5 | A scope routine, e.g. scope=Spells |
GPR_TT |
6 | A general parsing routine (GPR) |
Elementary Token Constants
Within the ELEMENTARY_TT category, individual tokens are identified by these
constants:
| Constant | Value | Grammar keyword | Meaning |
|---|---|---|---|
NOUN_TOKEN |
0 | noun |
Any single object in scope |
HELD_TOKEN |
1 | held |
Object held by the player |
MULTI_TOKEN |
2 | multi |
One or more objects in scope |
MULTIHELD_TOKEN |
3 | multiheld |
One or more held objects |
MULTIEXCEPT_TOKEN |
4 | multiexcept |
Multiple objects except the other |
MULTIINSIDE_TOKEN |
5 | multiinside |
Multiple objects inside the other |
CREATURE_TOKEN |
6 | creature |
An animate object |
SPECIAL_TOKEN |
7 | special |
Reads any single word from input |
NUMBER_TOKEN |
8 | number |
A decimal number |
TOPIC_TOKEN |
9 | topic |
Remaining words as a topic |
ENDIT_TOKEN |
15 | (internal) | Marks end of token list (GV2) |
Grammar Table Encoding
The compiler writes grammar into a binary table whose format depends on the
grammar version. The compiler sets the version with the $GRAMMAR_VERSION
option or by defining the constant Grammar__Version early in the source. The
standard library sets Grammar__Version to 2.
The grammar table is a word array starting at address #grammar_table. It
contains addresses of individual verb grammar tables. Each verb table begins
with a byte giving the number of grammar lines, followed by the lines
themselves.
[Z-machine] GV1 (grammar version 1) is the historical format. Each grammar line is exactly 8 bytes: one byte for the parameter count, six bytes for tokens (padded with zeros if fewer than six), and one byte for the action number. GV1 limits verbs to six tokens per line and 256 actions.
[Z-machine] GV2 (grammar version 2) is the standard format used by the
library. Each grammar line begins with a two-byte word encoding the action
number in the bottom 10 bits and the reverse flag in bit 10. Tokens follow as
three-byte entries (one byte for token type, two bytes for token data),
terminated by an ENDIT_TOKEN (15) byte. Lines may have a variable number of
tokens.
[Z-machine] GV3 (grammar version 3, new in 6.43) is a compact variation of
GV2 designed to save bytes. The header word encodes the action number in the
bottom 10 bits, the reverse flag in bit 10, and the token count in the top 5
bits. Since the count is in the header, no ENDIT_TOKEN terminator is needed.
Token data values are single bytes rather than words; auxiliary tables store
dictionary and routine addresses. GV3 limits verbs to 31 tokens per line.
PunyInform uses GV3.
[Glulx] Only GV2 is supported. Each grammar line has a two-byte action
number, a one-byte flags field (bit 0 is the reverse flag), then five-byte
token entries (one byte for token type, four bytes for token data), terminated
by ENDIT_TOKEN.
Unpacking Grammar Lines at Runtime
The parser unpacks each grammar line into three parallel arrays before attempting to match it:
| Array | Contents |
|---|---|
line_token |
Raw token values (addresses or byte values) |
line_ttype |
Token type for each position (ELEMENTARY_TT, etc.) |
line_tdata |
Token data (dict address, routine address, etc.) |
These are filled by UnpackGrammarLine(address), which reads the binary grammar
data according to the active grammar version. It also sets action_to_be,
action_reversed, and params_wanted. The parser then walks
line_ttype/line_tdata to dispatch each token to the appropriate matching
logic.
20.4 Custom Token Routines (General Parsing Routines)
The grammar system lets game authors write custom parsing logic by placing routines directly in grammar lines. Four mechanisms support this: general parsing routines (GPRs), scope routines, attribute filters, and routine filters.
General Parsing Routines (GPR_TT)
A GPR is a routine whose name appears directly as a token in a grammar line
(token type GPR_TT, value 6). When the parser reaches this token, it calls the
routine. The GPR reads words from the player's input using NextWord() or
NextWordStopped() and returns one of these values:
| Constant | Value | Meaning |
|---|---|---|
GPR_FAIL |
-1 | Token did not match; try next line |
GPR_PREPOSITION |
0 | Matched, no object result (like a preposition) |
GPR_NUMBER |
1 | Matched; result is in parsed_number |
GPR_MULTIPLE |
2 | Matched multiple objects |
GPR_REPARSE |
REPARSE_CODE |
Restart parsing from scratch |
| (object number) | (positive) | Matched that specific object |
The value of REPARSE_CODE is 10000 on [Z-machine] and $40000000 on
[Glulx].
A GPR should advance wn past the words it consumes. If it returns GPR_FAIL,
the parser restores wn and tries the next grammar line.
Example: Parsing a Time Expression
[ TimeParsing x hr mn;
x = NextWord();
if (x == 'midnight') { parsed_number = 0; return GPR_NUMBER; }
if (x == 'noon' or 'midday') { parsed_number = 720; return GPR_NUMBER; }
! Try to parse "H:MM" or "H"
x = TryNumber(wn - 1);
if (x == -1000) return GPR_FAIL;
hr = x;
if (NextWord() == ':') {
mn = TryNumber(wn);
if (mn == -1000) return GPR_FAIL;
wn++;
} else { wn--; mn = 0; }
if (hr < 0 || hr > 23 || mn < 0 || mn > 59) return GPR_FAIL;
parsed_number = hr * 60 + mn;
return GPR_NUMBER;
];
Verb 'set'
* noun 'to' TimeParsing -> SetClock;
Scope Routines (SCOPE_TT)
A scope token (scope=Routine) invokes a custom routine to define which objects
the parser considers as possible matches. As introduced in §19.3, the routine is
called at up to three stages via scope_stage:
Stage 1 - Called before searching, to set the token's multiplicity. Return
1 to make the token match multiple objects (like multi); return 0
(false) for a single-object token (like noun). The parser maps a return of
1 to MULTI_TOKEN and anything else to NOUN_TOKEN.
Stage 2 - Add objects to scope by calling PlaceInScope(obj) for individual
objects or ScopeWithin(domain) for all children of a container. Return true
when finished.
Stage 3 - Called when no match was found. Print an error and return true,
or return -1 for the parser's default error.
[ MagicScope;
switch (scope_stage) {
1: rfalse; ! single-object token
2: PlaceInScope(crystal_ball);
PlaceInScope(magic_mirror);
ScopeWithin(enchanted_cabinet);
rtrue;
3: "You sense no magical object like that.";
}
];
Verb 'scry'
* scope=MagicScope -> Scry;
PlaceInScope(thing) adds a single object to the parser's candidate list
regardless of its actual location.
ScopeWithin(domain) adds every child of domain to the candidate list.
Attribute Filter Tokens (ATTR_FILTER_TT)
An attribute name used directly as a grammar token restricts matching to objects that have the given attribute:
Verb 'eat'
* edible -> Eat;
This is equivalent to noun with a filter checking (noun has edible), but
more concise. The compiler encodes it as ATTR_FILTER_TT (value 4) with the
attribute number as data.
Routine Filter Tokens (ROUTINE_FILTER_TT)
The noun=Routine syntax (token type ROUTINE_FILTER_TT, value 3) restricts
matching to objects for which the named routine returns true. The standard
library uses this for directional filtering:
[ ADirection; if (noun in Compass) rtrue; rfalse; ];
Verb 'go'
* noun=ADirection -> Go;
20.5 Action Routines
Every grammar line's -> ActionName clause links to an action routine by naming
convention: action Foo requires a routine named FooSub. The compiler appends
Sub to the action name; if PhotographSub does not exist for -> Photograph,
compilation fails.
The ##ActionName Constant
For every action declared (via grammar or Fake_Action), the compiler creates a
constant ##ActionName whose value is the action number. These constants are
used in before/after handlers and in direct comparisons:
before [;
: "You can't take that!";
];
if (action == ) print "You look closely.^";
Fake Actions
The Fake_Action directive creates an action number constant without requiring
either a Sub routine or grammar. This is used for internal signaling between
before/after handlers - the action number exists solely for use with << >>
or action == ##Name tests:
Fake_Action LetGo;
Fake_Action Receive;
Fake_Action ThrownAt;
See §18.6 for a full treatment of fake actions.
The Dispatch Path
When the parser successfully matches a grammar line:
- It sets
action,noun, andsecondfrom the matched tokens. - If
action_reversedis true with two parameters,nounandsecondare swapped (§20.6). - The library runs the
beforechain viaBeforeRoutines(). - If no
beforehandler intercepts, it callsActionPrimitive(), which invokes the action'sSubroutine. - The
afterchain runs.
See §18.1 for action variables and §18.7 for << >> syntax.
Writing a Custom Action
Define the Sub routine, then the Verb directive (placed after
Include "Grammar"):
[ WaveAtSub;
print "You wave at ", (the) noun, ".^";
];
Verb 'wave' * 'at' creature -> WaveAt;
Custom grammar should be placed after Include "Grammar";.
20.6 Reverse Mode
The reverse keyword may appear after the action name in a grammar line,
instructing the parser to swap noun and second after parsing but before the
action fires.
When two parameters were parsed and reverse is active, the parser swaps them:
! In parser.h, after matching:
if (action_reversed && parameters == 2) {
i = results-->2;
results-->2 = results-->3;
results-->3 = i;
}
The global action_reversed is set to true when a reversed line matches. The
standard library uses this for Give and Show:
Verb 'give' 'feed' 'offer' 'pay'
* creature held -> Give reverse
* held 'to' creature -> Give
* 'over' held 'to' creature -> Give;
Verb 'show' 'display' 'present'
* creature held -> Show reverse
* held 'to' creature -> Show;
Consider GIVE TROLL SWORD: * creature held matches creature=troll,
held=sword. But GiveSub expects noun=object, second=recipient. The
reverse keyword swaps them. Without it, you would need separate actions for
different word orders.
Encoding
In GV2 (Z-machine), the reverse flag is stored in bit 10 of the action word in
the grammar table. In Glulx, it is bit 0 of the flags byte at offset +2 of the
grammar line.
20.7 Standard Grammar Entries
The standard library defines its verbs in grammar.h (version 6.12.8). The
complete, source-generated grammar - every verb word, its action(s), and its
token patterns - is reproduced in Appendix A: §A.3 (the meta-verb grammar,
grouped by function), §A.4 (the game-verb grammar, listed alphabetically by
primary verb word), and §A.5 (the complete action index). To keep a single
authoritative copy, these verb tables are not repeated here; the verb-definition
syntax and the meta/debug distinctions are covered in §20.1-§20.6 and §18.5.
Helper Routines
Three small filter routines are provided for use in grammar tokens:
[ ADirection; if (noun in Compass) rtrue; rfalse; ];
[ NotPlayer; if (noun ~= player) rtrue; rfalse; ];
[ IsPlayer; if (noun == player) rtrue; rfalse; ];
ADirection - Returns true if noun is a compass direction object. Used in
go, leave, and look to match directional input.
NotPlayer - Returns true if noun is not the player. Used in transfer
to route TRANSFER X TO NPC to the Transfer action.
IsPlayer - Returns true if noun is the player. Used in transfer to
route TRANSFER X TO ME to the Take action.
20.8 Creating New Verbs and Grammar Lines
This section guides you through creating custom verbs and extending existing grammar.
Step-by-Step Process
- Define the action routine - write the
Subroutine:
[ PhotographSub;
if (noun has animate)
"The flash goes off. ", (The) noun, " blinks.";
"You snap a photo of ", (the) noun, ".";
];
- Define the Verb directive - list synonyms, then grammar lines:
Verb 'photograph' 'photo' 'snap'
* noun -> Photograph
* noun 'with' held -> Photograph;
- Placement - custom grammar goes after all three library includes:
Include "Parser";
Include "VerbLib";
Include "Grammar";
! Custom grammar goes here
[ PhotographSub; ... ];
Verb 'photograph' ...;
- Extending existing verbs - use
ExtendafterInclude "Grammar":
Extend 'cut'
* noun 'with' held -> Cut;
Complete Worked Example
A custom PLAY verb with an extension to LISTEN:
[ PlaySub;
print_ret "You play ", (the) noun, " beautifully.";
];
Verb 'play' 'perform'
* held -> Play;
Extend 'listen'
* 'to' 'performance' -> ListenToPerformance;
The ConTopic Helper Routine
The library provides ConTopic in grammar.h as a helper parsing routine for
topic-based input. Although the library no longer uses it, it remains available
for games. It consumes words from the input until end-of-line or the word 'to'
(for Answer), setting consult_from and consult_words:
[ ConTopic w;
consult_from = wn;
do w = NextWordStopped();
until (w == -1 || (w == 'to' && action_to_be == ));
wn--;
consult_words = wn - consult_from;
if (consult_words == 0) return -1;
if (action_to_be == or or ) {
w = wn; wn = consult_from; parsed_number = NextWord();
if (parsed_number == 'the' && consult_words > 1)
parsed_number = NextWord();
wn = w;
return 1;
}
return 0;
];
This routine returns -1 if no words were consumed, 1 for Answer/Ask/Tell
(setting parsed_number to the first significant word), and 0 otherwise.
Stub Declarations
After all grammar, grammar.h provides Stub declarations for entry point
routines the library calls but the game need not define, including AfterLife,
BeforeParsing, ChooseObjects, GamePreRoutine, GamePostRoutine,
InScope, ParseNumber, ParserError, PrintVerb, and UnknownVerb. If the
game omits one, the stub provides a no-op.