aver-lang 0.17.2

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
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
#![allow(clippy::doc_lazy_continuation)]
//! Traversal-pass lints — surfaces antipatterns that the buffer-build
//! deforestation pass deliberately *does not* fuse.
//!
//! The fuse-vs-warn split is intentional: silent fusion fits when Aver
//! forces the idiom (string interpolation has no user-level alternative;
//! `String.join(<sink>(args, []), sep)` has no exposed `String.Builder`
//! to write directly). It does NOT fit when Aver already publishes a
//! more direct primitive — fusing then would hide both the cost and
//! the better idiom from the programmer.
//!
//! Three patterns land here:
//!
//! 1. `Vector.fromList(<sink>(args, []))` — Aver has `Vector.new(N, default)`
//!    + `Option.withDefault(Vector.set(v, i, x), v)` (the owned-mutate
//!    fast path published in 0.14.0). Building a `List<T>` only to flatten
//!    it into a `Vector<T>` allocates ~2N cons cells (N from prepend, N
//!    from the implicit reverse-during-fromList walk) plus the final
//!    `Vec<T>`. The direct-fill version skips the whole list intermediate.
//!
//! 2. `Map.fromList(<sink>(args, []))` — same pattern with `{}` (empty
//!    map literal) + `Map.set` chain. Marginal in practice (~6 sites
//!    in-tree) but treated uniformly with Vector for consistency of
//!    advice.
//!
//! 3. Standalone `List.reverse(<sink>(args, []))` whose result is *not*
//!    fed straight into `String.join` (when it is, the external-reverse
//!    fusion path already eliminates the explicit reverse). When the
//!    result is consumed as a `List<T>`, the user has the option to
//!    write the sink so that the base case returns `acc` already in the
//!    right order — typically by accumulating with append-via-tail-cons
//!    instead of prepend, or by computing index-based offsets.
//!
//! All three reuse the same sink-shape detector `compute_buffer_build_sinks`
//! the deforestation pass uses, so the lint and the optimization stay
//! in lockstep — what we don't fuse, we warn about.

use std::collections::HashMap;

use crate::ast::{Expr, FnDef, Pattern, Spanned, Stmt, TopLevel};
use crate::ir::{BufferBuildShape, compute_buffer_build_sinks};

use super::CheckFinding;

pub fn collect_traversal_warnings_in(items: &[TopLevel], file: Option<&str>) -> Vec<CheckFinding> {
    let fn_refs: Vec<&FnDef> = items
        .iter()
        .filter_map(|it| match it {
            TopLevel::FnDef(fd) => Some(fd),
            _ => None,
        })
        .collect();
    let sinks = compute_buffer_build_sinks(&fn_refs);
    if sinks.is_empty() {
        return Vec::new();
    }

    let module_name = items.iter().find_map(|item| match item {
        TopLevel::Module(m) => Some(m.name.clone()),
        _ => None,
    });

    let mut warnings = Vec::new();
    for fd in &fn_refs {
        for stmt in fd.body.stmts() {
            match stmt {
                Stmt::Binding(_, _, expr) | Stmt::Expr(expr) => walk(
                    &expr.node,
                    expr.line,
                    /* inside_string_join = */ false,
                    fd,
                    &sinks,
                    &module_name,
                    file,
                    &mut warnings,
                ),
            }
        }
    }
    warnings
}

