luaur-compiler 0.1.3

Luau source-to-bytecode compiler (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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Source: `Compiler/src/ConstantFolding.cpp:944-1396`

use crate::enums::table_constant_kind::TableConstantKind;
use crate::records::constant::Constant;
use crate::records::variable::Variable;
use crate::type_aliases::expr_constant_change_log::ExprConstantChangeLog;
use crate::type_aliases::library_member_constant_callback::LibraryMemberConstantCallback;
use crate::type_aliases::local_constant_change_log::LocalConstantChangeLog;
use alloc::vec::Vec;
use luaur_ast::records::ast_array::AstArray;
use luaur_ast::records::ast_expr::AstExpr;
use luaur_ast::records::ast_expr_call::AstExprCall;
use luaur_ast::records::ast_expr_table::Item;
use luaur_ast::records::ast_local::AstLocal;
use luaur_ast::records::ast_name::AstName;
use luaur_ast::records::ast_name_table::AstNameTable;
use luaur_ast::records::ast_visitor::AstVisitor;
use luaur_common::records::dense_hash_map::DenseHashMap;

#[derive(Debug)]
pub struct ConstantVisitor<'a> {
    pub(crate) constants: &'a mut DenseHashMap<*mut AstExpr, Constant>,
    pub(crate) variables: &'a mut DenseHashMap<*mut AstLocal, Variable>,
    pub(crate) locals: &'a mut DenseHashMap<*mut AstLocal, Constant>,
    pub(crate) builtins: *const DenseHashMap<*mut AstExprCall, i32>,
    pub(crate) fold_library_k: bool,
    pub(crate) library_member_constant_cb: LibraryMemberConstantCallback,
    pub(crate) string_table: &'a mut AstNameTable,
    pub(crate) constant_tables: Vec<DenseHashMap<AstName, Constant>>,
    pub(crate) was_empty: bool,
    pub(crate) builtin_args: Vec<Constant>,
    pub(crate) constant_table_locals: &'a DenseHashMap<*mut AstLocal, TableConstantKind>,
    pub(crate) table_locals: DenseHashMap<*mut AstLocal, Constant>,
    pub(crate) expr_change_log: *mut ExprConstantChangeLog,
    pub(crate) local_change_log: *mut LocalConstantChangeLog,
}

impl<'a> ConstantVisitor<'a> {
    pub fn constant_visitor(
        constants: &'a mut DenseHashMap<*mut AstExpr, Constant>,
        variables: &'a mut DenseHashMap<*mut AstLocal, Variable>,
        locals: &'a mut DenseHashMap<*mut AstLocal, Constant>,
        builtins: *const DenseHashMap<*mut AstExprCall, i32>,
        fold_library_k: bool,
        library_member_constant_cb: LibraryMemberConstantCallback,
        string_table: &'a mut AstNameTable,
        constant_table_locals: &'a DenseHashMap<*mut AstLocal, TableConstantKind>,
        expr_change_log: *mut ExprConstantChangeLog,
        local_change_log: *mut LocalConstantChangeLog,
    ) -> Self {
        let mut constant_tables = Vec::new();
        constant_tables.reserve(16);

        let table_locals = DenseHashMap::new(core::ptr::null_mut());

        let was_empty = constants.empty() && locals.empty();

        Self {
            constants,
            variables,
            locals,
            builtins,
            fold_library_k,
            library_member_constant_cb,
            string_table,
            constant_tables,
            was_empty,
            builtin_args: Vec::new(),
            constant_table_locals,
            table_locals,
            expr_change_log,
            local_change_log,
        }
    }

