aver-lang 0.15.0

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
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
528
529
530
531
532
533
534
535
536
//! Single-file analysis pipeline.
//!
//! `analyze_source` is the canonical entry for going from source text to
//! diagnostics. Runtime-neutral: no file IO, no config, no VM. Multi-file
//! concerns (unused exposes, config suppression, dependency resolution)
//! stay in CLI / LSP callers.

use super::factories::{from_check_finding, from_type_error, unused_binding_diagnostic};
use super::model::{AnalysisReport, Diagnostic, Severity, Span};
use crate::checker::{
    CheckFinding, check_module_intent_with_sigs_in, collect_cse_warnings_in,
    collect_independence_warnings_in, collect_module_effects_warnings_in,
    collect_naming_warnings_in, collect_perf_warnings_in,
    collect_plain_cases_effectful_warnings_in, collect_traversal_warnings_in,
    collect_verify_coverage_warnings_in,
};
#[cfg(feature = "runtime")]
use crate::checker::{FindingSpan, collect_verify_law_dependency_warnings_in};
use crate::source::{LoadedModule, parse_source};
#[cfg(feature = "runtime")]
use crate::tail_check::collect_non_tail_recursion_warnings_with_sigs;
use crate::tco;
use crate::types::checker::{run_type_check_full, run_type_check_with_loaded};

/// Options for `analyze_source`. Defaults enable every available collector.
#[derive(Clone, Debug)]
pub struct AnalyzeOptions {
    pub file_label: String,
    pub module_base_dir: Option<String>,
    /// Pre-resolved dependency modules (e.g. from a virtual filesystem
    /// in the playground). When set, takes precedence over
    /// `module_base_dir` — the type checker integrates these directly
    /// instead of loading from disk.
    pub loaded_modules: Option<Vec<LoadedModule>>,
    pub include_intent_warnings: bool,
    pub include_coverage_warnings: bool,
    pub include_law_dependency_warnings: bool,
    pub include_cse_warnings: bool,
    pub include_perf_warnings: bool,
    /// 0.15 Traversal antipattern lints — surfaces uses of recursive
    /// list builders feeding `Vector.fromList`, `Map.fromList`, or a
    /// standalone `List.reverse`, where Aver has a more direct primitive.
    /// Companion to the buffer-build deforestation pass: what we don't
    /// fuse, we warn about.
    pub include_traversal_warnings: bool,
    pub include_independence_warnings: bool,
    pub include_naming_warnings: bool,
    pub include_non_tail_warnings: bool,
    pub include_unused_bindings: bool,
    /// Plain cases-form `verify fn` on an effectful fn whose effect list
    /// includes at least one generative effect. The test runs with real
    /// effects and the RHS is compared against a non-deterministic value.
    pub include_verify_effectful_warnings: bool,
    /// When `true` **and** the `runtime` feature is enabled, execute every
    /// verify block found in the source and emit a diagnostic per failing
    /// case. Off by default: analysis should stay pure static checks;
    /// callers opt in explicitly.
    pub include_verify_run: bool,
    /// When `true` and `include_verify_run` is also `true`, run verify
    /// blocks under `--hostile` mode: typed `given` domains are expanded
    /// with the per-type boundary set and each case is multiplied by the
    /// adversarial effect-profile cartesian. Failures that surface only
    /// here are flagged with `from_hostile = true` so the renderer can
    /// suggest weakening the law (`when`) or pinning the effect (`given`).
    pub verify_run_hostile: bool,
    /// When `true`, populate `AnalysisReport::why_summary` with
    /// per-function justification data. Off by default.
    pub include_why_summary: bool,
    /// When `true`, populate `AnalysisReport::context_summary` with
    /// module shape / function / type / decision summary.
    pub include_context_summary: bool,
}

