oxc_isolated_declarations 0.21.0

A collection of JavaScript tools written in Rust.
Documentation
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
//! DTS Transformer / Transpiler
//!
//! References:
//! * <https://devblogs.microsoft.com/typescript/announcing-typescript-5-5-rc/#isolated-declarations>
//! * <https://www.typescriptlang.org/tsconfig#isolatedDeclarations>
//! * <https://github.com/microsoft/TypeScript/blob/main/src/compiler/transformers/declarations.ts>

mod class;
mod declaration;
mod diagnostics;
mod r#enum;
mod formal_parameter_binding_pattern;
mod function;
mod inferrer;
mod literal;
mod module;
mod return_type;
mod scope;
mod types;

use std::{cell::RefCell, collections::VecDeque, mem};

use diagnostics::function_with_assigning_properties;
use oxc_allocator::Allocator;
#[allow(clippy::wildcard_imports)]
use oxc_ast::{ast::*, AstBuilder, Visit};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::{Atom, SourceType, SPAN};
use rustc_hash::FxHashSet;

use crate::scope::ScopeTree;

pub struct IsolatedDeclarationsReturn<'a> {
    pub program: Program<'a>,
    pub errors: Vec<OxcDiagnostic>,
}

pub struct IsolatedDeclarations<'a> {
    ast: AstBuilder<'a>,
    // state
    scope: ScopeTree<'a>,
    errors: RefCell<Vec<OxcDiagnostic>>,
}

impl<'a> IsolatedDeclarations<'a> {
    pub fn new(allocator: &'a Allocator) -> Self {
        Self {
            ast: AstBuilder::new(allocator),
            scope: ScopeTree::new(allocator),
            errors: RefCell::new(vec![]),
        }
    }

    /// # Errors
    ///
    /// Returns `Vec<Error>` if any errors were collected during the transformation.
    pub fn build(mut self, program: &Program<'a>) -> IsolatedDeclarationsReturn<'a> {
        let source_type = SourceType::default().with_module(true).with_typescript_definition(true);
        let directives = self.ast.vec();
        let stmts = self.transform_program(program);
        let program = self.ast.program(SPAN, source_type, directives, None, stmts);
        IsolatedDeclarationsReturn { program, errors: self.take_errors() }
    }

    fn take_errors(&self) -> Vec<OxcDiagnostic> {
        mem::take(&mut self.errors.borrow_mut())
    }

    /// Add an Error
    fn error(&self, error: OxcDiagnostic) {
        self.errors.borrow_mut().push(error);
    }
}

impl<'a> IsolatedDeclarations<'a> {
    pub fn transform_program(
        &mut self,
        program: &Program<'a>,
    ) -> oxc_allocator::Vec<'a, Statement<'a>> {
        let has_import_or_export = program.body.iter().any(|stmt| {
            matches!(
                stmt,
                Statement::ImportDeclaration(_)
                    | Statement::ExportAllDeclaration(_)
                    | Statement::ExportDefaultDeclaration(_)
                    | Statement::ExportNamedDeclaration(_)
            )
        });

        if has_import_or_export {
            self.transform_statements_on_demand(&program.body)
        } else {
            self.transform_program_without_module_declaration(&program.body)
        }
    }

    pub fn transform_program_without_module_declaration(
        &mut self,
        stmts: &oxc_allocator::Vec<'a, Statement<'a>>,
    ) -> oxc_allocator::Vec<'a, Statement<'a>> {
        let mut new_ast_stmts = self.ast.vec::<Statement<'a>>();
        for stmt in Self::remove_function_overloads_implementation(self.ast.copy(stmts)) {
            if let Some(decl) = stmt.as_declaration() {
                if let Some(decl) = self.transform_declaration(decl, false) {
                    new_ast_stmts.push(Statement::from(decl));
                } else {
                    new_ast_stmts.push(Statement::from(self.ast.copy(decl)));
                }
            }
        }
        self.report_error_for_expando_function(stmts);
        new_ast_stmts
    }

