lisette-emit 0.2.5

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
use super::NativeCallContext;
use crate::Emitter;
use crate::expressions::access::index_access::range_var_bounds;
use crate::expressions::context::ExpressionContext;
use crate::expressions::emission::EmittedExpression;
use crate::names::go_name;
use crate::types::native::NativeGoType;
use syntax::ast::Expression;
use syntax::types::peel_to_range_type;

#[derive(Clone, Copy)]
pub(super) enum InlineImport {
    None,
    Slices,
    Strings,
    Maps,
    Stdlib,
}

struct InlineRule {
    types: &'static [NativeGoType],
    method: &'static str,
    arity: i8,
    template: &'static str,
    import: InlineImport,
}

type N = NativeGoType;

static INLINE_METHODS: &[InlineRule] = &[
    // No-arg methods
    InlineRule {
        types: &[
            N::Slice,
            N::Map,
            N::Channel,
            N::Sender,
            N::Receiver,
            N::String,
        ],
        method: "length",
        arity: 0,
        template: "len({r})",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::Slice, N::Channel, N::Sender, N::Receiver],
        method: "capacity",
        arity: 0,
        template: "cap({r})",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[
            N::Slice,
            N::Map,
            N::Channel,
            N::Sender,
            N::Receiver,
            N::String,
        ],
        method: "is_empty",
        arity: 0,
        template: "len({r}) == 0",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::Slice],
        method: "enumerate",
        arity: 0,
        template: "{r}",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::Slice],
        method: "clone",
        arity: 0,
        template: "slices.Clone({r})",
        import: InlineImport::Slices,
    },
    InlineRule {
        types: &[N::Map],
        method: "clone",
        arity: 0,
        template: "maps.Clone({r})",
        import: InlineImport::Maps,
    },
    InlineRule {
        types: &[N::String],
        method: "bytes",
        arity: 0,
        template: "[]byte({r})",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::String],
        method: "runes",
        arity: 0,
        template: "[]rune({r})",
        import: InlineImport::None,
    },
    // Single-arg methods
    InlineRule {
        types: &[N::Map],
        method: "delete",
        arity: 1,
        template: "delete({r}, {0})",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::Slice],
        method: "extend",
        arity: 1,
        template: "append({r}, {0}...)",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::Slice],
        method: "copy_from",
        arity: 1,
        template: "copy({r}, {0})",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::Slice],
        method: "contains",
        arity: 1,
        template: "slices.Contains({r}, {0})",
        import: InlineImport::Slices,
    },
    InlineRule {
        types: &[N::String],
        method: "contains",
        arity: 1,
        template: "strings.Contains({r}, {0})",
        import: InlineImport::Strings,
    },
    InlineRule {
        types: &[N::String],
        method: "split",
        arity: 1,
        template: "strings.Split({r}, {0})",
        import: InlineImport::Strings,
    },
    InlineRule {
        types: &[N::String],
        method: "starts_with",
        arity: 1,
        template: "strings.HasPrefix({r}, {0})",
        import: InlineImport::Strings,
    },
    InlineRule {
        types: &[N::String],
        method: "ends_with",
        arity: 1,
        template: "strings.HasSuffix({r}, {0})",
        import: InlineImport::Strings,
    },
    InlineRule {
        types: &[N::String],
        method: "byte_at",
        arity: 1,
        template: "{r}[{0}]",
        import: InlineImport::None,
    },
    InlineRule {
        types: &[N::String],
        method: "rune_at",
        arity: 1,
        template: "lisette.RuneAt({r}, {0})",
        import: InlineImport::Stdlib,
    },
    InlineRule {
        types: &[N::Slice],
        method: "join",
        arity: 1,
        template: "strings.Join({r}, {0})",
        import: InlineImport::Strings,
    },
    InlineRule {
        types: &[N::Slice],
        method: "any",
        arity: 1,
        template: "slices.ContainsFunc({r}, {0})",
        import: InlineImport::Slices,
    },
    // Variadic methods
    InlineRule {
        types: &[N::Slice],
        method: "append",
        arity: -1,
        template: "append({r+args})",
        import: InlineImport::None,
    },
];

