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
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
//! In-process Luau type checking for Rust.
//!
//! # Example
//!
//! ```no_run
//! use luau_analyze::Checker;
//!
//! let mut checker = Checker::new().expect("checker should initialize");
//! checker
//!     .add_definitions(
//!         r#"
//!         declare class TodoBuilder
//!             function content(self, content: string): TodoBuilder
//!         end
//!         declare Todo: { create: () -> TodoBuilder }
//!         "#,
//!     )
//!     .expect("definitions should load");
//!
//! let result = checker.check(
//!     r#"
//!     --!strict
//!     local _todo = Todo.create():content("review")
//!     "#,
//! );
//! assert!(result.is_ok());
//! ```

/// Low-level FFI declarations for the Luau analysis bridge.
mod ffi;

use std::{
    cmp::Ordering,
    error::Error as StdError,
    fmt,
    marker::PhantomData,
    ptr::{self, NonNull},
    slice,
    sync::Arc,
    time::Duration,
};

/// Default module label for source checks.
const DEFAULT_CHECK_MODULE_NAME: &str = "main";
/// Default module label for definition loading.
const DEFAULT_DEFINITIONS_MODULE_NAME: &str = "@definitions";

/// Diagnostic severity emitted by the checker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// Type-check or lint error.
    Error,
    /// Lint warning.
    Warning,
}

/// A single diagnostic item from checking Luau source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    /// Zero-based start line.
    pub line: u32,
    /// Zero-based start column.
    pub col: u32,
    /// Zero-based end line.
    pub end_line: u32,
    /// Zero-based end column.
    pub end_col: u32,
    /// Severity level.
    pub severity: Severity,
    /// Human-readable diagnostic message.
    pub message: String,
}

/// Result of a single checker run.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CheckResult {
    /// Collected diagnostics sorted by location and severity.
    pub diagnostics: Vec<Diagnostic>,
    /// Whether the check hit one or more time limits.
    pub timed_out: bool,
    /// Whether cancellation was requested during checking.
    pub cancelled: bool,
}

/// One parameter extracted from a direct functional entrypoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntrypointParam {
    /// Parameter name in source order.
    pub name: String,
    /// Type annotation text as written.
    pub annotation: String,
    /// Whether the parameter is syntactically optional.
    pub optional: bool,
}

/// Parsed schema for a direct `return function(...) ... end` chunk.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EntrypointSchema {
    /// Ordered parameter list for the returned function literal.
    pub params: Vec<EntrypointParam>,
}

impl CheckResult {
    /// Returns `true` when the result contains no errors.
    pub fn is_ok(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity == Severity::Error)
    }

    /// Returns all error diagnostics.
    pub fn errors(&self) -> Vec<&Diagnostic> {
        self.diagnostics_with_severity(Severity::Error)
    }

    /// Returns all warning diagnostics.
    pub fn warnings(&self) -> Vec<&Diagnostic> {
        self.diagnostics_with_severity(Severity::Warning)
    }

    /// Returns all diagnostics matching the requested severity.
    fn diagnostics_with_severity(&self, severity: Severity) -> Vec<&Diagnostic> {
        self.diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.severity == severity)
            .collect()
    }

}

/// Stable checker policy values exposed by this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CheckerPolicy {
    /// Whether strict mode is always enforced.
    pub strict_mode: bool,
    /// Active solver policy string.
    pub solver: &'static str,
    /// Whether batch queue support is exposed by this crate.
    pub exposes_batch_queue: bool,
}

/// Returns the current fixed checker policy.
pub const fn checker_policy() -> CheckerPolicy {
    CheckerPolicy {
        strict_mode: true,
        solver: "new",
        exposes_batch_queue: false,
    }
}

/// Errors returned by checker construction and definition loading.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// Checker creation failed in the native layer.
    CreateCheckerFailed,
    /// Cancellation token creation failed in the native layer.
    CreateCancellationTokenFailed,
    /// Definitions failed to parse or type-check.
    Definitions(String),
    /// Entrypoint schema extraction failed.
    EntrypointSchema(String),
    /// UTF-8 input is too large for the C ABI length type.
    InputTooLarge {
        /// Logical input category such as `"source"` or `"definitions"`.
        kind: &'static str,
        /// Original input length in bytes.
        len: usize,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CreateCheckerFailed => formatter.write_str("failed to create Luau checker"),
            Self::CreateCancellationTokenFailed => {
                formatter.write_str("failed to create Luau cancellation token")
            }
            Self::Definitions(message) => {
                write!(formatter, "failed to load Luau definitions: {message}")
            }
            Self::EntrypointSchema(message) => {
                write!(
                    formatter,
                    "failed to extract Luau entrypoint schema: {message}"
                )
            }
            Self::InputTooLarge { kind, len } => {
                write!(
                    formatter,
                    "{kind} input is too large for checker FFI boundary ({len} bytes)"
                )
            }
        }
    }
}

