formawasm 0.0.1-beta

Backend that compiles a typed FormaLang IR module into a WebAssembly component.
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
//! Pre-flight rejection of IR shapes the backend cannot handle.
//!
//! Runs as the first step inside `WasmBackend::generate`. The goal is
//! to fail fast with a typed error when an upstream pass was skipped
//! (monomorphisation, closure conversion) or when the module crosses
//! the component boundary with a type that cannot be expressed in
//! WIT.
//!
//! Each rejection returns a [`PreflightError`] variant carrying a
//! human-readable breadcrumb so the surfaced diagnostic points at the
//! offending item.

use formalang::ast::Visibility;
use formalang::ir::{
    IrBlockStatement, IrExpr, IrField, IrFunction, IrImpl, IrLet, IrMatchArm, IrModule, IrStruct,
    IrTrait, ResolvedType,
};
use thiserror::Error;

/// Errors produced by [`check`].
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum PreflightError {
    /// An [`IrExpr::Closure`] survived `ClosureConversionPass`. The
    /// backend only accepts the post-conversion [`IrExpr::ClosureRef`]
    /// form.
    #[error(
        "unconverted IrExpr::Closure in {location}; ClosureConversionPass must run before WasmBackend::generate"
    )]
    UnconvertedClosure {
        /// Breadcrumb pointing at the offending expression.
        location: String,
    },

    /// A public struct field has a closure type. Closures cannot cross
    /// the WIT boundary.
    #[error(
        "pub struct '{struct_name}' field '{field}' has closure type — closures cannot cross the WIT boundary"
    )]
    PublicClosureField {
        /// Name of the offending struct.
        struct_name: String,
        /// Name of the offending field.
        field: String,
    },

    /// A trait still carries generic parameters. `MonomorphisePass`
    /// should have specialised every generic-trait impl by now.
    #[error(
        "trait '{trait_name}' still has {param_count} generic parameter(s); MonomorphisePass must run before WasmBackend::generate"
    )]
    GenericTrait {
        /// Name of the offending trait.
        trait_name: String,
        /// Number of unresolved generic parameters.
        param_count: usize,
    },

    /// A [`ResolvedType::TypeParam`] reached the backend, meaning the
    /// module was not fully monomorphised.
    #[error("ResolvedType::TypeParam('{name}') in {location}; module must be monomorphised first")]
    UnresolvedTypeParam {
        /// Name of the unresolved parameter (e.g. `"T"`).
        name: String,
        /// Breadcrumb pointing at the offending location.
        location: String,
    },

    /// A [`ResolvedType::Error`] placeholder reached the backend. The
    /// frontend should have returned its associated `CompilerError`
    /// before invoking the backend.
    #[error(
        "ResolvedType::Error placeholder in {location}; upstream compilation must have failed before reaching the backend"
    )]
    ErrorTypePlaceholder {
        /// Breadcrumb pointing at the offending location.
        location: String,
    },
}

/// Run all pre-flight checks against `module`. Short-circuits on the
/// first violation.
pub fn check(module: &IrModule) -> Result<(), PreflightError> {
    for s in &module.structs {
        check_struct(s)?;
    }
    for t in &module.traits {
        check_trait(t)?;
    }
    for e in &module.enums {
        check_enum(e)?;
    }
    for l in &module.lets {
        check_let(l)?;
    }
    for f in &module.functions {
        check_function(f, &format!("function '{}'", f.name))?;
    }
    for i in &module.impls {
        check_impl(i, module)?;
    }
    Ok(())
}

// ───────────────────────────────────────────────────────────────────
// Item-level checks
// ───────────────────────────────────────────────────────────────────

fn check_struct(s: &IrStruct) -> Result<(), PreflightError> {
    // Generic struct *definitions* (e.g. the prelude's `Array<T>`,
    // `Range<T>`, `Dictionary<K,V>`) keep their `TypeParam(_)`
    // placeholders in field types — those resolve at every
    // monomorphic instantiation site, not in the generic
    // declaration itself. Walking the field types would surface
    // the placeholders as `UnresolvedTypeParam` errors. Skip the
    // body walk; the closure-field check above doesn't trip on
    // `TypeParam` so it still runs for non-generic definitions.
    if !s.generic_params.is_empty() {
        return Ok(());
    }
    let is_public = matches!(s.visibility, Visibility::Public);
    for field in &s.fields {
        if is_public && matches!(field.ty, ResolvedType::Closure { .. }) {
            return Err(PreflightError::PublicClosureField {
                struct_name: s.name.clone(),
                field: field.name.clone(),
            });
        }
        check_type(
            &field.ty,
            &format!("struct '{}' field '{}'", s.name, field.name),
        )?;
        check_field_default(field, &s.name)?;
    }
    Ok(())
}

