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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! AST Lowering Pass: Unwrap Hoisting
//!
//! This pass transforms deep property access chains that traverse SWC wrapper enums
//! into explicit pattern matching blocks.
//!
//! Example transformation:
//! ```reluxscript
//! let name = member.property.name;
//! ```
//! Becomes:
//! ```reluxscript
//! let name = {
//! let __prop = member.property;
//! if let MemberProp::Ident(__prop_inner) = &__prop {
//! __prop_inner.sym.clone()
//! } else {
//! panic!("Expected MemberProp::Ident")
//! }
//! };
//! ```
use crate::parser::{
Program, TopLevelDecl, PluginDecl, PluginItem, WriterDecl, ModuleDecl,
FnDecl, Block, Stmt, Expr, LetStmt, MemberExpr, IdentExpr, CallExpr,
IfStmt, ExprStmt, Literal, Type, AssignExpr, Pattern,
};
use crate::lexer::Span;
use crate::type_system::{
TypeContext, TypeEnvironment, get_typed_field_mapping, classify_swc_type,
SwcTypeKind, infer_expected_variant, map_reluxscript_to_swc,
};
/// The UnwrapHoister pass that lowers deep chains to explicit pattern matching
pub struct UnwrapHoister {
/// Type environment for tracking variable types
type_env: TypeEnvironment,
/// Counter for generating unique temp variable names
temp_counter: usize,
/// Counter for generating unique XPath IDs for synthetic nodes
path_id: u16,
/// Current path context
current_path: String,
}
/// Describes a single step in a property access chain that needs unwrapping
#[derive(Debug, Clone)]
struct ChainLink {
/// The field name being accessed (ReluxScript name)
field_name: String,
/// The SWC field name
swc_field: String,
/// The SWC enum type (e.g., "MemberProp", "Expr")
swc_enum_type: String,
/// The expected variant (e.g., "Ident")
swc_variant: String,
/// The unwrapped struct type (e.g., "Ident")
swc_struct: String,
/// Whether this needs Box dereference
is_boxed: bool,
}
/// Analysis of a complete chain
#[derive(Debug)]
struct ChainAnalysis {
/// The base expression (e.g., `member` in `member.property.name`)
base_expr: Expr,
/// Steps that don't need unwrapping (prefix)
simple_steps: Vec<String>,
/// Steps that need unwrapping
unwrap_steps: Vec<ChainLink>,
/// Final field access after unwrapping
final_field: String,
/// Final field's SWC name
final_swc_field: String,
}
impl UnwrapHoister {
pub fn new() -> Self {
Self {
type_env: TypeEnvironment::new(),
temp_counter: 0,
path_id: 0xF000, // Start at F000 to avoid collision with parser paths
current_path: String::new(),
}
}
/// Generate a unique hex ID for synthetic nodes
fn next_path_id(&mut self) -> String {
let id = format!("{:04X}", self.path_id);
self.path_id = self.path_id.wrapping_add(1);
id
}
/// Create a path for a synthetic node
fn make_path(&mut self, name: &str) -> String {
let id = self.next_path_id();
if self.current_path.is_empty() {
format!("{}[{}]", name, id)
} else {
format!("{}.{}[{}]", self.current_path, name, id)
}
}
fn next_temp(&mut self, prefix: &str) -> String {
self.temp_counter += 1;
format!("__{}_{}", prefix, self.temp_counter)
}
/// Run the hoisting pass on a program
pub fn run(&mut self, program: &mut Program) {
match &mut program.decl {
TopLevelDecl::Plugin(plugin) => self.visit_plugin(plugin),
TopLevelDecl::Writer(writer) => self.visit_writer(writer),
TopLevelDecl::Module(module) => self.visit_module(module),
TopLevelDecl::Interface(_) => {} // Interfaces don't need hoisting
}
}
fn visit_plugin(&mut self, plugin: &mut PluginDecl) {
for item in &mut plugin.body {
match item {
PluginItem::Function(func) => self.visit_function(func),
_ => {}
}
}
}
fn visit_writer(&mut self, writer: &mut WriterDecl) {
for item in &mut writer.body {
match item {
PluginItem::Function(func) => self.visit_function(func),
_ => {}
}
}
}
fn visit_module(&mut self, module: &mut ModuleDecl) {
for item in &mut module.items {
match item {
PluginItem::Function(func) => self.visit_function(func),
_ => {}
}
}
}
/// Define variables from a pattern in the type environment
fn define_pattern_vars(&mut self, pattern: &Pattern, type_ctx: TypeContext) {
match pattern {
Pattern::Ident(name) => {
self.type_env.define(name, type_ctx);
}
Pattern::Tuple(patterns) => {
// For tuple destructuring, give each element the base type
// (Proper implementation would track tuple element types)
for pat in patterns {
self.define_pattern_vars(pat, type_ctx.clone());
}
}
_ => {
// Other patterns not yet implemented
}
}
}
fn visit_function(&mut self, func: &mut FnDecl) {
// Set up parameter types in the environment
self.type_env.push_scope();
for param in &func.params {
let type_ctx = self.type_from_ast(¶m.ty);
self.type_env.define(¶m.name, type_ctx);
}
self.visit_block(&mut func.body);
self.type_env.pop_scope();
}
fn visit_block(&mut self, block: &mut Block) {
let mut new_stmts = Vec::new();
for stmt in block.stmts.drain(..) {
match stmt {
Stmt::Let(let_stmt) => {
// Only handle simple identifier patterns for now
if let Pattern::Ident(ref name) = let_stmt.pattern {
// Check if the init expression has a chain that needs unwrapping
if let Some(ref init) = let_stmt.init {
if let Some(analysis) = self.detect_unwrap_chain(init) {
// Transform into statements with pattern matching
let transformed = self.lower_chain_to_block(
name.clone(),
let_stmt.mutable,
analysis,
let_stmt.span,
);
new_stmts.extend(transformed);
} else {
// No transformation needed - but still track the type
let init_type = self.infer_expr_type(init);
self.type_env.define(name, init_type);
new_stmts.push(Stmt::Let(let_stmt));
}
} else {
// No init - just pass through
new_stmts.push(Stmt::Let(let_stmt));
}
} else {
// Complex patterns - just pass through without transformation
new_stmts.push(Stmt::Let(let_stmt));
}
}
Stmt::Expr(mut expr_stmt) => {
// Check for chains in expression statements and extract if needed
let extracted = self.extract_chains_from_expr(&mut expr_stmt.expr);
new_stmts.extend(extracted);
new_stmts.push(Stmt::Expr(expr_stmt));
}
Stmt::If(mut if_stmt) => {
self.visit_block(&mut if_stmt.then_branch);
for (_, block) in &mut if_stmt.else_if_branches {
self.visit_block(block);
}
if let Some(ref mut else_block) = if_stmt.else_branch {
self.visit_block(else_block);
}
new_stmts.push(Stmt::If(if_stmt));
}
Stmt::For(mut for_stmt) => {
self.type_env.push_scope();
// Infer iterator element type
let iter_type = self.infer_expr_type(&for_stmt.iter);
// Define variables from pattern
self.define_pattern_vars(&for_stmt.pattern, iter_type);
self.visit_block(&mut for_stmt.body);
self.type_env.pop_scope();
new_stmts.push(Stmt::For(for_stmt));
}
Stmt::While(mut while_stmt) => {
self.visit_block(&mut while_stmt.body);
new_stmts.push(Stmt::While(while_stmt));
}
Stmt::Loop(mut loop_stmt) => {
self.visit_block(&mut loop_stmt.body);
new_stmts.push(Stmt::Loop(loop_stmt));
}
Stmt::Return(ret) => {
// Could also extract chains from return values
new_stmts.push(Stmt::Return(ret));
}
other => new_stmts.push(other),
}
}
block.stmts = new_stmts;
}
/// Extract chains from expressions in non-let contexts
/// Returns any hoisted let statements that need to come before
fn extract_chains_from_expr(&mut self, expr: &mut Expr) -> Vec<Stmt> {
let mut hoisted = Vec::new();
match expr {
Expr::Call(call) => {
// Check arguments for chains
for arg in &mut call.args {
if let Some(analysis) = self.detect_unwrap_chain(arg) {
// Create a temp variable
let temp_name = self.next_temp("arg");
let temp_span = Span::new(0, 0, 0, 0);
// Create the hoisted statements
let hoisted_stmts = self.lower_chain_to_block(
temp_name.clone(),
false,
analysis,
temp_span,
);
hoisted.extend(hoisted_stmts);
// Replace the argument with the temp variable
*arg = Expr::Ident(IdentExpr {
name: temp_name.clone(),
span: temp_span,
path: self.make_path(&temp_name),
});
} else {
// Recursively check nested expressions
hoisted.extend(self.extract_chains_from_expr(arg));
}
}
// Check callee
hoisted.extend(self.extract_chains_from_expr(&mut call.callee));
}
Expr::Binary(bin) => {
hoisted.extend(self.extract_chains_from_expr(&mut bin.left));
hoisted.extend(self.extract_chains_from_expr(&mut bin.right));
}
Expr::Member(mem) => {
hoisted.extend(self.extract_chains_from_expr(&mut mem.object));
}
_ => {}
}
hoisted
}
/// Detect if an expression contains a chain that needs unwrapping
fn detect_unwrap_chain(&self, expr: &Expr) -> Option<ChainAnalysis> {
// Handle .clone() calls - look at the inner expression
let inner_expr = if let Expr::Call(call) = expr {
if let Expr::Member(mem) = call.callee.as_ref() {
if mem.property == "clone" && call.args.is_empty() {
// This is a .clone() call, look at the object
&*mem.object
} else {
expr
}
} else {
expr
}
} else {
expr
};
// Only handle member expressions
let _mem = match inner_expr {
Expr::Member(_mem) => _mem,
_ => return None,
};
// Collect the full chain
let mut chain_parts: Vec<(Expr, String)> = Vec::new();
let mut current = inner_expr.clone();
loop {
match current {
Expr::Member(m) => {
chain_parts.push(((*m.object).clone(), m.property.clone()));
current = (*m.object).clone();
}
_ => break,
}
}
// Reverse to get base-first order
chain_parts.reverse();
if chain_parts.is_empty() {
return None;
}
// Analyze each step for unwrap requirements
let base_expr = current;
let base_type = self.infer_expr_type(&base_expr);
let mut current_type = base_type;
let mut simple_steps = Vec::new();
let mut unwrap_steps = Vec::new();
let mut found_unwrap = false;
for (i, (_, field)) in chain_parts.iter().enumerate() {
// Get field mapping
let mapping = get_typed_field_mapping(¤t_type.swc_type, field);
if let Some(m) = mapping {
let result_kind = classify_swc_type(m.swc_type);
// Check if this step needs unwrapping
if matches!(result_kind, SwcTypeKind::WrapperEnum | SwcTypeKind::Enum) {
found_unwrap = true;
// Try to infer the expected variant from the next field access
let next_field = if i + 1 < chain_parts.len() {
Some(&chain_parts[i + 1].1)
} else {
None
};
if let Some(next) = next_field {
if let Some(variant) = infer_expected_variant(m.swc_type, next) {
// For now, use the variant name as struct name too
// (proper implementation would look this up properly)
let struct_name = variant.clone();
unwrap_steps.push(ChainLink {
field_name: field.clone(),
swc_field: m.swc.to_string(),
swc_enum_type: m.swc_type.to_string(),
swc_variant: variant,
swc_struct: struct_name.clone(),
is_boxed: m.needs_box_unwrap,
});
// Update current type to the unwrapped struct
// We need to look up the struct type
let (_, kind) = map_reluxscript_to_swc(&unwrap_steps.last().unwrap().swc_struct);
current_type = TypeContext {
reluxscript_type: m.reluxscript.to_string(),
swc_type: unwrap_steps.last().unwrap().swc_struct.clone(),
kind,
known_variant: None,
needs_deref: false,
};
continue;
}
}
// Can't infer variant - can't auto-unwrap
return None;
} else if !found_unwrap {
// Simple step before any unwrapping
simple_steps.push(field.clone());
}
// Update current type
let (_, kind) = map_reluxscript_to_swc(m.reluxscript);
current_type = TypeContext {
reluxscript_type: m.reluxscript.to_string(),
swc_type: m.swc_type.to_string(),
kind,
known_variant: None,
needs_deref: m.needs_box_unwrap,
};
} else {
// Unknown field - can't analyze
if found_unwrap {
// We're after an unwrap, this must be the final field
// Get the final field mapping
let final_mapping = get_typed_field_mapping(¤t_type.swc_type, field);
let final_swc = final_mapping.map(|m| m.swc.to_string())
.unwrap_or_else(|| field.clone());
return Some(ChainAnalysis {
base_expr,
simple_steps,
unwrap_steps,
final_field: field.clone(),
final_swc_field: final_swc,
});
}
return None;
}
}
// Check if we found any unwrap steps
if unwrap_steps.is_empty() {
return None;
}
// Get final field info
let last_field = &chain_parts.last()?.1;
let final_mapping = get_typed_field_mapping(¤t_type.swc_type, last_field);
let final_swc = final_mapping.map(|m| m.swc.to_string())
.unwrap_or_else(|| last_field.clone());
Some(ChainAnalysis {
base_expr,
simple_steps,
unwrap_steps,
final_field: last_field.clone(),
final_swc_field: final_swc,
})
}
/// Transform a chain into a block with pattern matching
///
/// Transforms:
/// ```reluxscript
/// let name = member.property.name;
/// ```
/// Into:
/// ```reluxscript
/// let __prop_1 = member.property;
/// if matches!(__prop_1, Identifier) {
/// let name = __prop_1.name.clone();
/// } else {
/// panic!("Expected Identifier");
/// }
/// ```
fn lower_chain_to_block(
&mut self,
target_var: String,
mutable: bool,
analysis: ChainAnalysis,
span: Span,
) -> Vec<Stmt> {
// Build the base access with simple steps
let mut base_access = analysis.base_expr.clone();
for step in &analysis.simple_steps {
base_access = Expr::Member(MemberExpr {
object: Box::new(base_access),
property: step.clone(),
optional: false,
computed: false,
is_path: false,
span,
path: self.make_path(step),
});
}
// Handle the unwrap steps - for now we handle single unwrap
// TODO: Support nested unwraps (multiple unwrap_steps)
if let Some(unwrap) = analysis.unwrap_steps.first() {
// Step 1: Create the intermediate let statement
// let __prop_1 = member.property;
let temp_name = self.next_temp(&unwrap.field_name);
let temp_access = Expr::Member(MemberExpr {
object: Box::new(base_access),
property: unwrap.field_name.clone(),
optional: false,
computed: false,
is_path: false,
span,
path: self.make_path(&unwrap.field_name),
});
// Add explicit type annotation so codegen knows this is a MemberProp
let temp_let = Stmt::Let(LetStmt {
mutable: false,
pattern: Pattern::Ident(temp_name.clone()),
ty: Some(Type::Named(unwrap.swc_enum_type.clone())),
init: Some(temp_access),
span,
path: self.make_path(&temp_name),
});
// Track the temp variable's type in our environment
let temp_type = TypeContext {
reluxscript_type: unwrap.swc_enum_type.clone(),
swc_type: unwrap.swc_enum_type.clone(),
kind: SwcTypeKind::WrapperEnum,
known_variant: None,
needs_deref: false,
};
self.type_env.define(&temp_name, temp_type);
// Step 2: Create the matches! condition
// matches!(__prop_1, Identifier)
let matches_condition = Expr::Call(CallExpr {
callee: Box::new(Expr::Ident(IdentExpr {
name: "matches!".to_string(),
span,
path: self.make_path("matches"),
})),
args: vec![
Expr::Ident(IdentExpr {
name: temp_name.clone(),
span,
path: self.make_path(&temp_name),
}),
Expr::Ident(IdentExpr {
name: self.swc_variant_to_reluxscript(&unwrap.swc_struct),
span,
path: self.make_path(&unwrap.swc_struct),
}),
],
type_args: Vec::new(),
optional: false,
is_macro: true,
span,
path: self.make_path("call"),
});
// Step 3: Create declaration for target variable (must be mutable for assignment)
// let mut name = Default::default();
let target_decl = Stmt::Let(LetStmt {
mutable: true, // Must be mutable since we assign in the if block
pattern: Pattern::Ident(target_var.clone()),
ty: None,
// Use a placeholder that will be assigned in the if
init: Some(Expr::Ident(IdentExpr {
name: "Default::default()".to_string(),
span,
path: self.make_path("default"),
})),
span,
path: self.make_path(&target_var),
});
// Step 4: Create the inner assignment with final field access
// name = __prop_1.name.clone();
let inner_access = Expr::Member(MemberExpr {
object: Box::new(Expr::Ident(IdentExpr {
name: temp_name.clone(),
span,
path: self.make_path(&temp_name),
})),
property: analysis.final_field.clone(),
optional: false,
computed: false,
is_path: false,
span,
path: self.make_path(&analysis.final_field),
});
// Add .clone() call
let cloned_access = Expr::Call(CallExpr {
callee: Box::new(Expr::Member(MemberExpr {
object: Box::new(inner_access),
property: "clone".to_string(),
optional: false,
computed: false,
is_path: false,
span,
path: self.make_path("clone"),
})),
args: vec![],
type_args: Vec::new(),
optional: false,
is_macro: false,
span,
path: self.make_path("call"),
});
let inner_assign = Stmt::Expr(ExprStmt {
expr: Expr::Assign(AssignExpr {
target: Box::new(Expr::Ident(IdentExpr {
name: target_var.clone(),
span,
path: self.make_path(&target_var),
})),
value: Box::new(cloned_access),
span,
path: self.make_path("assign"),
}),
span,
});
// Step 5: Create the if statement with the pattern match
let if_stmt = Stmt::If(IfStmt {
condition: matches_condition,
pattern: None, // Not an if-let, just a regular if with matches!
then_branch: Block {
stmts: vec![inner_assign],
span,
path: self.make_path("then"),
},
else_if_branches: vec![],
else_branch: Some(Block {
stmts: vec![
// panic!("Expected {}")
Stmt::Expr(ExprStmt {
expr: Expr::Call(CallExpr {
callee: Box::new(Expr::Ident(IdentExpr {
name: "panic!".to_string(),
span,
path: self.make_path("panic"),
})),
args: vec![
Expr::Literal(Literal::String(format!(
"Expected {} for .{} access",
unwrap.swc_struct,
analysis.final_field
))),
],
type_args: Vec::new(),
optional: false,
is_macro: true,
span,
path: self.make_path("call"),
}),
span,
}),
],
span,
path: self.make_path("else"),
}),
span,
path: self.make_path("if"),
});
// Track the type of the target variable
let final_type = TypeContext::from_reluxscript(&unwrap.swc_struct);
self.type_env.define(&target_var, final_type);
// Return the statements to splice into the parent block
return vec![temp_let, target_decl, if_stmt];
}
// No unwrap needed - return original as single statement
let final_field = analysis.final_field.clone();
vec![Stmt::Let(LetStmt {
mutable,
pattern: Pattern::Ident(target_var.clone()),
ty: None,
init: Some(Expr::Member(MemberExpr {
object: Box::new(analysis.base_expr),
property: analysis.final_field,
optional: false,
computed: false,
is_path: false,
span,
path: self.make_path(&final_field),
})),
span,
path: self.make_path(&target_var),
})]
}
/// Convert SWC struct name back to ReluxScript type name for matches!
fn swc_variant_to_reluxscript(&self, swc_struct: &str) -> String {
match swc_struct {
"Ident" => "Identifier".to_string(),
"MemberExpr" => "MemberExpression".to_string(),
"CallExpr" => "CallExpression".to_string(),
"Str" => "StringLiteral".to_string(),
"Number" => "NumericLiteral".to_string(),
"Bool" => "BooleanLiteral".to_string(),
"BindingIdent" => "Identifier".to_string(),
_ => swc_struct.to_string(),
}
}
/// Convert an AST type to a TypeContext
fn type_from_ast(&self, ty: &Type) -> TypeContext {
match ty {
Type::Named(name) => TypeContext::from_reluxscript(name),
Type::Reference { inner, .. } => self.type_from_ast(inner),
_ => TypeContext::unknown(),
}
}
/// Infer the type of an expression
fn infer_expr_type(&self, expr: &Expr) -> TypeContext {
match expr {
Expr::Ident(ident) => {
self.type_env.lookup(&ident.name)
.cloned()
.unwrap_or(TypeContext::unknown())
}
Expr::Member(mem) => {
let obj_type = self.infer_expr_type(&mem.object);
if let Some(mapping) = get_typed_field_mapping(&obj_type.swc_type, &mem.property) {
let (_, kind) = map_reluxscript_to_swc(mapping.reluxscript);
TypeContext {
reluxscript_type: mapping.reluxscript.to_string(),
swc_type: mapping.swc_type.to_string(),
kind,
known_variant: None,
needs_deref: mapping.needs_box_unwrap,
}
} else {
TypeContext::unknown()
}
}
Expr::Call(call) => {
// Check for .clone() which preserves type
if let Expr::Member(mem) = call.callee.as_ref() {
if mem.property == "clone" && call.args.is_empty() {
return self.infer_expr_type(&mem.object);
}
}
TypeContext::unknown()
}
_ => TypeContext::unknown(),
}
}
}
impl Default for UnwrapHoister {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detect_simple_chain() {
let hoister = UnwrapHoister::new();
// Create: member.property
let expr = Expr::Member(MemberExpr {
object: Box::new(Expr::Ident(IdentExpr {
name: "member".to_string(),
span: Span::new(0, 0, 0, 0),
})),
property: "property".to_string(),
optional: false,
computed: false,
is_path: false,
span: Span::new(0, 0, 0, 0),
});
// This should not be detected as needing unwrap
// because there's no subsequent .name access
let result = hoister.detect_unwrap_chain(&expr);
assert!(result.is_none());
}
#[test]
fn test_detect_deep_chain() {
let mut hoister = UnwrapHoister::new();
// Set up type environment - pretend we have a MemberExpr variable
hoister.type_env.define("member", TypeContext::narrowed("MemberExpression", "MemberExpr"));
// Create: member.property.name
let expr = Expr::Member(MemberExpr {
object: Box::new(Expr::Member(MemberExpr {
object: Box::new(Expr::Ident(IdentExpr {
name: "member".to_string(),
span: Span::new(0, 0, 0, 0),
})),
property: "property".to_string(),
optional: false,
computed: false,
is_path: false,
span: Span::new(0, 0, 0, 0),
})),
property: "name".to_string(),
optional: false,
computed: false,
is_path: false,
span: Span::new(0, 0, 0, 0),
});
// This SHOULD be detected as needing unwrap
// because property returns MemberProp (WrapperEnum)
// and .name only works on MemberProp::Ident
let result = hoister.detect_unwrap_chain(&expr);
// For now, check if we got any result
// The detect_unwrap_chain may return None if it can't infer the variant
if let Some(analysis) = result {
assert!(!analysis.unwrap_steps.is_empty(), "Should have unwrap steps");
println!("Analysis: {:?}", analysis);
} else {
// If None, it means the chain detection needs improvement
// to properly track the type of 'member' from the environment
println!("Chain not detected - type inference may need improvement");
}
}
}