aura-lang 0.1.1

Aura configuration language: deterministic, capability-secured, schema-validated configs — embeddable library + the `aura` CLI
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Static analysis (SPEC §6.1): a single AST pass with a scope stack
//! mirroring the Environment. Runs before the runtime.
//!
//! Errors (always): E0504 undefined variable, static E0301/E0302.
//! Warnings (promoted to errors by the caller under --strict):
//! W0501 unused variable, W0502 unused import, W0503 unused function/type,
//! W0303 useless shadow, W0512 effectful call in imported module.
//! Under `hermetic`: E0505 for any effectful call at all.

use indexmap::IndexMap;

use crate::error::{Diagnostic, Severity};
use crate::lexer::token::StrPart;
use crate::lexer::Lexer;
use crate::parser::ast::*;
use crate::parser::Parser;
use crate::span::Span;

const BUILTINS: &[&str] = &["env", "read_file", "fail", "range"];
const EFFECTFUL: &[&str] = &["env", "read_file"];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DeclKind {
    Var,
    /// Function/lambda parameters are never considered dead code (the signature may require them).
    Param,
    Import,
    Func,
    Type,
}

struct Decl {
    span: Span,
    used: bool,
    kind: DeclKind,
}

pub struct SemanticAnalyzer<'a> {
    scopes: Vec<IndexMap<&'a str, Decl>>,
    /// Property names (`key:`) per scope, parallel to `scopes`.
    ///
    /// A property is not a binding — that is the language's central rule — so it
    /// never enters `scopes`. But referring to one by name is the mistake that
    /// rule produces, and answering it with a bare "undefined variable" explains
    /// nothing. Collected up front so the hint works regardless of whether the
    /// reference comes before or after the property.
    properties: Vec<Vec<&'a str>>,
    diags: Vec<Diagnostic>,
    is_root: bool,
    /// Deny `env()` and `read_file()` outright, as an analysis error.
    hermetic: bool,
}

/// `is_root = false` — analysis of an imported module (includes W0512).
pub fn analyze<'a>(module: &Module<'a>, is_root: bool) -> Vec<Diagnostic> {
    analyze_with(module, is_root, false)
}

/// As [`analyze`], with `hermetic` denying every effectful call (E0505).
///
/// The denial lives here rather than in the interpreter on purpose: an analysis
/// error is provable without running the manifest, so `aura check --hermetic` can
/// be a CI gate. A runtime refusal would only tell you after the fact, and only
/// for the branch that happened to execute.
pub fn analyze_with<'a>(module: &Module<'a>, is_root: bool, hermetic: bool) -> Vec<Diagnostic> {
    let mut a = SemanticAnalyzer {
        scopes: Vec::new(),
        properties: Vec::new(),
        diags: Vec::new(),
        is_root,
        hermetic,
    };
    a.push_scope();
    for imp in &module.imports {
        a.declare(imp.alias, imp.span, DeclKind::Import, false);
    }
    a.note_properties(&module.stmts);
    for stmt in &module.stmts {
        a.walk_stmt(stmt);
    }
    a.pop_scope();
    a.diags
}

/// Whether there are blocking diagnostics: errors always, warnings too under strict (SPEC §6.1).
pub fn has_blocking(diags: &[Diagnostic], strict: bool) -> bool {
    diags
        .iter()
        .any(|d| strict || d.severity == Severity::Error)
}

impl<'a> SemanticAnalyzer<'a> {
    fn push_scope(&mut self) {
        self.scopes.push(IndexMap::new());
        self.properties.push(Vec::new());
    }

