lisette-emit 0.1.24

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
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
use crate::Emitter;
use crate::names::go_name;
use crate::patterns::decision_tree;
use crate::statements::assignments::is_lvalue_chain;
use crate::types::emitter::Position;
use crate::utils::{Staged, output_ends_with_diverge};
use crate::write_line;
use syntax::ast::{Expression, Pattern, TypedPattern};

impl Emitter<'_> {
    pub(crate) fn emit_if(
        &mut self,
        output: &mut String,
        condition: &Expression,
        consequence: &Expression,
        alternative: &Expression,
    ) {
        let condition_string = self.emit_condition_operand(output, condition);
        let condition_string = wrap_if_struct_literal(condition_string);
        write_line!(output, "if {} {{", condition_string);
        self.enter_scope();
        self.emit_in_position(output, consequence);
        self.exit_scope();
        self.emit_else_chain(output, alternative);
    }

    fn emit_else_chain(&mut self, output: &mut String, alternative: &Expression) {
        let is_empty_alternative = match alternative {
            Expression::Unit { .. } => true,
            Expression::Block { items, .. } => items.is_empty(),
            _ => false,
        };
        if is_empty_alternative {
            output.push_str("}\n");
            return;
        }

        if let Expression::If {
            condition,
            consequence,
            alternative: next_alternative,
            ..
        } = alternative
        {
            let condition_string = self.emit_condition_operand(output, condition);
            let condition_string = wrap_if_struct_literal(condition_string);
            write_line!(output, "}} else if {} {{", condition_string);
            self.enter_scope();
            self.emit_in_position(output, consequence);
            self.exit_scope();
            self.emit_else_chain(output, next_alternative);
        } else if output_ends_with_diverge(output) {
            output.push_str("}\n");
            self.emit_in_position(output, alternative);
        } else {
            output.push_str("} else {\n");
            self.enter_scope();
            self.emit_in_position(output, alternative);
            self.exit_scope();
            output.push_str("}\n");
        }
    }

    /// Emit an if/else-if branch header for pattern matching chains.
    ///
    /// When `is_first` is true, emits `if <condition> {`. Otherwise, exits the
    /// previous scope and emits `} else if <condition> {` (or `} else {` for catchalls).
    /// Always enters a new scope after the header.
    pub(crate) fn emit_branch_header(
        &mut self,
        output: &mut String,
        condition: &str,
        is_catchall: bool,
        is_first: bool,
    ) {
        if is_first {
            if is_catchall {
                output.push_str("if true {\n");
            } else {
                write_line!(output, "if {} {{", condition);
            }
        } else {
            self.exit_scope();
            if is_catchall {
                output.push_str("} else {\n");
            } else {
                write_line!(output, "}} else if {} {{", condition);
            }
        }
        self.enter_scope();
    }

    pub(crate) fn emit_while_let(
        &mut self,
        output: &mut String,
        pattern: &Pattern,
        typed_pattern: Option<&TypedPattern>,
        scrutinee: &Expression,
        body: &Expression,
        needs_label: bool,
    ) {
        self.maybe_set_loop_label(needs_label);
        if let Some(label) = self.current_loop_label() {
            write_line!(output, "{}:", label);
        }
        output.push_str("for {\n");

        let inlined = if let Expression::Identifier { value, .. } = scrutinee {
            let name = value.to_string();
            let has_collision = Self::pattern_binds_name(pattern, &name);
            if !has_collision && !name.contains('.') {
                Some(
                    self.scope
                        .bindings
                        .get(&name)
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| go_name::escape_reserved(&name).into_owned()),
                )
            } else {
                None
            }
        } else {
            None
        };
        let subject_var = inlined.unwrap_or_else(|| {
            let var = self.fresh_var(Some("subject"));
            let expression = self.emit_operand(output, scrutinee);
            write_line!(output, "{} := {}", var, expression);
            var
        });

        if let Pattern::Or { patterns, .. } = pattern
            && Self::pattern_has_bindings(pattern)
        {
            let mut alternatives: Vec<_> = patterns
                .iter()
                .map(|alt| decision_tree::collect_pattern_info(self, alt, None))
                .collect();

            let unused_names: rustc_hash::FxHashSet<String> = alternatives
                .iter()
                .flat_map(|(_, bindings)| bindings.iter())
                .filter(|b| b.go_name.is_none())
                .map(|b| b.lisette_name.clone())
                .collect();
            for (_, bindings) in alternatives.iter_mut() {
                for binding in bindings.iter_mut() {
                    if unused_names.contains(&binding.lisette_name) {
                        binding.go_name = None;
                    }
                }
            }

            for (i, (checks, bindings)) in alternatives.iter().enumerate() {
                let condition = decision_tree::render_condition(checks, &subject_var);

                self.emit_branch_header(output, &condition, false, i == 0);

                decision_tree::emit_tree_bindings(self, output, bindings, &subject_var);
                self.emit_block(output, body);
            }

            self.emit_while_let_break_else(output);
            return;
        }

        let (checks, bindings) = decision_tree::collect_pattern_info(self, pattern, typed_pattern);
        let condition = decision_tree::render_condition(&checks, &subject_var);
        write_line!(output, "if {} {{", condition);
        self.enter_scope();

        if !matches!(pattern, Pattern::Or { .. }) {
            decision_tree::emit_tree_bindings(self, output, &bindings, &subject_var);
        }

        self.emit_block(output, body);

        self.emit_while_let_break_else(output);
    }

    fn emit_while_let_break_else(&mut self, output: &mut String) {
        self.exit_scope();
        output.push_str("} else {\n");
        self.enter_scope();
        if let Some(label) = self.current_loop_label() {
            write_line!(output, "break {}", label);
        } else {
            output.push_str("break\n");
        }
        self.exit_scope();
        output.push_str("}\n");
        output.push_str("}\n");
    }

    pub(crate) fn emit_branching_directly(&mut self, output: &mut String, expression: &Expression) {
        match expression {
            Expression::If {
                condition,
                consequence,
                alternative,
                ..
            } => {
                self.emit_if(output, condition, consequence, alternative);
            }
            Expression::Match {
                subject, arms, ty, ..
            } => {
                self.emit_match(output, subject, arms, ty);
            }
            Expression::Select { arms, .. } => {
                self.emit_select(output, arms);
            }
            _ => unreachable!("expected if/match/select"),
        }
    }

    pub(crate) fn emit_block(&mut self, output: &mut String, expression: &Expression) {
        let Expression::Block { items, .. } = expression else {
            self.emit_statement(output, expression);
            return;
        };

        for item in items {
            self.emit_statement(output, item);
        }
    }

    pub(crate) fn emit_block_to_var_with_braces(
        &mut self,
        output: &mut String,
        expression: &Expression,
        var: &str,
        has_go_braces: bool,
    ) {
        let is_block = matches!(expression, Expression::Block { .. });
        let items: &[Expression] = if let Expression::Block { items, .. } = expression {
            items
        } else {
            std::slice::from_ref(expression)
        };

        self.enter_block_scope(is_block, has_go_braces);

        if let Some((last, rest)) = items.split_last() {
            let is_new_target = self.scope.assign_targets.insert(var.to_string());
            for item in rest {
                self.emit_statement(output, item);
            }
            self.emit_tail_to_var(output, last, var);
            if is_new_target {
                self.scope.assign_targets.remove(var);
            }
        }

        self.exit_block_scope(is_block, has_go_braces);
    }

    /// Enter the scope appropriate for a block-to-var assignment.
    /// Go-brace blocks get a full Go scope; brace-less blocks save bindings only
    /// (variables need to remain visible after the block).
    fn enter_block_scope(&mut self, is_block: bool, has_go_braces: bool) {
        if !is_block {
            return;
        }
        if has_go_braces {
            self.enter_scope();
        } else {
            self.scope.bindings.save();
        }
    }

    fn exit_block_scope(&mut self, is_block: bool, has_go_braces: bool) {
        if !is_block {
            return;
        }
        if has_go_braces {
            self.exit_scope();
        } else {
            self.scope.bindings.restore();
        }
    }

    /// Emit the tail expression of a block-to-var assignment, handling
    /// statement-only forms, divergent expressions, unit calls, and append
    /// optimizations before falling through to general branching or value
    /// emission.
    fn emit_tail_to_var(&mut self, output: &mut String, last: &Expression, var: &str) {
        if matches!(
            last,
            Expression::Return { .. }
                | Expression::Break { .. }
                | Expression::Continue { .. }
                | Expression::Let { .. }
                | Expression::While { .. }
                | Expression::WhileLet { .. }
                | Expression::For { .. }
                | Expression::Const { .. }
        ) {
            self.emit_statement(output, last);
            return;
        }
        if last.get_type().is_never() {
            // Never-typed expressions (panic(), blocks ending in break/continue/return)
            // don't produce a value. Emit as a statement to avoid unused temp vars.
            self.emit_statement(output, last);
            if !Self::is_go_never(last) {
                output.push_str("panic(\"unreachable\")\n");
            }
            return;
        }
        if last.get_type().is_unit() && matches!(last.unwrap_parens(), Expression::Call { .. }) {
            // Emit as statement and assign struct{}{} to the block result var.
            let call_str = self.emit_value(output, last);
            if !call_str.is_empty() {
                write_line!(output, "{call_str}");
            }
            write_line!(output, "{var} = struct{{}}{{}}");
            return;
        }
        if self.emit_append_to_var(output, var, last) {
            return;
        }
        if matches!(
            last,
            Expression::If { .. } | Expression::Match { .. } | Expression::Select { .. }
        ) {
            self.with_position(Position::Assign(var.to_string()), |this| {
                this.emit_branching_directly(output, last);
            });
            return;
        }
        let expression_string = self.emit_value(output, last);
        let target_ty = self.assign_target_ty.clone();
        let expression_string =
            self.apply_type_coercion(output, target_ty.as_ref(), last, expression_string);
        write_line!(output, "{} = {}", var, expression_string);
    }

    fn emit_append_to_var(&mut self, output: &mut String, var: &str, last: &Expression) -> bool {
        let Expression::Call {
            expression: func,
            args,
            spread,
            ..
        } = last
        else {
            return false;
        };
        if !self.is_slice_append_or_extend(func) {
            return false;
        }

        let Expression::DotAccess {
            expression: receiver,
            member,
            ..
        } = func.as_ref()
        else {
            return true;
        };

        let is_extend = member == "extend";
        let unwrapped = receiver.unwrap_parens();
        let receiver_is_lvalue =
            is_lvalue_chain(unwrapped) && !self.contains_newtype_access(unwrapped);

        if receiver_is_lvalue {
            // false: append args never produce RHS temp statements (if/match/block).
            let receiver_lv = self.emit_left_value_capturing(output, unwrapped, false);
            let args_str = self.emit_append_args(output, args, (**spread).as_ref(), is_extend);
            write_line!(output, "{} = append({}, {})", var, receiver_lv, args_str);
        } else {
            let value_str = self.emit_value(output, last);
            write_line!(output, "{} = {}", var, value_str);
        }

        true
    }

    pub(crate) fn emit_block_to_tail(&mut self, output: &mut String, expression: &Expression) {
        let items: &[Expression] = if let Expression::Block { items, .. } = expression {
            items
        } else {
            std::slice::from_ref(expression)
        };

        let Some((last, rest)) = items.split_last() else {
            return;
        };

        for item in rest {
            self.emit_statement(output, item);
        }

        let return_span = last.get_span();

        let last = if let Expression::Return { expression, .. } = last {
            expression.as_ref()
        } else {
            last
        };

        if last.get_type().is_unit() {
            if !matches!(last, Expression::Unit { .. }) {
                self.emit_statement(output, last);
            }
            return;
        }

        if last.get_type().is_never() {
            let directive = self.maybe_line_directive(&return_span);
            output.push_str(&directive);
            self.emit_statement(output, last);
            if !Self::is_go_never(last) {
                output.push_str("panic(\"unreachable\")\n");
            }
            return;
        }

        let directive = self.maybe_line_directive(&return_span);
        match last {
            Expression::If { .. } | Expression::Match { .. } | Expression::Select { .. } => {
                output.push_str(&directive);
                self.emit_branching_directly(output, last);
            }
            _ => {
                output.push_str(&directive);
                if self.emit_wrapped_return(output, last) {
                    return;
                }
                let expression_string = self.emit_value(output, last);
                let return_ty = self
                    .current_return_context
                    .as_ref()
                    .map(|ctx| ctx.ty.clone());
                let expression_string =
                    self.apply_type_coercion(output, return_ty.as_ref(), last, expression_string);
                write_line!(output, "return {}", expression_string);
            }
        }
    }

    pub(crate) fn emit_in_position(&mut self, output: &mut String, expression: &Expression) {
        match &self.position {
            Position::Statement | Position::Expression => {
                self.emit_block(output, expression);
            }
            Position::Assign(var) => {
                let var = var.clone();
                if expression.get_type().is_result() || expression.get_type().is_option() {
                    let target_ty = self.assign_target_ty.clone();
                    self.emit_option_result_assignment(
                        output,
                        &var,
                        target_ty.as_ref(),
                        expression,
                    );
                } else {
                    self.emit_block_to_var_with_braces(output, expression, &var, false);
                }
            }
            Position::Tail => self.emit_block_to_tail(output, expression),
        }
    }
}

