luau-analyzer-sys 0.1.1

A high-performance, embedded Luau type-checking and analysis engine written in Rust. This crate provides bindings to the Luau analyzer, allowing you to integrate static analysis and code intelligence directly into your applications.
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
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_uint, c_void};

#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub severity: u8, // 0 for error, 1 for warning
    pub line: u32,
    pub col: u32,
    pub end_line: u32,
    pub end_col: u32,
    pub message: String,
}

#[repr(C)]
pub struct LuauAnalyzerOpaque {
    _private: [u8; 0],
}

type DiagnosticCallback = unsafe extern "C" fn(
    context: *mut c_void,
    severity: c_int,
    line: c_uint,
    col: c_uint,
    end_line: c_uint,
    end_col: c_uint,
    message: *const c_char,
);

type ReadSourceCallback =
    unsafe extern "C" fn(context: *mut c_void, module_name: *const c_char) -> *const c_char;

type ResolveModuleCallback = unsafe extern "C" fn(
    context: *mut c_void,
    current_module: *const c_char,
    required_name: *const c_char,
) -> *const c_char;

unsafe extern "C" {
    fn luau_analyzer_create() -> *mut LuauAnalyzerOpaque;
    fn luau_analyzer_destroy(analyzer: *mut LuauAnalyzerOpaque);
    fn luau_analyzer_add_definitions(analyzer: *mut LuauAnalyzerOpaque, source: *const c_char);
    fn luau_analyzer_check(
        analyzer: *mut LuauAnalyzerOpaque,
        module_name: *const c_char,
        read_callback: Option<ReadSourceCallback>,
        resolve_callback: Option<ResolveModuleCallback>,
        diag_callback: Option<DiagnosticCallback>,
        context: *mut c_void,
    );
}

struct CheckContext<'a> {
    diagnostics: Vec<Diagnostic>,
    cached_strings: HashMap<String, CString>,
    resolver: &'a dyn Fn(&str) -> Option<String>,
    path_resolver: &'a dyn Fn(&str, &str) -> Option<String>,
}

pub struct NativeAnalyzer {
    ptr: *mut LuauAnalyzerOpaque,
}

impl NativeAnalyzer {
    pub fn new() -> Self {
        unsafe {
            Self {
                ptr: luau_analyzer_create(),
            }
        }
    }

    pub fn add_definitions(&mut self, source: &str) {
        if let Ok(c_str) = CString::new(source) {
            unsafe {
                luau_analyzer_add_definitions(self.ptr, c_str.as_ptr());
            }
        }
    }

    pub fn check<F, P>(
        &mut self,
        module_name: &str,
        resolver: F,
        path_resolver: P,
    ) -> Vec<Diagnostic>
    where
        F: Fn(&str) -> Option<String>,
        P: Fn(&str, &str) -> Option<String>,
    {
        let mut context = CheckContext {
            diagnostics: Vec::new(),
            cached_strings: HashMap::new(),
            resolver: &resolver,
            path_resolver: &path_resolver,
        };

        if let Ok(mod_cstr) = CString::new(module_name) {
            unsafe extern "C" fn read_callback(
                ctx_ptr: *mut c_void,
                mod_name: *const c_char,
            ) -> *const c_char {
                let ctx = unsafe { &mut *(ctx_ptr as *mut CheckContext) };
                if mod_name.is_null() {
                    return std::ptr::null();
                }
                let name_str = unsafe { CStr::from_ptr(mod_name) }.to_string_lossy();
                if let Some(c_str) = ctx.cached_strings.get(name_str.as_ref()) {
                    return c_str.as_ptr();
                }
                if let Some(src) = (ctx.resolver)(name_str.as_ref())
                    && let Ok(c_str) = CString::new(src)
                {
                    let ptr = c_str.as_ptr();
                    ctx.cached_strings.insert(name_str.into_owned(), c_str);
                    return ptr;
                }
                std::ptr::null()
            }

            unsafe extern "C" fn resolve_callback(
                ctx_ptr: *mut c_void,
                curr_mod: *const c_char,
                req_name: *const c_char,
            ) -> *const c_char {
                let ctx = unsafe { &mut *(ctx_ptr as *mut CheckContext) };
                if curr_mod.is_null() || req_name.is_null() {
                    return std::ptr::null();
                }
                let curr_mod_str = unsafe { CStr::from_ptr(curr_mod) }.to_string_lossy();
                let req_name_str = unsafe { CStr::from_ptr(req_name) }.to_string_lossy();

                let cache_key = format!("RESOLVED:{}:{}", curr_mod_str, req_name_str);
                if let Some(c_str) = ctx.cached_strings.get(&cache_key) {
                    return c_str.as_ptr();
                }

                if let Some(resolved) =
                    (ctx.path_resolver)(curr_mod_str.as_ref(), req_name_str.as_ref())
                    && let Ok(c_str) = CString::new(resolved)
                {
                    let ptr = c_str.as_ptr();
                    ctx.cached_strings.insert(cache_key, c_str);
                    return ptr;
                }
                std::ptr::null()
            }

            unsafe extern "C" fn diag_callback(
                ctx_ptr: *mut c_void,
                severity: c_int,
                line: c_uint,
                col: c_uint,
                end_line: c_uint,
                end_col: c_uint,
                message: *const c_char,
            ) {
                let ctx = unsafe { &mut *(ctx_ptr as *mut CheckContext) };
                let msg_str = if message.is_null() {
                    String::new()
                } else {
                    unsafe { CStr::from_ptr(message) }
                        .to_string_lossy()
                        .into_owned()
                };
                ctx.diagnostics.push(Diagnostic {
                    severity: severity as u8,
                    line,
                    col,
                    end_line,
                    end_col,
                    message: msg_str,
                });
            }

            unsafe {
                let ctx_void = &mut context as *mut CheckContext as *mut c_void;
                luau_analyzer_check(
                    self.ptr,
                    mod_cstr.as_ptr(),
                    Some(read_callback),
                    Some(resolve_callback),
                    Some(diag_callback),
                    ctx_void,
                );
            }
        }

        context.diagnostics
    }
}

