-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathimport_elision.rs
More file actions
2005 lines (1787 loc) · 73.8 KB
/
import_elision.rs
File metadata and controls
2005 lines (1787 loc) · 73.8 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-compatible import elision using oxc's semantic reference tracking.
//!
//! This module uses oxc's `ReferenceFlags` to determine which imports have value references
//! vs type-only references. This is the same approach used by oxc's TypeScript transformer.
//!
//! ## How it works
//!
//! oxc's semantic analysis tracks every reference to a symbol with `ReferenceFlags`:
//! - `Type` flag: Symbol is used in a type position (type annotation, implements, etc.)
//! - `Read`/`Write` flags: Symbol is used as a value (expressions, decorator args, etc.)
//!
//! An import should be elided if ALL its references have ONLY the `Type` flag.
//!
//! ## What gets elided
//!
//! - `import type { X }` - explicit type-only imports
//! - `import { type X }` - explicit type-only specifiers
//! - Types only used in type annotations (e.g., `userId?: UserId`)
//! - Interfaces only used in `implements` clause
//! - Constructor parameter types (DI tokens are provided via namespace imports)
//! - Constructor parameter decorators (`@Inject`, `@Optional`, etc.) - Angular removes these
//! - DI tokens used only in `@Inject(TOKEN)` arguments
//!
//! ## What gets preserved
//!
//! - Decorators used at runtime (@Component, @Input, etc.)
//! - Values used in expressions (new X(), call X(), etc.)
//! - Any import with at least one value reference outside of constructor parameter context
//!
//! ## Cross-file analysis (optional)
//!
//! When the `cross_file_elision` feature is enabled, additional analysis can be performed
//! to check if imported symbols are type-only in their source files. This is useful for
//! compare tests but is not needed in production (bundlers handle this).
#[cfg(feature = "cross_file_elision")]
use std::path::Path;
use oxc_ast::ast::{
BindingIdentifier, ClassElement, Expression, ImportDeclarationSpecifier, MethodDefinitionKind,
Program, Statement, TSType,
};
use oxc_semantic::{Semantic, SemanticBuilder, SymbolFlags};
use oxc_span::Atom;
use rustc_hash::FxHashSet;
/// Angular constructor parameter decorators that are removed during compilation.
/// These decorators are downleveled to factory metadata and their imports can be elided.
///
/// Reference: packages/compiler-cli/src/ngtsc/annotations/common/src/di.ts
const PARAM_DECORATORS: &[&str] = &["Inject", "Optional", "Self", "SkipSelf", "Host", "Attribute"];
/// Analyzer for determining which imports are type-only and can be elided.
pub struct ImportElisionAnalyzer<'a> {
/// Set of import specifier local names that should be removed (type-only).
type_only_specifiers: FxHashSet<Atom<'a>>,
}
impl<'a> ImportElisionAnalyzer<'a> {
/// Analyze a program to determine which imports are type-only.
///
/// This builds a semantic model from the program and checks each import
/// specifier to see if it has any non-type references.
pub fn analyze(program: &'a Program<'a>) -> Self {
let semantic_ret = SemanticBuilder::new().build(program);
let semantic = &semantic_ret.semantic;
let mut type_only_specifiers = FxHashSet::default();
// First, collect all symbols that are used ONLY in constructor parameter decorators.
// These should be elided because Angular removes these decorators during compilation.
let ctor_param_decorator_only = Self::collect_ctor_param_decorator_only_imports(program);
// Analyze each import declaration
for stmt in &program.body {
let Statement::ImportDeclaration(import_decl) = stmt else {
continue;
};
// Skip type-only imports entirely (import type { X })
// These are already handled by TypeScript stripping
if import_decl.import_kind.is_type() {
continue;
}
let Some(specifiers) = &import_decl.specifiers else {
continue;
};
for specifier in specifiers {
match specifier {
ImportDeclarationSpecifier::ImportSpecifier(spec) => {
// Explicit type-only specifiers (import { type X }) are always elided
if spec.import_kind.is_type() {
type_only_specifiers.insert(spec.local.name.clone().into());
continue;
}
let name: Atom<'a> = spec.local.name.clone().into();
// Check if this import has only type references
if Self::is_type_only_import(&spec.local, semantic) {
type_only_specifiers.insert(name.clone());
}
// Check if this import is only used in constructor parameter decorators
else if ctor_param_decorator_only.contains(name.as_str()) {
type_only_specifiers.insert(name.clone());
}
}
ImportDeclarationSpecifier::ImportDefaultSpecifier(spec) => {
let name: Atom<'a> = spec.local.name.clone().into();
if Self::is_type_only_import(&spec.local, semantic) {
type_only_specifiers.insert(name.clone());
}
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(spec) => {
// Check if the namespace import is type-only using semantic analysis.
// e.g., `import * as moment from 'moment'` where `moment` is only
// used in type annotations like `moment.Moment`.
if Self::is_type_only_import(&spec.local, semantic) {
type_only_specifiers.insert(spec.local.name.clone().into());
}
}
}
}
}
// Post-pass: remove identifiers used as computed property keys in type annotations.
// These are value references (they compute runtime property names) even though they
// appear inside type contexts. TypeScript preserves these imports.
// Example: `[fromEmail]: Emailer[]` in a type literal uses `fromEmail` as a value.
let computed_key_idents = Self::collect_computed_property_key_idents(program);
for name in &computed_key_idents {
type_only_specifiers.remove(name);
}
Self { type_only_specifiers }
}
/// Collect identifiers used as computed property keys in type annotations.
///
/// Computed property keys like `[fromEmail]` in type literals reference runtime values,
/// even when they appear in type contexts. TypeScript considers these as value references
/// and preserves their imports.
fn collect_computed_property_key_idents(program: &'a Program<'a>) -> FxHashSet<Atom<'a>> {
let mut result = FxHashSet::default();
for stmt in &program.body {
Self::collect_computed_keys_from_statement(stmt, &mut result);
}
result
}
/// Walk a statement collecting computed property key identifiers from type annotations.
fn collect_computed_keys_from_statement(
stmt: &'a Statement<'a>,
result: &mut FxHashSet<Atom<'a>>,
) {
match stmt {
Statement::ClassDeclaration(class) => {
Self::collect_computed_keys_from_class(class, result);
}
Statement::ExportDefaultDeclaration(export) => {
if let oxc_ast::ast::ExportDefaultDeclarationKind::ClassDeclaration(class) =
&export.declaration
{
Self::collect_computed_keys_from_class(class, result);
}
}
Statement::ExportNamedDeclaration(export) => {
if let Some(oxc_ast::ast::Declaration::ClassDeclaration(class)) =
&export.declaration
{
Self::collect_computed_keys_from_class(class, result);
}
}
_ => {}
}
}
/// Walk class members collecting computed property key identifiers from type annotations.
fn collect_computed_keys_from_class(
class: &'a oxc_ast::ast::Class<'a>,
result: &mut FxHashSet<Atom<'a>>,
) {
for element in &class.body.body {
if let ClassElement::PropertyDefinition(prop) = element {
// Check the type annotation for computed property keys in type literals
if let Some(ts_type) = &prop.type_annotation {
Self::collect_computed_keys_from_ts_type(&ts_type.type_annotation, result);
}
}
}
}
/// Recursively walk a TypeScript type collecting computed property key identifiers.
fn collect_computed_keys_from_ts_type(
ts_type: &'a TSType<'a>,
result: &mut FxHashSet<Atom<'a>>,
) {
match ts_type {
TSType::TSTypeLiteral(type_lit) => {
for member in &type_lit.members {
if let oxc_ast::ast::TSSignature::TSPropertySignature(prop_sig) = member {
// Check if the property key is computed
if prop_sig.computed {
Self::collect_idents_from_expr(&prop_sig.key, result);
}
// Recurse into the property's type annotation to find
// computed keys in nested type literals
if let Some(type_ann) = &prop_sig.type_annotation {
Self::collect_computed_keys_from_ts_type(
&type_ann.type_annotation,
result,
);
}
}
}
}
TSType::TSUnionType(union_type) => {
for ty in &union_type.types {
Self::collect_computed_keys_from_ts_type(ty, result);
}
}
TSType::TSIntersectionType(intersection_type) => {
for ty in &intersection_type.types {
Self::collect_computed_keys_from_ts_type(ty, result);
}
}
TSType::TSArrayType(array_type) => {
Self::collect_computed_keys_from_ts_type(&array_type.element_type, result);
}
TSType::TSTupleType(tuple_type) => {
for element in &tuple_type.element_types {
Self::collect_computed_keys_from_ts_type(element.to_ts_type(), result);
}
}
TSType::TSTypeReference(type_ref) => {
if let Some(type_args) = &type_ref.type_arguments {
for ty in &type_args.params {
Self::collect_computed_keys_from_ts_type(ty, result);
}
}
}
TSType::TSParenthesizedType(paren_type) => {
Self::collect_computed_keys_from_ts_type(&paren_type.type_annotation, result);
}
_ => {}
}
}
/// Collect identifier names from an expression (for computed property keys).
fn collect_idents_from_expr(
expr: &'a oxc_ast::ast::PropertyKey<'a>,
result: &mut FxHashSet<Atom<'a>>,
) {
match expr {
oxc_ast::ast::PropertyKey::StaticIdentifier(_) => {
// Static identifiers are NOT computed property keys
}
oxc_ast::ast::PropertyKey::PrivateIdentifier(_) => {}
_ => {
if let Some(expr) = expr.as_expression() {
Self::collect_idents_from_expression(expr, result);
}
}
}
}
/// Collect identifier names from an expression.
fn collect_idents_from_expression(expr: &'a Expression<'a>, result: &mut FxHashSet<Atom<'a>>) {
match expr {
Expression::Identifier(id) => {
result.insert(id.name.clone().into());
}
Expression::StaticMemberExpression(member) => {
// For `RecipientType.To`, collect `RecipientType`
if let Expression::Identifier(id) = &member.object {
result.insert(id.name.clone().into());
}
}
_ => {}
}
}
/// Collect import names that are used ONLY in compiler-handled positions.
///
/// This includes:
/// 1. Constructor parameter decorators (`@Inject`, `@Optional`, etc.) - removed by Angular
/// 2. `@Inject(TOKEN)` arguments - only used in ctor param decorators
/// 3. `declare` property decorator arguments - `declare` properties are not emitted by
/// TypeScript, so their decorator arguments have no runtime value references
///
/// Reference: packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.ts
fn collect_ctor_param_decorator_only_imports(program: &'a Program<'a>) -> FxHashSet<&'a str> {
let mut result = FxHashSet::default();
// Track:
// 1. Symbols used ONLY in ctor param decorator position (the decorator itself)
// 2. Symbols used ONLY as @Inject() arguments
// 3. Symbols used ONLY in `declare` property decorator arguments
let mut ctor_param_decorator_uses: FxHashSet<&'a str> = FxHashSet::default();
let mut inject_arg_uses: FxHashSet<&'a str> = FxHashSet::default();
let mut declare_prop_decorator_uses: FxHashSet<&'a str> = FxHashSet::default();
let mut other_value_uses: FxHashSet<&'a str> = FxHashSet::default();
// Walk the AST to find constructor parameters and their decorators
for stmt in &program.body {
Self::collect_uses_from_statement(
stmt,
&mut ctor_param_decorator_uses,
&mut inject_arg_uses,
&mut declare_prop_decorator_uses,
&mut other_value_uses,
);
}
// A symbol can be elided if it appears ONLY in compiler-handled positions
// and NOT in other value positions
for name in ctor_param_decorator_uses {
if !other_value_uses.contains(name) {
result.insert(name);
}
}
for name in inject_arg_uses {
if !other_value_uses.contains(name) {
result.insert(name);
}
}
for name in declare_prop_decorator_uses {
if !other_value_uses.contains(name) {
result.insert(name);
}
}
result
}
/// Recursively collect uses from a statement.
fn collect_uses_from_statement(
stmt: &'a Statement<'a>,
ctor_param_decorator_uses: &mut FxHashSet<&'a str>,
inject_arg_uses: &mut FxHashSet<&'a str>,
declare_prop_decorator_uses: &mut FxHashSet<&'a str>,
other_value_uses: &mut FxHashSet<&'a str>,
) {
match stmt {
Statement::ClassDeclaration(class) => {
Self::collect_uses_from_class(
class,
ctor_param_decorator_uses,
inject_arg_uses,
declare_prop_decorator_uses,
other_value_uses,
);
}
Statement::ExportDefaultDeclaration(export) => {
if let oxc_ast::ast::ExportDefaultDeclarationKind::ClassDeclaration(class) =
&export.declaration
{
Self::collect_uses_from_class(
class,
ctor_param_decorator_uses,
inject_arg_uses,
declare_prop_decorator_uses,
other_value_uses,
);
}
}
Statement::ExportNamedDeclaration(export) => {
if let Some(oxc_ast::ast::Declaration::ClassDeclaration(class)) =
&export.declaration
{
Self::collect_uses_from_class(
class,
ctor_param_decorator_uses,
inject_arg_uses,
declare_prop_decorator_uses,
other_value_uses,
);
}
}
// Collect value uses from variable declarations
Statement::VariableDeclaration(var_decl) => {
for decl in &var_decl.declarations {
if let Some(init) = &decl.init {
Self::collect_value_uses_from_expr(init, other_value_uses);
}
}
}
// Collect value uses from expression statements
Statement::ExpressionStatement(expr_stmt) => {
Self::collect_value_uses_from_expr(&expr_stmt.expression, other_value_uses);
}
_ => {}
}
}
/// Collect uses from a class declaration.
fn collect_uses_from_class(
class: &'a oxc_ast::ast::Class<'a>,
ctor_param_decorator_uses: &mut FxHashSet<&'a str>,
inject_arg_uses: &mut FxHashSet<&'a str>,
declare_prop_decorator_uses: &mut FxHashSet<&'a str>,
other_value_uses: &mut FxHashSet<&'a str>,
) {
// Process class decorators - these are NOT elided (they run at runtime)
for decorator in &class.decorators {
Self::collect_value_uses_from_expr(&decorator.expression, other_value_uses);
}
// Process class members
for element in &class.body.body {
match element {
ClassElement::MethodDefinition(method) => {
// Process method decorators (e.g., @HostListener) - NOT elided
for decorator in &method.decorators {
Self::collect_value_uses_from_expr(&decorator.expression, other_value_uses);
}
if method.kind == MethodDefinitionKind::Constructor {
// This is the constructor - process parameter decorators specially
Self::collect_uses_from_constructor_params(
&method.value.params,
ctor_param_decorator_uses,
inject_arg_uses,
);
}
}
ClassElement::PropertyDefinition(prop) => {
if prop.declare {
// `declare` properties are not emitted by TypeScript, so their
// decorators and arguments have no runtime value references.
// Track them separately for elision.
for decorator in &prop.decorators {
Self::collect_value_uses_from_expr(
&decorator.expression,
declare_prop_decorator_uses,
);
}
} else {
// Process property decorators (e.g., @Input, @ViewChild) - NOT elided
for decorator in &prop.decorators {
Self::collect_value_uses_from_expr(
&decorator.expression,
other_value_uses,
);
}
}
// Process property initializers (e.g., doc = DOCUMENT)
if let Some(init) = &prop.value {
Self::collect_value_uses_from_expr(init, other_value_uses);
}
}
ClassElement::AccessorProperty(prop) => {
for decorator in &prop.decorators {
Self::collect_value_uses_from_expr(&decorator.expression, other_value_uses);
}
}
_ => {}
}
}
}
/// Collect uses from constructor parameters.
///
/// This is the key function that identifies parameter decorators and their arguments.
fn collect_uses_from_constructor_params(
params: &'a oxc_ast::ast::FormalParameters<'a>,
ctor_param_decorator_uses: &mut FxHashSet<&'a str>,
inject_arg_uses: &mut FxHashSet<&'a str>,
) {
for param in ¶ms.items {
for decorator in ¶m.decorators {
// Get the decorator name
let (decorator_name, call_args) = match &decorator.expression {
// @Optional (without call)
Expression::Identifier(id) => (Some(id.name.as_str()), None),
// @Optional() or @Inject(TOKEN)
Expression::CallExpression(call) => {
if let Expression::Identifier(id) = &call.callee {
(Some(id.name.as_str()), Some(&call.arguments))
} else {
(None, None)
}
}
_ => (None, None),
};
if let Some(name) = decorator_name {
// Check if this is a known parameter decorator
if PARAM_DECORATORS.contains(&name) {
ctor_param_decorator_uses.insert(name);
// If this is @Inject(TOKEN), collect the TOKEN argument
if name == "Inject" {
if let Some(args) = call_args {
for arg in args {
// Handle spread elements by extracting their inner expression
if let oxc_ast::ast::Argument::SpreadElement(spread) = arg {
Self::collect_inject_arg_uses(
&spread.argument,
inject_arg_uses,
);
} else if let Some(expr) = arg.as_expression() {
Self::collect_inject_arg_uses(expr, inject_arg_uses);
}
}
}
}
}
}
}
}
}
/// Collect identifier uses from an @Inject() argument.
fn collect_inject_arg_uses(expr: &'a Expression<'a>, inject_arg_uses: &mut FxHashSet<&'a str>) {
match expr {
Expression::Identifier(id) => {
inject_arg_uses.insert(id.name.as_str());
}
// Handle property access like SomeModule.TOKEN
Expression::StaticMemberExpression(member) => {
if let Expression::Identifier(id) = &member.object {
inject_arg_uses.insert(id.name.as_str());
}
}
_ => {}
}
}
/// Collect all identifier uses from an expression (for "other" non-elided uses).
fn collect_value_uses_from_expr(
expr: &'a Expression<'a>,
other_value_uses: &mut FxHashSet<&'a str>,
) {
match expr {
Expression::Identifier(id) => {
other_value_uses.insert(id.name.as_str());
}
Expression::CallExpression(call) => {
Self::collect_value_uses_from_expr(&call.callee, other_value_uses);
for arg in &call.arguments {
// Handle spread elements by extracting their inner expression
if let oxc_ast::ast::Argument::SpreadElement(spread) = arg {
Self::collect_value_uses_from_expr(&spread.argument, other_value_uses);
} else if let Some(expr) = arg.as_expression() {
Self::collect_value_uses_from_expr(expr, other_value_uses);
}
}
}
Expression::StaticMemberExpression(member) => {
Self::collect_value_uses_from_expr(&member.object, other_value_uses);
}
Expression::ComputedMemberExpression(member) => {
Self::collect_value_uses_from_expr(&member.object, other_value_uses);
Self::collect_value_uses_from_expr(&member.expression, other_value_uses);
}
Expression::ObjectExpression(obj) => {
for prop in &obj.properties {
if let oxc_ast::ast::ObjectPropertyKind::ObjectProperty(prop) = prop {
Self::collect_value_uses_from_expr(&prop.value, other_value_uses);
}
}
}
Expression::ArrayExpression(arr) => {
for elem in &arr.elements {
match elem {
oxc_ast::ast::ArrayExpressionElement::SpreadElement(spread) => {
Self::collect_value_uses_from_expr(&spread.argument, other_value_uses);
}
oxc_ast::ast::ArrayExpressionElement::Elision(_) => {}
_ => {
if let Some(expr) = elem.as_expression() {
Self::collect_value_uses_from_expr(expr, other_value_uses);
}
}
}
}
}
Expression::NewExpression(new_expr) => {
Self::collect_value_uses_from_expr(&new_expr.callee, other_value_uses);
for arg in &new_expr.arguments {
// Handle spread elements by extracting their inner expression
if let oxc_ast::ast::Argument::SpreadElement(spread) = arg {
Self::collect_value_uses_from_expr(&spread.argument, other_value_uses);
} else if let Some(expr) = arg.as_expression() {
Self::collect_value_uses_from_expr(expr, other_value_uses);
}
}
}
Expression::ArrowFunctionExpression(arrow) => {
// Arrow function bodies may contain value references, e.g.,
// `forwardRef(() => TagPickerComponent)` in Component imports.
for stmt in &arrow.body.statements {
match stmt {
Statement::ExpressionStatement(expr_stmt) => {
Self::collect_value_uses_from_expr(
&expr_stmt.expression,
other_value_uses,
);
}
Statement::ReturnStatement(ret) => {
if let Some(arg) = &ret.argument {
Self::collect_value_uses_from_expr(arg, other_value_uses);
}
}
_ => {}
}
}
}
_ => {}
}
}
/// Check if an import binding is only used in type positions.
fn is_type_only_import(id: &BindingIdentifier<'a>, semantic: &Semantic<'a>) -> bool {
let symbol_id = id.symbol_id();
// If the symbol has a value redeclaration that shadows the import, it's safe to remove
// e.g., `import T from 'mod'; const T = 1;`
let symbol_flags = semantic.scoping().symbol_flags(symbol_id);
if (symbol_flags - SymbolFlags::Import).is_value() {
return true; // Shadowed, safe to remove
}
// Check if all references to this symbol are type-only
// If ANY reference is NOT type-only, we must keep the import
let has_value_reference = semantic
.scoping()
.get_resolved_references(symbol_id)
.any(|reference| !reference.is_type());
!has_value_reference
}
/// Check if a specifier name should be elided (removed).
pub fn should_elide(&self, name: &str) -> bool {
self.type_only_specifiers.contains(name)
}
/// Get the set of type-only specifier names.
pub fn type_only_specifiers(&self) -> &FxHashSet<Atom<'a>> {
&self.type_only_specifiers
}
/// Check if the analyzer found any type-only imports.
pub fn has_type_only_imports(&self) -> bool {
!self.type_only_specifiers.is_empty()
}
/// Analyze with optional cross-file resolution.
///
/// This method extends the basic analysis with cross-file type resolution.
/// It resolves import paths to actual files and checks if the exports are
/// type-only (interfaces, type aliases) in their source files.
///
/// # Arguments
///
/// * `program` - The parsed program to analyze
/// * `file_path` - The path to the file being analyzed
/// * `cross_file_analyzer` - The cross-file analyzer instance
///
/// # Note
///
/// This is intended for compare tests only. In production, bundlers like
/// rolldown handle import elision as part of their tree-shaking process.
#[cfg(feature = "cross_file_elision")]
pub fn analyze_with_cross_file(
program: &'a Program<'a>,
file_path: &Path,
cross_file_analyzer: &mut super::cross_file_elision::CrossFileAnalyzer,
) -> Self {
let mut analyzer = Self::analyze(program);
// Enhanced analysis: check cross-file for remaining imports
for stmt in &program.body {
let Statement::ImportDeclaration(import_decl) = stmt else {
continue;
};
// Skip type-only imports (already handled)
if import_decl.import_kind.is_type() {
continue;
}
let source = import_decl.source.value.as_str();
let Some(specifiers) = &import_decl.specifiers else {
continue;
};
for specifier in specifiers {
if let ImportDeclarationSpecifier::ImportSpecifier(spec) = specifier {
// Skip explicit type-only specifiers
if spec.import_kind.is_type() {
continue;
}
let local_name = &spec.local.name;
// Skip if already marked as type-only by semantic analysis
if analyzer.type_only_specifiers.contains(local_name.as_str()) {
continue;
}
// Check cross-file: is the export type-only in the source file?
let imported_name = spec.imported.name().as_str();
if cross_file_analyzer.is_type_only_import(source, imported_name, file_path) {
analyzer.type_only_specifiers.insert(local_name.clone().into());
}
}
}
}
analyzer
}
}
/// Filter import declarations to remove type-only specifiers.
///
/// Returns a new source string with type-only import specifiers removed.
/// Entire import declarations are removed if all their specifiers are type-only,
/// or if the import has no specifiers at all (`import {} from 'module'`).
pub fn filter_imports<'a>(
source: &str,
program: &Program<'a>,
analyzer: &ImportElisionAnalyzer<'a>,
) -> String {
// Check if there are empty imports that need removal (import {} from '...')
let has_empty_imports = program.body.iter().any(|stmt| {
if let Statement::ImportDeclaration(import_decl) = stmt {
if let Some(specifiers) = &import_decl.specifiers {
return specifiers.is_empty();
}
}
false
});
if !analyzer.has_type_only_imports() && !has_empty_imports {
return source.to_string();
}
// Collect spans to remove (in reverse order for safe removal)
let mut removals: Vec<(usize, usize)> = Vec::new();
// Collect partial replacements (start, end, replacement_string)
let mut partial_replacements: Vec<(usize, usize, String)> = Vec::new();
for stmt in &program.body {
let oxc_ast::ast::Statement::ImportDeclaration(import_decl) = stmt else {
continue;
};
// Skip type-only imports (already handled by TS stripping)
if import_decl.import_kind.is_type() {
continue;
}
let Some(specifiers) = &import_decl.specifiers else {
continue;
};
// Count how many specifiers should be kept vs removed
let (kept, removed): (Vec<_>, Vec<_>) = specifiers.iter().partition(|spec| {
let name = match spec {
ImportDeclarationSpecifier::ImportSpecifier(s) => &s.local.name,
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => &s.local.name,
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => &s.local.name,
};
!analyzer.should_elide(name.as_str())
});
if removed.is_empty() && !kept.is_empty() {
// All specifiers kept and at least one exists, no changes needed
continue;
}
if kept.is_empty() {
// All specifiers removed - remove entire import declaration
let start = import_decl.span.start as usize;
let mut end = import_decl.span.end as usize;
// Also remove trailing newline
let bytes = source.as_bytes();
while end < bytes.len() && (bytes[end] == b'\n' || bytes[end] == b'\r') {
end += 1;
}
removals.push((start, end));
} else {
// Partial removal - reconstruct import with only kept specifiers
// We need to rebuild the import statement preserving the original structure
// Find default import and named specifiers among kept
let mut default_import: Option<&str> = None;
let mut named_specifiers: Vec<String> = Vec::new();
for spec in &kept {
match spec {
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
default_import = Some(s.local.name.as_str());
}
ImportDeclarationSpecifier::ImportSpecifier(s) => {
let imported_name = s.imported.name().as_str();
let local_name = s.local.name.as_str();
if imported_name == local_name {
named_specifiers.push(local_name.to_string());
} else {
named_specifiers.push(format!("{imported_name} as {local_name}"));
}
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
// Namespace import: import * as foo
named_specifiers.push(format!("* as {}", s.local.name));
}
}
}
// Build the new import statement
let source_str = import_decl.source.value.as_str();
let mut new_import = String::from("import ");
if let Some(default_name) = default_import {
new_import.push_str(default_name);
if !named_specifiers.is_empty() {
new_import.push_str(", ");
}
}
if !named_specifiers.is_empty() {
// Check if any is a namespace import
if named_specifiers.len() == 1 && named_specifiers[0].starts_with("* as ") {
new_import.push_str(&named_specifiers[0]);
} else {
new_import.push_str("{ ");
new_import.push_str(&named_specifiers.join(", "));
new_import.push_str(" }");
}
}
new_import.push_str(" from \"");
new_import.push_str(source_str);
new_import.push_str("\";");
// Replace the entire import declaration
let start = import_decl.span.start as usize;
let mut end = import_decl.span.end as usize;
// Include trailing newline in replacement
let bytes = source.as_bytes();
while end < bytes.len() && (bytes[end] == b'\n' || bytes[end] == b'\r') {
end += 1;
// Add newline to replacement
if !new_import.ends_with('\n') {
new_import.push('\n');
}
}
// Store as replacement (start, end, replacement)
// We'll handle this differently - store removals with replacement
partial_replacements.push((start, end, new_import));
}
}
// Combine full removals (replacement = empty string) with partial replacements
// and sort in reverse order for safe string manipulation
let mut all_operations: Vec<(usize, usize, String)> = Vec::new();
for (start, end) in removals {
all_operations.push((start, end, String::new()));
}
all_operations.extend(partial_replacements);
// Sort by start position in reverse order
all_operations.sort_by(|a, b| b.0.cmp(&a.0));
let mut result = source.to_string();
for (start, end, replacement) in all_operations {
result.replace_range(start..end, &replacement);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use oxc_allocator::Allocator;
use oxc_parser::Parser;
use oxc_span::SourceType;
fn analyze_source(source: &str) -> FxHashSet<String> {
let allocator = Allocator::default();
let source_type = SourceType::ts();
let parser_ret = Parser::new(&allocator, source, source_type).parse();
let analyzer = ImportElisionAnalyzer::analyze(&parser_ret.program);
analyzer.type_only_specifiers().iter().map(|a| a.to_string()).collect()
}
#[test]
fn test_type_only_interface_implements() {
let source = r#"
import { Component, OnInit, OnDestroy } from '@angular/core';
class MyComponent implements OnInit, OnDestroy {
ngOnInit() {}
ngOnDestroy() {}
}
"#;
let type_only = analyze_source(source);
// OnInit and OnDestroy are only used in implements clause (type position)
assert!(type_only.contains("OnInit"));
assert!(type_only.contains("OnDestroy"));
// Component is not used at all, so it's also type-only
assert!(type_only.contains("Component"));
}
#[test]
fn test_value_usage_in_decorator() {
let source = r#"
import { Component, Input } from '@angular/core';
@Component({ selector: 'app-test' })
class MyComponent {
@Input() value: string;
}
"#;
let type_only = analyze_source(source);
// Component and Input are used in decorators (value position)
assert!(!type_only.contains("Component"));
assert!(!type_only.contains("Input"));
}
#[test]
fn test_type_annotation_only() {
let source = r#"
import { UserId } from './types';
function processUser(id: UserId): void {}
"#;
let type_only = analyze_source(source);
// UserId is only used in type annotation
assert!(type_only.contains("UserId"));
}
#[test]
fn test_value_usage_in_expression() {
let source = r#"
import { AuthService } from './auth.service';
const service = new AuthService();
"#;
let type_only = analyze_source(source);
// AuthService is used in a new expression (value position)
assert!(!type_only.contains("AuthService"));
}
fn filter_source(source: &str) -> String {
let allocator = Allocator::default();
let source_type = SourceType::ts();
let parser_ret = Parser::new(&allocator, source, source_type).parse();
let analyzer = ImportElisionAnalyzer::analyze(&parser_ret.program);
filter_imports(source, &parser_ret.program, &analyzer)
}
#[test]
fn test_filter_partial_multiline_import() {
let source = r#"import {
ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
} from "@angular/core";
@Component({ selector: 'test' })
class MyComponent implements OnInit, OnDestroy {
constructor(private cdr: ChangeDetectorRef) {}
ngOnInit() {}
ngOnDestroy() {}
}
"#;
let filtered = filter_source(source);
println!("=== FILTERED OUTPUT ===");
println!("{}", filtered);
println!("=== END ===");
// Extract just the import line
let import_line = filtered.lines().find(|l| l.starts_with("import")).unwrap();
println!("Import line: {}", import_line);
// Should keep Component (used as decorator)
// Should remove ChangeDetectorRef, OnInit, OnDestroy (all type-only)
// Constructor parameter types ARE type-only - Angular generates namespace imports for DI
assert!(import_line.contains("Component"));
assert!(!import_line.contains("ChangeDetectorRef"));
assert!(!import_line.contains("OnInit"));
assert!(!import_line.contains("OnDestroy"));