impl Emitter<'_> {
    pub(crate) fn maybe_set_loop_label(&mut self, needs_label: bool) {
        if needs_label {
            let label = self.fresh_var(Some("loop"));
            if let Some(ctx) = self.scope.loop_stack.last_mut() {
                ctx.label = Some(label);
            }
        }
    }

    pub(crate) fn emit_labeled_loop(
        &mut self,
        output: &mut String,
        header: &str,
        body: &Expression,
        needs_label: bool,
    ) {
        self.maybe_set_loop_label(needs_label);
        if let Some(label) = self.current_loop_label() {
            write_line!(output, "{}:", label);
        }
        output.push_str(header);
        self.enter_scope();
        self.emit_block(output, body);
        self.exit_scope();
        output.push_str("}\n");
    }

    fn is_slice_append_or_extend(&self, func: &Expression) -> bool {
        if let Expression::DotAccess {
            expression, member, ..
        } = func
            && (member == "append" || member == "extend")
        {
            return expression.get_type().has_name("Slice");
        }
        false
    }

    fn emit_append_args(
        &mut self,
        output: &mut String,
        args: &[Expression],
        spread: Option<&Expression>,
        is_extend: bool,
    ) -> String {
        let stages: Vec<Staged> = args.iter().map(|a| self.stage_composite(a)).collect();
        let emitted_args = self.sequence_with_spread(output, stages, spread, false, "_arg");
        let args_str = emitted_args.join(", ");
        let suffix = if is_extend { "..." } else { "" };
        format!("{}{}", args_str, suffix)
    }
}

pub(crate) fn wrap_if_struct_literal(condition: String) -> String {
    if condition.contains('{') {
        format!("({})", condition)
    } else {
        condition
    }
}