rils_frontend 0.1.0

Syntax and type model for the Rils scripting language
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
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
use super::*;

#[test]
fn resolves_local_definitions_and_references() {
    let source = "let value = 42; value";
    let analysis = analyze(source).unwrap();
    assert!(analysis.diagnostics.is_empty());
    let reference = analysis
        .symbols
        .iter()
        .find(|symbol| !symbol.is_definition && symbol.name == "value")
        .unwrap();
    assert_eq!(reference.definition_span, Some(Span::new(4, 9)));
}

#[test]
fn reports_undefined_names_without_executing() {
    let analysis = analyze("if false { missing }").unwrap();
    assert_eq!(analysis.diagnostics.len(), 1);
    assert!(analysis.diagnostics[0].message.contains("missing"));
}

#[test]
fn pattern_bindings_are_scoped() {
    let analysis = analyze("match Some(1) { Some(value) => value, None => 0 }; value").unwrap();
    assert_eq!(analysis.diagnostics.len(), 1);
    assert!(analysis.diagnostics[0].message.contains("undefined"));
}

#[test]
fn analyzes_builtin_result_patterns_and_try_expressions() {
    let source = r#"
            fn source() -> Result<int, string> { Ok(42) }
            fn forward() -> Result<int, string> {
                let value = source()?;
                Ok(value)
            }
            match forward() { Ok(value) => value, Err(_) => 0 }
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn analyzes_standard_io_and_fs_paths() {
    let source = r#"
            fn load(path: string) -> Result<string, std::io::Error> {
                std::fs::read_to_string(path)
            }
            let loaded = std::fs::read_to_string("missing.txt");
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
    assert!(analysis.inlay_hints.iter().any(|hint| {
        &source[hint.span.start..hint.span.end] == "loaded"
            && hint.label == ": Result<string, std::io::Error>"
    }));
}

#[test]
fn annotated_types_resolve_to_their_declarations() {
    let source = "struct Point { x: int }\nfn keep(value: Point) -> Point { value }\nlet p: Point = Point { x: 1 };";
    let analysis = analyze(source).unwrap();
    assert!(analysis.diagnostics.is_empty());
    let definition = analysis
        .symbols
        .iter()
        .find(|symbol| symbol.is_definition && symbol.name == "Point")
        .unwrap()
        .span;
    let references = analysis
        .symbols
        .iter()
        .filter(|symbol| !symbol.is_definition && symbol.name == "Point")
        .collect::<Vec<_>>();
    assert_eq!(references.len(), 4);
    assert!(
        references
            .iter()
            .all(|reference| reference.definition_span == Some(definition))
    );
}

#[test]
fn resolves_ufcs_methods_and_place_expressions() {
    let source = r#"
            trait Value { fn value(&self) -> int; }
            struct Number { inner: int }
            impl Value for Number { fn value(&self) -> int { self.inner } }

            let mut number = Number { inner: 1 };
            number.inner = 42;
            let index = 0;
            number[index];
            Value::value(&number);
            <Number as Value>::value(&number);
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );

    let definition = analysis
        .symbols
        .iter()
        .find(|symbol| {
            symbol.is_definition && symbol.kind == SymbolKind::Method && symbol.name == "value"
        })
        .expect("trait method definition");
    let ufcs_references = analysis
        .symbols
        .iter()
        .filter(|symbol| {
            !symbol.is_definition
                && symbol.kind == SymbolKind::Method
                && symbol.name == "value"
                && symbol.definition_span == Some(definition.span)
        })
        .count();
    assert_eq!(ufcs_references, 2);

    assert!(
        analysis
            .symbols
            .iter()
            .any(|symbol| !symbol.is_definition && symbol.name == "index")
    );
}

#[test]
fn classifies_called_members_as_methods_and_other_members_as_fields() {
    let source = r#"
            struct Factory { value: int }
            impl Factory {
                fn make(&self) -> int { self.value }
            }
            let factory = Factory { value: 42 };
            factory.make();
            factory.value;
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );

    assert!(analysis.symbols.iter().any(|symbol| {
        !symbol.is_definition && symbol.name == "make" && symbol.kind == SymbolKind::Method
    }));
    assert!(analysis.symbols.iter().any(|symbol| {
        !symbol.is_definition && symbol.name == "value" && symbol.kind == SymbolKind::Field
    }));
}

