flowlog-build 0.3.0

Build-time FlowLog compiler for library mode.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Parse errors and grammar-contract internal errors.
//!
//! `ParseError` covers failures reachable from a user-authored `.dl` program:
//! syntax errors, duplicate declarations, references to undeclared relations,
//! broken include directives, and so on. Each variant carries a [`Span`] so
//! the renderer can point at the offending source.
//!
//! [`grammar_bug`] produces an [`InternalError`] for Pest grammar contracts
//! that should hold by construction (e.g. an `atom` rule always has an inner
//! `relation_name`). Those aren't user errors, but they still need to surface
//! as a structured diagnostic rather than a SIGABRT.

use std::path::PathBuf;

use codespan_reporting::diagnostic::{Diagnostic as CsDiagnostic, Label};
use thiserror::Error;

use crate::common::{
    BUG_URL, Diagnostic, FileId, InternalError, Span, primary_label, secondary_label,
};

/// Which `.decl`-style directive is being reported.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectiveKind {
    Input,
    Output,
    PrintSize,
}

impl std::fmt::Display for DirectiveKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            DirectiveKind::Input => ".input",
            DirectiveKind::Output => ".output",
            DirectiveKind::PrintSize => ".printsize",
        })
    }
}

/// Build the `[primary, secondary]` label pair for a "duplicate X, first
/// declared at Y" style diagnostic. Dummy spans (no source position) drop
/// out instead of pointing at a bogus file.
fn dup_labels(span: Span, prior: Span, here: &str, first: &str) -> Vec<Label<FileId>> {
    [
        primary_label(span).map(|l| l.with_message(here)),
        secondary_label(prior).map(|l| l.with_message(first)),
    ]
    .into_iter()
    .flatten()
    .collect()
}

/// Single-element label vec for diagnostics that only point at one span.
/// Returns an empty vec for dummy spans rather than fabricating a location.
fn primary_only(span: Span) -> Vec<Label<FileId>> {
    primary_label(span).into_iter().collect()
}

