luaur-analysis 0.1.3

Luau type checker and type inference (Rust).
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
//! Source: `Analysis/src/Unifier.cpp` (Unifier::tryUnify_(TypePackId,...), L1405-1634)
use crate::enums::polarity::Polarity;
use crate::functions::flatten_type_pack_alt_b::flatten;
use crate::functions::fresh_type::fresh_type;
use crate::functions::is_blocked_unifier_alt_c::is_blocked_txn_log_type_pack_id;
use crate::functions::is_optional::is_optional;
use crate::functions::size_type_pack::size;
use crate::records::count_mismatch::{CountMismatch, CountMismatchContext};
use crate::records::free_type_pack::FreeTypePack;
use crate::records::type_pack::TypePack;
use crate::records::type_pack_mismatch::TypePackMismatch;
use crate::records::type_pack_var::TypePackVar;
use crate::records::unifier::Unifier;
use crate::records::variadic_type_pack::VariadicTypePack;
use crate::records::weird_iter::WeirdIter;
use crate::records::widen::Widen;
use crate::type_aliases::error_type_pack::ErrorTypePack;
use crate::type_aliases::type_error_data::TypeErrorData;
use crate::type_aliases::type_pack_id::TypePackId;
use crate::type_aliases::type_pack_variant::TypePackVariant;
use alloc::string::String;

