emmylua_code_analysis 0.24.0

A library for analyzing lua code.
Documentation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#[cfg(test)]
mod test {
    use crate::{
        DiagnosticCode, LuaType, RenderLevel, TypeSubstitutor, VirtualWorkspace, humanize_type,
    };

    #[test]
    fn test_variadic_func() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
        ---@generic T, R
        ---@param call async fun(...: T...): R...
        ---@return async fun(...: T...): R...
        function async_create(call)

        end


        ---@param a number
        ---@param b string
        ---@param c boolean
        ---@return number
        function locaf(a, b, c)

        end
        "#,
        );

        let ty = ws.expr_ty("async_create(locaf)");
        let expected = ws.ty("async fun(a: number, b: string, c:boolean): number...");
        assert_eq!(ty, expected);
    }

    #[test]
    fn test_select_type() {
        let mut ws = VirtualWorkspace::new_with_init_std_lib();
        ws.def(
            r#"
        ---@param ... string
        function ffff(...)
            a, b, c = select(2, ...)
        end
        "#,
        );

        let a_ty = ws.expr_ty("a");
        let b_ty = ws.expr_ty("b");
        let c_ty = ws.expr_ty("c");
        let expected = ws.ty("string");
        assert_eq!(a_ty, expected);
        assert_eq!(b_ty, expected);
        assert_eq!(c_ty, expected);

        ws.def(
            r#"
        e, f = select(2, "a", "b", "c")
        "#,
        );

        let e = ws.expr_ty("e");
        let expected = LuaType::String;
        let f = ws.expr_ty("f");
        let expected_f = LuaType::String;
        assert_eq!(e, expected);
        assert_eq!(f, expected_f);

        ws.def(
            r#"
        h = select('#', "a", "b")
        "#,
        );

        let h = ws.expr_ty("h");
        let expected = LuaType::IntegerConst(2);
        assert_eq!(h, expected);

        // select(n, func()) where func() returns multiple values
        ws.def(
            r#"
        ---@return integer, string
        function multi_ret() end
        g = select(2, multi_ret())
        "#,
        );

        let g = ws.expr_ty("g");
        let expected_g = ws.ty("string");
        assert_eq!(g, expected_g);
    }

    #[test]
    fn test_unpack() {
        let mut ws = VirtualWorkspace::new_with_init_std_lib();

        ws.def(
            r#"
        local h ---@type number[]
        a, b, c = table.unpack(h)
        "#,
        );

        let a = ws.expr_ty("a");
        let expected = ws.ty("number?");
        let b = ws.expr_ty("b");
        let expected_b = ws.ty("number?");
        let c = ws.expr_ty("c");
        let expected_c = ws.ty("number?");
        assert_eq!(a, expected);
        assert_eq!(b, expected_b);
        assert_eq!(c, expected_c);
    }

    #[test]
    fn test_return() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
                ---@class ab
                ---@field a number
                local A

                ---@generic T
                ---@param a T
                ---@return T
                local function name(a)
                    return a
                end

                local a = name(A)
                a.b = 1
                R = A.b
        "#,
        );

        let a = ws.expr_ty("R");
        let expected = ws.ty("nil");
        assert_eq!(a, expected);
    }

    #[test]
    fn test_issue_797() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
---@class Holder<T>

---@class C_StringHolder : Holder<string>

---@class C_StringHolderExt : C_StringHolder

---@class C_StringHolderWith<T> : Holder<string>

---@class C_StringHolderWithExt<T> : C_StringHolderWith<T>

---@alias A_StringHolder Holder<string>

---@alias A_StringHolderExt A_StringHolder

---@alias A_StringHolderWith<T> Holder<string>

---@alias A_StringHolderWithExt<T> A_StringHolderWith<T>

---@generic T
---@param v Holder<T>
---@return T
local function extract_holder(v) return v end

local direct ---@type Holder<string>

local class_a ---@type C_StringHolder
local class_b ---@type C_StringHolderExt
local class_c ---@type C_StringHolderWith<table>
local class_d ---@type C_StringHolderWithExt<table>

local alias_a ---@type A_StringHolder
local alias_b ---@type A_StringHolderExt
local alias_c ---@type A_StringHolderWith<table>
local alias_d ---@type A_StringHolderWithExt<table>