/// Errors raised while parsing a FlowLog program.
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum ParseError {
    /// Pest rejected the input with a grammar error.
    #[error("syntax error: {message}")]
    Syntax { span: Span, message: String },

    /// Two `.decl` declarations share a name (or case-colliding raw names).
    #[error("duplicate declaration of relation `{name}`")]
    DuplicateDecl {
        span: Span,
        prior: Span,
        name: String,
    },

    /// Two attributes in one `.decl` share a name (or case-colliding raw names).
    #[error("duplicate attribute `{name}` in relation `{relation}`")]
    DuplicateAttribute {
        span: Span,
        prior: Span,
        relation: String,
        name: String,
    },

    /// Two directives of the same kind target the same relation.
    #[error("duplicate {kind} directive for relation `{name}`")]
    DuplicateDirective {
        span: Span,
        prior: Span,
        kind: DirectiveKind,
        name: String,
    },

    /// A directive names a relation that was never `.decl`-d.
    #[error("{kind} directive references undeclared relation `{name}`")]
    UndeclaredInDirective {
        span: Span,
        kind: DirectiveKind,
        name: String,
    },

    /// A loop's `iterative [...]` list names a relation that was never `.decl`-d.
    #[error("iterative list references undeclared relation `{name}`")]
    UndeclaredInIterativeList { span: Span, name: String },

    /// A loop's `until`/`while` condition names a relation that was never `.decl`-d.
    #[error("loop condition references undeclared relation `{name}`")]
    UndeclaredLoopCondition { span: Span, name: String },

    /// A rule head or body atom names a relation that was never `.decl`-d.
    #[error("rule references undeclared relation `{name}`")]
    UndeclaredInRule { span: Span, name: String },

    /// A ground fact names a relation that was never `.decl`-d.
    #[error("fact references undeclared relation `{name}`")]
    UndeclaredInFact { span: Span, name: String },

    /// A `loop` / `fixpoint` block appeared outside `extend-*` mode.
    #[error("`loop`/`fixpoint` blocks require `--mode extend-batch` or `extend-inc`")]
    LoopBlockInStandardMode { span: Span },

    /// A loop's until-condition names a relation with nonzero arity.
    #[error("loop condition relation `{name}` must be nullary, but is declared with arity {arity}")]
    NonNullaryLoopCondition {
        span: Span,
        name: String,
        arity: usize,
    },

    /// A UDF call uses `_` as an argument; wildcards aren't allowed in UDF args.
    #[error("`_` placeholder is not allowed in arguments to UDF `{udf_name}`")]
    PlaceholderInUdf { span: Span, udf_name: String },

    /// A built-in call passes the wrong number of arguments. Carries the
    /// keyword string instead of the enum to keep this error layer
    /// independent of `crate::parser::logic::BuiltinOperator`.
    #[error("built-in `{op}` expects {expected} argument(s) but got {found}")]
    BuiltinArity {
        span: Span,
        op: &'static str,
        expected: usize,
        found: usize,
    },

    /// An `.include` directive's target could not be opened.
    #[error("failed to read included file `{}`: {source}", path.display())]
    IncludeIo {
        span: Span,
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// An `.include` chain cycles back to a file already being loaded.
    #[error("circular include of `{}`", path.display())]
    CircularInclude {
        span: Span,
        path: PathBuf,
        /// Files currently being loaded, outer-most first.
        chain: Vec<PathBuf>,
    },

    /// Two `.type` declarations share a name.
    #[error("duplicate `.type` declaration of `{name}`")]
    DuplicateTypeDecl {
        span: Span,
        prior: Span,
        name: String,
    },

    /// `.type X = Y` (or `<:`) where `Y` is undeclared.
    #[error("`.type {name} = ...` references unknown type `{parent}`")]
    UnknownTypeParent {
        span: Span,
        name: String,
        parent: String,
    },

    /// `.decl R(x: T)` where `T` is undeclared.
    #[error("attribute references unknown type `{name}`")]
    UnknownAttributeType { span: Span, name: String },

    /// `.init c = Foo<...>` where `Foo` was never declared as a `.comp`.
    #[error("unknown component `{name}`")]
    UnknownComponent { span: Span, name: String },

    /// `.comp A : B { ... }` where the inheritance chain cycles back to `A`.
    #[error("circular component inheritance involving `{name}`")]
    CircularInheritance { span: Span, name: String },

    /// `.init c = Foo<...>` passes a different number of type arguments
    /// than `Foo`'s `.comp` declaration accepts.
    #[error("component `{name}` expects {expected} type argument(s) but got {found}")]
    ComponentArityMismatch {
        span: Span,
        name: String,
        expected: usize,
        found: usize,
    },

    /// A dotted reference like `cfg.X` appears in a component body but
    /// `cfg` is neither a nested init nor a bound type-parameter.
    #[error("unresolved qualified reference `{path}`")]
    UnresolvedQualifiedRef { span: Span, path: String },

    /// `overridable` keyword on a top-level `.decl`. The keyword only
    /// makes sense inside a `.comp` body where a subcomponent might
    /// supply an `.override`.
    #[error("`overridable` is only allowed on a `.decl` inside a `.comp` body")]
    OverridableOutsideComp { span: Span, name: String },

    /// `.override Foo` in a subcomponent, but no `.decl Foo` was
    /// inherited from any parent component.
    #[error("override of undeclared relation `{name}`")]
    OverrideUnknownRelation { span: Span, name: String },

    /// `.override Foo` in a subcomponent, but the inherited `.decl Foo`
    /// is not marked `overridable`.
    #[error("override of non-overridable relation `{name}`")]
    OverrideOfNonOverridable {
        span: Span,
        prior: Span,
        name: String,
    },

    /// Subcomponent has `.override Foo` and also redeclares `.decl Foo`.
    /// Override only applies to *inherited* relations, so a local
    /// redeclaration would shadow the inherited decl and leave nothing
    /// for `.override` to target.
    #[error("override of non-inherited relation `{name}`")]
    OverrideRedeclaresRelation {
        span: Span,
        prior: Span,
        name: String,
    },

    /// A grammar contract the Pest grammar should have made unreachable. Not a
    /// user error; reported as an internal compiler bug.
    #[error(transparent)]
    Internal(#[from] InternalError),
}

impl ParseError {
    /// Construct a [`ParseError::Syntax`] from a Pest error, anchoring the
    /// span to `file`.
    pub(crate) fn syntax_from_pest(
        err: &pest::error::Error<crate::parser::Rule>,
        file: FileId,
    ) -> Self {
        use pest::error::InputLocation;
        let (start, end) = match err.location {
            InputLocation::Pos(p) => (p as u32, p as u32),
            InputLocation::Span((s, e)) => (s as u32, e as u32),
        };
        ParseError::Syntax {
            span: Span::new(file, start, end),
            message: err.variant.message().into_owned(),
        }
    }
}

impl Diagnostic for ParseError {
    fn to_diagnostic(&self) -> CsDiagnostic<FileId> {
        if let ParseError::Internal(e) = self {
            return e.to_diagnostic();
        }
        let base = CsDiagnostic::error().with_message(self.to_string());
        match self {
            ParseError::DuplicateDecl { span, prior, .. } => {
                base.with_labels(dup_labels(*span, *prior, "redeclared here", "first declared here"))
            }

            ParseError::DuplicateDirective { span, prior, .. } => base.with_labels(dup_labels(
                *span,
                *prior,
                "duplicate directive",
                "first directive here",
            )),

            ParseError::DuplicateAttribute { span, prior, .. } => base.with_labels(dup_labels(
                *span,
                *prior,
                "duplicate attribute here",
                "first declared here",
            )),

            ParseError::UndeclaredInDirective { span, name, .. } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "add a `.decl {name}(...)` before this directive"
                )]),

            ParseError::UndeclaredInIterativeList { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "either `.decl {name}(...)` it, or drop `{name}` from the iterative list"
                )]),

            ParseError::UndeclaredLoopCondition { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "declare `{name}` as a nullary relation with `.decl {name}()` and derive it inside the loop"
                )]),

            ParseError::UndeclaredInRule { span, name }
            | ParseError::UndeclaredInFact { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "add a matching `.decl {name}(...)` declaration, or remove the reference"
                )]),

            ParseError::CircularInclude { span, chain, .. } => {
                let mut diag = base.with_labels(primary_only(*span));
                if !chain.is_empty() {
                    let shown: Vec<String> = chain.iter().map(|p| p.display().to_string()).collect();
                    diag = diag.with_notes(vec![format!("include chain: {}", shown.join(""))]);
                }
                diag
            }

            ParseError::DuplicateTypeDecl { span, prior, .. } => base.with_labels(dup_labels(
                *span,
                *prior,
                "redeclared here",
                "first declared here",
            )),

            ParseError::UnknownTypeParent { span, parent, .. } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "declare `{parent}` with a `.type {parent} = ...` (or `<:`) earlier in the program"
                )]),

            ParseError::UnknownAttributeType { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "either use a built-in primitive or add `.type {name} = ...`"
                )]),

            ParseError::UnknownComponent { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "declare `{name}` with a `.comp {name} {{ ... }}` block"
                )]),

            ParseError::CircularInheritance { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "`.comp {name}` inherits transitively from itself; break the cycle"
                )]),

            ParseError::ComponentArityMismatch { span, .. } => {
                base.with_labels(primary_only(*span))
            }

            ParseError::UnresolvedQualifiedRef { span, path } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "the first segment of `{path}` must be either a nested `.init` instance in this component or a bound type-parameter"
                )]),

            ParseError::OverridableOutsideComp { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "remove `overridable` from this top-level `.decl {name}`, or move the declaration inside a `.comp` body"
                )]),

            ParseError::OverrideUnknownRelation { span, name } => base
                .with_labels(primary_only(*span))
                .with_notes(vec![format!(
                    "no inherited `.decl {name}(...) overridable` was found in any parent component"
                )]),

            ParseError::OverrideOfNonOverridable { span, prior, name } => base.with_labels(dup_labels(
                *span,
                *prior,
                "override target is not `overridable`",
                "declared without `overridable` here",
            )).with_notes(vec![format!(
                "add `overridable` to the parent `.decl {name}` to allow this override"
            )]),

            ParseError::OverrideRedeclaresRelation { span, prior, name } => base.with_labels(dup_labels(
                *span,
                *prior,
                "`.override` here",
                "relation redeclared in this comp here",
            )).with_notes(vec![format!(
                "`.override {name}` may only target an inherited relation; drop the local `.decl {name}` from this comp"
            )]),

            ParseError::Syntax { span, .. }
            | ParseError::LoopBlockInStandardMode { span }
            | ParseError::NonNullaryLoopCondition { span, .. }
            | ParseError::PlaceholderInUdf { span, .. }
            | ParseError::BuiltinArity { span, .. }
            | ParseError::IncludeIo { span, .. } => base.with_labels(primary_only(*span)),

            ParseError::Internal(_) => unreachable!("handled above"),
        }
    }

    fn is_internal(&self) -> bool {
        matches!(self, ParseError::Internal(_))
    }
}