#[allow(clippy::too_many_arguments)]
fn walk(
    expr: &Expr,
    fallback_line: usize,
    inside_string_join: bool,
    fd: &FnDef,
    sinks: &HashMap<String, BufferBuildShape>,
    module_name: &Option<String>,
    file: Option<&str>,
    out: &mut Vec<CheckFinding>,
) {
    if let Expr::FnCall(callee, args) = expr {
        // Vector.fromList(<sink>(args, []))
        if is_dotted(&callee.node, "Vector", "fromList")
            && args.len() == 1
            && let Some(name) = sink_call_with_empty_acc(&args[0].node, sinks)
        {
            out.push(make_finding(
                fallback_line,
                module_name,
                file,
                fd,
                format!(
                    "Vector.fromList over a recursive list builder ({}). \
                     Consider Vector.new(N, default) + Option.withDefault(Vector.set(v, i, x), v) \
                     when the target size is known — skips ~2N cons-cell allocations and the \
                     list-to-vector copy.",
                    name
                ),
            ));
        }

        // Map.fromList(<sink>(args, []))
        if is_dotted(&callee.node, "Map", "fromList")
            && args.len() == 1
            && let Some(name) = sink_call_with_empty_acc(&args[0].node, sinks)
        {
            out.push(make_finding(
                fallback_line,
                module_name,
                file,
                fd,
                format!(
                    "Map.fromList over a recursive list builder ({}). \
                     Consider threading a Map directly via {{}} + Map.set in the \
                     accumulator slot — skips the cons-cell intermediate and the fold.",
                    name
                ),
            ));
        }

        // Standalone List.reverse(<sink>(args, [])) — only flag when
        // NOT inside a `String.join(...)`. Inside, the external-reverse
        // fusion already handles it.
        if !inside_string_join
            && is_dotted(&callee.node, "List", "reverse")
            && args.len() == 1
            && let Some(name) = sink_call_with_empty_acc(&args[0].node, sinks)
        {
            out.push(make_finding(
                fallback_line,
                module_name,
                file,
                fd,
                format!(
                    "List.reverse over a recursive prepend-builder ({}) used as a list result. \
                     The reverse pass allocates a second N cons cells. If the result feeds \
                     `String.join`, the deforestation pass eliminates both this reverse and \
                     the intermediate list — nothing to do. Otherwise consider building the \
                     list in forward order directly (e.g. by computing positions).",
                    name
                ),
            ));
        }

        // Recurse into args. Track whether we're inside a String.join's
        // first arg so the standalone-reverse warning skips that case.
        let is_string_join = is_dotted(&callee.node, "String", "join") && args.len() == 2;
        for (i, arg) in args.iter().enumerate() {
            walk(
                &arg.node,
                line_of(arg, fallback_line),
                inside_string_join || (is_string_join && i == 0),
                fd,
                sinks,
                module_name,
                file,
                out,
            );
        }
        // Recurse through the callee too (e.g. partial-application
        // shapes; rare in Aver but harmless to cover).
        walk(
            &callee.node,
            line_of(callee, fallback_line),
            inside_string_join,
            fd,
            sinks,
            module_name,
            file,
            out,
        );
        return;
    }

    visit_subexprs(
        expr,
        fallback_line,
        inside_string_join,
        fd,
        sinks,
        module_name,
        file,
        out,
    );
}

#[allow(clippy::too_many_arguments)]
fn visit_subexprs(
    expr: &Expr,
    fallback_line: usize,
    inside_string_join: bool,
    fd: &FnDef,
    sinks: &HashMap<String, BufferBuildShape>,
    module_name: &Option<String>,
    file: Option<&str>,
    out: &mut Vec<CheckFinding>,
) {
    let mut recurse = |sub: &Spanned<Expr>| {
        walk(
            &sub.node,
            line_of(sub, fallback_line),
            inside_string_join,
            fd,
            sinks,
            module_name,
            file,
            out,
        );
    };
    match expr {
        Expr::Literal(_)
        | Expr::Ident(_)
        | Expr::Resolved { .. }
        | Expr::Constructor(_, None)
        | Expr::InterpolatedStr(_) => {}
        Expr::Constructor(_, Some(inner)) | Expr::Attr(inner, _) | Expr::ErrorProp(inner) => {
            recurse(inner);
        }
        Expr::FnCall(_, _) => {
            // Handled by the FnCall arm in `walk` directly; not reached
            // through `visit_subexprs` because `walk` returns early.
        }
        Expr::TailCall(data) => {
            for a in data.args.iter() {
                recurse(a);
            }
        }
        Expr::BinOp(_, l, r) => {
            recurse(l);
            recurse(r);
        }
        Expr::Match { subject, arms } => {
            recurse(subject);
            for arm in arms.iter() {
                recurse(&arm.body);
            }
        }
        Expr::List(items) | Expr::Tuple(items) | Expr::IndependentProduct(items, _) => {
            for it in items.iter() {
                recurse(it);
            }
        }
        Expr::MapLiteral(entries) => {
            for (k, v) in entries.iter() {
                recurse(k);
                recurse(v);
            }
        }
        Expr::RecordCreate { fields, .. } => {
            for (_, v) in fields.iter() {
                recurse(v);
            }
        }
        Expr::RecordUpdate { base, updates, .. } => {
            recurse(base);
            for (_, v) in updates.iter() {
                recurse(v);
            }
        }
    }
}

/// Match `<sink>(args, ...)` where `args[acc_idx]` is a literal empty
/// `List`. Mirrors the precondition the buffer-build rewrite uses for
/// the corresponding fusion sites — a non-empty initial accumulator
/// would pre-load elements the warning's suggested rewrite couldn't
/// silently drop, so we skip in that case (the user's code may be
/// doing something deliberate we don't want to second-guess).
fn sink_call_with_empty_acc(
    expr: &Expr,
    sinks: &HashMap<String, BufferBuildShape>,
) -> Option<String> {
    let Expr::FnCall(callee, args) = expr else {
        return None;
    };
    let Expr::Ident(name) = &callee.node else {
        return None;
    };
    let shape = sinks.get(name)?;
    let acc_arg = args.get(shape.acc_param_idx)?;
    if !matches!(&acc_arg.node, Expr::List(items) if items.is_empty()) {
        return None;
    }
    Some(name.clone())
}

fn is_dotted(expr: &Expr, module: &str, member: &str) -> bool {
    let Expr::Attr(base, attr) = expr else {
        return false;
    };
    if attr != member {
        return false;
    }
    matches!(&base.node, Expr::Ident(name) if name == module)
}