result = {
    direct = extract_holder(direct),

    class_a = extract_holder(class_a),
    class_b = extract_holder(class_b),
    class_c = extract_holder(class_c),
    class_d = extract_holder(class_d),

    alias_a = extract_holder(alias_a),
    alias_b = extract_holder(alias_b),
    alias_c = extract_holder(alias_c),
    alias_d = extract_holder(alias_d),
}
        "#,
        );

        let a = ws.expr_ty("result");
        let a_desc = ws.humanize_type_detailed(a);
        let expected = r#"{
    direct: string,
    class_a: string,
    class_b: string,
    class_c: string,
    class_d: string,
    alias_a: string,
    alias_b: string,
    alias_c: string,
    alias_d: string,
}"#;
        assert_eq!(a_desc, expected);
    }

    #[test]
    fn test_call_generic() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@alias Warp<T> T

            ---@generic T
            ---@param ... Warp<T>
            function test(...)
            end
        "#,
        );

        assert!(!ws.has_no_diagnostic(
            DiagnosticCode::ParamTypeMismatch,
            r#"
            ---@type Warp<number>, Warp<string>
            local a, b
            test(a, b)
        "#,
        ));

        assert!(ws.has_no_diagnostic(
            DiagnosticCode::ParamTypeMismatch,
            r#"
            ---@type Warp<number>, Warp<string>
            local a, b
            test--[[@<number | string>]](a, b)
        "#,
        ));
    }

    #[test]
    fn test_generic_alias_instantiation() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@alias Arrayable<T> T | T[]

            ---@class Suite

            ---@generic T
            ---@param value Arrayable<T>
            ---@return T[]
            function toArray(value)
            end
        "#,
        );

        ws.def(
            r#"
            ---@type Arrayable<Suite>
            local suite

            arraySuites = toArray(suite)
        "#,
        );

        let a = ws.expr_ty("arraySuites");
        let expected = ws.ty("Suite[]");
        assert_eq!(a, expected);
    }

    #[test]
    fn test_keyof_generic_instantiates_to_union() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@class A
            ---@field one 1
            ---@field two 2
            ---@field three 3

            ---@alias B<T> T extends any and keyof T or never
            "#,
        );

        let ty = ws.ty("B<A>");
        let db = ws.analysis.compilation.get_db();
        let origin = match ty {
            LuaType::Generic(generic) => {
                let type_decl = db
                    .get_type_index()
                    .get_type_decl(&generic.get_base_type_id())
                    .expect("B must resolve to an alias declaration");
                let substitutor = TypeSubstitutor::from_type_array(generic.get_params().clone());
                type_decl
                    .get_alias_origin(&db, Some(&substitutor))
                    .expect("B<A> must expand to its instantiated alias origin")
            }
            ty => ty,
        };

        let LuaType::Union(union) = &origin else {
            panic!(
                "keyof generic should instantiate to union, got {}",
                humanize_type(&db, &origin, RenderLevel::Detailed)
            );
        };

        let mut keys = union
            .into_vec()
            .iter()
            .map(|ty| humanize_type(&db, ty, RenderLevel::Brief))
            .collect::<Vec<_>>();
        keys.sort();

        assert_eq!(keys, vec!["\"one\"", "\"three\"", "\"two\""]);
    }

    #[test]
    fn test_generic_alias_instantiation2() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@alias Arrayable<T> T | T[]

            ---@class Suite

            ---@param value Arrayable<Suite>
            function toArray(value)

            end
            "#,
        );
        assert!(ws.has_no_diagnostic(
            DiagnosticCode::ParamTypeMismatch,
            r#"

            ---@type Suite
            local suite

            local arraySuites = toArray(suite)
            "#
        ));
    }

    #[test]
    fn test_dot_defined_generic_constructor_called_with_colon() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@class a
            local a = {}

            ---@generic T
            ---@param cls T
            ---@return T
            function a.create(cls)
                local instance = setmetatable({}, cls)
                return instance
            end

            b = a:create()
            "#,
        );

        let ty = ws.expr_ty("b");
        assert_eq!(ws.humanize_type(ty), "a");
    }

    #[test]
    fn test_generic_map_lambda_return() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@generic T, U
            ---@param list T[]
            ---@param fn fun(item: T): U
            ---@return U[]
            local function map(list, fn)
            end

            local list_1 = {} ---@type string[]

            _mapped_2 = map(list_1, function (item)
                return item
            end)
        "#,
        );

        let ty = ws.expr_ty("_mapped_2");
        let expected = ws.ty("string[]");
        assert_eq!(ty, expected);
    }

    #[test]
    fn test_colon_call_infers_generic_self_and_callback_return() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@class Promise<T>
            local M = {}

            ---@alias Unwrap<T> T extends Promise<infer U> and U or T

            ---@generic T
            ---@return Promise<T>
            function M.new() return M end

            ---@generic U
            ---@param on_resolved fun(value: T): U
            ---@return Promise<Unwrap<U>>
            function M:then1(on_resolved) return self end

            p1 = M.new():then1(function()
                return {} ---@as Promise<integer>
            end)

        "#,
        );

        let expected = ws.ty("Promise<integer>");
        assert_eq!(ws.expr_ty("p1"), expected);
        // assert_eq!(ws.expr_ty("p2"), expected);
    }

    #[test]
    fn test_simple_alias_param_still_infers_function_generic() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@alias Id<T> T

            ---@generic T
            ---@param value Id<T>
            ---@return T
            function id(value)
            end

            result = id("value")
        "#,
        );

        assert_eq!(ws.expr_ty("result"), ws.ty("string"));
    }

    #[test]
    fn test_function_and_alias_generic_same_name_do_not_collide() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@alias Id<U> U

            ---@generic U
            ---@param value Id<U>
            ---@return U
            function id(value)
            end

            result = id("value")
        "#,
        );

        assert_eq!(ws.expr_ty("result"), ws.ty("string"));
    }

    #[test]
    fn test_nested_callback_return_alias_waits_for_function_generic() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@class Promise<T>
            local M = {}

            ---@alias Unwrap<T> T extends Promise<infer U> and U or T
            ---@alias Awaited<T> Unwrap<T>

            ---@generic T
            ---@return Promise<T>
            function M.new() return M end

            ---@generic U
            ---@param on_resolved fun(value: T): U
            ---@return Promise<Awaited<U>>
            function M:then_nested(on_resolved) return self end

            result = M.new():then_nested(function()
                return {} ---@as Promise<integer>
            end)
        "#,
        );

        assert_eq!(ws.expr_ty("result"), ws.ty("Promise<integer>"));
    }

    #[test]
    fn test_nested_function_generic_shadows_outer_function_generic() {
        let mut ws = VirtualWorkspace::new();
        ws.def(
            r#"
            ---@generic T
            ---@param value T
            ---@return fun<T>(value: T): T
            function make(value)
            end

            local fn = make("outer")
            result = fn(1)
        "#,
        );

        assert_eq!(ws.expr_ty("result"), ws.ty("integer"));
    }
}