-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmod.rs
More file actions
1430 lines (1378 loc) · 59.9 KB
/
mod.rs
File metadata and controls
1430 lines (1378 loc) · 59.9 KB
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Reify phase.
//!
//! Converts IR operations to Output AST statements.
//!
//! After this phase, the create_statements and update_statements fields
//! of each ViewCompilationUnit are populated with the generated JavaScript
//! statements that call the Angular runtime instructions.
//!
//! Ported from Angular's `template/pipeline/src/phases/reify.ts`.
mod angular_expression;
pub(crate) mod ir_expression;
mod statements;
mod utils;
use oxc_allocator::{Box, Vec as OxcVec};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::Atom;
use rustc_hash::FxHashMap;
use crate::ast::expression::AngularExpression;
use crate::ir::enums::BindingKind;
use crate::ir::expression::IrExpression;
use crate::ir::ops::{CreateOp, UpdateOp, XrefId};
use crate::output::ast::{
ArrowFunctionBody, ArrowFunctionExpr, FnParam, FunctionExpr, InvokeFunctionExpr, LiteralExpr,
LiteralValue, OutputExpression, OutputStatement, ReadPropExpr, ReadVarExpr, ReturnStatement,
clone_output_statement,
};
use crate::pipeline::compilation::{
ComponentCompilationJob, HostBindingCompilationJob, TemplateCompilationMode,
ViewCompilationUnit,
};
use crate::pipeline::constant_pool::ConstantPool;
use crate::pipeline::expression_store::ExpressionStore;
use angular_expression::convert_angular_expression;
use ir_expression::convert_ir_expression;
use statements::*;
use utils::strip_prefix;
use crate::output::ast::ExpressionStatement;
/// Converts an OutputStatement that may contain WrappedIrNode expressions
/// to a proper OutputStatement with all IR expressions converted.
fn convert_statement_ir_nodes<'a>(
allocator: &'a oxc_allocator::Allocator,
stmt: &OutputStatement<'a>,
expressions: &ExpressionStore<'a>,
root_xref: XrefId,
diagnostics: &mut Vec<OxcDiagnostic>,
) -> OutputStatement<'a> {
match stmt {
OutputStatement::Return(ret) => {
let converted_expr =
convert_output_expr_ir_nodes(allocator, &ret.value, expressions, root_xref);
OutputStatement::Return(Box::new_in(
ReturnStatement { value: converted_expr, source_span: ret.source_span },
allocator,
))
}
OutputStatement::Expression(expr_stmt) => {
let converted_expr =
convert_output_expr_ir_nodes(allocator, &expr_stmt.expr, expressions, root_xref);
OutputStatement::Expression(Box::new_in(
ExpressionStatement { expr: converted_expr, source_span: expr_stmt.source_span },
allocator,
))
}
// Other statement types pass through (they don't contain WrappedIrNode)
OutputStatement::DeclareVar(_)
| OutputStatement::DeclareFunction(_)
| OutputStatement::If(_) => {
// These shouldn't appear in listener handler_ops.
// Emit a warning for unexpected statement types.
diagnostics.push(OxcDiagnostic::warn(
"Unexpected statement type in handler_ops. Only Return and Expression statements are expected."
));
// Return the statement unchanged as a fallback
clone_output_statement(stmt, allocator)
}
}
}
/// Converts an OutputExpression that may be a WrappedIrNode to a proper OutputExpression.
fn convert_output_expr_ir_nodes<'a>(
allocator: &'a oxc_allocator::Allocator,
expr: &OutputExpression<'a>,
expressions: &ExpressionStore<'a>,
root_xref: XrefId,
) -> OutputExpression<'a> {
match expr {
OutputExpression::WrappedIrNode(wrapped) => {
// Convert the wrapped IR expression to a proper output expression
convert_ir_expression(allocator, &wrapped.node, expressions, root_xref)
}
// All other expressions are already proper output expressions
// Clone them to get owned values
other => other.clone_in(allocator),
}
}
/// Context for reifying operations, holding information needed across views.
struct ReifyContext<'a> {
/// Map from view xref to its function name (set by naming phase).
view_fn_names: FxHashMap<XrefId, Atom<'a>>,
/// Map from view xref to its declaration count.
view_decls: FxHashMap<XrefId, u32>,
/// Map from view xref to its variable count.
view_vars: FxHashMap<XrefId, u32>,
/// Template compilation mode (Full or DomOnly).
mode: TemplateCompilationMode,
/// Whether to use `ɵɵconditionalCreate` (Angular 20+) or `ɵɵtemplate` (Angular 19-).
supports_conditional_create: bool,
}
/// Reifies IR expressions to Output AST.
///
/// This phase converts all IR operations into output statements containing
/// runtime instruction calls (ɵɵelementStart, ɵɵtext, ɵɵproperty, etc.).
pub fn reify(job: &mut ComponentCompilationJob<'_>) {
let allocator = job.allocator;
let root_xref = job.root.xref;
let mode = job.mode;
let mut diagnostics = Vec::new();
// Build context with view function names, decl counts, and var counts.
// This allows us to reference embedded view functions when reifying TemplateOp/RepeaterCreate/Projection.
let mut view_fn_names = FxHashMap::default();
let mut view_decls = FxHashMap::default();
let mut view_vars = FxHashMap::default();
for view in job.all_views() {
if let Some(fn_name) = &view.fn_name {
view_fn_names.insert(view.xref, fn_name.clone());
}
if let Some(decl_count) = view.decl_count {
view_decls.insert(view.xref, decl_count);
}
if let Some(vars) = view.vars {
view_vars.insert(view.xref, vars);
}
}
let supports_conditional_create = job.supports_conditional_create();
let ctx =
ReifyContext { view_fn_names, view_decls, view_vars, mode, supports_conditional_create };
// Collect xrefs of embedded views (excluding root) before splitting borrows
let embedded_xrefs: std::vec::Vec<XrefId> =
job.all_views().filter(|v| v.xref != root_xref).map(|v| v.xref).collect();
// Process root view first using split borrow
{
let ComponentCompilationJob { expressions, root, pool, .. } = job;
let (create_stmts, update_stmts) = reify_view_to_stmts(
allocator,
root,
expressions,
pool,
root_xref,
&ctx,
&mut diagnostics,
);
root.create_statements.extend(create_stmts);
root.update_statements.extend(update_stmts);
}
// Process embedded views using split borrow
for xref in embedded_xrefs {
let ComponentCompilationJob { expressions, views, pool, .. } = job;
if let Some(view) = views.get_mut(&xref) {
let view = view.as_mut();
let (create_stmts, update_stmts) = reify_view_to_stmts(
allocator,
view,
expressions,
pool,
root_xref,
&ctx,
&mut diagnostics,
);
view.create_statements.extend(create_stmts);
view.update_statements.extend(update_stmts);
}
}
job.diagnostics.extend(diagnostics);
}
/// Reify a single view's operations to statements (without modifying the view).
fn reify_view_to_stmts<'a>(
allocator: &'a oxc_allocator::Allocator,
view: &mut ViewCompilationUnit<'a>,
expressions: &ExpressionStore<'a>,
pool: &mut ConstantPool<'a>,
root_xref: XrefId,
ctx: &ReifyContext<'a>,
diagnostics: &mut Vec<OxcDiagnostic>,
) -> (std::vec::Vec<OutputStatement<'a>>, std::vec::Vec<OutputStatement<'a>>) {
let mut create_stmts = std::vec::Vec::new();
let mut update_stmts = std::vec::Vec::new();
// Reify create operations
// Use iter_mut() so we can take ownership of expressions that can't be cloned
for op in view.create.iter_mut() {
let stmt = reify_create_op(allocator, op, expressions, pool, root_xref, ctx, diagnostics);
if let Some(s) = stmt {
create_stmts.push(s);
}
}
// Reify update operations
for op in view.update.iter() {
let stmt = reify_update_op(allocator, op, expressions, root_xref, ctx.mode, diagnostics);
if let Some(s) = stmt {
update_stmts.push(s);
}
}
(create_stmts, update_stmts)
}
/// Reify a single create operation to a statement.
fn reify_create_op<'a>(
allocator: &'a oxc_allocator::Allocator,
op: &mut CreateOp<'a>,
expressions: &ExpressionStore<'a>,
pool: &mut ConstantPool<'a>,
root_xref: XrefId,
ctx: &ReifyContext<'a>,
diagnostics: &mut Vec<OxcDiagnostic>,
) -> Option<OutputStatement<'a>> {
let is_dom_only = ctx.mode == TemplateCompilationMode::DomOnly;
match op {
CreateOp::ElementStart(elem) => {
let slot = elem.slot.map(|s| s.0).unwrap_or(0);
let local_refs_index = elem.local_refs_index;
if is_dom_only {
Some(create_dom_element_start_stmt(
allocator,
&elem.tag,
slot,
elem.attributes,
local_refs_index,
))
} else {
Some(create_element_start_stmt(
allocator,
&elem.tag,
slot,
elem.attributes,
local_refs_index,
))
}
}
CreateOp::Element(elem) => {
let slot = elem.slot.map(|s| s.0).unwrap_or(0);
let local_refs_index = elem.local_refs_index;
if is_dom_only {
Some(create_dom_element_stmt(
allocator,
&elem.tag,
slot,
elem.attributes,
local_refs_index,
))
} else {
Some(create_element_stmt(
allocator,
&elem.tag,
slot,
elem.attributes,
local_refs_index,
))
}
}
CreateOp::ElementEnd(_) => {
if is_dom_only {
Some(create_dom_element_end_stmt(allocator))
} else {
Some(create_element_end_stmt(allocator))
}
}
CreateOp::Text(text) => {
let slot = text.slot.map(|s| s.0).unwrap_or(0);
let initial_value = if text.initial_value.as_str().is_empty() {
None
} else {
Some(text.initial_value.as_str())
};
Some(create_text_stmt(allocator, slot, initial_value))
}
CreateOp::Template(tmpl) => {
// Look up the function name for this template's embedded view
let fn_name = ctx.view_fn_names.get(&tmpl.embedded_view).cloned();
let decls = tmpl.decl_count;
let vars = tmpl.vars;
let slot = tmpl.slot.map(|s| s.0).unwrap_or(0);
let tag = tmpl.tag.as_ref();
let attributes = tmpl.attributes;
let local_refs_index = tmpl.local_refs_index;
// Block templates can't have directives so we can always generate them as DOM-only.
// In DomOnly mode, all templates use domTemplate because there are no directive deps.
// This matches Angular's reify.ts:
// op.templateKind === ir.TemplateKind.Block || unit.job.mode === TemplateCompilationMode.DomOnly
let use_dom_template =
tmpl.template_kind == crate::ir::enums::TemplateKind::Block || is_dom_only;
if use_dom_template {
Some(create_dom_template_stmt(
allocator,
slot,
fn_name,
decls,
vars,
tag,
attributes,
local_refs_index,
))
} else {
Some(create_template_stmt(
allocator,
slot,
fn_name,
decls,
vars,
tag,
attributes,
local_refs_index,
))
}
}
CreateOp::Listener(listener) => {
// Convert handler_ops to statements for the handler function
let mut handler_stmts = OxcVec::new_in(allocator);
// Process handler_ops if present (new approach aligned with Angular)
// These include Variable ops (e.g., RestoreView) added by save_restore_view phase
for handler_op in listener.handler_ops.iter() {
if let UpdateOp::Statement(stmt_op) = handler_op {
// Convert WrappedIrNode expressions in the statement to output expressions
let converted_stmt = convert_statement_ir_nodes(
allocator,
&stmt_op.statement,
expressions,
root_xref,
diagnostics,
);
handler_stmts.push(converted_stmt);
} else if let Some(stmt) = reify_update_op(
allocator,
handler_op,
expressions,
root_xref,
ctx.mode,
diagnostics,
) {
handler_stmts.push(stmt);
}
}
// Always add handler_expression as a return statement at the end
// This is the actual event handler logic
if let Some(handler_expr) = &listener.handler_expression {
let output_expr =
convert_ir_expression(allocator, handler_expr, expressions, root_xref);
// Use return statement so the handler returns the result
handler_stmts.push(OutputStatement::Return(Box::new_in(
ReturnStatement { value: output_expr, source_span: None },
allocator,
)));
}
// Parse global event target (window, document, body) if present
let event_target = listener
.event_target
.as_ref()
.and_then(|target| GlobalEventTarget::from_str(target.as_str()));
// Use domListener in DomOnly mode when not a host listener or animation listener
let use_dom_listener =
is_dom_only && !listener.host_listener && !listener.is_animation_listener;
// use_capture is true when both host_listener and is_animation_listener are true
let use_capture = listener.host_listener && listener.is_animation_listener;
if use_dom_listener {
Some(create_dom_listener_stmt_with_handler(
allocator,
&listener.name,
handler_stmts,
event_target,
listener.handler_fn_name.as_ref(),
listener.consumes_dollar_event,
))
} else {
Some(create_listener_stmt_with_handler(
allocator,
&listener.name,
handler_stmts,
event_target,
use_capture,
listener.handler_fn_name.as_ref(),
listener.consumes_dollar_event,
))
}
}
CreateOp::Projection(proj) => {
let slot = proj.slot.map(|s| s.0).unwrap_or(0);
let projection_slot_index = proj.projection_slot_index;
// Get fallback view info if present
let (fallback_fn_name, fallback_decls, fallback_vars) =
if let Some(fallback_xref) = proj.fallback {
let fn_name = ctx.view_fn_names.get(&fallback_xref).map(|a| a.as_str());
let decls = ctx.view_decls.get(&fallback_xref).copied();
let vars = ctx.view_vars.get(&fallback_xref).copied();
(fn_name, decls, vars)
} else {
(None, None, None)
};
// Take ownership of attributes (moves it out of proj)
let attributes = std::mem::take(&mut proj.attributes);
Some(create_projection_stmt(
allocator,
slot,
projection_slot_index,
attributes,
fallback_fn_name,
fallback_decls,
fallback_vars,
))
}
CreateOp::Container(container) => {
let slot = container.slot.map(|s| s.0).unwrap_or(0);
let attributes = container.attributes;
let local_refs_index = container.local_refs_index;
if is_dom_only {
Some(create_dom_container_stmt(allocator, slot, attributes, local_refs_index))
} else {
Some(create_container_stmt(allocator, slot, attributes, local_refs_index))
}
}
CreateOp::ContainerEnd(_) => {
if is_dom_only {
Some(create_dom_container_end_stmt(allocator))
} else {
Some(create_container_end_stmt(allocator))
}
}
CreateOp::DeclareLet(decl) => {
let slot = decl.slot.map(|s| s.0).unwrap_or(0);
Some(create_declare_let_stmt(allocator, slot))
}
CreateOp::Conditional(cond) => {
// Look up the function name for this branch's view
let fn_name = ctx.view_fn_names.get(&cond.xref).cloned();
let slot = cond.slot.map(|s| s.0).unwrap_or(0);
if ctx.supports_conditional_create {
// Angular 20+: Emit ɵɵconditionalCreate for the first branch in @if/@switch
Some(create_conditional_create_stmt(
allocator,
slot,
fn_name,
cond.decls,
cond.vars,
cond.tag.as_ref(),
cond.attributes,
cond.local_refs_index,
))
} else {
// Angular 19: Emit ɵɵtemplate instead (conditionalCreate doesn't exist)
Some(create_template_stmt(
allocator,
slot,
fn_name,
cond.decls,
cond.vars,
cond.tag.as_ref(),
cond.attributes,
cond.local_refs_index,
))
}
}
CreateOp::RepeaterCreate(repeater) => {
// Emit repeaterCreate instruction for @for
// Look up the function name for the repeater's body view (not xref!)
let fn_name = ctx.view_fn_names.get(&repeater.body_view).cloned();
// Look up empty view function name if present
let empty_fn_name =
repeater.empty_view.and_then(|ev| ctx.view_fn_names.get(&ev).cloned());
let slot = repeater.slot.map(|s| s.0).unwrap_or(0);
// Generate track function if not already set by optimization phase
// Ported from Angular's reifyTrackBy() in reify.ts
let track_fn_expr = reify_track_by(
allocator,
pool,
expressions,
root_xref,
&repeater.track,
repeater.track_fn_name.as_ref(),
repeater.uses_component_instance,
&mut repeater.track_by_ops,
diagnostics,
);
Some(create_repeater_create_stmt_with_track_expr(
allocator,
slot,
fn_name,
repeater.decls,
repeater.vars,
repeater.tag.as_ref(),
repeater.attributes,
track_fn_expr,
repeater.uses_component_instance,
empty_fn_name,
repeater.empty_decl_count,
repeater.empty_var_count,
repeater.empty_tag.as_ref(),
repeater.empty_attributes,
))
}
CreateOp::Pipe(pipe) => {
// Emit pipe instruction
let slot = pipe.slot.map(|s| s.0).unwrap_or(0);
Some(create_pipe_stmt(allocator, slot, &pipe.name))
}
CreateOp::Defer(defer) => {
// Emit defer instruction for @defer
let slot = defer.slot.map(|s| s.0).unwrap_or(0);
// Extract const indices from resolved ConstReference expressions.
// By this point, Phase 53 (collectConstExpressions) has replaced
// ConstCollectedExpr with ConstReference(index).
let loading_config = defer.loading_config.as_ref().and_then(|expr| {
if let crate::ir::expression::IrExpression::ConstReference(cr) = expr.as_ref() {
Some(cr.index)
} else {
None
}
});
let placeholder_config = defer.placeholder_config.as_ref().and_then(|expr| {
if let crate::ir::expression::IrExpression::ConstReference(cr) = expr.as_ref() {
Some(cr.index)
} else {
None
}
});
Some(create_defer_stmt(
allocator,
slot,
defer.main_slot.map(|s| s.0),
defer.resolver_fn.take(),
defer.loading_slot.map(|s| s.0),
defer.placeholder_slot.map(|s| s.0),
defer.error_slot.map(|s| s.0),
loading_config,
placeholder_config,
defer.flags,
))
}
CreateOp::DeferOn(defer_on) => {
// Emit deferOn instruction based on trigger kind
let options = defer_on
.options
.as_ref()
.map(|expr| convert_ir_expression(allocator, expr, expressions, root_xref));
Some(create_defer_on_stmt(
allocator,
defer_on.trigger,
defer_on.target_slot.map(|s| s.0),
defer_on.target_slot_view_steps,
defer_on.modifier,
defer_on.delay,
options,
))
}
CreateOp::I18nStart(i18n) => {
// Emit i18nStart instruction
let slot = i18n.slot.map(|s| s.0).unwrap_or(0);
Some(create_i18n_start_stmt(
allocator,
slot,
i18n.message_index,
i18n.sub_template_index,
))
}
CreateOp::I18n(i18n) => {
// Emit i18n instruction
let slot = i18n.slot.map(|s| s.0).unwrap_or(0);
Some(create_i18n_stmt(allocator, slot, i18n.message_index, i18n.sub_template_index))
}
CreateOp::I18nEnd(_) => {
// Emit i18nEnd instruction
Some(create_i18n_end_stmt(allocator))
}
CreateOp::Namespace(ns) => {
// Emit namespace change instruction
Some(create_namespace_stmt(allocator, ns.active))
}
CreateOp::ProjectionDef(proj_def) => {
// Emit projectionDef instruction with R3 format def expression
Some(create_projection_def_stmt_from_expr(allocator, proj_def.def.as_ref()))
}
CreateOp::DisableBindings(_) => {
// Emit disableBindings instruction
Some(create_disable_bindings_stmt(allocator))
}
CreateOp::EnableBindings(_) => {
// Emit enableBindings instruction
Some(create_enable_bindings_stmt(allocator))
}
CreateOp::TwoWayListener(listener) => {
// Emit twoWayListener instruction
// Convert handler_ops to statements for the handler function
let mut handler_stmts = OxcVec::new_in(allocator);
for handler_op in listener.handler_ops.iter() {
// Handle Statement ops specially to convert WrappedIrNode expressions
if let UpdateOp::Statement(stmt_op) = handler_op {
// Convert WrappedIrNode expressions in the statement to output expressions
let converted_stmt = convert_statement_ir_nodes(
allocator,
&stmt_op.statement,
expressions,
root_xref,
diagnostics,
);
handler_stmts.push(converted_stmt);
} else if let Some(stmt) = reify_update_op(
allocator,
handler_op,
expressions,
root_xref,
ctx.mode,
diagnostics,
) {
handler_stmts.push(stmt);
}
}
Some(create_two_way_listener_stmt(
allocator,
&listener.name,
handler_stmts,
listener.handler_fn_name.as_ref(),
))
}
CreateOp::AnimationListener(listener) => {
// Emit syntheticHostListener instruction for animation listeners
let mut handler_stmts = OxcVec::new_in(allocator);
for handler_op in listener.handler_ops.iter() {
if let Some(stmt) = reify_update_op(
allocator,
handler_op,
expressions,
root_xref,
ctx.mode,
diagnostics,
) {
handler_stmts.push(stmt);
}
}
Some(create_animation_listener_stmt(
allocator,
&listener.name,
listener.phase,
handler_stmts,
listener.handler_fn_name.as_ref(),
listener.consumes_dollar_event,
))
}
CreateOp::AnimationString(anim) => {
// Emit ɵɵanimateEnter or ɵɵanimateLeave instruction for animation string bindings
let expr = convert_ir_expression(allocator, &anim.expression, expressions, root_xref);
Some(create_animation_string_stmt(allocator, anim.animation_kind, expr))
}
CreateOp::Animation(anim) => {
// Emit ɵɵanimateEnter or ɵɵanimateLeave instruction for animation bindings (Value kind)
// The handler_ops contain a return statement with the expression
let mut handler_stmts = OxcVec::new_in(allocator);
for handler_op in anim.handler_ops.iter() {
if let Some(stmt) = reify_update_op(
allocator,
handler_op,
expressions,
root_xref,
ctx.mode,
diagnostics,
) {
handler_stmts.push(stmt);
}
}
Some(create_animation_op_stmt(
allocator,
anim.animation_kind,
handler_stmts,
anim.handler_fn_name.as_ref(),
))
}
CreateOp::Variable(var) => {
// Emit variable declaration with initializer
// All Variable ops use `const` (StmtModifier::Final), matching Angular's reify.ts
let value = convert_ir_expression(allocator, &var.initializer, expressions, root_xref);
Some(create_variable_decl_stmt_with_value(allocator, &var.name, value))
}
CreateOp::ContainerStart(container) => {
// Emit elementContainerStart instruction
let slot = container.slot.map(|s| s.0).unwrap_or(0);
let attributes = container.attributes;
let local_refs_index = container.local_refs_index;
if is_dom_only {
Some(create_dom_container_start_stmt(allocator, slot, attributes, local_refs_index))
} else {
Some(create_container_start_stmt(allocator, slot, attributes, local_refs_index))
}
}
CreateOp::I18nAttributes(i18n_attrs) => {
// Emit ɵɵi18nAttributes instruction only if config is set
if let Some(config_index) = i18n_attrs.i18n_attributes_config {
use crate::ir::ops::I18nSlotHandle;
let slot = match i18n_attrs.handle {
I18nSlotHandle::Single(slot_id) => slot_id.0,
I18nSlotHandle::Range(start, _) => start.0,
};
Some(create_i18n_attributes_stmt(allocator, slot, config_index))
} else {
None
}
}
CreateOp::ConditionalBranch(branch) => {
// Look up the function name for this branch's view
let fn_name = ctx.view_fn_names.get(&branch.xref).cloned();
let slot = branch.slot.map(|s| s.0).unwrap_or(0);
if ctx.supports_conditional_create {
// Angular 20+: Emit ɵɵconditionalBranchCreate for branches after the first
Some(create_conditional_branch_create_stmt(
allocator,
slot,
fn_name,
branch.decls,
branch.vars,
branch.tag.as_ref(),
branch.attributes,
branch.local_refs_index,
))
} else {
// Angular 19: Emit ɵɵtemplate instead (conditionalBranchCreate doesn't exist)
Some(create_template_stmt(
allocator,
slot,
fn_name,
branch.decls,
branch.vars,
branch.tag.as_ref(),
branch.attributes,
branch.local_refs_index,
))
}
}
CreateOp::ControlCreate(_) => {
// Emit ɵɵcontrolCreate instruction for control binding initialization
Some(create_control_create_stmt(allocator))
}
// Non-emitting operations
CreateOp::ListEnd(_)
| CreateOp::I18nMessage(_)
| CreateOp::I18nContext(_)
| CreateOp::IcuStart(_)
| CreateOp::IcuEnd(_)
| CreateOp::IcuPlaceholder(_)
| CreateOp::ExtractedAttribute(_)
| CreateOp::SourceLocation(_)
| CreateOp::Statement(_) => None,
}
}
/// Reify a single update operation to a statement.
fn reify_update_op<'a>(
allocator: &'a oxc_allocator::Allocator,
op: &UpdateOp<'a>,
expressions: &ExpressionStore<'a>,
root_xref: XrefId,
mode: TemplateCompilationMode,
diagnostics: &mut Vec<OxcDiagnostic>,
) -> Option<OutputStatement<'a>> {
let is_dom_only = mode == TemplateCompilationMode::DomOnly;
match op {
UpdateOp::Property(prop) => {
// Angular uses property() with nested interpolate*() calls for interpolated properties.
// The interpolation is handled by convert_ir_expression which generates
// ɵɵinterpolate*() calls when the expression is an Interpolation.
// Example: [title]="Hello {{name}}" -> ɵɵproperty("title", ɵɵinterpolate1("Hello ", name, ""))
let expr = convert_ir_expression(allocator, &prop.expression, expressions, root_xref);
// In DomOnly mode, use domProperty unless it's an animation binding
// Matches Angular's reify.ts line 613-621
let is_animation =
matches!(prop.binding_kind, BindingKind::LegacyAnimation | BindingKind::Animation);
if is_dom_only && !is_animation {
Some(create_dom_property_stmt(allocator, &prop.name, expr, prop.sanitizer.as_ref()))
} else if is_aria_attribute(prop.name.as_str()) {
// Use ɵɵariaProperty for ARIA attributes (e.g., aria-label, aria-hidden)
Some(create_aria_property_stmt(allocator, &prop.name, expr))
} else {
Some(create_property_stmt_with_expr(
allocator,
&prop.name,
expr,
prop.sanitizer.as_ref(),
))
}
}
UpdateOp::InterpolateText(interp) => {
// Handle multiple interpolations like "{{a}} and {{b}}"
let (args, expr_count) =
reify_interpolation(allocator, &interp.interpolation, expressions, root_xref);
Some(create_text_interpolate_stmt_with_args(allocator, args, expr_count))
}
UpdateOp::Binding(binding) => {
let expr =
convert_ir_expression(allocator, &binding.expression, expressions, root_xref);
Some(create_binding_stmt_with_expr(allocator, &binding.name, expr))
}
UpdateOp::StyleProp(style) => {
let expr = convert_ir_expression(allocator, &style.expression, expressions, root_xref);
// Strip "style." prefix if present
let name = strip_prefix(&style.name, "style.");
Some(create_style_prop_stmt_with_expr(allocator, &name, expr, style.unit.as_ref()))
}
UpdateOp::ClassProp(class) => {
let expr = convert_ir_expression(allocator, &class.expression, expressions, root_xref);
// Strip "class." prefix if present
let name = strip_prefix(&class.name, "class.");
Some(create_class_prop_stmt_with_expr(allocator, &name, expr))
}
UpdateOp::Attribute(attr) => {
let expr = convert_ir_expression(allocator, &attr.expression, expressions, root_xref);
// Strip "attr." prefix if present
let name = strip_prefix(&attr.name, "attr.");
Some(create_attribute_stmt_with_expr(
allocator,
&name,
expr,
attr.sanitizer.as_ref(),
attr.namespace.as_ref(),
))
}
UpdateOp::Advance(adv) => Some(create_advance_stmt(allocator, adv.delta)),
UpdateOp::StoreLet(store) => {
// StoreLet as an update op should have been converted to a StoreLet expression
// during the store_let_optimization phase. If it reaches reify, it's a compiler bug.
// This matches Angular's behavior which throws: "AssertionError: unexpected storeLet"
diagnostics.push(OxcDiagnostic::error(format!(
"AssertionError: unexpected storeLet {}",
store.declared_name
)));
None
}
UpdateOp::TwoWayProperty(twp) => {
let expr = convert_ir_expression(allocator, &twp.expression, expressions, root_xref);
Some(create_two_way_property_stmt(allocator, &twp.name, expr, twp.sanitizer.as_ref()))
}
UpdateOp::Repeater(rep) => {
let expr = convert_ir_expression(allocator, &rep.collection, expressions, root_xref);
Some(create_repeater_stmt(allocator, expr))
}
UpdateOp::Conditional(cond) => {
// Use processed expression (built by conditionals phase).
// Angular asserts that processed is always set by this point
// (throws "Conditional test was not set." in reify.ts:698).
let expr = if let Some(ref processed) = cond.processed {
convert_ir_expression(allocator, processed, expressions, root_xref)
} else {
diagnostics
.push(OxcDiagnostic::error("AssertionError: Conditional test was not set."));
return None;
};
let context_value = cond
.context_value
.as_ref()
.map(|cv| convert_ir_expression(allocator, cv, expressions, root_xref));
Some(create_conditional_update_stmt(allocator, expr, context_value))
}
UpdateOp::StyleMap(style) => {
let expr = convert_ir_expression(allocator, &style.expression, expressions, root_xref);
Some(create_style_map_stmt(allocator, expr))
}
UpdateOp::ClassMap(class) => {
let expr = convert_ir_expression(allocator, &class.expression, expressions, root_xref);
Some(create_class_map_stmt(allocator, expr))
}
UpdateOp::DomProperty(prop) => {
let expr = convert_ir_expression(allocator, &prop.expression, expressions, root_xref);
// Animation bindings use syntheticHostProperty instead of domProperty
// Matches Angular's reify.ts lines 662-675
let is_animation =
matches!(prop.binding_kind, BindingKind::LegacyAnimation | BindingKind::Animation);
if is_animation {
Some(create_animation_stmt(allocator, &prop.name, expr))
} else {
Some(create_dom_property_stmt(allocator, &prop.name, expr, prop.sanitizer.as_ref()))
}
}
UpdateOp::I18nExpression(i18n) => {
let expr = convert_ir_expression(allocator, &i18n.expression, expressions, root_xref);
Some(create_i18n_exp_stmt(allocator, expr))
}
UpdateOp::I18nApply(i18n) => {
// Use the slot from handle, matching Angular's reify.ts line 648:
// `ng.i18nApply(op.handle.slot!, op.sourceSpan)`
let slot = match i18n.handle {
crate::ir::ops::I18nSlotHandle::Single(slot_id) => slot_id.0,
crate::ir::ops::I18nSlotHandle::Range(start, _) => start.0,
};
Some(create_i18n_apply_stmt(allocator, slot))
}
UpdateOp::AnimationBinding(anim) => {
let expr = convert_ir_expression(allocator, &anim.expression, expressions, root_xref);
Some(create_animation_binding_stmt(allocator, &anim.name, expr))
}
UpdateOp::Control(ctrl) => {
let expr = convert_ir_expression(allocator, &ctrl.expression, expressions, root_xref);
Some(create_control_stmt(allocator, expr, &ctrl.name))
}
UpdateOp::Variable(var) => {
// Emit variable declaration with initializer for update phase
// All Variable ops use `const` (StmtModifier::Final), matching Angular's reify.ts
let value = convert_ir_expression(allocator, &var.initializer, expressions, root_xref);
Some(create_variable_decl_stmt_with_value(allocator, &var.name, value))
}
UpdateOp::DeferWhen(defer_when) => {
// Emit deferWhen runtime instruction with condition
let expr =
convert_ir_expression(allocator, &defer_when.condition, expressions, root_xref);
Some(create_defer_when_stmt(allocator, defer_when.modifier, expr))
}
// Non-emitting or already handled operations
UpdateOp::ListEnd(_) => None,
// Statement ops contain pre-built OutputStatements (e.g., temp variable declarations,
// or side-effectful expressions from variable optimization).
// These may contain WrappedIrNode expressions that need to be converted.
UpdateOp::Statement(stmt_op) => Some(convert_statement_ir_nodes(
allocator,
&stmt_op.statement,
expressions,
root_xref,
diagnostics,
)),
}
}
/// Reify an interpolation expression to arguments for textInterpolate.
fn reify_interpolation<'a>(
allocator: &'a oxc_allocator::Allocator,
interpolation: &IrExpression<'a>,
expressions: &ExpressionStore<'a>,
root_xref: XrefId,
) -> (OxcVec<'a, OutputExpression<'a>>, usize) {
match interpolation {
IrExpression::Interpolation(ir_interp) => {
// Direct IR interpolation - interleave strings and expressions
let expr_count = ir_interp.expressions.len();
let mut args = OxcVec::new_in(allocator);
// For single expression with empty surrounding strings, use simple form
if expr_count == 1 && ir_interp.strings.iter().all(|s| s.is_empty()) {
args.push(convert_ir_expression(
allocator,
&ir_interp.expressions[0],
expressions,
root_xref,
));
} else {
for (i, expr) in ir_interp.expressions.iter().enumerate() {
if i < ir_interp.strings.len() {
args.push(OutputExpression::Literal(Box::new_in(
LiteralExpr {
value: LiteralValue::String(ir_interp.strings[i].clone()),
source_span: None,
},
allocator,
)));
}
args.push(convert_ir_expression(allocator, expr, expressions, root_xref));
}
if ir_interp.strings.len() > ir_interp.expressions.len() {
if let Some(trailing) = ir_interp.strings.last() {
// Only add trailing string if it's not empty
// (Angular drops trailing empty strings and the runtime handles it)
if !trailing.is_empty() {
args.push(OutputExpression::Literal(Box::new_in(
LiteralExpr {
value: LiteralValue::String(trailing.clone()),
source_span: None,
},
allocator,
)));
}
}
}
}
(args, expr_count)