fn check_field_default(field: &IrField, owner: &str) -> Result<(), PreflightError> {
    if let Some(default) = &field.default {
        check_expr(default, &format!("default for {owner}::{}", field.name))?;
    }
    Ok(())
}

fn check_trait(t: &IrTrait) -> Result<(), PreflightError> {
    if !t.generic_params.is_empty() {
        return Err(PreflightError::GenericTrait {
            trait_name: t.name.clone(),
            param_count: t.generic_params.len(),
        });
    }
    for field in &t.fields {
        check_type(
            &field.ty,
            &format!("trait '{}' field '{}'", t.name, field.name),
        )?;
    }
    for sig in &t.methods {
        let where_ = format!("trait '{}' method '{}'", t.name, sig.name);
        for p in &sig.params {
            if let Some(ty) = &p.ty {
                check_type(ty, &format!("{where_} parameter '{}'", p.name))?;
            }
        }
        if let Some(rt) = &sig.return_type {
            check_type(rt, &format!("{where_} return type"))?;
        }
    }
    Ok(())
}

fn check_enum(e: &formalang::ir::IrEnum) -> Result<(), PreflightError> {
    // Skip the body of generic enum *declarations* (the prelude's
    // `Optional<T>` is the canonical case). Their variant fields
    // carry `TypeParam(_)` placeholders by design; each
    // monomorphic instantiation supplies a real type elsewhere.
    if !e.generic_params.is_empty() {
        return Ok(());
    }
    for variant in &e.variants {
        for field in &variant.fields {
            check_type(
                &field.ty,
                &format!(
                    "enum '{}' variant '{}' field '{}'",
                    e.name, variant.name, field.name
                ),
            )?;
        }
    }
    Ok(())
}

fn check_let(l: &IrLet) -> Result<(), PreflightError> {
    let location = format!("let '{}'", l.name);
    check_type(&l.ty, &location)?;
    check_expr(&l.value, &location)?;
    Ok(())
}

fn check_function(f: &IrFunction, location: &str) -> Result<(), PreflightError> {
    for p in &f.params {
        if let Some(ty) = &p.ty {
            check_type(ty, &format!("{location} parameter '{}'", p.name))?;
        }
    }
    if let Some(rt) = &f.return_type {
        check_type(rt, &format!("{location} return type"))?;
    }
    if let Some(body) = &f.body {
        check_expr(body, &format!("{location} body"))?;
    }
    Ok(())
}

fn check_impl(i: &IrImpl, module: &IrModule) -> Result<(), PreflightError> {
    let target_name = match i.target {
        formalang::ir::ImplTarget::Struct(id) => module
            .get_struct(id)
            .map_or_else(|| format!("struct#{}", id.0), |s| s.name.clone()),
        formalang::ir::ImplTarget::Enum(id) => module
            .get_enum(id)
            .map_or_else(|| format!("enum#{}", id.0), |e| e.name.clone()),
        formalang::ir::ImplTarget::Primitive(p) => format!("primitive {p:?}"),
    };
    for f in &i.functions {
        check_function(f, &format!("impl '{target_name}' method '{}'", f.name))?;
    }
    Ok(())
}

// ───────────────────────────────────────────────────────────────────
// Type walker
// ───────────────────────────────────────────────────────────────────

fn check_type(ty: &ResolvedType, location: &str) -> Result<(), PreflightError> {
    match ty {
        ResolvedType::Primitive(_)
        | ResolvedType::Struct(_)
        | ResolvedType::Trait(_)
        | ResolvedType::Enum(_) => Ok(()),

        ResolvedType::Tuple(fields) => {
            for (_, inner) in fields {
                check_type(inner, location)?;
            }
            Ok(())
        }

        // The four prelude compounds (Optional / Array / Range /
        // Dictionary) all flow through here under formalang
        // 0.0.4-beta — their type args are walked the same way as
        // any user-defined generic.
        ResolvedType::Generic { args, .. } => {
            for arg in args {
                check_type(arg, location)?;
            }
            Ok(())
        }

        ResolvedType::External { type_args, .. } => {
            for arg in type_args {
                check_type(arg, location)?;
            }
            Ok(())
        }

        ResolvedType::Closure {
            param_tys,
            return_ty,
        } => {
            for (_, inner) in param_tys {
                check_type(inner, location)?;
            }
            check_type(return_ty, location)
        }

        ResolvedType::TypeParam(name) => Err(PreflightError::UnresolvedTypeParam {
            name: name.clone(),
            location: location.to_owned(),
        }),

        ResolvedType::Error => Err(PreflightError::ErrorTypePlaceholder {
            location: location.to_owned(),
        }),
    }
}

