feat(kernel): R7b Lua+Luau walker — one lua module, vendored-grammar-C lua v0.4.1, tree-sitter-luau 1.2.0 pin, both default-routed (#1384)

R7b batch 4 #2 (docs/design/lua-luau-kernel-port-checklist.md is the
authoritative quirk list). ONE walker for both dialects (ccpp precedent) —
the differences are exactly four: luau's type_definition aliases, the
`export `-slice isExported hook, the return-type signature suffix, and the
grammar handle.

Grammar prep is kernel-side only, no wasm change: lua is the SECOND
vendored-grammar-C language (the vendored wasm is the v0.4.1 tag, a revision
not on crates.io — tag artifacts compiled via build.rs, shas pinned); luau
is a plain crate pin =1.2.0 whose tarball is sha-identical to the tag (the
swift tag≠crate divergence does not recur). Grammar-parity rows replace the
bump gate entirely.

Preserved bug-for-bug (all probe-pinned): the require/visitNode-hook
ASYMMETRIES (top-level requires — including inside top-level if/for/while —
mint import nodes while the identical body-level statement emits
`calls "require"`; top-level `local x = foo()` initializers are invisible
while global `x = foo()` calls emit), the BFS string-win inside require args
(`require(script:WaitForChild("Kid"))` → import Kid) and Roblox instance
paths, receiver-QN methods (`M.sub.deep::chained`, `_G::installed`,
stack-QN nested globals like `render::leakedGlobal`), the raw-text callee
world (colon forms with `self` never stripped, bracket callees,
newline-glued chains byte-verbatim, the `(handler)` paren-conversion),
LUA_SPEC function-as-value capture with the `M.cb = cb` param-storage skip
and first-occurrence dedupe, LuaDoc `---` keeping a leading `- ` plus
`--!strict` joining docstring chains (block-comment docstrings keep interior
CRLF bytes), variable nodes at the IDENTIFIER with positional value pairing,
duplicate same-(kind,name,line) ids, and the lua↔luau isExported wire
divergence (lua functions: flag absent; luau functions: present-false;
methods: absent in both; variables: present-false in both; `export type`:
true).