impl Default for AnalyzeOptions {
    fn default() -> Self {
        Self {
            file_label: "<input>".to_string(),
            module_base_dir: None,
            loaded_modules: None,
            include_intent_warnings: true,
            include_coverage_warnings: true,
            include_law_dependency_warnings: true,
            include_cse_warnings: true,
            include_perf_warnings: true,
            include_traversal_warnings: true,
            include_independence_warnings: true,
            include_naming_warnings: true,
            include_non_tail_warnings: true,
            include_unused_bindings: true,
            include_verify_effectful_warnings: true,
            include_verify_run: false,
            verify_run_hostile: false,
            include_why_summary: false,
            include_context_summary: false,
        }
    }
}

impl AnalyzeOptions {
    pub fn new(file_label: impl Into<String>) -> Self {
        Self {
            file_label: file_label.into(),
            ..Default::default()
        }
    }

    pub fn with_module_base_dir(mut self, dir: impl Into<String>) -> Self {
        self.module_base_dir = Some(dir.into());
        self
    }

    pub fn with_loaded_modules(mut self, loaded: Vec<LoadedModule>) -> Self {
        self.loaded_modules = Some(loaded);
        self
    }
}

/// Run the single-file analysis pipeline.
///
/// Pipeline: parse → TCO → typecheck → collectors → canonical diagnostics.
/// Returns all diagnostics encountered; does not stop at first error.
pub fn analyze_source(source: &str, options: &AnalyzeOptions) -> AnalysisReport {
    let items = match parse_source(source) {
        Ok(items) => items,
        Err(e) => {
            return AnalysisReport::with_diagnostics(
                options.file_label.clone(),
                vec![parse_error_diagnostic(&e, source, &options.file_label)],
            );
        }
    };

    let mut transformed = items.clone();
    tco::transform_program(&mut transformed);

    let tc_result = if let Some(loaded) = options.loaded_modules.as_deref() {
        run_type_check_with_loaded(&items, loaded)
    } else {
        run_type_check_full(&items, options.module_base_dir.as_deref())
    };

    let mut diagnostics: Vec<Diagnostic> = Vec::new();

    for te in &tc_result.errors {
        diagnostics.push(from_type_error(te, source, &options.file_label));
    }

    let findings = if options.include_intent_warnings {
        Some(check_module_intent_with_sigs_in(
            &items,
            Some(&tc_result.fn_sigs),
            None,
        ))
    } else {
        None
    };

    if let Some(ref findings) = findings {
        for e in &findings.errors {
            diagnostics.push(from_check_finding(
                Severity::Error,
                e,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_unused_bindings {
        for (binding, fn_name, line) in &tc_result.unused_bindings {
            diagnostics.push(unused_binding_diagnostic(
                binding,
                fn_name,
                *line,
                source,
                &options.file_label,
            ));
        }
    }

    if let Some(ref findings) = findings {
        for w in &findings.warnings {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_coverage_warnings {
        for w in collect_verify_coverage_warnings_in(&items, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    // Module-level `effects [...]` boundary diagnostics. Underdeclared
    // (a fn uses an effect outside the boundary) is a hard type error,
    // surfaced via `tc_result.errors`. Overdeclared (boundary lists
    // effects no fn uses) is a softer hint — still worth surfacing so
    // the module header documents what the code actually does.
    for w in collect_module_effects_warnings_in(&items, None) {
        diagnostics.push(from_check_finding(
            Severity::Warning,
            &w,
            source,
            &options.file_label,
        ));
    }

    #[cfg(feature = "runtime")]
    if options.include_law_dependency_warnings {
        for w in collect_verify_law_dependency_warnings_in(&items, &tc_result.fn_sigs, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_cse_warnings {
        for w in collect_cse_warnings_in(&transformed, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_perf_warnings {
        for w in collect_perf_warnings_in(&transformed, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_traversal_warnings {
        for w in collect_traversal_warnings_in(&transformed, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_independence_warnings {
        for w in collect_independence_warnings_in(&transformed, &tc_result.fn_sigs, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_verify_effectful_warnings {
        for w in collect_plain_cases_effectful_warnings_in(&transformed, &tc_result.fn_sigs, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    if options.include_naming_warnings {
        for w in collect_naming_warnings_in(&items, None) {
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &w,
                source,
                &options.file_label,
            ));
        }
    }

    #[cfg(feature = "runtime")]
    let verify_summary_opt = if options.include_verify_run && tc_result.errors.is_empty() {
        // Verify execution only runs when typecheck is clean — otherwise
        // the compiled VM would crash on missing symbols. Multi-file
        // now works through the same VM path via loaded_modules →
        // compile_program_with_loaded_modules.
        let runnable_items = items.clone();
        let mode = if options.verify_run_hostile {
            crate::verify_law::expand::ExpansionMode::Hostile
        } else {
            crate::verify_law::expand::ExpansionMode::Declared
        };
        let (verify_diags, verify_summary) = if let Some(loaded) = options.loaded_modules.clone() {
            super::verify_run::run_verify_blocks_with_loaded_and_mode(
                runnable_items,
                loaded,
                &options.file_label,
                source,
                mode,
            )
        } else {
            super::verify_run::run_verify_blocks_with_mode(
                runnable_items,
                options.module_base_dir.as_deref(),
                &options.file_label,
                source,
                mode,
            )
        };
        for diag in verify_diags {
            diagnostics.push(diag);
        }
        Some(verify_summary)
    } else {
        None
    };
    #[cfg(not(feature = "runtime"))]
    let verify_summary_opt: Option<super::model::VerifySummary> = None;

    #[cfg(feature = "runtime")]
    if options.include_non_tail_warnings {
        let non_tail =
            collect_non_tail_recursion_warnings_with_sigs(&transformed, &tc_result.fn_sigs);
        for w in &non_tail {
            let mut line_counts: Vec<(usize, usize)> = Vec::new();
            for &ln in &w.callsite_lines {
                if let Some(entry) = line_counts.iter_mut().find(|(l, _)| *l == ln) {
                    entry.1 += 1;
                } else {
                    line_counts.push((ln, 1));
                }
            }
            let max_shown = 3;
            let extra_spans: Vec<FindingSpan> = line_counts
                .iter()
                .take(max_shown)
                .map(|&(ln, count)| {
                    let label = if count > 1 {
                        format!("{} non-tail calls", count)
                    } else {
                        "non-tail call".to_string()
                    };
                    FindingSpan {
                        line: ln,
                        col: 0,
                        len: 0,
                        label,
                    }
                })
                .collect();
            let finding = CheckFinding {
                line: w.line,
                module: None,
                file: None,
                fn_name: Some(w.fn_name.clone()),
                message: w.message.clone(),
                extra_spans,
            };
            diagnostics.push(from_check_finding(
                Severity::Warning,
                &finding,
                source,
                &options.file_label,
            ));
        }
    }

    let mut report = AnalysisReport::with_diagnostics(options.file_label.clone(), diagnostics);
    report.verify_summary = verify_summary_opt;

    if options.include_why_summary {
        report.why_summary = Some(super::why::summarize(
            &items,
            source,
            options.file_label.clone(),
        ));
    }

    if options.include_context_summary {
        let ctx = super::context::build_context_for_items(
            &items,
            source,
            options.file_label.clone(),
            options.module_base_dir.as_deref(),
        );
        report.context_summary = Some(super::context::summarize(&ctx));
    }

    report
}

/// Build a `Diagnostic` for a parser error.
///
/// Parser emits its message as `error[LINE:COL]: <body>` (see
/// `ParseError::Display`). We strip the prefix to rebuild the real
/// span, add a source region anchored on that line, and map common
/// patterns to a repair hint — otherwise the CLI / playground showed
/// parse errors pointing at line 1:1 with no fix suggestion.
fn parse_error_diagnostic(msg: &str, source: &str, file: &str) -> Diagnostic {
    use super::classify::{estimate_span_len, extract_source_lines_range};
    use super::model::{AnnotatedRegion, Underline};
    let (line, col, body) = strip_parse_error_prefix(msg);
    let regions = if line > 0 {
        // Include one line of pre-context so the reader sees the
        // surrounding code, but stop at the target line so the
        // underline renders directly beneath it (tty_render draws
        // the caret after the last line of the region).
        let start = line.saturating_sub(1).max(1);
        let source_lines = extract_source_lines_range(source, start, line);
        if source_lines.is_empty() {
            Vec::new()
        } else {
            // Underline the offending token. Parser emits col =
            // line_len + 1 for errors that fire at the newline
            // (e.g. Unterminated string literal); clamp to the last
            // real char so the caret doesn't float off the end of
            // the line.
            let underline = source.lines().nth(line.saturating_sub(1)).map(|l| {
                let line_chars = l.chars().count();
                let anchor = if col > line_chars && line_chars > 0 {
                    line_chars
                } else {
                    col.max(1)
                };
                Underline {
                    col: anchor,
                    len: estimate_span_len(l, anchor),
                    label: String::new(),
                }
            });
            vec![AnnotatedRegion {
                source_lines,
                underline,
            }]
        }
    } else {
        Vec::new()
    };
    Diagnostic {
        severity: Severity::Error,
        slug: "parse-error",
        summary: body.to_string(),
        span: Span {
            file: file.to_string(),
            line: line.max(1),
            col: col.max(1),
        },
        fn_name: None,
        intent: None,
        fields: Vec::new(),
        conflict: None,
        repair: parse_error_repair(body),
        regions,
        related: Vec::new(),
        from_hostile: false,
    }
}

fn strip_parse_error_prefix(msg: &str) -> (usize, usize, &str) {
    // `error[LINE:COL]: body` — the parser's Display impl (see
    // src/parser/mod.rs). Lexer errors may share the shape.
    let Some(rest) = msg.strip_prefix("error[") else {
        return (0, 0, msg);
    };
    let Some(close) = rest.find("]: ") else {
        return (0, 0, msg);
    };
    let (coord, tail) = rest.split_at(close);
    let body = &tail[3..];
    let Some((line_s, col_s)) = coord.split_once(':') else {
        return (0, 0, body);
    };
    let line = line_s.parse::<usize>().unwrap_or(0);
    let col = col_s.parse::<usize>().unwrap_or(0);
    (line, col, body)
}

fn parse_error_repair(body: &str) -> super::model::Repair {
    // Map common parser messages to a concrete nudge. The parser
    // emits short human strings (`Expected X, found Y`, `Expected '['
    // after '!'`, ...); we pattern-match on the shape so the repair
    // points at a likely fix instead of leaving the user staring at
    // "found EOF".
    use super::model::Repair;
    let hint = if body.contains("after '?'") {
        Some("Description needs a string literal: `? \"what this does\"`")
    } else if body.contains("after 'intent ='") {
        Some(
            "Module intent is a string or an indented block of strings: `intent = \"one line\"` or `intent =\\n    \"line one\"\\n    \"line two\"`",
        )
    } else if body.contains("Expected '[' after '!'") {
        Some("Effects are a bracketed list: `! [Console.print, Random.int]`")
    } else if body.contains("Expected '=>' between key and value in map literal") {
        Some("Map literal uses `=>`: `{\"k\" => 1, \"other\" => 2}`")
    } else if body.contains("Tuple type must have at least 2 elements") {
        Some("Single-element tuples aren't allowed — use the bare type, or add a second element.")
    } else if body.contains("Constructor patterns must be qualified") {
        Some(
            "Qualify variant patterns with the type name: `Shape.Circle(r) ->` not `Circle(r) ->`.",
        )
    } else if body.contains("bind the whole value with a lower-case name") {
        Some(
            "Record patterns don't take positional args — bind the whole record: `match user ... u -> u.name`.",
        )
    } else if body.starts_with("Expected ") && body.contains(", found ") {
        Some(
            "Replace the unexpected token with the expected form; check for a missing keyword, bracket, or separator above.",
        )
    } else if body.contains("must place `module <Name>`") {
        Some("Move `module <Name>` so it's the very first top-level item in the file.")
    } else if body.contains("must declare `module <Name>`") {
        Some("Add `module <Name>` as the first line of the file.")
    } else if body.contains("must contain exactly one module declaration") {
        Some("Keep one `module` per file — split multi-module files into one file each.")
    } else {
        None
    };
    Repair {
        primary: hint.map(String::from),
        ..Repair::default()
    }
}