    fn analyze(&mut self, node: *mut AstExpr) -> Constant {
        let mut result = Constant::default();
        result.r#type = crate::enums::type_constant_folding::Type::Type_Unknown;

        let node_ref = unsafe { &*node };

        if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_group::AstExprGroup>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            result = self.analyze(expr.expr);
        } else if luaur_ast::rtti::ast_node_is::<
            luaur_ast::records::ast_expr_constant_nil::AstExprConstantNil,
        >(node as *mut luaur_ast::records::ast_node::AstNode)
        {
            result.r#type = crate::enums::type_constant_folding::Type::Type_Nil;
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_constant_bool::AstExprConstantBool,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            result.r#type = crate::enums::type_constant_folding::Type::Type_Boolean;
            result.data.value_boolean = expr.value;
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_constant_number::AstExprConstantNumber,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            result.r#type = crate::enums::type_constant_folding::Type::Type_Number;
            result.data.value_number = expr.value;
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_constant_integer::AstExprConstantInteger,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            result.r#type = crate::enums::type_constant_folding::Type::Type_Integer;
            result.data.value_integer64 = expr.value;
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_constant_string::AstExprConstantString,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            result.r#type = crate::enums::type_constant_folding::Type::Type_String;
            result.data.value_string = expr.value.data as *const core::ffi::c_char;
            result.string_length = expr.value.size as u32;
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_local::AstExprLocal>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            if let Some(l) = self.locals.find(&expr.local) {
                result = *l;
            } else if luaur_common::FFlag::LuauCompileFoldOptimize.get() {
                if let Some(l) = self.table_locals.find(&expr.local) {
                    result = *l;
                }
            }
        } else if luaur_ast::rtti::ast_node_is::<luaur_ast::records::ast_expr_global::AstExprGlobal>(
            node as *mut luaur_ast::records::ast_node::AstNode,
        ) {
            // nope
        } else if luaur_ast::rtti::ast_node_is::<luaur_ast::records::ast_expr_varargs::AstExprVarargs>(
            node as *mut luaur_ast::records::ast_node::AstNode,
        ) {
            // nope
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_call::AstExprCall>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            self.analyze(expr.func);

            let bfid = if !self.builtins.is_null() {
                unsafe { &*self.builtins }
                    .find(&(expr as *mut luaur_ast::records::ast_expr_call::AstExprCall))
            } else {
                None
            };

            if let Some(bfid_ptr) = bfid {
                if *bfid_ptr != 0 {
                    let offset = self.builtin_args.len();
                    let mut can_fold = true;

                    self.builtin_args.reserve(offset + expr.args.size as usize);

                    for i in 0..expr.args.size as usize {
                        let ac = self.analyze(unsafe { *expr.args.data.add(i) });

                        if luaur_common::FFlag::LuauCompilePropagateTableProps2.get() {
                            if ac.r#type == crate::enums::type_constant_folding::Type::Type_Unknown
                                || ac.r#type
                                    == crate::enums::type_constant_folding::Type::Type_Table
                            {
                                can_fold = false;
                            } else {
                                self.builtin_args.push(ac);
                            }
                        } else if ac.r#type
                            == crate::enums::type_constant_folding::Type::Type_Unknown
                        {
                            can_fold = false;
                        } else {
                            self.builtin_args.push(ac);
                        }
                    }

                    if can_fold {
                        luaur_common::LUAU_ASSERT!(
                            self.builtin_args.len() == offset + expr.args.size as usize
                        );
                        result = crate::functions::fold_builtin::fold_builtin(
                            self.string_table,
                            *bfid_ptr,
                            unsafe { self.builtin_args.as_ptr().add(offset) },
                            expr.args.size as usize,
                        );
                    }

                    self.builtin_args.resize(offset, Constant::default());
                } else {
                    for i in 0..expr.args.size as usize {
                        self.analyze(unsafe { *expr.args.data.add(i) });
                    }
                }
            } else {
                for i in 0..expr.args.size as usize {
                    self.analyze(unsafe { *expr.args.data.add(i) });
                }
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_index_name::AstExprIndexName>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            let value = self.analyze(expr.expr);
            if luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
                && value.r#type == crate::enums::type_constant_folding::Type::Type_Table
            {
                let table_index = unsafe { value.data.value_table };
                luaur_common::LUAU_ASSERT!(table_index < self.constant_tables.len());
                if table_index < self.constant_tables.len() {
                    let props = &self.constant_tables[table_index];
                    if let Some(prop) = props.find(&expr.index) {
                        result = *prop;
                    }
                }
            } else if value.r#type == crate::enums::type_constant_folding::Type::Type_Vector {
                let index_str =
                    unsafe { core::ffi::CStr::from_ptr(expr.index.value).to_string_lossy() };
                if index_str == "x" || index_str == "X" {
                    result.r#type = crate::enums::type_constant_folding::Type::Type_Number;
                    result.data.value_number = unsafe { value.data.value_vector[0] as f64 };
                } else if index_str == "y" || index_str == "Y" {
                    result.r#type = crate::enums::type_constant_folding::Type::Type_Number;
                    result.data.value_number = unsafe { value.data.value_vector[1] as f64 };
                } else if index_str == "z" || index_str == "Z" {
                    result.r#type = crate::enums::type_constant_folding::Type::Type_Number;
                    result.data.value_number = unsafe { value.data.value_vector[2] as f64 };
                }

                // Do not handle 'w' component because it isn't known if the runtime will be configured in 3-wide or 4-wide mode
                // In 3-wide, access to 'w' will call unspecified metamethod or fail
            } else if self.fold_library_k {
                if let Some(eg) = unsafe {
                    luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_global::AstExprGlobal>(expr.expr as *mut luaur_ast::records::ast_node::AstNode).as_mut()
                } {
                    let eg_name =
                        unsafe { core::ffi::CStr::from_ptr(eg.name.value).to_string_lossy() };
                    let index_str =
                        unsafe { core::ffi::CStr::from_ptr(expr.index.value).to_string_lossy() };
                    if eg_name == "math" {
                        result = crate::functions::fold_builtin_math::fold_builtin_math(expr.index);
                    }

                    if self.library_member_constant_cb.is_some()
                        && result.r#type == crate::enums::type_constant_folding::Type::Type_Unknown
                    {
                        let cb = self.library_member_constant_cb.unwrap();
                        // C++ passes reinterpret_cast<CompileConstant*>(&result): the
                        // pointer VALUE handed to the callback must be &result itself.
                        let constant_ptr = &mut result as *mut Constant
                            as *mut crate::type_aliases::compile_constant::CompileConstant;
                        unsafe { cb(eg.name.value, expr.index.value, constant_ptr) };
                    }
                }
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_index_expr::AstExprIndexExpr>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            let index_val = self.analyze(expr.index);
            let table_val = self.analyze(expr.expr);

            if luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
                && table_val.r#type == crate::enums::type_constant_folding::Type::Type_Table
                && index_val.r#type == crate::enums::type_constant_folding::Type::Type_String
            {
                let table_index = unsafe { table_val.data.value_table };
                luaur_common::LUAU_ASSERT!(table_index < self.constant_tables.len());
                if table_index < self.constant_tables.len() && index_val.string_length != 0 {
                    let props = &self.constant_tables[table_index];
                    let index_name = self.string_table.get_or_add(
                        unsafe { index_val.data.value_string } as *const core::ffi::c_char,
                        index_val.string_length as usize,
                    );
                    if let Some(prop) = props.find(&index_name) {
                        result = *prop;
                    }
                }
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_function::AstExprFunction>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            unsafe {
                luaur_ast::visit::ast_stat_visit(
                    expr.body as *mut luaur_ast::records::ast_stat::AstStat,
                    self as &mut dyn AstVisitor,
                );
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_table::AstExprTable>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            if luaur_common::FFlag::LuauCompilePropagateTableProps2.get() {
                let mut props = DenseHashMap::new(AstName::new());
                for i in 0..expr.items.size as usize {
                    let item = unsafe { &*expr.items.data.add(i) };

                    let value_val = self.analyze(item.value);

                    if !item.key.is_null() {
                        let key_val = self.analyze(item.key);

                        if key_val.r#type == crate::enums::type_constant_folding::Type::Type_String
                            && value_val.r#type
                                != crate::enums::type_constant_folding::Type::Type_Unknown
                            && value_val.r#type
                                != crate::enums::type_constant_folding::Type::Type_Table
                            && key_val.string_length != 0
                        {
                            let const_key = self.string_table.get_or_add(
                                unsafe { key_val.data.value_string } as *const core::ffi::c_char,
                                key_val.string_length as usize,
                            );
                            props.try_insert(const_key, value_val);
                        }
                    }
                }

                if props.size() == expr.items.size as usize {
                    result.r#type = crate::enums::type_constant_folding::Type::Type_Table;
                    result.data.value_table = self.constant_tables.len();
                    self.constant_tables.push(props);
                }
            } else {
                for i in 0..expr.items.size as usize {
                    let item = unsafe { &*expr.items.data.add(i) };

                    if !item.key.is_null() {
                        self.analyze(item.key);
                    }

                    self.analyze(item.value);
                }
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_unary::AstExprUnary>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            let arg = self.analyze(expr.expr);

            if arg.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                crate::functions::fold_unary::fold_unary(&mut result, expr.op, &arg);
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_binary::AstExprBinary>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            let la = self.analyze(expr.left);
            let ra = self.analyze(expr.right);

            if la.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                crate::functions::fold_binary::fold_binary(
                    &mut result,
                    expr.op,
                    &la,
                    &ra,
                    self.string_table,
                );
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_type_assertion::AstExprTypeAssertion,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            let arg = self.analyze(expr.expr);
            result = arg;
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<luaur_ast::records::ast_expr_if_else::AstExprIfElse>(
                node as *mut luaur_ast::records::ast_node::AstNode,
            )
            .as_mut()
        } {
            let cond = self.analyze(expr.condition);
            let true_expr = self.analyze(expr.true_expr);
            let false_expr = self.analyze(expr.false_expr);

            if cond.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                result = if cond.is_truthful() {
                    true_expr
                } else {
                    false_expr
                };
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_interp_string::AstExprInterpString,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            // C++ analyzes EVERY sub-expression (no early break) so that constants
            // are recorded for all of them — including local references nested in
            // later, non-constant interpolations. A `break` here left those refs
            // unfolded; a constant local whose declaration is then elided
            // (areLocalsRedundant) would reach compile_expr with no register and
            // trip the upvalue assert.
            let mut only_constant_sub_expr = true;
            for i in 0..expr.expressions.size as usize {
                if self
                    .analyze(unsafe { *expr.expressions.data.add(i) })
                    .r#type
                    != crate::enums::type_constant_folding::Type::Type_String
                {
                    only_constant_sub_expr = false;
                }
            }

            if only_constant_sub_expr {
                crate::functions::fold_interp_string::fold_interp_string(
                    &mut result,
                    expr,
                    self.constants,
                    self.string_table,
                );
            }
        } else if let Some(expr) = unsafe {
            luaur_ast::rtti::ast_node_as::<
                luaur_ast::records::ast_expr_instantiate::AstExprInstantiate,
            >(node as *mut luaur_ast::records::ast_node::AstNode)
            .as_mut()
        } {
            result = self.analyze(expr.expr);
        } else {
            luaur_common::LUAU_ASSERT!(false, "Unknown expression type");
        }

        self.record_expr_constant(node, result);

        result
    }

    fn record_expr_constant(&mut self, key: *mut AstExpr, value: Constant) {
        if luaur_common::FFlag::LuauCompileFoldOptimize.get()
            && luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
        {
            if value.r#type == crate::enums::type_constant_folding::Type::Type_Table {
                // Table constants are recorded in a separate map
            } else if value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                self.log_expr_change(key, None);
                *self.constants.get_or_insert(key) = value;
            } else if self.was_empty {
                // No need to clear out entries if we started with empty maps
            } else if let Some(old) = self.constants.find(&key).copied() {
                self.log_expr_change(key, Some(old));
                // C++ `old->type = Type_Unknown`: clear the STALE entry. try_insert is a no-op
                // when the key exists, so the stale constant survived across inline re-folds.
                *self.constants.get_or_insert(key) = Constant::default();
            }
        } else {
            if value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                *self.constants.get_or_insert(key) = value;
            } else if self.was_empty && !luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
            {
                // nothing
            } else if self.constants.find(&key).is_some() {
                // C++ `old->type = Type_Unknown`: clear the STALE entry. try_insert is a no-op
                // when the key exists, so the stale constant survived across inline re-folds.
                *self.constants.get_or_insert(key) = Constant::default();
            }
        }
    }