fn line_of(s: &Spanned<Expr>, fallback: usize) -> usize {
    if s.line > 0 { s.line } else { fallback }
}

fn make_finding(
    line: usize,
    module_name: &Option<String>,
    file: Option<&str>,
    fd: &FnDef,
    message: String,
) -> CheckFinding {
    let _ = Pattern::Wildcard; // touch the import so a future extension that
    // pattern-matches doesn't trip the unused-import lint
    CheckFinding {
        line,
        module: module_name.clone(),
        file: file.map(|s| s.to_string()),
        fn_name: Some(fd.name.clone()),
        message,
        extra_spans: vec![],
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::parse_source;

    fn parse_and_lower(src: &str) -> Vec<TopLevel> {
        let mut items = parse_source(src)
            .unwrap_or_else(|e| panic!("parse error: {}\n--- source ---\n{}\n--- end ---", e, src));
        crate::ir::pipeline::tco(&mut items);
        items
    }

    const PURE_HEADER: &str =
        "module M\n    intent = \"t\"\n    exposes [main]\n    effects []\n\n";

    const CONSOLE_HEADER: &str =
        "module M\n    intent = \"t\"\n    exposes [main]\n    effects [Console]\n\n";

    #[test]
    fn warns_on_vector_fromlist_of_builder() {
        let body = "fn build(n: Int, acc: List<Int>) -> List<Int>\n    match n <= 0\n        true  -> List.reverse(acc)\n        false -> build(n - 1, List.prepend(n, acc))\n\nfn main() -> Vector<Int>\n    Vector.fromList(build(10, []))\n";
        let src = format!("{PURE_HEADER}{body}");
        let items = parse_and_lower(&src);
        let warnings = collect_traversal_warnings_in(&items, None);
        assert!(
            warnings
                .iter()
                .any(|w| w.message.contains("Vector.fromList") && w.message.contains("build")),
            "expected Vector.fromList warning; got: {:?}",
            warnings.iter().map(|w| &w.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn warns_on_map_fromlist_of_builder() {
        let body = "fn build(n: Int, acc: List<Tuple<String, Int>>) -> List<Tuple<String, Int>>\n    match n <= 0\n        true  -> List.reverse(acc)\n        false -> build(n - 1, List.prepend((\"k\", n), acc))\n\nfn main() -> Map<String, Int>\n    Map.fromList(build(10, []))\n";
        let src = format!("{PURE_HEADER}{body}");
        let items = parse_and_lower(&src);
        let warnings = collect_traversal_warnings_in(&items, None);
        assert!(
            warnings
                .iter()
                .any(|w| w.message.contains("Map.fromList") && w.message.contains("build")),
            "expected Map.fromList warning"
        );
    }

    #[test]
    fn warns_on_standalone_listreverse_of_builder() {
        let body = "fn build(xs: List<Int>, acc: List<Int>) -> List<Int>\n    match xs\n        []        -> acc\n        [h, ..t]  -> build(t, List.prepend(h * 2, acc))\n\nfn main() -> List<Int>\n    List.reverse(build([1, 2, 3], []))\n";
        let src = format!("{PURE_HEADER}{body}");
        let items = parse_and_lower(&src);
        let warnings = collect_traversal_warnings_in(&items, None);
        assert!(
            warnings.iter().any(
                |w| w.message.contains("List.reverse") && w.message.contains("prepend-builder")
            ),
            "expected standalone List.reverse warning"
        );
    }

    #[test]
    fn does_not_warn_when_listreverse_inside_string_join() {
        // The external-reverse fusion handles this — no warning needed.
        let body = "fn build(xs: List<Int>, acc: List<String>) -> List<String>\n    match xs\n        []        -> acc\n        [h, ..t]  -> build(t, List.prepend(\"x\", acc))\n\nfn main() -> Unit\n    ! [Console.print]\n    Console.print(String.join(List.reverse(build([1, 2, 3], [])), \",\"))\n";
        let src = format!("{CONSOLE_HEADER}{body}");
        let items = parse_and_lower(&src);
        let warnings = collect_traversal_warnings_in(&items, None);
        assert!(
            warnings.iter().all(|w| !w.message.contains("List.reverse")),
            "should NOT warn — String.join wrapper means the fusion path takes over"
        );
    }

    #[test]
    fn does_not_warn_on_non_empty_initial_acc() {
        // The user is starting with a seeded accumulator, which the
        // suggested rewrite would silently lose. Don't second-guess.
        let body = "fn build(n: Int, acc: List<Int>) -> List<Int>\n    match n <= 0\n        true  -> List.reverse(acc)\n        false -> build(n - 1, List.prepend(n, acc))\n\nfn main() -> Vector<Int>\n    Vector.fromList(build(10, [99]))\n";
        let src = format!("{PURE_HEADER}{body}");
        let items = parse_and_lower(&src);
        let warnings = collect_traversal_warnings_in(&items, None);
        assert!(
            warnings.is_empty(),
            "non-empty initial acc should suppress the warning"
        );
    }
}