Skip to main content

bynk_emit/emitter/
internal_fault.rs

1//! The one policy for a checker fact the emitter needs and does not find.
2//!
3//! A checked program carries every fact lowering reads: an expression's type,
4//! a call's callee, the arity of an argument list, a field's default. When one
5//! is absent the checker and the emitter disagree, which no program the user
6//! wrote can cause. The emitter used to answer that in four ways (an `any` in a
7//! type position, an `undefined` in a value position, a panic, and a silent
8//! `Ty::Error`), so a compiler fault could compile to a program that meant
9//! something else. It now answers it in one: [`LowerCtx::missing_fact`] records
10//! an [`InternalFault`] against the `.bynk` span and returns the `undefined`
11//! identifier so lowering carries on and reports every fault of the unit, not
12//! only the first. The unit's output is never used; the driver turns each
13//! fault into a `bynk.internal.missing_checker_fact` diagnostic.
14//!
15//! Three situations stay out of this path, and the sweep classified each
16//! fallback in `bynk-emit` as exactly one of them:
17//! 1. **a missing fact**: `missing_fact` / `missing_fact_ty`;
18//! 2. **a named widening**: the receiver type arguments of a generic instance
19//!    method, spelled by [`unnameable_receiver_type_arg`] (#2795);
20//! 3. **a legitimate default**: an `Option` in the Rust, rendered once as the
21//!    `undefined` identifier ([`undefined_node`]).
22//!
23//! The sink has the shape of [`RuntimeUse`](super::RuntimeUse): interior
24//! mutability, so it threads through the `&`-taking lowering tree without a
25//! `&mut` chain, and it lives on `RuntimeUse` itself because that is the one
26//! per-module accumulator every lowering context already shares.
27
28use bynk_syntax::error::CompileError;
29use bynk_syntax::span::Span;
30use bynk_ts::{TsExpr, TsType};
31
32/// The diagnostic code every [`InternalFault`] is reported under.
33pub const MISSING_CHECKER_FACT: &str = "bynk.internal.missing_checker_fact";
34
35/// Where to report a compiler fault.
36const REPORT_URL: &str = "https://github.com/bynk-lang/bynk/issues";
37
38/// One checker fact the emitter needed and did not find: the `.bynk` span of
39/// the construct being lowered, and a description of the fact.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct InternalFault {
42    pub span: Span,
43    pub what: String,
44}
45
46impl InternalFault {
47    /// The diagnostic the user sees: the code, the span, and the words
48    /// `bynk internal error` with where to report it.
49    pub fn into_compile_error(self) -> CompileError {
50        CompileError::new(
51            MISSING_CHECKER_FACT,
52            self.span,
53            [
54                "bynk internal error: the checker recorded no ",
55                self.what.as_str(),
56                ", which the code generator needs here. This is a compiler fault, not a problem \
57                 in your program; please report it at ",
58                REPORT_URL,
59            ]
60            .concat(),
61        )
62    }
63}
64
65/// Where a missing fact is reported: the module's sink and the `.bynk` span of
66/// the construct being lowered. `Copy`, so a lowering helper that holds neither
67/// the context nor the expression (the `Query` arms) carries one.
68#[derive(Clone, Copy)]
69pub(crate) struct FaultSite<'a> {
70    pub(crate) sink: &'a super::RuntimeUse,
71    pub(crate) span: Span,
72}
73
74impl FaultSite<'_> {
75    /// A missing fact in a value position: records it and returns the
76    /// `undefined` identifier ([`undefined_node`]).
77    pub(crate) fn missing_fact(&self, what: impl std::fmt::Display) -> TsExpr {
78        self.sink.note_internal_fault(self.span, what.to_string());
79        undefined_node()
80    }
81
82    /// A missing fact in a type position: records it and returns
83    /// [`fault_type`].
84    pub(crate) fn missing_fact_ty(&self, what: impl std::fmt::Display) -> TsType {
85        self.sink.note_internal_fault(self.span, what.to_string());
86        fault_type()
87    }
88}
89
90/// The `undefined` identifier: what a fault lowers to (its output is never
91/// used) and what a legitimate default, an absent optional slot, renders as.
92pub(crate) fn undefined_node() -> TsExpr {
93    TsExpr::Ident("undefined".to_string())
94}
95
96/// The type placeholder a fault in a type position lowers to. `never`, not
97/// `any`: the unit's output is discarded, and the placeholder must not look like
98/// a fallback to the `emit_silent_fallbacks` probe.
99pub(crate) fn fault_type() -> TsType {
100    TsType::named("never")
101}
102
103/// The one deliberate widening in the lowering (#2795), and not a fallback.
104///
105/// A generic instance method's explicit type arguments are spelled receiver's
106/// own parameters first, so a call with no argument of type `U` still types as
107/// written. A receiver argument is spelled only when it is a base or built-in
108/// type, which is in scope in every emitted module. Any other (a type the
109/// calling module may never import, or a type variable that may not be this
110/// function's) is `any`: the checker has already typed the call, so `any` in a
111/// receiver slot loses nothing. Changing it to `unknown` or a named type is a
112/// type-level output change that can break `tsc` inference.
113pub(crate) fn unnameable_receiver_type_arg() -> TsType {
114    super::lower_list::any_ty()
115}
116
117#[cfg(test)]
118mod tests {
119    //! Decision C (1A.34): one test per class of missing fact. Each takes one fact out of a
120    //! checked program, then asserts the fault is recorded at the right span and that lowering
121    //! continued (the whole unit lowered, so every fault of it is reported). The argument-arity
122    //! class needs a context (an agent construction, a cross-context call), which the single-file
123    //! pipeline here has not: it is held by `lower_call::agents` and `lower_call::cross_context`'s
124    //! own tests. The driver's mapping to a diagnostic is held by
125    //! `bynk_driver::project::tests`.
126    use super::*;
127    use crate::emitter::{BaseType, Expr, ExprKind, Ident, TypeBody};
128    use bynk_check::checker::{Callee, TypedCommons, certify};
129    use bynk_check::kernel_op::{KernelOp, OptionOp};
130
131    const SOURCE: &str = "commons demo\n\ntype P = { n: Int = 1 }\n\nfn total(xs: List[Int]) -> Int { xs.fold(0, (a, b) => a + b) }\n\nfn make() -> P { P { } }\n\nfn P.size(self) -> Int { self.n }\n\nfn probe(p: P) -> Int { p.size() }\n";
132
133    /// Check `SOURCE`, let `mutate` take a fact out, certify and emit. The faults, in order.
134    fn faults_after(mutate: impl FnOnce(&mut TypedCommons)) -> (String, Vec<InternalFault>) {
135        let (mut typed, warnings) =
136            crate::check_single_typed(SOURCE, crate::SingleFileMode::Build).expect("checks");
137        mutate(&mut typed);
138        let program = certify(typed, warnings).expect("certifies");
139        match crate::emitter::emit(&program) {
140            Ok(ts) => (ts, Vec::new()),
141            Err(faults) => (String::new(), faults),
142        }
143    }
144
145    /// The span of `needle`'s first occurrence in [`SOURCE`].
146    fn span_of(needle: &str) -> Span {
147        let start = SOURCE.find(needle).expect("in the source");
148        Span::new(start, start + needle.len())
149    }
150
151    /// The expression id of the call spelled `needle`.
152    fn call_id(typed: &TypedCommons, needle: &str) -> bynk_check::checker::ExprId {
153        let span = span_of(needle);
154        *typed
155            .expr_types
156            .iter()
157            .find(|(_, te)| te.span == span)
158            .map(|(id, _)| id)
159            .expect("the call is typed")
160    }
161
162    #[test]
163    fn a_checked_program_reports_no_fault() {
164        let (ts, faults) = faults_after(|_| {});
165        assert!(faults.is_empty(), "{faults:?}");
166        assert!(ts.contains("export function total"), "{ts}");
167    }
168
169    #[test]
170    fn a_missing_type_is_recorded_at_the_expression_and_lowering_continues() {
171        let (_, faults) = faults_after(|typed| {
172            let fold = call_id(typed, "xs.fold(0, (a, b) => a + b)");
173            typed.expr_types.remove(&fold);
174        });
175        assert_eq!(faults.len(), 1, "{faults:?}");
176        assert_eq!(faults[0].span, span_of("xs.fold(0, (a, b) => a + b)"));
177        assert!(
178            faults[0].what.contains("type for a `fold` call"),
179            "{faults:?}"
180        );
181    }
182
183    #[test]
184    fn a_callee_that_disagrees_with_the_receiver_is_recorded_at_the_call() {
185        let (_, faults) = faults_after(|typed| {
186            let fold = call_id(typed, "xs.fold(0, (a, b) => a + b)");
187            let int = typed
188                .tys()
189                .intern(bynk_check::checker::Ty::Base(BaseType::Int));
190            // `Option.map` resolved against an `Int` receiver.
191            typed.callees.insert(
192                fold,
193                Callee::Kernel {
194                    op: KernelOp::Option(OptionOp::Map),
195                    recv: int,
196                },
197            );
198        });
199        assert_eq!(faults.len(), 1, "{faults:?}");
200        assert_eq!(faults[0].span, span_of("xs.fold(0, (a, b) => a + b)"));
201        assert!(
202            faults[0]
203                .what
204                .contains("receiver type matching the resolved kernel op"),
205            "{faults:?}"
206        );
207    }
208
209    /// 1A.35a part C: an instance call whose receiver has no recorded type has no namespace to
210    /// call into, which used to lower to a `/* unknown */` placeholder; it is a fault now.
211    #[test]
212    fn a_receiver_with_no_namespace_is_recorded_at_the_receiver() {
213        let (_, faults) = faults_after(|typed| {
214            let at = SOURCE.find("p.size()").unwrap();
215            let receiver = typed
216                .expr_types
217                .iter()
218                .find(|(_, te)| te.span == Span::new(at, at + 1))
219                .map(|(id, _)| *id)
220                .expect("the receiver is typed");
221            typed.expr_types.remove(&receiver);
222        });
223        assert!(
224            faults
225                .iter()
226                .any(|f| f.what.contains("receiver namespace for an instance call")),
227            "{faults:?}"
228        );
229    }
230
231    #[test]
232    fn a_missing_field_default_is_recorded_at_the_construction() {
233        let (_, faults) = faults_after(|typed| {
234            // The checker required a closed-form default; take that away.
235            let mut decl = (**typed.types.get("P").expect("P")).clone();
236            if let TypeBody::Record(r) = &mut decl.body {
237                let field = &mut r.fields[0];
238                field.init = Some(Expr {
239                    id: bynk_check::checker::ExprId::SYNTHETIC,
240                    kind: ExprKind::Ident(Ident {
241                        name: "missing".to_string(),
242                        span: Span::new(0, 0),
243                    }),
244                    span: Span::new(0, 0),
245                });
246            }
247            typed
248                .types
249                .insert("P".to_string(), std::sync::Arc::new(decl));
250        });
251        assert_eq!(faults.len(), 1, "{faults:?}");
252        // The construction's type name, `P`, in `P { }`.
253        let construction = SOURCE.find("P { }").unwrap();
254        assert_eq!(faults[0].span, Span::new(construction, construction + 1));
255        assert!(
256            faults[0].what.contains("default value for field `n`"),
257            "{faults:?}"
258        );
259    }
260
261    #[test]
262    fn every_fault_of_a_unit_is_reported_not_only_the_first() {
263        let (_, faults) = faults_after(|typed| {
264            let fold = call_id(typed, "xs.fold(0, (a, b) => a + b)");
265            typed.expr_types.remove(&fold);
266            let mut decl = (**typed.types.get("P").expect("P")).clone();
267            if let TypeBody::Record(r) = &mut decl.body {
268                r.fields[0].init = Some(Expr {
269                    id: bynk_check::checker::ExprId::SYNTHETIC,
270                    kind: ExprKind::Ident(Ident {
271                        name: "missing".to_string(),
272                        span: Span::new(0, 0),
273                    }),
274                    span: Span::new(0, 0),
275                });
276            }
277            typed
278                .types
279                .insert("P".to_string(), std::sync::Arc::new(decl));
280        });
281        assert_eq!(faults.len(), 2, "{faults:?}");
282    }
283
284    #[test]
285    fn a_fault_becomes_the_coded_diagnostic() {
286        let fault = InternalFault {
287            span: Span::new(4, 9),
288            what: "type for a `fold` call".to_string(),
289        };
290        let error = fault.into_compile_error();
291        assert_eq!(error.category, MISSING_CHECKER_FACT);
292        assert_eq!(MISSING_CHECKER_FACT, "bynk.internal.missing_checker_fact");
293        assert_eq!((error.span.start, error.span.end), (4, 9));
294        assert!(
295            error.message.starts_with("bynk internal error:"),
296            "{}",
297            error.message
298        );
299        assert!(
300            error.message.contains("compiler fault"),
301            "{}",
302            error.message
303        );
304        assert!(error.message.contains(REPORT_URL), "{}", error.message);
305    }
306}