    pub fn transform_statements_on_demand(
        &mut self,
        stmts: &oxc_allocator::Vec<'a, Statement<'a>>,
    ) -> oxc_allocator::Vec<'a, Statement<'a>> {
        // https://github.com/microsoft/TypeScript/pull/58912
        let mut need_empty_export_marker = true;

        let mut new_stmts = Vec::new();
        let mut variables_declarations = VecDeque::new();
        let mut variable_transformed_indexes = VecDeque::new();
        let mut transformed_indexes = FxHashSet::default();
        // 1. Collect all declarations, module declarations
        // 2. Transform export declarations
        // 3. Collect all bindings / reference from module declarations
        // 4. Collect transformed indexes
        for stmt in Self::remove_function_overloads_implementation(self.ast.copy(stmts)) {
            match stmt {
                match_declaration!(Statement) => {
                    match stmt.to_declaration() {
                        Declaration::VariableDeclaration(decl) => {
                            variables_declarations.push_back(
                                self.ast.copy(&decl.declarations).into_iter().collect::<Vec<_>>(),
                            );
                            variable_transformed_indexes.push_back(FxHashSet::default());
                        }
                        Declaration::UsingDeclaration(decl) => {
                            variables_declarations.push_back(
                                self.ast.copy(&decl.declarations).into_iter().collect::<Vec<_>>(),
                            );
                            variable_transformed_indexes.push_back(FxHashSet::default());
                        }
                        Declaration::TSModuleDeclaration(decl) => {
                            if decl.kind.is_global() {
                                self.scope.visit_ts_module_declaration(decl);
                                transformed_indexes.insert(new_stmts.len());
                            }
                        }
                        _ => {}
                    }
                    new_stmts.push(stmt);
                }
                match_module_declaration!(Statement) => {
                    match stmt.to_module_declaration() {
                        ModuleDeclaration::ExportDefaultDeclaration(decl) => {
                            transformed_indexes.insert(new_stmts.len());
                            if let Some((var_decl, new_decl)) =
                                self.transform_export_default_declaration(decl)
                            {
                                if let Some(var_decl) = var_decl {
                                    need_empty_export_marker = false;
                                    self.scope.visit_variable_declaration(&var_decl);
                                    new_stmts.push(Statement::VariableDeclaration(
                                        self.ast.alloc(var_decl),
                                    ));
                                    transformed_indexes.insert(new_stmts.len());
                                }

                                self.scope.visit_export_default_declaration(&new_decl);
                                new_stmts.push(Statement::ExportDefaultDeclaration(
                                    self.ast.alloc(new_decl),
                                ));
                                continue;
                            }

                            need_empty_export_marker = false;
                            self.scope.visit_export_default_declaration(decl);
                        }

                        ModuleDeclaration::ExportNamedDeclaration(decl) => {
                            transformed_indexes.insert(new_stmts.len());
                            if let Some(new_decl) = self.transform_export_named_declaration(decl) {
                                self.scope.visit_declaration(
                                    new_decl.declaration.as_ref().unwrap_or_else(|| unreachable!()),
                                );

                                new_stmts.push(Statement::ExportNamedDeclaration(
                                    self.ast.alloc(new_decl),
                                ));
                                continue;
                            }
                            need_empty_export_marker = false;
                            self.scope.visit_export_named_declaration(decl);
                        }
                        ModuleDeclaration::ImportDeclaration(_) => {
                            // We must transform this in the end, because we need to know all references
                        }
                        module_declaration => {
                            transformed_indexes.insert(new_stmts.len());
                            self.scope.visit_module_declaration(module_declaration);
                        }
                    }

                    new_stmts.push(stmt);
                }
                _ => {}
            }
        }

        // 5. Transform statements until no more transformation can be done
        let last_transformed_len = transformed_indexes.len();
        let mut last_reference_len = 0;
        while last_reference_len != self.scope.references_len() {
            last_reference_len = self.scope.references_len();

            let mut variables_declarations_iter = variables_declarations.iter_mut();
            let mut variable_transformed_indexes_iter = variable_transformed_indexes.iter_mut();

            for (i, stmt) in new_stmts.iter_mut().enumerate() {
                if transformed_indexes.contains(&i) {
                    continue;
                }
                let Some(decl) = stmt.as_declaration() else { continue };

                if let Declaration::VariableDeclaration(_) | Declaration::UsingDeclaration(_) = decl
                {
                    let Some(cur_variable_declarations) = variables_declarations_iter.next() else {
                        unreachable!()
                    };
                    let Some(cur_transformed_indexes) = variable_transformed_indexes_iter.next()
                    else {
                        unreachable!()
                    };

                    for (ii, declarator) in cur_variable_declarations.iter_mut().enumerate() {
                        if cur_transformed_indexes.contains(&ii) {
                            continue;
                        }

                        if let Some(decl) = self.transform_variable_declarator(declarator, true) {
                            self.scope.visit_variable_declarator(&decl);
                            cur_transformed_indexes.insert(ii);
                            *declarator = decl;
                        }
                    }
                } else if let Some(decl) = self.transform_declaration(decl, true) {
                    self.scope.visit_declaration(&decl);
                    transformed_indexes.insert(i);
                    *stmt = Statement::from(decl);
                }
            }
        }

        // 6. Transform variable/using declarations, import statements, remove unused imports
        // 7. Return transformed statements
        let mut new_ast_stmts = self.ast.vec_with_capacity(transformed_indexes.len());
        for (index, stmt) in new_stmts.into_iter().enumerate() {
            match stmt {
                _ if transformed_indexes.contains(&index) => {
                    new_ast_stmts.push(stmt);
                }
                Statement::VariableDeclaration(decl) => {
                    let indexes =
                        variable_transformed_indexes.pop_front().unwrap_or_else(|| unreachable!());
                    let declarations =
                        variables_declarations.pop_front().unwrap_or_else(|| unreachable!());

                    if !indexes.is_empty() {
                        let variables_declaration = self
                            .transform_variable_declaration_with_new_declarations(
                                &decl,
                                self.ast.vec_from_iter(
                                    declarations
                                        .into_iter()
                                        .enumerate()
                                        .filter(|(i, _)| indexes.contains(i))
                                        .map(|(_, decl)| decl),
                                ),
                            );
                        new_ast_stmts.push(Statement::VariableDeclaration(variables_declaration));
                        transformed_indexes.insert(index);
                    }
                }
                Statement::UsingDeclaration(decl) => {
                    let indexes =
                        variable_transformed_indexes.pop_front().unwrap_or_else(|| unreachable!());
                    let declarations =
                        variables_declarations.pop_front().unwrap_or_else(|| unreachable!());

                    if !indexes.is_empty() {
                        let variable_declaration = self
                            .transform_using_declaration_with_new_declarations(
                                &decl,
                                self.ast.vec_from_iter(
                                    declarations
                                        .into_iter()
                                        .enumerate()
                                        .filter(|(i, _)| indexes.contains(i))
                                        .map(|(_, decl)| decl),
                                ),
                            );
                        new_ast_stmts.push(Statement::VariableDeclaration(variable_declaration));
                        transformed_indexes.insert(index);
                    }
                }
                Statement::ImportDeclaration(decl) => {
                    // We must transform this in the end, because we need to know all references
                    if decl.specifiers.is_none() {
                        new_ast_stmts.push(Statement::ImportDeclaration(decl));
                    } else if let Some(decl) = self.transform_import_declaration(&decl) {
                        new_ast_stmts.push(Statement::ImportDeclaration(decl));
                    }
                }
                _ => {}
            }
        }

        if !transformed_indexes.is_empty() && last_transformed_len == transformed_indexes.len() {
            need_empty_export_marker = false;
        }

        if need_empty_export_marker {
            let specifiers = self.ast.vec();
            let kind = ImportOrExportKind::Value;
            let empty_export =
                self.ast.alloc_export_named_declaration(SPAN, None, specifiers, None, kind, None);
            new_ast_stmts
                .push(Statement::from(ModuleDeclaration::ExportNamedDeclaration(empty_export)));
        }

        self.report_error_for_expando_function(stmts);
        new_ast_stmts
    }

