luau-analyze 0.0.1

In-process Luau type checker for Rust
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
//! Integration tests for `luau-analyze`.

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::{Path, PathBuf},
        time::Duration,
    };

    use luau_analyze::{CancellationToken, CheckOptions, Checker, Severity};

    /// Expected result marker parsed from script header comments.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Expectation {
        /// Script should type-check without errors.
        Pass,
        /// Script should report at least one error.
        Fail,
    }

    /// Verifies strict-mode type mismatch reporting.
    #[test]
    fn strict_type_mismatch_reports_error() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker
            .check(
                r#"
            --!strict
            local x: number = "hello"
            "#,
            )
            .unwrap();

        assert!(!result.is_ok(), "expected strict type mismatch");
        assert!(
            result
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.severity == Severity::Error)
        );
        assert!(!result.timed_out);
        assert!(!result.cancelled);
    }

    /// Verifies strict mode is enforced even without `--!strict`.
    #[test]
    fn strict_mode_is_enforced_without_hot_comment() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker
            .check(
                r#"
            local x: number = "hello"
            "#,
            )
            .unwrap();

        assert!(!result.is_ok(), "strict type mismatch should be reported");
        assert!(
            result
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.severity == Severity::Error)
        );
    }

    /// Verifies invalid definitions return an actionable error.
    #[test]
    fn invalid_definitions_fail() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let invalid_defs = read_example("definitions/invalid_api.d.luau");
        let error = checker
            .add_definitions(&invalid_defs)
            .expect_err("invalid definitions should fail");

        let message = error.to_string();
        assert!(!message.trim().is_empty());
        assert!(message.contains("failed to load Luau definitions"));
    }

    /// Verifies custom definition labels are preserved in error messages.
    #[test]
    fn invalid_definitions_include_custom_label() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let invalid_defs = read_example("definitions/invalid_api.d.luau");
        let error = checker
            .add_definitions_with_name(&invalid_defs, "defs/invalid_api.d.luau")
            .expect_err("invalid definitions should fail");

        assert!(error.to_string().contains("defs/invalid_api.d.luau"));
    }

    /// Verifies multiple definitions with distinct labels stay active.
    #[test]
    fn multiple_definition_labels_keep_all_types_available() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        checker
            .add_definitions_with_name("declare function alpha_id(): string", "defs/alpha.d.luau")
            .expect("alpha definitions should load");
        checker
            .add_definitions_with_name("declare function beta_count(): number", "defs/beta.d.luau")
            .expect("beta definitions should load");

        let result = checker
            .check(
                r#"
            --!strict
            local id: string = alpha_id()
            local count: number = beta_count()
            "#,
            )
            .unwrap();

        assert!(
            result.is_ok(),
            "both definition files should remain active: {result:#?}"
        );
    }

    /// Verifies host definitions affect check outcomes.
    #[test]
    fn definitions_change_check_behavior() {
        let mut checker = checker_with_demo_definitions();

        let ok_result = checker
            .check(
                r#"
            --!strict
            local todo = Todo.create():content("Review"):due("today"):save()
            todo:complete()
            "#,
            )
            .unwrap();
        assert!(
            ok_result.is_ok(),
            "expected script to pass with valid API usage: {ok_result:#?}"
        );

        let bad_result = checker
            .check(
                r#"
            --!strict
            local todo = Todo.create():content("Review"):due(42):save()
            "#,
            )
            .unwrap();
        assert!(!bad_result.is_ok(), "expected type error for due(42)");
    }

    /// Verifies one checker can run multiple checks while keeping definitions.
    #[test]
    fn checker_reuse_keeps_definitions() {
        let mut checker = checker_with_demo_definitions();

        let first = checker
            .check(
                r#"
            --!strict
            local _todo = Todo.create():content("one"):save()
            "#,
            )
            .unwrap();
        assert!(first.is_ok(), "first check should succeed");

        let second = checker
            .check(
                r#"
            --!strict
            local _todo = Todo.create():content("two"):due(123):save()
            "#,
            )
            .unwrap();
        assert!(!second.is_ok(), "second check should fail");

        let third = checker
            .check(
                r#"
            --!strict
            local id = make_id("todo")
            local _: string = id
            "#,
            )
            .unwrap();
        assert!(third.is_ok(), "third check should still succeed");
    }

    /// Verifies empty source does not produce type errors.
    #[test]
    fn empty_script_is_ok() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker.check("").unwrap();
        assert!(result.is_ok(), "empty script should not produce errors");
    }

    /// Verifies syntax errors are surfaced as diagnostics.
    #[test]
    fn syntax_error_is_reported() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker
            .check(
                r#"
            --!strict
            local value: number =
            "#,
            )
            .unwrap();

        assert!(!result.is_ok(), "expected syntax error");
        assert!(
            result
                .diagnostics
                .iter()
                .any(|diagnostic| !diagnostic.message.is_empty())
        );
    }

    /// Verifies timeout state and labels are surfaced for zero-timeout checks.
    #[test]
    fn timeout_marks_result_and_uses_module_label() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker
            .check_with_options(
                "--!strict\nlocal x = 1\n",
                CheckOptions {
                    timeout: Some(Duration::ZERO),
                    module_name: Some("custom/module_timeout.luau"),
                    cancellation_token: None,
                },
            )
            .unwrap();

        assert!(result.timed_out, "expected timeout marker");
        assert!(!result.is_ok(), "timeout should fail check");
        assert!(
            result
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains("custom/module_timeout.luau"))
        );
    }

    /// Verifies cancellation state is surfaced through check results.
    #[test]
    fn cancellation_marks_result() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let token = CancellationToken::new().expect("token should be created");
        token.cancel();

        let result = checker
            .check_with_options(
                "--!strict\nlocal x = 1\n",
                CheckOptions {
                    timeout: None,
                    module_name: Some("cancelled.luau"),
                    cancellation_token: Some(&token),
                },
            )
            .unwrap();

        assert!(result.cancelled, "expected cancelled marker");
        assert!(!result.is_ok(), "cancelled check should fail");
        assert!(
            result
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.contains("cancelled"))
        );
    }

    /// Verifies cross-file `require` is currently unsupported in checker mode.
    #[test]
    fn single_file_require_is_not_supported() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker
            .check(
                r#"
            --!strict
            local dep = require("./other_module")
            local _: number = dep.value
            "#,
            )
            .unwrap();

        assert!(
            !result.is_ok(),
            "expected unresolved module diagnostic for single-file checker"
        );
    }

    /// Verifies diagnostics are deterministically sorted.
    #[test]
    fn diagnostics_are_sorted() {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let result = checker
            .check(
                r#"
            --!strict
            local a: number = "x"
            local b: number = "y"
            "#,
            )
            .unwrap();

        for pair in result.diagnostics.windows(2) {
            let left = &pair[0];
            let right = &pair[1];
            let ordered = (left.line, left.col, left.severity, &left.message)
                <= (right.line, right.col, right.severity, &right.message);
            assert!(
                ordered,
                "diagnostics were not sorted: {left:?} then {right:?}"
            );
        }
    }

    /// Verifies all bundled example scripts match their declared expectations.
    #[test]
    fn bundled_examples_match_expectations() {
        let mut checker = checker_with_demo_definitions();
        let scripts_dir = examples_root().join("scripts");
        let mut scripts = collect_scripts_recursive(&scripts_dir)
            .expect("scripts should be collected recursively");
        scripts.sort();

        let mut mismatches = Vec::new();
        for script in scripts {
            let source = fs::read_to_string(&script).expect("example script should be readable");
            let expected = parse_expectation(&source);
            let result = checker.check(&source).unwrap();
            let actual = if result.is_ok() {
                Expectation::Pass
            } else {
                Expectation::Fail
            };
            if actual != expected {
                mismatches.push(format!(
                    "{} expected {:?} got {:?}",
                    script.display(),
                    expected,
                    actual
                ));
            }
        }

        assert!(
            mismatches.is_empty(),
            "script expectation mismatches:\n{}",
            mismatches.join("\n")
        );
    }

    /// Verifies packaged fixtures stay in sync with the workspace examples.
    #[test]
    fn bundled_examples_match_workspace_examples() {
        let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples");
        if !workspace_root.exists() {
            return;
        }

        let bundled_root = examples_root();
        let mut bundled_files = collect_scripts_recursive(&bundled_root)
            .expect("bundled examples should be collected recursively")
            .into_iter()
            .map(|path| {
                path.strip_prefix(&bundled_root)
                    .expect("bundled file should stay under bundled root")
                    .to_path_buf()
            })
            .collect::<Vec<_>>();
        let mut workspace_files = collect_scripts_recursive(&workspace_root)
            .expect("workspace examples should be collected recursively")
            .into_iter()
            .map(|path| {
                path.strip_prefix(&workspace_root)
                    .expect("workspace file should stay under workspace root")
                    .to_path_buf()
            })
            .collect::<Vec<_>>();

        bundled_files.sort();
        workspace_files.sort();

        assert_eq!(
            bundled_files, workspace_files,
            "bundled fixtures drifted from workspace examples"
        );

        for relative_path in bundled_files {
            let bundled = fs::read_to_string(bundled_root.join(&relative_path))
                .expect("bundled example should be readable");
            let workspace = fs::read_to_string(workspace_root.join(&relative_path))
                .expect("workspace example should be readable");
            assert_eq!(
                bundled,
                workspace,
                "bundled fixture `{}` drifted from workspace example",
                relative_path.display()
            );
        }
    }

    /// Creates a checker preloaded with demo API definitions.
    fn checker_with_demo_definitions() -> Checker {
        let mut checker = Checker::new().expect("checker creation should succeed");
        let defs = read_example("definitions/api.d.luau");
        checker
            .add_definitions(&defs)
            .expect("demo definitions should load");
        checker
    }

    /// Reads one file under the crate-bundled examples fixture directory.
    fn read_example(relative_path: &str) -> String {
        let path = examples_root().join(relative_path);
        fs::read_to_string(&path).unwrap_or_else(|error| {
            panic!("failed to read `{}`: {error}", path.display());
        })
    }

    /// Returns the crate-bundled examples fixture root.
    fn examples_root() -> PathBuf {
        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/examples");
        assert!(
            root.exists(),
            "examples root should exist at `{}`",
            root.display()
        );
        root
    }

    /// Parses the script expectation marker from leading comments.
    fn parse_expectation(source: &str) -> Expectation {
        for line in source.lines().take(10) {
            let normalized = line.trim();
            if let Some(rest) = normalized.strip_prefix("-- expect:") {
                let marker = rest.trim();
                if marker.eq_ignore_ascii_case("fail") || marker.eq_ignore_ascii_case("error") {
                    return Expectation::Fail;
                }
                if marker.eq_ignore_ascii_case("pass") || marker.eq_ignore_ascii_case("ok") {
                    return Expectation::Pass;
                }
            }
            if !normalized.is_empty() && !normalized.starts_with("--") {
                break;
            }
        }
        Expectation::Pass
    }

    /// Recursively collects all `.luau` scripts under `root`.
    fn collect_scripts_recursive(root: &Path) -> Result<Vec<PathBuf>, String> {
        let mut scripts = Vec::new();
        let mut stack = vec![root.to_path_buf()];

        while let Some(dir) = stack.pop() {
            for entry in fs::read_dir(&dir).map_err(|error| {
                format!("failed to read scripts dir `{}`: {error}", dir.display())
            })? {
                let entry =
                    entry.map_err(|error| format!("failed to read directory entry: {error}"))?;
                let path = entry.path();
                if path.is_dir() {
                    stack.push(path);
                } else if path.extension().is_some_and(|ext| ext == "luau") {
                    scripts.push(path);
                }
            }
        }

        Ok(scripts)
    }
}