oxc_estree 0.157.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
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
use oxc_data_structures::code_buffer::CodeBuffer;

use super::{
    Config, ESTree, ESTreeSequenceSerializer, ESTreeSerializer, Formatter, Serializer,
    TracePathPart,
};

/// Trait for struct serializers.
pub trait StructSerializer {
    type Config: Config;
    type Formatter: Formatter;

    /// Serialize struct field.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    fn serialize_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T);

    /// Serialize struct field which is JS syntax only (not in TS AST).
    ///
    /// This method behaves differently, depending on the serializer's `Config`:
    /// * `include_ts_fields() == false`: Behaves same as `serialize_field`
    ///   i.e. the field is included in JSON.
    /// * `include_ts_fields() == true`: Do nothing.
    ///   i.e. the field is skipped.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    fn serialize_js_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T);

    /// Serialize struct field which is TypeScript syntax.
    ///
    /// This method behaves differently, depending on the serializer's `Config`:
    /// * `include_ts_fields() == true`: Behaves same as `serialize_field`
    ///   i.e. the field is included in JSON.
    /// * `include_ts_fields() == false`: Do nothing.
    ///   i.e. the field is skipped.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    fn serialize_ts_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T);

    /// Serialize `Span`.
    ///
    /// * If `serializer.ranges() == true`, outputs `start`, `end`, and `range` fields.
    /// * Otherwise, outputs only `start` and `end`.
    fn serialize_span<S: ESTreeSpan>(&mut self, span: S);

    /// Finish serializing struct.
    fn end(self);

    /// Get whether output should contain TS fields.
    fn include_ts_fields(&self) -> bool;

    /// Get whether output should contain `range` fields.
    fn ranges(&self) -> bool;
}

/// Serializer for structs.
///
/// This is returned by `ESTreeSerializer::serialize_struct`.
pub struct ESTreeStructSerializer<'s, C: Config, F: Formatter> {
    /// Serializer
    serializer: &'s mut ESTreeSerializer<C, F>,
    /// State of struct.
    /// Starts as `StructState::Empty`, transitions to `StructState::HasFields` on first field.
    state: StructState,
}

impl<'s, C: Config, F: Formatter> ESTreeStructSerializer<'s, C, F> {
    /// Create new [`ESTreeStructSerializer`].
    pub(super) fn new(mut serializer: &'s mut ESTreeSerializer<C, F>) -> Self {
        // Push item to `trace_path`. It will be replaced with a `TracePathPart::Key`
        // when serializing each field in the struct, and popped off again in `end` method.
        if serializer.config.fixes() {
            serializer.trace_path.push(TracePathPart::DUMMY);
        }

        serializer.buffer_mut().print_ascii_byte(b'{');

        Self { serializer, state: StructState::Empty }
    }
}

