oxc_semantic 0.129.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
use std::borrow::Cow;

use itertools::Itertools;
use rustc_hash::FxHashMap;

use oxc_ast::{AstKind, ast::*};
use oxc_ecmascript::BoundNames;
use oxc_span::{GetSpan, Span};
use oxc_str::Str;

use crate::{builder::SemanticBuilder, diagnostics};

pub fn check_ts_type_parameter<'a>(param: &TSTypeParameter<'a>, ctx: &SemanticBuilder<'a>) {
    check_type_name_is_reserved(&param.name, ctx, "Type parameter");
    if param.r#in || param.out {
        let is_allowed_node = matches!(
            // skip parent TSTypeParameterDeclaration
            ctx.nodes.ancestor_kinds(ctx.current_node_id).nth(1),
            Some(
                AstKind::TSInterfaceDeclaration(_)
                    | AstKind::Class(_)
                    | AstKind::TSTypeAliasDeclaration(_)
            )
        );
        if !is_allowed_node {
            if param.r#in {
                ctx.error(diagnostics::can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias(
                    "in", param.span,
                ));
            }
            if param.out {
                ctx.error(diagnostics::can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias(
                    "out", param.span,
                ));
            }
        }
    }
}

pub fn check_ts_type_annotation(annotation: &TSTypeAnnotation<'_>, ctx: &SemanticBuilder<'_>) {
    let (modifier, is_start, span_with_illegal_modifier) = match &annotation.type_annotation {
        TSType::JSDocNonNullableType(ty) => ('!', !ty.postfix, ty.span()),
        TSType::JSDocNullableType(ty) => ('?', !ty.postfix, ty.span()),
        _ => {
            return;
        }
    };

    let valid_type_span = if is_start {
        span_with_illegal_modifier.shrink_left(1)
    } else {
        span_with_illegal_modifier.shrink_right(1)
    };

    let suggestion = &ctx.source_text[valid_type_span];
    let suggestion = if modifier == '?' {
        Cow::Owned(format!("{suggestion} | null | undefined"))
    } else {
        Cow::Borrowed(suggestion)
    };

    ctx.error(diagnostics::jsdoc_type_in_annotation(
        modifier,
        is_start,
        span_with_illegal_modifier,
        &suggestion,
    ));
}

pub fn check_ts_type_alias_declaration<'a>(
    decl: &TSTypeAliasDeclaration<'a>,
    ctx: &SemanticBuilder<'a>,
) {
    check_type_name_is_reserved(&decl.id, ctx, "Type alias");
}

pub fn check_ts_infer_type<'a>(infer_type: &TSInferType<'a>, ctx: &SemanticBuilder<'a>) {
    let is_in_conditional_extends_clause =
        ctx.nodes.ancestor_kinds(ctx.current_node_id).any(|kind| {
            kind.as_ts_conditional_type().is_some_and(|conditional| {
                conditional.extends_type.span().contains_inclusive(infer_type.span)
            })
        });

    if !is_in_conditional_extends_clause {
        ctx.error(diagnostics::infer_declaration_only_permitted_in_extends_clause(infer_type.span));
    }
}

pub fn check_formal_parameters(params: &FormalParameters, ctx: &SemanticBuilder<'_>) {
    if params.kind == FormalParameterKind::Signature && params.items.len() > 1 {
        check_duplicate_bound_names(params, ctx);
    }

    let mut has_optional = false;

    for param in &params.items {
        // function a(optional?: number, required: number) { }
        if param.optional {
            has_optional = true;
        } else if has_optional && param.initializer.is_none() {
            ctx.error(diagnostics::required_parameter_after_optional_parameter(param.span));
        }
    }
}

fn check_duplicate_bound_names<'a, T: BoundNames<'a>>(bound_names: &T, ctx: &SemanticBuilder<'_>) {
    let mut idents: FxHashMap<Str<'a>, Span> = FxHashMap::default();
    bound_names.bound_names(&mut |ident| {
        if let Some(old_span) = idents.insert(ident.name.into(), ident.span) {
            ctx.error(diagnostics::redeclaration(&ident.name, old_span, ident.span));
        }
    });
}

pub fn check_ts_module_declaration<'a>(decl: &TSModuleDeclaration<'a>, ctx: &SemanticBuilder<'a>) {
    check_ts_module_or_global_declaration(decl.span, ctx);
    check_ts_export_assignment_in_module_decl(decl, ctx);
}

pub fn check_ts_global_declaration<'a>(decl: &TSGlobalDeclaration<'a>, ctx: &SemanticBuilder<'a>) {
    check_ts_module_or_global_declaration(decl.span, ctx);

    if !decl.declare && !ctx.in_declare_scope() {
        ctx.error(diagnostics::global_scope_augmentation_should_have_declare_modifier(
            decl.global_span,
        ));
    }
}