    /// Records the property names a scope declares, before walking it.
    fn note_properties(&mut self, stmts: &[Stmt<'a>]) {
        let names: Vec<&'a str> = stmts
            .iter()
            .filter_map(|st| match st {
                Stmt::Property { key, .. } => Some(*key),
                _ => None,
            })
            .collect();
        if let Some(top) = self.properties.last_mut() {
            top.extend(names);
        }
    }

    fn is_property(&self, name: &str) -> bool {
        self.properties.iter().any(|s| s.contains(&name))
    }

    /// On leaving a scope — report dead code (SPEC §6.1, step 3).
    fn pop_scope(&mut self) {
        self.properties.pop();
        let scope = self.scopes.pop().expect("scope stack underflow");
        for (name, decl) in scope {
            if decl.used {
                continue;
            }
            let (code, what) = match decl.kind {
                DeclKind::Var => ("W0501", "variable"),
                DeclKind::Import => ("W0502", "import"),
                DeclKind::Func => ("W0503", "function"),
                DeclKind::Type => ("W0503", "type"),
                DeclKind::Param => continue,
            };
            self.diags.push(Diagnostic::warning(
                code,
                format!("unused {what} '{name}'"),
                decl.span,
                "never used",
            ));
        }
    }

    fn declare(&mut self, name: &'a str, span: Span, kind: DeclKind, shadow: bool) {
        let in_current = self.scopes.last().is_some_and(|s| s.contains_key(name));
        if in_current {
            self.diags.push(Diagnostic::error(
                "E0301",
                format!("'{name}' is already defined in this scope"),
                span,
                "duplicate definition",
            ));
            return;
        }
        let outer = self.lookup_span(name);
        match (shadow, outer) {
            (false, Some(orig)) if kind == DeclKind::Var => {
                let mut d = Diagnostic::error(
                    "E0302",
                    format!("'{name}' shadows an outer variable"),
                    span,
                    "add `shadow`",
                );
                d.secondary
                    .push((orig, "outer variable declared here".to_string()));
                d.help = Some(format!(
                    "write `shadow {name} = ...` to make the shadowing explicit"
                ));
                self.diags.push(d);
            }
            (true, None) => {
                self.diags.push(Diagnostic::warning(
                    "W0303",
                    format!("`shadow` on '{name}' shadows nothing"),
                    span,
                    "remove `shadow`",
                ));
            }
            _ => {}
        }
        self.scopes.last_mut().unwrap().insert(
            name,
            Decl {
                span,
                used: false,
                kind,
            },
        );
    }

    fn lookup_span(&self, name: &str) -> Option<Span> {
        self.scopes
            .iter()
            .rev()
            .skip(1)
            .find_map(|s| s.get(name).map(|d| d.span))
    }

    /// Step 2 of SPEC §6.1: mark the nearest declaration (respects shadowing).
    fn mark_used(&mut self, name: &str, span: Span) {
        for scope in self.scopes.iter_mut().rev() {
            if let Some(decl) = scope.get_mut(name) {
                decl.used = true;
                return;
            }
        }
        if !BUILTINS.contains(&name) {
            let mut d = Diagnostic::error(
                "E0504",
                format!("use of undefined variable '{name}'"),
                span,
                "not found in any scope",
            );
            if self.is_property(name) {
                d.help = Some(format!(
                    "'{name}' is a property (`{name}:`), which is exported but does not create a name — bind the value with `{name} = ...` first and give the property that binding"
                ));
            }
            self.diags.push(d);
        }
    }

    /// A schema field's type: `mark_used`, but the diagnostic talks about types.
    ///
    /// Reported generically, an unknown one reads `use of undefined variable
    /// 'Str'` — which never mentions types, and is what an assistant hit after
    /// the reference wrongly listed `Str` as a built-in. The name is legitimately
    /// unresolved either way; only the wording differs, and here the wording is
    /// the whole difference between a two-second fix and a puzzle.
    fn mark_used_as_type(&mut self, name: &str, span: Span) {
        for scope in self.scopes.iter_mut().rev() {
            if let Some(decl) = scope.get_mut(name) {
                decl.used = true;
                return;
            }
        }
        let mut d = Diagnostic::error(
            "E0504",
            format!("unknown type '{name}'"),
            span,
            "no such type is declared, and it is not built in",
        );
        let builtins = crate::parser::ast::BUILTIN_TYPE_NAMES;
        // Edit distance alone misses this case: `Str` against `String` is three
        // insertions, well past the typo threshold, yet it is exactly the
        // mistake people make — an abbreviation of the real name. Try a prefix
        // relation first, then fall back to the usual nearest-neighbour.
        let suggestion = builtins
            .iter()
            .find(|b| b.starts_with(name) || name.starts_with(**b))
            .copied()
            .or_else(|| crate::eval::nearest(builtins, name));
        let list = builtins.join(", ");
        d.help = Some(match suggestion {
            Some(closest) => format!(
                "did you mean `{closest}`? The built-in types are {list}; anything else has to be declared with `type {name} … end` or `enum {name} … end`"
            ),
            None => format!(
                "the built-in types are {list}; anything else has to be declared with `type {name} … end` or `enum {name} … end`"
            ),
        });
        self.diags.push(d);
    }

    fn walk_stmt(&mut self, stmt: &Stmt<'a>) {
        match stmt {
            Stmt::Assign {
                name,
                shadow,
                value,
                span,
            } => {
                self.walk_expr(value); // the value does not see its own name
                self.declare(name, *span, DeclKind::Var, *shadow);
            }
            Stmt::Property { value, .. } => self.walk_expr(value),
            Stmt::Assert { cond, message, .. } => {
                self.walk_expr(cond);
                if let Some(m) = message {
                    self.walk_expr(m);
                }
            }
            Stmt::EnumDecl(en) => {
                self.declare(en.name, en.span, DeclKind::Type, false);
                // D12: pub is the module's API, not dead code
                if en.public {
                    self.mark_used(en.name, en.span);
                }
            }
            Stmt::TypeDecl(schema) => {
                for f in &schema.fields {
                    if let TypeName::Custom(name) = f.ty {
                        self.mark_used_as_type(name, f.ty_span);
                    }
                    // a default expression may reference variables (e.g. `= base_port`)
                    if let Some(default) = &f.default {
                        self.walk_expr(default);
                    }
                }
                self.declare(schema.name, schema.span, DeclKind::Type, false);
                // D12: pub is the module's API, not dead code
                if schema.public {
                    self.mark_used(schema.name, schema.span);
                }
            }
            Stmt::FuncDecl {
                name,
                params,
                body,
                public,
                span,
            } => {
                self.declare(name, *span, DeclKind::Func, false);
                // D12: pub is the module's API, not dead code
                if *public {
                    self.mark_used(name, *span);
                }
                self.push_scope();
                for p in params {
                    self.declare(p, *span, DeclKind::Param, false);
                }
                self.walk_stmt_body(body);
                self.pop_scope();
            }
            Stmt::Block(block) => self.walk_block(block),
            Stmt::Expr(e) => self.walk_expr(e),
        }
    }

    fn walk_block(&mut self, block: &BlockDeclaration<'a>) {
        self.walk_expr(&block.label);
        self.push_scope();
        self.note_properties(&block.body);
        for stmt in &block.body {
            self.walk_stmt(stmt);
        }
        self.pop_scope();
    }

    /// A code body (D17): statements in the caller's freshly pushed scope.
    fn walk_stmt_body(&mut self, body: &[Stmt<'a>]) {
        self.note_properties(body);
        for stmt in body {
            self.walk_stmt(stmt);
        }
    }

    fn walk_object_body(&mut self, body: &ObjectBody<'a>) {
        for (_, value, _) in &body.props {
            self.walk_expr(value);
        }
    }

    fn walk_expr(&mut self, e: &Expr<'a>) {
        match e {
            Expr::Literal(LitValue::InterpStr(parts), span) => {
                for part in parts {
                    if let StrPart::Interp(src) = part {
                        self.walk_interp(src, *span);
                    }
                }
            }
            Expr::Literal(..) => {}
            Expr::Variable(name, span) => self.mark_used(name, *span),
            Expr::Unary { rhs, .. } => self.walk_expr(rhs),
            Expr::Binary { lhs, rhs, .. } => {
                self.walk_expr(lhs);
                self.walk_expr(rhs);
            }
            Expr::Ternary {
                cond,
                then,
                otherwise,
                ..
            } => {
                self.walk_expr(cond);
                self.walk_expr(then);
                self.walk_expr(otherwise);
            }
            Expr::Cond {
                arms, otherwise, ..
            } => {
                for (condition, value) in arms {
                    self.walk_expr(condition);
                    self.walk_expr(value);
                }
                self.walk_expr(otherwise);
            }
            Expr::Call { callee, args, span } => {
                // W0512: an effectful call in an imported module (SPEC §6.1, D1)
                if let Expr::Variable(name, _) = callee.as_ref() {
                    // Hermetic mode: no I/O anywhere, root included. This is the
                    // guarantee CUE, KCL and Starlark give by construction; here it
                    // is a mode, so one repository can hold both kinds of manifest
                    // and CI can require the strict kind per directory.
                    if self.hermetic && EFFECTFUL.contains(name) {
                        let mut d = Diagnostic::error(
                            "E0505",
                            format!("{name}() is not allowed in hermetic mode"),
                            *span,
                            "no I/O is permitted here",
                        );
                        d.help = Some(format!(
                            "pass the value in from the host, or drop --hermetic to grant {name}() explicitly"
                        ));
                        self.diags.push(d);
                    }
                    if !self.is_root && EFFECTFUL.contains(name) {
                        self.diags.push(Diagnostic::warning(
                            "W0512",
                            format!("effectful call {name}() in imported module"),
                            *span,
                            "imports have no I/O capability by default",
                        ));
                    }
                }
                self.walk_expr(callee);
                for a in args {
                    self.walk_expr(a);
                }
            }
            Expr::MethodCall {
                recv, args, lambda, ..
            } => {
                self.walk_expr(recv);
                for a in args {
                    self.walk_expr(a);
                }
                if let Some(l) = lambda {
                    self.walk_expr(l);
                }
            }
            Expr::FieldAccess { recv, .. } => self.walk_expr(recv),
            Expr::Index { recv, key, .. } => {
                self.walk_expr(recv);
                self.walk_expr(key);
            }
            Expr::ObjectLiteral(body) => self.walk_object_body(body),
            Expr::ListLiteral(items, _) => {
                for i in items {
                    self.walk_expr(i);
                }
            }
            Expr::Lambda { params, body, span } => {
                self.push_scope();
                for p in params {
                    self.declare(p, *span, DeclKind::Param, false);
                }
                match body {
                    LambdaBody::Expr(e) => self.walk_expr(e),
                    LambdaBody::Block(b) => self.walk_stmt_body(b),
                }
                self.pop_scope();
            }
            Expr::SchemaInstance {
                schema,
                schema_alias,
                body,
                span,
            } => {
                // `new alias.Schema` uses the import alias; the schema itself lives in another module
                match schema_alias {
                    Some(alias) => self.mark_used(alias, *span),
                    None => self.mark_used(schema, *span),
                }
                self.walk_object_body(body);
            }
        }
    }

    /// `#{expr}` is parsed and analyzed as an ordinary expression — variables
    /// used only inside an interpolation are not considered dead.
    fn walk_interp(&mut self, src: &'a str, span: Span) {
        let parsed = Lexer::new(src, span.source)
            .tokenize()
            .and_then(|toks| Parser::new(toks).parse_expression());
        match parsed {
            Ok(expr) => self.walk_expr(&expr),
            Err(d) => self.diags.push(Diagnostic::error(
                "E0316",
                format!("invalid interpolation: {}", d.message),
                span,
                "in #{...}",
            )),
        }
    }
}

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

    fn diags(src: &str) -> Vec<Diagnostic> {
        diags_as(src, true)
    }

    fn diags_as(src: &str, is_root: bool) -> Vec<Diagnostic> {
        let toks = Lexer::new(src, 0).tokenize().expect("lex ok");
        let module = Parser::new(toks).parse_module().expect("parse ok");
        analyze(&module, is_root)
    }

    fn codes(src: &str) -> Vec<&'static str> {
        diags(src).into_iter().map(|d| d.code).collect()
    }

