lisette-emit 0.2.15

Little language inspired by Rust that compiles to Go
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
use syntax::ast::MatchArm;

use crate::EmitEffects;
use crate::control_flow::branching::wrap_if_struct_literal;
use crate::patterns::binding_decls::{is_catchall_pattern, is_unconditional_catchall};
use crate::patterns::decision_tree::{
    AccessPath, ChainTest, Decision, PatternBinding, SwitchBranch, SwitchKind, SwitchShape,
    decision_is_exhaustive, render_condition, tree_has_unguarded_terminal,
};

#[derive(Debug, Clone)]
pub(crate) struct EmitBinding {
    pub lisette_name: String,
    pub go_name: Option<String>,
    pub rendered_access: String,
    pub composable_access: String,
}

#[derive(Debug)]
pub(crate) enum MatchEmitPlan {
    Switch { tree: EmitDecision },
    SingleCatchall(SingleCatchallPlan),
    Chain(ChainPlan),
    RetryLoop(RetryLoopPlan),
}

#[derive(Debug)]
pub(crate) struct SingleCatchallPlan {
    pub arm_index: usize,
    pub bindings: Vec<EmitBinding>,
    pub pattern_has_collisions: bool,
}

#[derive(Debug)]
pub(crate) struct ChainPlan {
    pub tree: EmitDecision,
    /// Planner emits trailing `panic("unreachable")` iff
    /// `destination.is_tail() && !chain_tail_is_exhaustive`.
    pub chain_tail_is_exhaustive: bool,
}

#[derive(Debug)]
pub(crate) struct RetryLoopPlan {
    pub tree: EmitDecision,
    pub all_arms_diverge: bool,
    pub root_has_unguarded_terminal: bool,
    pub last_arm_is_any_catchall: bool,
}

#[derive(Debug)]
pub(crate) enum EmitDecision {
    Success {
        arm_index: usize,
        bindings: Vec<EmitBinding>,
        leaf_emits_no_output: bool,
    },
    Guard {
        arm_index: usize,
        bindings: Vec<EmitBinding>,
        success: Box<EmitDecision>,
        failure: Box<EmitDecision>,
    },
    IfElse {
        condition: String,
        then_branch: Box<EmitDecision>,
        else_branch: Option<Box<EmitDecision>>,
    },
    /// Exhaustive single-variant enum: no condition wrapper.
    InlineBranch {
        branch: Box<EmitDecision>,
    },
    Switch {
        expr: String,
        cases: Vec<EmitCase>,
        default: Option<Box<EmitDecision>>,
    },
    TypeSwitch {
        base: String,
        cases: Vec<EmitCase>,
        default: Option<Box<EmitDecision>>,
    },
    Chain {
        tests: Vec<EmitChainTest>,
        fallback: Box<EmitDecision>,
        last_is_catchall: bool,
    },
    Unreachable,
}

#[derive(Debug)]
pub(crate) struct EmitChainTest {
    /// `None` marks a catchall test (empty `checks` in the source).
    pub condition: Option<String>,
    pub decision: Box<EmitDecision>,
}

#[derive(Debug)]
pub(crate) struct EmitCase {
    pub case_label: String,
    pub decision: Box<EmitDecision>,
}

pub(crate) type MatchPlanEffects = EmitEffects;

#[derive(Debug)]
pub(crate) struct LoweredMatch {
    pub plan: MatchEmitPlan,
    pub effects: MatchPlanEffects,
}

pub(crate) struct LoweringCtx<'a> {
    arms: &'a [MatchArm],
    current_subject: String,
    effects: MatchPlanEffects,
}

impl<'a> LoweringCtx<'a> {
    fn new(arms: &'a [MatchArm], subject_var: String) -> Self {
        Self {
            arms,
            current_subject: subject_var,
            effects: MatchPlanEffects::default(),
        }
    }