// ───────────────────────────────────────────────────────────────────
// Expression walker
// ───────────────────────────────────────────────────────────────────

#[expect(
    clippy::too_many_lines,
    reason = "exhaustive walk over every IrExpr variant; splitting hides the per-variant pre-flight contract"
)]
fn check_expr(expr: &IrExpr, location: &str) -> Result<(), PreflightError> {
    check_type(expr.ty(), location)?;

    match expr {
        IrExpr::Closure { .. } => Err(PreflightError::UnconvertedClosure {
            location: location.to_owned(),
        }),

        IrExpr::Literal { .. }
        | IrExpr::Reference { .. }
        | IrExpr::SelfFieldRef { .. }
        | IrExpr::LetRef { .. } => Ok(()),

        IrExpr::StructInst { fields, .. } | IrExpr::EnumInst { fields, .. } => {
            for (_, _, sub) in fields {
                check_expr(sub, location)?;
            }
            Ok(())
        }

        IrExpr::Tuple { fields, .. } => {
            for (_, sub) in fields {
                check_expr(sub, location)?;
            }
            Ok(())
        }

        IrExpr::Array { elements, .. } => {
            for e in elements {
                check_expr(e, location)?;
            }
            Ok(())
        }

        IrExpr::FieldAccess { object, .. } => check_expr(object, location),

        IrExpr::BinaryOp { left, right, .. } => {
            check_expr(left, location)?;
            check_expr(right, location)
        }

        IrExpr::UnaryOp { operand, .. } => check_expr(operand, location),

        IrExpr::If {
            condition,
            then_branch,
            else_branch,
            ..
        } => {
            check_expr(condition, location)?;
            check_expr(then_branch, location)?;
            if let Some(else_branch) = else_branch {
                check_expr(else_branch, location)?;
            }
            Ok(())
        }

        IrExpr::For {
            collection, body, ..
        } => {
            check_expr(collection, location)?;
            check_expr(body, location)
        }

        IrExpr::Match {
            scrutinee, arms, ..
        } => {
            check_expr(scrutinee, location)?;
            for arm in arms {
                check_match_arm(arm, location)?;
            }
            Ok(())
        }

        IrExpr::FunctionCall { args, .. } => {
            for (_, sub) in args {
                check_expr(sub, location)?;
            }
            Ok(())
        }

        IrExpr::CallClosure { closure, args, .. } => {
            check_expr(closure, location)?;
            for (_, sub) in args {
                check_expr(sub, location)?;
            }
            Ok(())
        }

        IrExpr::MethodCall { receiver, args, .. } => {
            check_expr(receiver, location)?;
            for (_, sub) in args {
                check_expr(sub, location)?;
            }
            Ok(())
        }

        IrExpr::ClosureRef { env_struct, .. } => check_expr(env_struct, location),

        IrExpr::DictLiteral { entries, .. } => {
            for (k, v) in entries {
                check_expr(k, location)?;
                check_expr(v, location)?;
            }
            Ok(())
        }

        IrExpr::DictAccess { dict, key, .. } => {
            check_expr(dict, location)?;
            check_expr(key, location)
        }

        IrExpr::Block {
            statements, result, ..
        } => {
            for stmt in statements {
                check_block_statement(stmt, location)?;
            }
            check_expr(result, location)
        }
    }
}

fn check_block_statement(stmt: &IrBlockStatement, location: &str) -> Result<(), PreflightError> {
    match stmt {
        IrBlockStatement::Let { ty, value, .. } => {
            if let Some(ty) = ty {
                check_type(ty, location)?;
            }
            check_expr(value, location)
        }
        IrBlockStatement::Assign { target, value, .. } => {
            check_expr(target, location)?;
            check_expr(value, location)
        }
        IrBlockStatement::Expr(e) => check_expr(e, location),
    }
}

fn check_match_arm(arm: &IrMatchArm, location: &str) -> Result<(), PreflightError> {
    for (_, _, ty) in &arm.bindings {
        check_type(ty, location)?;
    }
    check_expr(&arm.body, location)
}