bonsai-ninja-lang-lua 0.3.1

Lua language adapter.
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
//! P1.2: Lua module-table return idiom. `local M = {}; ...; return M`
//! declares `M` as the file's exported surface. Functions attached to
//! the table (`function M.foo(...)`) keep `Public`; sibling top-level
//! free functions become `Visibility::Module` so the resolver narrows
//! cross-file candidate sets.

use bonsai_db::AnalyzerDb;
use bonsai_lang_api::{CallKind, FlowEvent, ImportScope, LanguageRegistry, Visibility};
use bonsai_vfs::Vfs;
use std::sync::Arc;

fn db_with(source: &str) -> AnalyzerDb {
    let vfs = Arc::new(Vfs::new());
    vfs.write("m.lua".to_string(), Arc::<str>::from(source));
    let registry = Arc::new(LanguageRegistry::new());
    registry.register(Arc::new(bonsai_lang_lua::LuaAdapter::new()));
    let db = AnalyzerDb::new(vfs, registry);
    for f in db.vfs().all_files() {
        let _ = db.decl_index(f);
    }
    db
}

fn visibility_of(db: &AnalyzerDb, name: &str) -> Visibility {
    let g = db.global_index();
    g.find_by_name(name)
        .iter()
        .find_map(|s| g.decl_of(*s).cloned())
        .map(|d| d.visibility)
        .unwrap_or(Visibility::Public)
}

#[test]
fn module_table_export_marks_unlisted_globals_module_private() {
    let src = r#"
local M = {}
function M.public_fn(x) return x end
function exposed_global(x) return M.public_fn(x) end
return M
"#;
    let db = db_with(src);
    assert_eq!(
        visibility_of(&db, "public_fn"),
        Visibility::Public,
        "M.public_fn is exported via the module table"
    );
    assert_eq!(
        visibility_of(&db, "exposed_global"),
        Visibility::Module,
        "free top-level function not on M is module-private"
    );
}

#[test]
fn no_module_return_keeps_default_public() {
    // Files without `return M` (script-style files, top-level
    // statements) keep the default visibility — narrowing is gated
    // on the module-export idiom being present.
    let src = r#"
function exposed_global(x) return x end
print(exposed_global("hi"))
"#;
    let db = db_with(src);
    assert_eq!(
        visibility_of(&db, "exposed_global"),
        Visibility::Public,
        "files without `return M` skip the narrowing"
    );
}

#[test]
fn computed_return_skips_narrowing() {
    // `return setmetatable(M, {})` is not a bare-identifier return;
    // we don't try to resolve metatable-wrapped exports.
    let src = r#"
local M = {}
function M.api(x) return x end
function helper_global(x) return x end
return setmetatable(M, {})
"#;
    let db = db_with(src);
    assert_eq!(
        visibility_of(&db, "helper_global"),
        Visibility::Public,
        "non-bare-identifier return falls open"
    );
}

#[test]
fn local_function_remains_private() {
    // `local function` is already chunk-private. The module-export
    // narrowing should not change that.
    let src = r#"
local M = {}
function M.api(x) return helper(x) end
local function helper(x) return x end
return M
"#;
    let db = db_with(src);
    assert_eq!(
        visibility_of(&db, "helper"),
        Visibility::Private,
        "local functions stay Private (chunk-scoped)"
    );
    assert_eq!(visibility_of(&db, "api"), Visibility::Public);
}

#[test]
fn module_table_export_binding_is_resolver_only_import_scope() {
    let src = r#"
local M = {}
function M.api(x) return x end
return M
"#;
    let db = db_with(src);
    let file = db.vfs().all_files()[0];
    let imports = db.imports_for(file);

    assert!(
        imports.iter().any(|imp| {
            imp.module == "m"
                && imp.alias.as_deref() == Some("M")
                && !imp.is_wildcard
                && imp.scope == ImportScope::Local
        }),
        "Lua module table export must stay as resolver-only local binding: {imports:?}"
    );
    assert!(
        !imports.iter().any(|imp| {
            imp.module == "m" && imp.alias.as_deref() == Some("M") && imp.scope == ImportScope::Module
        }),
        "Lua module table export is not an import statement and must not be Module-scope: {imports:?}"
    );
}