#[test]
fn describes_type_aliases_with_recursively_expanded_targets() {
    let source = r#"
            struct Box<T> { value: T }
            type ValueBox<T> = Box<T>;
            type IntBox = ValueBox<int>;
            fn consume(value: IntBox) {}
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );

    for expected in [
        "type ValueBox<T> = Box<T>",
        "type ValueBox<int> = Box<int>",
        "type IntBox = Box<int>",
    ] {
        assert!(
            analysis
                .symbols
                .iter()
                .any(|symbol| symbol.detail.as_deref() == Some(expected)),
            "missing {expected:?}: {:?}",
            analysis.symbols
        );
    }
}

#[test]
fn infers_function_let_and_pattern_binding_types() {
    let source = "
            fn answer() { 42 }
            fn identity<T>(input: T) { input }
            fn make_getter() {
                fn get() { 42 }
                get
            }
            let result = answer();
            let copied = identity(result);
            let getter = make_getter();
            let nested = getter();
            let maybe = Some(result);
            match maybe { Some(value) => value, None => 0 }
            struct Point { x: int }
            let point = Point { x: 1 };
            match point { Point { x } => x }
        ";
    let analysis = analyze(source).unwrap();
    for expected in [": int", ": Option<int>", " -> int"] {
        assert!(
            analysis
                .inlay_hints
                .iter()
                .any(|hint| hint.label == expected),
            "missing hint {expected:?}: {:?}",
            analysis.inlay_hints
        );
    }
    let answer = analysis
        .symbols
        .iter()
        .find(|symbol| symbol.is_definition && symbol.name == "answer")
        .unwrap();
    assert_eq!(
        answer.inferred_type,
        Some(Type::function(Vec::new(), Type::Int))
    );
    let copied = analysis
        .symbols
        .iter()
        .find(|symbol| symbol.is_definition && symbol.name == "copied")
        .unwrap();
    assert_eq!(copied.inferred_type, Some(Type::Int));
    let getter = analysis
        .symbols
        .iter()
        .find(|symbol| symbol.is_definition && symbol.name == "getter")
        .unwrap();
    assert_eq!(
        getter.inferred_type,
        Some(Type::function(Vec::new(), Type::Int))
    );
    let nested = analysis
        .symbols
        .iter()
        .find(|symbol| symbol.is_definition && symbol.name == "nested")
        .unwrap();
    assert_eq!(nested.inferred_type, Some(Type::Int));
    assert!(
        analysis.inlay_hints.iter().any(|hint| {
            &source[hint.span.start..hint.span.end] == "x" && hint.label == ": int"
        })
    );
}

#[test]
fn resolves_macro_definitions_and_invocations() {
    let source = "macro twice($value) { $value + $value } twice!(21)";
    let analysis = analyze(source).unwrap();
    let definition = analysis
        .symbols
        .iter()
        .find(|symbol| symbol.is_definition && symbol.kind == SymbolKind::Macro)
        .unwrap();
    let reference = analysis
        .symbols
        .iter()
        .find(|symbol| !symbol.is_definition && symbol.kind == SymbolKind::Macro)
        .unwrap();
    assert_eq!(reference.definition_span, Some(definition.span));
}

#[test]
fn analyzes_modules_imports_and_builtin_namespaces() {
    let source = r#"
            mod math { pub fn answer() -> int { 42 } }
            use math::answer;
            let value = answer();
            std::io::println(value);
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
    assert!(analysis.symbols.iter().any(|symbol| {
        symbol.is_definition && symbol.name == "math" && symbol.kind == SymbolKind::Module
    }));
    assert!(
        analysis
            .symbols
            .iter()
            .any(|symbol| { symbol.is_definition && symbol.name == "answer" })
    );
}

#[test]
fn reports_non_exhaustive_builtin_and_enum_matches() {
    let source = r#"
            enum State { Ready, Waiting(int), Failed { code: int } }
            let state = State::Ready;
            match state { State::Ready => 1, State::Waiting(_) => 2 };
            match Some(1) { Some(value) => value };
            match true { true => 1 };
        "#;
    let analysis = analyze(source).unwrap();
    let messages = analysis
        .diagnostics
        .iter()
        .map(|diagnostic| diagnostic.message.as_str())
        .collect::<Vec<_>>();
    assert!(messages.iter().any(|message| message.contains("Failed")));
    assert!(messages.iter().any(|message| message.contains("None")));
    assert!(messages.iter().any(|message| message.contains("false")));
}

