Chapter 19: The Parser and Grammar
The parser is the largest and most complex component of the standard library. It reads the player's typed input, matches it against grammar definitions, resolves noun phrases to objects, and produces an action with its arguments. This chapter explains how the parser works, how to define grammar, and how game authors can customize parsing behavior.
19.1 How the Parser Works
When the player types a command and presses Enter, the parser performs four major phases:
Phase 1: Tokenization
The library calls Keyboard() to read a line of input into the buffer
array. The Z-machine performs the main tokenization read opcode inside
KeyboardPrimitive (or the Glulx equivalent, which additionally calls
Tokenise__()). The results are stored in the parse table, which records
the number of words and, for each word, its dictionary address (or zero if not
found), its length, and its position in the buffer. Tokenise__() is also
called in the OOPS-repair path and when LanguageToInformese is defined.
! Key global variables set during tokenization:
! num_words - total number of words typed
! wn - current word number (1-based index into parse)
! verb_word - dictionary address of the verb word
! verb_wordnum - position of the verb in the input (1-based)
Before grammar matching begins, the library calls the BeforeParsing() entry
point (if the game defines one), giving the game a chance to manipulate the
input buffer or parse table before the parser examines it.
Phase 2: Grammar Matching
The parser identifies the verb word and looks up its grammar table - the set of
grammar lines defined by Verb and Extend directives. It tries each grammar
line in order, attempting to match the remaining input words against the line's
token pattern.
For each token in a grammar line, the parser calls internal matching routines that consume words from the input. If a token fails to match, the parser backtracks and tries the next grammar line. If all lines fail, the parser generates a parser error.
When a grammar line matches completely, the parser records the action and the matched objects in the results it returns to its caller.
Phase 3: Noun Resolution
When the parser encounters a noun-type token (noun, held, multi, etc.), it
searches the current scope for objects whose names match the input words.
This involves:
- Calling
parse_nameon each object in scope (if defined). - Matching individual
nameproperty words against input words. - Building a list of candidate objects in
match_list. - If multiple candidates remain, running disambiguation (§19.7).
Phase 4: Action Dispatch
Once parsing succeeds, the parser returns the action number and its parameters
to the main game loop, which fills the global variables action, inp1,
inp2, noun, and second from them; actor is the one of these the parser
sets itself. The action processing pipeline (§18) takes over from here.
Special Input Handling
Before grammar matching, the parser handles several special cases:
- "oops" - replaces a word in the previous command.
- "again" (or "g") - re-executes the previous command.
- Implicit "go" - a bare direction word like
NORTHis treated asGO NORTH. - Actor commands - input of the form
NPC, COMMANDsetsactorto the NPC and parsesCOMMANDas an order.
19.2 The Verb Directive
The Verb directive defines grammar for one or more verb words. It appears in
grammar.h (or in game source after Include "Grammar").
Basic Syntax
Verb 'word' 'synonym1' 'synonym2' ...
* token1 token2 ... -> ActionName
* token1 token2 ... -> OtherAction;
Each Verb directive begins with one or more dictionary words that the player
can type as the verb. The body contains one or more grammar lines, each
starting with * and ending with -> ActionName. The directive ends with a
semicolon after the last grammar line.
Verb 'take'
* multi -> Take
* 'off' multiheld -> Disrobe
* multiinside 'from'/'off' noun -> Remove
* 'inventory' -> Inv;
All synonym words in a single Verb directive share the same grammar lines. In
the example above, TAKE and any synonyms listed all use the same four grammar
lines.
Single-Letter Abbreviations
Inside a Verb directive, every single-quoted token is added to the dictionary
as a word, whatever its length, so 'x' and 'x//' compile to the same entry.
The // suffix marks the end of the word and introduces its optional dictionary
flag characters (p, s, n, and the negating ~); with nothing after it,
the flag list is empty. The library nevertheless writes single-letter verb
synonyms with //, because in an expression a single character in single
quotes is a character literal rather than a dictionary word:
Verb 'examine' 'x//' 'check' 'describe' 'watch'
* noun -> Examine;
Here x is a single-letter synonym for examine.
Meta Verbs
Adding meta after Verb declares all grammar lines as meta actions:
Verb meta 'score'
* -> Score;
Verb meta 'quit' 'q//' 'die'
* -> Quit;
Meta actions do not consume a game turn and bypass before/after processing (see §18.5).
The reverse Modifier
Adding reverse after the action name swaps noun and second before the
action fires:
Verb 'give' 'feed' 'offer' 'pay'
* creature held -> Give reverse
* held 'to' creature -> Give;
The first line matches GIVE TROLL SWORD - the creature comes first in the
input, but reverse swaps them so noun = sword and second = troll, matching
the Give action's expected argument order.
19.3 Grammar Lines and Tokens
Each grammar line is a pattern of tokens that the parser matches against the
player's input. Tokens are listed between * and ->.
Token Types
| Token | Matches | noun/second receives |
|---|---|---|
noun |
Any single object in scope | The object |
held |
An object held by the actor | The object |
multi |
One or more objects in scope | Each object (action runs per object) |
multiheld |
One or more held objects | Each object |
multiexcept |
Multiple objects, excluding the other noun | Each object |
multiinside |
Multiple objects inside a container | Each object |
creature |
An animate object in scope, or a talkable one for the conversation actions |
The object |
number |
A numeric value | The number (as integer) |
topic |
Free-form text (any words) | Nothing - the range is left in consult_from/consult_words; for ##Ask, ##Answer and ##Tell a single topic word is passed instead |
special |
A single word or number | The parsed value |
'word' |
A specific dictionary word (literal) | (consumed, not stored) |
noun=Routine |
An object filtered by Routine | The object |
scope=Routine |
An object from a custom scope | The object |
attribute |
An object with a given attribute | The object |
A creature token is accepted by the library's CreatureTest routine: an
animate object always matches; a talkable object matches when the action
being parsed is ##Ask, ##Answer, ##Tell, ##AskFor or ##AskTo; and when
the actor is not the player, every object matches.
Literal Words
Literal words are enclosed in single quotes and must appear exactly in the input:
Verb 'look'
* -> Look
* 'at' noun -> Examine
* 'under' noun -> LookUnder
* 'inside'/'in'/'into' noun -> Search;
The / operator provides alternatives - 'inside'/'in'/'into' matches any one
of those three words.
The multi Family
The multi tokens cause the action to fire once per matched object. If the
player types TAKE ALL, the parser matches every takeable object in scope, and
TakeSub runs separately for each one.
multi- any objects in scope.multiheld- only objects carried by the actor.multiexcept- objects in scope except the other noun argument. Used in patterns likePUT ALL IN BOXwhere the box is excluded.multiinside- objects inside a specified container. Used in patterns likeTAKE ALL FROM BOX.
Verb 'drop' 'discard'
* multiheld -> Drop
* multiexcept 'in'/'into' noun -> Insert
* multiexcept 'on'/'onto' noun -> PutOn;
Filter Tokens: noun=Routine
A noun=Routine token restricts matches to objects for which Routine returns
true. The library uses this for direction filtering:
Verb 'go' 'run' 'walk'
* noun=ADirection -> Go
* noun -> Enter;
The ADirection routine returns true only for direction objects, so GO NORTH
matches the first line, while GO CAVE matches the second.
Scope Tokens: scope=Routine
A scope=Routine token replaces the normal scope with objects provided by a
custom routine. The routine is called with scope_stage set to indicate what
phase of scoping is occurring:
[ SearchDeadScope x;
switch (scope_stage) {
1: rfalse; ! Single-object token (return 1 for a multiple-object token)
2: objectloop (x ofclass Thing)
if (x has dead) PlaceInScope(x);
rtrue; ! Scope provided
3: "You think of the dead."; ! Error message
}
];
Verb 'remember'
* scope=SearchDeadScope -> Remember;
The topic Token
The topic token matches free-form text - any sequence of words. It is used for
conversational actions and consulting:
Verb 'ask'
* creature 'about' topic -> Ask;
Verb 'consult'
* noun 'about' topic -> Consult;
When topic matches, the library sets consult_from and consult_words to
indicate which words were matched:
[ ConsultSub;
! consult_from = word number of first topic word
! consult_words = number of topic words
...
];
19.4 The Extend Directive
The Extend directive adds grammar lines to an existing verb, by default
without replacing its original grammar. This is the primary mechanism for
customizing the parser from game source.
Basic Syntax
Extend 'verb' * tokens -> ActionName;
By default, new grammar lines are appended after the existing lines. The parser tries original lines first, then extended ones.
Placement Modifiers
| Modifier | Effect |
|---|---|
first |
New lines are inserted before existing lines. |
last |
New lines are appended after existing lines (default). |
replace |
All existing lines are removed; only the new lines remain. |
only |
Extends only the named synonym, not all words sharing the verb's grammar. |
! Add a new grammar line tried before existing ones:
Extend 'look' first
* 'through' noun -> Search;
! Replace all grammar for 'listen':
Extend 'listen' replace
* 'to' noun -> Listen
* 'carefully' -> Listen;
! Extend only 'x', not 'examine':
Extend only 'x//'
* 'me' -> Inv;
Practical Example
Adding a new SEARCH UNDER command:
Extend 'search'
* 'under' noun -> LookUnder
* noun 'for' topic -> Consult;
Now SEARCH UNDER TABLE works alongside the original SEARCH TABLE.
19.5 Object Names and the parse_name Property
The name Property
The name property holds the list of dictionary words that the parser
recognizes as referring to an object. The compiler defines it rather than
linklpa.h, and it is additive: when a class provides name words, instances
inherit them and can add more. See §7 for the object-definition syntax.
Object brass_lamp "brass lamp" cave
with name 'brass' 'lamp' 'lantern',
description "A well-polished brass lamp.";
The player can refer to this object as "brass lamp", "lantern", or any combination of the listed words.
Custom Matching with parse_name
The parse_name property provides custom parsing logic for an object. When the
parser tries to match input words against an object, it calls parse_name (if
defined) before falling back to matching individual name words.
How It Works
The parse_name routine is called with wn set to the current word position.
It should examine words starting at wn (using NextWord() or WordAddress())
and return the number of consecutive words that match the object.
Object "red brick wall" room
with parse_name [ w n;
while (true) {
w = NextWord();
if (w == 'red' or 'brick' or 'wall') n++;
else break;
}
return n; ! Number of words consumed
],
name 'red' 'brick' 'wall';
Return Values
| Return value | Meaning |
|---|---|
n > 0 |
Matched n words. |
0 |
No match - the object is rejected outright; its name words are not consulted. |
-1 |
Used during ##TheSame disambiguation: the two objects are identical. |
-2 |
Used during ##TheSame disambiguation: the two objects are different. |
Disambiguation with parse_name
When the parser needs to determine whether two objects are identical (for
purposes like TAKE A BALL vs TAKE THE BALL), it calls parse_name with
parser_action set to ##TheSame, parser_one set to the first object, and
parser_two set to the second. The routine should return -1 (identical) or
-2 (different).
Object "red ball" room
with parse_name [ w n;
if (parser_action == ) {
if (parser_two ofclass RedBall) return -1;
return -2;
}
while (true) {
w = NextWord();
if (w == 'red' or 'ball') n++;
else return n;
}
];
Signaling Plurals
If parse_name matches a plural word, it should set parser_action to
##PluralFound so the parser knows to consider multiple objects:
parse_name [ w n;
while (true) {
w = NextWord();
if (w == 'coin') { n++; continue; }
if (w == 'coins') {
n++;
parser_action = ;
continue;
}
return n;
}
],
The grammar Property
The grammar property provides custom grammar lines for an animate or
talkable object. When the player gives a command to this NPC, the library
checks grammar before the standard grammar tables, the routine can return
true to indicate the command has been parsed, or false to fall through to
standard grammar.
Object computer "computer terminal" lab
with name 'computer' 'terminal',
grammar [;
if (verb_word == 'run' or 'execute') {
action = ;
rtrue;
}
],
has talkable switchable;
19.6 The ParseNoun Entry Point
The game can define a ParseNoun entry-point routine that the parser calls
while resolving a noun phrase against an object, once that object's own
parse_name (if it has one) has declined by returning a negative value. It
receives the object being tested and should return the number of words matched,
or -1 to decline (letting the parser use its own matching).
[ ParseNoun obj w;
! Allow "shiny" as an adjective for any object with the general attribute
w = NextWord();
if (w == 'shiny' && obj has general) return 1;
wn--; ! put the peeked word back
return -1; ! Don't interfere: let the parser match names itself
];
ParseNoun is called after parse_name but before the standard name word
matching. If it returns a positive value, it consumes that many words as a
match. If it returns 0, the object is treated as not matching (zero words
matched). If it returns -1, the routine is declining to handle this object,
and the parser falls through to the standard name-word matching instead.
19.7 Disambiguation
When multiple objects match a noun phrase, the parser must determine which object the player intended. This process is called disambiguation.
The Disambiguation Process
- The parser builds
match_list, an array of candidate objects. - Objects are grouped into equivalence classes - groups of identical
objects (same name words, same
parse_namebehavior). - If one candidate outscores every other, the parser takes it without asking; if the best score is shared but all the tied objects belong to the same class, it picks one of them.
- If objects from more than one class share the best score, the parser asks the
player:
"Which do you mean, the red ball or the blue ball?"The one exception is a noun phrase of a single word that exactly matches a candidate's printed short name: that candidate is taken silently. - The player's response is parsed to narrow the selection.
The ChooseObjects Entry Point
The game can define ChooseObjects to influence which objects the parser
prefers. It is called for each candidate object during noun resolution.
[ ChooseObjects obj flag;
! flag == 2: disambiguating among candidates - return a score 0-9
! flag == 0 or 1: take-all / multiple-object selection - return:
! 0 = let parser decide
! 1 = force acceptance
! 2 = force rejection
if (flag == 2) {
! Prefer lit objects for "examine"
if (action_to_be == && obj has light)
return 5;
return 3; ! neutral
}
return 0; ! let parser decide
];
When flag is 2 (disambiguation), the routine returns a score from 0 to 9;
the parser prefers higher-scoring objects. When flag is 0 or 1 (the
take-all / multiple-object path), the routine returns 0 (parser decides), 1
(accept), or 2 (reject).
Practical Example
Preferring the brass key whenever an ##Unlock is being parsed. The objects the
current command has already matched are not yet available to ChooseObjects:
the parser does not fill noun and second with them until action dispatch
(§19.1, Phase 4), so the test can consult only action_to_be and the candidate
object itself.
[ ChooseObjects obj flag;
if (flag < 2) return 0;
if (action_to_be == && obj == brass_key)
return 9; ! Strongly prefer
return 3;
];
19.8 Parser Error Handling
When the parser cannot understand the player's input, it generates a parser
error. The library defines 18 standard error types as constants (STUCK_PE ...
ASKSCOPE_PE); Appendix C § C. 10 tabulates their values and default messages.
The ParserError Entry Point
The game can define a ParserError routine to customize error messages. It
receives the error type as its argument. Return true to suppress the default
message, or false to let the library print its standard error.
[ ParserError etype;
switch (etype) {
CANTSEE_PE:
"You don't see anything like that here.";
NOTHELD_PE:
"You're not carrying that!";
VERB_PE:
"I beg your pardon?";
}
rfalse; ! Use library default for other errors
];
The UnknownVerb Entry Point
When the parser encounters a word in verb position that has no grammar
definition, it calls UnknownVerb (if defined). The routine receives the
dictionary address of the unknown word and can return a replacement dictionary
word (redirecting to a known verb) or false to let the standard error occur.
[ UnknownVerb word;
if (word == 'xyzzy') return 'cast';
rfalse;
];
The PrintVerb Entry Point
When the library needs to print a verb word (e.g., in error messages), it calls
PrintVerb after trying LanguageVerb. Return true if the routine handled
the printing, or false for the default.
[ PrintVerb verb;
if (verb == 'swim') { print "swim"; rtrue; }
rfalse;
];
19.9 The Input Buffer and Parse Table
The parser uses two main data structures to hold input: the buffer (raw character input) and the parse table (tokenized word list).
Z-Machine Layout
On the Z-machine, buffer is sized to hold 120 characters of input
(INPUT_BUFFER_LEN is WORDSIZE + 120), preceded by two header bytes: the
maximum length and the count of characters actually typed. The parse table
holds up to 15 words, each recorded as a 4-byte entry:
! Byte access (->) reads one byte; word access (-->) reads two bytes.
!
! buffer->0 : maximum characters allowed
! buffer->1 : number of characters typed (filled by VM)
! buffer->2+ : the typed characters
!
! parse->0 : maximum words allowed (15)
! parse->1 : number of words found
!
! After the two header bytes, each word occupies 4 bytes. For word k
! (1-based), those 4 bytes begin at byte offset 4k-2 inside parse:
! bytes 4k-2 .. 4k-1 : dictionary address (parse-->(2k-1) == 0 if not found)
! byte 4k : length of word (parse->(4k))
! byte 4k+1 : position in buffer (parse->(4k+1))
Glulx Layout
On Glulx, buffer is 260 bytes and the parse table holds up to 20 words. Each
parse entry occupies three machine words (12 bytes): the 32-bit dictionary
address, the word length, and the buffer position. parse-->0 holds the number
of words found.
Key Variables
| Variable | Purpose |
|---|---|
wn |
Current word index into the parse table (1-based). The parser advances this as it consumes words. |
num_words |
Total number of words in the current input. |
verb_word |
Dictionary address of the recognized verb word. |
verb_wordnum |
Position of the verb word in the input (1-based). |
Word Access Routines
The library provides routines for accessing words in the parse table:
NextWord() ! Returns dictionary address of word at wn,
! then advances wn. Returns 0 if not in dictionary.
NextWordStopped() ! Like NextWord() but returns -1 past end of input.
WordAddress(n) ! Returns the buffer address of word n.
WordLength(n) ! Returns the length of word n.
NumberWord(w) ! Takes a dictionary word w; if it is a spelled-out
! number word (in the LanguageNumbers table, e.g.
! 'one', 'two', ...) returns its value, else 0.
! To parse an input word as a number, use TryNumber(n).
Manipulating input
Games can modify the buffer and re-tokenize to alter what the parser sees. This
is typically done in BeforeParsing():
[ BeforeParsing i;
! Replace "please" at start of input with nothing
if (parse-->1 == 'please') {
for (i = 1 : i <= parse->1 - 1 : i++)
parse-->(i) = parse-->(i + 1);
parse->1 = parse->1 - 1;
num_words = num_words - 1;
}
];
Caution: The
parse-->(i) = parse-->(i+1)shift above is illustrative only. On the Z-machine, each parse entry is four bytes (a 2-byte dictionary address plus a length byte and a position byte), so shifting in 2-byte-->units moves half-entries: each dictionary-address slot receives its own entry's length and position bytes, and each length/position slot receives the next entry's dictionary address, corrupting every field of every entry. A correct in-place shift must operate on whole 4-byte entries, or the simplest safe approach is to callTokenise__(buffer, parse)after editing the rawbufferstring instead.
The Tokenise__() function can be called to re-tokenize the buffer after
modifications:
! Z-machine:
Tokenise__(buffer, parse);
! After modifying buffer contents, re-tokenize to update the
! parse table with new word boundaries and dictionary lookups.
The Keyboard() Function
Keyboard() is the top-level input routine. It:
- Prints the command prompt (after sending
##Prompt). - Reads a line of input from the player into
bufferviaKeyboardPrimitive, which uses the Z-machinereadopcode (or the Glulx equivalent) to perform tokenization; on GlulxKeyboardPrimitivealso callsTokenise__()itself. - Handles
OOPSif the first word isoops- repairs the previous buffer and callsTokenise__()to re-tokenize. - Handles
UNDOif the input is the single wordundo.
Game code rarely needs to call Keyboard() directly, but understanding its role
helps when debugging parser issues or writing advanced input manipulation.