buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// ===============================================================================
// BUILDLANG TYPE SYSTEM - ERRORS
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Type system error types.

use std::fmt;
use thiserror::Error;

use super::ty::*;
use crate::lexer::Span;

/// Result type for type operations.
pub type TypeResult<T> = Result<T, TypeError>;

/// A type error with location information.
#[derive(Debug, Clone)]
pub struct TypeErrorWithSpan {
    /// The error.
    pub error: TypeError,
    /// The span where the error occurred.
    pub span: Span,
    /// Optional help message.
    pub help: Option<String>,
    /// Optional notes.
    pub notes: Vec<String>,
    /// An exact-edit fix, when the checker knows one.
    pub fix: Option<crate::diagnostics::Fix>,
}

impl TypeErrorWithSpan {
    /// Create a new type error with span.
    pub fn new(error: TypeError, span: Span) -> Self {
        Self {
            error,
            span,
            help: None,
            notes: Vec::new(),
            fix: None,
        }
    }

    /// Attach an exact-edit fix.
    pub fn with_fix(mut self, fix: crate::diagnostics::Fix) -> Self {
        self.fix = Some(fix);
        self
    }

    /// Add a help message.
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());
        self
    }

    /// Add a note.
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }
}

impl fmt::Display for TypeErrorWithSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.error)?;
        let suggestion = self.error.suggestion();
        for help in crate::diagnostics::help_lines_with_fix(
            self.help.as_deref(),
            suggestion.as_deref(),
            self.fix.as_ref(),
        ) {
            write!(f, "\n  help: {}", help)?;
        }
        for note in &self.notes {
            write!(f, "\n  note: {}", note)?;
        }
        Ok(())
    }
}

impl std::error::Error for TypeErrorWithSpan {}

/// The tail of a duplicate-definition message: where the first one is.
fn first_definition_note(first_line: &Option<u32>) -> String {
    match first_line {
        Some(line) => format!(" is already defined on line {line}"),
        None => String::new(),
    }
}

/// Type errors.
#[derive(Debug, Clone, Error)]
pub enum TypeError {
    // =========================================================================
    // UNIFICATION ERRORS
    // =========================================================================
    /// Types do not match.
    #[error("type mismatch: expected `{expected}`, found `{found}`")]
    TypeMismatch { expected: Ty, found: Ty },

    /// Infinite type (occurs check failure).
    #[error("infinite type: `{var}` occurs in `{ty}`")]
    InfiniteType { var: TyVarId, ty: Ty },

    /// Mutability mismatch.
    #[error("mutability mismatch: expected `{expected:?}`, found `{found:?}`")]
    MutabilityMismatch {
        expected: Mutability,
        found: Mutability,
    },

    /// A write through a shared (read-only) reference to a slice or array.
    #[error("cannot write through `{name}`: it is a read-only `&[T]`; take a `&mut [T]` (or use `slice::from_raw_parts_mut`) to write")]
    WriteThroughReadOnly { name: String },

    /// Array length mismatch.
    #[error("array length mismatch: expected `{expected}`, found `{found}`")]
    ArrayLengthMismatch { expected: usize, found: usize },

    /// Arity mismatch (wrong number of arguments).
    #[error("expected {expected} arguments, found {found}")]
    ArityMismatch { expected: usize, found: usize },

    /// Unsafety mismatch.
    #[error("unsafety mismatch")]
    UnsafetyMismatch,

    /// Lifetime mismatch.
    #[error("lifetime mismatch: expected `{expected}`, found `{found}`")]
    LifetimeMismatch {
        expected: super::ty::Lifetime,
        found: super::ty::Lifetime,
    },

    /// ABI mismatch.
    #[error("ABI mismatch: expected `{expected}`, found `{found}`")]
    AbiMismatch {
        expected: std::sync::Arc<str>,
        found: std::sync::Arc<str>,
    },