Gates: parity sweeps first-run 0-diff on kong/lazy.nvim/lua-resty-core
(lua) + lune/Fusion (luau) — 1,734 clean files byte-parity, deferrals
1/0/0/3/8 matching the survey's both-arm predictions exactly (kong's 1 = a
deliberately invalid fixture; luau's = grammar-inherent generic type packs
and default type params); full-init dumps byte-identical kernel-vs-wasm ×4
(kong 157,650 dump lines); kernel-lua-parity suite (both torture fixtures +
in-memory CRLF variants + glue-chain, duplicate-id, and cross-dialect defer
pins + kernel-arm wire-flag pins); full suite 2,647 green ×2 with
CODEGRAPH_KERNEL_EXPECT=1. DEFAULT_ROUTED += lua, luau (18 langs).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Colby Mchenry
2026-07-20 18:42:14 -05:00
committed by GitHub
parent b2f9ab1800
commit e32135171e
21 changed files with 15599 additions and 6 deletions
+11
View File
@@ -60,6 +60,7 @@ dependencies = [
"tree-sitter-java",
"tree-sitter-javascript",
"tree-sitter-language",
"tree-sitter-luau",
"tree-sitter-php",
"tree-sitter-python",
"tree-sitter-r",
@@ -558,6 +559,16 @@ version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009994f150cc0cd50ff54917d5bc8bffe8cad10ca10d81c34da2ec421ae61782"
[[package]]
name = "tree-sitter-luau"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871abeb427d719788bb38094facd7ff082908ef2b93c1d3d6a5f6025330120f4"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-php"
version = "0.24.2"
+5
View File
@@ -52,6 +52,11 @@ tree-sitter-swift = "=0.7.3"
# predates the ABI-15 generator) — parity asserts same-revision, not
# same-ABI (ruby precedent). Bump crate + wasm together.
tree-sitter-r = "=1.2.0"
# luau: the vendored wasm IS tree-sitter-grammars v1.2.0 and this crate's
# tarball ships parser.c/scanner.c sha-identical to the tag (8f25bc17… /
# a157bb52… — lua-luau checklist §Grammar prep). ABI 14. Lua itself is
# vendored C (build.rs) — its v0.4.1 revision is not on crates.io.
tree-sitter-luau = "=1.2.0"
# tree-sitter-language: the version-agnostic LanguageFn shim for the vendored
# kotlin grammar C (see build.rs — no kotlin crate dep is possible).
+19
View File
@@ -20,4 +20,23 @@ fn main() {
c.flag_if_supported("-utf-8"); // msvc
c.compile("tree-sitter-kotlin");
println!("cargo:rerun-if-changed=grammars/kotlin");
// Lua grammar — vendored C (second vendored-grammar-C language): the
// vendored wasm is tree-sitter-grammars/tree-sitter-lua v0.4.1 (tag
// 816840c592), which is NOT on crates.io (only 0.1/0.2/0.5 exist; 0.5.0
// adds Lua-5.5 `global` — a future bump with its own gate). Sources are
// the v0.4.1 tag's checked-in generated artifacts, sha-recorded in the
// lua-luau checklist §Grammar prep:
// parser.c b34a362e43f0311f405721f3089e94f97f31da403b154d456d093e64609a4081
// scanner.c 35bbd630b5a7421d46d2e91185eeea09bf78565d44cb676b63ca20d0f1b54bbd
let mut lua = cc::Build::new();
lua.include("grammars/lua");
lua.file("grammars/lua/parser.c");
lua.file("grammars/lua/scanner.c");
lua.flag_if_supported("-Wno-unused-parameter");
lua.flag_if_supported("-Wno-unused-but-set-variable");
lua.flag_if_supported("-Wno-trigraphs");
lua.flag_if_supported("-utf-8"); // msvc
lua.compile("tree-sitter-lua");
println!("cargo:rerun-if-changed=grammars/lua");
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021 Munif Tanjim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because it is too large Load Diff
+195
View File
@@ -0,0 +1,195 @@
#include <stdio.h>
#include "tree_sitter/alloc.h"
#include "tree_sitter/parser.h"
#include <wctype.h>
enum TokenType {
BLOCK_COMMENT_START,
BLOCK_COMMENT_CONTENT,
BLOCK_COMMENT_END,
BLOCK_STRING_START,
BLOCK_STRING_CONTENT,
BLOCK_STRING_END,
};
static inline void consume(TSLexer *lexer) { lexer->advance(lexer, false); }
static inline void skip(TSLexer *lexer) { lexer->advance(lexer, true); }
static inline bool consume_char(char c, TSLexer *lexer) {
if (lexer->lookahead != c) {
return false;
}
consume(lexer);
return true;
}
static inline uint8_t consume_and_count_char(char c, TSLexer *lexer) {
uint8_t count = 0;
while (lexer->lookahead == c) {
++count;
consume(lexer);
}
return count;
}
static inline void skip_whitespaces(TSLexer *lexer) {
while (iswspace(lexer->lookahead)) {
skip(lexer);
}
}
typedef struct {
char ending_char;
uint8_t level_count;
} Scanner;
static inline void reset_state(Scanner *scanner) {
scanner->ending_char = 0;
scanner->level_count = 0;
}
void *tree_sitter_lua_external_scanner_create() {
Scanner *scanner = ts_calloc(1, sizeof(Scanner));
return scanner;
}
void tree_sitter_lua_external_scanner_destroy(void *payload) {
Scanner *scanner = (Scanner *)payload;
ts_free(scanner);
}
unsigned tree_sitter_lua_external_scanner_serialize(void *payload, char *buffer) {
Scanner *scanner = (Scanner *)payload;
buffer[0] = scanner->ending_char;
buffer[1] = (char)scanner->level_count;
return 2;
}
void tree_sitter_lua_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {
Scanner *scanner = (Scanner *)payload;
if (length == 0) return;
scanner->ending_char = buffer[0];
if (length == 1) return;
scanner->level_count = buffer[1];
}
static bool scan_block_start(Scanner *scanner, TSLexer *lexer) {
if (consume_char('[', lexer)) {
uint8_t level = consume_and_count_char('=', lexer);
if (consume_char('[', lexer)) {
scanner->level_count = level;
return true;
}
}
return false;
}
static bool scan_block_end(Scanner *scanner, TSLexer *lexer) {
if (consume_char(']', lexer)) {
uint8_t level = consume_and_count_char('=', lexer);
if (scanner->level_count == level && consume_char(']', lexer)) {
return true;
}
}
return false;
}
static bool scan_block_content(Scanner *scanner, TSLexer *lexer) {
while (lexer->lookahead != 0) {
if (lexer->lookahead == ']') {
lexer->mark_end(lexer);
if (scan_block_end(scanner, lexer)) {
return true;
}
} else {
consume(lexer);
}
}
return false;
}
static bool scan_comment_start(Scanner *scanner, TSLexer *lexer) {
if (consume_char('-', lexer) && consume_char('-', lexer)) {
lexer->mark_end(lexer);
if (scan_block_start(scanner, lexer)) {
lexer->mark_end(lexer);
lexer->result_symbol = BLOCK_COMMENT_START;
return true;
}
}
return false;
}
static bool scan_comment_content(Scanner *scanner, TSLexer *lexer) {
if (scanner->ending_char == 0) { // block comment
if (scan_block_content(scanner, lexer)) {
lexer->result_symbol = BLOCK_COMMENT_CONTENT;
return true;
}
return false;
}
while (lexer->lookahead != 0) {
if (lexer->lookahead == scanner->ending_char) {
reset_state(scanner);
lexer->result_symbol = BLOCK_COMMENT_CONTENT;
return true;
}
consume(lexer);
}
return false;
}
bool tree_sitter_lua_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
Scanner *scanner = (Scanner *)payload;
if (valid_symbols[BLOCK_STRING_END] && scan_block_end(scanner, lexer)) {
reset_state(scanner);
lexer->result_symbol = BLOCK_STRING_END;
return true;
}
if (valid_symbols[BLOCK_STRING_CONTENT] && scan_block_content(scanner, lexer)) {
lexer->result_symbol = BLOCK_STRING_CONTENT;
return true;
}
if (valid_symbols[BLOCK_COMMENT_END] && scanner->ending_char == 0 && scan_block_end(scanner, lexer)) {
reset_state(scanner);
lexer->result_symbol = BLOCK_COMMENT_END;
return true;
}
if (valid_symbols[BLOCK_COMMENT_CONTENT] && scan_comment_content(scanner, lexer)) {
return true;
}
skip_whitespaces(lexer);
if (valid_symbols[BLOCK_STRING_START] && scan_block_start(scanner, lexer)) {
lexer->result_symbol = BLOCK_STRING_START;
return true;
}
if (valid_symbols[BLOCK_COMMENT_START]) {
if (scan_comment_start(scanner, lexer)) {
return true;
}
}
return false;
}
@@ -0,0 +1,54 @@
#ifndef TREE_SITTER_ALLOC_H_
#define TREE_SITTER_ALLOC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Allow clients to override allocation functions
#ifdef TREE_SITTER_REUSE_ALLOCATOR
extern void *(*ts_current_malloc)(size_t size);
extern void *(*ts_current_calloc)(size_t count, size_t size);
extern void *(*ts_current_realloc)(void *ptr, size_t size);
extern void (*ts_current_free)(void *ptr);
#ifndef ts_malloc
#define ts_malloc ts_current_malloc
#endif
#ifndef ts_calloc
#define ts_calloc ts_current_calloc
#endif
#ifndef ts_realloc
#define ts_realloc ts_current_realloc
#endif
#ifndef ts_free
#define ts_free ts_current_free
#endif
#else
#ifndef ts_malloc
#define ts_malloc malloc
#endif
#ifndef ts_calloc
#define ts_calloc calloc
#endif
#ifndef ts_realloc
#define ts_realloc realloc
#endif
#ifndef ts_free
#define ts_free free
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_ALLOC_H_
@@ -0,0 +1,291 @@
#ifndef TREE_SITTER_ARRAY_H_
#define TREE_SITTER_ARRAY_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "./alloc.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4101)
#elif defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#define Array(T) \
struct { \
T *contents; \
uint32_t size; \
uint32_t capacity; \
}
/// Initialize an array.
#define array_init(self) \
((self)->size = 0, (self)->capacity = 0, (self)->contents = NULL)
/// Create an empty array.
#define array_new() \
{ NULL, 0, 0 }
/// Get a pointer to the element at a given `index` in the array.
#define array_get(self, _index) \
(assert((uint32_t)(_index) < (self)->size), &(self)->contents[_index])
/// Get a pointer to the first element in the array.
#define array_front(self) array_get(self, 0)
/// Get a pointer to the last element in the array.
#define array_back(self) array_get(self, (self)->size - 1)
/// Clear the array, setting its size to zero. Note that this does not free any
/// memory allocated for the array's contents.
#define array_clear(self) ((self)->size = 0)
/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is
/// less than the array's current capacity, this function has no effect.
#define array_reserve(self, new_capacity) \
_array__reserve((Array *)(self), array_elem_size(self), new_capacity)
/// Free any memory allocated for this array. Note that this does not free any
/// memory allocated for the array's contents.
#define array_delete(self) _array__delete((Array *)(self))
/// Push a new `element` onto the end of the array.
#define array_push(self, element) \
(_array__grow((Array *)(self), 1, array_elem_size(self)), \
(self)->contents[(self)->size++] = (element))
/// Increase the array's size by `count` elements.
/// New elements are zero-initialized.
#define array_grow_by(self, count) \
do { \
if ((count) == 0) break; \
_array__grow((Array *)(self), count, array_elem_size(self)); \
memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \
(self)->size += (count); \
} while (0)
/// Append all elements from one array to the end of another.
#define array_push_all(self, other) \
array_extend((self), (other)->size, (other)->contents)
/// Append `count` elements to the end of the array, reading their values from the
/// `contents` pointer.
#define array_extend(self, count, contents) \
_array__splice( \
(Array *)(self), array_elem_size(self), (self)->size, \
0, count, contents \
)
/// Remove `old_count` elements from the array starting at the given `index`. At
/// the same index, insert `new_count` new elements, reading their values from the
/// `new_contents` pointer.
#define array_splice(self, _index, old_count, new_count, new_contents) \
_array__splice( \
(Array *)(self), array_elem_size(self), _index, \
old_count, new_count, new_contents \
)
/// Insert one `element` into the array at the given `index`.
#define array_insert(self, _index, element) \
_array__splice((Array *)(self), array_elem_size(self), _index, 0, 1, &(element))
/// Remove one element from the array at the given `index`.
#define array_erase(self, _index) \
_array__erase((Array *)(self), array_elem_size(self), _index)
/// Pop the last element off the array, returning the element by value.
#define array_pop(self) ((self)->contents[--(self)->size])
/// Assign the contents of one array to another, reallocating if necessary.
#define array_assign(self, other) \
_array__assign((Array *)(self), (const Array *)(other), array_elem_size(self))
/// Swap one array with another
#define array_swap(self, other) \
_array__swap((Array *)(self), (Array *)(other))
/// Get the size of the array contents
#define array_elem_size(self) (sizeof *(self)->contents)
/// Search a sorted array for a given `needle` value, using the given `compare`
/// callback to determine the order.
///
/// If an existing element is found to be equal to `needle`, then the `index`
/// out-parameter is set to the existing value's index, and the `exists`
/// out-parameter is set to true. Otherwise, `index` is set to an index where
/// `needle` should be inserted in order to preserve the sorting, and `exists`
/// is set to false.
#define array_search_sorted_with(self, compare, needle, _index, _exists) \
_array__search_sorted(self, 0, compare, , needle, _index, _exists)
/// Search a sorted array for a given `needle` value, using integer comparisons
/// of a given struct field (specified with a leading dot) to determine the order.
///
/// See also `array_search_sorted_with`.
#define array_search_sorted_by(self, field, needle, _index, _exists) \
_array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists)
/// Insert a given `value` into a sorted array, using the given `compare`
/// callback to determine the order.
#define array_insert_sorted_with(self, compare, value) \
do { \
unsigned _index, _exists; \
array_search_sorted_with(self, compare, &(value), &_index, &_exists); \
if (!_exists) array_insert(self, _index, value); \
} while (0)
/// Insert a given `value` into a sorted array, using integer comparisons of
/// a given struct field (specified with a leading dot) to determine the order.
///
/// See also `array_search_sorted_by`.
#define array_insert_sorted_by(self, field, value) \
do { \
unsigned _index, _exists; \
array_search_sorted_by(self, field, (value) field, &_index, &_exists); \
if (!_exists) array_insert(self, _index, value); \
} while (0)
// Private
typedef Array(void) Array;
/// This is not what you're looking for, see `array_delete`.
static inline void _array__delete(Array *self) {
if (self->contents) {
ts_free(self->contents);
self->contents = NULL;
self->size = 0;
self->capacity = 0;
}
}
/// This is not what you're looking for, see `array_erase`.
static inline void _array__erase(Array *self, size_t element_size,
uint32_t index) {
assert(index < self->size);
char *contents = (char *)self->contents;
memmove(contents + index * element_size, contents + (index + 1) * element_size,
(self->size - index - 1) * element_size);
self->size--;
}
/// This is not what you're looking for, see `array_reserve`.
static inline void _array__reserve(Array *self, size_t element_size, uint32_t new_capacity) {
if (new_capacity > self->capacity) {
if (self->contents) {
self->contents = ts_realloc(self->contents, new_capacity * element_size);
} else {
self->contents = ts_malloc(new_capacity * element_size);
}
self->capacity = new_capacity;
}
}
/// This is not what you're looking for, see `array_assign`.
static inline void _array__assign(Array *self, const Array *other, size_t element_size) {
_array__reserve(self, element_size, other->size);
self->size = other->size;
memcpy(self->contents, other->contents, self->size * element_size);
}
/// This is not what you're looking for, see `array_swap`.
static inline void _array__swap(Array *self, Array *other) {
Array swap = *other;
*other = *self;
*self = swap;
}
/// This is not what you're looking for, see `array_push` or `array_grow_by`.
static inline void _array__grow(Array *self, uint32_t count, size_t element_size) {
uint32_t new_size = self->size + count;
if (new_size > self->capacity) {
uint32_t new_capacity = self->capacity * 2;
if (new_capacity < 8) new_capacity = 8;
if (new_capacity < new_size) new_capacity = new_size;
_array__reserve(self, element_size, new_capacity);
}
}
/// This is not what you're looking for, see `array_splice`.
static inline void _array__splice(Array *self, size_t element_size,
uint32_t index, uint32_t old_count,
uint32_t new_count, const void *elements) {
uint32_t new_size = self->size + new_count - old_count;
uint32_t old_end = index + old_count;
uint32_t new_end = index + new_count;
assert(old_end <= self->size);
_array__reserve(self, element_size, new_size);
char *contents = (char *)self->contents;
if (self->size > old_end) {
memmove(
contents + new_end * element_size,
contents + old_end * element_size,
(self->size - old_end) * element_size
);
}
if (new_count > 0) {
if (elements) {
memcpy(
(contents + index * element_size),
elements,
new_count * element_size
);
} else {
memset(
(contents + index * element_size),
0,
new_count * element_size
);
}
}
self->size += new_count - old_count;
}
/// A binary search routine, based on Rust's `std::slice::binary_search_by`.
/// This is not what you're looking for, see `array_search_sorted_with` or `array_search_sorted_by`.
#define _array__search_sorted(self, start, compare, suffix, needle, _index, _exists) \
do { \
*(_index) = start; \
*(_exists) = false; \
uint32_t size = (self)->size - *(_index); \
if (size == 0) break; \
int comparison; \
while (size > 1) { \
uint32_t half_size = size / 2; \
uint32_t mid_index = *(_index) + half_size; \
comparison = compare(&((self)->contents[mid_index] suffix), (needle)); \
if (comparison <= 0) *(_index) = mid_index; \
size -= half_size; \
} \
comparison = compare(&((self)->contents[*(_index)] suffix), (needle)); \
if (comparison == 0) *(_exists) = true; \
else if (comparison < 0) *(_index) += 1; \
} while (0)
/// Helper macro for the `_sorted_by` routines below. This takes the left (existing)
/// parameter by reference in order to work with the generic sorting function above.
#define _compare_int(a, b) ((int)*(a) - (int)(b))
#ifdef _MSC_VER
#pragma warning(pop)
#elif defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_ARRAY_H_
@@ -0,0 +1,286 @@
#ifndef TREE_SITTER_PARSER_H_
#define TREE_SITTER_PARSER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#define ts_builtin_sym_error ((TSSymbol)-1)
#define ts_builtin_sym_end 0
#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024
#ifndef TREE_SITTER_API_H_
typedef uint16_t TSStateId;
typedef uint16_t TSSymbol;
typedef uint16_t TSFieldId;
typedef struct TSLanguage TSLanguage;
typedef struct TSLanguageMetadata {
uint8_t major_version;
uint8_t minor_version;
uint8_t patch_version;
} TSLanguageMetadata;
#endif
typedef struct {
TSFieldId field_id;
uint8_t child_index;
bool inherited;
} TSFieldMapEntry;
// Used to index the field and supertype maps.
typedef struct {
uint16_t index;
uint16_t length;
} TSMapSlice;
typedef struct {
bool visible;
bool named;
bool supertype;
} TSSymbolMetadata;
typedef struct TSLexer TSLexer;
struct TSLexer {
int32_t lookahead;
TSSymbol result_symbol;
void (*advance)(TSLexer *, bool);
void (*mark_end)(TSLexer *);
uint32_t (*get_column)(TSLexer *);
bool (*is_at_included_range_start)(const TSLexer *);
bool (*eof)(const TSLexer *);
void (*log)(const TSLexer *, const char *, ...);
};
typedef enum {
TSParseActionTypeShift,
TSParseActionTypeReduce,
TSParseActionTypeAccept,
TSParseActionTypeRecover,
} TSParseActionType;
typedef union {
struct {
uint8_t type;
TSStateId state;
bool extra;
bool repetition;
} shift;
struct {
uint8_t type;
uint8_t child_count;
TSSymbol symbol;
int16_t dynamic_precedence;
uint16_t production_id;
} reduce;
uint8_t type;
} TSParseAction;
typedef struct {
uint16_t lex_state;
uint16_t external_lex_state;
} TSLexMode;
typedef struct {
uint16_t lex_state;
uint16_t external_lex_state;
uint16_t reserved_word_set_id;
} TSLexerMode;
typedef union {
TSParseAction action;
struct {
uint8_t count;
bool reusable;
} entry;
} TSParseActionEntry;
typedef struct {
int32_t start;
int32_t end;
} TSCharacterRange;
struct TSLanguage {
uint32_t abi_version;
uint32_t symbol_count;
uint32_t alias_count;
uint32_t token_count;
uint32_t external_token_count;
uint32_t state_count;
uint32_t large_state_count;
uint32_t production_id_count;
uint32_t field_count;
uint16_t max_alias_sequence_length;
const uint16_t *parse_table;
const uint16_t *small_parse_table;
const uint32_t *small_parse_table_map;
const TSParseActionEntry *parse_actions;
const char * const *symbol_names;
const char * const *field_names;
const TSMapSlice *field_map_slices;
const TSFieldMapEntry *field_map_entries;
const TSSymbolMetadata *symbol_metadata;
const TSSymbol *public_symbol_map;
const uint16_t *alias_map;
const TSSymbol *alias_sequences;
const TSLexerMode *lex_modes;
bool (*lex_fn)(TSLexer *, TSStateId);
bool (*keyword_lex_fn)(TSLexer *, TSStateId);
TSSymbol keyword_capture_token;
struct {
const bool *states;
const TSSymbol *symbol_map;
void *(*create)(void);
void (*destroy)(void *);
bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist);
unsigned (*serialize)(void *, char *);
void (*deserialize)(void *, const char *, unsigned);
} external_scanner;
const TSStateId *primary_state_ids;
const char *name;
const TSSymbol *reserved_words;
uint16_t max_reserved_word_set_size;
uint32_t supertype_count;
const TSSymbol *supertype_symbols;
const TSMapSlice *supertype_map_slices;
const TSSymbol *supertype_map_entries;
TSLanguageMetadata metadata;
};
static inline bool set_contains(const TSCharacterRange *ranges, uint32_t len, int32_t lookahead) {
uint32_t index = 0;
uint32_t size = len - index;
while (size > 1) {
uint32_t half_size = size / 2;
uint32_t mid_index = index + half_size;
const TSCharacterRange *range = &ranges[mid_index];
if (lookahead >= range->start && lookahead <= range->end) {
return true;
} else if (lookahead > range->end) {
index = mid_index;
}
size -= half_size;
}
const TSCharacterRange *range = &ranges[index];
return (lookahead >= range->start && lookahead <= range->end);
}
/*
* Lexer Macros
*/
#ifdef _MSC_VER
#define UNUSED __pragma(warning(suppress : 4101))
#else
#define UNUSED __attribute__((unused))
#endif
#define START_LEXER() \
bool result = false; \
bool skip = false; \
UNUSED \
bool eof = false; \
int32_t lookahead; \
goto start; \
next_state: \
lexer->advance(lexer, skip); \
start: \
skip = false; \
lookahead = lexer->lookahead;
#define ADVANCE(state_value) \
{ \
state = state_value; \
goto next_state; \
}
#define ADVANCE_MAP(...) \
{ \
static const uint16_t map[] = { __VA_ARGS__ }; \
for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \
if (map[i] == lookahead) { \
state = map[i + 1]; \
goto next_state; \
} \
} \
}
#define SKIP(state_value) \
{ \
skip = true; \
state = state_value; \
goto next_state; \
}
#define ACCEPT_TOKEN(symbol_value) \
result = true; \
lexer->result_symbol = symbol_value; \
lexer->mark_end(lexer);
#define END_STATE() return result;
/*
* Parse Table Macros
*/
#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT)
#define STATE(id) id
#define ACTIONS(id) id
#define SHIFT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = (state_value) \
} \
}}
#define SHIFT_REPEAT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = (state_value), \
.repetition = true \
} \
}}
#define SHIFT_EXTRA() \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.extra = true \
} \
}}
#define REDUCE(symbol_name, children, precedence, prod_id) \
{{ \
.reduce = { \
.type = TSParseActionTypeReduce, \
.symbol = symbol_name, \
.child_count = children, \
.dynamic_precedence = precedence, \
.production_id = prod_id \
}, \
}}
#define RECOVER() \
{{ \
.type = TSParseActionTypeRecover \
}}
#define ACCEPT_INPUT() \
{{ \
.type = TSParseActionTypeAccept \
}}
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_PARSER_H_
+15 -2
View File
@@ -18,12 +18,17 @@ use tree_sitter::Language;
extern "C" {
fn tree_sitter_kotlin() -> *const ();
}
// Vendored lua grammar (build.rs-compiled C — the wasm's v0.4.1 revision is
// not on crates.io; see grammars/lua and the lua-luau checklist).
extern "C" {
fn tree_sitter_lua() -> *const ();
}
/// Languages this kernel binary can extract (reported by contractInfo;
/// TS-side routing policy decides what actually routes).
pub const LANGUAGES: [&str; 16] = [
pub const LANGUAGES: [&str; 18] = [
"typescript", "tsx", "javascript", "jsx", "java", "python", "go", "c", "cpp", "rust",
"csharp", "ruby", "php", "swift", "kotlin", "r",
"csharp", "ruby", "php", "swift", "kotlin", "r", "lua", "luau",
];
pub fn grammar_for(language: &str) -> Option<Language> {
@@ -60,6 +65,14 @@ pub fn grammar_for(language: &str) -> Option<Language> {
// R7b batch 4: crate =1.2.0, sha-identical to the r-lib v1.2.0 tag
// the vendored wasm was built from (r checklist §Grammar prep).
"r" => Some(tree_sitter_r::LANGUAGE.into()),
// R7b batch 4: v0.4.1 vendored C compiled in build.rs (revision not
// on crates.io — the wasm is the v0.4.1 tag, table-identical).
"lua" => {
Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_lua) }.into())
}
// R7b batch 4: crate =1.2.0, sha-identical to the v1.2.0 tag the
// vendored wasm was built from (lua-luau checklist §Grammar prep).
"luau" => Some(tree_sitter_luau::LANGUAGE.into()),
_ => None,
}
}
+2
View File
@@ -26,6 +26,7 @@ mod go;
mod java;
mod kotlin;
mod langs;
mod lua;
mod php;
mod rlang;
mod ruby;
@@ -225,6 +226,7 @@ pub fn extract_file(file_path: String, content: String, language: String) -> Res
"swift" => swift::extract(&file_path, &content).map_err(Error::from_reason)?,
"kotlin" => kotlin::extract(&file_path, &content).map_err(Error::from_reason)?,
"r" => rlang::extract(&file_path, &content).map_err(Error::from_reason)?,
"lua" | "luau" => lua::extract(&file_path, &content, &language).map_err(Error::from_reason)?,
_ => tsjs::extract(&file_path, &content, &language).map_err(Error::from_reason)?,
};
Ok(ExtractBuffers {
+846
View File
@@ -0,0 +1,846 @@
//! Lua + Luau extraction — a faithful Rust port of the lua/luau paths of
//! `TreeSitterExtractor` (src/extraction/tree-sitter.ts) plus
//! languages/lua.ts and languages/luau.ts (36 lines extending lua).
//!
//! One walker, two dialects (ccpp precedent): the differences are exactly
//! four — luau's typeAliasTypes=['type_definition'], the `export `-slice
//! isExported hook, the return-type signature suffix, and the grammar handle.
//! The authoritative quirk list is docs/design/lua-luau-kernel-port-checklist.md.
//! Load-bearing oddities preserved on purpose: the require/visitNode-hook
//! ASYMMETRIES (top-level requires — including inside top-level if/for/while
//! blocks — mint import nodes, while the identical statement in a function
//! body emits `calls "require"`; a top-level `local x = foo()` initializer
//! emits NO calls ref while a top-level global `x = foo()` does), the BFS
//! string-win inside require args (`require(script:WaitForChild("Kid"))` →
//! import "Kid"; `require("a".."b")` → import "a"), raw-text callees verbatim
//! (colon forms `M:render` with `self` never stripped, brackets `t2[k2]`,
//! newline-glued chains byte-verbatim, the `(handler)` paren-conversion),
//! receiver-QN methods (`M.sub.deep::chained`, stack-QN nested globals like
//! `render::leakedGlobal`), variable nodes positioned at the IDENTIFIER with
//! positional value pairing, LuaDoc `---` keeping a leading `- ` and
//! `--!strict` joining docstring chains, the lua↔luau isExported wire
//! divergence (lua functions: flag ABSENT; luau functions: present-false;
//! methods: absent in both; variables: present-false in both), and duplicate
//! same-(kind,name,line) ids emitted twice. Positions in UTF-16 code units.
//! Files with parse errors defer to wasm (lua ~0%; luau 1.4–7.1% both-arm).
use crate::buffers::{
build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
RefRow, Tables, FLAG_IS_EXPORTED, FUNCTION_REF_CODE, NONE, NONE_STR, StrRef,
};
use crate::docstring::preceding_docstring;
use crate::ids;
use crate::textutil as util;
use std::collections::{HashSet, VecDeque};
use tree_sitter::{Node, Parser};
/// NAME_STOPLIST (function-ref.ts).
fn is_stoplisted(name: &str) -> bool {
matches!(
name,
"this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
| "NULL" | "nullptr" | "None"
)
}
struct Scope {
row: u32,
kind: &'static str,
name: String,
}
struct Cand {
from: u32,
name: String,
line: u32,
column_byte: usize,
row: usize,
}
#[derive(Default)]
struct Extra<'a> {
docstring: Option<String>,
signature: Option<String>,
/// Some(_) sets the present bit (luau functions/type_aliases, variables
/// in both dialects); None leaves the pair absent (lua functions,
/// methods, imports).
is_exported: Option<bool>,
qualified_name_override: Option<String>,
_marker: std::marker::PhantomData<&'a ()>,
}
pub struct Walker<'t> {
src: &'t str,
file_path: &'t str,
is_luau: bool,
line_starts: Vec<usize>,
arena: Arena,
tables: Tables,
stack: Vec<Scope>,
node_ids: Vec<String>,
defined_fn_names: HashSet<String>,
imported_names: HashSet<String>,
fn_ref_cands: Vec<Cand>,
}
pub fn extract(file_path: &str, source: &str, language: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for(language).ok_or("no lua/luau grammar")?;
let t0 = std::time::Instant::now();
let mut parser = Parser::new();
parser
.set_language(&grammar)
.map_err(|e| format!("set_language({language}) failed: {e}"))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
}
let mut w = Walker {
src: source,
file_path,
is_luau: language == "luau",
line_starts: util::line_starts(source),
arena: Arena::default(),
tables: Tables::default(),
stack: Vec::new(),
node_ids: Vec::new(),
defined_fn_names: HashSet::new(),
imported_names: HashSet::new(),
fn_ref_cands: Vec::new(),
};
// File node (tree-sitter.ts:508-521).
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
let mut flags = BoolFlags::default();
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
visibility: 0,
flags,
start_line: 1,
end_line: line_count,
start_column: 0,
end_column: 0,
name: name_ref,
qualified_name: qn_ref,
id: file_id,
docstring: NONE_STR,
signature: NONE_STR,
decorators: NONE_STR,
type_parameters: NONE_STR,
return_type: NONE_STR,
extra_json: NONE_STR,
});
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
// No packageTypes → no namespace node. Value-refs are language-gated off.
w.visit(tree.root_node());
w.flush_fn_ref_candidates();
w.stack.pop();
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
meta,
nodes: w.tables.nodes,
edges: w.tables.edges,
refs: w.tables.refs,
arena: w.arena.into_vec(),
})
}
impl<'t> Walker<'t> {
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
}
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
}
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
}
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
}
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
}
fn push_ref_at(&mut self, from_row: u32, name: &str, kind: &str, node: Node) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
from_idx: from_row,
kind: edge_kind_index(kind).unwrap(),
line: self.line_of(node),
column: self.col_of(node),
reference_name: name_ref,
candidates: NONE_STR,
from_id_str: NONE_STR,
});
// flushFnRefCandidates' importedNames gate (tree-sitter.ts:661-675):
// dotted lua module paths contribute their LAST segment; simple names
// (Roblox leaves) pass whole.
if kind == "imports" {
if util::simple_name().is_match(name) {
self.imported_names.insert(name.to_string());
} else if let Some(c) = util::qualified_import().captures(name) {
self.imported_names.insert(c[1].to_string());
}
}
}
// --- createNode (tree-sitter.ts:1308) ---------------------------------
fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
if name.is_empty() {
return None;
}
let start_line = self.line_of(node);
let id = ids::node_id(self.file_path, kind, name, start_line);
// buildQualifiedName (1447-1460) — non-file stack NAMES joined `::`;
// the receiver override (extractMethod:1790-1792) replaces it whole.
let qualified = match &extra.qualified_name_override {
Some(qn) => qn.clone(),
None => {
let mut parts: Vec<&str> = Vec::new();
for s in &self.stack {
if s.kind != "file" {
parts.push(&s.name);
}
}
let mut qn = parts.join("::");
if !qn.is_empty() {
qn.push_str("::");
}
qn.push_str(name);
qn
}
};
let name_ref = self.arena.put(name);
let qn_ref = self.arena.put(&qualified);
let id_ref = self.arena.put(&id);
let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
let mut flags = BoolFlags::default();
if let Some(v) = extra.is_exported {
flags.set(FLAG_IS_EXPORTED, v);
}
let row = self.tables.push_node(&NodeRow {
kind: node_kind_index(kind).unwrap(),
visibility: 0,
flags,
start_line,
end_line: node.end_position().row as u32 + 1, // no resolveBody
start_column: self.col_of(node),
end_column: self.end_col_of(node),
name: name_ref,
qualified_name: qn_ref,
id: id_ref,
docstring: doc_ref,
signature: sig_ref,
decorators: NONE_STR,
type_parameters: NONE_STR,
return_type: NONE_STR,
extra_json: NONE_STR,
});
self.node_ids.push(id);
if kind == "function" || kind == "method" {
self.defined_fn_names.insert(name.to_string());
}
let parent_row = self.top_row();
self.tables.push_edge(&EdgeRow {
source_idx: parent_row,
target_idx: row,
kind: edge_kind_index("contains").unwrap(),
provenance: 0,
line: NONE,
column: NONE,
metadata_json: NONE_STR,
source_id_str: NONE_STR,
target_id_str: NONE_STR,
});
Some(row)
}
// --- lua.ts helper transcriptions -------------------------------------
/// findDescendant (lua.ts:9-17) — breadth-first over namedChildren.
fn find_descendant(&self, node: Node<'t>, kind: &str) -> Option<Node<'t>> {
let mut queue: VecDeque<Node<'t>> = VecDeque::new();
let mut cursor = node.walk();
for c in node.named_children(&mut cursor) {
queue.push_back(c);
}
while let Some(n) = queue.pop_front() {
if n.kind() == kind {
return Some(n);
}
let mut cur = n.walk();
for c in n.named_children(&mut cur) {
queue.push_back(c);
}
}
None
}
/// requireModule (lua.ts:28-60).
fn require_module(&self, call: Node<'t>) -> Option<String> {
let name = call.child_by_field_name("name")?;
if name.kind() != "identifier" || self.text(name) != "require" {
return None;
}
let args = call.child_by_field_name("arguments")?;
// String win: first string_content descendant, BFS order.
if let Some(content) = self.find_descendant(args, "string_content") {
let t = self.text(content).trim();
return if t.is_empty() { None } else { Some(t.to_string()) };
}
// Fallback: a string node with no content child — strip [[ ]] / quotes.
if let Some(s) = self.find_descendant(args, "string") {
let mut t = self.text(s).trim();
t = t.strip_prefix("[[").unwrap_or(t);
t = t.strip_suffix("]]").unwrap_or(t);
t = t.strip_prefix(['"', '\'']).unwrap_or(t);
t = t.strip_suffix(['"', '\'']).unwrap_or(t);
if !t.is_empty() {
return Some(t.to_string());
}
}
// Roblox instance path: trailing field/method segment.
let idx = self
.find_descendant(args, "dot_index_expression")
.or_else(|| self.find_descendant(args, "method_index_expression"));
if let Some(idx) = idx {
if let Some(field) = idx
.child_by_field_name("field")
.or_else(|| idx.child_by_field_name("method"))
{
let t = self.text(field).trim();
return if t.is_empty() { None } else { Some(t.to_string()) };
}
}
None
}
/// The hook's `emit` (lua.ts:108-126): import node at the CALL node +
/// imports ref from the stack top.
fn emit_require(&mut self, call: Node<'t>, module: &str) {
let (sig, _) = util::slice_utf16(self.text(call).trim(), 100);
let imp = self.create_node(
"import",
module,
call,
Extra { signature: Some(sig), ..Default::default() },
);
if imp.is_some() && !self.stack.is_empty() {
let parent_row = self.top_row();
self.push_ref_at(parent_row, module, "imports", call);
}
}
/// getReceiverType (lua.ts:92-99).
fn receiver_type(&self, node: Node<'t>) -> Option<&'t str> {
let name = node.child_by_field_name("name")?;
if name.kind() == "dot_index_expression" || name.kind() == "method_index_expression" {
return name.child_by_field_name("table").map(|t| self.text(t));
}
None
}
/// extractName (tree-sitter.ts:98-192) — the lua-reachable branches.
fn extract_name(&self, node: Node<'t>) -> String {
if let Some(name_node) = node.child_by_field_name("name") {
// Lua: dot/method index → the trailing field/method segment.
if name_node.kind() == "dot_index_expression" {
if let Some(f) = name_node.child_by_field_name("field") {
return self.text(f).to_string();
}
}
if name_node.kind() == "method_index_expression" {
if let Some(m) = name_node.child_by_field_name("method") {
return self.text(m).to_string();
}
}
return self.text(name_node).to_string();
}
// Fallback: first identifier-ish named child.
let mut cursor = node.walk();
for c in node.named_children(&mut cursor) {
if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
return self.text(c).to_string();
}
}
"<anonymous>".to_string()
}
/// getSignature — lua (lua.ts:83-86) / luau (luau.ts:26-35).
fn signature_of(&self, node: Node<'t>) -> Option<String> {
let params = node.child_by_field_name("parameters")?;
let mut sig = self.text(params).to_string();
if self.is_luau {
// Return type = the named child AFTER `parameters` (found by
// startIndex match), unless it's the block.
let mut cursor = node.walk();
let kids: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
if let Some(idx) = kids.iter().position(|k| k.start_byte() == params.start_byte()) {
if let Some(ret) = kids.get(idx + 1) {
if ret.kind() != "block" {
sig.push_str(": ");
sig.push_str(self.text(*ret));
}
}
}
}
Some(sig)
}
/// isExported (luau.ts:23) — the raw 7-unit slice is an ASCII prefix test.
fn is_exported_of(&self, node: Node<'t>) -> Option<bool> {
if self.is_luau {
Some(self.text(node).starts_with("export "))
} else {
None
}
}
// --- the main walk (visitNode, tree-sitter.ts:936-1303) ---------------
fn visit(&mut self, node: Node<'t>) {
let kind = node.kind();
// The visitNode hook (lua.ts:105-151) runs FIRST.
if kind == "function_call" {
if let Some(module) = self.require_module(node) {
self.emit_require(node, &module);
// Consumed → scanFnRefSubtree (tree-sitter.ts:951).
self.scan_fn_ref_subtree(node, 0);
return;
}
// falls through — extractCall claims it below
} else if kind == "variable_declaration" {
// `local x = require(...)` — dig requires out of the initializer
// the variable branch will skip. Always falls through.
let mut cursor = node.walk();
let assign = node.named_children(&mut cursor).find(|c| c.kind() == "assignment_statement");
if let Some(assign) = assign {
let mut ac = assign.walk();
let expr_list = assign.named_children(&mut ac).find(|c| c.kind() == "expression_list");
if let Some(expr_list) = expr_list {
let mut ec = expr_list.walk();
let vals: Vec<Node<'t>> = expr_list.named_children(&mut ec).collect();
for val in vals {
if val.kind() == "function_call" {
if let Some(module) = self.require_module(val) {
self.emit_require(val, &module);
}
}
}
}
}
}
// maybeCaptureFnRefs (tree-sitter.ts:990).
self.maybe_capture_fn_refs(node);
// The dispatch ladder — lua/luau rows only.
if kind == "function_declaration" {
// isInsideClassLikeNode is always false (no class-like kinds).
self.extract_function(node);
return; // skipChildren — the body walk handles children
}
if self.is_luau && kind == "type_definition" {
let skip = self.extract_type_alias(node);
if skip {
return;
}
// plain path returns false → children re-visited (the
// typeof(require(...)) alias+import pair rides this).
} else if kind == "variable_declaration" {
self.extract_variable(node);
// Initializer subtrees are never walked — candidates only.
self.scan_fn_ref_subtree(node, 0);
return; // skipChildren
} else if kind == "function_call" {
self.extract_call(node);
// no skipChildren — nested/inner calls each get their own ref
}
let mut cursor = node.walk();
let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
for child in children {
self.visit(child);
}
}
// --- extractFunction / extractMethod (1517 / 1737) --------------------
fn extract_function(&mut self, node: Node<'t>) {
// :1522 receiver short-circuit IS the method routing.
if let Some(receiver) = self.receiver_type(node) {
let receiver = receiver.to_string();
self.extract_method(node, receiver);
return;
}
let name = self.extract_name(node);
if name == "<anonymous>" {
// Unreachable for function_declaration (grammar requires a name)
// but preserved: body walked with nothing pushed.
if let Some(body) = node.child_by_field_name("body") {
self.visit_body(body);
}
return;
}
let docstring = preceding_docstring(node, self.src);
let signature = self.signature_of(node);
let is_exported = self.is_exported_of(node); // lua None / luau Some(false)
let fn_row = self.create_node(
"function",
&name,
node,
Extra { docstring, signature, is_exported, ..Default::default() },
);
let Some(row) = fn_row else { return };
// extractTypeAnnotations / extractDecoratorsFor: structurally zero
// output for lua/luau (gates + no decorator kinds in scan positions).
self.stack.push(Scope { row, kind: "function", name });
if let Some(body) = node.child_by_field_name("body") {
self.visit_body(body);
}
self.stack.pop();
}
fn extract_method(&mut self, node: Node<'t>, receiver: String) {
let name = self.extract_name(node);
let docstring = preceding_docstring(node, self.src);
let signature = self.signature_of(node);
// extractMethod passes NO isExported — absent for BOTH dialects.
// QN override (:1790-1792): `receiver::name` verbatim (namespacePrefix
// is empty outside C++).
let qn = format!("{receiver}::{name}");
let method_row = self.create_node(
"method",
&name,
node,
Extra {
docstring,
signature,
qualified_name_override: Some(qn),
..Default::default()
},
);
let Some(row) = method_row else { return };
// Owner-contains (:1799-1813) never fires: lua mints no
// struct/class/enum/trait nodes for a receiver name to match.
self.stack.push(Scope { row, kind: "method", name });
if let Some(body) = node.child_by_field_name("body") {
self.visit_body(body);
}
self.stack.pop();
}
// --- extractVariable — the lua/luau branch (2538-2549, 2789-2805) -----
fn extract_variable(&mut self, node: Node<'t>) {
// isConst absent → kind is ALWAYS `variable`; docstring from the
// DECLARATION node; isExported = hook ?? false → false for BOTH
// dialects (luau's slice sees `local …`).
let docstring = preceding_docstring(node, self.src);
let is_exported = self.is_exported_of(node).unwrap_or(false);
let mut cursor = node.walk();
let assign = node
.named_children(&mut cursor)
.find(|c| c.kind() == "assignment_statement")
.unwrap_or(node);
let mut ac = assign.walk();
let var_list = assign.named_children(&mut ac).find(|c| c.kind() == "variable_list");
let mut ec = assign.walk();
let expr_list = assign.named_children(&mut ec).find(|c| c.kind() == "expression_list");
let values: Vec<Node<'t>> = match expr_list {
Some(el) => {
let mut c = el.walk();
el.named_children(&mut c).collect()
}
None => Vec::new(),
};
let names: Vec<Node<'t>> = match var_list {
Some(vl) => {
let mut c = vl.walk();
vl.named_children(&mut c).filter(|n| n.kind() == "identifier").collect()
}
None => Vec::new(),
};
for (i, name_node) in names.iter().enumerate() {
let name = self.text(*name_node);
if name.is_empty() {
continue;
}
// Positional value pairing; a missing value → NO signature key.
let signature = values.get(i).map(|v| util::init_signature(self.text(*v)));
let name = name.to_string();
self.create_node(
"variable",
&name,
*name_node, // positioned at the IDENTIFIER
Extra {
docstring: docstring.clone(),
signature,
is_exported: Some(is_exported),
..Default::default()
},
);
}
}
// --- extractTypeAlias (2890; plain path 2967-2991) — luau only --------
/// Returns skipChildren (always false on the plain path).
fn extract_type_alias(&mut self, node: Node<'t>) -> bool {
let name = self.extract_name(node); // generic_type name → verbatim text
if name == "<anonymous>" {
return false;
}
let docstring = preceding_docstring(node, self.src);
let is_exported = self.is_exported_of(node); // Some(true) for `export type`
self.create_node(
"type_alias",
&name,
node,
Extra { docstring, is_exported, ..Default::default() },
);
// TYPE_ANNOTATION_LANGUAGES excludes luau → no alias-value refs.
false // children re-visited by the ladder
}
// --- extractCall (3684; generic tail 4313, 4518-4532, 4572-4580) ------
fn extract_call(&mut self, node: Node<'t>) {
if self.stack.is_empty() {
return;
}
let caller_row = self.top_row();
// The `function` field is NULL in this grammar → namedChild(0) (the
// `name:` child). Member branch never fires (dot/method_index aren't
// in its type list) → raw source text, then the paren-conversion.
let func = node
.child_by_field_name("function")
.or_else(|| node.named_child(0));
let Some(func) = func else { return };
let mut callee: &str = self.text(func);
if let Some(caps) = util::paren_conversion().captures(callee) {
if let Some(inner) = caps.get(1) {
callee = &callee[inner.range()];
}
}
if callee.is_empty() {
return;
}
let callee = callee.to_string();
self.push_ref_at(caller_row, &callee, "calls", node);
}
// --- visitFunctionBody (5129-5286) — the hook-free body walk ----------
fn visit_body(&mut self, node: Node<'t>) {
// maybeCaptureFnRefs (5137) fires in the body walker too.
self.maybe_capture_fn_refs(node);
let kind = node.kind();
if kind == "function_call" {
// The hook NEVER runs here — a body-level require emits
// `calls "require"` (the neovim lazy-loading idiom).
self.extract_call(node);
// falls through to recursion — chains emit every link
} else if kind == "function_declaration" {
// Nested NAMED functions (5245-5250): extractFunction walks the
// nested body itself, so return. extractName is never
// `<anonymous>` for function_declaration.
self.extract_function(node);
return;
}
// variable_declaration / type_definition have NO branch here → plain
// recursion: body-local initializers ARE walked (calls emit), no
// variable/type_alias nodes minted.
let mut cursor = node.walk();
let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
for child in children {
self.visit_body(child);
}
}
// --- function-as-value capture (#756) — LUA_SPEC ----------------------
fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
// LUA_SPEC dispatch: arguments → args; assignment_statement → rhs
// (no field — last named child; param-storage skip via namedChild(0));
// field → value (field 'value', last-named-child fallback).
let mode: &str = match node.kind() {
"arguments" => "args",
"assignment_statement" => "rhs",
"field" => "value",
_ => return,
};
if self.stack.is_empty() {
return;
}
let from = self.top_row();
let mut values: Vec<Node<'t>> = Vec::new();
match mode {
"args" => {
let mut cursor = node.walk();
for c in node.named_children(&mut cursor) {
values.push(c);
}
}
"rhs" => {
// No `field` in the rule → RHS = LAST named child (the
// expression_list). Param-storage skip: lhs =
// left/lhs/target field ?? namedChild(0) when ≥2 children;
// its trailing identifier vs the whole RHS text.
let count = node.named_child_count();
let rhs = if count > 0 { node.named_child(count - 1) } else { None };
if let Some(rhs) = rhs {
let lhs = node
.child_by_field_name("left")
.or_else(|| node.child_by_field_name("lhs"))
.or_else(|| node.child_by_field_name("target"))
.or_else(|| if count >= 2 { node.named_child(0) } else { None });
let lhs_text = lhs.map(|l| self.text(l)).unwrap_or("");
let lhs_last = util::lhs_last_name()
.captures(lhs_text)
.and_then(|c| c.get(1))
.map(|m| m.as_str());
if !(lhs_last.is_some() && lhs_last == Some(self.text(rhs).trim())) {
values.push(rhs);
}
}
}
_ => {
// value — the `value` field (keyed AND positional table
// fields carry it), falling back to the last named child.
let v = node.child_by_field_name("value").or_else(|| {
let count = node.named_child_count();
if count > 0 { node.named_child(count - 1) } else { None }
});
if let Some(v) = v {
values.push(v);
}
}
}
for v in values {
self.normalize_fn_ref_value(v, from, 0);
}
}
/// normalizeValue with LUA_SPEC's one transparent layer (expression_list
/// fans out to named children).
fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
if depth > 4 {
return;
}
match v.kind() {
"identifier" => {
let name = self.text(v).to_string();
if name.is_empty() || is_stoplisted(&name) {
return;
}
let p = v.start_position();
self.fn_ref_cands.push(Cand {
from,
name,
line: p.row as u32 + 1,
column_byte: v.start_byte(),
row: p.row,
});
}
"expression_list" => {
let mut cursor = v.walk();
let kids: Vec<Node<'t>> = v.named_children(&mut cursor).collect();
for c in kids {
self.normalize_fn_ref_value(c, from, depth + 1);
}
}
_ => {}
}
}
fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
if depth > 12 {
return;
}
// Halt at nested function definitions (their bodies are walked — and
// attributed — by extractFunction). function_definition (anonymous)
// is deliberately NOT in the halt list — the scan descends into
// anonymous initializer bodies, attributing candidates to the file.
if depth > 0
&& matches!(
node.kind(),
"function_declaration" | "arrow_function" | "function_expression"
| "lambda_literal" | "lambda_expression"
)
{
return;
}
self.maybe_capture_fn_refs(node);
let mut cursor = node.walk();
let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
for c in children {
self.scan_fn_ref_subtree(c, depth + 1);
}
}
fn flush_fn_ref_candidates(&mut self) {
let cands = std::mem::take(&mut self.fn_ref_cands);
if cands.is_empty() || util::is_generated_file(self.file_path) {
return;
}
let mut seen: HashSet<(String, String)> = HashSet::new();
for c in cands {
// Gate: same-file function/method names ∪ imported names (lua
// candidates are always bare identifiers — no `this.`/`::`).
if !c.name.starts_with("this.")
&& !c.name.contains("::")
&& !self.defined_fn_names.contains(&c.name)
&& !self.imported_names.contains(&c.name)
{
continue;
}
if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
continue;
}
let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
let name_ref = self.arena.put(&c.name);
self.tables.push_ref(&RefRow {
from_idx: c.from,
kind: FUNCTION_REF_CODE,
line: c.line,
column,
reference_name: name_ref,
candidates: NONE_STR,
from_id_str: NONE_STR,
});
}
}
}
fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
match s {
Some(s) => arena.put(s),
None => NONE_STR,
}
}