#[test]
fn accepts_exhaustive_matches_and_reports_unreachable_arms() {
    let source = r#"
            match Some(1) {
                Some(value) => value,
                None => 0,
                _ => -1,
                Some(_) => -2,
            };
        "#;
    let analysis = analyze(source).unwrap();
    let unreachable = analysis
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.message == "unreachable match arm")
        .count();
    assert_eq!(unreachable, 2, "{:?}", analysis.diagnostics);
    assert!(
        !analysis
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.message.contains("non-exhaustive"))
    );
}

#[test]
fn reports_missing_return_paths_and_unreachable_statements() {
    let source = r#"
            fn incomplete(flag: bool) -> int {
                if flag { return 1; }
            }
            fn complete(flag: bool) -> int {
                if flag { return 1; } else { return 2; }
                3
            }
            loop {
                break;
                4;
            }
        "#;
    let analysis = analyze(source).unwrap();
    assert_eq!(
        analysis
            .diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.message.contains("not all paths return"))
            .count(),
        1,
        "{:?}",
        analysis.diagnostics
    );
    assert_eq!(
        analysis
            .diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.message == "unreachable statement")
            .count(),
        2,
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn accepts_diverging_loops_and_finds_duplicate_literals() {
    let source = r#"
            fn forever() -> int { loop {} }
            match 1 { 1 => 1, 1 => 2, _ => 3 };
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        !analysis
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.message.contains("not all paths return")),
        "{:?}",
        analysis.diagnostics
    );
    assert_eq!(
        analysis
            .diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.message == "unreachable match arm")
            .count(),
        1,
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn reports_moves_and_merges_definite_branch_moves() {
    let source = r#"
            fn moved(flag: bool) {
                let first = "first";
                let owner = first;
                first;

                let second = "second";
                if flag { let left = second; } else { let right = second; }
                second;

                let third = "third";
                if flag { let maybe = third; }
                third;
            }
        "#;
    let analysis = analyze(source).unwrap();
    let moved = analysis
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.message.contains("use of moved value"))
        .collect::<Vec<_>>();
    assert_eq!(moved.len(), 2, "{:?}", analysis.diagnostics);
    assert!(
        moved
            .iter()
            .any(|diagnostic| diagnostic.message.contains("first"))
    );
    assert!(
        moved
            .iter()
            .any(|diagnostic| diagnostic.message.contains("second"))
    );
}

#[test]
fn preserves_copy_values_and_allows_multiple_mutable_references() {
    let source = r#"
            fn valid() -> int {
                let value = 21;
                let copied = value;
                let mut target = value + copied;
                {
                    let first = &mut target;
                    let second = &mut target;
                    *first = *second;
                }
                target
            }
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn reports_mutability_borrow_and_reference_escape_errors() {
    let source = r#"
            fn invalid_return(value: &int) { value }
            fn invalid_local() {
                let immutable = 1;
                immutable = 2;
                let writable = &mut immutable;

                let text = "hello";
                {
                    let reference = &text;
                    let moved = text;
                }

                let value = 1;
                let wrapped = Some(&value);
            }
        "#;
    let analysis = analyze(source).unwrap();
    for expected in [
        "cannot be returned",
        "cannot assign to immutable",
        "cannot mutably reference immutable",
        "while it is referenced",
        "cannot be stored inside owned values",
    ] {
        assert!(
            analysis
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains(expected)),
            "missing {expected:?}: {:?}",
            analysis.diagnostics
        );
    }
}