    // =========================================================================
    // LOOKUP ERRORS
    // =========================================================================
    /// Undefined variable.
    #[error("undefined variable: `{name}`")]
    UndefinedVariable { name: String },

    /// Undefined type.
    #[error("undefined type: `{name}`")]
    UndefinedType { name: String },

    /// Undefined function.
    #[error("undefined function: `{name}`")]
    UndefinedFunction { name: String },

    /// Undefined field.
    #[error("type `{ty}` has no field `{field}`")]
    UndefinedField { ty: Ty, field: String },

    /// Undefined method.
    #[error("type `{ty}` has no method `{method}`")]
    UndefinedMethod { ty: Ty, method: String },

    /// Undefined variant.
    #[error("enum `{enum_name}` has no variant `{variant}`")]
    UndefinedVariant { enum_name: String, variant: String },

    // =========================================================================
    // EXPRESSION ERRORS
    // =========================================================================
    /// Cannot call non-function type.
    #[error("type `{ty}` is not callable")]
    NotCallable { ty: Ty },

    /// No overloaded method matches the argument-type tuple (after arity
    /// filter). Lists the argument types and the available candidate signatures.
    #[error("no method `{name}` matches argument types ({arg_tys}); candidates:\n{candidates}")]
    NoMatchingMethod {
        name: String,
        arg_tys: String,
        candidates: String,
    },

