lisette-emit 0.2.13

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
use crate::EmitEffects;
use crate::Planner;
use crate::Renderer;
use crate::ReturnContext;
use crate::abi::coercion::{Coercion, CoercionDirection};
use crate::context::expression::ExpressionContext;
use crate::is_order_sensitive;
use crate::names::go_name;
use crate::plan::bodies::{AssignForm, AssignPlan, CompoundKind, LoweredBlock, LoweredStatement};
use crate::plan::values::value_plan_from_statements;
use crate::state::bindings::BindingValue;
use syntax::ast::{BinaryOperator, Expression, UnaryOperator};
use syntax::parse::TUPLE_FIELDS;
use syntax::types::Type;

impl Planner<'_> {
    /// String-context bridge over `lower_statement`.
    pub(crate) fn emit_statement(
        &mut self,
        output: &mut String,
        expression: &Expression,
        return_ctx: &ReturnContext,
        fx: &mut EmitEffects,
    ) {
        let statement = self.lower_statement(expression, return_ctx, fx);
        let block = LoweredBlock {
            statements: vec![statement],
        };
        Renderer.render_lowered_block(output, &block);
    }

    /// Build an `AssignPlan`, dispatching on shape: never-typed, compound,
    /// discard, Go-nullable-field clear, or simple `target = value`.
    pub(crate) fn build_assignment_plan(
        &mut self,
        target: &Expression,
        value: &Expression,
        compound_operator: Option<&BinaryOperator>,
        return_ctx: &ReturnContext,
        directive: String,
        fx: &mut EmitEffects,
    ) -> AssignPlan {
        let raw_body = |statements: Vec<LoweredStatement>| LoweredBlock { statements };
        let capture_to_vec = |buffer: String| {
            if buffer.is_empty() {
                Vec::new()
            } else {
                vec![LoweredStatement::RawGo(buffer)]
            }
        };

        if value.get_type().is_never() {
            let mut buffer = String::new();
            self.emit_statement(&mut buffer, value, return_ctx, fx);
            return AssignPlan {
                directive,
                form: AssignForm::NeverTyped {
                    body: raw_body(vec![LoweredStatement::RawGo(buffer)]),
                },
            };
        }

        if let Some((op, rhs)) = detect_compound_assignment(target, value, compound_operator) {
            let mut target_setup = String::new();
            let target_str = if is_order_sensitive(target) {
                self.emit_left_value_capturing(&mut target_setup, target, false, fx)
            } else {
                self.emit_left_value(&mut target_setup, target, fx)
            };
            let target_capture = capture_to_vec(target_setup);
            let is_inc_dec = is_literal_one(rhs)
                && matches!(op, BinaryOperator::Addition | BinaryOperator::Subtraction);
            let kind = if is_inc_dec {
                if *op == BinaryOperator::Addition {
                    CompoundKind::Increment
                } else {
                    CompoundKind::Decrement
                }
            } else {
                let staged = self.stage_operand(rhs, ExpressionContext::value(), fx);
                CompoundKind::OpAssign {
                    op_text: format!("{}", op),
                    rhs: value_plan_from_statements(staged.setup, staged.value),
                }
            };
            return AssignPlan {
                directive,
                form: AssignForm::Compound {
                    target_capture,
                    target_str,
                    kind,
                },
            };
        }

        if self.target_binds_to_discard(target) {
            let mut buffer = String::new();
            self.emit_discard(&mut buffer, value, return_ctx, fx);
            return AssignPlan {
                directive,
                form: AssignForm::Discard {
                    body: raw_body(vec![LoweredStatement::RawGo(buffer)]),
                },
            };
        }

        let go_field_ty: Option<Type> = match target {
            Expression::DotAccess { expression, ty, .. }
                if self.go_imported_shape(&expression.get_type()).is_some()
                    && (self.is_go_nullable(ty) || ty.resolves_to_unknown()) =>
            {
                Some(ty.clone())
            }
            _ => None,
        };

        if let Some(ref target_ty) = go_field_ty
            && target_ty.resolves_to_unknown()
            && value.is_none_literal()
        {
            let mut target_setup = String::new();
            let target_str = if is_order_sensitive(target) {
                self.emit_left_value_capturing(&mut target_setup, target, false, fx)
            } else {
                self.emit_left_value(&mut target_setup, target, fx)
            };
            return AssignPlan {
                directive,
                form: AssignForm::NilClear {
                    target_capture: capture_to_vec(target_setup),
                    target_str,
                },
            };
        }

        // `target = value`. Stage RHS first (so the target capture knows
        // whether RHS produced setup), capture the target, then fold RHS
        // setup + coercion setup into the value plan in emission order.
        let rhs_staged = self.stage_composite(
            value,
            ExpressionContext::value().with_ambient_return_ctx(return_ctx),
            fx,
        );
        let rhs_has_setup = !rhs_staged.setup.is_empty();
        let mut target_setup = String::new();
        let target_str = if is_order_sensitive(target) {
            self.emit_left_value_capturing(&mut target_setup, target, rhs_has_setup, fx)
        } else {
            self.emit_left_value(&mut target_setup, target, fx)
        };
        let mut value_setup = rhs_staged.setup;
        let coercion = if let Some(target_ty) = go_field_ty {
            Coercion::resolve(
                self,
                &value.get_type(),
                &target_ty,
                CoercionDirection::ToGoBoundary,
            )
        } else {
            Coercion::resolve(
                self,
                &value.get_type(),
                &target.get_type(),
                CoercionDirection::Internal,
            )
        };
        let (coercion_setup, final_value) = coercion.lower(self, rhs_staged.value, fx);
        value_setup.extend(coercion_setup);
        AssignPlan {
            directive,
            form: AssignForm::Simple {
                target_capture: capture_to_vec(target_setup),
                target_str,
                value: value_plan_from_statements(value_setup, final_value),
            },
        }
    }

    fn target_binds_to_discard(&self, target: &Expression) -> bool {
        let Expression::Identifier { value, .. } = target.unwrap_parens() else {
            return false;
        };
        match self.scope.resolve_identifier_binding(value) {
            Some(BindingValue::GoName(go_name)) => go_name == "_",
            Some(BindingValue::InlineExpr(_)) => false,
            None => value == "_",
        }
    }

    pub(crate) fn emit_left_value(
        &mut self,
        output: &mut String,
        expression: &Expression,
        fx: &mut EmitEffects,
    ) -> String {
        let expression = expression.unwrap_parens();
        match expression {
            Expression::Identifier { value, .. } => self
                .scope
                .resolve_binding_go_name(value)
                .unwrap_or(value)
                .to_string(),
            Expression::DotAccess {
                expression, member, ..
            } => {
                let base_str = if let Some(inner) = expression.deref_inner() {
                    self.emit_operand(output, inner, ExpressionContext::value(), fx)
                } else {
                    self.emit_operand(output, expression, ExpressionContext::value(), fx)
                };
                let expression_ty = expression.get_type();
                self.format_dot_access_lvalue(&base_str, &expression_ty, member, fx)
            }
            Expression::IndexedAccess {
                expression, index, ..
            } => {
                let expression_string = if let Some(inner) = expression.deref_inner() {
                    let inner_str =
                        self.emit_operand(output, inner, ExpressionContext::value(), fx);
                    format!("(*{})", inner_str)
                } else {
                    self.emit_operand(output, expression, ExpressionContext::value(), fx)
                };
                let index_str = self.emit_operand(output, index, ExpressionContext::value(), fx);
                format!("{}[{}]", expression_string, index_str)
            }
            Expression::Unary {
                operator: UnaryOperator::Deref,
                expression,
                ..
            } => self.emit_deref_lvalue(output, expression, fx),
            Expression::Call { .. } if expression.get_type().is_ref() => {
                let call_str =
                    self.emit_operand(output, expression, ExpressionContext::value(), fx);
                self.hoist_tmp_value(output, "ref", &call_str)
            }
            _ => "_".to_string(),
        }
    }

    /// Emit `*X` lvalue form, capturing the pointee into a temp if it's a
    /// call (Go requires an addressable operand for deref-assignment).
    fn emit_deref_lvalue(
        &mut self,
        output: &mut String,
        pointee: &Expression,
        fx: &mut EmitEffects,
    ) -> String {
        let pointee_string = self.emit_operand(output, pointee, ExpressionContext::value(), fx);
        if matches!(pointee.unwrap_parens(), Expression::Call { .. }) {
            let tmp = self.hoist_tmp_value(output, "ref", &pointee_string);
            return format!("*{}", tmp);
        }
        format!("*{}", pointee_string)
    }

    /// Format a dot-access lvalue (struct field or tuple element) onto the
    /// already-emitted base expression. Numeric members route through the
    /// tuple-struct field helper (newtype unwrap) or positional `Fi` fallback.
    fn format_dot_access_lvalue(
        &mut self,
        base_str: &str,
        expression_ty: &Type,
        member: &str,
        fx: &mut EmitEffects,
    ) -> String {
        if let Ok(index) = member.parse::<usize>() {
            let access =
                self.try_emit_tuple_struct_field_access(base_str, expression_ty, index, fx);
            if let Some(access) = access {
                return access;
            }
            let field = TUPLE_FIELDS.get(index).expect("oversize tuple arity");
            return format!("{}.{}", base_str, field);
        }
        let field = if self.field_is_public(expression_ty, member) {
            go_name::make_exported(member)
        } else {
            go_name::escape_keyword(member).into_owned()
        };
        format!("{}.{}", base_str, field)
    }

    /// Emit a left-value, capturing side-effecting subexpressions (index, base)
    /// to temp vars so they evaluate before any RHS temps, but leaving the
    /// structural lvalue intact (so assigning to it mutates the original).
    pub(crate) fn emit_left_value_capturing(
        &mut self,
        output: &mut String,
        expression: &Expression,
        rhs_has_setup: bool,
        fx: &mut EmitEffects,
    ) -> String {
        let expression = expression.unwrap_parens();
        match expression {
            Expression::IndexedAccess {
                expression: base,
                index,
                ..
            } => {
                let base_str = self.emit_indexed_base_lvalue(output, base, fx);
                let index_str = self.emit_index_lvalue(output, index, rhs_has_setup, fx);
                format!("{}[{}]", base_str, index_str)
            }
            Expression::DotAccess {
                expression: base,
                member,
                ..
            } => {
                let base_str = if let Some(inner) = base.deref_inner() {
                    self.emit_operand(output, inner, ExpressionContext::value(), fx)
                } else if is_order_sensitive(base) {
                    self.emit_left_value_capturing(output, base, rhs_has_setup, fx)
                } else {
                    self.emit_left_value(output, base, fx)
                };
                let expression_ty = base.get_type();
                self.format_dot_access_lvalue(&base_str, &expression_ty, member, fx)
            }
            Expression::Unary {
                operator: UnaryOperator::Deref,
                expression: inner,
                ..
            } => self.emit_deref_lvalue(output, inner, fx),
            _ => self.emit_left_value(output, expression, fx),
        }
    }

    /// Emit the base of an `IndexedAccess` lvalue, peeling an explicit deref
    /// so `(*ptr)[i]` evaluates the pointer separately from the index, and
    /// capturing the base to a temp when ordering matters.
    fn emit_indexed_base_lvalue(
        &mut self,
        output: &mut String,
        base: &Expression,
        fx: &mut EmitEffects,
    ) -> String {
        let force = is_order_sensitive(base);
        if let Some(inner) = base.deref_inner() {
            let inner_str = self.emit_base_operand(output, inner, force, fx);
            format!("(*{})", inner_str)
        } else {
            self.emit_base_operand(output, base, force, fx)
        }
    }

    fn emit_base_operand(
        &mut self,
        output: &mut String,
        expression: &Expression,
        force_capture: bool,
        fx: &mut EmitEffects,
    ) -> String {
        if force_capture {
            self.emit_force_capture(output, expression, "base", fx)
        } else {
            self.emit_operand(output, expression, ExpressionContext::value(), fx)
        }
    }

    /// Emit the index of an `IndexedAccess` lvalue, capturing to a temp when
    /// the RHS will emit setup statements that could mutate the index variable,
    /// or when the index expression itself is order-sensitive.
    fn emit_index_lvalue(
        &mut self,
        output: &mut String,
        index: &Expression,
        rhs_has_setup: bool,
        fx: &mut EmitEffects,
    ) -> String {
        let needs_capture = if rhs_has_setup {
            !matches!(index.unwrap_parens(), Expression::Literal { .. })
        } else {
            is_order_sensitive(index)
        };
        if needs_capture {
            self.emit_force_capture(output, index, "idx", fx)
        } else {
            self.emit_operand(output, index, ExpressionContext::value(), fx)
        }
    }
}