impl StdError for Error {}

/// Default checker configuration used by `Checker`.
#[derive(Debug, Clone)]
pub struct CheckerOptions {
    /// Optional timeout applied to checks that do not override it.
    pub default_timeout: Option<Duration>,
    /// Default module label used for source checks.
    pub default_module_name: String,
    /// Default module label used for definition loading.
    pub default_definitions_module_name: String,
}

impl Default for CheckerOptions {
    fn default() -> Self {
        Self {
            default_timeout: None,
            default_module_name: DEFAULT_CHECK_MODULE_NAME.to_owned(),
            default_definitions_module_name: DEFAULT_DEFINITIONS_MODULE_NAME.to_owned(),
        }
    }
}

/// Per-call options for `Checker::check_with_options`.
#[derive(Debug, Clone, Copy, Default)]
pub struct CheckOptions<'a> {
    /// Optional timeout override for this call.
    pub timeout: Option<Duration>,
    /// Optional module label override for this call.
    pub module_name: Option<&'a str>,
    /// Optional cancellation token for this call.
    pub cancellation_token: Option<&'a CancellationToken>,
}

/// A reusable cancellation token that can be signaled from another thread.
///
/// `CancellationToken` is `Send` and `Sync` because the underlying Luau implementation
/// uses atomic operations to manage its signaled state safely across thread boundaries.
#[derive(Clone, Debug)]
pub struct CancellationToken {
    /// Shared token internals.
    inner: Arc<CancellationTokenInner>,
}

/// Shared cancellation token internals.
#[derive(Debug)]
struct CancellationTokenInner {
    /// Raw C cancellation token handle.
    raw: NonNull<ffi::LuauCancellationToken>,
}

// The underlying C cancellation token uses atomic state and is thread-safe for signal/reset.
unsafe impl Send for CancellationTokenInner {}
// The underlying C cancellation token uses atomic state and is thread-safe for signal/reset.
unsafe impl Sync for CancellationTokenInner {}

impl Drop for CancellationTokenInner {
    fn drop(&mut self) {
        // SAFETY: `raw` originates from `luau_cancellation_token_new` and is valid until drop.
        unsafe { ffi::luau_cancellation_token_free(self.raw.as_ptr()) };
    }
}

impl CancellationToken {
    /// Creates a new cancellation token.
    pub fn new() -> Result<Self, Error> {
        // SAFETY: Calling into shim constructor. Null indicates failure.
        let raw = NonNull::new(unsafe { ffi::luau_cancellation_token_new() })
            .ok_or(Error::CreateCancellationTokenFailed)?;
        Ok(Self {
            inner: Arc::new(CancellationTokenInner { raw }),
        })
    }

    /// Requests cancellation on this token.
    pub fn cancel(&self) {
        // SAFETY: `raw` is valid while `inner` is alive.
        unsafe { ffi::luau_cancellation_token_cancel(self.inner.raw.as_ptr()) };
    }

    /// Clears cancellation state on this token.
    pub fn reset(&self) {
        // SAFETY: `raw` is valid while `inner` is alive.
        unsafe { ffi::luau_cancellation_token_reset(self.inner.raw.as_ptr()) };
    }

    /// Returns the raw C token pointer.
    fn raw(&self) -> *mut ffi::LuauCancellationToken {
        self.inner.raw.as_ptr()
    }
}

/// Reusable checker instance with persistent global definitions.
///
/// `Checker` is `Send` but not `Sync`. The underlying Luau Analysis structures
/// are safely movable between threads, but all operations that mutate or read
/// from the checker require exclusive `&mut self` access, meaning it cannot
/// be concurrently accessed from multiple threads.
pub struct Checker {
    /// Opaque pointer to the native checker instance.
    inner: NonNull<ffi::LuauChecker>,
    /// Default checker behavior options.
    options: CheckerOptions,
}

// The underlying checker is single-threaded (`&mut self` methods), but ownership can move.
unsafe impl Send for Checker {}

impl Checker {
    /// Creates a checker with default options.
    pub fn new() -> Result<Self, Error> {
        Self::with_options(CheckerOptions::default())
    }