    /// Two or more equally-most-specific overloaded methods match; the call is
    /// ambiguous. Lists the tied candidate signatures (Julia-style).
    #[error(
        "call to `{name}` is ambiguous for argument types ({arg_tys}); \
         equally-specific candidates:\n{candidates}"
    )]
    AmbiguousMethod {
        name: String,
        arg_tys: String,
        candidates: String,
    },

    /// An overloaded name referenced as a bare value (not called). Multiple
    /// dispatch requires a call with arguments to select a method.
    #[error(
        "`{name}` is an overloaded function ({count} definitions); \
         referencing it as a value is ambiguous. Call it with arguments so \
         multiple dispatch can select a method"
    )]
    AmbiguousFunctionReference { name: String, count: usize },

    /// Cannot index non-array type.
    #[error("type `{ty}` cannot be indexed")]
    NotIndexable { ty: Ty },

    /// Cannot dereference non-pointer type.
    #[error("type `{ty}` cannot be dereferenced")]
    NotDereferenceable { ty: Ty },

    /// Cannot apply the try operator to this type.
    #[error("type `{ty}` cannot be used with `?`")]
    NotTryable { ty: Ty },

    /// Cannot apply the await operator to this type.
    #[error("type `{ty}` cannot be used with `.await`")]
    NotAwaitable { ty: Ty },

    /// Cannot borrow variable as mutable while it is already borrowed.
    #[error("cannot borrow `{variable}` as mutable because it is already borrowed")]
    AlreadyBorrowed { variable: String },

    /// Cannot borrow variable as mutable more than once at a time.
    #[error("cannot borrow `{variable}` as mutable more than once at a time")]
    DoubleMutableBorrow { variable: String },

    /// Cannot use a moved value.
    #[error("use of moved value: `{variable}`")]
    UseAfterMove { variable: String },

    /// Reference to local variable escapes function scope.
    #[error("cannot return reference to local variable `{variable}`")]
    ReferenceEscapesScope { variable: String },

    /// A `#[linear]` value was used after it was already consumed.
    ///
    /// Values whose nominal type is marked `#[linear]` may be moved/consumed
    /// at most once (no-cloning). This enforces qubit no-cloning, on-chain
    /// no-double-spend, and resource-handle safety. Borrow it with `&` to read
    /// it without consuming, or restructure so it is consumed on exactly one path.
    #[error("use of linear value `{name}` after it was consumed (linear values cannot be cloned or used twice)")]
    LinearUseAfterMove { name: String },

    /// A `#[linear]` value was borrowed (read) after it was already consumed.
    ///
    /// A borrow reads the value without consuming it, but the value is already
    /// gone: whatever consumed it took ownership, so there is nothing left to
    /// read. Reported within this statement (MIR spans are statement-level).
    /// Move the borrow before the consuming use, or restructure so the value is
    /// consumed on exactly one path after every read.
    #[error("borrow of linear value `{name}` after it was consumed within this statement (nothing remains to read once a linear value is moved)")]
    LinearBorrowAfterMove { name: String },

    /// A `#[linear]` value was moved out of a shared (`&`) borrow.
    ///
    /// A shared borrow grants read-only access; moving the referent out would
    /// consume a value the borrow does not own, duplicating or invalidating it
    /// past no-cloning. Reported within this statement (MIR spans are
    /// statement-level). Take the value by `&mut`/by value, or read it through
    /// the shared borrow without moving.
    #[error("cannot move linear value `{name}` out of a shared borrow within this statement (a `&` borrow does not own its referent; moving it would violate no-cloning)")]
    LinearMoveOutOfBorrow { name: String },

    /// A non-`#[linear]` aggregate has a field whose type is `#[linear]`.
    ///
    /// A linear value placed in an untracked aggregate could be read out
    /// repeatedly, laundering it past no-cloning. The container must itself
    /// be marked `#[linear]` so the whole aggregate is move-tracked.
    #[error("non-linear type `{container}` cannot contain linear field `{field}: {field_type}` (mark `{container}` as `#[linear]`)")]
    LinearFieldInNonLinearType {
        container: String,
        field: String,
        field_type: String,
    },

    /// A `#[linear]` value appeared in a position the move-analysis cannot
    /// track (a tuple/array element, a generic argument, a closure capture, a
    /// value moved out of a reference, ...), where it could be silently
    /// duplicated. Conservatively rejected to preserve no-cloning.
    #[error("linear value cannot be used in {context}: it could be duplicated there (linear values must stay in tracked positions: a local, a parameter, a borrow, or a by-value argument of its own type)")]
    LinearInUnsupportedPosition { context: String },

    /// A `par_for` / `par_map` body could write state another index reads
    /// (M5): a `&mut` or `*mut` parameter, a `static mut`, or a variable from
    /// outside a closure.
    #[error("`{call}` body `{body}` can write shared state: {detail}")]
    ParallelSharedWrite {
        call: String,
        body: String,
        detail: String,
    },

    /// Invalid binary operation.
    #[error("cannot apply binary operator `{op}` to types `{left}` and `{right}`")]
    InvalidBinaryOp { op: String, left: Ty, right: Ty },

    /// Invalid unary operation.
    #[error("cannot apply unary operator `{op}` to type `{ty}`")]
    InvalidUnaryOp { op: String, ty: Ty },

    /// Integer literal does not fit the requested concrete integer type.
    #[error("integer literal `{literal}` is out of range for type `{ty}`")]
    IntegerLiteralOutOfRange { literal: String, ty: String },

    /// Compile-time integer arithmetic overflow in a constant expression.
    #[error("integer overflow in {op} for type `{ty}`")]
    IntegerOverflow { op: String, ty: String },

    /// Invalid assignment target.
    #[error("invalid assignment target")]
    InvalidAssignTarget,

    /// Cannot assign to immutable binding.
    #[error("cannot assign to immutable variable `{name}`")]
    ImmutableAssignment { name: String },

    // =========================================================================
    // PATTERN ERRORS
    // =========================================================================
    /// Pattern type mismatch.
    #[error("pattern type mismatch: expected `{expected}`, found `{found}`")]
    PatternMismatch { expected: Ty, found: Ty },

    /// Refutable pattern in irrefutable position.
    #[error("refutable pattern in irrefutable position")]
    RefutablePattern,

    /// Non-exhaustive patterns.
    #[error("non-exhaustive patterns")]
    NonExhaustivePatterns,

    /// Non-exhaustive match (missing specific enum variants).
    #[error("non-exhaustive match: missing variants {}", missing_variants.join(", "))]
    NonExhaustiveMatch { missing_variants: Vec<String> },

    // =========================================================================
    // CONTROL FLOW ERRORS
    // =========================================================================
    /// Break outside of loop.
    #[error("`break` outside of loop")]
    BreakOutsideLoop,

    /// Continue outside of loop.
    #[error("`continue` outside of loop")]
    ContinueOutsideLoop,

    /// Reference to a loop label that is not in scope.
    #[error("use of undefined loop label `'{label}`")]
    UndefinedLoopLabel { label: String },

    /// Return outside of function.
    #[error("`return` outside of function")]
    ReturnOutsideFunction,

    /// Missing return type.
    #[error("function returns `{found}` but expected `{expected}`")]
    ReturnTypeMismatch { expected: Ty, found: Ty },

    // =========================================================================
    // TRAIT ERRORS
    // =========================================================================
    /// Trait not implemented.
    #[error("the trait bound `{ty}: {trait_id:?}` is not satisfied")]
    TraitNotImplemented {
        ty: Ty,
        trait_id: super::traits::TraitId,
    },

    /// Ambiguous trait resolution.
    #[error("multiple implementations of trait `{trait_name}` for type `{ty}`")]
    AmbiguousImpl { trait_name: String, ty: Ty },

    /// Associated type not found.
    #[error("associated type `{name}` not found in trait `{trait_name}`")]
    AssocTypeNotFound { name: String, trait_name: String },

    /// Associated type not defined in impl.
    #[error("associated type `{assoc_name}` not defined")]
    AssociatedTypeNotDefined { assoc_name: String },

    /// Internal error.
    #[error("internal error: {0}")]
    InternalError(String),

    /// A parsed language construct the downstream pipeline (checker/codegen)
    /// does not yet support. Rejecting loudly here prevents a silent
    /// miscompile: parse-only constructs must never reach codegen and be
    /// silently discarded.
    #[error("`{construct}` is not yet supported: {detail}")]
    UnsupportedConstruct { construct: String, detail: String },

    /// A struct or enum holds itself by value, so it has no finite size and
    /// the C backend cannot lay it out. A `Box<T>` field breaks the cycle.
    #[error("recursive type `{name}` has infinite size: {path}")]
    InfiniteSizeType { name: String, path: String },

    // =========================================================================
    // GENERICS ERRORS
    // =========================================================================
    /// Wrong number of type arguments.
    #[error("expected {expected} type arguments, found {found}")]
    WrongTypeArgCount { expected: usize, found: usize },

    /// Bound not satisfied.
    #[error("type `{ty}` does not satisfy bound `{bound}`")]
    BoundNotSatisfied { ty: Ty, bound: String },

    // =========================================================================
    // OTHER ERRORS
    // =========================================================================
    /// Duplicate definition. `first_line` is the line of the earlier
    /// definition when the source text was at hand.
    #[error("duplicate definition: `{name}`{}", first_definition_note(.first_line))]
    DuplicateDefinition {
        name: String,
        first_line: Option<u32>,
    },

    /// Type annotation required.
    #[error("type annotations needed")]
    TypeAnnotationNeeded,

    /// Unsafe operation outside unsafe block.
    #[error("unsafe operation outside of `unsafe` block")]
    UnsafeOutsideUnsafe,

    /// Internal error.
    #[error("internal type error: {0}")]
    Internal(String),

    // =========================================================================
    // EFFECT ERRORS
    // =========================================================================
    /// Unknown effect: the effect has not been declared.
    #[error("unknown effect `{name}`")]
    UnknownEffect { name: String },

    /// Unhandled effect: a function performs an effect but does not declare it.
    #[error("function `{func_name}` performs effect `{effect_name}` but does not declare it")]
    UnhandledEffect {
        func_name: String,
        effect_name: String,
    },

    /// Undeclared effect: a function body performs an effect not in the signature.
    #[error("function performs undeclared effect `{effect_name}`")]
    UndeclaredEffect {
        func_name: String,
        effect_name: String,
        declared_effects: Vec<String>,
    },

    /// Unknown effect operation.
    #[error("unknown operation `{operation}` in effect `{effect_name}`")]
    UnknownEffectOperation {
        effect_name: String,
        operation: String,
    },

    /// A `par_for` / `par_map` body performs an effect (M5). A parallel body
    /// runs on any thread in any order, so its effect row must be empty.
    #[error("`{call}` body `{body}` performs `{effects}`; a parallel body must have an empty effect row")]
    ParallelBodyEffect {
        call: String,
        body: String,
        effects: String,
    },

    /// A `par_for` / `par_map` body the checker cannot see into (M5).
    #[error("the `{call}` body cannot be checked: {detail}")]
    ParallelBodyUnknown { call: String, detail: String },

    /// Missing handler clause: a handle block does not cover all operations.
    #[error("handler for effect `{effect_name}` is missing operation `{operation}`")]
    MissingHandlerClause {
        effect_name: String,
        operation: String,
    },

    // =========================================================================
    // UNIT ERRORS (experimental: unit-annotated numeric types, `f64<m/s>`)
    // =========================================================================
    /// Unit dimensions disagree at a unification boundary (assignment,
    /// annotation, argument, return).
    #[error("unit mismatch: expected `{expected}`, found `{found}` (dimensions differ)")]
    UnitMismatch { expected: String, found: String },

    /// Unit dimensions disagree for a specific operation (add/subtract/compare),
    /// wording identical to units::UnitError::Mismatch.
    #[error("unit mismatch: cannot {operation} `{left}` and `{right}` (dimensions differ)")]
    UnitOperationMismatch {
        operation: &'static str,
        left: String,
        right: String,
    },

    /// A trigonometric, exponential or logarithmic operation got a value
    /// with a dimension. `sin(3 m)` has no meaning; divide by a reference
    /// quantity in the same unit first.
    #[error("unit mismatch: `{operation}` needs a dimensionless value, found `{found}`")]
    UnitNotDimensionless { operation: String, found: String },

    /// A root of a unit whose exponents do not divide (`.sqrt()` of `m`),
    /// which has no unit with integer exponents.
    #[error("unit mismatch: `.{method}()` of `{found}` has no unit with integer exponents")]
    UnitRootNotExact { method: String, found: String },

    /// A `#[measured]` constant without a source, with an unknown key, or on
    /// an item that is not a `const`.
    #[error("measured constant `{name}`: {reason}")]
    MeasuredConstantInvalid { name: String, reason: String },

    // =========================================================================
    // MODULE ERRORS
    // =========================================================================
    /// A `mod NAME;` chain resolves back to a file already being loaded.
    /// Reported instead of recursing into a stack overflow: the module graph
    /// has a cycle and cannot be loaded. Names the path and the module that
    /// closed the loop.
    #[error("module import cycle: `{path}` is already being loaded (module `{module}` imports back into it)")]
    ModuleImportCycle { path: String, module: String },

    // =========================================================================
    // MACRO ERRORS
    // =========================================================================
    /// A formatting macro (`println!`, `print!`, `eprintln!`, `eprint!`,
    /// `format!`) whose first argument is not a string literal. The lowering
    /// takes its format string from the first string literal it finds, so
    /// `println!(read_file("ops.toml"))` used to print the path `ops.toml`
    /// instead of the file contents, and `println!(r#"text"#)` printed an
    /// empty line. The call is rejected instead.
    #[error("`{macro_name}!` needs a plain string literal as its first argument, found {found}")]
    FormatArgNotStringLiteral { macro_name: String, found: String },

    // =========================================================================
    // BACKEND ERRORS
    // =========================================================================
    /// The program type-checks but the C backend cannot compile it. `buildc
    /// check` lowers every program to C, so this is reported by `check` as well
    /// as by `build` and `run`: a passing check means the program compiles.
    #[error("{message}")]
    BackendRejected { message: String },

    /// A `law` or an `ensures` clause is false on a concrete input that
    /// `buildc verify` found and re-ran.
    #[error("{message}")]
    SpecRefuted { message: String },

    /// The verifier's prover claimed an obligation that a concrete input
    /// refutes: a defect in the verifier, never reported as proved.
    #[error("{message}")]
    SpecInconsistent { message: String },
}

