oxc_span/source_type/
mod.rs

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
// Silence erroneous warnings from Rust Analyser for `#[derive(Tsify)]`
#![allow(non_snake_case)]

mod error;

use std::{hash::Hash, path::Path};

use oxc_allocator::{Allocator, CloneIn};
use oxc_ast_macros::ast;
#[cfg(feature = "serialize")]
use {serde::Serialize, tsify::Tsify};

use crate::{cmp::ContentEq, hash::ContentHash};
pub use error::UnknownExtension;

/// Source Type for JavaScript vs TypeScript / Script vs Module / JSX
#[ast]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize, Tsify))]
#[serde(rename_all = "camelCase")]
pub struct SourceType {
    /// JavaScript or TypeScript, default JavaScript
    pub(super) language: Language,

    /// Script or Module, default Module
    pub(super) module_kind: ModuleKind,

    /// Support JSX for JavaScript and TypeScript? default without JSX
    pub(super) variant: LanguageVariant,
}

/// JavaScript or TypeScript
#[ast]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize, Tsify))]
#[serde(rename_all = "lowercase")]
pub enum Language {
    JavaScript = 0,
    TypeScript = 1,
    #[serde(rename = "typescriptDefinition")]
    TypeScriptDefinition = 2,
}

/// Script or Module
#[ast]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize, Tsify))]
#[serde(rename_all = "camelCase")]
pub enum ModuleKind {
    /// Regular JS script or CommonJS file
    Script = 0,
    /// ES6 Module
    Module = 1,
    /// Consider the file a "module" if ESM syntax is present, or else consider it a "script".
    ///
    /// ESM syntax includes `import` statement, `export` statement and `import.meta`.
    ///
    /// Note: Dynamic import expression is not ESM syntax.
    ///
    /// See <https://babel.dev/docs/options#misc-options>
    Unambiguous = 2,
}

/// JSX for JavaScript and TypeScript
#[ast]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize, Tsify))]
#[serde(rename_all = "camelCase")]
pub enum LanguageVariant {
    Standard = 0,
    Jsx = 1,
}

impl Default for SourceType {
    #[inline]
    fn default() -> Self {
        Self::mjs()
    }
}

impl<'a> CloneIn<'a> for SourceType {
    type Cloned = Self;

    #[inline]
    fn clone_in(&self, _: &'a Allocator) -> Self {
        *self
    }
}

impl ContentEq for SourceType {
    #[inline]
    fn content_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ContentHash for SourceType {
    #[inline]
    fn content_hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.hash(state);
    }
}

/// Valid file extensions
pub const VALID_EXTENSIONS: [&str; 8] = ["js", "mjs", "cjs", "jsx", "ts", "mts", "cts", "tsx"];

impl SourceType {
    /// Creates a [`SourceType`] representing a regular [`JavaScript`] file.
    ///
    /// The resulting source type is not a [`module`], nor does it support [`JSX`].
    /// Use [`SourceType::jsx`] for [`JSX`] sources.
    ///
    /// ## Example
    /// ```
    /// # use oxc_span::SourceType;
    ///
    /// let js = SourceType::cjs();
    /// assert!(js.is_javascript());
    /// assert!(js.is_script()); // not a module
    /// assert!(!js.is_jsx());
    /// ```
    ///
    /// [`JavaScript`]: Language::JavaScript
    /// [`module`]: ModuleKind::Module
    /// [`JSX`]: LanguageVariant::Jsx
    pub const fn cjs() -> Self {
        Self {
            language: Language::JavaScript,
            module_kind: ModuleKind::Script,
            variant: LanguageVariant::Standard,
        }
    }

    pub const fn mjs() -> Self {
        Self {
            language: Language::JavaScript,
            module_kind: ModuleKind::Module,
            variant: LanguageVariant::Standard,
        }
    }

    pub const fn unambiguous() -> Self {
        Self {
            language: Language::JavaScript,
            module_kind: ModuleKind::Unambiguous,
            variant: LanguageVariant::Standard,
        }
    }

    /// Creates a [`SourceType`] representing a [`JavaScript`]` file with JSX.
    ///
    /// ## Example
    /// ```
    /// # use oxc_span::SourceType;
    ///
    /// let jsx = SourceType::jsx();
    /// assert!(jsx.is_javascript());
    /// assert!(jsx.is_jsx());
    /// ```
    ///
    /// [`JavaScript`]: Language::JavaScript
    pub const fn jsx() -> Self {
        Self::mjs().with_jsx(true)
    }