/// Recognize compound assignment — either `x += y` syntax (caller supplies
/// `compound_operator`) or the desugared `x = x + y` pattern.
fn detect_compound_assignment<'a>(
    target: &Expression,
    value: &'a Expression,
    compound_operator: Option<&'a BinaryOperator>,
) -> Option<(&'a BinaryOperator, &'a Expression)> {
    if let Some(op) = compound_operator {
        return Some((op, compound_rhs(value)));
    }
    let Expression::Binary {
        left,
        operator,
        right,
        ..
    } = value
    else {
        return None;
    };
    if !is_compound_eligible(operator) || !lvalues_match(target, left) {
        return None;
    }
    Some((operator, right.as_ref()))
}

/// Extract the original RHS from a desugared compound assignment.
/// `x += rhs` is parsed as `Assignment { value: Binary(x, +, rhs), .. }`.
fn compound_rhs(value: &Expression) -> &Expression {
    if let Expression::Binary { right, .. } = value {
        right
    } else {
        value
    }
}

fn is_literal_one(expression: &Expression) -> bool {
    matches!(
        expression.unwrap_parens(),
        Expression::Literal {
            literal: syntax::ast::Literal::Integer { value: 1, .. },
            ..
        }
    )
}

/// Check if two lvalue expressions refer to the same location.
/// Used to detect `x = x + y` → `x += y` patterns.
/// Compares by binding_id for identifiers, recursively for DotAccess/Deref.
/// Deliberately skips IndexedAccess (side-effect hazard from index evaluation).
fn lvalues_match(a: &Expression, b: &Expression) -> bool {
    let a = a.unwrap_parens();
    let b = b.unwrap_parens();
    match (a, b) {
        (
            Expression::Identifier {
                binding_id: Some(id_a),
                ..
            },
            Expression::Identifier {
                binding_id: Some(id_b),
                ..
            },
        ) => id_a == id_b,
        (
            Expression::DotAccess {
                expression: base_a,
                member: member_a,
                ..
            },
            Expression::DotAccess {
                expression: base_b,
                member: member_b,
                ..
            },
        ) => member_a == member_b && lvalues_match(base_a, base_b),
        (
            Expression::Unary {
                operator: UnaryOperator::Deref,
                expression: inner_a,
                ..
            },
            Expression::Unary {
                operator: UnaryOperator::Deref,
                expression: inner_b,
                ..
            },
        ) => lvalues_match(inner_a, inner_b),
        _ => false,
    }
}

fn is_compound_eligible(op: &BinaryOperator) -> bool {
    matches!(
        op,
        BinaryOperator::Addition
            | BinaryOperator::Subtraction
            | BinaryOperator::Multiplication
            | BinaryOperator::Division
            | BinaryOperator::Remainder
    )
}

pub(crate) fn is_lvalue_chain(expression: &Expression) -> bool {
    let expression = expression.unwrap_parens();
    match expression {
        Expression::Identifier { .. } => true,
        Expression::Unary {
            operator: UnaryOperator::Deref,
            ..
        } => true,
        Expression::IndexedAccess { expression, .. } => is_lvalue_chain(expression),
        Expression::DotAccess { expression, .. } => is_lvalue_chain(expression),
        Expression::Call { .. } if expression.get_type().is_ref() => true,
        _ => false,
    }
}