luau-syntax 0.732.0

Luau lexer, parser, AST, CST, and source utilities
Documentation
use luau_syntax::allocator::AstArena;
use luau_syntax::ast_names::AstNameTable;
use luau_syntax::location::Position;
use luau_syntax::parser::{self, ParseOptions, ParseResult};

fn with_parse<R>(
    source: &str,
    options: ParseOptions,
    f: impl for<'ast> FnOnce(ParseResult<'ast>) -> R,
) -> R {
    let arena = AstArena::new();
    let mut names = AstNameTable::new(&arena);
    let result = parser::parse(source, &arena, &mut names, options).unwrap();
    f(result)
}
fn with_comments<R>(source: &str, f: impl for<'ast> FnOnce(ParseResult<'ast>) -> R) -> R {
    with_parse(
        source,
        ParseOptions::default().with_comment_capture(true),
        f,
    )
}

fn module_source() -> &'static str {
    r#"
        --!strict
        local foo = {}
        function foo:bar() end

        --[[
            foo:
        ]] foo:bar()

        --[[]]--[[]] -- Two distinct comments that have zero characters of space between them.
    "#
}

// Module.test.cpp: is_within_comment
#[test]
fn source_module_is_within_comment() {
    with_comments(module_source(), |result| {
        assert_eq!(result.metadata.comment_locations.len(), 5);

        assert!(result.is_within_comment(Position::new(1, 15)));
        assert!(result.is_within_comment(Position::new(6, 16)));
        assert!(result.is_within_comment(Position::new(9, 13)));
        assert!(result.is_within_comment(Position::new(9, 14)));

        assert!(!result.is_within_comment(Position::new(2, 15)));
        assert!(!result.is_within_comment(Position::new(7, 10)));
        assert!(!result.is_within_comment(Position::new(7, 11)));
    });
}

// Module.test.cpp: is_within_comment_parse_result
#[test]
fn is_within_comment_parse_result() {
    with_comments(module_source(), |result| {
        assert_eq!(result.metadata.comment_locations.len(), 5);

        assert!(result.is_within_comment(Position::new(1, 15)));
        assert!(result.is_within_comment(Position::new(6, 16)));
        assert!(result.is_within_comment(Position::new(9, 13)));
        assert!(result.is_within_comment(Position::new(9, 14)));

        assert!(!result.is_within_comment(Position::new(2, 15)));
        assert!(!result.is_within_comment(Position::new(7, 10)));
        assert!(!result.is_within_comment(Position::new(7, 11)));
    });
}