    /// Creates a [`SourceType`] representing a [`TypeScript`] file.
    ///
    /// Unlike [`SourceType::cjs`], this method creates [`modules`]. Use
    /// [`SourceType::tsx`] for TypeScript files with [`JSX`] support.
    ///
    /// ## Example
    /// ```
    /// # use oxc_span::SourceType;
    ///
    /// let ts = SourceType::ts();
    /// assert!(ts.is_typescript());
    /// assert!(!ts.is_typescript_definition());
    /// assert!(ts.is_module());
    /// assert!(!ts.is_jsx());
    /// ```
    ///
    /// [`TypeScript`]: Language::TypeScript
    /// [`modules`]: ModuleKind::Module
    /// [`JSX`]: LanguageVariant::Jsx
    pub const fn ts() -> Self {
        Self {
            language: Language::TypeScript,
            module_kind: ModuleKind::Module,
            variant: LanguageVariant::Standard,
        }
    }

    /// Creates a [`SourceType`] representing a [`TypeScript`] file with [`JSX`].
    ///
    /// ## Example
    /// ```
    /// # use oxc_span::SourceType;
    ///
    /// let tsx = SourceType::tsx();
    /// assert!(tsx.is_typescript());
    /// assert!(!tsx.is_typescript_definition());
    /// assert!(tsx.is_module());
    /// assert!(tsx.is_jsx());
    /// ```
    ///
    /// [`TypeScript`]: Language::TypeScript
    /// [`JSX`]: LanguageVariant::Jsx
    pub const fn tsx() -> Self {
        Self::ts().with_jsx(true)
    }

    /// Creates a [`SourceType`] representing a [`TypeScript definition`] file.
    ///
    /// ## Example
    /// ```
    /// # use oxc_span::SourceType;
    ///
    /// let dts = SourceType::d_ts();
    /// assert!(dts.is_typescript());
    /// assert!(dts.is_typescript_definition());
    /// assert!(dts.is_module());
    /// assert!(!dts.is_jsx());
    /// ```
    pub const fn d_ts() -> Self {
        Self {
            language: Language::TypeScriptDefinition,
            module_kind: ModuleKind::Module,
            variant: LanguageVariant::Standard,
        }
    }

    pub fn is_script(self) -> bool {
        self.module_kind == ModuleKind::Script
    }

    pub fn is_module(self) -> bool {
        self.module_kind == ModuleKind::Module
    }

    pub fn is_unambiguous(self) -> bool {
        self.module_kind == ModuleKind::Unambiguous
    }

    pub fn module_kind(self) -> ModuleKind {
        self.module_kind
    }

    pub fn is_javascript(self) -> bool {
        self.language == Language::JavaScript
    }

    /// Returns `true` if this is a TypeScript file or TypeScript definition file.
    ///
    /// I.e., `true` for `.ts`, `.cts`, `.mts`, `.tsx`, and `.d.ts` files.
    pub fn is_typescript(self) -> bool {
        matches!(self.language, Language::TypeScript | Language::TypeScriptDefinition)
    }

    pub fn is_typescript_definition(self) -> bool {
        self.language == Language::TypeScriptDefinition
    }

    pub fn is_jsx(self) -> bool {
        self.variant == LanguageVariant::Jsx
    }

    pub fn is_strict(self) -> bool {
        self.is_module()
    }

    #[must_use]
    pub const fn with_script(mut self, yes: bool) -> Self {
        if yes {
            self.module_kind = ModuleKind::Script;
        }
        self
    }

    #[must_use]
    pub const fn with_module(mut self, yes: bool) -> Self {
        if yes {
            self.module_kind = ModuleKind::Module;
        } else {
            self.module_kind = ModuleKind::Script;
        }
        self
    }

    #[must_use]
    pub const fn with_unambiguous(mut self, yes: bool) -> Self {
        if yes {
            self.module_kind = ModuleKind::Unambiguous;
        }
        self
    }

    #[must_use]
    pub const fn with_javascript(mut self, yes: bool) -> Self {
        if yes {
            self.language = Language::JavaScript;
        }
        self
    }

