prolog-dcg-masterylisted
Install: claude install-skill dougransom/prolog-agent-toolkit
# Definite Clause Grammar (DCG) Mastery Guidelines
Use this skill when designing grammars, tokenizers, parsers, abstract syntax tree (AST) generators, or sequence serializers in Prolog.
## 1. Core Syntax & Modules
Always include standard DCG libraries across engines:
- **Scryer Prolog**: Requires explicit module import:
```prolog
:- use_module(library(dcgs)).
:- use_module(library(charsio)).
```
- **SWI / Trealla / Tau**: Standard syntax built-in or provided via standard library.
---
## 2. Bidirectional Parsing & Serialization
Structure DCG rules so they operate bi-directionally whenever possible:
```prolog
% Rule parses a sequence of digits to an integer or formats an integer to chars
integer_ast(N) -->
digits(Ds),
{ Ds \= [], number_chars(N, Ds) }.
digits([D|Ds]) --> digit(D), digits(Ds).
digits([]) --> [].
digit(D) --> [D], { member(D, "0123456789") }.
```
---
## 3. Pure Lookahead & Pushback Lists
Avoid non-logical cuts (`!`) inside DCG rules. Use **Pushback Lists** (right-hand side context insertion `[X], ...`) to implement lookahead cleanly:
```prolog
% Lookahead: inspect next character C without consuming it
peek(C), [C] --> [C].
% Rule matching an identifier until a delimiter without consuming the delimiter
identifier([C|Cs]) -->
[C],
{ char_type(C, alphanumeric) },
!, % Local deterministic match
identifier(Cs).
identifier([]) --> [].
```
---
## 4. AST Construction Patterns
Pass AST accumulator variables in rule arg