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
//! TypeScript Definitions
//!
//! [AST Spec](https://github.com/typescript-eslint/typescript-eslint/tree/v8.9.0/packages/ast-spec)
//! [Archived TypeScript spec](https://github.com/microsoft/TypeScript/blob/3c99d50da5a579d9fa92d02664b1b66d4ff55944/doc/spec-ARCHIVED.md)
use std::fmt;
use oxc_str::Str;
use crate::ast::*;
impl<'a> TSEnumMemberName<'a> {
/// Get the name of this enum member.
/// # Panics
/// Panics if `self` is a `TemplateString` with no quasi.
pub fn static_name(&self) -> Str<'a> {
match self {
Self::Identifier(ident) => ident.name.into(),
Self::String(lit) | Self::ComputedString(lit) => lit.value,
Self::ComputedTemplateString(template) => template
.single_quasi()
.expect("`TSEnumMemberName::TemplateString` should have no substitution and at least one quasi"),
}
}
}
impl<'a> TSType<'a> {
/// Get the first identifier reference in this type.
///
/// For qualified (i.e. namespaced) types, the left-most identifier is
/// returned.
pub fn get_identifier_reference(&self) -> Option<&IdentifierReference<'a>> {
match self {
TSType::TSTypeReference(reference) => reference.type_name.get_identifier_reference(),
TSType::TSTypeQuery(query) => match &query.expr_name {
TSTypeQueryExprName::IdentifierReference(ident) => Some(ident),
_ => None,
},
_ => None,
}
}
/// Returns `true` if this type is a type reference to `const`.
pub fn is_const_type_reference(&self) -> bool {
matches!(self, TSType::TSTypeReference(reference) if reference.type_name.is_const())
}
/// Check if type maybe `undefined`
pub fn is_maybe_undefined(&self) -> bool {
match self {
TSType::TSAnyKeyword(_)
| TSType::TSUnknownKeyword(_)
| TSType::TSUndefinedKeyword(_) => true,
TSType::TSUnionType(un) => un.types.iter().any(Self::is_maybe_undefined),
_ => false,
}
}
/// Returns `true` if this is a keyword type (e.g. `number`, `any`, `string`).
#[rustfmt::skip]
pub fn is_keyword(&self) -> bool {
matches!(self, TSType::TSAnyKeyword(_) | TSType::TSBigIntKeyword(_) | TSType::TSBooleanKeyword(_)
| TSType::TSNeverKeyword(_) | TSType::TSNullKeyword(_) | TSType::TSNumberKeyword(_)
| TSType::TSObjectKeyword(_) | TSType::TSStringKeyword(_)| TSType::TSVoidKeyword(_)
| TSType::TSIntrinsicKeyword(_) | TSType::TSSymbolKeyword(_) | TSType::TSThisType(_)
| TSType::TSUndefinedKeyword(_) | TSType::TSUnknownKeyword(_)
)
}
/// Returns `true` if this is a [keyword] or literal type.
///
/// [keyword]: Self::is_keyword
pub fn is_keyword_or_literal(&self) -> bool {
self.is_keyword() || matches!(self, TSType::TSLiteralType(_))
}
}
impl<'a> TSTypeName<'a> {
/// Get the "leftmost" identifier in a dot-separated type name.
///
/// ## Example
/// ```ts
/// type Foo = Bar; // -> Bar
/// type Foo = Bar.Baz; // -> Bar
/// ```
pub fn get_identifier_reference(&self) -> Option<&IdentifierReference<'a>> {
match self {
TSTypeName::IdentifierReference(ident) => Some(ident),
TSTypeName::QualifiedName(name) => name.left.get_identifier_reference(),
TSTypeName::ThisExpression(_) => None,
}
}
/// Returns `true` if this is a reference to `const`.
pub fn is_const(&self) -> bool {
if let TSTypeName::IdentifierReference(ident) = self
&& ident.name == "const"
{
return true;
}
false
}
/// Returns `true` if this is an [`TSTypeName::IdentifierReference`].
pub fn is_identifier(&self) -> bool {
matches!(self, Self::IdentifierReference(_))
}
/// Returns `true` if this is a [qualified name](TSTypeName::QualifiedName)
/// (i.e. a dot-separated name).
pub fn is_qualified_name(&self) -> bool {
matches!(self, Self::QualifiedName(_))
}
}
impl fmt::Display for TSTypeName<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TSTypeName::IdentifierReference(ident) => ident.fmt(f),
TSTypeName::QualifiedName(qualified) => qualified.fmt(f),
TSTypeName::ThisExpression(_) => "this".fmt(f),
}
}
}
impl fmt::Display for TSQualifiedName<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.left, self.right)
}
}
impl TSType<'_> {
/// Remove nested parentheses from this type.
pub fn without_parenthesized(&self) -> &Self {
match self {
Self::TSParenthesizedType(expr) => expr.type_annotation.without_parenthesized(),
_ => self,
}
}
}
impl TSAccessibility {
/// Returns `true` for `private` accessibility modifiers.
#[inline]
pub fn is_private(self) -> bool {
matches!(self, Self::Private)
}
/// Converts this modifier into a string as it would appear in the source code.
pub fn as_str(self) -> &'static str {
match self {
Self::Public => "public",
Self::Private => "private",
Self::Protected => "protected",
}
}
}
impl From<TSAccessibility> for &'static str {
fn from(accessibility: TSAccessibility) -> Self {
accessibility.as_str()
}
}
impl fmt::Display for TSAccessibility {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl TSModuleDeclaration<'_> {
/// Returns `true` if this module's body exists and has a `"use strict"` directive.
///
/// Note that for a nested [`TSModuleDeclaration`], only returns `true` for the innermost `TSModuleDeclaration`.
/// e.g. this AST has 3 x `TSModuleDeclaration`s:
/// ```ts
/// namespace X.Y.Z {
/// "use strict";
/// }
/// ```
/// This method will only return `true` for the innermost one (`Z`).
pub fn has_use_strict_directive(&self) -> bool {
self.body.as_ref().is_some_and(TSModuleDeclarationBody::has_use_strict_directive)
}
}
impl TSModuleDeclarationKind {
/// Declaration keyword as a string, identical to how it would appear in the
/// source code.
pub fn as_str(self) -> &'static str {
match self {
Self::Module => "module",
Self::Namespace => "namespace",
}
}
}
impl<'a> TSModuleDeclarationName<'a> {
/// Returns `true` if this name is a string literal.
///
/// ## Example
/// ```ts
/// // true
/// module "*.less" {
/// const styles: { [key: string]: string };
/// export default styles;
/// }
///
/// // false
/// module bar {}
/// namespace bang {}
/// ```
pub fn is_string_literal(&self) -> bool {
matches!(self, Self::StringLiteral(_))
}
/// Get the static name of this module declaration name.
pub fn name(&self) -> Str<'a> {
match self {
Self::Identifier(ident) => ident.name.into(),
Self::StringLiteral(lit) => lit.value,
}
}
}
impl fmt::Display for TSModuleDeclarationName<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Identifier(id) => id.fmt(f),
Self::StringLiteral(lit) => lit.fmt(f),
}
}
}
impl<'a> TSModuleDeclarationBody<'a> {
/// Returns `true` if this module has a `"use strict"` directive.
///
/// Note that for a nested [`TSModuleDeclaration`], only returns `true` for the innermost [`TSModuleDeclarationBody`].
/// e.g. this AST has 3 x `TSModuleDeclarationBody`s:
/// ```ts
/// namespace X.Y.Z {
/// "use strict";
/// }
/// ```
/// This method will only return `true` for the innermost one (`Z`).
pub fn has_use_strict_directive(&self) -> bool {
matches!(self, Self::TSModuleBlock(block) if block.has_use_strict_directive())
}
/// Returns `true` if this module contains no statements.
pub fn is_empty(&self) -> bool {
match self {
TSModuleDeclarationBody::TSModuleDeclaration(declaration) => declaration.body.is_none(),
TSModuleDeclarationBody::TSModuleBlock(block) => block.body.len() == 0,
}
}
/// Get a mutable reference to `self` as a [`TSModuleBlock`]. Returns
/// [`None`] if the body is something other than a block.
pub fn as_module_block_mut(&mut self) -> Option<&mut TSModuleBlock<'a>> {
let mut body = self;
loop {
match body {
TSModuleDeclarationBody::TSModuleBlock(block) => return Some(block.as_mut()),
TSModuleDeclarationBody::TSModuleDeclaration(decl) => {
body = decl.body.as_mut()?;
}
}
}
}
}
impl TSModuleBlock<'_> {
/// Returns `true` if this module contains a `"use strict"` directive.
pub fn has_use_strict_directive(&self) -> bool {
self.directives.iter().any(Directive::is_use_strict)
}
}
impl TSModuleReference<'_> {
/// Returns `true` if this is an [`TSModuleReference::ExternalModuleReference`].
pub fn is_external(&self) -> bool {
matches!(self, Self::ExternalModuleReference(_))
}
}
impl<'a> Decorator<'a> {
/// Get the name of the decorator
/// ```ts
/// // The name of the decorator is `decorator`
/// @decorator
/// @decorator.a.b
/// @decorator(xx)
/// @decorator.a.b(xx)
/// ```
pub fn name(&self) -> Option<&'a str> {
match &self.expression {
Expression::Identifier(ident) => Some(ident.name.as_str()),
expr @ match_member_expression!(Expression) => {
expr.to_member_expression().static_property_name()
}
Expression::CallExpression(call) => {
call.callee.get_member_expr().and_then(MemberExpression::static_property_name)
}
_ => None,
}
}
}
impl ImportOrExportKind {
/// Returns `true` for "regular" imports and exports.
pub fn is_value(self) -> bool {
matches!(self, Self::Value)
}
/// Returns `true` if this is an `import type` or `export type` statement.
pub fn is_type(self) -> bool {
matches!(self, Self::Type)
}
}
impl TSTypeOperatorOperator {
/// Get the operator string as it would appear in the source code.
pub fn to_str(self) -> &'static str {
match self {
TSTypeOperatorOperator::Keyof => "keyof",
TSTypeOperatorOperator::Readonly => "readonly",
TSTypeOperatorOperator::Unique => "unique",
}
}
}