← ClaudeAtlas

prolog-dcg-masterylisted

Definite Clause Grammar (DCG) standards and advanced patterns. Use when parsing text, lexing tokens, building ASTs, generating binary/text output, handling lookahead without cuts, error recovery, and using pushback lists.
dougransom/prolog-agent-toolkit · ★ 4 · AI & Automation · score 60
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