    /// An unknown schema-field type used to be reported as an undefined
    /// *variable*, which never mentioned types and sent people looking for a
    /// missing `=` binding. It also pointed at the whole `type` block rather than
    /// the field.
    #[test]
    fn an_unknown_field_type_says_so_and_points_at_the_field() {
        let ds = diags(
            "type T
  a: Str
  b: Int
end

x: new T
  a: \"v\"
  b: 1
end
",
        );
        let d = ds
            .iter()
            .find(|d| d.code == "E0504")
            .expect("an unknown type is still E0504");
        assert!(
            d.message.contains("unknown type 'Str'"),
            "expected a message about types, got: {}",
            d.message
        );
        let help = d.help.as_deref().unwrap_or_default();
        assert!(
            help.contains("did you mean `String`"),
            "an abbreviation of a built-in should be suggested; got: {help}"
        );
        // The arrow belongs on the field, not on `type T`.
        assert!(
            d.primary.0.start > 0,
            "the diagnostic should point at the type name, not the block start"
        );
    }

    /// Edit distance still applies for ordinary typos, and a name that resembles
    /// nothing gets the list without a misleading guess.
    #[test]
    fn a_typo_is_suggested_and_an_unrelated_name_is_not() {
        let typo = diags(
            "type T
  a: Intt
end
",
        );
        let help = typo
            .iter()
            .find(|d| d.code == "E0504")
            .and_then(|d| d.help.clone())
            .unwrap_or_default();
        assert!(help.contains("did you mean `Int`"), "got: {help}");

        let unrelated = diags(
            "type T
  a: Widget
end
",
        );
        let help = unrelated
            .iter()
            .find(|d| d.code == "E0504")
            .and_then(|d| d.help.clone())
            .unwrap_or_default();
        assert!(
            !help.contains("did you mean"),
            "an unrelated name should not be guessed at; got: {help}"
        );
        assert!(
            help.contains("String, Int"),
            "the list is still useful: {help}"
        );
    }