    #[must_use]
    pub const fn with_typescript(mut self, yes: bool) -> Self {
        if yes {
            self.language = Language::TypeScript;
        }
        self
    }

    #[must_use]
    pub const fn with_typescript_definition(mut self, yes: bool) -> Self {
        if yes {
            self.language = Language::TypeScriptDefinition;
        }
        self
    }

    #[must_use]
    pub const fn with_jsx(mut self, yes: bool) -> Self {
        if yes {
            self.variant = LanguageVariant::Jsx;
        }
        self
    }

    #[must_use]
    pub const fn with_standard(mut self, yes: bool) -> Self {
        if yes {
            self.variant = LanguageVariant::Standard;
        }
        self
    }

    /// Converts a file [`Path`] to [`SourceType`].
    ///
    /// ## Examples
    /// ```
    /// # use oxc_span::SourceType;
    ///
    /// // supports .ts, .mts, .cts, .tsx, .d.ts, etc.
    /// let ts = SourceType::from_path("foo.ts").unwrap();
    /// assert!(ts.is_typescript());
    /// assert!(!ts.is_typescript_definition());
    ///
    /// // supports .js, .mjs, .cjs, .jsx
    /// let jsx = SourceType::from_path("foo.jsx").unwrap();
    /// assert!(jsx.is_javascript());
    /// assert!(jsx.is_jsx());
    /// ```
    ///
    /// ## Behavior
    /// ### JSX
    /// All JavaScript-like files are treated as JSX, since some tools (like
    /// babel) also do not make a distinction between `.js` and `.jsx`. However,
    /// for TypeScript files, only `.tsx` files are treated as JSX.
    ///
    /// Note that this behavior deviates from [`SourceType::cjs`], which produces
    /// [`scripts`].
    ///
    /// ### Modules vs. Scripts.
    /// Oxc has partial support for Node's
    /// [CommonJS](https://nodejs.org/api/modules.html#enabling) detection
    /// strategy. Any file with a `.c[tj]s` extension is treated as a [`script`].
    /// All other files are treated as [`modules`].
    ///
    /// # Errors
    /// Returns [`UnknownExtension`] if:
    ///   * there is no file name
    ///   * the file extension is not one of "js", "mjs", "cjs", "jsx", "ts",
    ///     "mts", "cts", "tsx". See [`VALID_EXTENSIONS`] for the list of valid
    ///     extensions.
    ///
    /// [`script`]: ModuleKind::Script
    /// [`scripts`]: ModuleKind::Script
    /// [`modules`]: ModuleKind::Module
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, UnknownExtension> {
        let file_name = path
            .as_ref()
            .file_name()
            .and_then(std::ffi::OsStr::to_str)
            .ok_or_else(|| UnknownExtension::new("Please provide a valid file name."))?;

        let extension = path
            .as_ref()
            .extension()
            .and_then(std::ffi::OsStr::to_str)
            .filter(|s| VALID_EXTENSIONS.contains(s))
            .ok_or_else(|| {
                let path = path.as_ref().to_string_lossy();
                UnknownExtension::new(
                    format!("Please provide a valid file extension for {path}: .js, .mjs, .jsx or .cjs for JavaScript, or .ts, .d.ts, .mts, .cts or .tsx for TypeScript"),
                )
            })?;

        let (language, module_kind) = match extension {
            "js" | "mjs" | "jsx" => (Language::JavaScript, ModuleKind::Module),
            "cjs" => (Language::JavaScript, ModuleKind::Script),
            "ts" if file_name.ends_with(".d.ts") => {
                (Language::TypeScriptDefinition, ModuleKind::Module)
            }
            "mts" if file_name.ends_with(".d.mts") => {
                (Language::TypeScriptDefinition, ModuleKind::Module)
            }
            "cts" if file_name.ends_with(".d.cts") => {
                (Language::TypeScriptDefinition, ModuleKind::Script)
            }
            "ts" | "mts" | "tsx" => (Language::TypeScript, ModuleKind::Module),
            "cts" => (Language::TypeScript, ModuleKind::Script),
            _ => {
                #[cfg(debug_assertions)]
                unreachable!();
                #[cfg(not(debug_assertions))]
                return Err(UnknownExtension(format!("Unknown extension: {}", extension).into()));
            }
        };

        let variant = match extension {
            "js" | "mjs" | "cjs" | "jsx" | "tsx" => LanguageVariant::Jsx,
            _ => LanguageVariant::Standard,
        };

        Ok(Self { language, module_kind, variant })
    }
}