fn render_inline(rule: &InlineRule, receiver: &str, args: &[String]) -> String {
    let mut result = rule.template.to_string();
    result = result.replace("{r}", receiver);
    for (i, arg) in args.iter().enumerate() {
        result = result.replace(&format!("{{{}}}", i), arg);
    }
    if result.contains("{args}") {
        result = result.replace("{args}", &args.join(", "));
    }
    if result.contains("{r+args}") {
        let all = std::iter::once(receiver.to_string())
            .chain(args.iter().cloned())
            .collect::<Vec<_>>()
            .join(", ");
        result = result.replace("{r+args}", &all);
    }
    result
}

/// Try to inline a native type method call to raw Go.
///
/// Many native type methods are thin wrappers around Go builtins.
/// Inlining them produces cleaner output and avoids function call overhead.
///
/// Returns `Some((code, extra_import))` if the method can be inlined.
pub(super) fn try_inline_native_method(
    native_type: &NativeGoType,
    method: &str,
    receiver: &str,
    args: &[String],
) -> Option<(String, InlineImport)> {
    // Special case: append with 0 args returns receiver unchanged
    // (Go's append requires at least 2 args)
    if method == "append" && args.is_empty() {
        return Some((receiver.to_string(), InlineImport::None));
    }

    let rule = INLINE_METHODS.iter().find(|s| {
        s.method == method
            && s.types.contains(native_type)
            && (s.arity < 0 || s.arity as usize == args.len())
    })?;

    Some((render_inline(rule, receiver, args), rule.import))
}