    /// Creates a checker with explicit defaults.
    pub fn with_options(options: CheckerOptions) -> Result<Self, Error> {
        // SAFETY: Calling into shim constructor. Null indicates failure.
        let inner =
            NonNull::new(unsafe { ffi::luau_checker_new() }).ok_or(Error::CreateCheckerFailed)?;
        Ok(Self { inner, options })
    }

    /// Returns immutable access to default checker options.
    pub fn options(&self) -> &CheckerOptions {
        &self.options
    }

    /// Loads Luau definition source using default module label.
    pub fn add_definitions(&mut self, defs: &str) -> Result<(), Error> {
        let module_name = self.options.default_definitions_module_name.clone();
        self.add_definitions_with_name(defs, &module_name)
    }

    /// Loads Luau definition source with an explicit module label.
    pub fn add_definitions_with_name(
        &mut self,
        defs: &str,
        module_name: &str,
    ) -> Result<(), Error> {
        let defs = FfiStr::new(defs, "definitions")?;
        let module_name = FfiStr::new(module_name, "definition module name")?;

        // SAFETY: Pointers are valid for call duration and checker handle is live.
        let raw = RawStringGuard::new(unsafe {
            ffi::luau_checker_add_definitions(
                self.inner.as_ptr(),
                defs.ptr(),
                defs.len(),
                module_name.ptr(),
                module_name.len(),
            )
        });

        match raw.message() {
            Some(message) => Err(Error::Definitions(message)),
            None => Ok(()),
        }
    }

    /// Type-checks a Luau source module with default options.
    pub fn check(&mut self, source: &str) -> Result<CheckResult, Error> {
        self.check_with_options(source, CheckOptions::default())
    }

    /// Type-checks a Luau source module with explicit per-call options.
    pub fn check_with_options(
        &mut self,
        source: &str,
        options: CheckOptions<'_>,
    ) -> Result<CheckResult, Error> {
        let source = FfiStr::new(source, "source")?;

        let module_name = options
            .module_name
            .unwrap_or(self.options.default_module_name.as_str());
        let module_name = FfiStr::new(module_name, "module name")?;

        let timeout = options.timeout.or(self.options.default_timeout);
        let raw_options = ffi::LuauCheckOptions {
            module_name: module_name.ptr(),
            module_name_len: module_name.len(),
            has_timeout: u32::from(timeout.is_some()),
            timeout_seconds: timeout.map_or(0.0, |duration| duration.as_secs_f64()),
            cancellation_token: options
                .cancellation_token
                .map_or(ptr::null_mut(), CancellationToken::raw),
        };

        // SAFETY: Input pointers and checker handle are valid for call duration.
        let raw = unsafe {
            ffi::luau_checker_check(
                self.inner.as_ptr(),
                source.ptr(),
                source.len(),
                &raw_options,
            )
        };
        let raw = RawCheckResultGuard::new(raw);

        let mut diagnostics = collect_diagnostics(raw.as_ref());

        diagnostics.sort_by(diagnostic_sort_key);
        Ok(CheckResult {
            diagnostics,
            timed_out: raw.as_ref().timed_out != 0,
            cancelled: raw.as_ref().cancelled != 0,
        })
    }
}

/// Extracts parameter names, annotation text, and optionality from a direct
/// `return function(...) ... end` chunk.
pub fn extract_entrypoint_schema(source: &str) -> Result<EntrypointSchema, Error> {
    let source = FfiStr::new(source, "source")?;

    // SAFETY: Input pointer is valid for the call duration.
    let raw = unsafe { ffi::luau_extract_entrypoint_schema(source.ptr(), source.len()) };
    let raw = RawEntrypointSchemaGuard::new(raw);

    if raw.as_ref().error_len != 0 {
        return Err(Error::EntrypointSchema(string_from_raw(
            raw.as_ref().error,
            raw.as_ref().error_len,
        )));
    }

    Ok(EntrypointSchema {
        params: collect_entrypoint_params(raw.as_ref()),
    })
}

impl Drop for Checker {
    fn drop(&mut self) {
        // SAFETY: `self.inner` originates from `luau_checker_new` and is valid until drop.
        unsafe { ffi::luau_checker_free(self.inner.as_ptr()) };
    }
}

/// Borrowed UTF-8 input prepared for a C ABI call.
#[derive(Clone, Copy)]
struct FfiStr<'a> {
    /// Pointer to the UTF-8 bytes, or null for empty strings.
    ptr: *const u8,
    /// Length of the UTF-8 payload in bytes.
    len: u32,
    /// Ties the raw pointer to the borrowed Rust string lifetime.
    _marker: PhantomData<&'a str>,
}

