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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! 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,
//! W0513 a nullable field fed by a fallback-less `get`/`env` (D27).
//! 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,
/// Nullable field names per locally declared schema (D27), collected up
/// front so a `new` before the `type` still sees them.
///
/// Only local schemas: `new pkg.Schema` lives in another module and this
/// pass cannot see its fields. Saying nothing there is the honest outcome.
nullable_fields: IndexMap<&'a str, Vec<&'a str>>,
}
/// `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,
nullable_fields: IndexMap::new(),
};
a.note_schemas(&module.stmts);
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);
}
}
/// Collect the nullable fields of every schema declared anywhere in the
/// module, including inside `domain` blocks, before walking anything.
fn note_schemas(&mut self, stmts: &[Stmt<'a>]) {
for st in stmts {
match st {
Stmt::TypeDecl(s) => {
self.check_defaults(s);
let nullable: Vec<&'a str> = s
.fields
.iter()
.filter(|f| f.nullable)
.map(|f| f.name)
.collect();
if !nullable.is_empty() {
self.nullable_fields.insert(s.name, nullable);
}
}
Stmt::Block(b) => self.note_schemas(&b.body),
_ => {}
}
}
}
/// E0516: a default that its own field can never accept.
///
/// `q: Int = "not an int"` used to reach `check --strict` unremarked; the
/// only complaint was that the type went unused. The mismatch surfaced at
/// `new`, and a field that callers always supply explicitly never reaches
/// `new` with its default at all — so a schema could carry a value that
/// cannot be valid, indefinitely, and the declaration went on claiming
/// otherwise.
///
/// Only literals are judged. A default may be any expression, and what an
/// arbitrary one evaluates to is not knowable here; reporting on a guess
/// would cost more than the check is worth. A literal is the case that
/// actually occurs, and it is decidable.
fn check_defaults(&mut self, s: &SchemaDeclaration<'a>) {
for f in &s.fields {
let Some(default) = &f.default else { continue };
let Some((found, span)) = literal_shape(default) else {
continue;
};
// `= null` is the one mismatch that has a remedy in the declaration
// rather than in the value, so it is worth saying separately.
if found == "Null" {
if !f.nullable {
let mut d = Diagnostic::error(
"E0516",
format!(
"the default for '{}' is null, which schema {} does not admit",
f.name, s.name
),
span,
"this default",
);
// The marker alone is not the remedy: `q: Int?` with no
// default still requires the field at `new`. Keeping the
// default is what makes the field optional *and* null.
d.help = Some(format!(
"keep the default and admit null: {}: {}? = null",
f.name,
type_name_label(&f.ty)
));
self.diags.push(d);
}
continue;
}
// A custom type is an enum or another schema, and which one is not
// settled here — so it is left to `new`, which knows.
if matches!(f.ty, TypeName::Custom(_)) {
continue;
}
let declared = type_name_label(&f.ty);
if !literal_fits(&f.ty, found) {
let mut d = Diagnostic::error(
"E0516",
format!(
"the default for '{}' is {found}, but schema {} declares it {declared}",
f.name, s.name
),
span,
"this default",
);
// Int and Float are distinct (D6), and that is the mismatch a
// reader is most likely to think is a formality.
d.help = Some(if declared == "Float" && found == "Int" {
format!("Float and Int are different types: {}: Float = 1.0", f.name)
} else {
format!("write the default as {declared}, or declare the field {found}")
});
self.diags.push(d);
}
}
}
/// W0513: a nullable field fed by something that turns "absent" into `null`
/// without saying so.
///
/// The combination matters because of what it costs: with the field not
/// nullable, a missing key is `E0512` and the run stops, so two people with
/// different input files find out. Make the field nullable and the same
/// difference passes silently, and they ship different configurations. The
/// warning does not forbid it — an explicit fallback says which value stands
/// for absence, and that is all it asks for.
fn check_silent_nulls(&mut self, schema: &'a str, body: &ObjectBody<'a>) {
let Some(nullable) = self.nullable_fields.get(schema).cloned() else {
return;
};
for (key, value, span) in &body.props {
if !nullable.contains(key) {
continue;
}
let Some(kind) = Self::silent_null_source(value) else {
continue;
};
let (shown, fix) = match kind {
"get" => ("get(key)", "get(key, fallback)"),
_ => ("env(name)", "env(name, fallback)"),
};
let mut d = Diagnostic::warning(
"W0513",
format!(
"'{key}' is nullable and is filled from `{shown}`, so a missing \
value becomes null instead of an error"
),
*span,
"absence would pass unnoticed here",
);
d.help = Some(format!(
"name the value that stands for absence: `{fix}` — or drop the `?` \
so a missing one is reported"
));
self.diags.push(d);
}
}
/// An expression that yields `null` when something is simply absent, without
/// the author having written `null` anywhere.
///
/// `xs.get(k)` and `env(name)` both do this when given no fallback. Feeding
/// one into a nullable field is the single way a manifest can quietly
/// produce a different configuration for two people: before D27 the missing
/// value was `E0512` and the run stopped.
fn silent_null_source(e: &Expr<'a>) -> Option<&'static str> {
match e {
Expr::MethodCall { method, args, .. } if *method == "get" && args.len() == 1 => {
Some("get")
}
Expr::Call { callee, args, .. } if args.len() == 1 => match callee.as_ref() {
Expr::Variable(name, _) if *name == "env" => Some("env"),
_ => None,
},
_ => None,
}
}
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 Some(name) = f.ty.custom_name() {
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),
}
if schema_alias.is_none() {
self.check_silent_nulls(schema, body);
}
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::*;
pub(super) fn diags(src: &str) -> Vec<Diagnostic> {
diags_as(src, true)
}
#[test]
fn a_nullable_field_fed_without_a_fallback_is_w0513() {
// The one way D27 lets a manifest quietly differ between two people:
// with the field not nullable, a missing key stops the run; make it
// nullable and the same difference passes as null.
let src = concat!(
"type Plan\n quota: Int?\n region: String?\n fixed: Int?\nend\n",
"data = read_file(\"d.json\").parse_json()\n",
"p: new Plan\n",
" quota: data.get(\"quota\")\n",
" region: env(\"REGION\")\n",
" fixed: data.get(\"fixed\", 0)\n",
"end\n",
);
let d = diags(src);
let warned: Vec<&str> = d
.iter()
.filter(|x| x.code == "W0513")
.map(|x| x.message.as_str())
.collect();
assert_eq!(
warned.len(),
2,
"expected quota and region only: {warned:?}"
);
assert!(warned.iter().any(|m| m.contains("quota")), "{warned:?}");
assert!(warned.iter().any(|m| m.contains("region")), "{warned:?}");
// An explicit fallback is the whole point and must not be nagged at.
assert!(
!warned.iter().any(|m| m.contains("fixed")),
"a named fallback is the fix, not the problem: {warned:?}"
);
// And the warning has to show what to type.
let first = d.iter().find(|x| x.code == "W0513").unwrap();
let help = first.help.clone().unwrap_or_default();
assert!(help.contains("fallback"), "{help}");
}
#[test]
fn a_field_without_the_marker_is_not_warned_about() {
// Without `?` a missing key is already E0512 at runtime - loud, and
// nothing to warn about. Warning here would be noise on correct code.
let d = diags(concat!(
"type P\n q: Int\nend\n",
"data = read_file(\"d.json\").parse_json()\n",
"p: new P\n q: data.get(\"q\")\nend\n",
));
assert!(
!d.iter().any(|x| x.code == "W0513"),
"{:?}",
d.iter().map(|x| &x.message).collect::<Vec<_>>()
);
}
#[test]
fn a_schema_used_as_an_element_type_is_not_dead_code() {
// The sharpest symptom of the old gap: under --strict the compiler
// called Endpoint dead while letting rubbish into the field it was
// meant to describe. Both halves were wrong; this is the first.
let d = diags(concat!(
"type Endpoint
path: String
end
",
"type Service
endpoints: [Endpoint]
end
",
"pub def use_it()
n: 1
end
",
));
assert!(
!d.iter().any(|x| x.message.contains("Endpoint")),
"Endpoint reported as unused: {:?}",
d.iter().map(|x| &x.message).collect::<Vec<_>>()
);
}
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)
}
pub(super) 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));
}
}
/// The kind of a literal default, or `None` when the expression is anything
/// else — a call, a variable, arithmetic — whose value is not knowable here.
fn literal_shape(e: &Expr<'_>) -> Option<(&'static str, Span)> {
match e {
Expr::Literal(v, span) => Some((
match v {
LitValue::Int(_) => "Int",
LitValue::Float(_) => "Float",
LitValue::Str(_) | LitValue::InterpStr(_) => "String",
LitValue::Bool(_) => "Bool",
LitValue::Null => "Null",
},
*span,
)),
Expr::ListLiteral(_, span) => Some(("List", *span)),
// `-1` is an Int written with a sign, and reporting it as "not a
// literal" would let `port: String = -1` through.
Expr::Unary {
op: UnaryOp::Neg,
rhs,
..
} => literal_shape(rhs),
_ => None,
}
}
/// Whether a literal of `found` may stand as a default for a field declared
/// `ty`. Mirrors the check `new` performs, so the two cannot disagree about
/// what counts as a mismatch.
fn literal_fits(ty: &TypeName<'_>, found: &str) -> bool {
match ty {
TypeName::String => found == "String",
TypeName::Int => found == "Int",
TypeName::Float => found == "Float",
TypeName::Bool => found == "Bool",
TypeName::List(_) => found == "List",
// An object literal is not an expression, so nothing reaches here that
// could be judged; `new` sees the value and decides.
TypeName::Object | TypeName::Custom(_) => true,
}
}
/// A declared type as the author wrote it, for a message that quotes them back.
fn type_name_label(ty: &TypeName<'_>) -> String {
match ty {
TypeName::String => "String".into(),
TypeName::Int => "Int".into(),
TypeName::Float => "Float".into(),
TypeName::Bool => "Bool".into(),
TypeName::Object => "Object".into(),
TypeName::Custom(n) => (*n).to_string(),
TypeName::List(None) => "List".into(),
TypeName::List(Some(el)) => format!("[{}]", type_name_label(el)),
}
}
#[cfg(test)]
mod default_value_tests {
use super::tests::{codes, diags};
/// The declaration is where a bad default is decidable, and it was not being
/// decided: `q: Int = "not an int"` passed `check --strict` with nothing to
/// say but that the type was unused. The mismatch waited for `new`, and a
/// field callers always supply explicitly never reaches `new` with its
/// default — so the schema could carry an impossible value indefinitely.
#[test]
fn a_default_the_field_cannot_accept_is_e0516() {
for src in [
"type S\n q: Int = \"not an int\"\nend\nx: 1",
"type S\n q: String = 7\nend\nx: 1",
"type S\n q: Bool = 1\nend\nx: 1",
"type S\n q: Float = 1\nend\nx: 1",
"type S\n q: [Int] = 3\nend\nx: 1",
// A signed number is still a number: reading `-1` as "not a literal"
// would let this through.
"type S\n q: String = -1\nend\nx: 1",
] {
assert!(codes(src).contains(&"E0516"), "no E0516 for: {src}");
}
}
/// `= null` has its own message, because the remedy is in the declaration —
/// mark the field nullable — rather than in the value.
#[test]
fn a_null_default_names_the_nullable_marker() {
let ds = diags("type S\n q: Int = null\nend\nx: 1");
let d = ds.iter().find(|d| d.code == "E0516").expect("E0516");
assert!(d.message.contains("null"), "{}", d.message);
assert!(
d.help
.as_deref()
.unwrap_or_default()
.contains("q: Int? = null"),
"the marker alone still requires the field at `new`: {:?}",
d.help
);
}
/// Every remedy E0516 prints, run.
///
/// The first draft advised `q: Int?` for a null default, which does not
/// work: the marker alone still requires the field at `new`, so following
/// the advice exchanged one error for another. A help line is a promise
/// about code, and the only way to keep it is to execute it.
#[test]
fn the_e0516_remedies_actually_evaluate() {
use crate::facade::{eval_source, EvalOptions};
let src = concat!(
"type A
",
" q: Int? = null
", // the null remedy
"end
",
"type B
",
" ratio: Float = 1.0
", // the Int-for-Float remedy
"end
",
"type C
",
" q: String = \"7\"
", // the general remedy: write it as declared
"end
",
"a: new A
end
",
"b: new B
end
",
"c: new C
end
",
);
let files = std::collections::HashMap::from([("r.aura".to_string(), src.to_string())]);
let out = eval_source(files, "r.aura", &EvalOptions::default())
.expect("every remedy must evaluate");
assert_eq!(out.json["a"]["q"], serde_json::Value::Null);
assert_eq!(out.json["b"]["ratio"], 1.0);
assert_eq!(out.json["c"]["q"], "7");
}
/// Nothing that was already valid may start failing.
#[test]
fn a_default_that_fits_is_silent() {
let src = concat!(
"type S\n",
" a: Int = 2\n",
" b: Float = 1.5\n",
" c: String = \"x\"\n",
" d: Bool = true\n",
" e: [Int] = []\n",
// D27: the marker is what makes null admissible.
" f: Int? = null\n",
" g: String = \"v#{1}\"\n",
"end\n",
"x: 1\n",
);
assert!(!codes(src).contains(&"E0516"), "{:?}", codes(src));
}
/// A default may be any expression, and what an arbitrary one evaluates to
/// is not knowable here. Reporting on a guess would cost more than the check
/// is worth, so only literals are judged — and `new` still checks the rest.
#[test]
fn a_computed_default_is_left_to_new() {
let src = "base = 2\ntype S\n q: String = base + 1\nend\nx: 1";
assert!(!codes(src).contains(&"E0516"), "{:?}", codes(src));
}
/// A custom type is an enum or another schema, and which one is not settled
/// at this point, so the judgement belongs to `new`.
#[test]
fn a_custom_typed_field_is_left_to_new() {
let src = "enum T\n \"a\"\nend\ntype S\n t: T = \"a\"\nend\nx: 1";
assert!(!codes(src).contains(&"E0516"), "{:?}", codes(src));
}
}