impl Emitter<'_> {
    pub(super) fn apply_inline_import(&mut self, import: InlineImport) {
        match import {
            InlineImport::Slices => self.requirements.require_slices(),
            InlineImport::Strings => self.requirements.require_strings(),
            InlineImport::Maps => self.requirements.require_maps(),
            InlineImport::Stdlib => self.requirements.require_stdlib(),
            InlineImport::None => {}
        }
    }

    pub(super) fn emit_native_method_dot_access(
        &mut self,
        output: &mut String,
        ctx: &NativeCallContext,
    ) -> String {
        let Expression::DotAccess { expression, .. } = ctx.function else {
            unreachable!("expected DotAccess for native method call")
        };

        if matches!(ctx.native_type, NativeGoType::String) && ctx.method == "substring" {
            return self.emit_string_substring(output, expression, ctx.args);
        }

        let mut all_stages: Vec<EmittedExpression> =
            Vec::with_capacity(1 + ctx.args.len() + ctx.spread.is_some() as usize);
        all_stages.push(self.stage_operand(expression, ExpressionContext::value()));
        all_stages.extend(self.stage_native_method_args(ctx.function, ctx.args));

        let combine = Self::variadic_combine_for(ctx.function, ctx.spread, 1);
        let all_values =
            self.sequence_with_spread(output, all_stages, ctx.spread, false, "_arg", combine);

        let raw_receiver = all_values[0].clone();
        let emitted_args: Vec<String> = all_values[1..].to_vec();

        let is_ref_receiver = expression.get_type().is_ref();
        let receiver = if is_ref_receiver {
            format!("*{}", raw_receiver)
        } else {
            raw_receiver.clone()
        };

        if let Some((inlined, extra_import)) =
            try_inline_native_method(ctx.native_type, ctx.method, &receiver, &emitted_args)
        {
            self.apply_inline_import(extra_import);

            return inlined;
        }

        if !emitted_args.is_empty() {
            let static_receiver = &emitted_args[0];
            let remaining_args = &emitted_args[1..];
            if let Some((inlined, extra_import)) = try_inline_native_method(
                ctx.native_type,
                ctx.method,
                static_receiver,
                remaining_args,
            ) {
                self.apply_inline_import(extra_import);
                return inlined;
            }
        }

        let mut new_args = vec![receiver];
        new_args.extend(emitted_args);
        self.requirements.require_stdlib();
        let fn_name = format!(
            "{}.{}{}",
            go_name::GO_STDLIB_PKG,
            ctx.native_type.method_prefix(),
            go_name::snake_to_camel(ctx.method)
        );
        let type_args_string = if !ctx.type_args.is_empty() && ctx.call_ty.is_some() {
            let receiver_ty = expression.get_type();
            self.format_type_args_with_receiver(&receiver_ty, ctx.type_args)
        } else {
            self.format_type_args_from_annotations(ctx.type_args)
        };
        format!("{}{}({})", fn_name, type_args_string, new_args.join(", "))
    }

    pub(super) fn emit_native_method_identifier(
        &mut self,
        output: &mut String,
        ctx: &NativeCallContext,
    ) -> String {
        if matches!(ctx.native_type, NativeGoType::String)
            && ctx.method == "substring"
            && ctx.args.len() >= 2
        {
            return self.emit_string_substring(output, &ctx.args[0], &ctx.args[1..]);
        }

        let stages = self.stage_native_method_args(ctx.function, ctx.args);

        let combine = Self::variadic_combine_for(ctx.function, ctx.spread, 0);
        let emitted_args =
            self.sequence_with_spread(output, stages, ctx.spread, false, "_arg", combine);

        if !emitted_args.is_empty() {
            let receiver = &emitted_args[0];
            let remaining_args = &emitted_args[1..];
            if let Some((inlined, extra_import)) =
                try_inline_native_method(ctx.native_type, ctx.method, receiver, remaining_args)
            {
                self.apply_inline_import(extra_import);
                return inlined;
            }
        }

        self.requirements.require_stdlib();
        let fn_name = format!(
            "{}.{}{}",
            go_name::GO_STDLIB_PKG,
            ctx.native_type.method_prefix(),
            go_name::snake_to_camel(ctx.method)
        );
        let type_args_string = self.format_type_args_from_annotations(ctx.type_args);
        format!(
            "{}{}({})",
            fn_name,
            type_args_string,
            emitted_args.join(", ")
        )
    }

    fn emit_string_substring(
        &mut self,
        output: &mut String,
        receiver_expr: &Expression,
        args: &[Expression],
    ) -> String {
        self.requirements.require_stdlib();
        let arg = &args[0];
        let is_ref_receiver = receiver_expr.get_type().is_ref();
        let deref = |raw: &str| -> String {
            if is_ref_receiver {
                format!("*{}", raw)
            } else {
                raw.to_string()
            }
        };

        if let Expression::Range {
            start,
            end,
            inclusive,
            ..
        } = arg
        {
            let mut stages = vec![self.stage_operand(receiver_expr, ExpressionContext::value())];
            if let Some(s) = start.as_deref() {
                stages.push(self.stage_operand(s, ExpressionContext::value()));
            }
            if let Some(e) = end.as_deref() {
                stages.push(self.stage_operand(e, ExpressionContext::value()));
            }
            let values = self.sequence(output, stages, "_arg");
            let mut bounds = values.iter().skip(1);
            let start_bound = start.is_some().then(|| bounds.next().unwrap().clone());
            let end_bound = end.is_some().then(|| {
                let e = bounds.next().unwrap();
                if *inclusive {
                    format!("{}+1", e)
                } else {
                    e.clone()
                }
            });
            return format_substring_call(
                &deref(&values[0]),
                start_bound.as_deref(),
                end_bound.as_deref(),
            );
        }

        let arg_ty = arg.get_type();
        let range_kind = peel_to_range_type(&arg_ty)
            .and_then(|t| t.get_name())
            .expect("substring arg should resolve to a known range type");
        let receiver_staged = self.stage_operand(receiver_expr, ExpressionContext::value());
        let range_staged = self.stage_or_capture(arg, "range");
        let values = self.sequence(output, vec![receiver_staged, range_staged], "_arg");
        let (start, end) = range_var_bounds(&values[1], range_kind);
        format_substring_call(&deref(&values[0]), start.as_deref(), end.as_deref())
    }
}

fn format_substring_call(recv: &str, start: Option<&str>, end: Option<&str>) -> String {
    let pkg = go_name::GO_STDLIB_PKG;
    match (start, end) {
        (Some(s), Some(e)) => format!("{}.Substring({}, {}, {})", pkg, recv, s, e),
        (Some(s), None) => format!("{}.SubstringFrom({}, {})", pkg, recv, s),
        (None, Some(e)) => format!("{}.SubstringTo({}, {})", pkg, recv, e),
        (None, None) => unreachable!("`s.substring(..)` is rejected upstream"),
    }
}