/// Produce a `ParseError::Internal` for a Pest grammar-contract violation.
///
/// Use this at sites where an `.expect` would otherwise fire on an inner
/// token that the grammar guarantees — e.g. `"atom_rule always contains
/// relation_name"`. If such a site ever trips, it's a FlowLog bug, not a
/// user error.
pub(crate) fn grammar_bug(detail: impl Into<String>) -> ParseError {
    ParseError::Internal(InternalError::new("parser", detail, BUG_URL))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::SourceMap;
    use crate::common::{BoxError, emit};

    fn make_sm_with(text: &str) -> (SourceMap, FileId) {
        let mut sm = SourceMap::new();
        let f = sm.add("t.dl".into(), text.into());
        (sm, f)
    }

    fn render(err: ParseError, sm: &SourceMap) -> String {
        let err: BoxError = err.into();
        let mut buf: Vec<u8> = Vec::new();
        emit(&err, sm, &mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    }

    #[test]
    fn duplicate_decl_labels_both_sites() {
        let (sm, f) = make_sm_with(".decl Foo(x: int)\n.decl Foo(y: int)\n");
        let out = render(
            ParseError::DuplicateDecl {
                span: Span::new(f, 24, 27),
                prior: Span::new(f, 6, 9),
                name: "Foo".into(),
            },
            &sm,
        );
        assert!(out.contains("duplicate declaration"), "got: {out}");
        assert!(out.contains("redeclared here"), "got: {out}");
        assert!(out.contains("first declared here"), "got: {out}");
    }

    #[test]
    fn undeclared_in_directive_includes_help_note() {
        let (sm, f) = make_sm_with(".input Bar(filename=\"b.csv\")\n");
        let out = render(
            ParseError::UndeclaredInDirective {
                span: Span::new(f, 7, 10),
                kind: DirectiveKind::Input,
                name: "Bar".into(),
            },
            &sm,
        );
        assert!(out.contains(".input"), "got: {out}");
        assert!(out.contains("undeclared"), "got: {out}");
        assert!(out.contains("add a `.decl Bar"), "got: {out}");
    }

    #[test]
    fn internal_variant_renders_bug_note() {
        let (sm, _) = make_sm_with("");
        let out = render(grammar_bug("ghosts in the AST"), &sm);
        assert!(out.contains("bug"), "got: {out}");
        assert!(out.contains("ghosts in the AST"), "got: {out}");
        assert!(out.contains(BUG_URL), "got: {out}");
    }
}