    /// Scope a subject swap to the closure so a nested type switch's
    /// `base` cannot leak into a later outer branch.
    fn with_subject<R>(&mut self, new_subject: String, f: impl FnOnce(&mut Self) -> R) -> R {
        let prev = std::mem::replace(&mut self.current_subject, new_subject);
        let result = f(self);
        self.current_subject = prev;
        result
    }
}

/// Precedence: Switch, SingleCatchall, RetryLoop (if any guard), else Chain.
///
/// `single_catchall_has_collisions` is precomputed at the call site (it
/// needs emitter scope state). Only read on the SingleCatchall path.
pub(crate) fn lower_match(
    arms: &[MatchArm],
    subject_var: String,
    decision: &Decision,
    single_catchall_has_collisions: bool,
) -> LoweredMatch {
    let mut ctx = LoweringCtx::new(arms, subject_var);
    let plan = lower_match_inner(&mut ctx, decision, single_catchall_has_collisions);
    LoweredMatch {
        plan,
        effects: ctx.effects,
    }
}

fn lower_match_inner(
    ctx: &mut LoweringCtx,
    decision: &Decision,
    single_catchall_has_collisions: bool,
) -> MatchEmitPlan {
    if matches!(decision, Decision::Switch { .. }) {
        return MatchEmitPlan::Switch {
            tree: lower_decision(ctx, decision),
        };
    }

    if let Decision::Success {
        arm_index,
        bindings,
    } = decision
    {
        let bindings = lower_bindings(ctx, bindings);
        return MatchEmitPlan::SingleCatchall(SingleCatchallPlan {
            arm_index: *arm_index,
            bindings,
            pattern_has_collisions: single_catchall_has_collisions,
        });
    }

    let has_guards = ctx.arms.iter().any(|arm| arm.has_guard());
    if has_guards {
        let all_arms_diverge = ctx
            .arms
            .iter()
            .all(|arm| arm.expression.diverges().is_some());
        let root_has_unguarded_terminal = tree_has_unguarded_terminal(decision);
        let last_arm_is_any_catchall = ctx
            .arms
            .last()
            .is_some_and(|arm| !arm.has_guard() && is_catchall_pattern(&arm.pattern));
        let tree = lower_decision(ctx, decision);
        return MatchEmitPlan::RetryLoop(RetryLoopPlan {
            tree,
            all_arms_diverge,
            root_has_unguarded_terminal,
            last_arm_is_any_catchall,
        });
    }

    let chain_tail_is_exhaustive = decision_is_exhaustive(decision)
        || ctx
            .arms
            .last()
            .is_some_and(|arm| !arm.has_guard() && is_unconditional_catchall(&arm.pattern));
    let tree = lower_decision(ctx, decision);
    MatchEmitPlan::Chain(ChainPlan {
        tree,
        chain_tail_is_exhaustive,
    })
}

pub(crate) fn lower_decision(ctx: &mut LoweringCtx, decision: &Decision) -> EmitDecision {
    match decision {
        Decision::Unreachable => EmitDecision::Unreachable,

        Decision::Success {
            arm_index,
            bindings,
        } => {
            let bindings = lower_bindings(ctx, bindings);
            let arm = &ctx.arms[*arm_index];
            let leaf_emits_no_output =
                bindings.is_empty() && body_is_unit_or_empty(&arm.expression);
            EmitDecision::Success {
                arm_index: *arm_index,
                bindings,
                leaf_emits_no_output,
            }
        }

        Decision::Guard {
            arm_index,
            bindings,
            success,
            failure,
        } => {
            let bindings = lower_bindings(ctx, bindings);
            let success = Box::new(lower_decision(ctx, success));
            let failure = Box::new(lower_decision(ctx, failure));
            EmitDecision::Guard {
                arm_index: *arm_index,
                bindings,
                success,
                failure,
            }
        }

        Decision::Chain { tests, fallback } => {
            let lowered_tests = tests
                .iter()
                .map(|test| lower_chain_test(ctx, test))
                .collect::<Vec<_>>();
            let fallback = Box::new(lower_decision(ctx, fallback));
            let last_is_catchall =
                matches!(fallback.as_ref(), EmitDecision::Unreachable) && tests.len() > 1;
            EmitDecision::Chain {
                tests: lowered_tests,
                fallback,
                last_is_catchall,
            }
        }

        Decision::Switch {
            path,
            kind,
            shape,
            branches,
            fallback,
        } => lower_switch(ctx, path, kind, shape, branches, fallback),
    }
}