impl TypeError {
    /// Check if this is a fatal error that should stop type checking.
    pub fn is_fatal(&self) -> bool {
        matches!(
            self,
            TypeError::Internal(_) | TypeError::ModuleImportCycle { .. }
        )
    }

    /// Get a suggested fix for this error.
    pub fn suggestion(&self) -> Option<String> {
        match self {
            TypeError::TypeMismatch { expected, .. } => {
                Some(format!(
                    "change this expression so it has type `{}`, or change the annotation or signature that requires `{}`",
                    expected, expected
                ))
            }
            TypeError::ImmutableAssignment { name } => {
                Some(format!("consider making `{}` mutable: `let mut {}`", name, name))
            }
            TypeError::TypeAnnotationNeeded => {
                Some("consider adding a type annotation".to_string())
            }
            TypeError::UnsafeOutsideUnsafe => {
                Some("consider wrapping in an `unsafe` block".to_string())
            }
            TypeError::UnknownEffect { name } => {
                Some(format!(
                    "define the effect:\n  effect {} {{\n      fn operation_name(params) -> ReturnType,\n  }}",
                    name
                ))
            }
            TypeError::UnhandledEffect { func_name, effect_name } => {
                Some(format!(
                    "either add `~ {}` to the function signature:\n  fn {}() ~ {} {{ ... }}\n\nor handle the effect with a handler:\n  handle {{ ... }} with {{\n      {}.operation(args) => |resume| {{\n          // handle the operation\n          resume(())\n      }},\n  }}",
                    effect_name, func_name, effect_name, effect_name
                ))
            }
            TypeError::UndeclaredEffect { func_name: _, effect_name, declared_effects } => {
                let mut row = declared_effects.clone();
                row.push(effect_name.clone());
                Some(format!(
                    "add `{}` to the function's effect row: `~ {}`",
                    effect_name,
                    row.join(" + ")
                ))
            }
            TypeError::UnknownEffectOperation { effect_name, operation } => {
                Some(format!(
                    "effect `{}` does not define operation `{}`; check available operations",
                    effect_name, operation
                ))
            }
            TypeError::MissingHandlerClause { effect_name, operation } => {
                Some(format!(
                    "add a handler clause for `{}`:\n  {}.{}(params) => |resume| {{\n      // handle the {} operation\n      resume(())\n  }},",
                    operation, effect_name, operation, operation
                ))
            }
            TypeError::UndefinedLoopLabel { label } => {
                Some(format!(
                    "label an enclosing loop with `'{}:` (for example `'{}: loop {{ ... }}`)",
                    label, label
                ))
            }
            TypeError::NonExhaustiveMatch { missing_variants } => {
                Some(format!(
                    "add arms for the missing variants: {}, or add a wildcard `_` arm",
                    missing_variants.join(", ")
                ))
            }
            TypeError::NonExhaustivePatterns => {
                Some("add a wildcard `_` arm to cover the remaining values".to_string())
            }
            TypeError::FormatArgNotStringLiteral { macro_name, found } => {
                if found.starts_with("a raw") {
                    Some(format!(
                        "raw strings are not supported as format strings yet; write a plain \"...\" literal with escapes, or pass the raw string as a value: `{}!(\"{{}}\", r#\"...\"#)`",
                        macro_name
                    ))
                } else {
                    Some(format!(
                        "pass the value through a `{{}}` placeholder: `{}!(\"{{}}\", <expr>)`",
                        macro_name
                    ))
                }
            }
            _ => None,
        }
    }
}