#[cfg(test)]
mod tests {
    use super::SourceType;

    #[test]
    #[allow(clippy::similar_names)]
    fn test_ts_from_path() {
        let ts = SourceType::from_path("foo.ts")
            .expect("foo.ts should be a valid TypeScript file path.");
        let mts = SourceType::from_path("foo.mts")
            .expect("foo.mts should be a valid TypeScript file path.");
        let cts = SourceType::from_path("foo.cts")
            .expect("foo.cts should be a valid TypeScript file path.");
        let tsx = SourceType::from_path("foo.tsx")
            .expect("foo.tsx should be a valid TypeScript file path.");

        for ty in &[ts, mts, cts, tsx] {
            assert!(ty.is_typescript());
            assert!(!ty.is_typescript_definition());
            assert!(!ty.is_javascript());
        }

        assert_eq!(SourceType::ts(), ts);

        assert!(ts.is_module());
        assert!(mts.is_module());
        assert!(!cts.is_module());
        assert!(tsx.is_module());

        assert!(!ts.is_script());
        assert!(!mts.is_script());
        assert!(cts.is_script());
        assert!(!tsx.is_script());

        assert!(ts.is_strict());
        assert!(mts.is_strict());
        assert!(!cts.is_strict());
        assert!(tsx.is_strict());

        assert!(!ts.is_jsx());
        assert!(!mts.is_jsx());
        assert!(!cts.is_jsx());
        assert!(tsx.is_jsx());
    }

    #[test]
    #[allow(clippy::similar_names)]
    fn test_d_ts_from_path() {
        let dts = SourceType::from_path("foo.d.ts")
            .expect("foo.d.ts should be a valid TypeScript definition file path.");
        let dmts = SourceType::from_path("foo.d.mts")
            .expect("foo.d.mts should be a valid TypeScript definition file path.");
        let dcts = SourceType::from_path("foo.d.cts")
            .expect("foo.d.cts should be a valid TypeScript definition file path.");

        for ty in &[dts, dmts, dcts] {
            assert!(ty.is_typescript());
            assert!(ty.is_typescript_definition());
            assert!(!ty.is_javascript());
        }

        assert_eq!(SourceType::d_ts(), dts);

        assert!(dts.is_module());
        assert!(dmts.is_module());
        assert!(!dcts.is_module());

        assert!(!dts.is_script());
        assert!(!dmts.is_script());
        assert!(dcts.is_script());

        assert!(dts.is_strict());
        assert!(dmts.is_strict());
        assert!(!dcts.is_strict());

        assert!(!dts.is_jsx());
        assert!(!dmts.is_jsx());
        assert!(!dcts.is_jsx());
    }

    #[test]
    #[allow(clippy::similar_names)]
    fn test_js_from_path() {
        let js = SourceType::from_path("foo.js")
            .expect("foo.js should be a valid JavaScript file path.");
        let mjs = SourceType::from_path("foo.mjs")
            .expect("foo.mjs should be a valid JavaScript file path.");
        let cjs = SourceType::from_path("foo.cjs")
            .expect("foo.cjs should be a valid JavaScript file path.");
        let jsx = SourceType::from_path("foo.jsx")
            .expect("foo.jsx should be a valid JavaScript file path.");

        for ty in &[js, mjs, cjs, jsx] {
            assert!(ty.is_javascript(), "{ty:?}");
            assert!(!ty.is_typescript(), "{ty:?}");
        }

        assert_eq!(SourceType::jsx(), js);
        assert_eq!(SourceType::jsx().with_module(true), jsx);

        assert!(js.is_module());
        assert!(mjs.is_module());
        assert!(cjs.is_script());
        assert!(jsx.is_module());

        assert!(js.is_strict());
        assert!(mjs.is_strict());
        assert!(!cjs.is_strict());
        assert!(jsx.is_strict());

        assert!(js.is_jsx());
        assert!(mjs.is_jsx());
        assert!(cjs.is_jsx());
        assert!(jsx.is_jsx());
    }
}