fn check_ts_module_or_global_declaration(span: Span, ctx: &SemanticBuilder<'_>) {
    // skip current node
    for node in ctx.nodes.ancestors(ctx.current_node_id) {
        match node.kind() {
            AstKind::Program(_)
            | AstKind::TSModuleBlock(_)
            | AstKind::TSModuleDeclaration(_)
            | AstKind::TSGlobalDeclaration(_) => {
                break;
            }
            m if m.is_module_declaration() => {
                // We need to check the parent of the parent
            }
            _ => {
                ctx.error(diagnostics::not_allowed_namespace_declaration(span));
            }
        }
    }
}

pub fn check_ts_enum_declaration<'a>(decl: &TSEnumDeclaration<'a>, ctx: &SemanticBuilder<'a>) {
    let mut need_initializer = false;

    decl.body.members.iter().for_each(|member| {
        #[expect(clippy::unnested_or_patterns)]
        if let Some(initializer) = &member.initializer {
            need_initializer = !matches!(
                initializer.without_parentheses(),
                // A = 1
                Expression::NumericLiteral(_)
                    // B = A
                    | Expression::Identifier(_)
                    // C = E.D
                    | match_member_expression!(Expression)
                    // D = 1 + 2
                    | Expression::BinaryExpression(_)
                    // E = -1
                    | Expression::UnaryExpression(_)
            );
        } else if need_initializer {
            ctx.error(diagnostics::enum_member_must_have_initializer(member.span));
        }
    });

    check_type_name_is_reserved(&decl.id, ctx, "Enum");
}

pub fn check_ts_import_equals_declaration<'a>(
    decl: &TSImportEqualsDeclaration<'a>,
    ctx: &SemanticBuilder<'a>,
) {
    // `import type Foo = require('./foo')` is allowed
    // `import { Foo } from './foo'; import type Bar = Foo.Bar` is not allowed
    if decl.import_kind.is_type() && !decl.module_reference.is_external() {
        ctx.error(diagnostics::import_alias_cannot_use_import_type(decl.span));
    }
}

pub fn check_class<'a>(class: &Class<'a>, ctx: &SemanticBuilder<'a>) {
    if !class.r#abstract {
        for elem in &class.body.body {
            if elem.is_abstract() {
                let span = elem.property_key().map_or_else(|| elem.span(), GetSpan::span);
                ctx.error(diagnostics::abstract_elem_in_concrete_class(elem.is_property(), span));
            }
        }
    }

    if !class.r#declare && !ctx.in_declare_scope() {
        let mut is_in_overload_group = false;
        for (a, b) in class.body.body.iter().map(Some).chain(vec![None]).tuple_windows() {
            if let Some(ClassElement::MethodDefinition(a)) = a
                && !a.r#type.is_abstract()
                && !a.optional
                && a.value.r#type == FunctionType::TSEmptyBodyFunctionExpression
            {
                let next_is_same = b.is_some_and(|b| {
                    matches!(b,
                        ClassElement::MethodDefinition(b)
                            if b.key.static_name() == a.key.static_name()
                    )
                });
                if next_is_same {
                    is_in_overload_group = true;
                } else if a.key.static_name().is_some() || is_in_overload_group {
                    // Report error for:
                    // 1. Methods with static names that are not followed by an implementation
                    // 2. The last overload in a computed-name overload group (e.g. [Symbol.iterator])
                    if a.kind.is_constructor() {
                        ctx.error(diagnostics::constructor_implementation_missing(a.key.span()));
                    } else {
                        ctx.error(diagnostics::function_implementation_missing(a.key.span()));
                    }
                    is_in_overload_group = false;
                } else {
                    is_in_overload_group = false;
                }
            } else {
                is_in_overload_group = false;
            }
        }
    }
    if let Some(id) = &class.id {
        check_type_name_is_reserved(id, ctx, "Class");
    }
}

pub fn check_ts_interface_declaration<'a>(
    decl: &TSInterfaceDeclaration<'a>,
    ctx: &SemanticBuilder<'a>,
) {
    check_type_name_is_reserved(&decl.id, ctx, "Interface");
}

/// ```ts
/// function checkTypeNameIsReserved(name: Identifier, message: DiagnosticMessage): void {
///     // TS 1.0 spec (April 2014): 3.6.1
///     // The predefined type keywords are reserved and cannot be used as names of user defined types.
///     switch (name.escapedText) {
///         case "any":
///         case "unknown":
///         case "never":
///         case "number":
///         case "bigint":
///         case "boolean":
///         case "string":
///         case "symbol":
///         case "void":
///         case "object":
///         case "undefined":
///             error(name, message, name.escapedText as string);
///     }
/// }
/// ```
fn check_type_name_is_reserved<'a>(
    id: &BindingIdentifier<'a>,
    ctx: &SemanticBuilder<'a>,
    syntax_name: &str,
) {
    match id.name.as_str() {
        "any" | "unknown" | "never" | "number" | "bigint" | "boolean" | "string" | "symbol"
        | "void" | "object" | "undefined" => {
            ctx.error(diagnostics::reserved_type_name(id.span, id.name.as_str(), syntax_name));
        }
        _ => {}
    }
}