impl<'a> FfiStr<'a> {
    /// Converts a Rust string to a pointer-length pair accepted by the C ABI.
    fn new(value: &'a str, kind: &'static str) -> Result<Self, Error> {
        let len = u32::try_from(value.len()).map_err(|_| Error::InputTooLarge {
            kind,
            len: value.len(),
        })?;

        Ok(Self {
            ptr: if len == 0 {
                ptr::null()
            } else {
                value.as_ptr()
            },
            len,
            _marker: PhantomData,
        })
    }

    /// Returns the UTF-8 pointer for the C ABI.
    fn ptr(self) -> *const u8 {
        self.ptr
    }

    /// Returns the UTF-8 byte length for the C ABI.
    fn len(self) -> u32 {
        self.len
    }
}

/// RAII guard that releases a raw check result on scope exit.
struct RawCheckResultGuard {
    /// Raw check result allocated by the shim.
    raw: ffi::LuauCheckResult,
}

impl RawCheckResultGuard {
    /// Creates a guard for a raw check result.
    fn new(raw: ffi::LuauCheckResult) -> Self {
        Self { raw }
    }

    /// Returns a shared reference to the raw check result.
    fn as_ref(&self) -> &ffi::LuauCheckResult {
        &self.raw
    }
}

impl Drop for RawCheckResultGuard {
    fn drop(&mut self) {
        // SAFETY: `raw` came from shim and must be released exactly once.
        unsafe { ffi::luau_check_result_free(self.raw) };
    }
}

/// RAII guard that releases a raw string result on scope exit.
struct RawStringGuard {
    /// Raw string result allocated by the shim.
    raw: ffi::LuauString,
}

impl RawStringGuard {
    /// Creates a guard for a raw string result.
    fn new(raw: ffi::LuauString) -> Self {
        Self { raw }
    }

    /// Reads the string payload when the shim returned one.
    fn message(&self) -> Option<String> {
        if self.raw.len == 0 {
            None
        } else {
            Some(string_from_raw(self.raw.data, self.raw.len))
        }
    }
}

impl Drop for RawStringGuard {
    fn drop(&mut self) {
        // SAFETY: `raw` came from shim and must be released exactly once.
        unsafe { ffi::luau_string_free(self.raw) };
    }
}

/// RAII guard that releases a raw entrypoint schema result on scope exit.
struct RawEntrypointSchemaGuard {
    /// Raw entrypoint schema result allocated by the shim.
    raw: ffi::LuauEntrypointSchemaResult,
}

impl RawEntrypointSchemaGuard {
    /// Creates a guard for a raw entrypoint schema result.
    fn new(raw: ffi::LuauEntrypointSchemaResult) -> Self {
        Self { raw }
    }

    /// Returns a shared reference to the raw result.
    fn as_ref(&self) -> &ffi::LuauEntrypointSchemaResult {
        &self.raw
    }
}

impl Drop for RawEntrypointSchemaGuard {
    fn drop(&mut self) {
        // SAFETY: `raw` came from shim and must be released exactly once.
        unsafe { ffi::luau_entrypoint_schema_result_free(self.raw) };
    }
}

/// Converts raw UTF-8 bytes from C into a Rust `String`.
fn string_from_raw(ptr: *const u8, len: u32) -> String {
    if ptr.is_null() || len == 0 {
        return String::new();
    }

    // SAFETY: `ptr` points to `len` bytes provided by the shim for this call scope.
    let bytes = unsafe { slice::from_raw_parts(ptr, len as usize) };
    String::from_utf8_lossy(bytes).into_owned()
}

impl Severity {
    /// Converts the shim severity code into the public enum.
    fn from_ffi(code: u32) -> Self {
        match code {
            0 => Self::Error,
            _ => Self::Warning,
        }
    }
}

/// Converts diagnostic rows owned by the shim into Rust values.
fn collect_diagnostics(raw: &ffi::LuauCheckResult) -> Vec<Diagnostic> {
    // SAFETY: `raw.diagnostics` points to `diagnostic_count` entries owned by `raw`.
    unsafe { raw_slice(raw.diagnostics, raw.diagnostic_count) }
        .iter()
        .map(|diagnostic| Diagnostic {
            line: diagnostic.line,
            col: diagnostic.col,
            end_line: diagnostic.end_line,
            end_col: diagnostic.end_col,
            severity: Severity::from_ffi(diagnostic.severity),
            message: string_from_raw(diagnostic.message, diagnostic.message_len),
        })
        .collect()
}