fn lower_chain_test(ctx: &mut LoweringCtx, test: &ChainTest) -> EmitChainTest {
    let condition = if test.checks.is_empty() {
        None
    } else {
        Some(render_condition(&test.checks, &ctx.current_subject))
    };
    let decision = Box::new(lower_decision(ctx, &test.decision));
    EmitChainTest {
        condition,
        decision,
    }
}

fn lower_bindings(ctx: &mut LoweringCtx, bindings: &[PatternBinding]) -> Vec<EmitBinding> {
    bindings
        .iter()
        .map(|b| EmitBinding {
            lisette_name: b.lisette_name.clone(),
            go_name: b.go_name.clone(),
            rendered_access: b.path.render(&ctx.current_subject),
            composable_access: b.path.render_composable(&ctx.current_subject),
        })
        .collect()
}

fn lower_switch(
    ctx: &mut LoweringCtx,
    path: &AccessPath,
    kind: &SwitchKind,
    shape: &SwitchShape,
    branches: &[SwitchBranch],
    fallback: &Option<Box<Decision>>,
) -> EmitDecision {
    propagate_stdlib(ctx, branches);
    let rendered_path = path.render(&ctx.current_subject);

    match shape {
        SwitchShape::TypeSwitch => lower_type_switch(ctx, rendered_path, branches, fallback),
        SwitchShape::Bool => lower_bool_switch(ctx, rendered_path, branches),
        SwitchShape::Binary => lower_binary_switch(ctx, &rendered_path, kind, branches),
        SwitchShape::SingleArm => {
            lower_single_arm_switch(ctx, &rendered_path, kind, branches, fallback)
        }
        SwitchShape::Multi => lower_multi_switch(ctx, &rendered_path, kind, branches, fallback),
    }
}

fn lower_type_switch(
    ctx: &mut LoweringCtx,
    base: String,
    branches: &[SwitchBranch],
    fallback: &Option<Box<Decision>>,
) -> EmitDecision {
    ctx.with_subject(base.clone(), |ctx| {
        let (cases, default) =
            lower_cases_with_default_lift(ctx, branches, fallback, /*lift=*/ true);
        EmitDecision::TypeSwitch {
            base,
            cases,
            default,
        }
    })
}

fn lower_bool_switch(
    ctx: &mut LoweringCtx,
    rendered_path: String,
    branches: &[SwitchBranch],
) -> EmitDecision {
    // Select branches by label so `then_branch` is always the semantic-true
    // subtree regardless of source order.
    let true_branch = branches
        .iter()
        .find(|b| b.case_label == "true")
        .expect("Bool shape requires a true-labeled branch");
    let false_branch = branches
        .iter()
        .find(|b| b.case_label == "false")
        .expect("Bool shape requires a false-labeled branch");
    EmitDecision::IfElse {
        condition: wrap_if_struct_literal(rendered_path),
        then_branch: Box::new(lower_decision(ctx, &true_branch.decision)),
        else_branch: Some(Box::new(lower_decision(ctx, &false_branch.decision))),
    }
}