pub fn check_method_definition<'a>(method: &MethodDefinition<'a>, ctx: &SemanticBuilder<'a>) {
    let is_abstract = method.r#type.is_abstract();
    let is_declare = ctx.class_table_builder.current_class_id.map_or(
        ctx.source_type.is_typescript_definition(),
        |id| {
            let node_id = ctx.class_table_builder.classes.declarations[id];
            let AstKind::Class(class) = ctx.nodes.get_node(node_id).kind() else {
                #[cfg(debug_assertions)]
                panic!("current_class_id is set, but does not point to a Class node.");
                #[cfg(not(debug_assertions))]
                return ctx.source_type.is_typescript_definition();
            };
            class.declare || ctx.source_type.is_typescript_definition()
        },
    );

    if is_abstract {
        // constructors cannot be abstract, no matter what
        if method.kind.is_constructor() {
            ctx.error(diagnostics::illegal_abstract_modifier(method.key.span()));
        }
        // abstract cannot be used with private identifiers
        if method.key.is_private_identifier() {
            ctx.error(diagnostics::abstract_cannot_be_used_with_private_identifier(
                method.key.span(),
            ));
        }
    }

    let is_empty_body = method.value.r#type == FunctionType::TSEmptyBodyFunctionExpression;
    // Illegal to have `constructor(public foo);`
    if method.kind.is_constructor() && is_empty_body {
        for param in &method.value.params.items {
            if param.has_modifier() {
                ctx.error(diagnostics::parameter_property_only_in_constructor_impl(param.span));
            }
        }
    }

    // Illegal to have `get foo();` or `set foo(a)`
    if method.kind.is_accessor() && is_empty_body && !is_abstract && !is_declare {
        ctx.error(diagnostics::accessor_without_body(method.key.span()));
    }
}

pub fn check_property_definition(prop: &PropertyDefinition, ctx: &SemanticBuilder<'_>) {
    // abstract cannot be used with private identifiers
    if prop.r#type.is_abstract() && prop.key.is_private_identifier() {
        ctx.error(diagnostics::abstract_cannot_be_used_with_private_identifier(prop.key.span()));
    }
}

pub fn check_object_property(prop: &ObjectProperty, ctx: &SemanticBuilder<'_>) {
    if let Expression::FunctionExpression(func) = &prop.value
        && prop.kind.is_accessor()
        && matches!(func.r#type, FunctionType::TSEmptyBodyFunctionExpression)
    {
        ctx.error(diagnostics::accessor_without_body(prop.key.span()));
    }
}

pub fn check_for_statement_left(left: &ForStatementLeft, is_for_in: bool, ctx: &SemanticBuilder) {
    let ForStatementLeft::VariableDeclaration(decls) = left else {
        return;
    };

    for decl in &decls.declarations {
        if decl.type_annotation.is_some() {
            let span = decl.id.span();
            ctx.error(diagnostics::type_annotation_in_for_left(span, is_for_in));
        }
    }
}

pub fn check_jsx_expression_container(
    container: &JSXExpressionContainer,
    ctx: &SemanticBuilder<'_>,
) {
    if matches!(container.expression, JSXExpression::SequenceExpression(_)) {
        ctx.error(diagnostics::jsx_expressions_may_not_use_the_comma_operator(
            container.expression.span(),
        ));
    }
}

pub fn check_ts_export_assignment_in_program<'a>(program: &Program<'a>, ctx: &SemanticBuilder<'a>) {
    if !ctx.source_type.is_typescript() {
        return;
    }
    check_ts_export_assignment_in_statements(&program.body, ctx);
}

fn check_ts_export_assignment_in_module_decl<'a>(
    module_decl: &TSModuleDeclaration<'a>,
    ctx: &SemanticBuilder<'a>,
) {
    let Some(body) = &module_decl.body else {
        return;
    };
    match body {
        TSModuleDeclarationBody::TSModuleDeclaration(nested) => {
            check_ts_export_assignment_in_module_decl(nested, ctx);
        }
        TSModuleDeclarationBody::TSModuleBlock(block) => {
            check_ts_export_assignment_in_statements(&block.body, ctx);
        }
    }
}

fn check_ts_export_assignment_in_statements<'a>(
    statements: &[Statement<'a>],
    ctx: &SemanticBuilder<'a>,
) {
    let mut export_assignment_spans = vec![];
    let mut has_other_exports = false;

    for stmt in statements {
        match stmt {
            Statement::TSExportAssignment(export_assignment) => {
                export_assignment_spans.push(export_assignment.span);
            }
            Statement::ExportNamedDeclaration(export_decl) => {
                // ignore `export {}`
                if export_decl.declaration.is_none() && export_decl.specifiers.is_empty() {
                    continue;
                }
                has_other_exports = true;
            }
            Statement::ExportDefaultDeclaration(_) | Statement::ExportAllDeclaration(_) => {
                has_other_exports = true;
            }
            _ => {}
        }
    }

    if has_other_exports {
        for span in export_assignment_spans {
            ctx.error(diagnostics::ts_export_assignment_cannot_be_used_with_other_exports(span));
        }
    }
}