-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathingest.rs
More file actions
4592 lines (4194 loc) · 180 KB
/
ingest.rs
File metadata and controls
4592 lines (4194 loc) · 180 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
//! Template ingestion: R3 AST → IR operations.
//!
//! This module transforms the R3 AST representation into IR operations
//! that can be processed by the compilation phases.
//!
//! ## Expression Handling
//!
//! Expressions from R3 nodes are stored in the `ExpressionStore` and referenced
//! via `ExpressionId` using the Reference + Index pattern. This avoids cloning
//! expressions and maintains proper ownership.
//!
//! The R3 nodes are consumed (moved) during ingestion, which allows us to take
//! ownership of the expressions and store them properly without cloning.
//!
//! Ported from Angular's `template/pipeline/src/ingest.ts`.
use oxc_allocator::{Allocator, Box, Vec};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::Atom;
use super::compilation::{
CTX_REF, ComponentCompilationJob, DeferBlockDepsEmitMode, DeferMetadata,
HostBindingCompilationJob, I18nMessageMetadata, TemplateCompilationMode,
};
use super::conversion::prefix_with_namespace;
use crate::ast::expression::{AngularExpression, ParsedEventType};
use crate::ast::r3::{
I18nIcuPlaceholder, I18nMeta, I18nNode, R3BoundAttribute, R3BoundEvent, R3BoundText, R3Content,
R3DeferredBlock, R3Element, R3ForLoopBlock, R3Icu, R3IcuPlaceholder, R3IfBlock,
R3LetDeclaration, R3Node, R3SwitchBlock, R3Template, R3TemplateAttr, R3Text, R3TextAttribute,
SecurityContext,
};
use crate::ir::enums::{
AnimationKind, BindingKind, DeferOpModifierKind, DeferTriggerKind, Namespace, TemplateKind,
};
use crate::ir::expression::{
BinaryExpr, ConditionalCaseExpr, EmptyExpr, IrBinaryOperator, IrExpression, LexicalReadExpr,
PipeBindingExpr, ResolvedCallExpr, ResolvedKeyedReadExpr, ResolvedPropertyReadExpr,
SafeInvokeFunctionExpr, SafeKeyedReadExpr, SafePropertyReadExpr, SlotHandle,
TwoWayBindingSetExpr,
};
use crate::ir::ops::{
BindingOp, ConditionalBranchCreateOp, ConditionalOp, ConditionalUpdateOp, ControlCreateOp,
CreateOp, CreateOpBase, DeclareLetOp, DeferOnOp, DeferOp, DeferWhenOp, ElementEndOp,
ElementStartOp, ExtractedAttributeOp, I18nAttributesOp, I18nEndOp, I18nPlaceholder,
I18nSlotHandle, I18nStartOp, IcuEndOp, IcuStartOp, InterpolateTextOp, ListenerOp, LocalRef,
ProjectionOp, RepeaterCreateOp, RepeaterOp, RepeaterVarNames, SlotId, StatementOp, StoreLetOp,
TemplateOp, TextOp, TwoWayListenerOp, UpdateOp, UpdateOpBase, XrefId,
};
use crate::output::ast::OutputExpression;
use crate::pipeline::compilation::{AliasVariable, ContextVariable};
use rustc_hash::FxHashMap;
/// Options for ingesting a component template.
///
/// These options mirror the parameters passed to Angular's `ingestComponent()` function
/// in `template/pipeline/src/ingest.ts`.
///
/// Ported from Angular's ingestComponent parameters (lines 57-68 in ingest.ts).
#[derive(Debug)]
pub struct IngestOptions<'a> {
/// Template compilation mode (Full or DomOnly).
///
/// Use `DomOnly` when the component is standalone and has no directive dependencies.
pub mode: TemplateCompilationMode,
/// Relative path to the context file for i18n suffix generation.
///
/// Used to generate unique, file-based variable names for i18n translations.
pub relative_context_file_path: Option<Atom<'a>>,
/// Whether to use external message IDs in i18n variable names.
///
/// When true, generates variable names like `MSG_EXTERNAL_abc123$$SUFFIX`.
/// When false, uses file-based naming like `MSG_SUFFIX_0`.
pub i18n_use_external_ids: bool,
/// Defer block emit mode (PerBlock or PerComponent).
///
/// PerBlock is used in full compilation mode when the compiler has information
/// about which dependencies belong to which defer block.
/// PerComponent is used in local/JIT compilation.
pub defer_block_deps_emit_mode: DeferBlockDepsEmitMode,
/// Relative path to the template file for source location debugging.
pub relative_template_path: Option<Atom<'a>>,
/// Whether to enable debug source locations.
///
/// When enabled, the compiler generates `ɵɵsourceLocation` calls for debugging.
pub enable_debug_locations: bool,
/// Template source text for computing line/column from byte offsets.
///
/// Required when `enable_debug_locations` is true.
pub template_source: Option<&'a str>,
/// Reference to the deferrable dependencies function for PerComponent mode.
///
/// This corresponds to Angular's `allDeferrableDepsFn` parameter.
/// When using `DeferBlockDepsEmitMode::PerComponent`, this function provides
/// all deferrable dependencies for the entire component.
///
/// Ported from Angular's ingestComponent parameter (line 65 in ingest.ts).
pub all_deferrable_deps_fn: Option<OutputExpression<'a>>,
/// Starting index for the constant pool's name counter.
///
/// This is used when compiling multiple components in the same file to ensure
/// constant names don't conflict. Each component continues from where the
/// previous component's pool left off.
///
/// For example, if component 1 uses _c0, _c1, _c2, then component 2 should
/// be created with `pool_starting_index: 3` to start with _c3.
///
/// Default is 0 (start from _c0).
pub pool_starting_index: u32,
/// Angular version for feature-gated instruction selection.
///
/// When set to a version < 20, the compiler emits `ɵɵtemplate` instead of
/// `ɵɵconditionalCreate`/`ɵɵconditionalBranchCreate` for `@if`/`@switch` blocks.
/// When `None`, assumes latest Angular version (v20+ behavior).
pub angular_version: Option<crate::AngularVersion>,
}
impl Default for IngestOptions<'_> {
fn default() -> Self {
Self {
mode: TemplateCompilationMode::Full,
relative_context_file_path: None,
i18n_use_external_ids: true,
defer_block_deps_emit_mode: DeferBlockDepsEmitMode::PerBlock,
relative_template_path: None,
enable_debug_locations: false,
template_source: None,
all_deferrable_deps_fn: None,
pool_starting_index: 0,
angular_version: None,
}
}
}
/// Stores an expression from an R3 node and returns an IrExpression that references it.
///
/// This is the preferred way to handle expressions during ingestion. The expression
/// is stored in the CompilationJob's ExpressionStore and referenced by ID.
fn store_and_ref_expr<'a>(
job: &mut ComponentCompilationJob<'a>,
expr: AngularExpression<'a>,
) -> Box<'a, IrExpression<'a>> {
let id = job.store_expression(expr);
Box::new_in(IrExpression::ExpressionRef(id), job.allocator)
}
/// Converts an Angular expression to an IR expression during ingestion.
///
/// This function directly converts pipe expressions to their IR equivalents,
/// making them visible to subsequent phases like `pipe_creation`.
/// Safe navigation expressions are stored in the ExpressionStore to be processed
/// by the `expand_safe_reads` phase later.
/// Other expressions are stored in the ExpressionStore and referenced by ID.
///
/// This matches Angular's TypeScript `convertAst` function in `ingest.ts`.
fn convert_ast_to_ir<'a>(
job: &mut ComponentCompilationJob<'a>,
expr: AngularExpression<'a>,
) -> Box<'a, IrExpression<'a>> {
let allocator = job.allocator;
match expr {
// Convert BindingPipe to IrExpression::PipeBinding
// This makes pipes visible to the pipe_creation phase
AngularExpression::BindingPipe(pipe) => {
let pipe = pipe.unbox();
let target = job.allocate_xref_id();
// Convert the pipe input and arguments to IR expressions
let mut args = Vec::with_capacity_in(1 + pipe.args.len(), allocator);
// First argument is the pipe input expression
let input_expr = convert_ast_to_ir(job, pipe.exp);
args.push(input_expr.unbox());
// Remaining arguments are the pipe arguments
for arg in pipe.args {
let arg_expr = convert_ast_to_ir(job, arg);
args.push(arg_expr.unbox());
}
Box::new_in(
IrExpression::PipeBinding(Box::new_in(
PipeBindingExpr {
target,
target_slot: SlotHandle::new(),
name: pipe.name,
args,
var_offset: None,
source_span: Some(pipe.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Non-null assertion is transparent - just unwrap and convert inner expression
AngularExpression::NonNullAssert(nna) => {
let nna = nna.unbox();
convert_ast_to_ir(job, nna.expression)
}
// Convert SafePropertyRead (a?.b) to IR SafePropertyReadExpr
// This makes safe reads visible to the expand_safe_reads phase
AngularExpression::SafePropertyRead(safe) => {
let safe = safe.unbox();
let receiver = convert_ast_to_ir(job, safe.receiver);
Box::new_in(
IrExpression::SafePropertyRead(Box::new_in(
SafePropertyReadExpr {
receiver,
name: safe.name,
source_span: Some(safe.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert SafeKeyedRead (a?.[b]) to IR SafeKeyedReadExpr
AngularExpression::SafeKeyedRead(safe) => {
let safe = safe.unbox();
let receiver = convert_ast_to_ir(job, safe.receiver);
let index = convert_ast_to_ir(job, safe.key);
Box::new_in(
IrExpression::SafeKeyedRead(Box::new_in(
SafeKeyedReadExpr {
receiver,
index,
source_span: Some(safe.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert SafeCall (a?.()) to IR SafeInvokeFunctionExpr
AngularExpression::SafeCall(safe) => {
let safe = safe.unbox();
let receiver = convert_ast_to_ir(job, safe.receiver);
let mut args = Vec::with_capacity_in(safe.args.len(), allocator);
for arg in safe.args {
let arg_expr = convert_ast_to_ir(job, arg);
args.push(arg_expr.unbox());
}
Box::new_in(
IrExpression::SafeInvokeFunction(Box::new_in(
SafeInvokeFunctionExpr { receiver, args, source_span: None },
allocator,
)),
allocator,
)
}
// Convert LiteralArray - recursively convert elements to preserve pipes
AngularExpression::LiteralArray(arr) => {
let arr = arr.unbox();
let mut elements = Vec::with_capacity_in(arr.expressions.len(), allocator);
for elem in arr.expressions {
let elem_expr = convert_ast_to_ir(job, elem);
elements.push(elem_expr.unbox());
}
Box::new_in(
IrExpression::LiteralArray(Box::new_in(
crate::ir::expression::IrLiteralArrayExpr {
elements,
source_span: Some(arr.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert LiteralMap (object literal) - recursively convert values to preserve pipes
AngularExpression::LiteralMap(map) => {
use crate::ast::expression::LiteralMapKey;
let map = map.unbox();
let mut keys = Vec::with_capacity_in(map.keys.len(), allocator);
let mut values = Vec::with_capacity_in(map.values.len(), allocator);
let mut quoted = Vec::with_capacity_in(map.keys.len(), allocator);
for (key, value) in map.keys.into_iter().zip(map.values.into_iter()) {
// Only handle property keys; spread keys need special handling
if let LiteralMapKey::Property(prop) = key {
keys.push(prop.key);
quoted.push(prop.quoted);
let value_expr = convert_ast_to_ir(job, value);
values.push(value_expr.unbox());
}
}
Box::new_in(
IrExpression::LiteralMap(Box::new_in(
crate::ir::expression::IrLiteralMapExpr {
keys,
values,
quoted,
source_span: Some(map.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert Binary expression - recursively convert operands to preserve pipes
// This is needed for expressions like `a ?? (b | pipe)` where the pipe is nested
AngularExpression::Binary(bin) => {
let bin = bin.unbox();
let lhs = convert_ast_to_ir(job, bin.left);
let rhs = convert_ast_to_ir(job, bin.right);
Box::new_in(
IrExpression::Binary(oxc_allocator::Box::new_in(
crate::ir::expression::BinaryExpr {
operator: convert_binary_op(bin.operation),
lhs,
rhs,
source_span: Some(bin.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert ParenthesizedExpression - recursively convert inner expression to preserve pipes
// This is needed for expressions like `(a | pipe)` where the pipe is inside parens
AngularExpression::ParenthesizedExpression(paren) => {
let paren = paren.unbox();
let inner = convert_ast_to_ir(job, paren.expression);
Box::new_in(
IrExpression::Parenthesized(Box::new_in(
crate::ir::expression::IrParenthesizedExpr { expr: inner, source_span: None },
allocator,
)),
allocator,
)
}
// Convert Conditional expression (ternary) - recursively convert operands to preserve pipes
AngularExpression::Conditional(cond) => {
let cond = cond.unbox();
let condition = convert_ast_to_ir(job, cond.condition);
let true_exp = convert_ast_to_ir(job, cond.true_exp);
let false_exp = convert_ast_to_ir(job, cond.false_exp);
Box::new_in(
IrExpression::Ternary(oxc_allocator::Box::new_in(
crate::ir::expression::TernaryExpr {
condition,
true_expr: true_exp,
false_expr: false_exp,
source_span: Some(cond.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert PropertyRead - recursively convert receiver to preserve pipes
// This handles expressions like `(root$ | async).nav` where the pipe is in the receiver
// Matches Angular's convertAst for PropertyRead in ingest.ts
AngularExpression::PropertyRead(prop) => {
let prop = prop.unbox();
// Check if this is a simple property read from implicit receiver (just a name)
if matches!(prop.receiver, AngularExpression::ImplicitReceiver(_))
&& !matches!(prop.receiver, AngularExpression::ThisReceiver(_))
{
// This is like `foo` which becomes LexicalRead
Box::new_in(
IrExpression::LexicalRead(oxc_allocator::Box::new_in(
LexicalReadExpr {
name: prop.name,
source_span: Some(prop.source_span.to_span()),
},
allocator,
)),
allocator,
)
} else if matches!(prop.receiver, AngularExpression::ThisReceiver(_)) {
// Explicit `this` property read (e.g., `this.formGroup`) becomes a
// ResolvedPropertyRead with Context receiver. This is critical for embedded
// views because the resolve phases need to see the ContextExpr(root_xref)
// to properly generate nextContext() calls.
Box::new_in(
IrExpression::ResolvedPropertyRead(oxc_allocator::Box::new_in(
ResolvedPropertyReadExpr {
receiver: Box::new_in(
IrExpression::Context(oxc_allocator::Box::new_in(
crate::ir::expression::ContextExpr {
view: job.root.xref,
source_span: Some(prop.source_span.to_span()),
},
allocator,
)),
allocator,
),
name: prop.name,
source_span: Some(prop.source_span.to_span()),
},
allocator,
)),
allocator,
)
} else {
// This is a nested property read like `(expr).name`
// Recursively convert the receiver to preserve any pipes
let receiver = convert_ast_to_ir(job, prop.receiver);
Box::new_in(
IrExpression::ResolvedPropertyRead(oxc_allocator::Box::new_in(
ResolvedPropertyReadExpr {
receiver,
name: prop.name,
source_span: Some(prop.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
}
// Convert KeyedRead - recursively convert receiver and key to preserve pipes
// This handles expressions like `(items$ | async)[0]` where the pipe is in the receiver
AngularExpression::KeyedRead(keyed) => {
let keyed = keyed.unbox();
let receiver = convert_ast_to_ir(job, keyed.receiver);
let key = convert_ast_to_ir(job, keyed.key);
Box::new_in(
IrExpression::ResolvedKeyedRead(oxc_allocator::Box::new_in(
ResolvedKeyedReadExpr {
receiver,
key,
source_span: Some(keyed.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert Call - recursively convert receiver and args to preserve pipes
// This handles expressions like `(fn$ | async)(arg | pipe)` where pipes are in receiver or args
AngularExpression::Call(call) => {
let call = call.unbox();
let receiver = convert_ast_to_ir(job, call.receiver);
let mut args = Vec::with_capacity_in(call.args.len(), allocator);
for arg in call.args {
let arg_expr = convert_ast_to_ir(job, arg);
args.push(arg_expr.unbox());
}
Box::new_in(
IrExpression::ResolvedCall(oxc_allocator::Box::new_in(
ResolvedCallExpr {
receiver,
args,
source_span: Some(call.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert PrefixNot (!) - recursively convert operand to preserve pipes
// This handles expressions like `!(value$ | async)` where the pipe is in the operand
AngularExpression::PrefixNot(not) => {
let not = not.unbox();
let expr = convert_ast_to_ir(job, not.expression);
Box::new_in(
IrExpression::Not(oxc_allocator::Box::new_in(
crate::ir::expression::NotExpr {
expr,
source_span: Some(not.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert Unary (+/-) - recursively convert operand to preserve pipes
// This handles expressions like `+(value$ | pipe)` where the pipe is in the operand
AngularExpression::Unary(unary) => {
let unary = unary.unbox();
let expr = convert_ast_to_ir(job, unary.expr);
let operator = match unary.operator {
crate::ast::expression::UnaryOperator::Plus => {
crate::ir::expression::IrUnaryOperator::Plus
}
crate::ast::expression::UnaryOperator::Minus => {
crate::ir::expression::IrUnaryOperator::Minus
}
};
Box::new_in(
IrExpression::Unary(oxc_allocator::Box::new_in(
crate::ir::expression::UnaryExpr {
operator,
expr,
source_span: Some(unary.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert TypeofExpression - recursively convert operand to preserve pipes
AngularExpression::TypeofExpression(typeof_expr) => {
let typeof_expr = typeof_expr.unbox();
let expr = convert_ast_to_ir(job, typeof_expr.expression);
Box::new_in(
IrExpression::Typeof(oxc_allocator::Box::new_in(
crate::ir::expression::TypeofExpr {
expr,
source_span: Some(typeof_expr.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Convert VoidExpression - recursively convert operand to preserve pipes
AngularExpression::VoidExpression(void_expr) => {
let void_expr = void_expr.unbox();
let expr = convert_ast_to_ir(job, void_expr.expression);
Box::new_in(
IrExpression::Void(oxc_allocator::Box::new_in(
crate::ir::expression::VoidExpr {
expr,
source_span: Some(void_expr.source_span.to_span()),
},
allocator,
)),
allocator,
)
}
// Empty expression - convert directly to IrExpression::Empty
// This ensures is_empty() check works in remove_empty_bindings phase
// TypeScript reference: ingest.ts lines 1184-1185
AngularExpression::Empty(empty) => {
let empty = empty.unbox();
Box::new_in(
IrExpression::Empty(Box::new_in(
EmptyExpr { source_span: Some(empty.source_span.to_span()) },
allocator,
)),
allocator,
)
}
// For all other expressions, store in ExpressionStore and return reference.
other => store_and_ref_expr(job, other),
}
}
/// Converts an AST binary operator to an IR binary operator.
fn convert_binary_op(
op: crate::ast::expression::BinaryOperator,
) -> crate::ir::expression::IrBinaryOperator {
use crate::ast::expression::BinaryOperator as AstOp;
use crate::ir::expression::IrBinaryOperator as IrOp;
match op {
AstOp::Add => IrOp::Plus,
AstOp::Subtract => IrOp::Minus,
AstOp::Multiply => IrOp::Multiply,
AstOp::Divide => IrOp::Divide,
AstOp::Modulo => IrOp::Modulo,
AstOp::Power => IrOp::Exponentiation,
AstOp::Equal => IrOp::Equals,
AstOp::NotEqual => IrOp::NotEquals,
AstOp::StrictEqual => IrOp::Identical,
AstOp::StrictNotEqual => IrOp::NotIdentical,
AstOp::LessThan => IrOp::Lower,
AstOp::LessThanOrEqual => IrOp::LowerEquals,
AstOp::GreaterThan => IrOp::Bigger,
AstOp::GreaterThanOrEqual => IrOp::BiggerEquals,
AstOp::And => IrOp::And,
AstOp::Or => IrOp::Or,
AstOp::NullishCoalescing => IrOp::NullishCoalesce,
AstOp::In => IrOp::In,
AstOp::Instanceof => IrOp::Instanceof,
AstOp::Assign => IrOp::Assign,
AstOp::AddAssign => IrOp::AdditionAssignment,
AstOp::SubtractAssign => IrOp::SubtractionAssignment,
AstOp::MultiplyAssign => IrOp::MultiplicationAssignment,
AstOp::DivideAssign => IrOp::DivisionAssignment,
AstOp::ModuloAssign => IrOp::RemainderAssignment,
AstOp::PowerAssign => IrOp::ExponentiationAssignment,
AstOp::AndAssign => IrOp::AndAssignment,
AstOp::OrAssign => IrOp::OrAssignment,
AstOp::NullishCoalescingAssign => IrOp::NullishCoalesceAssignment,
}
}
/// Converts an interpolation expression to an IR interpolation, storing inner expressions.
///
/// This is needed because interpolations contain inner expressions that need to be
/// resolved during name resolution. By converting to IR Interpolation, the inner
/// expressions become visible to the expression transformer.
fn convert_interpolation_to_ir<'a>(
job: &mut ComponentCompilationJob<'a>,
expr: AngularExpression<'a>,
) -> Box<'a, IrExpression<'a>> {
let allocator = job.allocator;
convert_interpolation_to_ir_with_i18n_placeholders(job, expr, Vec::new_in(allocator))
}
/// Converts an Angular expression to IR, handling interpolations with i18n placeholders.
///
/// This is used for bound text inside i18n blocks where the i18n metadata contains
/// placeholder names that need to be preserved for the i18n message generation.
///
/// Ported from Angular's ingestBoundText (ingest.ts lines 506-512) which passes
/// i18nPlaceholders to the Interpolation constructor.
fn convert_interpolation_to_ir_with_i18n_placeholders<'a>(
job: &mut ComponentCompilationJob<'a>,
expr: AngularExpression<'a>,
i18n_placeholders: Vec<'a, Atom<'a>>,
) -> Box<'a, IrExpression<'a>> {
let allocator = job.allocator;
// If it's an interpolation, convert to IR interpolation with inner expressions
if let AngularExpression::Interpolation(interp_box) = expr {
// Unbox the interpolation to take ownership of its fields
let interp = interp_box.unbox();
let mut ir_expressions = Vec::new_in(allocator);
for inner_expr in interp.expressions {
// Convert each inner expression to IR (handles pipes, safe nav, etc.)
let converted = convert_ast_to_ir(job, inner_expr);
ir_expressions.push(converted.unbox());
}
Box::new_in(
IrExpression::Interpolation(Box::new_in(
crate::ir::expression::Interpolation {
strings: interp.strings,
expressions: ir_expressions,
i18n_placeholders,
source_span: Some(interp.source_span.to_span()),
},
allocator,
)),
allocator,
)
} else {
// For non-interpolation expressions, convert to IR
convert_ast_to_ir(job, expr)
}
}
/// Ingests a component template into a compilation job.
///
/// This function consumes the R3 AST nodes, moving expressions into the IR.
/// The R3 nodes cannot be used after ingestion.
///
/// This is a convenience wrapper around `ingest_component_with_options` that uses
/// default options. For full control over compilation settings, use
/// `ingest_component_with_options` directly.
pub fn ingest_component<'a>(
allocator: &'a Allocator,
component_name: Atom<'a>,
template: Vec<'a, R3Node<'a>>,
) -> ComponentCompilationJob<'a> {
ingest_component_with_options(allocator, component_name, template, IngestOptions::default())
}
/// Ingests a component template into a compilation job with the given options.
///
/// This is the full-featured version of `ingest_component` that accepts all
/// compilation options, matching Angular's `ingestComponent()` function signature.
///
/// Ported from Angular's `ingestComponent()` in `template/pipeline/src/ingest.ts`.
///
/// # Parameters
///
/// - `allocator`: The allocator for memory allocation
/// - `component_name`: Name of the component being compiled
/// - `template`: The R3 AST nodes representing the template
/// - `options`: Compilation options including mode, i18n settings, and debug options
///
/// # Returns
///
/// A `ComponentCompilationJob` ready for transformation phases.
pub fn ingest_component_with_options<'a>(
allocator: &'a Allocator,
component_name: Atom<'a>,
template: Vec<'a, R3Node<'a>>,
options: IngestOptions<'a>,
) -> ComponentCompilationJob<'a> {
// Create the job with the specified pool starting index.
// This ensures that when compiling multiple components in the same file,
// each component's constants have unique names.
let mut job = ComponentCompilationJob::with_pool_starting_index(
allocator,
component_name,
options.pool_starting_index,
);
// Apply options to the job
job.mode = options.mode;
job.relative_context_file_path = options.relative_context_file_path;
job.i18n_use_external_ids = options.i18n_use_external_ids;
job.enable_debug_locations = options.enable_debug_locations;
job.relative_template_path = options.relative_template_path;
job.template_source = options.template_source;
// Set defer metadata based on emit mode
// The all_deferrable_deps_fn is stored on the job and referenced during emit
job.defer_meta = match options.defer_block_deps_emit_mode {
DeferBlockDepsEmitMode::PerBlock => {
DeferMetadata::PerBlock { blocks: FxHashMap::default() }
}
DeferBlockDepsEmitMode::PerComponent => {
// In PerComponent mode, dependencies_fn is set from all_deferrable_deps_fn during emit
DeferMetadata::PerComponent { dependencies_fn: None }
}
};
// Store the all_deferrable_deps_fn reference for emit phase
// This is used when DeferBlockDepsEmitMode::PerComponent to reference the shared deps function
job.all_deferrable_deps_fn = options.all_deferrable_deps_fn;
// Set Angular version for feature-gated instruction selection
job.angular_version = options.angular_version;
let root_xref = job.root.xref;
for node in template {
ingest_node(&mut job, root_xref, node);
}
job
}
/// Ingests a single R3 node into the appropriate view.
///
/// Consumes the node, taking ownership of expressions.
fn ingest_node<'a>(job: &mut ComponentCompilationJob<'a>, view_xref: XrefId, node: R3Node<'a>) {
match node {
R3Node::Text(text) => ingest_text(job, view_xref, text.unbox(), None),
R3Node::BoundText(bound_text) => {
ingest_bound_text(job, view_xref, bound_text.unbox(), None)
}
R3Node::Element(element) => ingest_element(job, view_xref, element.unbox()),
R3Node::Template(template) => ingest_template(job, view_xref, template.unbox()),
R3Node::Content(content) => ingest_content(job, view_xref, content.unbox()),
R3Node::IfBlock(if_block) => ingest_if_block(job, view_xref, if_block.unbox()),
R3Node::ForLoopBlock(for_block) => ingest_for_block(job, view_xref, for_block.unbox()),
R3Node::SwitchBlock(switch_block) => {
ingest_switch_block(job, view_xref, switch_block.unbox())
}
R3Node::DeferredBlock(defer_block) => {
ingest_defer_block(job, view_xref, defer_block.unbox())
}
R3Node::LetDeclaration(let_decl) => {
ingest_let_declaration(job, view_xref, let_decl.unbox())
}
R3Node::Comment(_) => {
// Comments are not ingested into IR
}
R3Node::Icu(icu) => ingest_icu(job, view_xref, icu.unbox()),
R3Node::UnknownBlock(_) => {
// Unknown blocks are skipped with a warning
}
// The following are not standalone nodes in the template
R3Node::Variable(_) | R3Node::Reference(_) => {
// Variables and references are handled by their parent nodes
}
R3Node::DeferredBlockPlaceholder(_)
| R3Node::DeferredBlockLoading(_)
| R3Node::DeferredBlockError(_) => {
// Defer sub-blocks are handled by the parent defer block
}
R3Node::ForLoopBlockEmpty(_) => {
// Empty block is handled by the parent for block
}
R3Node::SwitchBlockCaseGroup(_) => {
// Switch case groups are handled by the parent switch block
}
R3Node::IfBlockBranch(_) => {
// If branches are handled by the parent if block
}
R3Node::Component(_) | R3Node::Directive(_) | R3Node::HostElement(_) => {
// Components, directives, and host elements are resolved during binding/type checking
}
}
}
/// Ingests a static text node.
///
/// `icu_placeholder` is provided when this text is part of an ICU expression,
/// indicating the placeholder name for this text within the ICU message.
fn ingest_text<'a>(
job: &mut ComponentCompilationJob<'a>,
view_xref: XrefId,
text: R3Text<'a>,
icu_placeholder: Option<Atom<'a>>,
) {
let xref = job.allocate_xref_id();
let op = CreateOp::Text(TextOp {
base: CreateOpBase { source_span: Some(text.source_span), ..Default::default() },
xref,
slot: None,
initial_value: text.value,
i18n_placeholder: None,
icu_placeholder,
});
if let Some(view) = job.view_mut(view_xref) {
view.create.push(op);
}
}
/// Ingests a bound text node (with interpolation).
///
/// `icu_placeholder` is provided when this text is part of an ICU expression,
/// indicating the placeholder name for this text within the ICU message.
fn ingest_bound_text<'a>(
job: &mut ComponentCompilationJob<'a>,
view_xref: XrefId,
bound_text: R3BoundText<'a>,
icu_placeholder: Option<Atom<'a>>,
) {
let allocator = job.allocator;
let xref = job.allocate_xref_id();
// Create the text slot
let text_op = CreateOp::Text(TextOp {
base: CreateOpBase { source_span: Some(bound_text.source_span), ..Default::default() },
xref,
slot: None,
initial_value: Atom::from(""),
i18n_placeholder: None,
icu_placeholder,
});
if let Some(view) = job.view_mut(view_xref) {
view.create.push(text_op);
}
// Extract i18n placeholders from the bound text's i18n metadata
// Ported from Angular's ingestBoundText (ingest.ts lines 485-495)
let i18n_placeholders: Vec<'_, Atom<'_>> = match &bound_text.i18n {
Some(I18nMeta::Node(I18nNode::Container(container))) => {
let mut placeholders = Vec::new_in(allocator);
for child in container.children.iter() {
if let I18nNode::Placeholder(placeholder) = child {
placeholders.push(placeholder.name.clone());
}
}
placeholders
}
_ => Vec::new_in(allocator),
};
// Convert the interpolation expression to an IR interpolation.
// This allows inner expressions to be resolved during name resolution.
let interpolation = convert_interpolation_to_ir_with_i18n_placeholders(
job,
bound_text.value,
i18n_placeholders,
);
// Create InterpolateText update op
let update_op = UpdateOp::InterpolateText(InterpolateTextOp {
base: UpdateOpBase { source_span: Some(bound_text.source_span), ..Default::default() },
target: xref,
interpolation,
i18n_placeholder: None,
});
if let Some(view) = job.view_mut(view_xref) {
view.update.push(update_op);
}
}
/// Checks if the i18n metadata is a Message containing a single IcuPlaceholder.
/// Returns the ICU placeholder if so, None otherwise.
fn get_single_icu_placeholder<'a, 'b>(
meta: &'b Option<I18nMeta<'a>>,
) -> Option<&'b I18nIcuPlaceholder<'a>> {
if let Some(I18nMeta::Message(message)) = meta {
if message.nodes.len() == 1 {
if let I18nNode::IcuPlaceholder(icu_placeholder) = &message.nodes[0] {
return Some(icu_placeholder);
}
}
}
None
}
/// Ingests an ICU expression node (plural, select, selectordinal).
///
/// Creates IcuStartOp and IcuEndOp to bracket the ICU expression,
/// and ingests all vars and placeholders within.
///
/// Ported from Angular's `ingestIcu` in `template/pipeline/src/ingest.ts`.
fn ingest_icu<'a>(job: &mut ComponentCompilationJob<'a>, view_xref: XrefId, icu: R3Icu<'a>) {
// Check if the i18n metadata is a Message with a single IcuPlaceholder
// TypeScript: if (icu.i18n instanceof i18n.Message && isSingleI18nIcu(icu.i18n))
let icu_placeholder_name = match get_single_icu_placeholder(&icu.i18n) {
Some(icu_placeholder) => icu_placeholder.name.clone(),
None => {
// TypeScript throws: Error(`Unhandled i18n metadata type for ICU: ${icu.i18n?.constructor.name}`)
// We report as a diagnostic and return early
job.diagnostics.push(OxcDiagnostic::error(
"Unhandled i18n metadata type for ICU: expected Message with single IcuPlaceholder",
).with_label(icu.source_span));
return;
}
};
let xref = job.allocate_xref_id();
// Create IcuStartOp
let start_op = CreateOp::IcuStart(IcuStartOp {
base: CreateOpBase { source_span: Some(icu.source_span), ..Default::default() },
xref,
context: None, // Will be set by create_i18n_contexts phase
message: None, // Will be set by phases
icu_placeholder: Some(icu_placeholder_name),
});
if let Some(view) = job.view_mut(view_xref) {
view.create.push(start_op);
}
// Process vars (bound text expressions)
// In Rust, vars is typed as HashMap<Atom, R3BoundText> so no runtime check needed
for (placeholder_name, bound_text) in icu.vars {
ingest_bound_text(job, view_xref, bound_text, Some(placeholder_name));
}
// Process placeholders (text or bound text)
for (placeholder_name, placeholder) in icu.placeholders {
match placeholder {
R3IcuPlaceholder::Text(text) => {
ingest_text(job, view_xref, text, Some(placeholder_name));
}
R3IcuPlaceholder::BoundText(bound_text) => {
ingest_bound_text(job, view_xref, bound_text, Some(placeholder_name));
}
}
}
// Create IcuEndOp
let end_op = CreateOp::IcuEnd(IcuEndOp {
base: CreateOpBase { source_span: Some(icu.source_span), ..Default::default() },
xref,
});
if let Some(view) = job.view_mut(view_xref) {
view.create.push(end_op);
}
}
/// Splits a namespaced name like `:svg:path` into (namespace_key, element_name).
///
/// Ported from Angular's `splitNsName` in `src/ml_parser/tags.ts`.
fn split_ns_name(name: &str) -> (Option<&str>, &str) {
if name.starts_with(':') {
// Format is `:namespace:element` (e.g., `:svg:path`)
if let Some(colon_idx) = name[1..].find(':') {
let namespace_key = &name[1..colon_idx + 1];
let element_name = &name[colon_idx + 2..];
return (Some(namespace_key), element_name);
}
}
// No namespace prefix
(None, name)
}
/// Converts a namespace key to a Namespace enum.
fn namespace_for_key(key: Option<&str>) -> Namespace {
match key {
Some("svg") => Namespace::Svg,
Some("math") => Namespace::Math,
_ => Namespace::Html,
}