    /// Referring to a property by name is the mistake the `:`/`=` rule produces,
    /// and "undefined variable" explains none of it. The hint fires whichever
    /// order the two appear in, which is why the names are collected up front.
    #[test]
    fn referring_to_a_property_explains_the_rule() {
        for src in [
            "limits:
  a: 1
end

assert limits.a == 1, \"x\"
",
            "assert limits.a == 1, \"x\"

limits:
  a: 1
end
",
        ] {
            let help = diags(src)
                .iter()
                .find(|d| d.code == "E0504")
                .and_then(|d| d.help.clone())
                .unwrap_or_default();
            assert!(
                help.contains("is a property") && help.contains("does not create a name"),
                "expected the property hint for {src:?}, got: {help:?}"
            );
        }
    }

    /// And an ordinary undefined name gets no such hint, which would be a
    /// confident wrong explanation.
    #[test]
    fn an_ordinary_undefined_name_gets_no_property_hint() {
        let d = diags(
            "x: nope + 1
",
        );
        let hint = d
            .iter()
            .find(|d| d.code == "E0504")
            .and_then(|d| d.help.clone());
        assert!(hint.is_none(), "unexpected hint: {hint:?}");
    }

    #[test]
    fn dead_code_detection() {
        assert_eq!(codes("x = 1"), vec!["W0501"]);
        assert_eq!(
            codes("import \"a.aura\" as a\nx = 1\ny = x"),
            vec!["W0502", "W0501"]
        ); // a, y
        assert_eq!(codes("type T\n  a: Int\nend"), vec!["W0503"]);
        assert_eq!(codes("def f(x)\n  a: x\nend"), vec!["W0503"]);
        // used — not dead
        assert!(codes("x = 1\ny = x + 1\nassert y > 0").is_empty());
    }