#[test]
fn anonymous_function_decl_uses_local_binding_name() {
    let db = db_with("function entry(args)\n  local f = function(x) sink(x) end\n  f(args)\nend\n");
    let global = db.global_index();
    let block = global
        .find_by_name("f")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .unwrap_or_else(|| {
            panic!("anonymous function must be indexed as local binding `f`; global: {global:?}")
        });

    assert_eq!(block.params, ["x"]);
    assert!(
        block.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Call { name, .. } if name == "sink"
        )),
        "anonymous function declaration must own sink(x); got {:?}",
        block.flow_events
    );
}

#[test]
fn dotted_table_call_keeps_explicit_receiver_argument() {
    let db = db_with(
        "local Box = {}\nfunction Box.method(self, p) sink(p) end\nfunction entry(args) Box.method(Box, args) end\n",
    );
    let global = db.global_index();
    let entry = global
        .find_by_name("entry")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("entry declaration");

    assert!(entry.flow_events.iter().any(|event| matches!(
        event,
        FlowEvent::Call {
            name,
            receiver,
            receiver_types,
            call_kind: CallKind::Function,
            args,
            ..
        } if name == "Box.method"
            && receiver.is_none()
            && receiver_types.is_empty()
            && args.len() == 2
    )));
    let method = global
        .find_by_name("method")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("table member declaration");
    assert_eq!(
        method.qualified_name.as_deref(),
        Some("Box.method"),
        "the Tree-sitter declaration owner must survive into semantic identity"
    );
}

#[test]
fn colon_call_preserves_implicit_receiver_while_dot_call_does_not() {
    let db =
        db_with("function entry(resource, Namespace)\n  resource:close()\n  Namespace.open(resource)\nend\n");
    let global = db.global_index();
    let entry = global
        .find_by_name("entry")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("entry declaration");

    assert!(
        entry.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Call {
                name,
                receiver: Some(receiver),
                call_kind: CallKind::Method,
                ..
            } if name == "resource.close" && receiver == "resource"
        )),
        "events={:?}",
        entry.flow_events
    );
    assert!(
        entry.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Call {
                name,
                receiver: None,
                call_kind: CallKind::Function,
                ..
            } if name == "Namespace.open"
        )),
        "events={:?}",
        entry.flow_events
    );
}

#[test]
fn static_bracket_assignment_keeps_the_complete_table_place() {
    let db = db_with(
        "function handle(input)\n  ngx.header[\"X-User\"] = input\n  ngx.header.Location = input\nend\n",
    );
    let global = db.global_index();
    let handle = global
        .find_by_name("handle")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("handle declaration");

    for expected in ["ngx.header.X-User", "ngx.header.Location"] {
        assert!(
            handle.flow_events.iter().any(|event| matches!(
                event,
                FlowEvent::Assign { target, source_name: Some(source), .. }
                    if target == expected && source == "input"
            )),
            "missing exact assignment place {expected}: {:?}",
            handle.flow_events
        );
    }
}

#[test]
fn factory_receiver_field_write_uses_exact_member_assignment() {
    let db = db_with(
        "local Repo = {}\nfunction Repo.new(conn)\n  local self = setmetatable({}, Repo)\n  self.conn = conn\n  return self\nend\nreturn Repo\n",
    );
    let global = db.global_index();
    let constructor = global
        .find_by_name("new")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("Repo.new declaration");

    assert_eq!(
        constructor.kind,
        bonsai_lang_api::DeclKind::Constructor,
        "a receiver-writing factory that returns that receiver is constructor syntax"
    );

    assert!(
        constructor.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Assign {
                target,
                source_name: Some(source),
                ..
            } if target == "self.conn" && source == "conn"
        )),
        "Lua member assignment must retain self.conn <- conn: {:#?}",
        constructor.flow_events
    );
    assert!(
        constructor
            .receiver_field_writes
            .iter()
            .any(|write| { write.target == "self.conn" && write.source_param_indices == [0] }),
        "Lua factory must summarize receiver state from its parsed member assignment; params={:?}, writes={:#?}",
        constructor.params,
        constructor.receiver_field_writes
    );
}

