big_code_analysis_ast/roles/lua.rs
1//! Lua's role rows. The Halstead keyword roles (#1693), the
2//! paying-construct roles — `Comparison`, `ShortCircuit`, `EagerLogical`,
3//! `Ternary`, `CaseArm`, `Guard`, `NullSafe` (#1694, #1695) — the space
4//! tree (#1696) and the control flow — `Branch`, `Switch`, `Loop`,
5//! `Catch`, `ElseIf`, `Exit` (#1697) — and
6//! the documentation rows (#1699) are declared.
7
8use crate::lang_helpers::doc_comment::{
9 documents_where_it_sits, ldoc_opener, lua_group_head_above, node_bytes,
10};
11use crate::role_table;
12use crate::{Ancestors, Lua, LuaCode, Node};
13
14/// Whether an assignment names one plain or dotted target (`x = 1`,
15/// `M.x = 1`): LDoc's `get_fun_name` stops at `,`, `<` and `[`, so
16/// `local a, b = …`, `local x <const> = …` and `M[1] = …` name no item.
17fn assigns_one_name(node: &Node<'_>) -> bool {
18 // The grammar always emits the `variable_list` first, empty when
19 // recovery had to invent the target (`= 1` on its own).
20 node.child(0).is_some_and(|targets| {
21 let mut names = targets.children().filter(Node::is_named);
22 names.next().is_some_and(|name| is_dotted_name(&name)) && names.next().is_none()
23 })
24}
25
26/// An identifier, or a `.` index of one (`M.a.b`).
27fn is_dotted_name(node: &Node) -> bool {
28 node.preorder().filter(Node::is_named).all(|part| {
29 matches!(
30 part.kind_id().into(),
31 Lua::Identifier | Lua::DotIndexExpression | Lua::DotIndexExpression2
32 )
33 })
34}
35
36/// Whether a `local` declaration assigns one name (`local x = 1`, not
37/// a bare `local x`).
38fn declares_one_name(node: &Node<'_>) -> bool {
39 node.children().any(|child| {
40 matches!(
41 child.kind_id().into(),
42 Lua::AssignmentStatement | Lua::AssignmentStatement2
43 ) && assigns_one_name(&child)
44 })
45}
46
47/// Whether a table field has a name (`new = function … end`): the
48/// bracket form starts with `[` and a positional field has no `=`.
49fn field_has_a_name(node: &Node<'_>) -> bool {
50 node.child(0)
51 .is_some_and(|name| name.kind_id() == Lua::Identifier)
52 && node.child(1).is_some_and(|eq| eq.kind_id() == Lua::EQ)
53}
54
55/// Whether a `return` returns a function or a table — the module
56/// shapes LDoc documents as an item, not an exit.
57fn returns_a_function_or_table(node: &Node<'_>) -> bool {
58 node.children()
59 .find(|child| {
60 matches!(
61 child.kind_id().into(),
62 Lua::ExpressionList | Lua::ExpressionList2
63 )
64 })
65 .and_then(|list| list.children().find(Node::is_named))
66 // role-bypass: allow(Closure) — what a returned value documents
67 // as, not whether it is a closure
68 .is_some_and(|value| {
69 matches!(
70 value.kind_id().into(),
71 Lua::FunctionDefinition | Lua::TableConstructor
72 )
73 })
74}
75
76/// Whether a comment opens an LDoc block where LDoc reads one: it opens
77/// `---`, it does not sit in a function body (LDoc documents what a
78/// module declares; a `---` block in a body — LuaLS's `---@type` on a
79/// local, an LDoc `@fixme` — annotates the code there), and it is not
80/// the continuation of a `--` group that a trailing comment on the row
81/// above opened. Whether the block then *documents* — has text, and an
82/// item, a tag or the file's first position — is the content decision
83/// `Checker::is_doc_run_opener` makes over the run, which needs the
84/// sibling after it.
85fn opens_an_ldoc_block_where_ldoc_reads<'a>(
86 node: &Node<'a>,
87 code: &[u8],
88 ancestors: Ancestors<'a, '_>,
89) -> bool {
90 ldoc_opener(node_bytes(node, code))
91 && documents_where_it_sits::<LuaCode>(node, code, ancestors)
92 && lua_group_head_above::<LuaCode>(node, code, ancestors)
93 .is_none_or(|head| ldoc_opener(node_bytes(&head, code)))
94}
95
96/// Whether a `function_call` is `error(…)` or `os.exit(…)`, by the text
97/// of its `name` field. Invalid UTF-8 reads as no match.
98fn error_or_os_exit(node: &Node<'_>, code: &[u8]) -> bool {
99 node.child_by_field_name("name")
100 .is_some_and(|name| matches!(name.utf8_text(code), Some("error" | "os.exit")))
101}
102
103role_table! {
104 lang: Lua;
105 Call { owns [FunctionCall] }
106 StringLit { owns [String] }
107 // The one `binary_expression` kind carries every binary operator;
108 // its `operator` field says which, so the owner is gated on the
109 // field. `~=` is Lua's inequality. `<` / `>` are gated to that
110 // parent for a token error recovery strands; the rest occur
111 // nowhere else.
112 Comparison {
113 owns [BinaryExpression(holds_payer)]
114 pays [
115 EQEQ, TILDEEQ, LTEQ, GTEQ,
116 LT under BinaryExpression, GT under BinaryExpression,
117 ]
118 project "operator"
119 }
120 // `and` / `or`, the word spellings, each a kind of its own that
121 // occurs only as a `binary_expression`'s operator.
122 ShortCircuit {
123 owns [BinaryExpression(holds_payer)]
124 pays [And, Or]
125 project "operator"
126 }
127 EagerLogical { absent "Lua's `and` / `or` are lazy; it has no eager boolean operator" }
128 Ternary { absent "Lua has no ternary expression; `a and b or c` is a chain" }
129 NullSafe { absent "Lua has no optional navigation or null coalescing" }
130 CaseArm { absent "Lua has no switch-like construct" }
131 Guard { absent "Lua has no guard clause" }
132 // Lua counts statement nodes, so every row here is plain (#1697).
133 Branch { owns [IfStatement] }
134 Switch { absent "Lua has no switch-like construct" }
135 // The numeric and generic `for` are one `for_statement`; `repeat …
136 // until` is a loop with its test at the end.
137 Loop { owns [ForStatement, WhileStatement, RepeatStatement] }
138 Catch { absent "Lua has no exception handling; `pcall` is a call" }
139 // The grammar gives `elseif` a statement node of its own, a direct
140 // child of the `if_statement`, so the clause *is* the else-if and pays
141 // for itself; no nested `if` is ever an else-if here.
142 ElseIf { owns [ElseifStatement(pays_itself)] pays [] }
143 // `return`, and the abrupt-exit builtins `error(…)` (unwinds to the
144 // nearest `pcall`) and `os.exit(…)`, each a `function_call` whose
145 // `name` field spells the callee — `error` a bare identifier,
146 // `os.exit` a `dot_index_expression` — told by text, so a user `foo()`
147 // or `myError()` is not counted.
148 Exit { owns [ReturnStatement, FunctionCall(text_gated_by error_or_os_exit no_chain)] }
149 Modifier { absent "Lua has no modifier keywords; `local` is a declaration" }
150 // `local` and `function`, each a leaf under an unlisted
151 // `function_declaration` / `variable_declaration` / `function_definition`.
152 DeclKeyword { owns [Local, Function] }
153 Primitive { absent "Lua has no type names" }
154 // The three aliased `function_declaration` ids (`function f`,
155 // `function M.f`, `local function f`) are the callables; an
156 // anonymous `function () … end` is the closure and opens a space.
157 FuncOpener {
158 owns [
159 FunctionDeclaration(callable opens Function),
160 FunctionDeclaration2(callable opens Function),
161 FunctionDeclaration3(callable opens Function),
162 FunctionDefinition(opens Function),
163 ]
164 }
165 Closure { owns [FunctionDefinition] }
166 Container { owns [Chunk(opens Unit)] }
167 Member { absent "Lua has no container to hold a member" }
168 // The one comment kind. LDoc marks a *block* by its opener (`---`)
169 // and continues it over the `--` rows below: documentation is a
170 // property of the run, decided once at its opener (`DocRunOpener`),
171 // so no single comment is a `DocComment` by itself (#1699).
172 Comment { owns [Comment] }
173 DocComment { absent "an LDoc block is documentation as a run opened by `---`, never one comment by a marker" }
174 Docstring { absent "Lua documents with LDoc comments, not string literals" }
175 // What LDoc's `item_follows` (`lang.lua`) documents under a block: a
176 // `function` statement, local or not (three aliased ids); an
177 // assignment to one plain or dotted name, local or not; a table
178 // field with a name; a `return` of a function or a table. Read by
179 // the content decision in `Checker::is_doc_run_opener` of the
180 // statement after a block — *not* by `Checker::is_doc_target`,
181 // which stays the trait default: LDoc attaches nothing to a
182 // declaration a plain `--` run precedes, and forwarding this row
183 // there would let one document. Every target here is a positional
184 // item, none a space-tree member — the parity exceptions
185 // `roles/doc_tests/parity.rs` records.
186 DocTarget {
187 owns [
188 FunctionDeclaration,
189 FunctionDeclaration2,
190 FunctionDeclaration3,
191 AssignmentStatement(gated_by assigns_one_name no_chain),
192 AssignmentStatement2(gated_by assigns_one_name no_chain),
193 VariableDeclaration(gated_by declares_one_name no_chain),
194 VariableDeclaration2(gated_by declares_one_name no_chain),
195 Field(gated_by field_has_a_name no_chain),
196 ReturnStatement(gated_by returns_a_function_or_table no_chain),
197 ]
198 }
199 // The opener candidate: a `---` comment where LDoc reads one. The
200 // Checker decides the rest of the run's content.
201 DocRunOpener { owns [Comment(text_gated_by opens_an_ldoc_block_where_ldoc_reads)] }
202 DocRunDirective { absent "LDoc reads no directive comment" }
203 DocBodyResidual { absent "only the functions hold an LDoc block in a body; the trait default" }
204}