    pub fn remove_function_overloads_implementation(
        stmts: oxc_allocator::Vec<'a, Statement<'a>>,
    ) -> impl Iterator<Item = Statement<'a>> + '_ {
        let mut last_function_name: Option<Atom<'a>> = None;
        let mut is_export_default_function_overloads = false;

        stmts.into_iter().filter_map(move |stmt| match stmt {
            Statement::FunctionDeclaration(ref func) => {
                let name = &func
                    .id
                    .as_ref()
                    .unwrap_or_else(|| {
                        unreachable!(
                            "Only export default function declaration is allowed to have no name"
                        )
                    })
                    .name;

                if func.body.is_some() {
                    if last_function_name.as_ref().is_some_and(|last_name| last_name == name) {
                        return None;
                    }
                } else {
                    last_function_name = Some(name.clone());
                }
                Some(stmt)
            }
            Statement::ExportNamedDeclaration(ref decl) => {
                if let Some(Declaration::FunctionDeclaration(ref func)) = decl.declaration {
                    let name = &func
                        .id
                        .as_ref()
                        .unwrap_or_else(|| {
                            unreachable!(
                            "Only export default function declaration is allowed to have no name"
                        )
                        })
                        .name;
                    if func.body.is_some() {
                        if last_function_name.as_ref().is_some_and(|last_name| last_name == name) {
                            return None;
                        }
                    } else {
                        last_function_name = Some(name.clone());
                    }
                    Some(stmt)
                } else {
                    Some(stmt)
                }
            }
            Statement::ExportDefaultDeclaration(ref decl) => {
                if let ExportDefaultDeclarationKind::FunctionDeclaration(ref func) =
                    decl.declaration
                {
                    if is_export_default_function_overloads && func.body.is_some() {
                        is_export_default_function_overloads = false;
                        return None;
                    }
                    is_export_default_function_overloads = true;
                    Some(stmt)
                } else {
                    is_export_default_function_overloads = false;
                    Some(stmt)
                }
            }
            _ => Some(stmt),
        })
    }

