Skip to main content

aft_parse/
luau.rs

1//! Extraction for the pinned Luau grammar, independent of file discovery.
2
3use std::collections::{BTreeMap, HashMap};
4
5use tree_sitter::Node;
6
7use crate::imports::{ImportBlock, ImportForm, ImportGroup, ImportKind, ImportStatement};
8use crate::symbols::SymbolKind;
9
10pub const LUAU_EXTRACTOR_VERSION: u32 = 3;
11
12pub(crate) fn extractor_version() -> u32 {
13    #[cfg(feature = "test-hooks")]
14    {
15        static VERSION: std::sync::LazyLock<u32> = std::sync::LazyLock::new(|| {
16            std::env::var("AFT_TEST_GRAMMAR_EXTRACTOR_VERSION")
17                .ok()
18                .map(|v| v.parse().expect("test extractor version"))
19                .unwrap_or(LUAU_EXTRACTOR_VERSION)
20        });
21        *VERSION
22    }
23    #[cfg(not(feature = "test-hooks"))]
24    LUAU_EXTRACTOR_VERSION
25}
26
27// Validate the syntax used by extraction before marking the Luau grammar ready.
28// The grammar registry reads these on every target that builds downloaded
29// grammars, Windows ARM64 included.
30#[cfg(feature = "wasm-grammars")]
31pub const EXTRACTION_QUERY: &str = r#"
32[(function_declaration name: (_) @name)
33 (local_function_declaration name: (identifier) @name)
34 (local_variable_declaration (binding_list (binding name: (identifier) @name)))
35 (assignment_statement (variable_list) (expression_list))
36 (type_alias_declaration name: (type_identifier) @name)
37 (function_definition) (table_constructor (field))
38 (return_statement) (function_call name: (_) arguments: (arguments))] @declaration
39"#;
40#[cfg(feature = "wasm-grammars")]
41pub const COMPLEXITY_QUERY: &str = r#"
42[(function_declaration) (local_function_declaration) (function_definition)
43 (if_statement) (elseif_statement) (if_else_expression) (elseif_expression)
44 (for_statement) (while_statement) (repeat_statement) (binary_expression)] @complexity
45"#;
46#[cfg(feature = "wasm-grammars")]
47pub const COMMENT_QUERY: &str = "(comment content: (comment_content) @content) @comment";
48pub const COMMENT_KINDS: &[&str] = &["comment"];
49
50pub fn nodes(root: Node<'_>) -> Vec<Node<'_>> {
51    let mut result = Vec::new();
52    let mut cursor = root.walk();
53    loop {
54        result.push(cursor.node());
55        if cursor.goto_first_child() {
56            continue;
57        }
58        while !cursor.goto_next_sibling() {
59            if !cursor.goto_parent() {
60                return result;
61            }
62        }
63    }
64}
65
66fn text<'a>(source: &'a str, node: Node<'_>) -> &'a str {
67    &source[node.byte_range()]
68}
69
70fn child<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
71    node.named_children(&mut node.walk())
72        .find(|n| n.kind() == kind)
73}
74
75fn single(node: Node<'_>) -> Option<Node<'_>> {
76    (node.named_child_count() == 1)
77        .then(|| node.named_child(0))
78        .flatten()
79}
80
81pub fn local_pair(node: Node<'_>) -> Option<(Node<'_>, Node<'_>)> {
82    let binding = single(child(node, "binding_list")?)?;
83    Some((
84        binding.child_by_field_name("name")?,
85        single(child(node, "expression_list")?)?,
86    ))
87}
88
89pub fn assignment_pairs(node: Node<'_>) -> Vec<(Node<'_>, Option<Node<'_>>)> {
90    let Some(left) = child(node, "variable_list") else {
91        return Vec::new();
92    };
93    let right = child(node, "expression_list");
94    left.named_children(&mut left.walk())
95        .enumerate()
96        .map(|(i, name)| (name, right.and_then(|r| r.named_child(i as u32))))
97        .collect()
98}
99
100/// Value-flow follows only one plain binding, not parallel assignments.
101pub fn single_assignment_pair(node: Node<'_>) -> Option<(Node<'_>, Node<'_>)> {
102    let value = single(child(node, "expression_list")?)?;
103    let pairs = assignment_pairs(node);
104    match pairs.as_slice() {
105        [(name, Some(_))] if name.kind() == "identifier" => Some((*name, value)),
106        _ => None,
107    }
108}
109
110fn member<'source, 'tree>(
111    source: &'source str,
112    node: Node<'tree>,
113) -> Option<(&'source str, Node<'tree>)> {
114    if !matches!(
115        node.kind(),
116        "dot_index_expression" | "method_index_expression"
117    ) {
118        return None;
119    }
120    let table = node.child_by_field_name("table")?;
121    let name = node
122        .child_by_field_name("field")
123        .or_else(|| node.child_by_field_name("method"))?;
124    Some((text(source, table), name))
125}
126
127pub struct Declaration<'a> {
128    pub name: Node<'a>,
129    pub definition: Node<'a>,
130    pub kind: SymbolKind,
131    pub parent: Option<String>,
132    pub exported: bool,
133}
134
135pub fn declarations<'a>(source: &str, root: Node<'a>) -> Vec<Declaration<'a>> {
136    let mut declarations = Vec::new();
137    for node in nodes(root) {
138        match node.kind() {
139            "function_declaration" | "local_function_declaration" => {
140                let Some(name) = node.child_by_field_name("name") else {
141                    continue;
142                };
143                let (parent, name) = member(source, name)
144                    .map(|(parent, name)| (Some(parent.to_string()), name))
145                    .unwrap_or((None, name));
146                declarations.push(Declaration {
147                    name,
148                    definition: node,
149                    kind: if parent.is_some() {
150                        SymbolKind::Method
151                    } else {
152                        SymbolKind::Function
153                    },
154                    parent,
155                    exported: true,
156                });
157            }
158            "assignment_statement" => {
159                for (left, right) in assignment_pairs(node) {
160                    if !right.is_some_and(|r| r.kind() == "function_definition") {
161                        continue;
162                    }
163                    if let Some((parent, name)) = member(source, left) {
164                        declarations.push(Declaration {
165                            name,
166                            definition: node,
167                            kind: SymbolKind::Method,
168                            parent: Some(parent.to_string()),
169                            exported: true,
170                        });
171                    }
172                }
173            }
174            "local_variable_declaration" if node.parent() == Some(root) => {
175                if let Some(bindings) = child(node, "binding_list") {
176                    for binding in bindings.named_children(&mut bindings.walk()) {
177                        if let Some(name) = binding.child_by_field_name("name") {
178                            declarations.push(Declaration {
179                                name,
180                                definition: node,
181                                kind: SymbolKind::Variable,
182                                parent: None,
183                                exported: true,
184                            });
185                        }
186                    }
187                }
188            }
189            "type_alias_declaration" => {
190                if let Some(name) = node.child_by_field_name("name") {
191                    declarations.push(Declaration {
192                        name,
193                        definition: node,
194                        kind: SymbolKind::TypeAlias,
195                        parent: None,
196                        exported: text(source, node).starts_with("export"),
197                    });
198                }
199            }
200            _ => {}
201        }
202    }
203    declarations
204}
205
206/// A literal string without escape interpretation. Escaped paths are deliberately
207/// unresolved rather than risking a different filename from Luau's interpretation.
208fn literal(source: &str, node: Node<'_>) -> Option<String> {
209    if node.kind() != "string" {
210        return None;
211    }
212    let value = text(source, node);
213    let quote = value.chars().next()?;
214    if !matches!(quote, '\'' | '"') || !value.ends_with(quote) || value.len() < 2 {
215        return None;
216    }
217    let value = &value[1..value.len() - 1];
218    (!value.contains('\\')).then(|| value.to_string())
219}
220
221// None is the Parent property; Some is a literal child lookup.
222fn script_steps(source: &str, mut node: Node<'_>) -> Option<Vec<Option<String>>> {
223    let mut steps = Vec::new();
224    loop {
225        if node.kind() == "identifier" && text(source, node) == "script" {
226            steps.reverse();
227            return Some(steps);
228        }
229        let (table, step) = match node.kind() {
230            "dot_index_expression" => {
231                let field = text(source, node.child_by_field_name("field")?);
232                (
233                    node.child_by_field_name("table")?,
234                    (field != "Parent").then(|| field.to_string()),
235                )
236            }
237            "bracket_index_expression" => (
238                node.child_by_field_name("table")?,
239                Some(literal(source, node.child_by_field_name("field")?)?),
240            ),
241            "function_call" => {
242                let callee = node.child_by_field_name("name")?;
243                if callee.kind() != "method_index_expression"
244                    || !matches!(
245                        text(source, callee.child_by_field_name("method")?),
246                        "WaitForChild" | "FindFirstChild"
247                    )
248                {
249                    return None;
250                }
251                (
252                    callee.child_by_field_name("table")?,
253                    Some(literal(
254                        source,
255                        single(node.child_by_field_name("arguments")?)?,
256                    )?),
257                )
258            }
259            _ => return None,
260        };
261        steps.push(step);
262        node = table;
263    }
264}
265
266pub const SCRIPT_PREFIX: &str = "__luau_script:";
267
268pub fn imports(source: &str, root: Node<'_>) -> ImportBlock {
269    let all = nodes(root);
270    let mut imports = Vec::new();
271    for &node in &all {
272        if node.kind() != "function_call"
273            || !node
274                .child_by_field_name("name")
275                .is_some_and(|n| n.kind() == "identifier" && text(source, n) == "require")
276        {
277            continue;
278        }
279        let Some(argument) = node.child_by_field_name("arguments").and_then(single) else {
280            continue;
281        };
282        let module_path = literal(source, argument)
283            .map(|path| {
284                if path.starts_with(SCRIPT_PREFIX) {
285                    format!("!{path}")
286                } else {
287                    path
288                }
289            })
290            .or_else(|| {
291                script_steps(source, argument).map(|steps| {
292                    format!(
293                        "{SCRIPT_PREFIX}{}",
294                        serde_json::to_string(&steps).expect("script steps")
295                    )
296                })
297            })
298            .unwrap_or_else(|| text(source, argument).to_string());
299        let statement = node
300            .parent()
301            .filter(|n| n.kind() == "expression_list")
302            .and_then(|n| n.parent())
303            .filter(|n| n.kind() == "local_variable_declaration");
304        let binding = statement
305            .and_then(local_pair)
306            .filter(|(_, value)| *value == node)
307            .map(|(name, _)| text(source, name).to_string())
308            .filter(|name| !reassigned(source, &all, name))
309            .filter(|name| {
310                statement.is_some_and(|declaration| {
311                    binding_covers_calls(source, &all, declaration, name)
312                })
313            });
314        let span = statement.unwrap_or(node);
315        imports.push(ImportStatement {
316            module_path,
317            names: Vec::new(),
318            default_import: binding.clone(),
319            namespace_import: None,
320            kind: if binding.is_some() {
321                ImportKind::Value
322            } else {
323                ImportKind::SideEffect
324            },
325            group: ImportGroup::Internal,
326            byte_range: span.byte_range(),
327            raw_text: text(source, span).to_string(),
328            form: ImportForm::Structured {
329                named: Vec::new(),
330                namespace: None,
331                alias: binding,
332                modifiers: Vec::new(),
333                import_kind: None,
334            },
335        });
336    }
337    let byte_range = imports
338        .first()
339        .zip(imports.last())
340        .map(|(a, b)| a.byte_range.start..b.byte_range.end);
341    ImportBlock {
342        imports,
343        byte_range,
344    }
345}
346
347fn binding_covers_calls(source: &str, all: &[Node<'_>], declaration: Node<'_>, name: &str) -> bool {
348    let Some(scope) = declaration.parent() else {
349        return false;
350    };
351    // References retain a local's name rather than its lexical scope. Keep a
352    // binding only when every matching member call can see that declaration;
353    // otherwise resolution could mistake a same-named global for the imported local.
354    all.iter()
355        .filter(|n| n.kind() == "function_call")
356        .filter(|n| {
357            n.child_by_field_name("name")
358                .and_then(|n| member(source, n))
359                .is_some_and(|(owner, _)| owner == name)
360        })
361        .all(|call| {
362            if call.start_byte() < declaration.end_byte() {
363                return false;
364            }
365            let mut ancestor = call.parent();
366            while let Some(node) = ancestor {
367                if node == scope {
368                    return true;
369                }
370                ancestor = node.parent();
371            }
372            false
373        })
374}
375
376fn reassigned(source: &str, all: &[Node<'_>], name: &str) -> bool {
377    let declarations = all
378        .iter()
379        .filter(|n| {
380            matches!(n.kind(), "binding" | "local_function_declaration")
381                && n.child_by_field_name("name")
382                    .is_some_and(|n| text(source, n) == name)
383        })
384        .count();
385    declarations > 1
386        || all.iter().any(|&n| match n.kind() {
387            "function_declaration" => n
388                .child_by_field_name("name")
389                .is_some_and(|left| left.kind() == "identifier" && text(source, left) == name),
390            "assignment_statement" => assignment_pairs(n)
391                .iter()
392                .any(|(left, _)| left.kind() == "identifier" && text(source, *left) == name),
393            "compound_assignment_statement" => n
394                .child_by_field_name("left")
395                .is_some_and(|left| text(source, left) == name),
396            _ => false,
397        })
398}
399
400pub struct Export<'a> {
401    pub symbol: String,
402    pub inline: Option<Declaration<'a>>,
403}
404
405fn chunk_level(mut node: Node<'_>, root: Node<'_>) -> bool {
406    while let Some(parent) = node.parent() {
407        if parent == root {
408            return true;
409        }
410        if matches!(
411            parent.kind(),
412            "function_declaration" | "local_function_declaration" | "function_definition"
413        ) {
414            return false;
415        }
416        node = parent;
417    }
418    false
419}
420
421/// Only the final, unconditional chunk return defines the module surface. Count
422/// writes before choosing functions: a later nil assignment is not an export.
423pub fn exports<'a>(source: &str, root: Node<'a>) -> BTreeMap<String, Export<'a>> {
424    if root.has_error() {
425        return BTreeMap::new();
426    }
427    let all = nodes(root);
428    let returns = all
429        .iter()
430        .copied()
431        .filter(|&n| n.kind() == "return_statement" && chunk_level(n, root))
432        .collect::<Vec<_>>();
433    if returns.len() != 1 {
434        return BTreeMap::new();
435    }
436    let ret = returns[0];
437    if ret.parent() != Some(root)
438        || root
439            .named_children(&mut root.walk())
440            .filter(|n| n.kind() != "comment")
441            .last()
442            != Some(ret)
443    {
444        return BTreeMap::new();
445    }
446    let Some(value) = child(ret, "expression_list").and_then(single) else {
447        return BTreeMap::new();
448    };
449    let (table_name, table) = match value.kind() {
450        "table_constructor" => (None, value),
451        "identifier" => {
452            let name = text(source, value);
453            let locals = root
454                .named_children(&mut root.walk())
455                .filter(|n| n.kind() == "local_variable_declaration")
456                .filter_map(local_pair)
457                .filter(|(n, _)| text(source, *n) == name)
458                .collect::<Vec<_>>();
459            if locals.len() != 1
460                || locals[0].1.kind() != "table_constructor"
461                || reassigned(source, &all, name)
462            {
463                return BTreeMap::new();
464            }
465            (Some(name), locals[0].1)
466        }
467        _ => return BTreeMap::new(),
468    };
469    let functions = root
470        .named_children(&mut root.walk())
471        .filter(|n| n.kind() == "local_function_declaration")
472        .filter_map(|n| {
473            n.child_by_field_name("name")
474                .map(|name| (text(source, name), n))
475        })
476        .collect::<HashMap<_, _>>();
477    let parent = table_name.unwrap_or("<return>");
478    let mut writes = BTreeMap::<String, Vec<Option<Export<'a>>>>::new();
479    for field in table
480        .named_children(&mut table.walk())
481        .filter(|n| n.kind() == "field")
482    {
483        let Some(name) = field.child_by_field_name("name") else {
484            continue;
485        };
486        // A computed key may alias any named member. Do not guess its value.
487        if name.kind() != "field_identifier" {
488            return BTreeMap::new();
489        }
490        let name_text = text(source, name).to_string();
491        let export = field.child_by_field_name("value").and_then(|value| {
492            if value.kind() == "function_definition" {
493                Some(Export {
494                    symbol: format!("{parent}::{name_text}"),
495                    inline: Some(Declaration {
496                        name,
497                        definition: value,
498                        kind: SymbolKind::Method,
499                        parent: Some(parent.to_string()),
500                        exported: false,
501                    }),
502                })
503            } else if value.kind() == "identifier"
504                && functions.contains_key(text(source, value))
505                && !reassigned(source, &all, text(source, value))
506            {
507                Some(Export {
508                    symbol: text(source, value).to_string(),
509                    inline: None,
510                })
511            } else {
512                None
513            }
514        });
515        writes.entry(name_text).or_default().push(export);
516    }
517    if let Some(table_name) = table_name {
518        for &node in &all {
519            match node.kind() {
520                "function_declaration" => {
521                    let Some(name) = node.child_by_field_name("name") else {
522                        continue;
523                    };
524                    if let Some((owner, name)) = member(source, name) {
525                        if owner == table_name {
526                            let key = text(source, name).to_string();
527                            let export = (node.parent() == Some(root)).then(|| Export {
528                                symbol: format!("{owner}::{key}"),
529                                inline: None,
530                            });
531                            writes.entry(key).or_default().push(export);
532                        }
533                    }
534                }
535                "assignment_statement" => {
536                    for (left, right) in assignment_pairs(node) {
537                        if left.kind() == "bracket_index_expression"
538                            && left
539                                .child_by_field_name("table")
540                                .is_some_and(|t| text(source, t) == table_name)
541                        {
542                            return BTreeMap::new();
543                        }
544                        if let Some((owner, name)) = member(source, left) {
545                            if owner == table_name {
546                                let key = text(source, name).to_string();
547                                let export = (node.parent() == Some(root)
548                                    && right.is_some_and(|r| r.kind() == "function_definition"))
549                                .then(|| Export {
550                                    symbol: format!("{owner}::{key}"),
551                                    inline: None,
552                                });
553                                writes.entry(key).or_default().push(export);
554                            }
555                        }
556                    }
557                }
558                "compound_assignment_statement" => {
559                    if let Some((owner, name)) = node
560                        .child_by_field_name("left")
561                        .and_then(|n| member(source, n))
562                    {
563                        if owner == table_name {
564                            writes
565                                .entry(text(source, name).to_string())
566                                .or_default()
567                                .push(None);
568                        }
569                    }
570                }
571                _ => {}
572            }
573        }
574    }
575    writes
576        .into_iter()
577        .filter_map(|(name, mut entries)| {
578            (entries.len() == 1)
579                .then(|| entries.pop().flatten())
580                .flatten()
581                .map(|export| (name, export))
582        })
583        .collect()
584}