-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdefinition.rs
More file actions
2324 lines (2043 loc) · 87 KB
/
definition.rs
File metadata and controls
2324 lines (2043 loc) · 87 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
//! Component definition generation (ɵcmp and ɵfac).
//!
//! This module generates the Angular runtime definitions that are added
//! as static properties on component classes:
//!
//! - `ɵcmp`: Component definition created by `ɵɵdefineComponent()`
//! - `ɵfac`: Factory function for instantiating the component
//!
//! These definitions are used by Angular's runtime to:
//! - Render the component's template
//! - Handle change detection
//! - Manage component lifecycle
//! - Inject dependencies
use oxc_allocator::{Allocator, Box, FromIn, Vec as OxcVec};
use oxc_span::Atom;
use crate::r3::Identifiers;
use super::dependency::{FactoryTarget, R3DependencyMetadata, compile_inject_dependencies};
use super::metadata::{
ChangeDetectionStrategy, ComponentMetadata, DeclarationListEmitMode, HostDirectiveMetadata,
ViewEncapsulation,
};
use super::namespace_registry::NamespaceRegistry;
use crate::directive::{
create_host_directive_mappings_array, create_inputs_literal, create_outputs_literal,
};
use crate::output::ast::{
FnParam, FunctionExpr, InstantiateExpr, InvokeFunctionExpr, LiteralArrayExpr, LiteralExpr,
LiteralMapEntry, LiteralMapExpr, LiteralValue, OutputExpression, OutputStatement, ReadPropExpr,
ReadVarExpr, ReturnStatement,
};
use crate::pipeline::compilation::{ComponentCompilationJob, ConstValue};
use crate::pipeline::emit::HostBindingCompilationResult;
use crate::pipeline::selector::{parse_selector_to_r3_selector, r3_selector_to_output_expr};
/// Result of generating component definitions.
pub struct ComponentDefinitions<'a> {
/// The ɵcmp definition (component metadata for Angular runtime).
pub cmp_definition: OutputExpression<'a>,
/// The ɵfac factory function.
pub fac_definition: OutputExpression<'a>,
}
/// Generate ɵcmp and ɵfac definitions for a component.
///
/// # Arguments
///
/// * `allocator` - Memory allocator
/// * `metadata` - Component metadata extracted from decorator
/// * `job` - The compilation job with template compilation results
/// * `template_fn` - The compiled template function
/// * `host_binding_result` - Optional host binding compilation result (function, hostAttrs, hostVars)
/// * `attrs_ref` - Optional pre-pooled attrs constant reference (pooled before template compilation)
/// * `view_query_fn` - Optional view query function (with pre-pooled predicates)
///
/// # Returns
///
/// The ɵcmp and ɵfac definitions as output expressions.
pub fn generate_component_definitions<'a>(
allocator: &'a Allocator,
metadata: &ComponentMetadata<'a>,
job: &mut ComponentCompilationJob<'a>,
template_fn: FunctionExpr<'a>,
host_binding_result: Option<HostBindingCompilationResult<'a>>,
attrs_ref: Option<OutputExpression<'a>>,
view_query_fn: Option<OutputExpression<'a>>,
content_queries_fn: Option<OutputExpression<'a>>,
namespace_registry: &mut NamespaceRegistry<'a>,
) -> ComponentDefinitions<'a> {
// IMPORTANT: Generate ɵfac BEFORE ɵcmp to match Angular's namespace index assignment order.
// Angular processes results in order [fac, def, ...] during the transform phase
// (see packages/compiler-cli/src/ngtsc/transform/src/transform.ts:158-198),
// so factory dependencies get registered first, followed by component definition dependencies.
// This ensures namespace indices (i0, i1, i2, ...) are assigned in the same order.
let fac_definition = generate_fac_definition(allocator, metadata, namespace_registry);
let cmp_definition = generate_cmp_definition(
allocator,
metadata,
job,
template_fn,
host_binding_result,
attrs_ref,
view_query_fn,
content_queries_fn,
namespace_registry,
);
ComponentDefinitions { cmp_definition, fac_definition }
}
/// Generate the ɵcmp definition.
///
/// Creates an expression like:
/// ```javascript
/// i0.ɵɵdefineComponent({
/// type: ComponentClass,
/// selectors: [["selector"]],
/// decls: 2,
/// vars: 1,
/// template: function ComponentClass_Template(rf, ctx) { ... },
/// styles: ["..."],
/// encapsulation: 0,
/// changeDetection: 0
/// })
/// ```
fn generate_cmp_definition<'a>(
allocator: &'a Allocator,
metadata: &ComponentMetadata<'a>,
job: &mut ComponentCompilationJob<'a>,
template_fn: FunctionExpr<'a>,
host_binding_result: Option<HostBindingCompilationResult<'a>>,
attrs_ref: Option<OutputExpression<'a>>,
view_query_fn: Option<OutputExpression<'a>>,
content_queries_fn: Option<OutputExpression<'a>>,
namespace_registry: &mut NamespaceRegistry<'a>,
) -> OutputExpression<'a> {
let mut entries: OxcVec<'a, LiteralMapEntry<'a>> = OxcVec::new_in(allocator);
// =========================================================================
// Angular field ordering from baseDirectiveFields (compiler.ts lines 41-104)
// =========================================================================
// 1. type: ComponentClass
entries.push(LiteralMapEntry {
key: Atom::from("type"),
value: OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: metadata.class_name.clone(), source_span: None },
allocator,
)),
quoted: false,
});
// 2. selectors: [["selector"]] or [["ng-component"]] if no selector
// Angular uses "ng-component" as the default selector for components without an explicit selector.
// See: packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts:264-290
// and packages/compiler/src/schema/dom_element_schema_registry.ts:463
let selector_value =
metadata.selector.as_ref().map_or_else(|| Atom::from("ng-component"), |s| s.clone());
let selector_entries = parse_selector_to_array(allocator, &selector_value);
entries.push(LiteralMapEntry {
key: Atom::from("selectors"),
value: selector_entries,
quoted: false,
});
// 3. contentQueries: function(rf, ctx, dirIndex) { ... } (if any)
// This handles @ContentChild/@ContentChildren decorators and signal-based queries
// (contentChild(), contentChildren()).
// Per Angular compiler.ts lines 57-63 (baseDirectiveFields)
if let Some(content_queries) = content_queries_fn {
entries.push(LiteralMapEntry {
key: Atom::from("contentQueries"),
value: content_queries,
quoted: false,
});
}
// 4. viewQuery: function(rf, ctx) { ... } (if any)
// This handles @ViewChild/@ViewChildren decorators.
// The predicate arrays are pre-pooled to ensure correct constant ordering.
// Per Angular compiler.ts lines 65-70 (baseDirectiveFields)
if let Some(view_query) = view_query_fn {
entries.push(LiteralMapEntry {
key: Atom::from("viewQuery"),
value: view_query,
quoted: false,
});
}
// 5-7. Host binding fields (hostAttrs, hostVars, hostBindings)
// Per Angular compiler.ts lines 72-84 and createHostBindingsFunction (lines 525-532)
// In Angular, createHostBindingsFunction sets hostAttrs and hostVars on definitionMap
// before returning the hostBindings function.
if let Some(host_result) = host_binding_result {
// 5. hostAttrs: [...] - static host attributes
if let Some(host_attrs) = host_result.host_attrs {
entries.push(LiteralMapEntry {
key: Atom::from("hostAttrs"),
value: host_attrs,
quoted: false,
});
}
// 6. hostVars: number - only if > 0
if let Some(host_vars) = host_result.host_vars {
entries.push(LiteralMapEntry {
key: Atom::from("hostVars"),
value: OutputExpression::Literal(Box::new_in(
LiteralExpr {
value: LiteralValue::Number(host_vars as f64),
source_span: None,
},
allocator,
)),
quoted: false,
});
}
// 7. hostBindings: function(rf, ctx) { ... } (if any)
if let Some(host_fn) = host_result.host_binding_fn {
entries.push(LiteralMapEntry {
key: Atom::from("hostBindings"),
value: OutputExpression::Function(Box::new_in(host_fn, allocator)),
quoted: false,
});
}
}
// 8. inputs: { prop: "prop", aliased: { classPropertyName: "aliased", publicName: "alias", ... } }
// Per Angular compiler.ts lines 86-87 (baseDirectiveFields)
if !metadata.inputs.is_empty() {
if let Some(inputs_expr) = create_inputs_literal(allocator, &metadata.inputs) {
entries.push(LiteralMapEntry {
key: Atom::from("inputs"),
value: inputs_expr,
quoted: false,
});
}
}
// 9. outputs: { click: "click" }
// Per Angular compiler.ts lines 89-90 (baseDirectiveFields)
if !metadata.outputs.is_empty() {
if let Some(outputs_expr) = create_outputs_literal(allocator, &metadata.outputs) {
entries.push(LiteralMapEntry {
key: Atom::from("outputs"),
value: outputs_expr,
quoted: false,
});
}
}
// 10. exportAs: [...] (if not null)
// Per Angular compiler.ts lines 92-94 (baseDirectiveFields)
if !metadata.export_as.is_empty() {
let mut export_items = OxcVec::new_in(allocator);
for name in &metadata.export_as {
export_items.push(OutputExpression::Literal(Box::new_in(
LiteralExpr { value: LiteralValue::String(name.clone()), source_span: None },
allocator,
)));
}
entries.push(LiteralMapEntry {
key: Atom::from("exportAs"),
value: OutputExpression::LiteralArray(Box::new_in(
LiteralArrayExpr { entries: export_items, source_span: None },
allocator,
)),
quoted: false,
});
}
// 11. standalone: false - only emit when NOT standalone (true is the default in Angular v17+)
// Per Angular compiler.ts lines 96-98 (baseDirectiveFields)
if !metadata.standalone {
entries.push(LiteralMapEntry {
key: Atom::from("standalone"),
value: OutputExpression::Literal(Box::new_in(
LiteralExpr { value: LiteralValue::Boolean(false), source_span: None },
allocator,
)),
quoted: false,
});
}
// 12. signals: true (if isSignal)
// Per Angular compiler.ts lines 99-101 (baseDirectiveFields)
if metadata.is_signal {
entries.push(LiteralMapEntry {
key: Atom::from("signals"),
value: OutputExpression::Literal(Box::new_in(
LiteralExpr { value: LiteralValue::Boolean(true), source_span: None },
allocator,
)),
quoted: false,
});
}
// =========================================================================
// Angular field ordering from addFeatures (compiler.ts lines 119-161)
// =========================================================================
// 13. features: [...] - component features like providers, lifecycle hooks, inheritance
// See: packages/compiler/src/render3/view/compiler.ts:119-161
if let Some(features) = generate_features_array(allocator, metadata, namespace_registry) {
entries.push(LiteralMapEntry {
key: Atom::from("features"),
value: features,
quoted: false,
});
}
// =========================================================================
// Angular field ordering from compileComponentFromMetadata (compiler.ts lines 184-354)
// =========================================================================
// 14. attrs: ["class", "..."] - only if first selector has attributes
// This is optional and only included if the first selector specifies attributes.
// Ported from Angular compiler.ts lines 195-212.
// The attrs_ref is pre-pooled BEFORE template compilation to ensure correct constant ordering.
// TypeScript Angular adds attrs to the pool BEFORE template ingestion/compilation.
if let Some(attrs) = attrs_ref {
entries.push(LiteralMapEntry { key: Atom::from("attrs"), value: attrs, quoted: false });
}
// 15. ngContentSelectors: [...] - content projection selectors
// Per Angular compiler.ts lines 254-256
if let Some(content_selectors) = job.content_selectors.take() {
entries.push(LiteralMapEntry {
key: Atom::from("ngContentSelectors"),
value: content_selectors,
quoted: false,
});
}
// 16. decls: number (from compilation)
// Per Angular compiler.ts line 258
let decls = job.root.decl_count.unwrap_or(0);
entries.push(LiteralMapEntry {
key: Atom::from("decls"),
value: OutputExpression::Literal(Box::new_in(
LiteralExpr { value: LiteralValue::Number(decls as f64), source_span: None },
allocator,
)),
quoted: false,
});
// 17. vars: number (from compilation)
// Per Angular compiler.ts line 259
let vars = job.root.vars.unwrap_or(0);
entries.push(LiteralMapEntry {
key: Atom::from("vars"),
value: OutputExpression::Literal(Box::new_in(
LiteralExpr { value: LiteralValue::Number(vars as f64), source_span: None },
allocator,
)),
quoted: false,
});
// 18. consts: [...] or consts: function() { ...initializers...; return [...]; }
// Per Angular compiler.ts lines 260-268:
// - If there are const initializers (e.g., for i18n dual-mode), wrap in arrow function
// - Otherwise, emit as plain literal array
if !job.consts.is_empty() {
let mut const_entries: OxcVec<'a, OutputExpression<'a>> = OxcVec::new_in(allocator);
for const_value in &job.consts {
const_entries.push(const_value_to_expression(allocator, const_value));
}
let consts_value = if !job.consts_initializers.is_empty() {
// Wrap consts in an arrow function that runs initializers first
// function() { ...initializers...; return [...consts...]; }
let mut fn_stmts: OxcVec<'a, OutputStatement<'a>> =
OxcVec::with_capacity_in(job.consts_initializers.len() + 1, allocator);
// Add all initializer statements
for stmt in job.consts_initializers.drain(..) {
fn_stmts.push(stmt);
}
// Add return statement with consts array
fn_stmts.push(OutputStatement::Return(Box::new_in(
ReturnStatement {
value: OutputExpression::LiteralArray(Box::new_in(
LiteralArrayExpr { entries: const_entries, source_span: None },
allocator,
)),
source_span: None,
},
allocator,
)));
OutputExpression::Function(Box::new_in(
FunctionExpr {
name: None,
params: OxcVec::new_in(allocator),
statements: fn_stmts,
source_span: None,
},
allocator,
))
} else {
// Plain literal array
OutputExpression::LiteralArray(Box::new_in(
LiteralArrayExpr { entries: const_entries, source_span: None },
allocator,
))
};
entries.push(LiteralMapEntry {
key: Atom::from("consts"),
value: consts_value,
quoted: false,
});
}
// 19. template: function(rf, ctx) { ... }
// Per Angular compiler.ts line 270
entries.push(LiteralMapEntry {
key: Atom::from("template"),
value: OutputExpression::Function(Box::new_in(template_fn, allocator)),
quoted: false,
});
// 20. dependencies: [...] - template dependencies (directives and pipes)
// Per Angular compiler.ts lines 272-289
if let Some(dependencies) =
generate_dependencies_expression(allocator, metadata, namespace_registry)
{
entries.push(LiteralMapEntry {
key: Atom::from("dependencies"),
value: dependencies,
quoted: false,
});
}
// 21. styles: [...]
// Process styles based on encapsulation mode
// Per Angular compiler (compiler.ts lines 291-323):
// - For Emulated mode: apply CSS scoping via compileStyles/encapsulate_style
// - For None/ShadowDom: use styles as-is
// - If no styles and Emulated: downgrade encapsulation to None
let mut has_styles = false;
let mut effective_encapsulation = metadata.encapsulation;
// CSS scoping uses %COMP% as a placeholder that Angular's runtime replaces
// with the actual component ID at runtime. This matches Angular's compiler behavior.
// See: packages/compiler/src/render3/view/compiler.ts
let content_attr = "_ngcontent-%COMP%";
let host_attr = "_nghost-%COMP%";
if !metadata.styles.is_empty() {
let mut style_entries: OxcVec<'a, OutputExpression<'a>> = OxcVec::new_in(allocator);
for style in &metadata.styles {
// Apply CSS scoping for Emulated encapsulation
let style_value = if metadata.encapsulation == ViewEncapsulation::Emulated {
// Use shim_css_text with %COMP% placeholder
// Angular's runtime will replace %COMP% with the actual component ID
let scoped = crate::styles::shim_css_text(style.as_str(), content_attr, host_attr);
// Skip empty styles
if scoped.trim().is_empty() {
continue;
}
Atom::from_in(scoped.as_str(), allocator)
} else {
// For None/ShadowDom, use styles as-is
if style.trim().is_empty() {
continue;
}
style.clone()
};
style_entries.push(OutputExpression::Literal(Box::new_in(
LiteralExpr { value: LiteralValue::String(style_value), source_span: None },
allocator,
)));
}
if !style_entries.is_empty() {
has_styles = true;
entries.push(LiteralMapEntry {
key: Atom::from("styles"),
value: OutputExpression::LiteralArray(Box::new_in(
LiteralArrayExpr { entries: style_entries, source_span: None },
allocator,
)),
quoted: false,
});
}
}
// If no styles and encapsulation is Emulated, downgrade to None
// (per Angular compiler.ts lines 315-318: "If there is no style, don't generate css selectors on elements")
if !has_styles && effective_encapsulation == ViewEncapsulation::Emulated {
effective_encapsulation = ViewEncapsulation::None;
}
// 22. encapsulation: number
// Only set encapsulation if it's NOT the default (Emulated)
// Per Angular compiler.ts lines 320-323
if effective_encapsulation != ViewEncapsulation::Emulated {
let encapsulation_value = match effective_encapsulation {
ViewEncapsulation::Emulated => 0, // Should not reach here
ViewEncapsulation::None => 2,
ViewEncapsulation::ShadowDom => 3,
};
entries.push(LiteralMapEntry {
key: Atom::from("encapsulation"),
value: OutputExpression::Literal(Box::new_in(
LiteralExpr {
value: LiteralValue::Number(encapsulation_value as f64),
source_span: None,
},
allocator,
)),
quoted: false,
});
}
// 23. data: {animation: [...]} - animation triggers
// Per Angular compiler.ts lines 325-331
if let Some(ref animations) = metadata.animations {
// Create the inner map: {animation: animationsExpr}
let mut data_entries: OxcVec<'a, LiteralMapEntry<'a>> =
OxcVec::with_capacity_in(1, allocator);
data_entries.push(LiteralMapEntry {
key: Atom::from("animation"),
// Use the full animations expression directly
value: animations.clone_in(allocator),
quoted: false,
});
entries.push(LiteralMapEntry {
key: Atom::from("data"),
value: OutputExpression::LiteralMap(Box::new_in(
LiteralMapExpr { entries: data_entries, source_span: None },
allocator,
)),
quoted: false,
});
}
// 24. changeDetection: ChangeDetectionStrategy.OnPush - only emit if not Default
// (to match TypeScript compiler behavior)
// Per Angular compiler.ts lines 334-346
// Angular enum values: OnPush = 0, Default = 1
// NOTE: Angular emits without namespace prefix (ChangeDetectionStrategy.OnPush, not i0.ChangeDetectionStrategy.OnPush)
if metadata.change_detection != ChangeDetectionStrategy::Default {
let strategy_name = match metadata.change_detection {
ChangeDetectionStrategy::Default => "Default",
ChangeDetectionStrategy::OnPush => "OnPush",
};
// Build: ChangeDetectionStrategy.OnPush (no i0 prefix)
// ReadPropExpr { receiver: ReadVarExpr("ChangeDetectionStrategy"), name: "OnPush" }
let change_detection_strategy_expr = OutputExpression::ReadVar(Box::new_in(
ReadVarExpr {
name: Atom::from(Identifiers::CHANGE_DETECTION_STRATEGY),
source_span: None,
},
allocator,
));
let strategy_value_expr = OutputExpression::ReadProp(Box::new_in(
ReadPropExpr {
receiver: Box::new_in(change_detection_strategy_expr, allocator),
name: Atom::from(strategy_name),
optional: false,
source_span: None,
},
allocator,
));
entries.push(LiteralMapEntry {
key: Atom::from("changeDetection"),
value: strategy_value_expr,
quoted: false,
});
}
// Create the config object
let config = OutputExpression::LiteralMap(Box::new_in(
LiteralMapExpr { entries, source_span: None },
allocator,
));
// Wrap in ɵɵdefineComponent call
create_define_component_call(allocator, config)
}
/// Generate the ɵfac factory function.
///
/// Creates one of two patterns:
///
/// ## With constructor (constructor_deps is Some):
/// ```javascript
/// // Constructor with dependencies:
/// function ComponentClass_Factory(__ngFactoryType__) {
/// return new (__ngFactoryType__ || ComponentClass)(
/// i0.ɵɵdirectiveInject(ServiceA),
/// i0.ɵɵdirectiveInject(ServiceB, 8) // 8 = Optional flag
/// );
/// }
///
/// // Constructor with no parameters:
/// function ComponentClass_Factory(__ngFactoryType__) {
/// return new (__ngFactoryType__ || ComponentClass)();
/// }
/// ```
///
/// ## No constructor (constructor_deps is None - use inherited factory):
/// ```javascript
/// /*@__PURE__*/ (() => {
/// let ɵComponentClass_BaseFactory;
/// return function ComponentClass_Factory(__ngFactoryType__) {
/// return (ɵComponentClass_BaseFactory ||
/// (ɵComponentClass_BaseFactory = i0.ɵɵgetInheritedFactory(ComponentClass)))
/// (__ngFactoryType__ || ComponentClass);
/// };
/// })()
/// ```
///
/// Ported from: `packages/compiler/src/render3/r3_factory.ts:106-200`
fn generate_fac_definition<'a>(
allocator: &'a Allocator,
metadata: &ComponentMetadata<'a>,
namespace_registry: &mut NamespaceRegistry<'a>,
) -> OutputExpression<'a> {
// Check if we need inherited factory pattern (no constructor found)
match &metadata.constructor_deps {
None => {
// No constructor - use inherited factory IIFE pattern
generate_inherited_factory(allocator, metadata)
}
Some(deps) => {
// Constructor exists - generate normal factory
generate_constructor_factory(allocator, metadata, deps, namespace_registry)
}
}
}
/// Generate a normal constructor-based factory function.
///
/// Generates:
/// ```javascript
/// function ComponentClass_Factory(__ngFactoryType__) {
/// return new (__ngFactoryType__ || ComponentClass)(deps...);
/// }
/// ```
fn generate_constructor_factory<'a>(
allocator: &'a Allocator,
metadata: &ComponentMetadata<'a>,
deps: &[R3DependencyMetadata<'a>],
namespace_registry: &mut NamespaceRegistry<'a>,
) -> OutputExpression<'a> {
// Function name: ComponentClass_Factory
let fn_name_string = format!("{}_Factory", metadata.class_name);
let fn_name = Atom::from_in(fn_name_string.as_str(), allocator);
// Parameter: __ngFactoryType__ (type override for inheritance/testing)
let mut params: OxcVec<'a, FnParam<'a>> = OxcVec::new_in(allocator);
params.push(FnParam { name: Atom::from("__ngFactoryType__") });
// Body: return new (__ngFactoryType__ || ComponentClass)(deps...);
let mut statements: OxcVec<'a, OutputStatement<'a>> = OxcVec::new_in(allocator);
// Create: (__ngFactoryType__ || ComponentClass)
let or_expr = OutputExpression::BinaryOperator(Box::new_in(
crate::output::ast::BinaryOperatorExpr {
operator: crate::output::ast::BinaryOperator::Or,
lhs: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: Atom::from("__ngFactoryType__"), source_span: None },
allocator,
)),
allocator,
),
rhs: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: metadata.class_name.clone(), source_span: None },
allocator,
)),
allocator,
),
source_span: None,
},
allocator,
));
// Compile constructor dependencies if any
// Uses FactoryTarget::Component for components
// The namespace_registry is used to resolve imported dependency namespaces
let constructor_args = if deps.is_empty() {
OxcVec::new_in(allocator)
} else {
compile_inject_dependencies(allocator, deps, FactoryTarget::Component, namespace_registry)
};
// Create: new (__ngFactoryType__ || ComponentClass)(dep1, dep2, ...)
let new_expr = OutputExpression::Instantiate(Box::new_in(
InstantiateExpr {
class_expr: Box::new_in(or_expr, allocator),
args: constructor_args,
source_span: None,
},
allocator,
));
// return new (__ngFactoryType__ || ComponentClass)(deps...);
statements.push(OutputStatement::Return(Box::new_in(
ReturnStatement { value: new_expr, source_span: None },
allocator,
)));
OutputExpression::Function(Box::new_in(
FunctionExpr { name: Some(fn_name), params, statements, source_span: None },
allocator,
))
}
/// Generate an inherited factory using the IIFE memoization pattern.
///
/// Generates:
/// ```javascript
/// /*@__PURE__*/ (() => {
/// let ɵComponentClass_BaseFactory;
/// return function ComponentClass_Factory(__ngFactoryType__) {
/// return (ɵComponentClass_BaseFactory ||
/// (ɵComponentClass_BaseFactory = i0.ɵɵgetInheritedFactory(ComponentClass)))
/// (__ngFactoryType__ || ComponentClass);
/// };
/// })()
/// ```
///
/// See: packages/compiler/src/render3/r3_factory.ts:160-193
fn generate_inherited_factory<'a>(
allocator: &'a Allocator,
metadata: &ComponentMetadata<'a>,
) -> OutputExpression<'a> {
use crate::output::ast::{
ArrowFunctionBody, ArrowFunctionExpr, BinaryOperator, BinaryOperatorExpr, DeclareVarStmt,
StmtModifier,
};
let factory_type_param = Atom::from("__ngFactoryType__");
// Create base factory variable name: ɵComponentClass_BaseFactory
let base_factory_var_name =
Atom::from_in(format!("ɵ{}_BaseFactory", metadata.class_name).as_str(), allocator);
// Function name: ComponentClass_Factory
let fn_name_string = format!("{}_Factory", metadata.class_name);
let fn_name = Atom::from_in(fn_name_string.as_str(), allocator);
// Create ɵɵgetInheritedFactory(ComponentClass) call
let get_inherited_factory_call = {
let fn_expr = OutputExpression::ReadProp(Box::new_in(
ReadPropExpr {
receiver: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: Atom::from("i0"), source_span: None },
allocator,
)),
allocator,
),
name: Atom::from(Identifiers::GET_INHERITED_FACTORY),
optional: false,
source_span: None,
},
allocator,
));
let mut args = OxcVec::new_in(allocator);
args.push(OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: metadata.class_name.clone(), source_span: None },
allocator,
)));
OutputExpression::InvokeFunction(Box::new_in(
InvokeFunctionExpr {
fn_expr: Box::new_in(fn_expr, allocator),
args,
pure: false,
optional: false,
source_span: None,
},
allocator,
))
};
// Create assignment: ɵComponentClass_BaseFactory = ɵɵgetInheritedFactory(ComponentClass)
let assignment = OutputExpression::BinaryOperator(Box::new_in(
BinaryOperatorExpr {
operator: BinaryOperator::Assign,
lhs: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: base_factory_var_name.clone(), source_span: None },
allocator,
)),
allocator,
),
rhs: Box::new_in(get_inherited_factory_call, allocator),
source_span: None,
},
allocator,
));
// Create memoization pattern: baseFactoryVar || (baseFactoryVar = ɵɵgetInheritedFactory(...))
let memoized_factory = OutputExpression::BinaryOperator(Box::new_in(
BinaryOperatorExpr {
operator: BinaryOperator::Or,
lhs: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: base_factory_var_name.clone(), source_span: None },
allocator,
)),
allocator,
),
rhs: Box::new_in(assignment, allocator),
source_span: None,
},
allocator,
));
// Create (__ngFactoryType__ || ComponentClass)
let type_for_ctor = OutputExpression::BinaryOperator(Box::new_in(
BinaryOperatorExpr {
operator: BinaryOperator::Or,
lhs: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: factory_type_param.clone(), source_span: None },
allocator,
)),
allocator,
),
rhs: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: metadata.class_name.clone(), source_span: None },
allocator,
)),
allocator,
),
source_span: None,
},
allocator,
));
// Create the factory call: (memoizedFactory)(__ngFactoryType__ || ComponentClass)
let mut factory_call_args = OxcVec::new_in(allocator);
factory_call_args.push(type_for_ctor);
let factory_call = OutputExpression::InvokeFunction(Box::new_in(
InvokeFunctionExpr {
fn_expr: Box::new_in(memoized_factory, allocator),
args: factory_call_args,
pure: false,
optional: false,
source_span: None,
},
allocator,
));
// Create return statement for inner function
let mut inner_body: OxcVec<'a, OutputStatement<'a>> = OxcVec::new_in(allocator);
inner_body.push(OutputStatement::Return(Box::new_in(
ReturnStatement { value: factory_call, source_span: None },
allocator,
)));
// Create inner function: function ComponentClass_Factory(__ngFactoryType__) { ... }
let mut inner_params = OxcVec::new_in(allocator);
inner_params.push(FnParam { name: factory_type_param });
let inner_fn = OutputExpression::Function(Box::new_in(
FunctionExpr {
name: Some(fn_name),
params: inner_params,
statements: inner_body,
source_span: None,
},
allocator,
));
// Create IIFE body: let ɵComponentClass_BaseFactory; return function...;
let mut iife_body: OxcVec<'a, OutputStatement<'a>> = OxcVec::new_in(allocator);
// Declaration: let ɵComponentClass_BaseFactory;
iife_body.push(OutputStatement::DeclareVar(Box::new_in(
DeclareVarStmt {
name: base_factory_var_name,
value: None,
modifiers: StmtModifier::NONE,
leading_comment: None,
source_span: None,
},
allocator,
)));
// Return the inner function
iife_body.push(OutputStatement::Return(Box::new_in(
ReturnStatement { value: inner_fn, source_span: None },
allocator,
)));
// Create arrow function IIFE: () => { let x; return function...; }
let arrow_fn = OutputExpression::ArrowFunction(Box::new_in(
ArrowFunctionExpr {
params: OxcVec::new_in(allocator),
body: ArrowFunctionBody::Statements(iife_body),
source_span: None,
},
allocator,
));
// Invoke the IIFE: (() => { ... })()
OutputExpression::InvokeFunction(Box::new_in(
InvokeFunctionExpr {
fn_expr: Box::new_in(arrow_fn, allocator),
args: OxcVec::new_in(allocator),
pure: true, // Mark as @__PURE__ for tree-shaking
optional: false,
source_span: None,
},
allocator,
))
}
/// Create an i0.ɵɵdefineComponent(config) call expression.
fn create_define_component_call<'a>(
allocator: &'a Allocator,
config: OutputExpression<'a>,
) -> OutputExpression<'a> {
// Access: i0.ɵɵdefineComponent
let define_component = OutputExpression::ReadProp(Box::new_in(
crate::output::ast::ReadPropExpr {
receiver: Box::new_in(
OutputExpression::ReadVar(Box::new_in(
ReadVarExpr { name: Atom::from("i0"), source_span: None },
allocator,
)),
allocator,
),
name: Atom::from(Identifiers::DEFINE_COMPONENT),
optional: false,
source_span: None,
},
allocator,
));
// Call: i0.ɵɵdefineComponent(config)
let mut args: OxcVec<'a, OutputExpression<'a>> = OxcVec::new_in(allocator);
args.push(config);
OutputExpression::InvokeFunction(Box::new_in(
crate::output::ast::InvokeFunctionExpr {
fn_expr: Box::new_in(define_component, allocator),
args,
pure: true,
optional: false,
source_span: None,
},
allocator,
))
}
/// Parse a CSS selector string into the Angular R3 selector format.
///
/// Uses the full CSS selector parser to correctly handle combined selectors.
/// Angular represents selectors as nested arrays:
/// - `"app-root"` -> `[["app-root"]]`
/// - `"span[bitBadge]"` -> `[["span", "bitBadge", ""]]`
/// - `"[type=button]"` -> `[["", "type", "button"]]`
/// - `".my-class"` -> `[["", 8, "my-class"]]` (8 = SelectorFlags.CLASS)
///
/// Ported from Angular's `parseSelectorToR3Selector` in `core.ts`.
fn parse_selector_to_array<'a>(
allocator: &'a Allocator,
selector: &Atom<'a>,
) -> OutputExpression<'a> {
let r3_selectors = parse_selector_to_r3_selector(selector.as_str());
let mut outer_entries: OxcVec<'a, OutputExpression<'a>> = OxcVec::new_in(allocator);
for r3_selector in &r3_selectors {
let inner_entries = r3_selector_to_output_expr(allocator, r3_selector);
outer_entries.push(OutputExpression::LiteralArray(Box::new_in(
LiteralArrayExpr { entries: inner_entries, source_span: None },
allocator,
)));
}
OutputExpression::LiteralArray(Box::new_in(
LiteralArrayExpr { entries: outer_entries, source_span: None },
allocator,
))
}
// =============================================================================
// Features Array Generation
// See: packages/compiler/src/render3/view/compiler.ts:119-161
// =============================================================================
/// Generate the features array for a component definition.
///
/// Features are special runtime behaviors that Angular applies to components:
/// - `ProvidersFeature`: When providers or viewProviders are defined
/// - `HostDirectivesFeature`: When hostDirectives are defined
/// - `InheritDefinitionFeature`: When the component extends another directive/component
/// - `NgOnChangesFeature`: When the component implements ngOnChanges
/// - `ExternalStylesFeature`: When external stylesheets need to be loaded
///
/// Order is important: ProvidersFeature → HostDirectivesFeature → InheritDefinitionFeature
/// → NgOnChangesFeature → ExternalStylesFeature
///
/// See: packages/compiler/src/render3/view/compiler.ts:119-161
fn generate_features_array<'a>(
allocator: &'a Allocator,
metadata: &ComponentMetadata<'a>,
namespace_registry: &mut NamespaceRegistry<'a>,
) -> Option<OutputExpression<'a>> {