    pub fn report_error_for_expando_function(&self, stmts: &oxc_allocator::Vec<'a, Statement<'a>>) {
        let mut can_expando_function_names = FxHashSet::default();
        for stmt in stmts {
            match stmt {
                Statement::ExportNamedDeclaration(decl) => match decl.declaration.as_ref() {
                    Some(Declaration::FunctionDeclaration(func)) => {
                        if func.body.is_some() {
                            if let Some(id) = func.id.as_ref() {
                                can_expando_function_names.insert(id.name.clone());
                            }
                        }
                    }
                    Some(Declaration::VariableDeclaration(decl)) => {
                        for declarator in &decl.declarations {
                            if declarator.id.type_annotation.is_none()
                                && declarator.init.as_ref().is_some_and(Expression::is_function)
                            {
                                if let Some(name) = declarator.id.get_identifier() {
                                    can_expando_function_names.insert(name.clone());
                                }
                            }
                        }
                    }
                    _ => (),
                },
                Statement::ExportDefaultDeclaration(decl) => {
                    if let ExportDefaultDeclarationKind::FunctionDeclaration(func) =
                        &decl.declaration
                    {
                        if func.body.is_some() {
                            if let Some(id) = func.id.as_ref() {
                                can_expando_function_names.insert(id.name.clone());
                            }
                        }
                    }
                }
                Statement::FunctionDeclaration(func) => {
                    if func.body.is_some() {
                        if let Some(id) = func.id.as_ref() {
                            if self.scope.has_reference(&id.name) {
                                can_expando_function_names.insert(id.name.clone());
                            }
                        }
                    }
                }
                Statement::VariableDeclaration(decl) => {
                    for declarator in &decl.declarations {
                        if declarator.id.type_annotation.is_none()
                            && declarator.init.as_ref().is_some_and(Expression::is_function)
                        {
                            if let Some(name) = declarator.id.get_identifier() {
                                if self.scope.has_reference(&name) {
                                    can_expando_function_names.insert(name.clone());
                                }
                            }
                        }
                    }
                }
                Statement::ExpressionStatement(stmt) => {
                    if let Expression::AssignmentExpression(assignment) = &stmt.expression {
                        if let AssignmentTarget::StaticMemberExpression(static_member_expr) =
                            &assignment.left
                        {
                            if let Expression::Identifier(ident) = &static_member_expr.object {
                                if can_expando_function_names.contains(&ident.name) {
                                    self.error(function_with_assigning_properties(
                                        static_member_expr.span,
                                    ));
                                }
                            }
                        }
                    }
                }

                _ => {}
            }
        }
    }

    pub fn is_declare(&self) -> bool {
        // If we are in a module block, we don't need to add declare
        !self.scope.is_ts_module_block_flag()
    }
}