    #[test]
    fn undefined_variable_is_e0504() {
        assert!(codes("x = nope + 1").contains(&"E0504"));
        // builtins are never considered undefined
        assert!(!codes("assert fail == fail").contains(&"E0504"));
    }

    #[test]
    fn static_shadow_rules() {
        assert!(codes("x = 1\ndomain \"d\"\n  x = 2\nend").contains(&"E0302"));
        assert!(codes("x = 1\nx = 2").contains(&"E0301"));
        assert!(codes("shadow x = 1\nassert x == 1").contains(&"W0303"));
        // a correct shadow — clean
        let src = "x = 1\ndomain \"d\"\n  shadow x = 2\n  assert x == 2\nend\nassert x == 1";
        assert!(codes(src).is_empty());
    }

    #[test]
    fn interpolation_uses_are_counted() {
        // x is used only inside #{} — not dead
        assert!(codes("x = 1\ns = \"v#{x}\"\nassert s == \"v1\"").is_empty());
        // an undefined variable inside #{} is caught
        assert!(codes("s = \"v#{nope}\"\nassert s == \"\"").contains(&"E0504"));
    }

    #[test]
    fn effectful_call_in_import_is_w0512() {
        let src = "x = env(\"A\", \"b\")\nassert x == x";
        assert!(!diags_as(src, true).iter().any(|d| d.code == "W0512"));
        assert!(diags_as(src, false).iter().any(|d| d.code == "W0512"));
    }

    #[test]
    fn strict_upgrades_warnings_to_blocking() {
        let ds = diags("x = 1");
        assert!(!has_blocking(&ds, false));
        assert!(has_blocking(&ds, true));
    }
}