Parse a Small Command Language with Prolog DCGs
Use Prolog definite clause grammars to parse commands, verify complete input consumption with phrase/2, and recover from invalid tokens without external libraries.
14 Mar 2026, 14:00 UTC

Goal
Parse a tiny command language such as move north, take key, or drop lamp into Prolog structure using a definite clause grammar (DCG). A DCG is a grammar notation that Prolog expands into ordinary predicates carrying two hidden difference-list arguments: one for the input not yet consumed and one for the remainder after a match. The parser must accept only complete commands, reject incomplete input, and report unexpected tokens without crashing.
Prerequisites
- A Prolog system with built-in DCG expansion, such as SWI-Prolog, GNU Prolog, or SICStus Prolog. No external libraries are required for basic parsing.
- Input represented as a list of tokens, for example
[move, north], or as a list of character codes if you prefer character-level grammars. - A text editor and access to the Prolog top-level console.
Procedure
1. Write the grammar rules
Create a file, for example command_parser.pl. Use --> instead of :- for grammar rules.
command --> action, target.
action --> [move].
action --> [take].
action --> [drop].
target --> [north].
target --> [south].
target --> [key].
target --> [lamp].
Each bracketed item such as [move] is a terminal that consumes one token from the input list. Nonterminals such as command, action, and target expand into predicates with two hidden list arguments during compilation.
2. Add a strict entry point
Expose a predicate that runs the grammar and demands that nothing is left over.
parse_command(Tokens) :-
phrase(command, Tokens).
phrase/2 succeeds only when the grammar consumes the entire input list. If tokens remain, phrase/2 fails, which signals an incomplete or invalid command.
3. Consult the file and run checks
Run these queries in the Prolog top-level, replacing command_parser.pl with your actual path. No special permissions are needed beyond read access to the file; parsing itself does not modify the database.
?- [command_parser].
?- phrase(command, [move, north]).
?- phrase(command, [take, lamp]).
?- phrase(command, [move]).
?- phrase(command, [eat, cake]).
Expected behavior: the first two queries succeed. The third fails because [move] leaves no target, so the grammar cannot complete. The fourth fails because eat and cake match no terminals.
4. Inspect the expansion
Use listing/1 to confirm that DCG expansion inserted the hidden difference-list arguments.
?- listing(command).
The displayed clauses should show extra arguments beyond the visible grammar nonterminal, and terminals should appear as equality or list-consumption checks rather than --> rules. If your system supports source-level DCG debugging, use it; otherwise the debugger will show the expanded predicates, which can obscure the failure point.
5. Add tolerant recovery (optional)
If the caller should survive unexpected input instead of failing outright, add a catch-all nonterminal that consumes one bad token, reports it, and continues.
start --> command.
start --> [Bad], {report_bad(Bad)}, start.
report_bad(Token) :-
format('Unexpected token: ~w~n', [Token]).
The {...} construct executes an ordinary Prolog goal inside the grammar. Here it prints a diagnostic. Because start can consume one bad token and recurse, phrase/2 can succeed on input that contains garbage after a valid command, while still logging each bad token.
Alternatively, wrap parsing in catch/3 to convert failure into a structured exception for the caller. Parsing does not change program state, so there is no rollback to perform after a failed parse.
Expected checks
| Check | Command | Expected result |
|---|---|---|
| Valid complete command | phrase(command, [move, north]) | Succeeds |
| Valid complete command | phrase(command, [drop, key]) | Succeeds |
| Incomplete command | phrase(command, [move]) | Fails |
| Unknown tokens | phrase(command, [eat, cake]) | Fails |
| Trailing garbage (strict mode) | phrase(command, [move, north, junk]) | Fails |
| Expansion inspection | listing(command) | Shows hidden difference-list arguments |
Limitations
- List-based DCGs copy the remaining input on each step. For long inputs, tokenize first or use an accumulator-based grammar; otherwise parsing can become slow.
- A cut (
!) inside a DCG commits to the current alternative and discards other parses. Place a cut only after deterministic lookahead confirms the choice; a premature cut can lose valid parses. - Debuggers typically display expanded predicates rather than DCG source unless your Prolog system supports source-level DCG debugging.
Practical verification
After consulting the grammar, run phrase(command, [move, north]) and confirm success. Then run phrase(command, [move, north, extra]) in strict mode and confirm failure. If you added the catch-all rule, confirm that phrase(start, [move, north, extra]) succeeds and prints the unexpected-token diagnostic. No output should be treated as authoritative until you observe it in your own Prolog session.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.