Skip to main content

polydat_core/dsl/
events.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Polydat compiler diagnostic event stream.
5//!
6//! The compiler emits typed events for each step: binding
7//! resolution, module inlining, type adaptation, constant folding,
8//! fusion, and compilation level selection: what `explain` retells.
9//!
10//! Events are tagged with severity levels:
11//! - **Info**: normal compilation steps (parsed, resolved, folded)
12//! - **Advisory**: type coercions, widenings, and implicit conversions
13//!   that the user should be aware of for module design quality
14//! - **Warning**: potential performance or correctness issues
15//! - **Error**: compilation failures (surfaced as Result::Err, not events)
16
17/// Severity level for compiler diagnostic events.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum EventLevel {
20    /// Normal compilation step — informational only.
21    Info,
22    /// Design advisory — implicit conversion or coercion that the user
23    /// should review for module quality. Surfaced by the binary's
24    /// `--stats` and `explain`.
25    Advisory,
26    /// Potential performance or correctness issue.
27    Warning,
28}
29
30/// A diagnostic event from the Polydat compilation pipeline.
31#[derive(Debug, Clone)]
32pub enum CompileEvent {
33    /// DSL source parsed into AST.
34    Parsed {
35        /// Top-level statements in the file.
36        statements: usize,
37    },
38    /// A binding was resolved from DSL to a node.
39    BindingResolved {
40        /// The binding's name.
41        name: String,
42        /// The node type it resolved to.
43        node_type: String,
44    },
45    /// A module was loaded and inlined.
46    ModuleInlined {
47        /// The module's name.
48        name: String,
49        /// Nodes the inlining added to the graph.
50        nodes_added: usize,
51    },
52    /// Type adapter inserted between mismatched ports.
53    TypeAdapterInserted {
54        /// The producing node.
55        from_node: String,
56        /// The consuming node.
57        to_node: String,
58        /// The adapter node inserted between them.
59        adapter: String,
60    },
61    /// Init-time constant folded (SRD 44).
62    ConstantFolded {
63        /// The node folded.
64        node: String,
65        /// The constant's rendered value.
66        value: String,
67    },
68    /// Fusion pattern matched and applied (SRD 36).
69    FusionApplied {
70        /// The fusion pattern's name.
71        pattern: String,
72        /// Nodes the fused node replaced.
73        nodes_replaced: usize,
74    },
75    /// Output declared.
76    OutputDeclared {
77        /// The output's name.
78        name: String,
79    },
80    /// Compilation level selected for a node.
81    CompileLevelSelected {
82        /// The node.
83        node: String,
84        /// The level's name.
85        level: String,
86    },
87    /// Config wire connected to a cycle-time source (performance warning).
88    ConfigWireCycleWarning {
89        /// The consuming node.
90        node: String,
91        /// The config port fed by a cycle-time source.
92        port: String,
93    },
94    /// Auto-widening type coercion inserted by the compiler.
95    TypeWidening {
96        /// The source type.
97        from: &'static str,
98        /// The type widened to.
99        to: &'static str,
100        /// Where the widening was inserted.
101        context: String,
102    },
103    /// A degenerate composition the comprehension validator warns
104    /// about (comprehension_forms.md §5.8): the comprehension
105    /// compiles and runs; a strict compile refuses it instead.
106    ComprehensionWarning {
107        /// The comprehension text as written.
108        source: String,
109        /// Line of the statement that names it.
110        line: usize,
111        /// Column of the statement that names it.
112        col: usize,
113        /// The warning, rendered.
114        warning: String,
115    },
116    /// Warning during compilation.
117    Warning {
118        /// The warning text.
119        message: String,
120    },
121    /// An extern with no default: `None` until the host sets it, and
122    /// every consumer reads `None` through it (engines.md §3.3).
123    ExternWithoutDefault {
124        /// The extern's name.
125        name: String,
126        /// Its declared type.
127        port_type: String,
128    },
129    /// Summary of the compiled program.
130    Summary {
131        /// Nodes in the compiled graph.
132        nodes: usize,
133        /// Declared outputs.
134        outputs: usize,
135        /// Init-time constants folded.
136        constants_folded: usize,
137    },
138    /// A module-level pragma was acknowledged. Recorded once per
139    /// recognised `// @pragma: <name>` directive at the top of the
140    /// source. Lets the binary's `--stats` and `explain` show which
141    /// graph transforms the module asked for.
142    PragmaAcknowledged {
143        /// The pragma's name.
144        name: String,
145        /// The source line it appears on.
146        line: usize,
147    },
148    /// An unrecognised module-level pragma was seen. Pragmas are
149    /// forward-compatible: an old binary parses a newer module
150    /// that opts into features it doesn't support, and the only
151    /// effect is this advisory.
152    UnknownPragma {
153        /// The pragma's name.
154        name: String,
155        /// The source line it appears on.
156        line: usize,
157    },
158    /// Strict-wire mode auto-inserted an assertion node between
159    /// `from_node` and `to_node`. SRD 15 §"Strict Wire Mode".
160    AssertionInserted {
161        /// The producing node.
162        from_node: String,
163        /// The consuming node.
164        to_node: String,
165        /// The assertion kind inserted.
166        kind: String,
167    },
168    /// Strict-wire mode considered inserting an assertion but
169    /// proved it redundant. The reason field names which skip
170    /// rule applied (constant source, upstream assertion, etc.).
171    AssertionSkipped {
172        /// The producing node.
173        from_node: String,
174        /// The consuming node.
175        to_node: String,
176        /// The skip rule that applied.
177        reason: String,
178    },
179    /// A tile hole was typed (SRD 114 §4): its expression, the wire
180    /// type the compiler inferred, the declared type if any, the
181    /// contextual expectation of its position, the encoder chosen, and
182    /// the adapter inserted between wire and declared type if one was.
183    TileHoleTyped {
184        /// The tile's name.
185        tile: String,
186        /// The hole's expression text.
187        hole: String,
188        /// The wire type the compiler inferred.
189        wire_type: String,
190        /// The declared type, if any.
191        declared: Option<String>,
192        /// The contextual expectation of the hole's position.
193        expectation: String,
194        /// The encoder chosen.
195        encoder: String,
196        /// The adapter inserted between wire and declared type, if any.
197        adapter: Option<String>,
198    },
199    /// A tile's skeleton (SRD 114 §6, §10): how many static runs it
200    /// copies and their byte total, its holes, branches, and
201    /// projections, and the source of each projection body program.
202    TileCompiled {
203        /// The tile's name.
204        tile: String,
205        /// The tile's encoding.
206        encoding: String,
207        /// Static runs the skeleton copies.
208        statics: usize,
209        /// Their byte total.
210        static_bytes: usize,
211        /// Holes.
212        holes: usize,
213        /// Branches.
214        branches: usize,
215        /// Projections.
216        projections: usize,
217        /// The source of each projection body program.
218        bodies: Vec<String>,
219    },
220}
221
222impl CompileEvent {
223    /// The severity level of this event.
224    pub fn level(&self) -> EventLevel {
225        match self {
226            // Info: normal steps
227            CompileEvent::Parsed { .. } => EventLevel::Info,
228            CompileEvent::BindingResolved { .. } => EventLevel::Info,
229            CompileEvent::ModuleInlined { .. } => EventLevel::Info,
230            CompileEvent::OutputDeclared { .. } => EventLevel::Info,
231            CompileEvent::CompileLevelSelected { .. } => EventLevel::Info,
232            CompileEvent::ConstantFolded { .. } => EventLevel::Info,
233            CompileEvent::FusionApplied { .. } => EventLevel::Info,
234            CompileEvent::Summary { .. } => EventLevel::Info,
235            CompileEvent::TileHoleTyped { adapter: None, .. } => EventLevel::Info,
236            CompileEvent::TileCompiled { .. } => EventLevel::Info,
237
238            // Advisory: implicit conversions the user should review
239            CompileEvent::TileHoleTyped {
240                adapter: Some(_), ..
241            } => EventLevel::Advisory,
242            CompileEvent::TypeAdapterInserted { .. } => EventLevel::Advisory,
243            CompileEvent::TypeWidening { .. } => EventLevel::Advisory,
244            CompileEvent::ComprehensionWarning { .. } => EventLevel::Advisory,
245            CompileEvent::PragmaAcknowledged { .. } => EventLevel::Advisory,
246            CompileEvent::AssertionInserted { .. } => EventLevel::Advisory,
247            CompileEvent::AssertionSkipped { .. } => EventLevel::Advisory,
248
249            // Warning: potential issues
250            CompileEvent::ConfigWireCycleWarning { .. } => EventLevel::Warning,
251            CompileEvent::Warning { .. } => EventLevel::Warning,
252            CompileEvent::ExternWithoutDefault { .. } => EventLevel::Warning,
253            CompileEvent::UnknownPragma { .. } => EventLevel::Warning,
254        }
255    }
256}
257
258/// Collects diagnostic events during compilation.
259#[derive(Debug, Default)]
260pub struct CompileEventLog {
261    events: Vec<CompileEvent>,
262}
263
264impl CompileEventLog {
265    /// An empty log.
266    pub fn new() -> Self {
267        Self { events: Vec::new() }
268    }
269
270    /// Record an event.
271    pub fn push(&mut self, event: CompileEvent) {
272        self.events.push(event);
273    }
274
275    /// Every event recorded, in order.
276    pub fn events(&self) -> &[CompileEvent] {
277        &self.events
278    }
279
280    /// Whether no event has been recorded.
281    pub fn is_empty(&self) -> bool {
282        self.events.is_empty()
283    }
284
285    /// Return only advisory-level events (type coercions, widenings).
286    /// These are the "module design quality" messages surfaced by the
287    /// binary's `--stats` and `explain`.
288    pub fn advisories(&self) -> Vec<&CompileEvent> {
289        self.events
290            .iter()
291            .filter(|e| e.level() == EventLevel::Advisory)
292            .collect()
293    }
294
295    /// Return only warning-level events.
296    pub fn warnings(&self) -> Vec<&CompileEvent> {
297        self.events
298            .iter()
299            .filter(|e| e.level() == EventLevel::Warning)
300            .collect()
301    }
302
303    /// Format all events as human-readable diagnostic lines.
304    /// Each line is prefixed with the severity tag.
305    pub fn format(&self) -> String {
306        self.events.iter().map(|e| {
307            let tag = match e.level() {
308                EventLevel::Info => "info",
309                EventLevel::Advisory => "advisory",
310                EventLevel::Warning => "warning",
311            };
312            let msg = match e {
313            CompileEvent::Parsed { statements } =>
314                format!("parsed {statements} statement(s)"),
315            CompileEvent::BindingResolved { name, node_type } =>
316                format!("resolved '{name}' → {node_type}"),
317            CompileEvent::ModuleInlined { name, nodes_added } =>
318                format!("module '{name}' inlined ({nodes_added} nodes)"),
319            CompileEvent::TypeAdapterInserted { from_node, to_node, adapter } =>
320                format!("type adapter {adapter}: {from_node} → {to_node}"),
321            CompileEvent::ConstantFolded { node, value } =>
322                format!("constant folded: {node} → {value}"),
323            CompileEvent::FusionApplied { pattern, nodes_replaced } =>
324                format!("fusion: {pattern} ({nodes_replaced} nodes replaced)"),
325            CompileEvent::OutputDeclared { name } =>
326                format!("output '{name}'"),
327            CompileEvent::CompileLevelSelected { node, level } =>
328                format!("{node} → {level}"),
329            CompileEvent::ConfigWireCycleWarning { node, port } =>
330                format!("config wire '{port}' on '{node}' connected to cycle-time source"),
331            CompileEvent::ComprehensionWarning { source, line, col, warning } =>
332                format!("`for {source}` at line {line}, col {col}: {warning}"),
333            CompileEvent::TypeWidening { from, to, context } =>
334                format!("widening {from} → {to} in {context}"),
335            CompileEvent::Warning { message } =>
336                message.to_string(),
337            CompileEvent::ExternWithoutDefault { name, port_type } =>
338                format!("extern '{name}' ({port_type}) has no default: it is `None` until the host sets it"),
339            CompileEvent::Summary { nodes, outputs, constants_folded } =>
340                format!("{nodes} nodes, {outputs} outputs, {constants_folded} constant(s) folded"),
341            CompileEvent::PragmaAcknowledged { name, line } =>
342                format!("pragma '{name}' acknowledged (line {line})"),
343            CompileEvent::UnknownPragma { name, line } =>
344                format!("unknown pragma '{name}' at line {line}; ignored"),
345            CompileEvent::AssertionInserted { from_node, to_node, kind } =>
346                format!("assertion inserted: {from_node} → {to_node} ({kind})"),
347            CompileEvent::AssertionSkipped { from_node, to_node, reason } =>
348                format!("assertion skipped: {from_node} → {to_node} ({reason})"),
349            CompileEvent::TileHoleTyped { tile, hole, wire_type, declared, expectation, encoder, adapter } =>
350                format!(
351                    "tile '{tile}' hole `{hole}`: wire {wire_type}{} expects {expectation}, encoder {encoder}{}",
352                    declared.as_ref().map(|d| format!(", declared {d},")).unwrap_or_else(|| ",".to_string()),
353                    adapter.as_ref().map(|a| format!(", adapter {a}")).unwrap_or_default()
354                ),
355            CompileEvent::TileCompiled { tile, encoding, statics, static_bytes, holes, branches, projections, .. } =>
356                format!(
357                    "tile '{tile}' ({encoding}): {statics} static run(s), {static_bytes} bytes; {holes} hole(s), {branches} branch(es), {projections} projection(s)"
358                ),
359            };
360            format!("polydat[{tag}]: {msg}")
361        }).collect::<Vec<_>>().join("\n")
362    }
363}