-
Notifications
You must be signed in to change notification settings - Fork 599
/
gen_js.rs
3948 lines (3821 loc) · 139 KB
/
gen_js.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
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::ast::*;
use juno_support::{convert, source_manager::SourceLoc};
use sourcemap::{RawToken, SourceMap, SourceMapBuilder};
use std::{
fmt,
io::{self, BufWriter, Write},
};
/// Whether to pretty-print the generated JS.
/// Does not do full formatting of the source, but does add indentation and
/// some extra spaces to make source more readable.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Pretty {
No,
Yes,
}
/// Generate JS for `root` and print it to `out`.
/// FIXME: This currently only returns an empty SourceMap.
pub fn generate<W: Write>(
out: W,
ctx: &mut Context,
root: &NodeRc,
pretty: Pretty,
) -> io::Result<SourceMap> {
let gc = GCLock::new(ctx);
GenJS::gen_root(out, &gc, root.node(&gc), pretty)
}
/// Associativity direction.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Assoc {
/// Left to right associativity.
Ltr,
/// Right to left associativity.
Rtl,
}
mod precedence {
use crate::ast::{BinaryExpressionOperator, LogicalExpressionOperator};
pub type Precedence = u32;
pub const ALWAYS_PAREN: Precedence = 0;
pub const SEQ: Precedence = 1;
pub const ARROW: Precedence = 2;
pub const YIELD: Precedence = 3;
pub const ASSIGN: Precedence = 4;
pub const COND: Precedence = 5;
pub const BIN_START: Precedence = 6;
pub const UNARY: Precedence = 26;
pub const POST_UPDATE: Precedence = 27;
pub const TAGGED_TEMPLATE: Precedence = 28;
pub const NEW_NO_ARGS: Precedence = 29;
pub const MEMBER: Precedence = 30;
pub const PRIMARY: Precedence = 31;
pub const TOP: Precedence = 32;
pub const UNION_TYPE: Precedence = 1;
pub const INTERSECTION_TYPE: Precedence = 2;
pub fn get_binary_precedence(op: BinaryExpressionOperator) -> Precedence {
use BinaryExpressionOperator::*;
(match op {
Exp => 12,
Mult => 11,
Mod => 11,
Div => 11,
Plus => 10,
Minus => 10,
LShift => 9,
RShift => 9,
RShift3 => 9,
Less => 8,
Greater => 8,
LessEquals => 8,
GreaterEquals => 8,
LooseEquals => 7,
LooseNotEquals => 7,
StrictEquals => 7,
StrictNotEquals => 7,
BitAnd => 6,
BitXor => 5,
BitOr => 4,
In => 8,
Instanceof => 8,
}) + BIN_START
}
pub fn get_logical_precedence(op: LogicalExpressionOperator) -> Precedence {
use LogicalExpressionOperator::*;
(match op {
And => 3,
Or => 2,
NullishCoalesce => 1,
}) + BIN_START
}
}
/// Child position for the purpose of determining whether the child needs parens.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ChildPos {
Left,
Anywhere,
Right,
}
/// Whether parens are needed around something.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum NeedParens {
/// No pathheses needed.
No,
/// Pathheses required.
Yes,
/// A space character is sufficient to distinguish.
/// Used in unary operations, e.g.
Space,
}
impl From<bool> for NeedParens {
fn from(x: bool) -> NeedParens {
if x { NeedParens::Yes } else { NeedParens::No }
}
}
/// Whether to force a space when adding a space in JS generation.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ForceSpace {
No,
Yes,
}
/// Whether to force the statements to be emitted inside a new block `{ }`.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ForceBlock {
No,
Yes,
}
/// Generator for output JS. Walks the AST to output real JS.
struct GenJS<W: Write> {
/// Where to write the generated JS.
out: BufWriter<W>,
/// Whether to pretty print the output JS.
pretty: Pretty,
/// Size of the indentation step.
/// May be configurable in the future.
indent_step: usize,
/// Current indentation level, used in pretty mode.
indent: usize,
/// Current position of the writer.
position: SourceLoc,
/// Raw token tracking the most recent node.
cur_token: Option<RawToken>,
/// Build a source map as we go along.
sourcemap: SourceMapBuilder,
/// Some(err) if an error has occurred when writing, else None.
error: Option<io::Error>,
}
/// Print to the output stream if no errors have been seen so far.
/// `$gen_js` is a mutable reference to the GenJS struct.
/// `$arg` arguments follow the format pattern used by `format!`.
/// The output must be ASCII and contain no newlines.
macro_rules! out {
($gen_js:expr, $($arg:tt)*) => {{
$gen_js.write_ascii(format_args!($($arg)*));
}}
}
/// Emit a source mapping token at this point with the given node, and call `out!()`.
/// Call this macro instead of `out!()` directly if emitting the start of an AST node.
macro_rules! out_token {
($gen_js:expr, $node:expr, $($arg:tt)*) => {{
$gen_js.add_segment($node);
out!($gen_js, $($arg)*);
}}
}
impl<W: Write> GenJS<W> {
/// Generate JS for `root` and flush the output.
/// If at any point, JS generation resulted in an error, return `Err(err)`,
/// otherwise return `Ok(())`.
fn gen_root<'gc>(
writer: W,
ctx: &'gc GCLock,
root: &'gc Node<'gc>,
pretty: Pretty,
) -> io::Result<SourceMap> {
let mut gen_js = GenJS {
out: BufWriter::new(writer),
pretty,
indent_step: 2,
indent: 0,
position: SourceLoc { line: 1, col: 1 },
cur_token: None,
// FIXME: Pass in file name here.
sourcemap: SourceMapBuilder::new(None),
error: None,
};
root.visit(ctx, &mut gen_js, None);
gen_js.force_newline();
gen_js.flush_cur_token();
match gen_js.error {
None => gen_js
.out
.flush()
.and(Ok(gen_js.sourcemap.into_sourcemap())),
Some(err) => Err(err),
}
}
/// Write to the `out` writer if we haven't seen any errors.
/// If we have seen any errors, do nothing.
/// Used via the `out!` macro.
/// The output must be ASCII and contain no newlines.
fn write_ascii(&mut self, args: fmt::Arguments<'_>) {
if self.error.is_none() {
let buf = format!("{}", args);
debug_assert!(buf.is_ascii(), "Output must be ASCII");
debug_assert!(!buf.contains('\n'), "Output must have no newlines");
if let Err(e) = self.out.write_all(buf.as_bytes()) {
self.error = Some(e);
}
self.position.col += buf.len() as u32;
}
}
/// Write a single unicode character to the `out` writer if we haven't seen any errors.
/// Character must not be a newline.
/// Use `dst` as a temporary buffer.
/// If we have seen any errors, do nothing.
fn write_char(&mut self, ch: char, dst: &mut [u8]) {
debug_assert!(ch != '\n', "Output must not contain newlines");
if self.error.is_none() {
if let Err(e) = self.out.write_all(ch.encode_utf8(dst).as_bytes()) {
self.error = Some(e);
}
self.position.col += 1;
}
}
/// Write unicode to the `out` writer if we haven't seen any errors.
/// If we have seen any errors, do nothing.
/// The output must contain no newlines.
fn write_utf8(&mut self, s: &str) {
debug_assert!(
!s.chars().any(|c| c == '\n'),
"Output must not contain newlines"
);
if self.error.is_none() {
if let Err(e) = self.out.write_all(s.as_bytes()) {
self.error = Some(e);
}
}
self.position.col += s.chars().count() as u32;
}
/// Generate the JS for each node kind.
fn gen_node<'gc>(&mut self, ctx: &'gc GCLock, node: &'gc Node<'gc>, path: Option<Path<'gc>>) {
match node {
Node::Empty(_) => {}
Node::Metadata(_) => {}
Node::Program(Program { metadata: _, body }) => {
self.visit_stmt_list(ctx, body, Path::new(node, NodeField::body));
}
Node::Module(Module { metadata: _, body }) => {
self.visit_stmt_list(ctx, body, Path::new(node, NodeField::body));
}
Node::FunctionExpression(FunctionExpression {
metadata: _,
id,
params,
body,
type_parameters,
return_type,
predicate,
generator,
is_async,
})
| Node::FunctionDeclaration(FunctionDeclaration {
metadata: _,
id,
params,
body,
type_parameters,
return_type,
predicate,
generator,
is_async,
}) => {
if *is_async {
out_token!(self, node, "async function");
} else {
out_token!(self, node, "function");
}
if *generator {
out!(self, "*");
if id.is_some() {
self.space(ForceSpace::No);
}
} else if id.is_some() {
self.space(ForceSpace::Yes);
}
if let Some(id) = id {
id.visit(ctx, self, Some(Path::new(node, NodeField::id)));
}
self.visit_func_params_body(
ctx,
params,
*type_parameters,
*return_type,
*predicate,
*body,
node,
);
}
Node::ArrowFunctionExpression(ArrowFunctionExpression {
metadata: _,
id: _,
params,
body,
type_parameters,
return_type,
predicate,
expression,
is_async,
}) => {
let mut need_sep = false;
if *is_async {
out!(self, "async");
need_sep = true;
}
if let Some(type_parameters) = type_parameters {
type_parameters.visit(
ctx,
self,
Some(Path::new(node, NodeField::type_parameters)),
);
need_sep = false;
}
// Single parameter without type info doesn't need parens.
// But only in expression mode, otherwise it is ugly.
if params.len() == 1
&& type_parameters.is_none()
&& return_type.is_none()
&& predicate.is_none()
&& node_isa!(Node::Identifier, params[0])
&& node_cast!(Node::Identifier, params[0])
.type_annotation
.is_none()
&& !node_cast!(Node::Identifier, params[0]).optional
&& (*expression || self.pretty == Pretty::No)
{
if need_sep {
out!(self, " ");
}
params[0].visit(ctx, self, Some(Path::new(node, NodeField::params)));
} else {
out!(self, "(");
for (i, param) in params.iter().enumerate() {
if i > 0 {
self.comma();
}
param.visit(ctx, self, Some(Path::new(node, NodeField::params)));
}
out!(self, ")");
}
if let Some(return_type) = return_type {
out!(self, ":");
self.space(ForceSpace::No);
self.print_child(
ctx,
Some(return_type),
Path::new(node, NodeField::return_type),
ChildPos::Anywhere,
);
}
if let Some(predicate) = predicate {
self.space(ForceSpace::Yes);
predicate.visit(ctx, self, Some(Path::new(node, NodeField::predicate)));
}
self.space(ForceSpace::No);
out!(self, "=>");
self.space(ForceSpace::No);
match &body {
Node::BlockStatement(_) => {
body.visit(ctx, self, Some(Path::new(node, NodeField::body)));
}
_ => {
self.print_child(
ctx,
Some(*body),
Path::new(node, NodeField::body),
ChildPos::Right,
);
}
}
}
Node::WhileStatement(WhileStatement {
metadata: _,
body,
test,
}) => {
out!(self, "while");
self.space(ForceSpace::No);
out!(self, "(");
test.visit(ctx, self, Some(Path::new(node, NodeField::test)));
out!(self, ")");
self.visit_stmt_or_block(
ctx,
*body,
ForceBlock::No,
Path::new(node, NodeField::body),
);
}
Node::DoWhileStatement(DoWhileStatement {
metadata: _,
body,
test,
}) => {
out!(self, "do");
let block = self.visit_stmt_or_block(
ctx,
*body,
ForceBlock::No,
Path::new(node, NodeField::body),
);
if block {
self.space(ForceSpace::No);
} else {
out!(self, ";");
self.newline();
}
out!(self, "while");
self.space(ForceSpace::No);
out!(self, "(");
test.visit(ctx, self, Some(Path::new(node, NodeField::test)));
out!(self, ")");
}
Node::ForInStatement(ForInStatement {
metadata: _,
left,
right,
body,
}) => {
out!(self, "for(");
left.visit(ctx, self, Some(Path::new(node, NodeField::left)));
out!(self, " in ");
right.visit(ctx, self, Some(Path::new(node, NodeField::right)));
out!(self, ")");
self.visit_stmt_or_block(
ctx,
*body,
ForceBlock::No,
Path::new(node, NodeField::body),
);
}
Node::ForOfStatement(ForOfStatement {
metadata: _,
left,
right,
body,
is_await,
}) => {
out!(self, "for{}(", if *is_await { " await" } else { "" });
left.visit(ctx, self, Some(Path::new(node, NodeField::left)));
out!(self, " of ");
right.visit(ctx, self, Some(Path::new(node, NodeField::right)));
out!(self, ")");
self.visit_stmt_or_block(
ctx,
*body,
ForceBlock::No,
Path::new(node, NodeField::body),
);
}
Node::ForStatement(ForStatement {
metadata: _,
init,
test,
update,
body,
}) => {
out!(self, "for(");
self.print_child(ctx, *init, Path::new(node, NodeField::init), ChildPos::Left);
out!(self, ";");
if let Some(test) = test {
self.space(ForceSpace::No);
test.visit(ctx, self, Some(Path::new(node, NodeField::test)));
}
out!(self, ";");
if let Some(update) = update {
self.space(ForceSpace::No);
update.visit(ctx, self, Some(Path::new(node, NodeField::update)));
}
out!(self, ")");
self.visit_stmt_or_block(
ctx,
*body,
ForceBlock::No,
Path::new(node, NodeField::body),
);
}
Node::DebuggerStatement(_) => {
out!(self, "debugger");
}
Node::EmptyStatement(_) => {}
Node::BlockStatement(BlockStatement { metadata: _, body }) => {
if body.is_empty() {
out!(self, "{{}}");
} else {
out!(self, "{{");
self.inc_indent();
self.newline();
self.visit_stmt_list(ctx, body, Path::new(node, NodeField::body));
self.dec_indent();
self.newline();
out!(self, "}}");
}
}
Node::BreakStatement(BreakStatement { metadata: _, label }) => {
out!(self, "break");
if let Some(label) = label {
self.space(ForceSpace::Yes);
label.visit(ctx, self, Some(Path::new(node, NodeField::label)));
}
}
Node::ContinueStatement(ContinueStatement { metadata: _, label }) => {
out!(self, "continue");
if let Some(label) = label {
self.space(ForceSpace::Yes);
label.visit(ctx, self, Some(Path::new(node, NodeField::label)));
}
}
Node::ThrowStatement(ThrowStatement {
metadata: _,
argument,
}) => {
out_token!(self, node, "throw ");
argument.visit(ctx, self, Some(Path::new(node, NodeField::argument)));
}
Node::ReturnStatement(ReturnStatement {
metadata: _,
argument,
}) => {
out_token!(self, node, "return");
if let Some(argument) = argument {
out!(self, " ");
argument.visit(ctx, self, Some(Path::new(node, NodeField::argument)));
}
}
Node::WithStatement(WithStatement {
metadata: _,
object,
body,
}) => {
out_token!(self, node, "with");
self.space(ForceSpace::No);
out!(self, "(");
object.visit(ctx, self, Some(Path::new(node, NodeField::object)));
out!(self, ")");
self.visit_stmt_or_block(
ctx,
*body,
ForceBlock::No,
Path::new(node, NodeField::body),
);
}
Node::SwitchStatement(SwitchStatement {
metadata: _,
discriminant,
cases,
}) => {
out_token!(self, node, "switch");
self.space(ForceSpace::No);
out!(self, "(");
discriminant.visit(ctx, self, Some(Path::new(node, NodeField::discriminant)));
out!(self, ")");
self.space(ForceSpace::No);
out!(self, "{{");
self.newline();
for case in cases {
case.visit(ctx, self, Some(Path::new(node, NodeField::cases)));
self.newline();
}
out!(self, "}}");
}
Node::SwitchCase(SwitchCase {
metadata: _,
test,
consequent,
}) => {
match test {
Some(test) => {
out_token!(self, node, "case ");
test.visit(ctx, self, Some(Path::new(node, NodeField::test)));
}
None => {
out_token!(self, node, "default");
}
};
out!(self, ":");
if !consequent.is_empty() {
self.inc_indent();
self.newline();
self.visit_stmt_list(ctx, consequent, Path::new(node, NodeField::consequent));
self.dec_indent();
}
}
Node::LabeledStatement(LabeledStatement {
metadata: _,
label,
body,
}) => {
label.visit(ctx, self, Some(Path::new(node, NodeField::label)));
out!(self, ":");
self.newline();
body.visit(ctx, self, Some(Path::new(node, NodeField::body)));
}
Node::ExpressionStatement(ExpressionStatement {
metadata: _,
expression,
directive: _,
}) => {
self.print_child(
ctx,
Some(*expression),
Path::new(node, NodeField::expression),
ChildPos::Anywhere,
);
}
Node::TryStatement(TryStatement {
metadata: _,
block,
handler,
finalizer,
}) => {
out_token!(self, node, "try");
self.visit_stmt_or_block(
ctx,
*block,
ForceBlock::Yes,
Path::new(node, NodeField::block),
);
if let Some(handler) = handler {
handler.visit(ctx, self, Some(Path::new(node, NodeField::handler)));
}
if let Some(finalizer) = finalizer {
out!(self, "finally");
self.space(ForceSpace::No);
self.visit_stmt_or_block(
ctx,
*finalizer,
ForceBlock::Yes,
Path::new(node, NodeField::finalizer),
);
}
}
Node::IfStatement(IfStatement {
metadata: _,
test,
consequent,
alternate,
}) => {
out_token!(self, node, "if");
self.space(ForceSpace::No);
out!(self, "(");
test.visit(ctx, self, Some(Path::new(node, NodeField::test)));
out!(self, ")");
let force_block = if alternate.is_some() && is_if_without_else(consequent) {
ForceBlock::Yes
} else {
ForceBlock::No
};
self.visit_stmt_or_block(
ctx,
*consequent,
force_block,
Path::new(node, NodeField::consequent),
);
if let Some(alternate) = alternate {
out!(self, "else");
self.space(if matches!(alternate, Node::BlockStatement(_)) {
ForceSpace::No
} else {
ForceSpace::Yes
});
self.visit_stmt_or_block(
ctx,
*alternate,
ForceBlock::No,
Path::new(node, NodeField::alternate),
);
}
}
Node::BooleanLiteral(BooleanLiteral { metadata: _, value }) => {
out_token!(self, node, "{}", if *value { "true" } else { "false" });
}
Node::NullLiteral(_) => {
out_token!(self, node, "null");
}
Node::StringLiteral(StringLiteral { metadata: _, value }) => {
out_token!(self, node, "\"");
self.print_escaped_string_literal(value, '"');
out!(self, "\"");
}
Node::NumericLiteral(NumericLiteral { metadata: _, value }) => {
out_token!(self, node, "{}", convert::number_to_string(*value));
}
Node::RegExpLiteral(RegExpLiteral {
metadata: _,
pattern,
flags,
}) => {
out_token!(self, node, "/");
// Parser doesn't handle escapes when lexing RegExp,
// so we don't need to do any manual escaping here.
self.write_utf8(ctx.str(*pattern));
out!(self, "/");
self.write_utf8(ctx.str(*flags));
}
Node::ThisExpression(_) => {
out_token!(self, node, "this");
}
Node::Super(_) => {
out_token!(self, node, "super");
}
Node::SequenceExpression(SequenceExpression {
metadata: _,
expressions,
}) => {
out!(self, "(");
for (i, expr) in expressions.iter().enumerate() {
if i > 0 {
self.comma();
}
self.print_child(
ctx,
Some(*expr),
Path::new(node, NodeField::expressions),
if i == 1 {
ChildPos::Left
} else {
ChildPos::Right
},
);
}
out!(self, ")");
}
Node::ObjectExpression(ObjectExpression {
metadata: _,
properties,
}) => {
self.visit_props(ctx, properties, Path::new(node, NodeField::properties));
}
Node::ArrayExpression(ArrayExpression {
metadata: _,
elements,
trailing_comma,
}) => {
out_token!(self, node, "[");
for (i, elem) in elements.iter().enumerate() {
if i > 0 {
self.comma();
}
if let Node::SpreadElement(_) = elem {
elem.visit(ctx, self, Some(Path::new(node, NodeField::elements)));
} else {
self.print_comma_expression(
ctx,
*elem,
Path::new(node, NodeField::elements),
);
}
}
if *trailing_comma {
self.comma();
}
out!(self, "]");
}
Node::SpreadElement(SpreadElement {
metadata: _,
argument,
}) => {
out_token!(self, node, "...");
argument.visit(ctx, self, Some(Path::new(node, NodeField::argument)));
}
Node::NewExpression(NewExpression {
metadata: _,
callee,
type_arguments,
arguments,
}) => {
out_token!(self, node, "new ");
self.print_child(
ctx,
Some(*callee),
Path::new(node, NodeField::callee),
ChildPos::Left,
);
if let Some(type_arguments) = type_arguments {
type_arguments.visit(
ctx,
self,
Some(Path::new(node, NodeField::type_arguments)),
);
}
out!(self, "(");
for (i, arg) in arguments.iter().enumerate() {
if i > 0 {
self.comma();
}
self.print_comma_expression(ctx, *arg, Path::new(node, NodeField::arguments));
}
out!(self, ")");
}
Node::YieldExpression(YieldExpression {
metadata: _,
argument,
delegate,
}) => {
out_token!(self, node, "yield");
if *delegate {
out!(self, "*");
self.space(ForceSpace::No);
} else if argument.is_some() {
out!(self, " ");
}
self.print_child(
ctx,
*argument,
Path::new(node, NodeField::argument),
ChildPos::Right,
);
}
Node::AwaitExpression(AwaitExpression {
metadata: _,
argument,
}) => {
out!(self, "await ");
self.print_child(
ctx,
Some(*argument),
Path::new(node, NodeField::argument),
ChildPos::Right,
);
}
Node::ImportExpression(ImportExpression {
metadata: _,
source,
attributes,
}) => {
out_token!(self, node, "import(");
source.visit(ctx, self, Some(Path::new(node, NodeField::source)));
if let Some(attributes) = attributes {
out!(self, ",");
self.space(ForceSpace::No);
attributes.visit(ctx, self, Some(Path::new(node, NodeField::attributes)));
}
out!(self, ")");
}
Node::CallExpression(CallExpression {
metadata: _,
callee,
type_arguments,
arguments,
}) => {
self.print_child(
ctx,
Some(*callee),
Path::new(node, NodeField::callee),
ChildPos::Left,
);
if let Some(type_arguments) = type_arguments {
type_arguments.visit(
ctx,
self,
Some(Path::new(node, NodeField::type_arguments)),
);
}
out!(self, "(");
for (i, arg) in arguments.iter().enumerate() {
if i > 0 {
self.comma();
}
self.print_child(
ctx,
Some(*arg),
Path::new(node, NodeField::arguments),
ChildPos::Anywhere,
);
}
out!(self, ")");
}
Node::OptionalCallExpression(OptionalCallExpression {
metadata: _,
callee,
type_arguments,
arguments,
optional,
}) => {
self.print_child(
ctx,
Some(*callee),
Path::new(node, NodeField::callee),
ChildPos::Left,
);
if let Some(type_arguments) = type_arguments {
type_arguments.visit(
ctx,
self,
Some(Path::new(node, NodeField::type_arguments)),
);
}
out!(self, "{}(", if *optional { "?." } else { "" });
for (i, arg) in arguments.iter().enumerate() {
if i > 0 {
self.comma();
}
self.print_child(
ctx,
Some(*arg),
Path::new(node, NodeField::arguments),
ChildPos::Anywhere,
);
}
out!(self, ")");
}
Node::AssignmentExpression(AssignmentExpression {
metadata: _,
operator,
left,
right,
}) => {
self.print_child(
ctx,
Some(*left),
Path::new(node, NodeField::left),
ChildPos::Left,
);
self.space(ForceSpace::No);
out!(self, "{}", operator.as_str());
self.space(ForceSpace::No);
self.print_child(
ctx,
Some(*right),
Path::new(node, NodeField::right),
ChildPos::Right,
);
}
Node::UnaryExpression(UnaryExpression {
metadata: _,
operator,
argument,
prefix,
}) => {
let ident = operator.as_str().chars().next().unwrap().is_alphabetic();
if *prefix {
out!(self, "{}", operator.as_str());
if ident {
out!(self, " ");
}