impl<C: Config, F: Formatter> StructSerializer for ESTreeStructSerializer<'_, C, F> {
    type Config = C;
    type Formatter = F;

    /// Serialize struct field.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    fn serialize_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T) {
        // Update last item in trace path to current key
        if self.serializer.config.fixes() {
            *self.serializer.trace_path.last_mut() = TracePathPart::Key(key);
        }

        let (buffer, formatter) = self.serializer.buffer_and_formatter_mut();
        if self.state == StructState::Empty {
            self.state = StructState::HasFields;
            formatter.before_first_element(buffer);
        } else {
            buffer.print_ascii_byte(b',');
            formatter.before_later_element(buffer);
        }

        buffer.print_strs_array(["\"", key, "\":"]);
        formatter.before_field_value(buffer);
        value.serialize(&mut *self.serializer);
    }

    /// Serialize struct field which is JS syntax only (not in TS AST).
    ///
    /// This method behaves differently, depending on the serializer's `Config`:
    /// * `include_ts_fields() == false`: Behaves same as `serialize_field`
    ///   i.e. the field is included in JSON.
    /// * `include_ts_fields() == true`: Do nothing.
    ///   i.e. the field is skipped.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    #[inline(always)]
    fn serialize_js_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T) {
        if !self.include_ts_fields() {
            self.serialize_field(key, value);
        }
    }

    /// Serialize struct field which is TypeScript syntax.
    ///
    /// This method behaves differently, depending on the serializer's `Config`:
    /// * `include_ts_fields() == true`: Behaves same as `serialize_field`
    ///   i.e. the field is included in JSON.
    /// * `include_ts_fields() == false`: Do nothing.
    ///   i.e. the field is skipped.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    #[inline(always)]
    fn serialize_ts_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T) {
        if self.include_ts_fields() {
            self.serialize_field(key, value);
        }
    }

    /// Serialize `Span`.
    ///
    /// * If `serializer.ranges() == true`, outputs `start`, `end`, and `range` fields.
    /// * Otherwise, outputs only `start` and `end`.
    fn serialize_span<S: ESTreeSpan>(&mut self, span: S) {
        let range = span.range();
        self.serialize_field("start", &range[0]);
        self.serialize_field("end", &range[1]);
        if self.serializer.ranges() {
            self.serialize_field("range", &range);
        }
    }

    /// Finish serializing struct.
    fn end(self) {
        let mut serializer = self.serializer;

        // Pop entry for this struct from `trace_path`
        if serializer.config.fixes() {
            // SAFETY: `trace_path` is pushed to in `new`, which is only way to create an `ESTreeStructSerializer`.
            // This method consumes the `ESTreeStructSerializer`, so this method can't be called more
            // times than `new`. So there must be an item to pop.
            unsafe { serializer.trace_path.pop_unchecked() };
        }

        let (buffer, formatter) = serializer.buffer_and_formatter_mut();
        if self.state == StructState::HasFields {
            formatter.after_last_element(buffer);
        }
        buffer.print_ascii_byte(b'}');
    }

    /// Get whether output should contain TS fields.
    #[inline(always)]
    fn include_ts_fields(&self) -> bool {
        self.serializer.include_ts_fields()
    }

    /// Get whether output should contain `range` fields.
    #[inline(always)]
    fn ranges(&self) -> bool {
        self.serializer.ranges()
    }
}

/// State of [`StructSerializer`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum StructState {
    Empty,
    HasFields,
}

/// Flattening struct serializer.
///
/// The only method it's legal to call on a `FlatStructSerializer` is `serialize_struct`.
///
/// # Example
/// ```rust,ignore
/// struct SomeNode {
///     // We want to flatten `Span` as if its fields were on `SomeNode`
///     span: Span,
///     whatever: u32,
/// }
///
/// struct Span {
///     start: u32,
///     end: u32,
/// }
///
/// impl ESTree for SomeNode {
///     fn serialize<S: Serializer>(&self, serializer: S) {
///         let mut state = serializer.serialize_struct();
///         self.inner.serialize(FlatStructSerializer(&mut state));
///         state.serialize_field("whatever", &self.whatever);
///         state.end();
///     }
/// }
///
/// impl ESTree for Span {
///     fn serialize<S: Serializer>(&self, serializer: S) {
///         let mut state = serializer.serialize_struct();
///         state.serialize_field("start", &self.start);
///         state.serialize_field("end", &self.end);
///         state.end();
///     }
/// }
/// ```
pub struct FlatStructSerializer<'p, P: StructSerializer>(pub &'p mut P);

impl<'p, P: StructSerializer> Serializer for FlatStructSerializer<'p, P> {
    type Formatter = P::Formatter;
    type StructSerializer = Self;
    type SequenceSerializer = ESTreeSequenceSerializer<'p, P::Config, P::Formatter>;

    /// Serialize struct.
    fn serialize_struct(self) -> Self {
        self
    }

    fn serialize_sequence(self) -> ESTreeSequenceSerializer<'p, P::Config, P::Formatter> {
        const {
            panic!("Cannot flatten a sequence into a struct");
        }
    }

    fn record_fix_path(&mut self) {
        const {
            panic!("Cannot call `record_fix_path` on a `FlatStructSerializer`");
        }
    }

    /// Get whether output should contain TS fields.
    #[inline(always)]
    fn include_ts_fields(&self) -> bool {
        self.0.include_ts_fields()
    }

    /// Get whether output should contain `range` fields.
    #[inline(always)]
    fn ranges(&self) -> bool {
        self.0.ranges()
    }

    fn buffer_mut(&mut self) -> &mut CodeBuffer {
        const {
            panic!("Cannot flatten anything but a struct into another struct");
        }
    }

    fn buffer_and_formatter_mut(&mut self) -> (&mut CodeBuffer, &mut P::Formatter) {
        const {
            panic!("Cannot flatten anything but a struct into another struct");
        }
    }
}

