Skip to main content

patch_prolog_frontend/parser/
mod.rs

1//! Operator-precedence parser for ISO Prolog programs and queries.
2//!
3//! Ported from patch-prolog's `parser.rs`, split into focused submodules:
4//! - [`operators`]: the operator-name table DATA (token → atom name).
5//! - [`term`]: term / primary parsing and the precedence-climbing levels.
6//! - [`clause`]: clause parsing and `:- ...` directive handling.
7//! - [`query`]: program / query entry points and goal-list parsing.
8//!
9//! Changes from v1: `fnv::FnvHashMap` → `std::collections::HashMap`, serde
10//! derives dropped, and `Term`/`Clause`/`StringInterner`/`VarId`/`AtomId`
11//! sourced from `plg_shared`.
12
13mod cg;
14mod clause;
15pub mod operators;
16mod query;
17mod term;
18
19pub use cg::CgClause;
20
21use crate::parse_error::ParseError;
22use crate::tokenizer::{Token, TokenKind};
23use plg_shared::{AtomId, Span, StringInterner, VarId};
24use std::collections::HashMap;
25
26/// Directives extracted from a program (`:- dynamic(f/1).` etc).
27///
28/// Currently `dynamic/1` and `io_format/1` are recognized. Future directives
29/// (e.g. `multifile`, `discontiguous`) extend this struct.
30#[derive(Debug, Default, Clone)]
31pub struct ProgramDirectives {
32    /// `(functor, arity)` pairs declared `:- dynamic(F/A).`.
33    /// A goal referencing a predicate in this set fails silently when no
34    /// clauses match, instead of throwing `existence_error`.
35    pub dynamic: Vec<(AtomId, usize)>,
36    /// Wire-encoding names the program declares via `:- io_format([...])`
37    /// (e.g. `[text, bson]`). Default `[text]`. The codegen-baked capability
38    /// table gates `--format`; encoders not listed are dead-stripped from the
39    /// binary. See docs/design/IO.md.
40    pub io_format: Vec<String>,
41}
42
43/// A source occurrence of an atom-functor term (`name` or `name(...)`),
44/// captured in `parse_primary`. This is a broad over-approximation of "call
45/// sites": it records *every* such term regardless of position — goals, but
46/// also atoms as constants (`X = foo`), atoms inside data (`p(foo, bar)`),
47/// functors in operator specs (`dynamic(foo/1)` records `dynamic`, `foo`,
48/// and `/`), and `[]` as `[]/0`. It never matches text in comments (those
49/// aren't parsed). The LSP narrows this to real calls by intersecting with
50/// the lint's undefined `(name, arity)` set, which keeps the false-positive
51/// surface small in practice.
52#[derive(Debug, Clone)]
53pub struct CallSite {
54    pub functor: AtomId,
55    pub arity: usize,
56    pub span: Span,
57}
58
59/// Parser for Edinburgh Prolog syntax.
60/// Parses tokens into Terms and Clauses, with variable scoping per clause.
61pub struct Parser<'a> {
62    tokens: Vec<Token>,
63    pos: usize,
64    interner: &'a mut StringInterner,
65    var_map: HashMap<String, VarId>,
66    next_var: VarId,
67    /// Atom-functor term occurrences, accumulated across the whole program
68    /// (not reset per clause — the LSP wants every buffer occurrence).
69    call_sites: Vec<CallSite>,
70    /// File id stamped on spans produced for the codegen path (SPANS.md
71    /// Layer 3). Default `0`; set per source by `parse_program_cg`.
72    file_id: plg_shared::FileId,
73}
74
75impl<'a> Parser<'a> {
76    /// Build a parser over already-tokenized input.
77    fn from_tokens(tokens: Vec<Token>, interner: &'a mut StringInterner) -> Self {
78        Parser {
79            tokens,
80            pos: 0,
81            interner,
82            var_map: HashMap::new(),
83            next_var: 0,
84            call_sites: Vec::new(),
85            file_id: 0,
86        }
87    }
88
89    /// Record an atom-functor term occurrence (see [`CallSite`]).
90    fn record_call_site(&mut self, functor: AtomId, arity: usize, span: Span) {
91        self.call_sites.push(CallSite {
92            functor,
93            arity,
94            span,
95        });
96    }
97
98    fn reset_vars(&mut self) {
99        self.var_map.clear();
100        self.next_var = 0;
101    }
102
103    fn current(&self) -> Option<&Token> {
104        self.tokens.get(self.pos)
105    }
106
107    fn current_kind(&self) -> Option<&TokenKind> {
108        self.current().map(|t| &t.kind)
109    }
110
111    fn at_eof(&self) -> bool {
112        matches!(self.current_kind(), None | Some(TokenKind::Eof))
113    }
114
115    fn advance(&mut self) -> &Token {
116        let tok = &self.tokens[self.pos];
117        self.pos += 1;
118        tok
119    }
120
121    /// Span of the current token, or a point at end-of-input if exhausted.
122    /// All parser errors point "here" — the position the parser stalled at.
123    fn here_span(&self) -> Span {
124        match self.current() {
125            Some(t) => Span::new(0, t.lo, t.hi),
126            None => self.eof_span(),
127        }
128    }
129
130    /// A point span at end of input (the `Eof` token's offset).
131    fn eof_span(&self) -> Span {
132        let off = self.tokens.last().map(|t| t.hi).unwrap_or(0);
133        Span::point(0, off)
134    }
135
136    /// Build a `ParseError` pointing at the current token.
137    fn error_here(&self, message: impl Into<String>) -> ParseError {
138        ParseError::new(message, self.here_span())
139    }
140
141    fn expect(&mut self, kind: &TokenKind) -> Result<(), ParseError> {
142        match self.current() {
143            Some(tok) if &tok.kind == kind => {
144                self.advance();
145                Ok(())
146            }
147            Some(tok) => {
148                let msg = format!("expected {}, got {}", kind, tok.kind);
149                Err(self.error_here(msg))
150            }
151            None => Err(self.error_here(format!("expected {kind}, got end of input"))),
152        }
153    }
154
155    /// Get the variable name map (for extracting query variable names in results).
156    pub fn var_names(&self) -> &HashMap<String, VarId> {
157        &self.var_map
158    }
159}