formalang 0.0.3-beta

FormaLang compiler frontend: lexer, parser, semantic analyzer, and IR lowering.
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
//! Lowering for the bare-call form `Path(args)`: struct instantiation,
//! external-type instantiation, closure-binding calls and regular function
//! calls (with default-substitution + let-wrapper for forward references
//! to preceding non-defaulted params).

use crate::ast::Expr;
use crate::ir::lower::IrLowerer;
use crate::ir::{IrBlockStatement, IrExpr, IrFunctionParam, ResolvedType};
use std::collections::{HashMap, HashSet};

/// True if `expr` (or any sub-expression) is an `IrExpr::Reference`
/// with a single-segment path matching one of `names`. Used to
/// decide whether a substituted default needs the let-wrapper that
/// binds preceding non-defaulted params to the call-site values.
fn expr_references_any_name(expr: &IrExpr, names: &HashSet<String>) -> bool {
    match expr {
        IrExpr::Reference { path, .. } => {
            path.first().is_some_and(|seg| names.contains(seg.as_str()))
        }
        IrExpr::LetRef { name, .. } => names.contains(name.as_str()),
        IrExpr::BinaryOp { left, right, .. } => {
            expr_references_any_name(left, names) || expr_references_any_name(right, names)
        }
        IrExpr::UnaryOp { operand, .. } => expr_references_any_name(operand, names),
        IrExpr::FieldAccess { object, .. } => expr_references_any_name(object, names),
        IrExpr::FunctionCall { args, .. } | IrExpr::MethodCall { args, .. } => {
            args.iter().any(|(_, a)| expr_references_any_name(a, names))
        }
        IrExpr::CallClosure { closure, args, .. } => {
            expr_references_any_name(closure, names)
                || args.iter().any(|(_, a)| expr_references_any_name(a, names))
        }
        IrExpr::If {
            condition,
            then_branch,
            else_branch,
            ..
        } => {
            expr_references_any_name(condition, names)
                || expr_references_any_name(then_branch, names)
                || else_branch
                    .as_deref()
                    .is_some_and(|e| expr_references_any_name(e, names))
        }
        IrExpr::Match {
            scrutinee, arms, ..
        } => {
            expr_references_any_name(scrutinee, names)
                || arms
                    .iter()
                    .any(|arm| expr_references_any_name(&arm.body, names))
        }
        IrExpr::Block {
            statements, result, ..
        } => {
            statements.iter().any(|s| match s {
                IrBlockStatement::Let { value, .. } => expr_references_any_name(value, names),
                IrBlockStatement::Assign { target, value, .. } => {
                    expr_references_any_name(target, names)
                        || expr_references_any_name(value, names)
                }
                IrBlockStatement::Expr(e) => expr_references_any_name(e, names),
            }) || expr_references_any_name(result, names)
        }
        IrExpr::Array { elements, .. } => {
            elements.iter().any(|e| expr_references_any_name(e, names))
        }
        IrExpr::Tuple { fields, .. } => fields
            .iter()
            .any(|(_, e)| expr_references_any_name(e, names)),
        IrExpr::StructInst { fields, .. } | IrExpr::EnumInst { fields, .. } => fields
            .iter()
            .any(|(_, _, e)| expr_references_any_name(e, names)),
        IrExpr::DictLiteral { entries, .. } => entries
            .iter()
            .any(|(k, v)| expr_references_any_name(k, names) || expr_references_any_name(v, names)),
        IrExpr::DictAccess { dict, key, .. } => {
            expr_references_any_name(dict, names) || expr_references_any_name(key, names)
        }
        IrExpr::For {
            collection, body, ..
        } => expr_references_any_name(collection, names) || expr_references_any_name(body, names),
        IrExpr::Closure { body, .. } => expr_references_any_name(body, names),
        IrExpr::ClosureRef { env_struct, .. } => expr_references_any_name(env_struct, names),
        IrExpr::Literal { .. } | IrExpr::SelfFieldRef { .. } => false,
    }
}