impl Default for NativeAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

impl Drop for NativeAnalyzer {
    fn drop(&mut self) {
        unsafe {
            if !self.ptr.is_null() {
                luau_analyzer_destroy(self.ptr);
                self.ptr = std::ptr::null_mut();
            }
        }
    }
}

unsafe impl Send for NativeAnalyzer {}

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

    #[test]
    fn test_create_analyzer() {
        let analyzer = NativeAnalyzer::new();
        assert!(!analyzer.ptr.is_null());
    }

    #[test]
    fn test_check_simple_no_errors() {
        let mut analyzer = NativeAnalyzer::new();
        let source = "local _x: number = 10\nlocal _y: number = _x + 5\n";

        let diagnostics = analyzer.check(
            "main",
            |name| {
                if name == "main" {
                    Some(source.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );

        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn test_check_type_error() {
        let mut analyzer = NativeAnalyzer::new();
        // Intentional type error: assigning string to a number variable
        let source = "local _x: number = 'hello'\n";

        let diagnostics = analyzer.check(
            "main",
            |name| {
                if name == "main" {
                    Some(source.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );

        assert!(
            !diagnostics.is_empty(),
            "Expected at least one type error diagnostic"
        );
        let diag = &diagnostics[0];
        assert!(
            diag.severity == 0 || diag.severity == 1,
            "Expected error or warning severity, got: {}",
            diag.severity
        );
        assert!(
            diag.message.contains("string"),
            "Expected message to mention 'string', got: {}",
            diag.message
        );
        assert!(
            diag.message.contains("number"),
            "Expected message to mention 'number', got: {}",
            diag.message
        );
    }

    #[test]
    fn test_check_syntax_error() {
        let mut analyzer = NativeAnalyzer::new();
        // Syntax error: missing end of statement/operator
        let source = "local x = \n";

        let diagnostics = analyzer.check(
            "main",
            |name| {
                if name == "main" {
                    Some(source.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );

        assert!(!diagnostics.is_empty(), "Expected syntax error diagnostic");
        // Syntax error is usually severity 0 (error)
        assert_eq!(diagnostics[0].severity, 0);
    }

    #[test]
    fn test_check_with_submodule() {
        let mut analyzer = NativeAnalyzer::new();
        let main_source = "local dep = require('dependency')\nlocal _x: number = dep.value\n";
        let dep_source = "local M = {}\nM.value = 42\nreturn M\n";

        let diagnostics = analyzer.check(
            "main",
            |name| match name {
                "main" => Some(main_source.to_string()),
                "dependency" => Some(dep_source.to_string()),
                _ => None,
            },
            |current, required| {
                if current == "main" && required == "dependency" {
                    Some("dependency".to_string())
                } else {
                    None
                }
            },
        );

        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics, got: {:?}",
            diagnostics
        );
    }

    #[test]
    fn test_multiple_checks_same_analyzer() {
        let mut analyzer = NativeAnalyzer::new();

        let src1 = "local _x: number = 10\n";
        let diagnostics1 = analyzer.check(
            "mod1",
            |name| {
                if name == "mod1" {
                    Some(src1.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );
        assert!(diagnostics1.is_empty());

        let src2 = "local _y: string = 'hello'\n";
        let diagnostics2 = analyzer.check(
            "mod2",
            |name| {
                if name == "mod2" {
                    Some(src2.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );
        assert!(diagnostics2.is_empty());
    }

    #[test]
    fn test_custom_definitions() {
        let mut analyzer = NativeAnalyzer::new();
        // Register a custom global function `my_global_helper`
        analyzer.add_definitions("declare function my_global_helper(val: string): number\n");

        // Code that uses the custom global function correctly
        let correct_source = "--!strict\nlocal _x: number = my_global_helper('test')\n";
        let diagnostics = analyzer.check(
            "main_correct",
            |name| {
                if name == "main_correct" {
                    Some(correct_source.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );
        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics, got: {:?}",
            diagnostics
        );

        // Code that uses it incorrectly (type mismatch: passing number instead of string)
        let incorrect_source = "--!strict\nlocal _x: number = my_global_helper(123)\n";
        let diagnostics2 = analyzer.check(
            "main_incorrect",
            |name| {
                if name == "main_incorrect" {
                    Some(incorrect_source.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );
        println!("test_custom_definitions diagnostics: {:?}", diagnostics2);
        assert!(
            !diagnostics2.is_empty(),
            "Expected a type error due to parameter type mismatch"
        );
        let msg = &diagnostics2[0].message;
        assert!(
            msg.contains("number") || msg.contains("string"),
            "Got message: {}",
            msg
        );
    }

    #[test]
    fn test_precise_error_coordinates() {
        let mut analyzer = NativeAnalyzer::new();
        // Error on line 3 (0-indexed line 2), column 19:
        // Line 1: --!strict
        // Line 2: local _x: number = 10
        // Line 3: local _y: string = 20
        let source = "--!strict\nlocal _x: number = 10\nlocal _y: string = 20\n";

        let diagnostics = analyzer.check(
            "main_precise",
            |name| {
                if name == "main_precise" {
                    Some(source.to_string())
                } else {
                    None
                }
            },
            |_, _| None,
        );

        assert!(!diagnostics.is_empty());
        let diag = &diagnostics[0];
        // In Luau, line numbers in error locations are 0-based.
        // Line 3 is index 2.
        assert_eq!(diag.line, 2);
        assert!(diag.col < 100);
    }

    #[test]
    fn test_resolver_returns_none() {
        use std::cell::RefCell;
        use std::rc::Rc;

        let mut analyzer = NativeAnalyzer::new();
        let source = "--!strict\nlocal _dep = require('missing_module')\n";

        let resolver_called = Rc::new(RefCell::new(false));
        let resolver_called_clone = resolver_called.clone();

        let diagnostics = analyzer.check(
            "main_resolver",
            |name| {
                if name == "main_resolver" {
                    Some(source.to_string())
                } else {
                    if name == "missing_module" {
                        *resolver_called_clone.borrow_mut() = true;
                    }
                    None // fails to load
                }
            },
            |current, required| {
                if current == "main_resolver" && required == "missing_module" {
                    Some("missing_module".to_string())
                } else {
                    None
                }
            },
        );

        println!("test_resolver_returns_none diagnostics: {:?}", diagnostics);
        // Verify that the resolver was indeed called with the missing module name
        assert!(*resolver_called.borrow());
        // And diagnostics for the entry file is empty because errors on the required module are filtered out
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn test_multithreaded_analyzer() {
        use std::thread;

        let mut analyzer = NativeAnalyzer::new();
        analyzer.add_definitions("declare function thread_safe_helper(): ()\n");

        // NativeAnalyzer is Send, so we can move it to another thread
        let handle = thread::spawn(move || {
            let source = "thread_safe_helper()\n";
            let diagnostics = analyzer.check(
                "main",
                |name| {
                    if name == "main" {
                        Some(source.to_string())
                    } else {
                        None
                    }
                },
                |_, _| None,
            );
            assert!(diagnostics.is_empty());
            analyzer // Return it back
        });

        let _analyzer = handle.join().unwrap();
    }

    #[test]
    fn test_default_analyzer() {
        // Test Default trait implementation
        let analyzer = NativeAnalyzer::default();
        assert!(!analyzer.ptr.is_null());
    }

    #[test]
    fn test_diagnostics_clone_and_debug() {
        let diag = Diagnostic {
            severity: 0,
            line: 1,
            col: 2,
            end_line: 3,
            end_col: 4,
            message: "Test message".to_string(),
        };

        let cloned = diag.clone();
        assert_eq!(cloned.severity, diag.severity);
        assert_eq!(cloned.line, diag.line);
        assert_eq!(cloned.col, diag.col);
        assert_eq!(cloned.end_line, diag.end_line);
        assert_eq!(cloned.end_col, diag.end_col);
        assert_eq!(cloned.message, diag.message);

        let debug_str = format!("{:?}", diag);
        assert!(debug_str.contains("Test message"));
    }

    #[test]
    fn test_check_with_nested_relative_modules() {
        let mut analyzer = NativeAnalyzer::new();

        // main requires foo/bar, which in turn requires ../baz
        let main_src = "local _bar = require('foo/bar')\n";
        let bar_src = "local _baz = require('../baz')\nlocal M = {}\nreturn M\n";
        let baz_src = "local M = {}\nM.value = 100\nreturn M\n";

        let diagnostics = analyzer.check(
            "main",
            |name| match name {
                "main" => Some(main_src.to_string()),
                "foo/bar" => Some(bar_src.to_string()),
                "baz" => Some(baz_src.to_string()),
                _ => None,
            },
            |current, required| {
                if current == "main" && required == "foo/bar" {
                    Some("foo/bar".to_string())
                } else if current == "foo/bar" && required == "../baz" {
                    // Resolve relative path "../baz" from "foo/bar" to "baz"
                    Some("baz".to_string())
                } else {
                    None
                }
            },
        );

        assert!(
            diagnostics.is_empty(),
            "Expected no diagnostics, got: {:?}",
            diagnostics
        );
    }
}