fn lower_binary_switch(
    ctx: &mut LoweringCtx,
    rendered_path: &str,
    kind: &SwitchKind,
    branches: &[SwitchBranch],
) -> EmitDecision {
    let first = &branches[0];
    let second = &branches[1];
    let expr = render_switch_expression(rendered_path, kind);
    EmitDecision::IfElse {
        condition: format!("{} == {}", expr, first.case_label),
        then_branch: Box::new(lower_decision(ctx, &first.decision)),
        else_branch: Some(Box::new(lower_decision(ctx, &second.decision))),
    }
}

fn lower_single_arm_switch(
    ctx: &mut LoweringCtx,
    rendered_path: &str,
    kind: &SwitchKind,
    branches: &[SwitchBranch],
    fallback: &Option<Box<Decision>>,
) -> EmitDecision {
    let branch = &branches[0];
    let Some(fb) = fallback else {
        return EmitDecision::InlineBranch {
            branch: Box::new(lower_decision(ctx, &branch.decision)),
        };
    };
    let expr = render_switch_expression(rendered_path, kind);
    let lowered_fallback = lower_decision(ctx, fb);
    let else_branch = if is_empty_emit_decision(&lowered_fallback) {
        None
    } else {
        Some(Box::new(lowered_fallback))
    };
    EmitDecision::IfElse {
        condition: format!("{} == {}", expr, branch.case_label),
        then_branch: Box::new(lower_decision(ctx, &branch.decision)),
        else_branch,
    }
}

fn lower_multi_switch(
    ctx: &mut LoweringCtx,
    rendered_path: &str,
    kind: &SwitchKind,
    branches: &[SwitchBranch],
    fallback: &Option<Box<Decision>>,
) -> EmitDecision {
    let expr = render_switch_expression(rendered_path, kind);
    let (cases, default) =
        lower_cases_with_default_lift(ctx, branches, fallback, /*lift=*/ true);
    EmitDecision::Switch {
        expr,
        cases,
        default,
    }
}

fn render_switch_expression(rendered_path: &str, kind: &SwitchKind) -> String {
    match kind {
        SwitchKind::EnumTag => wrap_if_struct_literal(format!("{}.Tag", rendered_path)),
        SwitchKind::Value => wrap_if_struct_literal(rendered_path.to_string()),
        SwitchKind::TypeSwitch => unreachable!("TypeSwitch handled separately"),
    }
}

fn propagate_stdlib(ctx: &mut LoweringCtx, branches: &[SwitchBranch]) {
    if branches.iter().any(|b| b.needs_stdlib) {
        ctx.effects.needs_stdlib = true;
    }
}

fn lower_cases_with_default_lift(
    ctx: &mut LoweringCtx,
    branches: &[SwitchBranch],
    fallback: &Option<Box<Decision>>,
    lift: bool,
) -> (Vec<EmitCase>, Option<Box<EmitDecision>>) {
    let use_last_as_default = lift && fallback.is_none() && !branches.is_empty();
    let (regular, default_branch) = if use_last_as_default {
        let (last, rest) = branches.split_last().expect("non-empty");
        (rest, Some(last))
    } else {
        (branches, None)
    };

    let cases = regular
        .iter()
        .map(|b| EmitCase {
            case_label: b.case_label.clone(),
            decision: Box::new(lower_decision(ctx, &b.decision)),
        })
        .collect();

    let default = match (default_branch, fallback) {
        (Some(last), _) => Some(Box::new(lower_decision(ctx, &last.decision))),
        (None, Some(fb)) => Some(Box::new(lower_decision(ctx, fb))),
        (None, None) => None,
    };

    (cases, default)
}

pub(crate) fn is_empty_emit_decision(d: &EmitDecision) -> bool {
    matches!(
        d,
        EmitDecision::Success {
            leaf_emits_no_output: true,
            ..
        }
    )
}

fn body_is_unit_or_empty(expression: &syntax::ast::Expression) -> bool {
    use syntax::ast::Expression;
    matches!(expression, Expression::Unit { .. })
        || matches!(expression, Expression::Block { items, .. } if items.is_empty())
}