impl Unifier {
    /// `void Unifier::tryUnify_(TypePackId subTp, TypePackId superTp, bool isFunctionCall)`
    pub fn try_unify_type_pack_id_type_pack_id_bool(
        &mut self,
        mut sub_tp: TypePackId,
        mut super_tp: TypePackId,
        is_function_call: bool,
    ) {
        unsafe {
            (*self.shared_state).counters.iteration_count += 1;
            if (*self.shared_state).counters.iteration_limit > 0
                && (*self.shared_state).counters.iteration_limit
                    < (*self.shared_state).counters.iteration_count
            {
                self.report_error_location_type_error_data(
                    self.location,
                    TypeErrorData::UnificationTooComplex(
                        crate::records::unification_too_complex::UnificationTooComplex::default(),
                    ),
                );
                return;
            }
        }

        super_tp = self.log.follow_type_pack_id(super_tp);
        sub_tp = self.log.follow_type_pack_id(sub_tp);

        // Reflexive structural-equality fast-path (see unifier_reflexive_equal):
        // identical curried-function arg/return packs (e.g. `(Color)` vs
        // `(Color)`) recur element-by-element on every use without this, which
        // is what tips np_hard over the iteration limit.
        if self.reflexive_equal_type_pack_id(super_tp, sub_tp, 32) {
            return;
        }

        loop {
            let tp = self.log.txn_log_get_mutable::<TypePack, TypePackId>(sub_tp);
            if tp.is_null() {
                break;
            }
            if unsafe { (*tp).head.is_empty() && (*tp).tail.is_some() } {
                sub_tp = self.log.follow_type_pack_id(unsafe { (*tp).tail.unwrap() });
            } else {
                break;
            }
        }

        loop {
            let tp = self
                .log
                .txn_log_get_mutable::<TypePack, TypePackId>(super_tp);
            if tp.is_null() {
                break;
            }
            if unsafe { (*tp).head.is_empty() && (*tp).tail.is_some() } {
                super_tp = self.log.follow_type_pack_id(unsafe { (*tp).tail.unwrap() });
            } else {
                break;
            }
        }

        if super_tp == sub_tp {
            return;
        }

        if self
            .log
            .have_seen_type_pack_id_type_pack_id(super_tp, sub_tp)
        {
            return;
        }

        let sub_blocked = is_blocked_txn_log_type_pack_id(&self.log, sub_tp);
        let super_blocked = is_blocked_txn_log_type_pack_id(&self.log, super_tp);
        if sub_blocked && super_blocked {
            self.blocked_type_packs.push(sub_tp);
            self.blocked_type_packs.push(super_tp);
        } else if sub_blocked {
            self.blocked_type_packs.push(sub_tp);
        } else if super_blocked {
            self.blocked_type_packs.push(super_tp);
        }

        if !self
            .log
            .txn_log_get_mutable::<FreeTypePack, TypePackId>(super_tp)
            .is_null()
        {
            if !self.occurs_check_type_pack_id_type_pack_id_bool(super_tp, sub_tp, true) {
                let mut widen = Widen::widen_widen(self.types, self.builtin_types);
                let widened = widen.operator_call(sub_tp);
                let bound = TypePackVar {
                    ty: TypePackVariant::Bound(widened),
                    persistent: false,
                    owningArena: core::ptr::null_mut(),
                };
                self.log.replace_type_pack_id_type_pack_var(super_tp, bound);
            }
        } else if !self
            .log
            .txn_log_get_mutable::<FreeTypePack, TypePackId>(sub_tp)
            .is_null()
        {
            if !self.occurs_check_type_pack_id_type_pack_id_bool(sub_tp, super_tp, false) {
                let bound = TypePackVar {
                    ty: TypePackVariant::Bound(super_tp),
                    persistent: false,
                    owningArena: core::ptr::null_mut(),
                };
                self.log.replace_type_pack_id_type_pack_var(sub_tp, bound);
            }
        } else if !self
            .log
            .txn_log_get_mutable::<ErrorTypePack, TypePackId>(super_tp)
            .is_null()
        {
            self.try_unify_with_any_type_pack_id_type_pack_id(sub_tp, super_tp);
        } else if !self
            .log
            .txn_log_get_mutable::<ErrorTypePack, TypePackId>(sub_tp)
            .is_null()
        {
            self.try_unify_with_any_type_pack_id_type_pack_id(super_tp, sub_tp);
        } else if !self
            .log
            .txn_log_get_mutable::<VariadicTypePack, TypePackId>(super_tp)
            .is_null()
        {
            self.unifier_try_unify_variadics(sub_tp, super_tp, false, 0);
        } else if !self
            .log
            .txn_log_get_mutable::<VariadicTypePack, TypePackId>(sub_tp)
            .is_null()
        {
            self.unifier_try_unify_variadics(super_tp, sub_tp, true, 0);
        } else if !self
            .log
            .txn_log_get_mutable::<TypePack, TypePackId>(super_tp)
            .is_null()
            && !self
                .log
                .txn_log_get_mutable::<TypePack, TypePackId>(sub_tp)
                .is_null()
        {
            let super_tpv = self
                .log
                .txn_log_get_mutable::<TypePack, TypePackId>(super_tp);
            let sub_tpv = self.log.txn_log_get_mutable::<TypePack, TypePackId>(sub_tp);

            // If the size of two heads does not match, but both packs have free tail
            // we set the sentinel to avoid growing forever.
            let (super_types, super_tail) = flatten(super_tp, &self.log);
            let (sub_types, sub_tail) = flatten(sub_tp, &self.log);

            let no_infinite_growth = (super_types.len() != sub_types.len())
                && super_tail.map_or(false, |t| {
                    !self
                        .log
                        .txn_log_get_mutable::<FreeTypePack, TypePackId>(t)
                        .is_null()
                })
                && sub_tail.map_or(false, |t| {
                    !self
                        .log
                        .txn_log_get_mutable::<FreeTypePack, TypePackId>(t)
                        .is_null()
                });

            let mut super_iter = WeirdIter {
                pack_id: super_tp,
                log: &mut self.log as *mut _,
                pack: core::ptr::null_mut(),
                index: 0,
                growing: false,
                level: crate::records::type_level::TypeLevel::default(),
                scope: core::ptr::null_mut(),
            };
            super_iter.weird_iter_type_pack_id_txn_log(super_tp, unsafe { &mut *(self.log_ptr()) });

            let mut sub_iter = WeirdIter {
                pack_id: sub_tp,
                log: &mut self.log as *mut _,
                pack: core::ptr::null_mut(),
                index: 0,
                growing: false,
                level: crate::records::type_level::TypeLevel::default(),
                scope: core::ptr::null_mut(),
            };
            sub_iter.weird_iter_type_pack_id_txn_log(sub_tp, unsafe { &mut *(self.log_ptr()) });

            super_iter.scope = self.scope;
            sub_iter.scope = self.scope;

            let empty_tp = unsafe {
                (*self.types).add_type_pack_t(TypePack {
                    head: alloc::vec::Vec::new(),
                    tail: None,
                })
            };

            let mut loop_count = 0;

            loop {
                if luaur_common::FInt::LuauTypeInferTypePackLoopLimit.get() > 0
                    && loop_count >= luaur_common::FInt::LuauTypeInferTypePackLoopLimit.get()
                {
                    self.ice_string("Detected possibly infinite TypePack growth");
                }

                loop_count += 1;

                if super_iter.weird_iter_good() && sub_iter.growing {
                    let ft = self.mk_fresh_for_iter(sub_iter.scope);
                    sub_iter.weird_iter_push_type(ft);
                }

                if sub_iter.weird_iter_good() && super_iter.growing {
                    let ft = self.mk_fresh_for_iter(super_iter.scope);
                    super_iter.weird_iter_push_type(ft);
                }

                if super_iter.weird_iter_good() && sub_iter.weird_iter_good() {
                    let s = *sub_iter.weird_iter_operator_deref();
                    let sup = *super_iter.weird_iter_operator_deref();
                    self.try_unify_type_id_type_id_bool_bool_literal_properties(
                        s, sup, false, false, None,
                    );

                    if !self.errors.is_empty() && self.first_pack_error_pos.is_none() {
                        self.first_pack_error_pos = Some(loop_count);
                    }

                    super_iter.weird_iter_advance();
                    sub_iter.weird_iter_advance();
                    continue;
                }

                // If both are at the end, we're done
                if !super_iter.weird_iter_good() && !sub_iter.weird_iter_good() {
                    let l_free_tail = unsafe {
                        (*super_tpv).tail.map_or(false, |t| {
                            !self
                                .log
                                .txn_log_get_mutable::<FreeTypePack, TypePackId>(
                                    self.log.follow_type_pack_id(t),
                                )
                                .is_null()
                        })
                    };
                    let r_free_tail = unsafe {
                        (*sub_tpv).tail.map_or(false, |t| {
                            !self
                                .log
                                .txn_log_get_mutable::<FreeTypePack, TypePackId>(
                                    self.log.follow_type_pack_id(t),
                                )
                                .is_null()
                        })
                    };
                    if l_free_tail && r_free_tail {
                        self.try_unify_type_pack_id_type_pack_id_bool(
                            unsafe { (*sub_tpv).tail.unwrap() },
                            unsafe { (*super_tpv).tail.unwrap() },
                            false,
                        );
                    } else if l_free_tail {
                        self.try_unify_type_pack_id_type_pack_id_bool(
                            empty_tp,
                            unsafe { (*super_tpv).tail.unwrap() },
                            false,
                        );
                    } else if r_free_tail {
                        self.try_unify_type_pack_id_type_pack_id_bool(
                            empty_tp,
                            unsafe { (*sub_tpv).tail.unwrap() },
                            false,
                        );
                    } else if unsafe { (*sub_tpv).tail.is_some() && (*super_tpv).tail.is_some() } {
                        if !self
                            .log
                            .txn_log_get_mutable::<VariadicTypePack, TypePackId>(super_iter.pack_id)
                            .is_null()
                        {
                            self.unifier_try_unify_variadics(
                                sub_iter.pack_id,
                                super_iter.pack_id,
                                false,
                                sub_iter.index as i32,
                            );
                        } else if !self
                            .log
                            .txn_log_get_mutable::<VariadicTypePack, TypePackId>(sub_iter.pack_id)
                            .is_null()
                        {
                            self.unifier_try_unify_variadics(
                                super_iter.pack_id,
                                sub_iter.pack_id,
                                true,
                                super_iter.index as i32,
                            );
                        } else {
                            self.try_unify_type_pack_id_type_pack_id_bool(
                                unsafe { (*sub_tpv).tail.unwrap() },
                                unsafe { (*super_tpv).tail.unwrap() },
                                false,
                            );
                        }
                    }

                    break;
                }

                // If both tails are free, bind one to the other and call it a day
                if super_iter.weird_iter_can_grow() && sub_iter.weird_iter_can_grow() {
                    let s = unsafe { (*sub_iter.pack).tail.unwrap() };
                    let sup = unsafe { (*super_iter.pack).tail.unwrap() };
                    return self.try_unify_type_pack_id_type_pack_id_bool(s, sup, false);
                }

                // If just one side is free on its tail, grow it to fit the other side.
                if super_iter.weird_iter_can_grow() {
                    let new_tail = unsafe {
                        (*self.types).add_type_pack_type_pack_var(TypePackVar {
                            ty: TypePackVariant::TypePack(TypePack {
                                head: alloc::vec::Vec::new(),
                                tail: None,
                            }),
                            persistent: false,
                            owningArena: core::ptr::null_mut(),
                        })
                    };
                    super_iter.weird_iter_grow(new_tail);
                } else if sub_iter.weird_iter_can_grow() {
                    let new_tail = unsafe {
                        (*self.types).add_type_pack_type_pack_var(TypePackVar {
                            ty: TypePackVariant::TypePack(TypePack {
                                head: alloc::vec::Vec::new(),
                                tail: None,
                            }),
                            persistent: false,
                            owningArena: core::ptr::null_mut(),
                        })
                    };
                    sub_iter.weird_iter_grow(new_tail);
                } else {
                    // A union type including nil marks an optional argument
                    if super_iter.weird_iter_good()
                        && is_optional(*super_iter.weird_iter_operator_deref())
                    {
                        super_iter.weird_iter_advance();
                        continue;
                    } else if sub_iter.weird_iter_good()
                        && is_optional(*sub_iter.weird_iter_operator_deref())
                    {
                        sub_iter.weird_iter_advance();
                        continue;
                    }

                    if !self
                        .log
                        .txn_log_get_mutable::<VariadicTypePack, TypePackId>(super_iter.pack_id)
                        .is_null()
                    {
                        self.unifier_try_unify_variadics(
                            sub_iter.pack_id,
                            super_iter.pack_id,
                            false,
                            sub_iter.index as i32,
                        );
                        return;
                    }

                    if !self
                        .log
                        .txn_log_get_mutable::<VariadicTypePack, TypePackId>(sub_iter.pack_id)
                        .is_null()
                    {
                        self.unifier_try_unify_variadics(
                            super_iter.pack_id,
                            sub_iter.pack_id,
                            true,
                            super_iter.index as i32,
                        );
                        return;
                    }

                    if !is_function_call && sub_iter.weird_iter_good() {
                        // Sometimes it is ok to pass too many arguments
                        return;
                    }

                    // This is a bit weird because we don't actually know expected vs actual.
                    let log_ptr = self.log_ptr();
                    let mut expected_size = size(super_tp, log_ptr);
                    let mut actual_size = size(sub_tp, log_ptr);
                    if self.ctx == CountMismatchContext::FunctionResult
                        || self.ctx == CountMismatchContext::ExprListResult
                    {
                        core::mem::swap(&mut expected_size, &mut actual_size);
                    }
                    let ctx = self.ctx;
                    self.report_error_location_type_error_data(
                        self.location,
                        TypeErrorData::CountMismatch(CountMismatch {
                            expected: expected_size,
                            maximum: None,
                            actual: actual_size,
                            context: ctx,
                            is_variadic: false,
                            function: String::new(),
                        }),
                    );

                    let error_type = unsafe { (*self.builtin_types).errorType };
                    while super_iter.weird_iter_good() {
                        let cur = *super_iter.weird_iter_operator_deref();
                        self.try_unify_type_id_type_id_bool_bool_literal_properties(
                            cur, error_type, false, false, None,
                        );
                        super_iter.weird_iter_advance();
                    }

                    while sub_iter.weird_iter_good() {
                        let cur = *sub_iter.weird_iter_operator_deref();
                        self.try_unify_type_id_type_id_bool_bool_literal_properties(
                            cur, error_type, false, false, None,
                        );
                        sub_iter.weird_iter_advance();
                    }

                    return;
                }

                if no_infinite_growth {
                    break;
                }
            }
        } else {
            self.report_error_location_type_error_data(
                self.location,
                TypeErrorData::TypePackMismatch(TypePackMismatch {
                    wanted_tp: super_tp,
                    given_tp: sub_tp,
                    reason: String::new(),
                }),
            );
        }
    }

    /// `mkFreshType` lambda in tryUnify_: `freshType(NotNull{types}, builtinTypes, scope)`.
    fn mk_fresh_for_iter(
        &mut self,
        scope: *mut crate::records::scope::Scope,
    ) -> crate::type_aliases::type_id::TypeId {
        fresh_type(
            unsafe { &mut *self.types },
            unsafe { &*self.builtin_types },
            scope,
            Polarity::Positive,
        )
    }

    #[inline]
    fn log_ptr(&mut self) -> *mut crate::records::txn_log::TxnLog {
        &mut self.log as *mut _
    }
}