-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmod.rs
More file actions
2180 lines (2014 loc) · 85 KB
/
mod.rs
File metadata and controls
2180 lines (2014 loc) · 85 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
//! Angular Partial Declaration Linker.
//!
//! Processes pre-compiled Angular library code from node_modules that contains
//! partial compilation declarations (`ɵɵngDeclare*`). These declarations need
//! to be "linked" (converted to full `ɵɵdefine*` calls) at build time.
//!
//! Without this linker, Angular falls back to JIT compilation which requires
//! `@angular/compiler` at runtime.
//!
//! ## Supported Declarations
//!
//! | Partial Declaration | Linked Output |
//! |--------------------|-|
//! | `ɵɵngDeclareFactory` | Factory function |
//! | `ɵɵngDeclareInjectable` | `ɵɵdefineInjectable(...)` |
//! | `ɵɵngDeclareInjector` | `ɵɵdefineInjector(...)` |
//! | `ɵɵngDeclareNgModule` | `ɵɵdefineNgModule(...)` |
//! | `ɵɵngDeclarePipe` | `ɵɵdefinePipe(...)` |
//! | `ɵɵngDeclareDirective` | `ɵɵdefineDirective(...)` |
//! | `ɵɵngDeclareComponent` | `ɵɵdefineComponent(...)` |
//! | `ɵɵngDeclareClassMetadata` | `ɵɵsetClassMetadata(...)` |
//!
//! ## Usage
//!
//! ```ignore
//! use oxc_allocator::Allocator;
//! use oxc_angular_compiler::linker::link;
//!
//! let allocator = Allocator::default();
//! let code = "static ɵfac = i0.ɵɵngDeclareFactory({...});";
//! let result = link(&allocator, code, "common.mjs");
//! println!("{}", result.code);
//! ```
use oxc_allocator::Allocator;
use oxc_ast::ast::{
Argument, ArrayExpressionElement, CallExpression, Expression, ObjectExpression,
ObjectPropertyKind, Program, PropertyKey, Statement,
};
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType};
use crate::optimizer::Edit;
/// Partial declaration function names to link.
const DECLARE_FACTORY: &str = "\u{0275}\u{0275}ngDeclareFactory";
const DECLARE_INJECTABLE: &str = "\u{0275}\u{0275}ngDeclareInjectable";
const DECLARE_INJECTOR: &str = "\u{0275}\u{0275}ngDeclareInjector";
const DECLARE_NG_MODULE: &str = "\u{0275}\u{0275}ngDeclareNgModule";
const DECLARE_PIPE: &str = "\u{0275}\u{0275}ngDeclarePipe";
const DECLARE_DIRECTIVE: &str = "\u{0275}\u{0275}ngDeclareDirective";
const DECLARE_COMPONENT: &str = "\u{0275}\u{0275}ngDeclareComponent";
const DECLARE_CLASS_METADATA: &str = "\u{0275}\u{0275}ngDeclareClassMetadata";
const DECLARE_CLASS_METADATA_ASYNC: &str = "\u{0275}\u{0275}ngDeclareClassMetadataAsync";
/// Result of linking an Angular package file.
#[derive(Debug, Clone, Default)]
pub struct LinkResult {
/// The linked code.
pub code: String,
/// Source map (if enabled).
pub map: Option<String>,
/// Whether any declarations were linked.
pub linked: bool,
}
/// Link Angular partial declarations in a JavaScript file.
///
/// Scans the code for `ɵɵngDeclare*` calls and replaces them with their
/// fully compiled equivalents.
pub fn link(allocator: &Allocator, code: &str, filename: &str) -> LinkResult {
// Quick check: if no declarations, return early
if !code.contains("\u{0275}\u{0275}ngDeclare") {
return LinkResult { code: code.to_string(), map: None, linked: false };
}
let source_type = SourceType::from_path(filename).unwrap_or(SourceType::mjs());
let parser_result = Parser::new(allocator, code, source_type).parse();
if parser_result.panicked || !parser_result.errors.is_empty() {
return LinkResult { code: code.to_string(), map: None, linked: false };
}
let program = parser_result.program;
let mut edits: Vec<Edit> = Vec::new();
// Walk all statements looking for ɵɵngDeclare* calls
collect_declaration_edits(&program, code, filename, &mut edits);
if edits.is_empty() {
return LinkResult { code: code.to_string(), map: None, linked: false };
}
let linked_code = crate::optimizer::apply_edits(code, edits);
LinkResult { code: linked_code, map: None, linked: true }
}
/// Recursively walk the AST to find all ɵɵngDeclare* calls and generate edits.
fn collect_declaration_edits(
program: &Program<'_>,
source: &str,
filename: &str,
edits: &mut Vec<Edit>,
) {
for stmt in &program.body {
walk_statement(stmt, source, filename, edits);
}
}
/// Walk a statement looking for ɵɵngDeclare* calls.
fn walk_statement(stmt: &Statement<'_>, source: &str, filename: &str, edits: &mut Vec<Edit>) {
match stmt {
Statement::ExpressionStatement(expr_stmt) => {
walk_expression(&expr_stmt.expression, source, filename, edits);
}
Statement::ClassDeclaration(class_decl) => {
walk_class_body(&class_decl.body, source, filename, edits);
}
Statement::VariableDeclaration(var_decl) => {
for decl in &var_decl.declarations {
if let Some(init) = &decl.init {
walk_expression(init, source, filename, edits);
}
}
}
Statement::ReturnStatement(ret) => {
if let Some(ref arg) = ret.argument {
walk_expression(arg, source, filename, edits);
}
}
Statement::BlockStatement(block) => {
for stmt in &block.body {
walk_statement(stmt, source, filename, edits);
}
}
Statement::IfStatement(if_stmt) => {
walk_statement(&if_stmt.consequent, source, filename, edits);
if let Some(ref alt) = if_stmt.alternate {
walk_statement(alt, source, filename, edits);
}
}
Statement::ForStatement(for_stmt) => {
walk_statement(&for_stmt.body, source, filename, edits);
}
Statement::ForInStatement(for_in) => {
walk_statement(&for_in.body, source, filename, edits);
}
Statement::ForOfStatement(for_of) => {
walk_statement(&for_of.body, source, filename, edits);
}
Statement::WhileStatement(while_stmt) => {
walk_statement(&while_stmt.body, source, filename, edits);
}
Statement::DoWhileStatement(do_while) => {
walk_statement(&do_while.body, source, filename, edits);
}
Statement::TryStatement(try_stmt) => {
for stmt in &try_stmt.block.body {
walk_statement(stmt, source, filename, edits);
}
if let Some(ref handler) = try_stmt.handler {
for stmt in &handler.body.body {
walk_statement(stmt, source, filename, edits);
}
}
if let Some(ref finalizer) = try_stmt.finalizer {
for stmt in &finalizer.body {
walk_statement(stmt, source, filename, edits);
}
}
}
Statement::SwitchStatement(switch_stmt) => {
for case in &switch_stmt.cases {
for stmt in &case.consequent {
walk_statement(stmt, source, filename, edits);
}
}
}
Statement::LabeledStatement(labeled) => {
walk_statement(&labeled.body, source, filename, edits);
}
Statement::FunctionDeclaration(func_decl) => {
if let Some(ref body) = func_decl.body {
for stmt in &body.statements {
walk_statement(stmt, source, filename, edits);
}
}
}
Statement::ExportNamedDeclaration(export_decl) => {
if let Some(ref decl) = export_decl.declaration {
walk_declaration(decl, source, filename, edits);
}
}
Statement::ExportDefaultDeclaration(export_default) => match &export_default.declaration {
oxc_ast::ast::ExportDefaultDeclarationKind::ClassDeclaration(class_decl) => {
walk_class_body(&class_decl.body, source, filename, edits);
}
oxc_ast::ast::ExportDefaultDeclarationKind::FunctionDeclaration(func_decl) => {
if let Some(ref body) = func_decl.body {
for stmt in &body.statements {
walk_statement(stmt, source, filename, edits);
}
}
}
_ => {
if let Some(expr) = export_default.declaration.as_expression() {
walk_expression(expr, source, filename, edits);
}
}
},
_ => {}
}
}
/// Walk a class body looking for ɵɵngDeclare* calls in property definitions and static blocks.
fn walk_class_body(
body: &oxc_ast::ast::ClassBody<'_>,
source: &str,
filename: &str,
edits: &mut Vec<Edit>,
) {
for element in &body.body {
if let oxc_ast::ast::ClassElement::PropertyDefinition(prop) = element {
if let Some(ref value) = prop.value {
walk_expression(value, source, filename, edits);
}
}
if let oxc_ast::ast::ClassElement::StaticBlock(block) = element {
for stmt in &block.body {
walk_statement(stmt, source, filename, edits);
}
}
if let oxc_ast::ast::ClassElement::MethodDefinition(method) = element {
if let Some(ref body) = method.value.body {
for stmt in &body.statements {
walk_statement(stmt, source, filename, edits);
}
}
}
}
}
/// Walk a declaration (from export statements) looking for ɵɵngDeclare* calls.
fn walk_declaration(
decl: &oxc_ast::ast::Declaration<'_>,
source: &str,
filename: &str,
edits: &mut Vec<Edit>,
) {
match decl {
oxc_ast::ast::Declaration::VariableDeclaration(var_decl) => {
for d in &var_decl.declarations {
if let Some(init) = &d.init {
walk_expression(init, source, filename, edits);
}
}
}
oxc_ast::ast::Declaration::FunctionDeclaration(func_decl) => {
if let Some(ref body) = func_decl.body {
for stmt in &body.statements {
walk_statement(stmt, source, filename, edits);
}
}
}
oxc_ast::ast::Declaration::ClassDeclaration(class_decl) => {
walk_class_body(&class_decl.body, source, filename, edits);
}
_ => {}
}
}
/// Walk an expression looking for ɵɵngDeclare* calls.
fn walk_expression(expr: &Expression<'_>, source: &str, filename: &str, edits: &mut Vec<Edit>) {
match expr {
Expression::CallExpression(call) => {
if let Some(name) = get_declare_name(call) {
if let Some(edit) = link_declaration(name, call, source, filename) {
edits.push(edit);
return;
}
}
// Walk arguments recursively
for arg in &call.arguments {
if let Argument::SpreadElement(_) = arg {
continue;
}
walk_expression(arg.to_expression(), source, filename, edits);
}
}
Expression::AssignmentExpression(assign) => {
walk_expression(&assign.right, source, filename, edits);
}
Expression::SequenceExpression(seq) => {
for expr in &seq.expressions {
walk_expression(expr, source, filename, edits);
}
}
Expression::ConditionalExpression(cond) => {
walk_expression(&cond.consequent, source, filename, edits);
walk_expression(&cond.alternate, source, filename, edits);
}
Expression::LogicalExpression(logical) => {
walk_expression(&logical.left, source, filename, edits);
walk_expression(&logical.right, source, filename, edits);
}
Expression::ParenthesizedExpression(paren) => {
walk_expression(&paren.expression, source, filename, edits);
}
Expression::ArrowFunctionExpression(arrow) => {
for stmt in &arrow.body.statements {
walk_statement(stmt, source, filename, edits);
}
}
Expression::FunctionExpression(func) => {
if let Some(body) = &func.body {
for stmt in &body.statements {
walk_statement(stmt, source, filename, edits);
}
}
}
Expression::ClassExpression(class_expr) => {
walk_class_body(&class_expr.body, source, filename, edits);
}
_ => {}
}
}
/// Check if a call expression is a ɵɵngDeclare* call and return the declaration name.
fn get_declare_name<'a>(call: &'a CallExpression<'a>) -> Option<&'a str> {
let name = match &call.callee {
Expression::Identifier(ident) => ident.name.as_str(),
Expression::StaticMemberExpression(member) => member.property.name.as_str(),
_ => return None,
};
match name {
DECLARE_FACTORY
| DECLARE_INJECTABLE
| DECLARE_INJECTOR
| DECLARE_NG_MODULE
| DECLARE_PIPE
| DECLARE_DIRECTIVE
| DECLARE_COMPONENT
| DECLARE_CLASS_METADATA
| DECLARE_CLASS_METADATA_ASYNC => Some(name),
_ => None,
}
}
/// Get the Angular import namespace (e.g., "i0") from the callee.
fn get_ng_import_namespace<'a>(call: &'a CallExpression<'a>) -> &'a str {
match &call.callee {
Expression::StaticMemberExpression(member) => {
if let Expression::Identifier(ident) = &member.object {
return ident.name.as_str();
}
"i0"
}
_ => "i0",
}
}
/// Get the metadata object from a ɵɵngDeclare* call's first argument.
fn get_metadata_object<'a>(call: &'a CallExpression<'a>) -> Option<&'a ObjectExpression<'a>> {
call.arguments.first().and_then(|arg| {
if let Argument::ObjectExpression(obj) = arg { Some(obj.as_ref()) } else { None }
})
}
/// Extract a string property value from an object expression.
/// Handles both regular string literals (`"..."`) and template literals with no expressions (`` `...` ``).
fn get_string_property<'a>(obj: &'a ObjectExpression<'a>, name: &str) -> Option<&'a str> {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if matches!(&prop.key, PropertyKey::StaticIdentifier(ident) if ident.name == name) {
match &prop.value {
Expression::StringLiteral(lit) => {
return Some(lit.value.as_str());
}
Expression::TemplateLiteral(tl) if tl.expressions.is_empty() => {
if let Some(quasi) = tl.quasis.first() {
if let Some(cooked) = &quasi.value.cooked {
return Some(cooked.as_str());
}
}
}
_ => {}
}
}
}
}
None
}
/// Extract the source text of a property value from an object expression.
fn get_property_source<'a>(
obj: &'a ObjectExpression<'a>,
name: &str,
source: &'a str,
) -> Option<&'a str> {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if matches!(&prop.key, PropertyKey::StaticIdentifier(ident) if ident.name == name) {
let span = prop.value.span();
return Some(&source[span.start as usize..span.end as usize]);
}
}
}
None
}
/// Check if a property exists in an object expression.
fn has_property(obj: &ObjectExpression<'_>, name: &str) -> bool {
obj.properties.iter().any(|prop| {
matches!(prop,
ObjectPropertyKind::ObjectProperty(p)
if matches!(&p.key, PropertyKey::StaticIdentifier(ident) if ident.name == name)
)
})
}
/// Extract an object expression property value from an object expression.
fn get_object_property<'a>(
obj: &'a ObjectExpression<'a>,
name: &str,
) -> Option<&'a ObjectExpression<'a>> {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if matches!(&prop.key, PropertyKey::StaticIdentifier(ident) if ident.name == name) {
if let Expression::ObjectExpression(inner) = &prop.value {
return Some(inner.as_ref());
}
}
}
}
None
}
/// Extract boolean property value.
fn get_bool_property(obj: &ObjectExpression<'_>, name: &str) -> Option<bool> {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if matches!(&prop.key, PropertyKey::StaticIdentifier(ident) if ident.name == name) {
if let Expression::BooleanLiteral(lit) = &prop.value {
return Some(lit.value);
}
}
}
}
None
}
/// Extract the `deps` array from a factory metadata object and generate inject calls.
fn extract_deps_source(obj: &ObjectExpression<'_>, source: &str, ns: &str) -> String {
for prop in &obj.properties {
if let ObjectPropertyKind::ObjectProperty(prop) = prop {
if matches!(&prop.key, PropertyKey::StaticIdentifier(ident) if ident.name == "deps") {
if let Expression::ArrayExpression(arr) = &prop.value {
if arr.elements.is_empty() {
return String::new();
}
// Generate inject calls for each dependency
let deps: Vec<String> = arr
.elements
.iter()
.filter_map(|el| {
use oxc_ast::ast::ArrayExpressionElement;
let expr = match el {
ArrayExpressionElement::SpreadElement(_) => return None,
_ => el.to_expression(),
};
let span = expr.span();
let dep_source = &source[span.start as usize..span.end as usize];
// Check if it's an object with token/attribute/flags
if let Expression::ObjectExpression(dep_obj) = expr {
let token = get_property_source(dep_obj.as_ref(), "token", source);
let optional = get_bool_property(dep_obj.as_ref(), "optional");
let self_flag = get_bool_property(dep_obj.as_ref(), "self");
let skip_self = get_bool_property(dep_obj.as_ref(), "skipSelf");
let host = get_bool_property(dep_obj.as_ref(), "host");
let attribute =
get_property_source(dep_obj.as_ref(), "attribute", source);
if let Some(attr) = attribute {
return Some(format!(
"{ns}.\u{0275}\u{0275}injectAttribute({attr})"
));
}
if let Some(token) = token {
let mut flags = 0u32;
if optional == Some(true) {
flags |= 8;
}
if self_flag == Some(true) {
flags |= 2;
}
if skip_self == Some(true) {
flags |= 4;
}
if host == Some(true) {
flags |= 1;
}
if flags != 0 {
return Some(format!(
"{ns}.\u{0275}\u{0275}inject({token}, {flags})"
));
}
return Some(format!("{ns}.\u{0275}\u{0275}inject({token})"));
}
Some(format!("{ns}.\u{0275}\u{0275}inject({dep_source})"))
} else {
Some(format!("{ns}.\u{0275}\u{0275}inject({dep_source})"))
}
})
.collect();
return deps.join(", ");
}
}
}
}
String::new()
}
/// Parse a CSS selector string into Angular's internal selector array format.
///
/// Angular represents selectors as nested arrays:
/// - `"app-root"` → `[["app-root"]]`
/// - `"[ngClass]"` → `[["", "ngClass", ""]]`
/// - `"[attr=value]"` → `[["", "attr", "value"]]`
/// - `"div[ngClass]"` → `[["div", "ngClass", ""]]`
/// - `"[a],[b]"` → `[["", "a", ""], ["", "b", ""]]`
/// - `".cls"` → `[["", "class", "cls"]]`
fn parse_selector(selector: &str) -> String {
let selectors: Vec<String> =
selector.split(',').map(|s| parse_single_selector(s.trim())).collect();
format!("[{}]", selectors.join(", "))
}
/// Parse a single selector (no commas) into Angular's array format.
fn parse_single_selector(selector: &str) -> String {
let mut parts: Vec<String> = Vec::new();
let mut remaining = selector;
// Extract tag name (everything before first [ or . or :)
let tag_end = remaining
.find(|c: char| c == '[' || c == '.' || c == ':' || c == '#')
.unwrap_or(remaining.len());
let tag = &remaining[..tag_end];
remaining = &remaining[tag_end..];
if !tag.is_empty() {
parts.push(format!("\"{}\"", tag));
} else {
parts.push("\"\"".to_string());
}
// Extract attribute selectors [attr] or [attr=value]
while let Some(bracket_start) = remaining.find('[') {
let bracket_end = remaining[bracket_start..].find(']').map(|i| bracket_start + i);
if let Some(end) = bracket_end {
let attr_content = &remaining[bracket_start + 1..end];
if let Some(eq_pos) = attr_content.find('=') {
let attr_name = &attr_content[..eq_pos];
let attr_value = attr_content[eq_pos + 1..].trim_matches('"').trim_matches('\'');
parts.push(format!("\"{}\"", attr_name));
parts.push(format!("\"{}\"", attr_value));
} else {
parts.push(format!("\"{}\"", attr_content));
parts.push("\"\"".to_string());
}
remaining = &remaining[end + 1..];
} else {
break;
}
}
// Extract class selectors .className
let mut class_remaining = remaining;
while let Some(dot_pos) = class_remaining.find('.') {
let class_end = class_remaining[dot_pos + 1..]
.find(|c: char| !c.is_alphanumeric() && c != '-' && c != '_')
.map(|i| dot_pos + 1 + i)
.unwrap_or(class_remaining.len());
let class_name = &class_remaining[dot_pos + 1..class_end];
if !class_name.is_empty() {
parts.push("\"class\"".to_string());
parts.push(format!("\"{}\"", class_name));
}
class_remaining = &class_remaining[class_end..];
}
format!("[{}]", parts.join(", "))
}
/// Build the `hostAttrs` flat array from the partial declaration's `host` object.
///
/// The `host` object in partial declarations has sub-properties:
/// - `attributes`: `{ "role": "tree", "tabindex": "-1" }` → `["role", "tree", "tabindex", "-1"]`
/// - `classAttribute`: `"cdk-tree"` → `[1, "cdk-tree"]` (1 = AttributeMarker.Classes)
/// - `styleAttribute`: `"display: block"` → `[2, "display: block"]` (2 = AttributeMarker.Styles)
///
/// Properties and listeners go into `hostBindings`, not `hostAttrs`.
fn build_host_attrs(host_obj: &ObjectExpression<'_>, source: &str) -> String {
let mut attrs: Vec<String> = Vec::new();
// Static attributes: { "role": "tree", "tabindex": "-1" }
if let Some(attr_obj) = get_object_property(host_obj, "attributes") {
for prop in &attr_obj.properties {
if let ObjectPropertyKind::ObjectProperty(p) = prop {
let key = match &p.key {
PropertyKey::StaticIdentifier(ident) => ident.name.to_string(),
PropertyKey::StringLiteral(s) => s.value.to_string(),
_ => continue,
};
let value_span = p.value.span();
let value = &source[value_span.start as usize..value_span.end as usize];
attrs.push(format!("\"{key}\""));
attrs.push(value.to_string());
}
}
}
// Class attribute: "cdk-tree" → [1, "cdk-tree"]
// AttributeMarker.Classes = 1
if let Some(class_attr) = get_string_property(host_obj, "classAttribute") {
// Split classes and add each separately
attrs.push("1".to_string()); // AttributeMarker.Classes
for class in class_attr.split_whitespace() {
attrs.push(format!("\"{class}\""));
}
}
// Style attribute: "display: block" → [2, "display", "block"]
// AttributeMarker.Styles = 2
if let Some(style_attr) = get_string_property(host_obj, "styleAttribute") {
attrs.push("2".to_string()); // AttributeMarker.Styles
// Parse style string into key-value pairs
for declaration in style_attr.split(';') {
let declaration = declaration.trim();
if declaration.is_empty() {
continue;
}
if let Some(colon_pos) = declaration.find(':') {
let prop = declaration[..colon_pos].trim();
let val = declaration[colon_pos + 1..].trim();
attrs.push(format!("\"{prop}\""));
attrs.push(format!("\"{val}\""));
}
}
}
attrs.join(", ")
}
/// Get the factory target from metadata.
fn get_factory_target(obj: &ObjectExpression<'_>, source: &str) -> &'static str {
if let Some(target_src) = get_property_source(obj, "target", source) {
if target_src.contains("Pipe") {
return "Pipe";
}
if target_src.contains("Directive") || target_src.contains("Component") {
return "Directive";
}
if target_src.contains("NgModule") {
return "NgModule";
}
}
"Injectable"
}
/// Link a single ɵɵngDeclare* call, generating the replacement code.
fn link_declaration(
name: &str,
call: &CallExpression<'_>,
source: &str,
filename: &str,
) -> Option<Edit> {
let meta = get_metadata_object(call)?;
let ns = get_ng_import_namespace(call);
let type_name = get_property_source(meta, "type", source)?;
let replacement = match name {
DECLARE_FACTORY => link_factory(meta, source, ns, type_name),
DECLARE_INJECTABLE => link_injectable(meta, source, ns, type_name),
DECLARE_INJECTOR => link_injector(meta, source, ns, type_name),
DECLARE_NG_MODULE => link_ng_module(meta, source, ns, type_name),
DECLARE_PIPE => link_pipe(meta, source, ns, type_name),
DECLARE_CLASS_METADATA => link_class_metadata(meta, source, ns, type_name),
DECLARE_CLASS_METADATA_ASYNC => link_class_metadata_async(meta, source, ns, type_name),
DECLARE_DIRECTIVE => link_directive(meta, source, ns, type_name),
DECLARE_COMPONENT => link_component(meta, source, filename, ns, type_name),
_ => return None,
};
let replacement = replacement?;
Some(Edit::replace(call.span.start, call.span.end, replacement))
}
/// Link ɵɵngDeclareFactory → factory function.
fn link_factory(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
let target = get_factory_target(meta, source);
// Check if deps are specified
let has_deps = has_property(meta, "deps");
if !has_deps {
// Inherited factory (no constructor) - use getInheritedFactory
Some(format!(
"/*@__PURE__*/ (() => {{\n\
let \u{0275}{type_name}_BaseFactory;\n\
return function {type_name}_Factory(__ngFactoryType__) {{\n\
return (\u{0275}{type_name}_BaseFactory || (\u{0275}{type_name}_BaseFactory = {ns}.\u{0275}\u{0275}getInheritedFactory({type_name})))(__ngFactoryType__ || {type_name});\n\
}};\n\
}})()"
))
} else {
let deps = extract_deps_source(meta, source, ns);
if target == "Pipe" {
// Pipes use ɵɵdirectiveInject instead of ɵɵinject
let deps_pipe = deps.replace(
&format!("{ns}.\u{0275}\u{0275}inject("),
&format!("{ns}.\u{0275}\u{0275}directiveInject("),
);
Some(format!(
"function {type_name}_Factory(__ngFactoryType__) {{\n\
return new (__ngFactoryType__ || {type_name})({deps_pipe});\n\
}}"
))
} else if target == "Directive" {
let deps_dir = deps.replace(
&format!("{ns}.\u{0275}\u{0275}inject("),
&format!("{ns}.\u{0275}\u{0275}directiveInject("),
);
Some(format!(
"function {type_name}_Factory(__ngFactoryType__) {{\n\
return new (__ngFactoryType__ || {type_name})({deps_dir});\n\
}}"
))
} else {
Some(format!(
"function {type_name}_Factory(__ngFactoryType__) {{\n\
return new (__ngFactoryType__ || {type_name})({deps});\n\
}}"
))
}
}
}
/// Link ɵɵngDeclareInjectable → ɵɵdefineInjectable.
///
/// For `useClass` and `useFactory` with deps, we generate a wrapper factory that calls
/// `ɵɵinject()` inside the factory body (deferred), not in a `deps` array (eager).
/// Eager inject calls would fail with NG0203 during static class initialization.
fn link_injectable(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
let provided_in = get_property_source(meta, "providedIn", source).unwrap_or("null");
// Check for useClass, useFactory, useExisting, useValue
if let Some(use_class) = get_property_source(meta, "useClass", source) {
if has_property(meta, "deps") {
let deps = extract_deps_source(meta, source, ns);
return Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: function {type_name}_Factory() {{ return new ({use_class})({deps}); }}, providedIn: {provided_in} }})"
));
}
return Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: function {type_name}_Factory() {{ return new ({use_class})(); }}, providedIn: {provided_in} }})"
));
}
if let Some(use_factory) = get_property_source(meta, "useFactory", source) {
if has_property(meta, "deps") {
let deps = extract_deps_source(meta, source, ns);
// Wrap the user factory: call inject() inside the wrapper, pass results as args
return Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: function {type_name}_Factory() {{ return ({use_factory})({deps}); }}, providedIn: {provided_in} }})"
));
}
return Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: {use_factory}, providedIn: {provided_in} }})"
));
}
if let Some(use_existing) = get_property_source(meta, "useExisting", source) {
return Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: function {type_name}_Factory() {{ return {ns}.\u{0275}\u{0275}inject({use_existing}); }}, providedIn: {provided_in} }})"
));
}
if let Some(use_value) = get_property_source(meta, "useValue", source) {
return Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: function {type_name}_Factory() {{ return {use_value}; }}, providedIn: {provided_in} }})"
));
}
// Default: use the class factory
Some(format!(
"{ns}.\u{0275}\u{0275}defineInjectable({{ token: {type_name}, factory: {type_name}.\u{0275}fac, providedIn: {provided_in} }})"
))
}
/// Link ɵɵngDeclareInjector → ɵɵdefineInjector.
fn link_injector(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
// The injector definition uses type for consistency with other declarations
let mut parts = vec![format!("type: {type_name}")];
if let Some(providers) = get_property_source(meta, "providers", source) {
parts.push(format!("providers: {providers}"));
}
if let Some(imports) = get_property_source(meta, "imports", source) {
parts.push(format!("imports: {imports}"));
}
Some(format!("{ns}.\u{0275}\u{0275}defineInjector({{ {} }})", parts.join(", ")))
}
/// Link ɵɵngDeclareNgModule → ɵɵdefineNgModule.
fn link_ng_module(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
let mut parts = vec![format!("type: {type_name}")];
if let Some(declarations) = get_property_source(meta, "declarations", source) {
parts.push(format!("declarations: {declarations}"));
}
if let Some(imports) = get_property_source(meta, "imports", source) {
parts.push(format!("imports: {imports}"));
}
if let Some(exports) = get_property_source(meta, "exports", source) {
parts.push(format!("exports: {exports}"));
}
if let Some(bootstrap) = get_property_source(meta, "bootstrap", source) {
parts.push(format!("bootstrap: {bootstrap}"));
}
if let Some(schemas) = get_property_source(meta, "schemas", source) {
parts.push(format!("schemas: {schemas}"));
}
Some(format!("{ns}.\u{0275}\u{0275}defineNgModule({{ {} }})", parts.join(", ")))
}
/// Link ɵɵngDeclarePipe → ɵɵdefinePipe.
fn link_pipe(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
let pipe_name = get_string_property(meta, "name")?;
let pure = get_property_source(meta, "pure", source).unwrap_or("true");
let standalone = get_property_source(meta, "isStandalone", source).unwrap_or("true");
Some(format!(
"{ns}.\u{0275}\u{0275}definePipe({{ name: \"{pipe_name}\", type: {type_name}, pure: {pure}, standalone: {standalone} }})"
))
}
/// Link ɵɵngDeclareClassMetadata → ɵɵsetClassMetadata.
fn link_class_metadata(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
let decorators = get_property_source(meta, "decorators", source).unwrap_or("[]");
let ctor_params = get_property_source(meta, "ctorParameters", source);
let prop_decorators = get_property_source(meta, "propDecorators", source);
let ctor_str = ctor_params.unwrap_or("null");
let prop_str = prop_decorators.unwrap_or("null");
Some(format!(
"(() => {{ (typeof ngDevMode === \"undefined\" || ngDevMode) && {ns}.\u{0275}setClassMetadata({type_name}, {decorators}, {ctor_str}, {prop_str}); }})()"
))
}
/// Link ɵɵngDeclareClassMetadataAsync → ɵɵsetClassMetadataAsync.
fn link_class_metadata_async(
meta: &ObjectExpression<'_>,
source: &str,
ns: &str,
type_name: &str,
) -> Option<String> {
let resolver_fn = get_property_source(meta, "resolveDeferredDeps", source)?;
let decorators = get_property_source(meta, "decorators", source).unwrap_or("[]");
let ctor_params = get_property_source(meta, "ctorParameters", source);
let prop_decorators = get_property_source(meta, "propDecorators", source);
let ctor_str = ctor_params.unwrap_or("null");
let prop_str = prop_decorators.unwrap_or("null");
Some(format!(
"(() => {{ (typeof ngDevMode === \"undefined\" || ngDevMode) && {ns}.\u{0275}setClassMetadataAsync({type_name}, {resolver_fn}, () => {{ {ns}.\u{0275}setClassMetadata({type_name}, {decorators}, {ctor_str}, {prop_str}); }}); }})()"
))
}
/// Convert inputs from declaration format to definition format.
///
/// Declaration format (`ɵɵngDeclareDirective`):
/// - `propertyName: "publicName"` (simple)
/// - `propertyName: ["publicName", "classPropertyName"]` (aliased)
/// - `propertyName: { classPropertyName: "...", publicName: "...", isRequired: bool,
/// isSignal: bool, transformFunction: expr }` (Angular 16+ object format)
///
/// Definition format (`ɵɵdefineDirective`):
/// - `propertyName: "publicName"` (simple, same as declaration)
/// - `propertyName: [InputFlags, "publicName", "declaredName", transform?]` (array format)
///
/// InputFlags: None=0, SignalBased=1, HasDecoratorInputTransform=2
fn convert_inputs_to_definition_format(inputs_obj: &ObjectExpression<'_>, source: &str) -> String {
let mut entries: Vec<String> = Vec::new();
for prop in &inputs_obj.properties {
let ObjectPropertyKind::ObjectProperty(p) = prop else { continue };
let key = match &p.key {
PropertyKey::StaticIdentifier(ident) => ident.name.to_string(),
PropertyKey::StringLiteral(s) => s.value.to_string(),
_ => {
// Fallback: use source text
let span = p.span();
entries.push(source[span.start as usize..span.end as usize].to_string());
continue;
}
};
match &p.value {
// Simple string: propertyName: "publicName" → keep as is
Expression::StringLiteral(lit) => {
entries.push(format!("{key}: \"{}\"", lit.value));
}
// Array: check if it's declaration format [publicName, classPropertyName]
// and convert to definition format [InputFlags, publicName, classPropertyName]
Expression::ArrayExpression(arr) => {
if arr.elements.len() == 2 {
// Check if first element is a string (declaration format)
let first_is_string = matches!(
arr.elements.first(),
Some(ArrayExpressionElement::StringLiteral(_))
);
if first_is_string {
// Declaration format: ["publicName", "classPropertyName"]
// Convert to: [0, "publicName", "classPropertyName"]
let arr_source =
&source[arr.span.start as usize + 1..arr.span.end as usize - 1];
entries.push(format!("{key}: [0, {arr_source}]"));
} else {
// Already in definition format or unknown, keep as is
let val =
&source[p.value.span().start as usize..p.value.span().end as usize];
entries.push(format!("{key}: {val}"));
}
} else {
// 3+ elements likely already in definition format, keep as is
let val = &source[p.value.span().start as usize..p.value.span().end as usize];
entries.push(format!("{key}: {val}"));
}
}
// Object: Angular 16+ format with classPropertyName, publicName, isRequired, etc.
Expression::ObjectExpression(obj) => {
let public_name = get_string_property(obj, "publicName").unwrap_or(&key);
let declared_name = get_string_property(obj, "classPropertyName").unwrap_or(&key);
let is_signal = get_bool_property(obj, "isSignal").unwrap_or(false);
let is_required = get_bool_property(obj, "isRequired").unwrap_or(false);
// Angular emits `transformFunction: null` for signal inputs without
// transforms. Filter out "null" to avoid setting HasDecoratorInputTransform.
let transform =
get_property_source(obj, "transformFunction", source).filter(|v| *v != "null");
let mut flags = 0u32;
if is_signal {
flags |= 1; // InputFlags.SignalBased
}
if transform.is_some() {
flags |= 2; // InputFlags.HasDecoratorInputTransform
}
// isRequired is expressed via InputFlags.SignalBased for signal inputs
// and is checked separately for non-signal inputs
let _ = is_required;