impl IrLowerer<'_> {
    /// resolve a `ResolvedType` to its enum
    /// type-name (used as the inferred-enum target for a struct-arg
    /// expression). Returns the empty string for non-enum, non-optional-
    /// of-enum types, which the caller filters out.
    fn enum_name_of(module: &crate::ir::IrModule, ty: &ResolvedType) -> String {
        match ty {
            ResolvedType::Enum(eid) => module
                .get_enum(*eid)
                .map_or_else(String::new, |e| e.name.clone()),
            ResolvedType::Optional(inner) => Self::enum_name_of(module, inner),
            ResolvedType::Primitive(_)
            | ResolvedType::Struct(_)
            | ResolvedType::Trait(_)
            | ResolvedType::Array(_)
            | ResolvedType::Range(_)
            | ResolvedType::Tuple(_)
            | ResolvedType::Generic { .. }
            | ResolvedType::TypeParam(_)
            | ResolvedType::External { .. }
            | ResolvedType::Dictionary { .. }
            | ResolvedType::Closure { .. }
            | ResolvedType::Error => String::new(),
        }
    }

    #[expect(
        clippy::too_many_lines,
        reason = "three branches (struct / external / function) each with their own arg-lowering plumbing; splitting hides the contract"
    )]
    pub(in crate::ir::lower::expr) fn lower_invocation(
        &mut self,
        path: &[crate::ast::Ident],
        type_args: &[crate::ast::Type],
        args: &[(Option<crate::ast::Ident>, Expr)],
    ) -> IrExpr {
        let name = path
            .iter()
            .map(|id| id.name.as_str())
            .collect::<Vec<_>>()
            .join("::");
        let type_args_resolved: Vec<ResolvedType> =
            type_args.iter().map(|t| self.lower_type(t)).collect();

        if let Some(id) = self.module.struct_id(&name) {
            let ty = if type_args_resolved.is_empty() {
                ResolvedType::Struct(id)
            } else {
                ResolvedType::Generic {
                    base: crate::ir::GenericBase::Struct(id),
                    args: type_args_resolved.clone(),
                }
            };
            // build a name->type-name map of the
            // struct's fields so each named-arg lowers with the field's
            // declared type as the inferred-enum target. Without this,
            // `Size(width: .auto)` inherits whatever outer
            // `current_function_return_type` was set to and `.auto` can't
            // resolve.
            let field_target: HashMap<String, ResolvedType> = self
                .module
                .get_struct(id)
                .map(|s| {
                    s.fields
                        .iter()
                        .map(|f| (f.name.clone(), f.ty.clone()))
                        .collect()
                })
                .unwrap_or_default();
            let named_fields: Vec<(String, crate::ir::FieldIdx, IrExpr)> = args
                .iter()
                .filter_map(|(name_opt, expr)| {
                    name_opt.as_ref().map(|n| {
                        let saved = self.current_function_return_type.take();
                        let saved_closure = self.expected_closure_type.take();
                        self.current_function_return_type = field_target
                            .get(&n.name)
                            .map(|t| Self::enum_name_of(&self.module, t))
                            .filter(|s| !s.is_empty());
                        // thread closure-typed field annotations
                        // into the closure-literal lowering so untyped params
                        // pick up the field's expected param types.
                        if let Some(t) = field_target.get(&n.name) {
                            if matches!(t, ResolvedType::Closure { .. }) {
                                self.expected_closure_type = Some(t.clone());
                            }
                        }
                        let lowered = self.lower_expr(expr);
                        self.expected_closure_type = saved_closure;
                        self.current_function_return_type = saved;
                        (n.name.clone(), crate::ir::FieldIdx(0), lowered)
                    })
                })
                .collect();
            IrExpr::StructInst {
                struct_id: Some(id),
                type_args: type_args_resolved,
                fields: named_fields,
                ty,
                span: self.current_ir_span(),
            }
        } else if let Some(external_ty) = self.try_external_type(&name, type_args_resolved.clone())
        {
            let named_fields: Vec<(String, crate::ir::FieldIdx, IrExpr)> = args
                .iter()
                .filter_map(|(name_opt, expr)| {
                    name_opt.as_ref().map(|n| {
                        (
                            n.name.clone(),
                            crate::ir::FieldIdx(0),
                            self.lower_expr(expr),
                        )
                    })
                })
                .collect();
            IrExpr::StructInst {
                struct_id: None,
                type_args: type_args_resolved,
                fields: named_fields,
                ty: external_ty,
                span: self.current_ir_span(),
            }
        } else if let Some(call) = self.try_lower_closure_invocation(path, args) {
            call
        } else {
            let path_strs: Vec<String> = path.iter().map(|i| i.name.clone()).collect();
            let fn_name = path_strs.last().map_or("", std::string::String::as_str);
            // Resolve the call to a `FunctionId` first — module-aware
            // for single-segment calls (try the current `mod`'s
            // qualified form, fall back to bare); joined-name lookup
            // for multi-segment. Cross-module / forward-reference
            // cases stay `None` and `ResolveReferencesPass` finishes
            // the job.
            let function_id = if path_strs.len() == 1 {
                self.find_function_in_scope(fn_name)
            } else {
                self.module
                    .function_id(&path_strs.join("::"))
                    .or_else(|| self.find_function_in_scope(fn_name))
            };
            // Derive expected param types from the resolved id
            // (covers cross-module qualified calls correctly), or
            // fall back to scanning by bare name for forward
            // references.
            let expected_param_tys: Vec<(String, ResolvedType)> = function_id
                .and_then(|id| self.module.functions.get(id.0 as usize))
                .map_or_else(
                    || self.lookup_function_param_types(fn_name),
                    |f| {
                        f.params
                            .iter()
                            .filter_map(|p| p.ty.as_ref().map(|t| (p.name.clone(), t.clone())))
                            .collect()
                    },
                );
            let mut lowered_args: Vec<(Option<String>, IrExpr)> = args
                .iter()
                .enumerate()
                .map(|(i, (name_opt, expr))| {
                    let saved_closure = self.expected_closure_type.take();
                    self.expected_closure_type =
                        Self::expected_arg_closure_ty(&expected_param_tys, i, name_opt.as_ref());
                    let lowered = self.lower_expr(expr);
                    self.expected_closure_type = saved_closure;
                    (name_opt.as_ref().map(|n| n.name.clone()), lowered)
                })
                .collect();
            // DP-2 / DP-4 / DP-7: substitute defaults for missing args.
            // For all-positional calls, append trailing defaults. For
            // labeled calls (mode A), walk callee params in order and
            // fill any whose label is missing from the call. If any
            // substituted default references a preceding non-defaulted
            // param by name, wrap the entire FunctionCall in a Block
            // whose Let statements bind those param names to the
            // explicit args (so the default's Reference resolves via
            // path lookup to the new binding, not to the callee's
            // stale binding-id, and side-effects don't duplicate).
            let mut needs_let_wrapper = false;
            let mut wrapper_param_names: Vec<String> = Vec::new();
            let mut wrapper_param_types: Vec<Option<ResolvedType>> = Vec::new();
            if let Some(func_id) = function_id {
                if let Some(func) = self.module.functions.get(func_id.0 as usize) {
                    let non_self_params: Vec<IrFunctionParam> = func
                        .params
                        .iter()
                        .filter(|p| p.name != "self")
                        .cloned()
                        .collect();
                    let want = non_self_params.len();
                    if lowered_args.len() < want {
                        let any_labeled = lowered_args.iter().any(|(l, _)| l.is_some());
                        // Names of params that already have a value in
                        // the call (used to detect earlier-param refs
                        // that need the let-wrapper).
                        let already_provided_names: HashSet<String> = if any_labeled {
                            lowered_args.iter().filter_map(|(l, _)| l.clone()).collect()
                        } else {
                            non_self_params
                                .iter()
                                .take(lowered_args.len())
                                .map(|p| p.name.clone())
                                .collect()
                        };
                        if any_labeled {
                            // Mode A — labeled call. Build a new
                            // ordered args list that walks callee
                            // params in order, picking up the
                            // explicit-call value when its label is
                            // present and substituting the default
                            // otherwise. Mid-list omissions get
                            // filled at the right position.
                            let mut new_args: Vec<(Option<String>, IrExpr)> =
                                Vec::with_capacity(want);
                            for param in &non_self_params {
                                if let Some(pos) = lowered_args.iter().position(|(l, _)| {
                                    l.as_ref().is_some_and(|name| name == &param.name)
                                }) {
                                    let (label, value) = lowered_args.remove(pos);
                                    new_args.push((label, value));
                                } else if let Some(default) = &param.default {
                                    if expr_references_any_name(default, &already_provided_names) {
                                        needs_let_wrapper = true;
                                    }
                                    new_args.push((Some(param.name.clone()), default.clone()));
                                } else {
                                    // Required label missing: validator
                                    // should have rejected. Stop on the
                                    // first gap to preserve some signal.
                                    break;
                                }
                            }
                            lowered_args = new_args;
                        } else {
                            // Positional — append trailing defaults.
                            for param in non_self_params.iter().skip(lowered_args.len()) {
                                if let Some(default) = &param.default {
                                    if expr_references_any_name(default, &already_provided_names) {
                                        needs_let_wrapper = true;
                                    }
                                    lowered_args.push((None, default.clone()));
                                } else {
                                    break;
                                }
                            }
                        }
                        if needs_let_wrapper {
                            for param in non_self_params
                                .iter()
                                .filter(|p| already_provided_names.contains(&p.name))
                            {
                                wrapper_param_names.push(param.name.clone());
                                wrapper_param_types.push(param.ty.clone());
                            }
                        }
                    }
                }
            }
            // Return type lookup uses the same id when available; the
            // legacy bare-name lookup is the fallback for forward
            // refs.
            let ty = function_id
                .and_then(|id| self.module.functions.get(id.0 as usize))
                .and_then(|f| f.return_type.clone())
                .unwrap_or_else(|| self.resolve_function_return_type(fn_name, &lowered_args));

            if needs_let_wrapper {
                // Build let bindings for each preceding non-defaulted
                // param. Move the explicit lowered_args[i] into the
                // let value; replace the call-site arg with a
                // Reference to the binding name. The default's
                // Reference{path:[name]} resolves to the let-binding
                // post-ResolveReferencesPass.
                let mut statements = Vec::with_capacity(wrapper_param_names.len());
                for ((name, ty), arg) in wrapper_param_names
                    .iter()
                    .zip(wrapper_param_types.iter())
                    .zip(lowered_args.iter_mut())
                {
                    let value = std::mem::replace(
                        &mut arg.1,
                        IrExpr::Reference {
                            path: vec![name.clone()],
                            target: crate::ir::ReferenceTarget::Unresolved,
                            ty: ty.clone().unwrap_or(ResolvedType::Error),
                            span: self.current_ir_span(),
                        },
                    );
                    statements.push(IrBlockStatement::Let {
                        binding_id: crate::ir::BindingId(0),
                        name: name.clone(),
                        mutable: false,
                        ty: ty.clone(),
                        value,
                        span: self.current_ir_span(),
                    });
                }
                let call = IrExpr::FunctionCall {
                    path: path_strs,
                    function_id,
                    args: lowered_args,
                    ty: ty.clone(),
                    span: self.current_ir_span(),
                };
                IrExpr::Block {
                    statements,
                    result: Box::new(call),
                    ty,
                    span: self.current_ir_span(),
                }
            } else {
                IrExpr::FunctionCall {
                    path: path_strs,
                    function_id,
                    args: lowered_args,
                    ty,
                    span: self.current_ir_span(),
                }
            }
        }
    }

    /// Detect when an `Invocation` whose path is a single segment
    /// resolves to a closure-typed local binding rather than a top-
    /// level function, and lower it as [`IrExpr::CallClosure`]
    /// targeting that binding.
    ///
    /// Returns `None` when the path doesn't refer to a closure-typed
    /// local — the caller falls through to the regular
    /// [`IrExpr::FunctionCall`] path.
    fn try_lower_closure_invocation(
        &mut self,
        path: &[crate::ast::Ident],
        args: &[(Option<crate::ast::Ident>, Expr)],
    ) -> Option<IrExpr> {
        let [ident] = path else {
            return None;
        };
        let name = &ident.name;
        let local_ty = self.lookup_local_binding(name)?.clone();
        let ResolvedType::Closure {
            param_tys,
            return_ty,
        } = &local_ty
        else {
            return None;
        };
        let return_ty = (**return_ty).clone();
        let expected_param_tys: Vec<(String, ResolvedType)> = param_tys
            .iter()
            .enumerate()
            .map(|(i, (_, ty))| (format!("__closure_arg_{i}"), ty.clone()))
            .collect();
        let lowered_args: Vec<(Option<String>, IrExpr)> = args
            .iter()
            .enumerate()
            .map(|(i, (arg_name, expr))| {
                let saved_closure = self.expected_closure_type.take();
                self.expected_closure_type =
                    Self::expected_arg_closure_ty(&expected_param_tys, i, arg_name.as_ref());
                let lowered = self.lower_expr(expr);
                self.expected_closure_type = saved_closure;
                (arg_name.as_ref().map(|n| n.name.clone()), lowered)
            })
            .collect();
        Some(IrExpr::CallClosure {
            closure: Box::new(IrExpr::LetRef {
                name: name.clone(),
                binding_id: crate::ir::BindingId(0),
                ty: local_ty,
                span: self.current_ir_span(),
            }),
            args: lowered_args,
            ty: return_ty,
            span: self.current_ir_span(),
        })
    }
}