#[test]
fn receiver_mutator_without_receiver_return_is_not_a_constructor() {
    let db =
        db_with("local Repo = {}\nfunction Repo.capture(self, conn)\n  self.conn = conn\nend\nreturn Repo\n");
    let global = db.global_index();
    let capture = global
        .find_by_name("capture")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("Repo.capture declaration");

    assert_ne!(capture.kind, bonsai_lang_api::DeclKind::Constructor);
}

#[test]
fn table_literal_emits_field_scoped_assignments() {
    let db = db_with(
        "function entry(raw, user)\n  local envelope = { cmd = '' .. raw, user = user, clean = 'ok' }\n  sink(envelope.cmd)\nend\n",
    );
    let global = db.global_index();
    let entry = global
        .find_by_name("entry")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("entry declaration");

    assert!(
        entry.flow_events.iter().any(|event| matches!(
            event,
            FlowEvent::Assign { target, source_names, .. }
                if target == "envelope.cmd" && source_names == &["raw"]
        )),
        "table cmd field should retain only its exact source: {:?}",
        entry.flow_events
    );
    assert!(entry.flow_events.iter().any(|event| matches!(
        event,
        FlowEvent::Assign { target, source_names, .. }
            if target == "envelope.user" && source_names == &["user"]
    )));
    assert!(entry.flow_events.iter().any(|event| matches!(
        event,
        FlowEvent::Assign { target, source_names, value_kind, .. }
            if target == "envelope.clean"
                && source_names.is_empty()
                && *value_kind == Some(bonsai_lang_api::AssignValueKind::Literal)
    )));
}

#[test]
fn parallel_table_assignments_follow_exact_lua_value_ordinals() {
    let db = db_with(
        r#"
function entry(raw, other, clean)
  local first, second = clean, { cmd = raw, nested = { user = other } }
  local left, right = { one = raw }, { two = other }
  local present, missing = { kept = raw }
  only = clean, { discarded = raw }
  sink(second.cmd, second.nested.user, left.one, right.two, present.kept)
end
"#,
    );
    let global = db.global_index();
    let entry = global
        .find_by_name("entry")
        .iter()
        .find_map(|symbol| global.decl_of(*symbol))
        .expect("entry declaration");
    let field_sources = entry
        .flow_events
        .iter()
        .filter_map(|event| match event {
            FlowEvent::Assign {
                target, source_names, ..
            } if target.contains('.') => Some((target.as_str(), source_names.as_slice())),
            _ => None,
        })
        .collect::<Vec<_>>();

    assert!(field_sources.contains(&("second.cmd", &["raw".to_string()][..])));
    assert!(field_sources.contains(&("second.nested.user", &["other".to_string()][..])));
    assert!(field_sources.contains(&("left.one", &["raw".to_string()][..])));
    assert!(field_sources.contains(&("right.two", &["other".to_string()][..])));
    assert!(field_sources.contains(&("present.kept", &["raw".to_string()][..])));

    assert!(
        !field_sources
            .iter()
            .any(|(target, _)| target.starts_with("first.")),
        "a later RHS table must never be assigned to an earlier target: {field_sources:#?}"
    );
    assert!(
        !field_sources
            .iter()
            .any(|(target, _)| target.starts_with("missing.")),
        "a target filled with nil has no table fields: {field_sources:#?}"
    );
    assert!(
        !field_sources
            .iter()
            .any(|(target, _)| target.starts_with("only.")),
        "an extra RHS table is evaluated then discarded, not paired with the sole target: {field_sources:#?}"
    );
}