/// Converts entrypoint parameter rows owned by the shim into Rust values.
fn collect_entrypoint_params(raw: &ffi::LuauEntrypointSchemaResult) -> Vec<EntrypointParam> {
    // SAFETY: `raw.params` points to `param_count` entries owned by `raw`.
    unsafe { raw_slice(raw.params, raw.param_count) }
        .iter()
        .map(|param| EntrypointParam {
            name: string_from_raw(param.name, param.name_len),
            annotation: string_from_raw(param.annotation, param.annotation_len),
            optional: param.optional != 0,
        })
        .collect()
}

/// Forms a borrowed slice from a non-owning C pointer and element count.
unsafe fn raw_slice<'a, T>(ptr: *const T, len: u32) -> &'a [T] {
    if len == 0 {
        &[]
    } else {
        debug_assert!(!ptr.is_null(), "non-empty shim slice must not be null");
        // SAFETY: The caller guarantees `ptr` is valid for `len` elements.
        unsafe { slice::from_raw_parts(ptr, len as usize) }
    }
}

/// Sorts diagnostics by location, then severity, then message.
fn diagnostic_sort_key(left: &Diagnostic, right: &Diagnostic) -> Ordering {
    left.line
        .cmp(&right.line)
        .then(left.col.cmp(&right.col))
        .then(left.severity.cmp(&right.severity))
        .then(left.message.cmp(&right.message))
}

/// Unit tests for public result helpers and policy defaults.
#[cfg(test)]
mod tests {
    use super::{
        CheckResult, CheckerOptions, Diagnostic, Severity, checker_policy,
        extract_entrypoint_schema,
    };

    /// Verifies `CheckResult::is_ok` is true for warning-only results.
    #[test]
    fn check_result_ok_with_warnings() {
        let result = CheckResult {
            diagnostics: vec![Diagnostic {
                line: 0,
                col: 0,
                end_line: 0,
                end_col: 1,
                severity: Severity::Warning,
                message: "unused local".to_owned(),
            }],
            timed_out: false,
            cancelled: false,
        };

        assert!(result.is_ok());
        assert_eq!(1, result.warnings().len());
        assert_eq!(0, result.errors().len());
    }

    /// Verifies `CheckResult::is_ok` is false when at least one error exists.
    #[test]
    fn check_result_not_ok_with_error() {
        let result = CheckResult {
            diagnostics: vec![Diagnostic {
                line: 1,
                col: 1,
                end_line: 1,
                end_col: 5,
                severity: Severity::Error,
                message: "type mismatch".to_owned(),
            }],
            timed_out: false,
            cancelled: false,
        };

        assert!(!result.is_ok());
        assert_eq!(0, result.warnings().len());
        assert_eq!(1, result.errors().len());
    }

    /// Verifies policy constants match project decisions.
    #[test]
    fn policy_is_strict_new_solver_and_queue_free() {
        let policy = checker_policy();
        assert!(policy.strict_mode);
        assert_eq!("new", policy.solver);
        assert!(!policy.exposes_batch_queue);
    }

    /// Verifies checker options defaults use stable module labels.
    #[test]
    fn checker_options_defaults_are_stable() {
        let options = CheckerOptions::default();
        assert_eq!("main", options.default_module_name);
        assert_eq!("@definitions", options.default_definitions_module_name);
        assert!(options.default_timeout.is_none());
    }

    /// Verifies schema extraction reads direct function parameters in order.
    #[test]
    fn extract_entrypoint_schema_reads_params() {
        let schema = extract_entrypoint_schema(
            r#"
return function(target: Node, count: number?, payload: JsonValue)
    return nil
end
"#,
        )
        .expect("schema");
        assert_eq!(3, schema.params.len());
        assert_eq!("target", schema.params[0].name);
        assert_eq!("Node", schema.params[0].annotation);
        assert!(!schema.params[0].optional);
        assert_eq!("count", schema.params[1].name);
        assert_eq!("number?", schema.params[1].annotation);
        assert!(schema.params[1].optional);
        assert_eq!("payload", schema.params[2].name);
        assert_eq!("JsonValue", schema.params[2].annotation);
        assert!(!schema.params[2].optional);
    }

    /// Verifies schema extraction rejects indirect entrypoints.
    #[test]
    fn extract_entrypoint_schema_rejects_indirect_return() {
        let error = extract_entrypoint_schema(
            r#"
local main = function(target: Node)
    return nil
end
return main
"#,
        )
        .expect_err("schema should fail");
        assert!(
            error
                .to_string()
                .contains("script must use a direct `return function(...) ... end` entrypoint"),
            "{error}"
        );
    }
}