1use bynk_syntax::error::CompileError;
29use bynk_syntax::span::Span;
30use bynk_ts::{TsExpr, TsType};
31
32pub const MISSING_CHECKER_FACT: &str = "bynk.internal.missing_checker_fact";
34
35const REPORT_URL: &str = "https://github.com/bynk-lang/bynk/issues";
37
38#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct InternalFault {
42 pub span: Span,
43 pub what: String,
44}
45
46impl InternalFault {
47 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#[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 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 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
90pub(crate) fn undefined_node() -> TsExpr {
93 TsExpr::Ident("undefined".to_string())
94}
95
96pub(crate) fn fault_type() -> TsType {
100 TsType::named("never")
101}
102
103pub(crate) fn unnameable_receiver_type_arg() -> TsType {
114 super::lower_list::any_ty()
115}
116
117#[cfg(test)]
118mod tests {
119 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 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 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 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 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 #[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 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 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}