impl<P: StructSerializer> StructSerializer for FlatStructSerializer<'_, P> {
    type Config = P::Config;
    type Formatter = P::Formatter;

    /// Serialize struct field.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    #[inline(always)]
    fn serialize_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T) {
        // Delegate to parent `StructSerializer`
        self.0.serialize_field(key, value);
    }

    /// Serialize struct field which is JS syntax only (not in TS AST).
    ///
    /// This method behaves differently, depending on the serializer's `Config`:
    /// * `include_ts_fields() == false`: Behaves same as `serialize_field`
    ///   i.e. the field is included in JSON.
    /// * `include_ts_fields() == true`: Do nothing.
    ///   i.e. the field is skipped.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    #[inline(always)]
    fn serialize_js_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T) {
        // Delegate to parent `StructSerializer`
        self.0.serialize_js_field(key, value);
    }

    /// Serialize struct field which is TypeScript syntax.
    ///
    /// This method behaves differently, depending on the serializer's `Config`:
    /// * `include_ts_fields() == true`: Behaves same as `serialize_field`
    ///   i.e. the field is included in JSON.
    /// * `include_ts_fields() == false`: Do nothing.
    ///   i.e. the field is skipped.
    ///
    /// `key` must not contain any characters which require escaping in JSON.
    #[inline(always)]
    fn serialize_ts_field<T: ESTree + ?Sized>(&mut self, key: &'static str, value: &T) {
        // Delegate to parent `StructSerializer`
        self.0.serialize_ts_field(key, value);
    }

    /// Serialize `Span`.
    ///
    /// * If `serializer.ranges() == true`, outputs `start`, `end`, and `range` fields.
    /// * Otherwise, outputs only `start` and `end`.
    fn serialize_span<S: ESTreeSpan>(&mut self, span: S) {
        self.0.serialize_span(span);
    }

    /// Finish serializing struct.
    fn end(self) {
        // No-op - there may be more fields to be added to the struct in the parent
    }

    /// Get whether output should contain TS fields.
    #[inline(always)]
    fn include_ts_fields(&self) -> bool {
        self.0.include_ts_fields()
    }

    /// Get whether output should contain `range` fields.
    #[inline(always)]
    fn ranges(&self) -> bool {
        self.0.ranges()
    }
}

/// Trait for `Span` to implement.
///
/// This is a workaround to avoid circular dependency. `oxc_span` crate depends on `oxc_estree` crate,
/// so we can't import `Span` directly from `oxc_span` here.
pub trait ESTreeSpan: Copy {
    fn range(self) -> [u32; 2];
}

#[cfg(test)]
mod tests {
    use super::super::{CompactSerializer, FlatStructSerializer, PrettySerializer, Serializer};
    use super::*;

    #[test]
    fn serialize_struct() {
        struct Foo<'a> {
            n: f64,
            u: u32,
            bar: Bar<'a>,
            empty: Null,
            hello: Option<&'a str>,
            maybe_bar: Option<Bar<'a>>,
            maybe_not_bar: Option<Bar<'a>>,
        }