#[test]
fn releases_local_and_temporary_borrows() {
    let source = r#"
            fn inspect(value: &string) -> int { 1 }
            fn valid() {
                let first = "first";
                inspect(&first);
                let moved_first = first;

                let second = "second";
                { let reference = &second; }
                let moved_second = second;
            }
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn tracks_partial_field_moves_and_field_reinitialization() {
    let source = r#"
            struct Message { text: string, code: int }
            fn invalid() {
                let message = Message { text: "hello", code: 1 };
                let text = message.text;
                message.text;
                message;
            }
            fn valid() {
                let mut message = Message { text: "hello", code: 1 };
                let text = message.text;
                message.text = "again";
                let restored = message;
            }
        "#;
    let analysis = analyze(source).unwrap();
    assert_eq!(
        analysis
            .diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.message.contains("moved place"))
            .count(),
        1,
        "{:?}",
        analysis.diagnostics
    );
    assert_eq!(
        analysis
            .diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.message.contains("partially moved"))
            .count(),
        1,
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn reports_basic_static_type_mismatches() {
    let source = r#"
            fn takes_int(value: int) -> int { value }
            fn wrong_return() -> int { "wrong" }
            fn explicit_wrong() -> int { return "wrong"; }

            let annotated: string = 42;
            let mut assigned: int = 1;
            assigned = "wrong";
            takes_int("wrong");
            if 1 { 1 } else { 2 };
            let mixed = if true { 1 } else { "wrong" };
            let array = [1, "wrong"];
            let range = 0..false;
            unwrap_or(Some(1), "wrong");
        "#;
    let analysis = analyze(source).unwrap();
    for expected in [
        "function result expects `int`",
        "return value expects `int`",
        "initializer expects `string`",
        "assigned value expects `int`",
        "argument expects `int`",
        "if condition expects `bool`",
        "if branch expects `int`",
        "array element expects `int`",
        "range bound expects `int`",
        "default argument expects `int`",
    ] {
        assert!(
            analysis
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains(expected)),
            "missing {expected:?}: {:?}",
            analysis.diagnostics
        );
    }
}

#[test]
fn accepts_aliases_generics_and_mixed_numeric_operators() {
    let source = r#"
            type Count = int;
            fn identity<T>(value: T) -> T { value }
            fn convert(value: float) -> float { value }
            let count: Count = 42;
            let text = identity("text");
            let number = convert(1.5);
            let mixed = 1 + 2.5;
            if true { count } else { 0 };
        "#;
    let analysis = analyze(source).unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn tracks_owned_and_borrowed_method_receivers() {
    let source = r#"
            struct Message { text: string }
            impl Message {
                fn read(&self) -> int { 1 }
                fn replace(&mut self, text: string) { *self = Message { text: text } }
                fn consume(self) -> int { 1 }
            }

            fn invalid_move() {
                let message = Message { text: "hello" };
                message.read();
                message.consume();
                message;
            }

            fn invalid_mutability() {
                let message = Message { text: "hello" };
                message.replace("next");
            }

            fn invalid_argument() {
                let mut message = Message { text: "hello" };
                message.replace(42);
            }

            fn valid() {
                let mut message = Message { text: "hello" };
                message.read();
                message.replace("next");
                message.read();
            }
        "#;
    let analysis = analyze(source).unwrap();
    for expected in [
        "use of moved value `message`",
        "cannot mutably reference immutable variable `message`",
        "argument expects `string`",
    ] {
        assert!(
            analysis
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains(expected)),
            "missing {expected:?}: {:?}",
            analysis.diagnostics
        );
    }
    assert_eq!(analysis.diagnostics.len(), 3, "{:?}", analysis.diagnostics);
}

#[test]
fn infers_generic_record_literals_in_return_positions() {
    let analysis = analyze(
        r#"
            struct Pair<T, U> { first: T, second: U }
            impl<T, U> Pair<T, U> {
                fn swap(self) -> Pair<U, T> {
                    Pair { first: self.second, second: self.first }
                }
            }
        "#,
    )
    .unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn accepts_exhaustive_nested_option_matches() {
    let analysis = analyze(
        r#"
            fn describe(value: Option<Option<int>>) -> int {
                match value {
                    Some(Some(number)) => number,
                    Some(None) => 0,
                    None => -1,
                }
            }
        "#,
    )
    .unwrap();
    assert!(
        analysis.diagnostics.is_empty(),
        "{:?}",
        analysis.diagnostics
    );
}

#[test]
fn merges_moves_from_all_loop_break_paths() {
    let source = r#"
            fn definite() {
                let text = "owned";
                loop {
                    let consumed = text;
                    break;
                }
                text;
            }

            fn conditional(flag: bool) {
                let text = "owned";
                loop {
                    if flag {
                        let consumed = text;
                        break;
                    } else {
                        break;
                    }
                }
                text;
            }
        "#;
    let analysis = analyze(source).unwrap();
    let moved = analysis
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.message.contains("use of moved value `text`"))
        .count();
    assert_eq!(moved, 1, "{:?}", analysis.diagnostics);
}