Skip to main content

dsl_kit_parse/
allow.rs

1//! Usage-site lint suppression: the reserved `$allow` annotation and
2//! the diagnostics it can produce.
3//!
4//! A lint rule fires at a node. Sometimes the author of that node knows
5//! better than the rule, and the only place that knowledge lives is the
6//! node itself — not a project-wide configuration file, which would
7//! switch the rule off everywhere and lose the reason. So a document
8//! may annotate a node with the rule names it accepts there:
9//!
10//! ```json
11//! { "type": "Par", "$allow": ["max-fan-out"], "branches": [ … ] }
12//! ```
13//!
14//! ## Reserved key
15//!
16//! The annotation is spelled [`ALLOW_KEY`] (`"$allow"`). The `$` sigil
17//! cannot appear in a Rust identifier, so the key can never collide
18//! with a field or child slot a DSL author declares — the same
19//! reservation that lets [`crate::import::IMPORT_VARIANT`] spell
20//! `$import` without a namespace. Keys are dispatched against the
21//! schema by name, so a reserved key is recognised before schema
22//! dispatch and never reaches the unknown-key path.
23//!
24//! One interaction with `$import` is worth naming: an object carrying
25//! both `$import` and `$allow` is rejected as
26//! [`crate::import::import_codes::SPEC_SHAPE`], because an import
27//! placeholder must be a single-key object. Annotate the imported
28//! source's own nodes instead.
29//!
30//! The text spelling is refused symmetrically: `@allow("x") @import
31//! "y"` is a [`codes::UNCOLLAPSED`] diagnostic from [`collapse`]. The
32//! loader replaces the placeholder with the imported tree, which would
33//! carry the annotation away with the node it was written on — and a
34//! suppression that quietly does nothing is exactly what the shape
35//! rules here exist to prevent.
36//!
37//! ## Shape
38//!
39//! The value must be an array of rule-name strings. An empty array is
40//! accepted and means the same as no annotation at all. Anything else
41//! — a bare string, a number, an array with a non-string element — is
42//! a [`codes::ALLOW_SHAPE`] diagnostic rather than a silently ignored
43//! key, because a mis-spelled suppression that quietly does nothing is
44//! worse than one that fails loudly.
45//!
46//! ## Where the names go
47//!
48//! The front-end stores them verbatim on [`ParseTree::allows`]; the
49//! names are not validated against a rule registry here, since the
50//! parse trunk does not know which rules exist. `#[derive(DslBuild)]`
51//! carries them to [`dsl_kit_core::AllowTable`], keyed on the
52//! [`NodeId`](dsl_kit_core::NodeId) minted for the annotated node,
53//! and a linter resolves them there.
54//!
55//! ## The text spelling
56//!
57//! The two front-ends are deliberately asymmetric. JSON recognises
58//! `$allow` unconditionally — a reserved key costs a document nothing
59//! until it spells one. The canonical text front-end is opt-in:
60//! [`add_allow_syntax`] injects the `@allow("rule") <node>` spelling
61//! into a [`Grammar`], and a grammar that never passes through it does
62//! not accept `@allow` anywhere, the same shape
63//! [`crate::import::add_import_syntax`] has.
64//!
65//! Where the annotation sits differs too, because the two surfaces
66//! differ: an object has a spare key, a text node has only the
67//! position in front of it. So text spells it as a **wrapper**:
68//!
69//! ```text
70//! @allow("max-fan-out") Par(branches: [ … ])
71//! @allow("max-fan-out", "max-depth") Par(branches: [ … ])
72//! ```
73//!
74//! parses to a reserved [`ALLOW_VARIANT`] node holding the annotated
75//! node in its [`ALLOW_TARGET_SLOT`] child, and [`collapse`] — which
76//! [`Grammar::parse`] runs on every text parse — folds the wrapper
77//! away onto its target's [`ParseTree::allows`]. Downstream therefore
78//! never sees the wrapper, and the two front-ends hand it the same
79//! tree for the same document. A wrapper that does reach
80//! [`check_conformance`](crate::check_conformance) is a
81//! [`codes::UNCOLLAPSED`] diagnostic there, the way an unexpanded
82//! `$import` is.
83//!
84//! [`ParseTree::allows`]: crate::ParseTree::allows
85//! [`Grammar::parse`]: crate::peg::Grammar::parse
86
87use crate::import::IMPORT_VARIANT;
88use crate::peg::{self, Grammar, Peg};
89use crate::{BuildError, Diagnostic, ParseTree, RawValue, Span};
90use dsl_kit_core::IdGen;
91use serde_json::Value;
92
93/// Reserved object key carrying a node's usage-site lint suppressions
94/// in the JSON front-end.
95pub const ALLOW_KEY: &str = "$allow";
96
97/// Reserved [`ParseTree::variant`](crate::ParseTree::variant) spelling
98/// for an un-collapsed `@allow` wrapper in the text front-end.
99///
100/// Same `$` sigil, same reservation argument as [`ALLOW_KEY`]: it
101/// cannot collide with a variant a DSL author declares. The two
102/// constants share a spelling but not a position — one is an object
103/// key, the other a variant name.
104pub const ALLOW_VARIANT: &str = "$allow";
105
106/// Payload field on an [`ALLOW_VARIANT`] wrapper carrying one rule
107/// name. A wrapper naming several rules carries the field once per
108/// name, in the order written.
109pub const ALLOW_RULES_FIELD: &str = "rules";
110
111/// Child slot on an [`ALLOW_VARIANT`] wrapper holding the single node
112/// the annotation applies to.
113pub const ALLOW_TARGET_SLOT: &str = "target";
114
115/// Diagnostic codes emitted by the `$allow` annotation machinery.
116pub mod codes {
117    /// The [`ALLOW_KEY`](super::ALLOW_KEY) value is not an array of
118    /// rule-name strings.
119    pub const ALLOW_SHAPE: &str = "dsl_kit::parse::allow::allow_shape";
120    /// An [`ALLOW_VARIANT`](super::ALLOW_VARIANT) wrapper survived
121    /// [`collapse`](super::collapse) — either because the document
122    /// never went through it and the wrapper reached
123    /// [`check_conformance`](crate::check_conformance), or because the
124    /// wrapper was malformed and the fold refused to guess.
125    pub const UNCOLLAPSED: &str = "dsl_kit::parse::allow::uncollapsed";
126}
127
128// ---------------------------------------------------------------------------
129// Text syntax injection
130// ---------------------------------------------------------------------------
131
132/// Adds the reserved `@allow("rule") <node>` spelling to a text
133/// grammar.
134///
135/// Appends a rule named [`ALLOW_VARIANT`] whose body is
136/// `Node("$allow", %kw:@allow "(" Field("rules", %str)+ ")"
137/// Field("target", <start>))`, and makes it an alternative of the
138/// grammar's start rule — for grammars generated by
139/// [`crate::schema_gen`], the start rule is the `node` choice every
140/// child slot references, so an annotation is writable at every node
141/// position. A start rule whose body is not a [`Peg::Choice`] is
142/// wrapped in one.
143///
144/// Opt-in by design: a grammar that never passes through this function
145/// accepts no `@allow` syntax at all, and the reserved rule is
146/// invisible to [`crate::example_gen`] (examples never spell `@allow`)
147/// and exempt from [`crate::grammar_check`]'s schema-consistency pass.
148///
149/// Idempotent — a grammar that already carries the reserved rule is
150/// returned unchanged. Fails with [`crate::peg::codes::UNKNOWN_RULE`]
151/// if the start rule is not defined.
152pub fn add_allow_syntax(grammar: &mut Grammar, ids: &IdGen) -> Result<(), BuildError> {
153    let already = grammar
154        .rules
155        .iter()
156        .any(|r| matches!(r, Peg::Rule { name, .. } if name == ALLOW_VARIANT));
157    if already {
158        return Ok(());
159    }
160
161    let start = grammar.start.clone();
162    let start_rule = grammar
163        .rules
164        .iter_mut()
165        .find(|r| matches!(r, Peg::Rule { name, .. } if *name == start));
166    let Some(Peg::Rule { body, .. }) = start_rule else {
167        return Err(BuildError::single(Diagnostic::error(
168            peg::codes::UNKNOWN_RULE,
169            format!("cannot add allow syntax: start rule `{start}` is not defined"),
170        )));
171    };
172
173    match body.as_mut() {
174        Peg::Choice { alts, .. } => alts.push(peg::rule_ref(ids, ALLOW_VARIANT)),
175        _ => {
176            let dummy = peg::token(ids, "");
177            let old = std::mem::replace(body.as_mut(), dummy);
178            **body = peg::choice(ids, vec![old, peg::rule_ref(ids, ALLOW_VARIANT)]);
179        }
180    }
181
182    // Each name lands in its own `Field`, so the wrapper carries one
183    // `rules` entry per rule rather than one entry holding every name
184    // concatenated — a `Field` joins the text productions it collects,
185    // which would fuse `"a", "b"` into `ab`.
186    let name = |ids: &IdGen| peg::field(ids, ALLOW_RULES_FIELD, peg::token(ids, "%str"));
187    grammar.rules.push(peg::rule(
188        ids,
189        ALLOW_VARIANT,
190        peg::node(
191            ids,
192            ALLOW_VARIANT,
193            peg::seq(
194                ids,
195                vec![
196                    peg::token(ids, "%kw:@allow"),
197                    peg::token(ids, "("),
198                    name(ids),
199                    peg::repeat(
200                        ids,
201                        peg::seq(ids, vec![peg::token(ids, ","), name(ids)]),
202                        0,
203                        None,
204                    ),
205                    peg::token(ids, ")"),
206                    peg::field(ids, ALLOW_TARGET_SLOT, peg::rule_ref(ids, start)),
207                ],
208            ),
209        ),
210    ));
211    Ok(())
212}
213
214// ---------------------------------------------------------------------------
215// Collapse
216// ---------------------------------------------------------------------------
217
218/// Folds every [`ALLOW_VARIANT`] wrapper in `tree` onto its target's
219/// [`ParseTree::allows`](crate::ParseTree::allows).
220///
221/// [`Grammar::parse`](crate::peg::Grammar::parse) applies this to
222/// every text parse, so a host wires up nothing: a document that never
223/// spells `@allow` has no wrapper to fold and comes back as it went
224/// in. Front-ends that build wrappers themselves call it directly.
225///
226/// Stacked wrappers (`@allow("a") @allow("b") X`) fold onto the same
227/// target, outermost name first. The surviving node keeps the
228/// **target's** span: the wrapper's span covers the annotation the
229/// author wrote, which is not where a diagnostic about the annotated
230/// node should point.
231///
232/// Fails with [`codes::UNCOLLAPSED`] on a wrapper the fold cannot
233/// consume — no target, more than one, a `rules` payload that is not a
234/// string, any other slot. The injected grammar cannot produce those
235/// shapes; a hand-built tree can, and dropping the annotated subtree
236/// quietly would be the wrong kind of forgiving.
237///
238/// It fails the same way on a wrapper whose target is an
239/// [`IMPORT_VARIANT`] placeholder, which the grammar *can* produce:
240/// the annotation would survive the fold only to be discarded when the
241/// loader substitutes the imported tree.
242pub fn collapse(tree: ParseTree) -> Result<ParseTree, BuildError> {
243    fold(tree).map_err(BuildError::new)
244}
245
246/// Recursive half of [`collapse`]. Diagnostics from distinct wrappers
247/// are collected before failing, as everywhere else in the trunk.
248fn fold(mut tree: ParseTree) -> Result<ParseTree, Vec<Diagnostic>> {
249    if tree.variant == ALLOW_VARIANT {
250        return fold_wrapper(tree);
251    }
252
253    let mut diags = Vec::new();
254    for (_, slot) in &mut tree.children {
255        for child in std::mem::take(slot) {
256            match fold(child) {
257                Ok(t) => slot.push(t),
258                Err(ds) => diags.extend(ds),
259            }
260        }
261    }
262    for (_, entries) in &mut tree.keyed_children {
263        for (key, child) in std::mem::take(entries) {
264            match fold(child) {
265                Ok(t) => entries.push((key, t)),
266                Err(ds) => diags.extend(ds),
267            }
268        }
269    }
270    if diags.is_empty() {
271        Ok(tree)
272    } else {
273        Err(diags)
274    }
275}
276
277/// Folds one wrapper: read its names, take its single target, fold
278/// that target in turn, and prepend the names to whatever the target
279/// already carries.
280fn fold_wrapper(tree: ParseTree) -> Result<ParseTree, Vec<Diagnostic>> {
281    let span = tree.span;
282    let ParseTree {
283        fields,
284        children,
285        keyed_children,
286        allows,
287        ..
288    } = tree;
289
290    let mut diags = Vec::new();
291    let mut names = Vec::new();
292    for (field, value) in fields {
293        if field != ALLOW_RULES_FIELD {
294            diags.push(malformed(
295                span,
296                format!("carries an unexpected field `{field}`"),
297            ));
298            continue;
299        }
300        match value {
301            RawValue::Text(s) | RawValue::Json(Value::String(s)) => names.push(s),
302            _ => diags.push(malformed(
303                span,
304                format!("carries a `{ALLOW_RULES_FIELD}` payload that is not a rule name"),
305            )),
306        }
307    }
308    if !allows.is_empty() {
309        diags.push(malformed(
310            span,
311            "carries suppressions of its own".to_string(),
312        ));
313    }
314    for (slot, _) in keyed_children {
315        diags.push(malformed(
316            span,
317            format!("carries a keyed child slot `{slot}`"),
318        ));
319    }
320
321    let mut target = None;
322    for (slot, mut nodes) in children {
323        if slot != ALLOW_TARGET_SLOT {
324            diags.push(malformed(
325                span,
326                format!("carries an unexpected child slot `{slot}`"),
327            ));
328        } else if target.is_some() {
329            diags.push(malformed(
330                span,
331                format!("carries more than one `{ALLOW_TARGET_SLOT}` slot"),
332            ));
333        } else if nodes.len() != 1 {
334            diags.push(malformed(
335                span,
336                format!(
337                    "holds {} nodes in its `{ALLOW_TARGET_SLOT}` slot, not the one it annotates",
338                    nodes.len()
339                ),
340            ));
341        } else {
342            target = Some(nodes.remove(0));
343        }
344    }
345
346    let Some(target) = target else {
347        if diags.is_empty() {
348            diags.push(malformed(
349                span,
350                format!("has no `{ALLOW_TARGET_SLOT}` child to annotate"),
351            ));
352        }
353        return Err(diags);
354    };
355    // The one malformed shape the injected grammar can produce. The
356    // fold would happily move the names onto the placeholder, and the
357    // loader would then replace that placeholder — annotation and all
358    // — with the imported tree, so the suppression the author wrote
359    // would silently do nothing.
360    if target.variant == IMPORT_VARIANT {
361        diags.push(malformed(
362            span,
363            format!(
364                "annotates an `{IMPORT_VARIANT}` placeholder, which cannot carry a \
365                 suppression; annotate the imported source's own nodes instead"
366            ),
367        ));
368    }
369    if !diags.is_empty() {
370        return Err(diags);
371    }
372
373    let mut target = fold(target)?;
374    names.append(&mut target.allows);
375    target.allows = names;
376    Ok(target)
377}
378
379fn malformed(span: Option<Span>, what: String) -> Diagnostic {
380    Diagnostic::error(
381        codes::UNCOLLAPSED,
382        format!("`{ALLOW_VARIANT}` wrapper {what}"),
383    )
384    .with_span(span)
385}