        struct Bar<'a> {
            yes: &'a str,
            no: &'a str,
        }

        struct Null;

        impl ESTree for Foo<'_> {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let mut state = serializer.serialize_struct();
                state.serialize_field("n", &self.n);
                state.serialize_field("u", &self.u);
                state.serialize_field("bar", &self.bar);
                state.serialize_field("empty", &self.empty);
                state.serialize_field("hello", &self.hello);
                state.serialize_field("maybe_bar", &self.maybe_bar);
                state.serialize_field("maybe_not_bar", &self.maybe_not_bar);
                state.end();
            }
        }

        impl ESTree for Bar<'_> {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let mut state = serializer.serialize_struct();
                state.serialize_field("yes", &self.yes);
                state.serialize_field("no", &self.no);
                state.end();
            }
        }

        impl ESTree for Null {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let state = serializer.serialize_struct();
                state.end();
            }
        }

        let foo = Foo {
            n: 123.0,
            u: 12345,
            bar: Bar { yes: "yup", no: "nope" },
            empty: Null,
            hello: Some("hi!"),
            maybe_bar: Some(Bar { yes: "hell yeah!", no: "not a chance in a million, mate" }),
            maybe_not_bar: None,
        };

        let mut serializer = CompactSerializer::default();
        foo.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(
            &s,
            r#"{"n":123,"u":12345,"bar":{"yes":"yup","no":"nope"},"empty":{},"hello":"hi!","maybe_bar":{"yes":"hell yeah!","no":"not a chance in a million, mate"},"maybe_not_bar":null}"#
        );

        let mut serializer = PrettySerializer::default();
        foo.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(
            &s,
            r#"{
  "n": 123,
  "u": 12345,
  "bar": {
    "yes": "yup",
    "no": "nope"
  },
  "empty": {},
  "hello": "hi!",
  "maybe_bar": {
    "yes": "hell yeah!",
    "no": "not a chance in a million, mate"
  },
  "maybe_not_bar": null
}"#
        );
    }

    #[test]
    fn serialize_flattened_struct() {
        struct Outer {
            outer1: &'static str,
            inner: Inner,
            outer2: &'static str,
        }

        struct Inner {
            inner1: &'static str,
            innermost: Innermost,
            inner2: &'static str,
        }

        struct Innermost {
            innermost1: &'static str,
            innermost2: &'static str,
        }

        impl ESTree for Outer {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let mut state = serializer.serialize_struct();
                state.serialize_field("outer1", &self.outer1);
                self.inner.serialize(FlatStructSerializer(&mut state));
                state.serialize_field("outer2", &self.outer2);
                state.end();
            }
        }

        impl ESTree for Inner {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let mut state = serializer.serialize_struct();
                state.serialize_field("inner1", &self.inner1);
                self.innermost.serialize(FlatStructSerializer(&mut state));
                state.serialize_field("inner2", &self.inner2);
                state.end();
            }
        }

        impl ESTree for Innermost {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let mut state = serializer.serialize_struct();
                state.serialize_field("innermost1", &self.innermost1);
                state.serialize_field("innermost2", &self.innermost2);
                state.end();
            }
        }

        let outer = Outer {
            outer1: "out1",
            inner: Inner {
                inner1: "in1",
                innermost: Innermost { innermost1: "inin1", innermost2: "inin2" },
                inner2: "in2",
            },
            outer2: "out2",
        };

        let mut serializer = CompactSerializer::default();
        outer.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(
            &s,
            r#"{"outer1":"out1","inner1":"in1","innermost1":"inin1","innermost2":"inin2","inner2":"in2","outer2":"out2"}"#
        );

        let mut serializer = PrettySerializer::default();
        outer.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(
            &s,
            r#"{
  "outer1": "out1",
  "inner1": "in1",
  "innermost1": "inin1",
  "innermost2": "inin2",
  "inner2": "in2",
  "outer2": "out2"
}"#
        );
    }

    #[test]
    fn serialize_struct_with_or_without_ts() {
        struct Foo {
            js: u32,
            ts: u32,
            js_only: u32,
            more_js: u32,
        }

        impl ESTree for Foo {
            fn serialize<S: Serializer>(&self, serializer: S) {
                let mut state = serializer.serialize_struct();
                state.serialize_field("js", &self.js);
                state.serialize_ts_field("ts", &self.ts);
                state.serialize_js_field("jsOnly", &self.js_only);
                state.serialize_field("moreJs", &self.more_js);
                state.end();
            }
        }

        let foo = Foo { js: 1, ts: 2, js_only: 3, more_js: 4 };

        let mut serializer = CompactSerializer::default();
        foo.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(&s, r#"{"js":1,"ts":2,"moreJs":4}"#);

        let mut serializer = PrettySerializer::default();
        foo.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(
            &s,
            r#"{
  "js": 1,
  "ts": 2,
  "moreJs": 4
}"#
        );

        let mut serializer = CompactSerializer::new(false, false);
        foo.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(&s, r#"{"js":1,"jsOnly":3,"moreJs":4}"#);

        let mut serializer = PrettySerializer::new(false, false);
        foo.serialize(&mut serializer);
        let s = serializer.into_string();
        assert_eq!(
            &s,
            r#"{
  "js": 1,
  "jsOnly": 3,
  "moreJs": 4
}"#
        );
    }
}