    fn record_local_constant(&mut self, key: *mut AstLocal, value: Constant) {
        if luaur_common::FFlag::LuauCompileFoldOptimize.get()
            && luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
        {
            if value.r#type == crate::enums::type_constant_folding::Type::Type_Table {
                // Table constants are recorded in a separate map
            } else if value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                self.log_local_change(key, None);
                *self.locals.get_or_insert(key) = value;
            } else if self.was_empty {
                // No need to clear out entries if we started with empty maps
            } else if let Some(old) = self.locals.find(&key).copied() {
                self.log_local_change(key, Some(old));
                *self.locals.get_or_insert(key) = Constant::default();
            }
        } else {
            if value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown {
                *self.locals.get_or_insert(key) = value;
            } else if self.was_empty && !luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
            {
                // nothing
            } else if self.locals.find(&key).is_some() {
                *self.locals.get_or_insert(key) = Constant::default();
            }
        }
    }

    fn log_expr_change(&mut self, key: *mut AstExpr, existing: Option<Constant>) {
        if self.expr_change_log.is_null() {
            return;
        }

        let old = existing
            .or_else(|| self.constants.find(&key).copied())
            .unwrap_or_default();
        let was_absent = existing.is_none() && self.constants.find(&key).is_none();

        let log = unsafe { &mut *self.expr_change_log };
        log.push(crate::records::expr_constant_change::ExprConstantChange {
            key,
            old_value: old,
            was_absent,
        });
    }

    fn log_local_change(&mut self, key: *mut AstLocal, existing: Option<Constant>) {
        if self.local_change_log.is_null() {
            return;
        }

        let old = existing
            .or_else(|| self.locals.find(&key).copied())
            .unwrap_or_default();
        let was_absent = existing.is_none() && self.locals.find(&key).is_none();

        let log = unsafe { &mut *self.local_change_log };
        log.push(crate::records::local_constant_change::LocalConstantChange {
            key,
            old_value: old,
            was_absent,
        });
    }

    fn record_value(&mut self, local: *mut AstLocal, value: Constant) {
        let v = self.variables.find_mut(&local).unwrap();

        if !v.written {
            if luaur_common::FFlag::LuauCompileFoldOptimize.get()
                && luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
            {
                if value.r#type == crate::enums::type_constant_folding::Type::Type_Table {
                    v.constant = false;
                    self.table_locals.try_insert(local, value);
                } else {
                    v.constant =
                        value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown;
                    self.record_local_constant(local, value);
                }
            } else {
                v.constant = if luaur_common::FFlag::LuauCompilePropagateTableProps2.get() {
                    value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown
                        && value.r#type != crate::enums::type_constant_folding::Type::Type_Table
                } else {
                    value.r#type != crate::enums::type_constant_folding::Type::Type_Unknown
                };
                self.record_local_constant(local, value);
            }
        }
    }

    fn visit_stat_local(
        &mut self,
        node: *mut luaur_ast::records::ast_stat_local::AstStatLocal,
    ) -> bool {
        let node_ref = unsafe { &*node };

        for i in 0..node_ref.vars.size.min(node_ref.values.size) {
            let rhs = unsafe { *node_ref.values.data.add(i) };
            let arg = self.analyze(rhs);

            if luaur_common::FFlag::LuauCompilePropagateTableProps2.get()
                && arg.r#type == crate::enums::type_constant_folding::Type::Type_Table
            {
                let local = unsafe { *node_ref.vars.data.add(i) };

                let kind = self.constant_table_locals.find(&local);
                if let Some(k) = kind {
                    if *k == crate::enums::table_constant_kind::TableConstantKind::ConstantTable {
                        self.record_value(local, arg);
                    } else {
                        self.record_value(local, Constant::default());
                    }
                } else {
                    self.record_value(local, Constant::default());
                }
            } else {
                self.record_value(unsafe { *node_ref.vars.data.add(i) }, arg);
            }
        }

        if node_ref.vars.size > node_ref.values.size {
            let last = if node_ref.values.size > 0 {
                Some(unsafe { *node_ref.values.data.add(node_ref.values.size as usize - 1) })
            } else {
                None
            };
            let mult_ret = last.map_or(false, |l| {
                luaur_ast::rtti::ast_node_is::<luaur_ast::records::ast_expr_call::AstExprCall>(
                    l as *mut luaur_ast::records::ast_node::AstNode,
                ) || luaur_ast::rtti::ast_node_is::<
                    luaur_ast::records::ast_expr_varargs::AstExprVarargs,
                >(l as *mut luaur_ast::records::ast_node::AstNode)
            });

            if !mult_ret {
                for i in node_ref.values.size..node_ref.vars.size {
                    let nil = Constant {
                        r#type: crate::enums::type_constant_folding::Type::Type_Nil,
                        string_length: 0,
                        data: Default::default(),
                    };
                    self.record_value(unsafe { *node_ref.vars.data.add(i as usize) }, nil);
                }
            }
        } else {
            for i in node_ref.vars.size..node_ref.values.size {
                self.analyze(unsafe { *node_ref.values.data.add(i as usize) });
            }
        }

        false
    }
}

impl<'a> AstVisitor for ConstantVisitor<'a> {
    fn visit_node(&mut self, node: *mut core::ffi::c_void) -> bool {
        true
    }

    fn visit_expr(&mut self, node: *mut core::ffi::c_void) -> bool {
        self.analyze(node as *mut AstExpr);
        false
    }

    fn visit_stat_local(&mut self, node: *mut core::ffi::c_void) -> bool {
        self.visit_stat_local(node as *mut luaur_ast::records::ast_stat_local::AstStatLocal);
        false
    }
}