Debian Codegraph @

js/ast.go

raw
1 package js
2
3 import (
4 "bytes"
5 "fmt"
6 "io"
7 "strconv"
8 "strings"
9
10 "github.com/tdewolff/parse/v2"
11 )
12
13 var ErrInvalidJSON = fmt.Errorf("invalid JSON")
14
15 type JSONer interface {
16 JSON(io.Writer) error
17 }
18
19 // AST is the full ECMAScript abstract syntax tree.
20 type AST struct {
21 BlockStmt // module
22 }
23
24 func (ast AST) String() string {
25 var s strings.Builder
26 for i, item := range ast.BlockStmt.List {
27 if i != 0 {
28 s.WriteString(" ")
29 }
30 s.WriteString(item.String())
31 }
32 return s.String()
33 }
34
35 // JS writes JavaScript to writer.
36 func (ast AST) JS(w io.Writer) {
37 for i, item := range ast.List {
38 if i != 0 {
39 w.Write([]byte("\n"))
40 }
41 item.JS(w)
42 if _, ok := item.(*VarDecl); ok {
43 w.Write([]byte(";"))
44 }
45 }
46 }
47
48 // JSONString returns a string of JavaScript.
49 func (ast AST) JSString() string {
50 sb := strings.Builder{}
51 ast.JS(&sb)
52 return sb.String()
53 }
54
55 // JSON writes JSON to writer.
56 func (ast AST) JSON(w io.Writer) error {
57 if 1 < len(ast.List) {
58 return fmt.Errorf("%v: JS must be a single statement", ErrInvalidJSON)
59 } else if len(ast.List) == 0 {
60 return nil
61 }
62 exprStmt, ok := ast.List[0].(*ExprStmt)
63 if !ok {
64 return fmt.Errorf("%v: JS must be an expression statement", ErrInvalidJSON)
65 }
66 expr := exprStmt.Value
67 if group, ok := expr.(*GroupExpr); ok {
68 expr = group.X // allow parsing expr contained in group expr
69 }
70 if val, ok := expr.(JSONer); !ok {
71 return fmt.Errorf("%v: JS must be a valid JSON expression", ErrInvalidJSON)
72 } else {
73 return val.JSON(w)
74 }
75 return nil
76 }
77
78 // JSONString returns a string of JSON if valid.
79 func (ast AST) JSONString() (string, error) {
80 sb := strings.Builder{}
81 err := ast.JSON(&sb)
82 return sb.String(), err
83 }
84
85 ////////////////////////////////////////////////////////////////
86
87 // DeclType specifies the kind of declaration.
88 type DeclType uint16
89
90 // DeclType values.
91 const (
92 NoDecl DeclType = iota // undeclared variables
93 VariableDecl // var
94 PrivateDecl // private class field
95 FunctionDecl // function
96 ArgumentDecl // function and method arguments
97 LexicalDecl // let, const, class
98 CatchDecl // catch statement argument
99 ExprDecl // function expression name or class expression name
100 )
101
102 func (decl DeclType) String() string {
103 switch decl {
104 case NoDecl:
105 return "NoDecl"
106 case VariableDecl:
107 return "VariableDecl"
108 case PrivateDecl:
109 return "PrivateDecl"
110 case FunctionDecl:
111 return "FunctionDecl"
112 case ArgumentDecl:
113 return "ArgumentDecl"
114 case LexicalDecl:
115 return "LexicalDecl"
116 case CatchDecl:
117 return "CatchDecl"
118 case ExprDecl:
119 return "ExprDecl"
120 }
121 return "Invalid(" + strconv.Itoa(int(decl)) + ")"
122 }
123
124 // Var is a variable, where Decl is the type of declaration and can be var|function for function scoped variables, let|const|class for block scoped variables.
125 type Var struct {
126 Data []byte
127 Link *Var // is set when merging variable uses, as in: {a} {var a} where the first links to the second, only used for undeclared variables
128 Uses uint16
129 Decl DeclType
130 }
131
132 // Name returns the variable name.
133 func (v *Var) Name() []byte {
134 for v.Link != nil {
135 v = v.Link
136 }
137 return v.Data
138 }
139
140 func (v *Var) Info() string {
141 s := fmt.Sprintf("%p type=%s name='%s' uses=%d", v, v.Decl, string(v.Data), v.Uses)
142 links := 0
143 for v.Link != nil {
144 v = v.Link
145 links++
146 }
147 if 0 < links {
148 s += fmt.Sprintf(" links=%d => %p", links, v)
149 }
150 return s
151 }
152
153 func (v Var) String() string {
154 return string(v.Name())
155 }
156
157 // JS writes JavaScript to writer.
158 func (v Var) JS(w io.Writer) {
159 w.Write(v.Name())
160 }
161
162 // VarsByUses is sortable by uses in descending order.
163 type VarsByUses VarArray
164
165 func (vs VarsByUses) Len() int {
166 return len(vs)
167 }
168
169 func (vs VarsByUses) Swap(i, j int) {
170 vs[i], vs[j] = vs[j], vs[i]
171 }
172
173 func (vs VarsByUses) Less(i, j int) bool {
174 return vs[i].Uses > vs[j].Uses
175 }
176
177 ////////////////////////////////////////////////////////////////
178
179 // VarArray is a set of variables in scopes.
180 type VarArray []*Var
181
182 func (vs VarArray) String() string {
183 var s strings.Builder
184 s.WriteString("[")
185 for i, v := range vs {
186 if i != 0 {
187 s.WriteString(", ")
188 }
189 links := 0
190 for v.Link != nil {
191 v = v.Link
192 links++
193 }
194 s.WriteString(fmt.Sprintf("Var{%v %s %v %v}", v.Decl, string(v.Data), links, v.Uses))
195 }
196 return s.String() + "]"
197 }
198
199 // Scope is a function or block scope with a list of variables declared and used.
200 type Scope struct {
201 Parent, Func *Scope // Parent is nil for global scope
202 Declared VarArray // Link in Var are always nil
203 Undeclared VarArray
204 VarDecls []*VarDecl
205 NumForDecls uint16 // offset into Declared to mark variables used in for statements
206 NumFuncArgs uint16 // offset into Declared to mark variables used in function arguments
207 NumArgUses uint16 // offset into Undeclared to mark variables used in arguments
208 IsGlobalOrFunc bool
209 HasWith bool
210 }
211
212 func (s Scope) String() string {
213 return "Scope{Declared: " + s.Declared.String() + ", Undeclared: " + s.Undeclared.String() + "}"
214 }
215
216 // Declare declares a new variable.
217 func (s *Scope) Declare(decl DeclType, name []byte) (*Var, bool) {
218 // refer to new variable for previously undeclared symbols in the current and lower scopes
219 // this happens in `{ a = 5; } var a` where both a's refer to the same variable
220 curScope := s
221 if decl == VariableDecl || decl == FunctionDecl {
222 // find function scope for var and function declarations
223 for s != s.Func {
224 // make sure that `{let i;{var i}}` is an error
225 if v := s.findDeclared(name, false); v != nil && v.Decl != decl && v.Decl != CatchDecl {
226 return nil, false
227 }
228 s = s.Parent
229 }
230 }
231
232 if v := s.findDeclared(name, true); v != nil {
233 // variable already declared, might be an error or a duplicate declaration
234 if (ArgumentDecl < v.Decl || FunctionDecl < decl) && v.Decl != ExprDecl {
235 // only allow (v.Decl,decl) of: (var|private|function|argument,var|private|function), (expr,*), any other combination is a syntax error
236 return nil, false
237 }
238 if v.Decl == ExprDecl {
239 v.Decl = decl
240 }
241 v.Uses++
242 for s != curScope {
243 curScope.AddUndeclared(v) // add variable declaration as used variable to the current scope
244 curScope = curScope.Parent
245 }
246 return v, true
247 }
248
249 var v *Var
250 // reuse variable if previously used, as in: a;var a
251 if decl != ArgumentDecl { // in case of function f(a=b,b), where the first b is different from the second
252 for i, uv := range s.Undeclared[s.NumArgUses:] {
253 // no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope
254 if 0 < uv.Uses && uv.Decl == NoDecl && bytes.Equal(name, uv.Data) {
255 // must be NoDecl so that it can't be a var declaration that has been added
256 v = uv
257 s.Undeclared = append(s.Undeclared[:int(s.NumArgUses)+i], s.Undeclared[int(s.NumArgUses)+i+1:]...)
258 break
259 }
260 }
261 }
262 if v == nil {
263 // add variable to the context list and to the scope
264 v = &Var{name, nil, 0, decl}
265 } else {
266 v.Decl = decl
267 }
268 v.Uses++
269 s.Declared = append(s.Declared, v)
270 for s != curScope {
271 curScope.AddUndeclared(v) // add variable declaration as used variable to the current scope
272 curScope = curScope.Parent
273 }
274 return v, true
275 }
276
277 // Use increments the usage of a variable.
278 func (s *Scope) Use(name []byte) *Var {
279 // check if variable is declared in the current scope
280 v := s.findDeclared(name, false)
281 if v == nil {
282 // check if variable is already used before in the current or lower scopes
283 v = s.findUndeclared(name)
284 if v == nil {
285 // add variable to the context list and to the scope's undeclared
286 v = &Var{name, nil, 0, NoDecl}
287 s.Undeclared = append(s.Undeclared, v)
288 }
289 }
290 v.Uses++
291 return v
292 }
293
294 // findDeclared finds a declared variable in the current scope.
295 func (s *Scope) findDeclared(name []byte, skipForDeclared bool) *Var {
296 start := 0
297 if skipForDeclared {
298 // we skip the for initializer for declarations (only has effect for let/const)
299 start = int(s.NumForDecls)
300 }
301 // reverse order to find the inner let first in `for(let a in []){let a; {a}}`
302 for i := len(s.Declared) - 1; start <= i; i-- {
303 v := s.Declared[i]
304 // no need to evaluate v.Link as v.Data stays the same, and Link is always nil in Declared
305 if bytes.Equal(name, v.Data) {
306 return v
307 }
308 }
309 return nil
310 }
311
312 // findUndeclared finds an undeclared variable in the current and contained scopes.
313 func (s *Scope) findUndeclared(name []byte) *Var {
314 for _, v := range s.Undeclared {
315 // no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope
316 if 0 < v.Uses && bytes.Equal(name, v.Data) {
317 return v
318 }
319 }
320 return nil
321 }
322
323 // add undeclared variable to scope, this is called for the block scope when declaring a var in it
324 func (s *Scope) AddUndeclared(v *Var) {
325 // don't add undeclared symbol if it's already there
326 for _, vorig := range s.Undeclared {
327 if v == vorig {
328 return
329 }
330 }
331 s.Undeclared = append(s.Undeclared, v) // add variable declaration as used variable to the current scope
332 }
333
334 // MarkForStmt marks the declared variables in current scope as for statement initializer to distinguish from declarations in body.
335 func (s *Scope) MarkForStmt() {
336 s.NumForDecls = uint16(len(s.Declared))
337 s.NumArgUses = uint16(len(s.Undeclared)) // ensures for different b's in for(var a in b){let b}
338 }
339
340 // MarkFuncArgs marks the declared/undeclared variables in the current scope as function arguments.
341 func (s *Scope) MarkFuncArgs() {
342 s.NumFuncArgs = uint16(len(s.Declared))
343 s.NumArgUses = uint16(len(s.Undeclared)) // ensures different b's in `function f(a=b){var b}`.
344 }
345
346 // HoistUndeclared copies all undeclared variables of the current scope to the parent scope.
347 func (s *Scope) HoistUndeclared() {
348 for i, vorig := range s.Undeclared {
349 // no need to evaluate vorig.Link as vorig.Data stays the same
350 if 0 < vorig.Uses && vorig.Decl == NoDecl {
351 if v := s.Parent.findDeclared(vorig.Data, false); v != nil {
352 // check if variable is declared in parent scope
353 v.Uses += vorig.Uses
354 vorig.Link = v
355 s.Undeclared[i] = v // point reference to existing var (to avoid many Link chains)
356 } else if v := s.Parent.findUndeclared(vorig.Data); v != nil {
357 // check if variable is already used before in parent scope
358 v.Uses += vorig.Uses
359 vorig.Link = v
360 s.Undeclared[i] = v // point reference to existing var (to avoid many Link chains)
361 } else {
362 // add variable to the context list and to the scope's undeclared
363 s.Parent.Undeclared = append(s.Parent.Undeclared, vorig)
364 }
365 }
366 }
367 }
368
369 // UndeclareScope undeclares all declared variables in the current scope and adds them to the parent scope.
370 // Called when possible arrow func ends up being a parenthesized expression, scope is not further used.
371 func (s *Scope) UndeclareScope() {
372 // look if the variable already exists in the parent scope, if so replace the Var pointer in original use
373 for _, vorig := range s.Declared {
374 // no need to evaluate vorig.Link as vorig.Data stays the same, and Link is always nil in Declared
375 // vorig.Uses will be atleast 1
376 if v := s.Parent.findDeclared(vorig.Data, false); v != nil {
377 // check if variable has been declared in this scope
378 v.Uses += vorig.Uses
379 vorig.Link = v
380 } else if v := s.Parent.findUndeclared(vorig.Data); v != nil {
381 // check if variable is already used before in the current or lower scopes
382 v.Uses += vorig.Uses
383 vorig.Link = v
384 } else {
385 // add variable to the context list and to the scope's undeclared
386 vorig.Decl = NoDecl
387 s.Parent.Undeclared = append(s.Parent.Undeclared, vorig)
388 }
389 }
390 s.Declared = s.Declared[:0]
391 s.Undeclared = s.Undeclared[:0]
392 }
393
394 // Unscope moves all declared variables of the current scope to the parent scope. Undeclared variables are already in the parent scope.
395 func (s *Scope) Unscope() {
396 for _, vorig := range s.Declared {
397 // no need to evaluate vorig.Link as vorig.Data stays the same, and Link is always nil in Declared
398 // vorig.Uses will be atleast 1
399 s.Parent.Declared = append(s.Parent.Declared, vorig)
400 }
401 s.Declared = s.Declared[:0]
402 s.Undeclared = s.Undeclared[:0]
403 }
404
405 ////////////////////////////////////////////////////////////////
406
407 // INode is an interface for AST nodes
408 type INode interface {
409 String() string
410 JS(io.Writer)
411 }
412
413 // IStmt is a dummy interface for statements.
414 type IStmt interface {
415 INode
416 stmtNode()
417 }
418
419 // IBinding is a dummy interface for bindings.
420 type IBinding interface {
421 INode
422 bindingNode()
423 }
424
425 // IExpr is a dummy interface for expressions.
426 type IExpr interface {
427 INode
428 exprNode()
429 }
430
431 ////////////////////////////////////////////////////////////////
432
433 // Comment block or line, usually a bang comment.
434 type Comment struct {
435 Value []byte
436 }
437
438 func (n Comment) String() string {
439 return "Stmt(" + string(n.Value) + ")"
440 }
441
442 // JS writes JavaScript to writer.
443 func (n Comment) JS(w io.Writer) {
444 if wi, ok := w.(parse.Indenter); ok {
445 wi.Writer.Write(n.Value)
446 } else {
447 w.Write(n.Value)
448 }
449 }
450
451 // BlockStmt is a block statement.
452 type BlockStmt struct {
453 List []IStmt
454 Scope
455 }
456
457 func (n BlockStmt) String() string {
458 var s strings.Builder
459 s.WriteString("Stmt({")
460 for _, item := range n.List {
461 s.WriteString(" " + item.String())
462 }
463 return s.String() + " })"
464 }
465
466 // JS writes JavaScript to writer.
467 func (n BlockStmt) JS(w io.Writer) {
468 if len(n.List) == 0 {
469 w.Write([]byte("{}"))
470 return
471 }
472
473 w.Write([]byte("{"))
474 wi := parse.NewIndenter(w, 4)
475 for _, item := range n.List {
476 wi.Write([]byte("\n"))
477 item.JS(wi)
478 if _, ok := item.(*VarDecl); ok {
479 w.Write([]byte(";"))
480 }
481 }
482 w.Write([]byte("\n}"))
483 }
484
485 // EmptyStmt is an empty statement.
486 type EmptyStmt struct{}
487
488 func (n EmptyStmt) String() string {
489 return "Stmt()"
490 }
491
492 // JS writes JavaScript to writer.
493 func (n EmptyStmt) JS(w io.Writer) {
494 w.Write([]byte(";"))
495 }
496
497 // ExprStmt is an expression statement.
498 type ExprStmt struct {
499 Value IExpr
500 }
501
502 func (n ExprStmt) String() string {
503 val := n.Value.String()
504 if val[0] == '(' && val[len(val)-1] == ')' {
505 return "Stmt" + n.Value.String()
506 }
507 return "Stmt(" + n.Value.String() + ")"
508 }
509
510 // JS writes JavaScript to writer.
511 func (n ExprStmt) JS(w io.Writer) {
512 buf := &bytes.Buffer{}
513 wb := io.Writer(buf)
514 if wi, ok := w.(parse.Indenter); ok {
515 // make sure that buf is indenter if w is so as well
516 // this is to prevent newlines in literals from indenting
517 wb = parse.NewIndenter(wb, wi.Indent())
518 w = wi.Writer
519 }
520 n.Value.JS(wb)
521 expr := buf.Bytes()
522
523 group := bytes.HasPrefix(expr, []byte("let "))
524 if group {
525 w.Write([]byte("("))
526 }
527 w.Write(expr)
528 if group {
529 w.Write([]byte(")"))
530 }
531 w.Write([]byte(";"))
532 }
533
534 // IfStmt is an if statement.
535 type IfStmt struct {
536 Cond IExpr
537 Body IStmt
538 Else IStmt // can be nil
539 }
540
541 func (n IfStmt) String() string {
542 s := "Stmt(if " + n.Cond.String() + " " + n.Body.String()
543 if n.Else != nil {
544 s += " else " + n.Else.String()
545 }
546 return s + ")"
547 }
548
549 // JS writes JavaScript to writer.
550 func (n IfStmt) JS(w io.Writer) {
551 w.Write([]byte("if ("))
552 n.Cond.JS(w)
553 w.Write([]byte(")"))
554 if _, ok := n.Body.(*EmptyStmt); !ok {
555 w.Write([]byte(" "))
556 }
557 n.Body.JS(w)
558 if _, ok := n.Body.(*VarDecl); ok {
559 w.Write([]byte(";"))
560 }
561 if n.Else != nil {
562 w.Write([]byte(" else"))
563 if _, ok := n.Else.(*EmptyStmt); !ok {
564 w.Write([]byte(" "))
565 }
566 n.Else.JS(w)
567 if _, ok := n.Else.(*VarDecl); ok {
568 w.Write([]byte(";"))
569 }
570 }
571 }
572
573 // DoWhileStmt is a do-while iteration statement.
574 type DoWhileStmt struct {
575 Cond IExpr
576 Body IStmt
577 }
578
579 func (n DoWhileStmt) String() string {
580 return "Stmt(do " + n.Body.String() + " while " + n.Cond.String() + ")"
581 }
582
583 // JS writes JavaScript to writer.
584 func (n DoWhileStmt) JS(w io.Writer) {
585 w.Write([]byte("do"))
586 if _, ok := n.Body.(*EmptyStmt); !ok {
587 w.Write([]byte(" "))
588 }
589 n.Body.JS(w)
590 if _, ok := n.Body.(*VarDecl); ok {
591 w.Write([]byte("; "))
592 } else if _, ok := n.Body.(*Comment); !ok {
593 w.Write([]byte(" "))
594 }
595 w.Write([]byte("while ("))
596 n.Cond.JS(w)
597 w.Write([]byte(");"))
598 }
599
600 // WhileStmt is a while iteration statement.
601 type WhileStmt struct {
602 Cond IExpr
603 Body IStmt
604 }
605
606 func (n WhileStmt) String() string {
607 return "Stmt(while " + n.Cond.String() + " " + n.Body.String() + ")"
608 }
609
610 // JS writes JavaScript to writer.
611 func (n WhileStmt) JS(w io.Writer) {
612 w.Write([]byte("while ("))
613 n.Cond.JS(w)
614 w.Write([]byte(")"))
615 if _, ok := n.Body.(*EmptyStmt); ok {
616 w.Write([]byte(";"))
617 return
618 }
619 w.Write([]byte(" "))
620 n.Body.JS(w)
621 if _, ok := n.Body.(*VarDecl); ok {
622 w.Write([]byte(";"))
623 }
624 }
625
626 // ForStmt is a regular for iteration statement.
627 type ForStmt struct {
628 Init IExpr // can be nil
629 Cond IExpr // can be nil
630 Post IExpr // can be nil
631 Body *BlockStmt
632 }
633
634 func (n ForStmt) String() string {
635 s := "Stmt(for"
636 if v, ok := n.Init.(*VarDecl); !ok && n.Init != nil || ok && len(v.List) != 0 {
637 s += " " + n.Init.String()
638 }
639 s += " ;"
640 if n.Cond != nil {
641 s += " " + n.Cond.String()
642 }
643 s += " ;"
644 if n.Post != nil {
645 s += " " + n.Post.String()
646 }
647 return s + " " + n.Body.String() + ")"
648 }
649
650 // JS writes JavaScript to writer.
651 func (n ForStmt) JS(w io.Writer) {
652 w.Write([]byte("for ("))
653 if v, ok := n.Init.(*VarDecl); !ok && n.Init != nil || ok && len(v.List) != 0 {
654 n.Init.JS(w)
655 } else {
656 w.Write([]byte(" "))
657 }
658 w.Write([]byte("; "))
659 if n.Cond != nil {
660 n.Cond.JS(w)
661 }
662 w.Write([]byte("; "))
663 if n.Post != nil {
664 n.Post.JS(w)
665 }
666 w.Write([]byte(") "))
667 n.Body.JS(w)
668 }
669
670 // ForInStmt is a for-in iteration statement.
671 type ForInStmt struct {
672 Init IExpr
673 Value IExpr
674 Body *BlockStmt
675 }
676
677 func (n ForInStmt) String() string {
678 return "Stmt(for " + n.Init.String() + " in " + n.Value.String() + " " + n.Body.String() + ")"
679 }
680
681 // JS writes JavaScript to writer.
682 func (n ForInStmt) JS(w io.Writer) {
683 w.Write([]byte("for ("))
684 n.Init.JS(w)
685 w.Write([]byte(" in "))
686 n.Value.JS(w)
687 w.Write([]byte(") "))
688 n.Body.JS(w)
689 }
690
691 // ForOfStmt is a for-of iteration statement.
692 type ForOfStmt struct {
693 Await bool
694 Init IExpr
695 Value IExpr
696 Body *BlockStmt
697 }
698
699 func (n ForOfStmt) String() string {
700 s := "Stmt(for"
701 if n.Await {
702 s += " await"
703 }
704 return s + " " + n.Init.String() + " of " + n.Value.String() + " " + n.Body.String() + ")"
705 }
706
707 // JS writes JavaScript to writer.
708 func (n ForOfStmt) JS(w io.Writer) {
709 w.Write([]byte("for"))
710 if n.Await {
711 w.Write([]byte(" await"))
712 }
713 w.Write([]byte(" ("))
714 n.Init.JS(w)
715 w.Write([]byte(" of "))
716 n.Value.JS(w)
717 w.Write([]byte(") "))
718 n.Body.JS(w)
719 }
720
721 // CaseClause is a case clause or default clause for a switch statement.
722 type CaseClause struct {
723 TokenType
724 Cond IExpr // can be nil
725 List []IStmt
726 }
727
728 func (n CaseClause) String() string {
729 var s strings.Builder
730 s.WriteString(" Clause(" + n.TokenType.String())
731 if n.Cond != nil {
732 s.WriteString(" " + n.Cond.String())
733 }
734 for _, item := range n.List {
735 s.WriteString(" " + item.String())
736 }
737 return s.String() + ")"
738 }
739
740 // JS writes JavaScript to writer.
741 func (n CaseClause) JS(w io.Writer) {
742 if n.Cond != nil {
743 w.Write([]byte("case "))
744 n.Cond.JS(w)
745 } else {
746 w.Write([]byte("default"))
747 }
748 w.Write([]byte(":"))
749 wi := parse.NewIndenter(w, 4)
750 for _, item := range n.List {
751 wi.Write([]byte("\n"))
752 item.JS(wi)
753 if _, ok := item.(*VarDecl); ok {
754 w.Write([]byte(";"))
755 }
756 }
757 }
758
759 // SwitchStmt is a switch statement.
760 type SwitchStmt struct {
761 Init IExpr
762 List []CaseClause
763 Scope
764 }
765
766 func (n SwitchStmt) String() string {
767 var s strings.Builder
768 s.WriteString("Stmt(switch " + n.Init.String())
769 for _, clause := range n.List {
770 s.WriteString(clause.String())
771 }
772 return s.String() + ")"
773 }
774
775 // JS writes JavaScript to writer.
776 func (n SwitchStmt) JS(w io.Writer) {
777 w.Write([]byte("switch ("))
778 n.Init.JS(w)
779 if len(n.List) == 0 {
780 w.Write([]byte(") {}"))
781 return
782 }
783 w.Write([]byte(") {"))
784 for _, clause := range n.List {
785 w.Write([]byte("\n"))
786 clause.JS(w)
787 }
788 w.Write([]byte("\n}"))
789 }
790
791 // BranchStmt is a continue or break statement.
792 type BranchStmt struct {
793 Type TokenType
794 Label []byte // can be nil
795 }
796
797 func (n BranchStmt) String() string {
798 s := "Stmt(" + n.Type.String()
799 if n.Label != nil {
800 s += " " + string(n.Label)
801 }
802 return s + ")"
803 }
804
805 // JS writes JavaScript to writer.
806 func (n BranchStmt) JS(w io.Writer) {
807 w.Write(n.Type.Bytes())
808 if n.Label != nil {
809 w.Write([]byte(" "))
810 w.Write(n.Label)
811 }
812 w.Write([]byte(";"))
813 }
814
815 // ReturnStmt is a return statement.
816 type ReturnStmt struct {
817 Value IExpr // can be nil
818 }
819
820 func (n ReturnStmt) String() string {
821 s := "Stmt(return"
822 if n.Value != nil {
823 s += " " + n.Value.String()
824 }
825 return s + ")"
826 }
827
828 // JS writes JavaScript to writer.
829 func (n ReturnStmt) JS(w io.Writer) {
830 w.Write([]byte("return"))
831 if n.Value != nil {
832 w.Write([]byte(" "))
833 n.Value.JS(w)
834 }
835 w.Write([]byte(";"))
836 }
837
838 // WithStmt is a with statement.
839 type WithStmt struct {
840 Cond IExpr
841 Body IStmt
842 }
843
844 func (n WithStmt) String() string {
845 return "Stmt(with " + n.Cond.String() + " " + n.Body.String() + ")"
846 }
847
848 // JS writes JavaScript to writer.
849 func (n WithStmt) JS(w io.Writer) {
850 w.Write([]byte("with ("))
851 n.Cond.JS(w)
852 w.Write([]byte(")"))
853 if _, ok := n.Body.(*EmptyStmt); !ok {
854 w.Write([]byte(" "))
855 }
856 n.Body.JS(w)
857 if _, ok := n.Body.(*VarDecl); ok {
858 w.Write([]byte(";"))
859 }
860 }
861
862 // LabelledStmt is a labelled statement.
863 type LabelledStmt struct {
864 Label []byte
865 Value IStmt
866 }
867
868 func (n LabelledStmt) String() string {
869 return "Stmt(" + string(n.Label) + " : " + n.Value.String() + ")"
870 }
871
872 // JS writes JavaScript to writer.
873 func (n LabelledStmt) JS(w io.Writer) {
874 w.Write(n.Label)
875 w.Write([]byte(":"))
876 if _, ok := n.Value.(*EmptyStmt); !ok {
877 w.Write([]byte(" "))
878 }
879 n.Value.JS(w)
880 if _, ok := n.Value.(*VarDecl); ok {
881 w.Write([]byte(";"))
882 }
883 }
884
885 // ThrowStmt is a throw statement.
886 type ThrowStmt struct {
887 Value IExpr
888 }
889
890 func (n ThrowStmt) String() string {
891 return "Stmt(throw " + n.Value.String() + ")"
892 }
893
894 // JS writes JavaScript to writer.
895 func (n ThrowStmt) JS(w io.Writer) {
896 w.Write([]byte("throw "))
897 n.Value.JS(w)
898 w.Write([]byte(";"))
899 }
900
901 // TryStmt is a try statement.
902 type TryStmt struct {
903 Body *BlockStmt
904 Binding IBinding // can be nil
905 Catch *BlockStmt // can be nil
906 Finally *BlockStmt // can be nil
907 }
908
909 func (n TryStmt) String() string {
910 s := "Stmt(try " + n.Body.String()
911 if n.Catch != nil {
912 s += " catch"
913 if n.Binding != nil {
914 s += " Binding(" + n.Binding.String() + ")"
915 }
916 s += " " + n.Catch.String()
917 }
918 if n.Finally != nil {
919 s += " finally " + n.Finally.String()
920 }
921 return s + ")"
922 }
923
924 // JS writes JavaScript to writer.
925 func (n TryStmt) JS(w io.Writer) {
926 w.Write([]byte("try "))
927 n.Body.JS(w)
928 if n.Catch != nil {
929 w.Write([]byte(" catch"))
930 if n.Binding != nil {
931 w.Write([]byte("("))
932 n.Binding.JS(w)
933 w.Write([]byte(")"))
934 }
935 w.Write([]byte(" "))
936 n.Catch.JS(w)
937 }
938 if n.Finally != nil {
939 w.Write([]byte(" finally "))
940 n.Finally.JS(w)
941 }
942 }
943
944 // DebuggerStmt is a debugger statement.
945 type DebuggerStmt struct{}
946
947 func (n DebuggerStmt) String() string {
948 return "Stmt(debugger)"
949 }
950
951 // JS writes JavaScript to writer.
952 func (n DebuggerStmt) JS(w io.Writer) {
953 w.Write([]byte("debugger;"))
954 }
955
956 // Alias is a name space import or import/export specifier for import/export statements.
957 type Alias struct {
958 Name []byte // can be nil
959 Binding []byte // can be nil
960 }
961
962 func (alias Alias) String() string {
963 s := ""
964 if alias.Name != nil {
965 s += string(alias.Name) + " as "
966 }
967 return s + string(alias.Binding)
968 }
969
970 // JS writes JavaScript to writer.
971 func (alias Alias) JS(w io.Writer) {
972 if alias.Name != nil {
973 w.Write(alias.Name)
974 w.Write([]byte(" as "))
975 }
976 w.Write(alias.Binding)
977 }
978
979 // ImportStmt is an import statement.
980 type ImportStmt struct {
981 List []Alias
982 Default []byte // can be nil
983 Module []byte
984 }
985
986 func (n ImportStmt) String() string {
987 var s strings.Builder
988 s.WriteString("Stmt(import")
989 if n.Default != nil {
990 s.WriteString(" " + string(n.Default))
991 if n.List != nil {
992 s.WriteString(" ,")
993 }
994 }
995 if len(n.List) == 1 && len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' {
996 s.WriteString(" " + n.List[0].String())
997 } else if n.List != nil {
998 s.WriteString(" {")
999 for i, item := range n.List {
1000 if i != 0 {
1001 s.WriteString(" ,")
1002 }
1003 if item.Binding != nil {
1004 s.WriteString(" " + item.String())
1005 }
1006 }
1007 s.WriteString(" }")
1008 }
1009 if n.Default != nil || n.List != nil {
1010 s.WriteString(" from")
1011 }
1012 return s.String() + " " + string(n.Module) + ")"
1013 }
1014
1015 // JS writes JavaScript to writer.
1016 func (n ImportStmt) JS(w io.Writer) {
1017 if wi, ok := w.(parse.Indenter); ok {
1018 w = wi.Writer
1019 }
1020 w.Write([]byte("import"))
1021 if n.Default != nil {
1022 w.Write([]byte(" "))
1023 w.Write(n.Default)
1024 if n.List != nil {
1025 w.Write([]byte(","))
1026 }
1027 }
1028 if len(n.List) == 1 && len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' {
1029 w.Write([]byte(" "))
1030 n.List[0].JS(w)
1031 } else if n.List != nil {
1032 if len(n.List) == 0 {
1033 w.Write([]byte(" {}"))
1034 } else {
1035 w.Write([]byte(" {"))
1036 for j, item := range n.List {
1037 if j != 0 {
1038 w.Write([]byte(","))
1039 }
1040 if item.Binding != nil {
1041 w.Write([]byte(" "))
1042 item.JS(w)
1043 }
1044 }
1045 w.Write([]byte(" }"))
1046 }
1047 }
1048 if n.Default != nil || n.List != nil {
1049 w.Write([]byte(" from"))
1050 }
1051 w.Write([]byte(" "))
1052 w.Write(n.Module)
1053 w.Write([]byte(";"))
1054 }
1055
1056 // ExportStmt is an export statement.
1057 type ExportStmt struct {
1058 List []Alias
1059 Module []byte // can be nil
1060 Default bool
1061 Decl IExpr
1062 }
1063
1064 func (n ExportStmt) String() string {
1065 s := "Stmt(export"
1066 if n.Decl != nil {
1067 if n.Default {
1068 s += " default"
1069 }
1070 return s + " " + n.Decl.String() + ")"
1071 } else if len(n.List) == 1 && (len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' || n.List[0].Name == nil && len(n.List[0].Binding) == 1 && n.List[0].Binding[0] == '*') {
1072 s += " " + n.List[0].String()
1073 } else if 0 < len(n.List) {
1074 s += " {"
1075 for i, item := range n.List {
1076 if i != 0 {
1077 s += " ,"
1078 }
1079 if item.Binding != nil {
1080 s += " " + item.String()
1081 }
1082 }
1083 s += " }"
1084 }
1085 if n.Module != nil {
1086 s += " from " + string(n.Module)
1087 }
1088 return s + ")"
1089 }
1090
1091 // JS writes JavaScript to writer.
1092 func (n ExportStmt) JS(w io.Writer) {
1093 if wi, ok := w.(parse.Indenter); ok {
1094 w = wi.Writer
1095 }
1096 w.Write([]byte("export"))
1097 if n.Decl != nil {
1098 if n.Default {
1099 w.Write([]byte(" default"))
1100 }
1101 w.Write([]byte(" "))
1102 n.Decl.JS(w)
1103 w.Write([]byte(";"))
1104 return
1105 } else if len(n.List) == 1 && (len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' || n.List[0].Name == nil && len(n.List[0].Binding) == 1 && n.List[0].Binding[0] == '*') {
1106 w.Write([]byte(" "))
1107 n.List[0].JS(w)
1108 } else if len(n.List) == 0 {
1109 w.Write([]byte(" {}"))
1110 } else {
1111 w.Write([]byte(" {"))
1112 for j, item := range n.List {
1113 if j != 0 {
1114 w.Write([]byte(","))
1115 }
1116 if item.Binding != nil {
1117 w.Write([]byte(" "))
1118 item.JS(w)
1119 }
1120 }
1121 w.Write([]byte(" }"))
1122 }
1123 if n.Module != nil {
1124 w.Write([]byte(" from "))
1125 w.Write(n.Module)
1126 }
1127 w.Write([]byte(";"))
1128 }
1129
1130 // DirectivePrologueStmt is a string literal at the beginning of a function or module (usually "use strict").
1131 type DirectivePrologueStmt struct {
1132 Value []byte
1133 }
1134
1135 func (n DirectivePrologueStmt) String() string {
1136 return "Stmt(" + string(n.Value) + ")"
1137 }
1138
1139 // JS writes JavaScript to writer.
1140 func (n DirectivePrologueStmt) JS(w io.Writer) {
1141 if wi, ok := w.(parse.Indenter); ok {
1142 w = wi.Writer
1143 }
1144 w.Write(n.Value)
1145 w.Write([]byte(";"))
1146 }
1147
1148 func (n Comment) stmtNode() {}
1149 func (n BlockStmt) stmtNode() {}
1150 func (n EmptyStmt) stmtNode() {}
1151 func (n ExprStmt) stmtNode() {}
1152 func (n IfStmt) stmtNode() {}
1153 func (n DoWhileStmt) stmtNode() {}
1154 func (n WhileStmt) stmtNode() {}
1155 func (n ForStmt) stmtNode() {}
1156 func (n ForInStmt) stmtNode() {}
1157 func (n ForOfStmt) stmtNode() {}
1158 func (n SwitchStmt) stmtNode() {}
1159 func (n BranchStmt) stmtNode() {}
1160 func (n ReturnStmt) stmtNode() {}
1161 func (n WithStmt) stmtNode() {}
1162 func (n LabelledStmt) stmtNode() {}
1163 func (n ThrowStmt) stmtNode() {}
1164 func (n TryStmt) stmtNode() {}
1165 func (n DebuggerStmt) stmtNode() {}
1166 func (n ImportStmt) stmtNode() {}
1167 func (n ExportStmt) stmtNode() {}
1168 func (n DirectivePrologueStmt) stmtNode() {}
1169
1170 ////////////////////////////////////////////////////////////////
1171
1172 // PropertyName is a property name for binding properties, method names, and in object literals.
1173 type PropertyName struct {
1174 Literal LiteralExpr
1175 Computed IExpr // can be nil
1176 }
1177
1178 // IsSet returns true is PropertyName is not nil.
1179 func (n PropertyName) IsSet() bool {
1180 return n.IsComputed() || n.Literal.TokenType != ErrorToken
1181 }
1182
1183 // IsComputed returns true if PropertyName is computed.
1184 func (n PropertyName) IsComputed() bool {
1185 return n.Computed != nil
1186 }
1187
1188 // IsIdent returns true if PropertyName equals the given identifier name.
1189 func (n PropertyName) IsIdent(data []byte) bool {
1190 return !n.IsComputed() && n.Literal.TokenType == IdentifierToken && bytes.Equal(data, n.Literal.Data)
1191 }
1192
1193 func (n PropertyName) String() string {
1194 if n.Computed != nil {
1195 val := n.Computed.String()
1196 if val[0] == '(' {
1197 return "[" + val[1:len(val)-1] + "]"
1198 }
1199 return "[" + val + "]"
1200 }
1201 return string(n.Literal.Data)
1202 }
1203
1204 // JS writes JavaScript to writer.
1205 func (n PropertyName) JS(w io.Writer) {
1206 if n.Computed != nil {
1207 w.Write([]byte("["))
1208 n.Computed.JS(w)
1209 w.Write([]byte("]"))
1210 return
1211 }
1212 if wi, ok := w.(parse.Indenter); ok {
1213 w = wi.Writer
1214 }
1215 w.Write(n.Literal.Data)
1216 }
1217
1218 // BindingArray is an array binding pattern.
1219 type BindingArray struct {
1220 List []BindingElement
1221 Rest IBinding // can be nil
1222 }
1223
1224 func (n BindingArray) String() string {
1225 var s strings.Builder
1226 s.WriteString("[")
1227 for i, item := range n.List {
1228 if i != 0 {
1229 s.WriteString(",")
1230 }
1231 s.WriteString(" " + item.String())
1232 }
1233 if n.Rest != nil {
1234 if len(n.List) != 0 {
1235 s.WriteString(",")
1236 }
1237 s.WriteString(" ...Binding(" + n.Rest.String() + ")")
1238 } else if 0 < len(n.List) && n.List[len(n.List)-1].Binding == nil {
1239 s.WriteString(",")
1240 }
1241 return s.String() + " ]"
1242 }
1243
1244 // JS writes JavaScript to writer.
1245 func (n BindingArray) JS(w io.Writer) {
1246 w.Write([]byte("["))
1247 for j, item := range n.List {
1248 if j != 0 {
1249 w.Write([]byte(","))
1250 }
1251 if item.Binding != nil {
1252 if j != 0 {
1253 w.Write([]byte(" "))
1254 }
1255 item.JS(w)
1256 }
1257 }
1258 if n.Rest != nil {
1259 if len(n.List) != 0 {
1260 w.Write([]byte(", "))
1261 }
1262 w.Write([]byte("..."))
1263 n.Rest.JS(w)
1264 } else if 0 < len(n.List) && n.List[len(n.List)-1].Binding == nil {
1265 w.Write([]byte(","))
1266 }
1267 w.Write([]byte("]"))
1268 }
1269
1270 // BindingObjectItem is a binding property.
1271 type BindingObjectItem struct {
1272 Key *PropertyName // can be nil
1273 Value BindingElement
1274 }
1275
1276 func (n BindingObjectItem) String() string {
1277 s := ""
1278 if n.Key != nil {
1279 if v, ok := n.Value.Binding.(*Var); !ok || !n.Key.IsIdent(v.Data) {
1280 s += " " + n.Key.String() + ":"
1281 }
1282 }
1283 return s + " " + n.Value.String()
1284 }
1285
1286 // JS writes JavaScript to writer.
1287 func (n BindingObjectItem) JS(w io.Writer) {
1288 if n.Key != nil {
1289 if v, ok := n.Value.Binding.(*Var); !ok || !n.Key.IsIdent(v.Data) {
1290 n.Key.JS(w)
1291 w.Write([]byte(": "))
1292 }
1293 }
1294 n.Value.JS(w)
1295 }
1296
1297 // BindingObject is an object binding pattern.
1298 type BindingObject struct {
1299 List []BindingObjectItem
1300 Rest *Var // can be nil
1301 }
1302
1303 func (n BindingObject) String() string {
1304 var s strings.Builder
1305 s.WriteString("{")
1306 for i, item := range n.List {
1307 if i != 0 {
1308 s.WriteString(",")
1309 }
1310 s.WriteString(item.String())
1311 }
1312 if n.Rest != nil {
1313 if len(n.List) != 0 {
1314 s.WriteString(",")
1315 }
1316 s.WriteString(" ...Binding(" + string(n.Rest.Data) + ")")
1317 }
1318 return s.String() + " }"
1319 }
1320
1321 // JS writes JavaScript to writer.
1322 func (n BindingObject) JS(w io.Writer) {
1323 w.Write([]byte("{"))
1324 for j, item := range n.List {
1325 if j != 0 {
1326 w.Write([]byte(", "))
1327 }
1328 item.JS(w)
1329 }
1330 if n.Rest != nil {
1331 if len(n.List) != 0 {
1332 w.Write([]byte(", "))
1333 }
1334 w.Write([]byte("..."))
1335 w.Write(n.Rest.Data)
1336 }
1337 w.Write([]byte("}"))
1338 }
1339
1340 // BindingElement is a binding element.
1341 type BindingElement struct {
1342 Binding IBinding // can be nil (in case of ellision)
1343 Default IExpr // can be nil
1344 }
1345
1346 func (n BindingElement) String() string {
1347 if n.Binding == nil {
1348 return "Binding()"
1349 }
1350 s := "Binding(" + n.Binding.String()
1351 if n.Default != nil {
1352 s += " = " + n.Default.String()
1353 }
1354 return s + ")"
1355 }
1356
1357 // JS writes JavaScript to writer.
1358 func (n BindingElement) JS(w io.Writer) {
1359 if n.Binding == nil {
1360 return
1361 }
1362
1363 n.Binding.JS(w)
1364 if n.Default != nil {
1365 w.Write([]byte(" = "))
1366 n.Default.JS(w)
1367 }
1368 }
1369
1370 func (v *Var) bindingNode() {}
1371 func (n BindingArray) bindingNode() {}
1372 func (n BindingObject) bindingNode() {}
1373
1374 ////////////////////////////////////////////////////////////////
1375
1376 // VarDecl is a variable statement or lexical declaration.
1377 type VarDecl struct {
1378 TokenType
1379 List []BindingElement
1380 Scope *Scope
1381 InFor, InForInOf bool
1382 }
1383
1384 func (n VarDecl) String() string {
1385 var s strings.Builder
1386 s.WriteString("Decl(" + n.TokenType.String())
1387 for _, item := range n.List {
1388 s.WriteString(" " + item.String())
1389 }
1390 return s.String() + ")"
1391 }
1392
1393 // JS writes JavaScript to writer.
1394 func (n VarDecl) JS(w io.Writer) {
1395 w.Write(n.TokenType.Bytes())
1396 for j, item := range n.List {
1397 if j != 0 {
1398 w.Write([]byte(","))
1399 }
1400 w.Write([]byte(" "))
1401 item.JS(w)
1402 }
1403 }
1404
1405 // Params is a list of parameters for functions, methods, and arrow function.
1406 type Params struct {
1407 List []BindingElement
1408 Rest IBinding // can be nil
1409 }
1410
1411 func (n Params) String() string {
1412 var s strings.Builder
1413 s.WriteString("Params(")
1414 for i, item := range n.List {
1415 if i != 0 {
1416 s.WriteString(", ")
1417 }
1418 s.WriteString(item.String())
1419 }
1420 if n.Rest != nil {
1421 if len(n.List) != 0 {
1422 s.WriteString(", ")
1423 }
1424 s.WriteString("...Binding(" + n.Rest.String() + ")")
1425 }
1426 return s.String() + ")"
1427 }
1428
1429 // JS writes JavaScript to writer.
1430 func (n Params) JS(w io.Writer) {
1431 w.Write([]byte("("))
1432 for j, item := range n.List {
1433 if j != 0 {
1434 w.Write([]byte(", "))
1435 }
1436 item.JS(w)
1437 }
1438 if n.Rest != nil {
1439 if len(n.List) != 0 {
1440 w.Write([]byte(", "))
1441 }
1442 w.Write([]byte("..."))
1443 n.Rest.JS(w)
1444 }
1445 w.Write([]byte(")"))
1446 }
1447
1448 // FuncDecl is an (async) (generator) function declaration or expression.
1449 type FuncDecl struct {
1450 Async bool
1451 Generator bool
1452 Name *Var // can be nil
1453 Params Params
1454 Body BlockStmt
1455 }
1456
1457 func (n FuncDecl) String() string {
1458 s := "Decl("
1459 if n.Async {
1460 s += "async function"
1461 } else {
1462 s += "function"
1463 }
1464 if n.Generator {
1465 s += "*"
1466 }
1467 if n.Name != nil {
1468 s += " " + string(n.Name.Data)
1469 }
1470 return s + " " + n.Params.String() + " " + n.Body.String() + ")"
1471 }
1472
1473 // JS writes JavaScript to writer.
1474 func (n FuncDecl) JS(w io.Writer) {
1475 if n.Async {
1476 w.Write([]byte("async function"))
1477 } else {
1478 w.Write([]byte("function"))
1479 }
1480
1481 if n.Generator {
1482 w.Write([]byte("*"))
1483 }
1484 if n.Name != nil {
1485 w.Write([]byte(" "))
1486 w.Write(n.Name.Data)
1487 }
1488 n.Params.JS(w)
1489 w.Write([]byte(" "))
1490 n.Body.JS(w)
1491 }
1492
1493 // ClassElementName is either a private method/field or a property name for a method/field.
1494 type ClassElementName struct {
1495 PropertyName
1496 Private *Var // can be nil
1497 }
1498
1499 func (n ClassElementName) String() string {
1500 if n.Private != nil {
1501 return n.Private.String()
1502 } else {
1503 return n.PropertyName.String()
1504 }
1505 }
1506
1507 // JS writes JavaScript to writer.
1508 func (n ClassElementName) JS(w io.Writer) {
1509 if n.Private != nil {
1510 n.Private.JS(w)
1511 } else {
1512 n.PropertyName.JS(w)
1513 }
1514 }
1515
1516 // MethodDecl is a method definition in a class declaration.
1517 type MethodDecl struct {
1518 Static bool
1519 Async bool
1520 Generator bool
1521 Get bool
1522 Set bool
1523 Name ClassElementName
1524 Params Params
1525 Body BlockStmt
1526 }
1527
1528 func (n MethodDecl) String() string {
1529 s := ""
1530 if n.Static {
1531 s += " static"
1532 }
1533 if n.Async {
1534 s += " async"
1535 }
1536 if n.Generator {
1537 s += " *"
1538 }
1539 if n.Get {
1540 s += " get"
1541 }
1542 if n.Set {
1543 s += " set"
1544 }
1545 s += " " + n.Name.String() + " " + n.Params.String() + " " + n.Body.String()
1546 return "Method(" + s[1:] + ")"
1547 }
1548
1549 // JS writes JavaScript to writer.
1550 func (n MethodDecl) JS(w io.Writer) {
1551 writen := false
1552 if n.Static {
1553 w.Write([]byte("static"))
1554 writen = true
1555 }
1556 if n.Async {
1557 if writen {
1558 w.Write([]byte(" "))
1559 }
1560 w.Write([]byte("async"))
1561 writen = true
1562 }
1563 if n.Generator {
1564 if writen {
1565 w.Write([]byte(" "))
1566 }
1567 w.Write([]byte("*"))
1568 writen = true
1569 }
1570 if n.Get {
1571 if writen {
1572 w.Write([]byte(" "))
1573 }
1574 w.Write([]byte("get"))
1575 writen = true
1576 }
1577 if n.Set {
1578 if writen {
1579 w.Write([]byte(" "))
1580 }
1581 w.Write([]byte("set"))
1582 writen = true
1583 }
1584 if writen {
1585 w.Write([]byte(" "))
1586 }
1587 n.Name.JS(w)
1588 w.Write([]byte(" "))
1589 n.Params.JS(w)
1590 w.Write([]byte(" "))
1591 n.Body.JS(w)
1592 }
1593
1594 // Field is a field definition in a class declaration.
1595 type Field struct {
1596 Static bool
1597 Name ClassElementName
1598 Init IExpr // can be nil
1599 }
1600
1601 func (n Field) String() string {
1602 s := "Field("
1603 if n.Static {
1604 s += "static "
1605 }
1606 s += n.Name.String()
1607 if n.Init != nil {
1608 s += " = " + n.Init.String()
1609 }
1610 return s + ")"
1611 }
1612
1613 // JS writes JavaScript to writer.
1614 func (n Field) JS(w io.Writer) {
1615 if n.Static {
1616 w.Write([]byte("static "))
1617 }
1618 n.Name.JS(w)
1619 if n.Init != nil {
1620 w.Write([]byte(" = "))
1621 n.Init.JS(w)
1622 }
1623 }
1624
1625 // ClassElement is a class element that is either a static block, a field definition, or a class method
1626 type ClassElement struct {
1627 StaticBlock *BlockStmt // can be nil
1628 Method *MethodDecl // can be nil
1629 Field
1630 }
1631
1632 func (n ClassElement) String() string {
1633 if n.StaticBlock != nil {
1634 return "Static(" + n.StaticBlock.String() + ")"
1635 } else if n.Method != nil {
1636 return n.Method.String()
1637 }
1638 return n.Field.String()
1639 }
1640
1641 // JS writes JavaScript to writer.
1642 func (n ClassElement) JS(w io.Writer) {
1643 if n.StaticBlock != nil {
1644 w.Write([]byte("static "))
1645 n.StaticBlock.JS(w)
1646 return
1647 } else if n.Method != nil {
1648 n.Method.JS(w)
1649 return
1650 }
1651 n.Field.JS(w)
1652 w.Write([]byte(";"))
1653 }
1654
1655 // ClassDecl is a class declaration.
1656 type ClassDecl struct {
1657 Name *Var // can be nil
1658 Extends IExpr // can be nil
1659 List []ClassElement
1660 Scope // for private elements
1661 }
1662
1663 func (n ClassDecl) String() string {
1664 var s strings.Builder
1665 s.WriteString("Decl(class")
1666 if n.Name != nil {
1667 s.WriteString(" " + string(n.Name.Data))
1668 }
1669 if n.Extends != nil {
1670 s.WriteString(" extends " + n.Extends.String())
1671 }
1672 for _, item := range n.List {
1673 s.WriteString(" " + item.String())
1674 }
1675 return s.String() + ")"
1676 }
1677
1678 // JS writes JavaScript to writer.
1679 func (n ClassDecl) JS(w io.Writer) {
1680 w.Write([]byte("class"))
1681 if n.Name != nil {
1682 w.Write([]byte(" "))
1683 w.Write(n.Name.Data)
1684 }
1685 if n.Extends != nil {
1686 w.Write([]byte(" extends "))
1687 n.Extends.JS(w)
1688 }
1689 if len(n.List) == 0 {
1690 w.Write([]byte(" {}"))
1691 return
1692 }
1693 w.Write([]byte(" {"))
1694 wi := parse.NewIndenter(w, 4)
1695 for _, item := range n.List {
1696 wi.Write([]byte("\n"))
1697 item.JS(wi)
1698 }
1699 w.Write([]byte("\n}"))
1700 }
1701
1702 func (n VarDecl) stmtNode() {}
1703 func (n FuncDecl) stmtNode() {}
1704 func (n ClassDecl) stmtNode() {}
1705
1706 func (n VarDecl) exprNode() {} // not a real IExpr, used for ForInit and ExportDecl
1707 func (n FuncDecl) exprNode() {}
1708 func (n ClassDecl) exprNode() {}
1709 func (n MethodDecl) exprNode() {} // not a real IExpr, used for ObjectExpression PropertyName
1710
1711 ////////////////////////////////////////////////////////////////
1712
1713 // LiteralExpr can be this, null, boolean, numeric, string, or regular expression literals.
1714 type LiteralExpr struct {
1715 TokenType
1716 Data []byte
1717 }
1718
1719 func (n LiteralExpr) String() string {
1720 return string(n.Data)
1721 }
1722
1723 // JS writes JavaScript to writer.
1724 func (n LiteralExpr) JS(w io.Writer) {
1725 if wi, ok := w.(parse.Indenter); ok {
1726 w = wi.Writer
1727 }
1728 w.Write(n.Data)
1729 }
1730
1731 // JSON writes JSON to writer.
1732 func (n LiteralExpr) JSON(w io.Writer) error {
1733 if wi, ok := w.(parse.Indenter); ok {
1734 w = wi.Writer
1735 }
1736 if n.TokenType == TrueToken || n.TokenType == FalseToken || n.TokenType == NullToken || n.TokenType == DecimalToken || n.TokenType == IntegerToken {
1737 w.Write(n.Data)
1738 return nil
1739 } else if n.TokenType == StringToken {
1740 data := n.Data
1741 if n.Data[0] == '\'' {
1742 data = parse.Copy(data)
1743 data = bytes.ReplaceAll(data, []byte(`\'`), []byte(`'`))
1744 data = bytes.ReplaceAll(data, []byte(`"`), []byte(`\"`))
1745 data[0] = '"'
1746 data[len(data)-1] = '"'
1747 }
1748 w.Write(data)
1749 return nil
1750 }
1751 js := &strings.Builder{}
1752 n.JS(js)
1753 return fmt.Errorf("%v: literal expression is not valid JSON: %v", ErrInvalidJSON, js.String())
1754 }
1755
1756 // Element is an array literal element.
1757 type Element struct {
1758 Value IExpr // can be nil
1759 Spread bool
1760 }
1761
1762 func (n Element) String() string {
1763 s := ""
1764 if n.Value != nil {
1765 if n.Spread {
1766 s += "..."
1767 }
1768 s += n.Value.String()
1769 }
1770 return s
1771 }
1772
1773 // JS writes JavaScript to writer.
1774 func (n Element) JS(w io.Writer) {
1775 if n.Value != nil {
1776 if n.Spread {
1777 w.Write([]byte("..."))
1778 }
1779 n.Value.JS(w)
1780 }
1781 }
1782
1783 // ArrayExpr is an array literal.
1784 type ArrayExpr struct {
1785 List []Element
1786 }
1787
1788 func (n ArrayExpr) String() string {
1789 var s strings.Builder
1790 s.WriteString("[")
1791 for i, item := range n.List {
1792 if i != 0 {
1793 s.WriteString(", ")
1794 }
1795 if item.Value != nil {
1796 if item.Spread {
1797 s.WriteString("...")
1798 }
1799 s.WriteString(item.Value.String())
1800 }
1801 }
1802 if 0 < len(n.List) && n.List[len(n.List)-1].Value == nil {
1803 s.WriteString(",")
1804 }
1805 return s.String() + "]"
1806 }
1807
1808 // JS writes JavaScript to writer.
1809 func (n ArrayExpr) JS(w io.Writer) {
1810 w.Write([]byte("["))
1811 for j, item := range n.List {
1812 if j != 0 {
1813 w.Write([]byte(", "))
1814 }
1815 if item.Value != nil {
1816 if item.Spread {
1817 w.Write([]byte("..."))
1818 }
1819 item.Value.JS(w)
1820 }
1821 }
1822 if 0 < len(n.List) && n.List[len(n.List)-1].Value == nil {
1823 w.Write([]byte(","))
1824 }
1825 w.Write([]byte("]"))
1826 }
1827
1828 // JSON writes JSON to writer.
1829 func (n ArrayExpr) JSON(w io.Writer) error {
1830 w.Write([]byte("["))
1831 for i, item := range n.List {
1832 if i != 0 {
1833 w.Write([]byte(", "))
1834 }
1835 if item.Value == nil || item.Spread {
1836 js := &strings.Builder{}
1837 n.JS(js)
1838 return fmt.Errorf("%v: array literal is not valid JSON: %v", ErrInvalidJSON, js.String())
1839 }
1840 if val, ok := item.Value.(JSONer); !ok {
1841 js := &strings.Builder{}
1842 item.Value.JS(js)
1843 return fmt.Errorf("%v: value is not valid JSON: %v", ErrInvalidJSON, js.String())
1844 } else if err := val.JSON(w); err != nil {
1845 return err
1846 }
1847 }
1848 w.Write([]byte("]"))
1849 return nil
1850 }
1851
1852 // Property is a property definition in an object literal.
1853 type Property struct {
1854 // either Name or Spread are set. When Spread is set then Value is AssignmentExpression
1855 // if Init is set then Value is IdentifierReference, otherwise it can also be MethodDefinition
1856 Name *PropertyName // can be nil
1857 Spread bool
1858 Value IExpr // Var, MethodDecl, AssignExpr, or IdentExpr
1859 Init IExpr // can be nil
1860 }
1861
1862 func (n Property) String() string {
1863 s := ""
1864 if n.Name != nil {
1865 if v, ok := n.Value.(*Var); !ok || !n.Name.IsIdent(v.Data) {
1866 s += n.Name.String() + ": "
1867 }
1868 } else if n.Spread {
1869 s += "..."
1870 }
1871 s += n.Value.String()
1872 if n.Init != nil {
1873 s += " = " + n.Init.String()
1874 }
1875 return s
1876 }
1877
1878 // JS writes JavaScript to writer.
1879 func (n Property) JS(w io.Writer) {
1880 if n.Name != nil {
1881 if v, ok := n.Value.(*Var); !ok || !n.Name.IsIdent(v.Data) {
1882 n.Name.JS(w)
1883 w.Write([]byte(": "))
1884 }
1885 } else if n.Spread {
1886 w.Write([]byte("..."))
1887 }
1888 n.Value.JS(w)
1889 if n.Init != nil {
1890 w.Write([]byte(" = "))
1891 n.Init.JS(w)
1892 }
1893 }
1894
1895 // JSON writes JSON to writer.
1896 func (n Property) JSON(w io.Writer) error {
1897 if n.Name == nil || n.Spread || n.Init != nil {
1898 js := &strings.Builder{}
1899 n.JS(js)
1900 return fmt.Errorf("%v: property is not valid JSON: %v", ErrInvalidJSON, js.String())
1901 } else if n.Name.Literal.TokenType == StringToken {
1902 _ = n.Name.Literal.JSON(w)
1903 } else if n.Name.Literal.TokenType == IdentifierToken || n.Name.Literal.TokenType == IntegerToken || n.Name.Literal.TokenType == DecimalToken {
1904 w.Write([]byte(`"`))
1905 w.Write(n.Name.Literal.Data)
1906 w.Write([]byte(`"`))
1907 } else {
1908 js := &strings.Builder{}
1909 n.JS(js)
1910 return fmt.Errorf("%v: property is not valid JSON: %v", ErrInvalidJSON, js.String())
1911 }
1912 w.Write([]byte(": "))
1913
1914 if val, ok := n.Value.(JSONer); !ok {
1915 js := &strings.Builder{}
1916 n.Value.JS(js)
1917 return fmt.Errorf("%v: value is not valid JSON: %v", ErrInvalidJSON, js.String())
1918 } else if err := val.JSON(w); err != nil {
1919 return err
1920 }
1921 return nil
1922 }
1923
1924 // ObjectExpr is an object literal.
1925 type ObjectExpr struct {
1926 List []Property
1927 }
1928
1929 func (n ObjectExpr) String() string {
1930 var s strings.Builder
1931 s.WriteString("{")
1932 for i, item := range n.List {
1933 if i != 0 {
1934 s.WriteString(", ")
1935 }
1936 s.WriteString(item.String())
1937 }
1938 return s.String() + "}"
1939 }
1940
1941 // JS writes JavaScript to writer.
1942 func (n ObjectExpr) JS(w io.Writer) {
1943 w.Write([]byte("{"))
1944 for j, item := range n.List {
1945 if j != 0 {
1946 w.Write([]byte(", "))
1947 }
1948 item.JS(w)
1949 }
1950 w.Write([]byte("}"))
1951 }
1952
1953 // JSON writes JSON to writer.
1954 func (n ObjectExpr) JSON(w io.Writer) error {
1955 w.Write([]byte("{"))
1956 for i, item := range n.List {
1957 if i != 0 {
1958 w.Write([]byte(", "))
1959 }
1960 if err := item.JSON(w); err != nil {
1961 return err
1962 }
1963 }
1964 w.Write([]byte("}"))
1965 return nil
1966 }
1967
1968 // TemplatePart is a template head or middle.
1969 type TemplatePart struct {
1970 Value []byte
1971 Expr IExpr
1972 }
1973
1974 func (n TemplatePart) String() string {
1975 return string(n.Value) + n.Expr.String()
1976 }
1977
1978 // JS writes JavaScript to writer.
1979 func (n TemplatePart) JS(w io.Writer) {
1980 w.Write(n.Value)
1981 n.Expr.JS(w)
1982 }
1983
1984 // TemplateExpr is a template literal or member/call expression, super property, or optional chain with template literal.
1985 type TemplateExpr struct {
1986 Tag IExpr // can be nil
1987 List []TemplatePart
1988 Tail []byte
1989 Prec OpPrec
1990 Optional bool
1991 }
1992
1993 func (n TemplateExpr) String() string {
1994 var s strings.Builder
1995 if n.Tag != nil {
1996 s.WriteString(n.Tag.String())
1997 if n.Optional {
1998 s.WriteString("?.")
1999 }
2000 }
2001 for _, item := range n.List {
2002 s.WriteString(item.String())
2003 }
2004 return s.String() + string(n.Tail)
2005 }
2006
2007 // JS writes JavaScript to writer.
2008 func (n TemplateExpr) JS(w io.Writer) {
2009 if wi, ok := w.(parse.Indenter); ok {
2010 w = wi.Writer
2011 }
2012 if n.Tag != nil {
2013 n.Tag.JS(w)
2014 if n.Optional {
2015 w.Write([]byte("?."))
2016 }
2017 }
2018 for _, item := range n.List {
2019 item.JS(w)
2020 }
2021 w.Write(n.Tail)
2022 }
2023
2024 // JSON writes JSON to writer.
2025 func (n TemplateExpr) JSON(w io.Writer) error {
2026 if wi, ok := w.(parse.Indenter); ok {
2027 w = wi.Writer
2028 }
2029 if n.Tag != nil || len(n.List) != 0 {
2030 js := &strings.Builder{}
2031 n.JS(js)
2032 return fmt.Errorf("%v: value is not valid JSON: %v", ErrInvalidJSON, js.String())
2033 }
2034
2035 // allow template literal string to be converted to normal string (to allow for minified JS)
2036 data := parse.Copy(n.Tail)
2037 data = bytes.ReplaceAll(data, []byte("\n"), []byte("\\n"))
2038 data = bytes.ReplaceAll(data, []byte("\r"), []byte("\\r"))
2039 data = bytes.ReplaceAll(data, []byte("\\`"), []byte("`"))
2040 data = bytes.ReplaceAll(data, []byte("\\$"), []byte("$"))
2041 data = bytes.ReplaceAll(data, []byte(`"`), []byte(`\"`))
2042 data[0] = '"'
2043 data[len(data)-1] = '"'
2044 w.Write(data)
2045 return nil
2046 }
2047
2048 // GroupExpr is a parenthesized expression.
2049 type GroupExpr struct {
2050 X IExpr
2051 }
2052
2053 func (n GroupExpr) String() string {
2054 return "(" + n.X.String() + ")"
2055 }
2056
2057 // JS writes JavaScript to writer.
2058 func (n GroupExpr) JS(w io.Writer) {
2059 w.Write([]byte("("))
2060 n.X.JS(w)
2061 w.Write([]byte(")"))
2062 }
2063
2064 // IndexExpr is a member/call expression, super property, or optional chain with an index expression.
2065 type IndexExpr struct {
2066 X IExpr
2067 Y IExpr
2068 Prec OpPrec
2069 Optional bool
2070 }
2071
2072 func (n IndexExpr) String() string {
2073 if n.Optional {
2074 return "(" + n.X.String() + "?.[" + n.Y.String() + "])"
2075 }
2076 return "(" + n.X.String() + "[" + n.Y.String() + "])"
2077 }
2078
2079 // JS writes JavaScript to writer.
2080 func (n IndexExpr) JS(w io.Writer) {
2081 n.X.JS(w)
2082 if n.Optional {
2083 w.Write([]byte("?.["))
2084 } else {
2085 w.Write([]byte("["))
2086 }
2087 n.Y.JS(w)
2088 w.Write([]byte("]"))
2089 }
2090
2091 // DotExpr is a member/call expression, super property, or optional chain with a dot expression.
2092 type DotExpr struct {
2093 X IExpr
2094 Y IExpr // LiteralExpr or Var
2095 Prec OpPrec
2096 Optional bool
2097 }
2098
2099 func (n DotExpr) String() string {
2100 if n.Optional {
2101 return "(" + n.X.String() + "?." + n.Y.String() + ")"
2102 }
2103 return "(" + n.X.String() + "." + n.Y.String() + ")"
2104 }
2105
2106 // JS writes JavaScript to writer.
2107 func (n DotExpr) JS(w io.Writer) {
2108 lit, ok := n.X.(*LiteralExpr)
2109 group := ok && !n.Optional && (lit.TokenType == DecimalToken || lit.TokenType == IntegerToken)
2110 if group {
2111 w.Write([]byte("("))
2112 }
2113 n.X.JS(w)
2114 if n.Optional {
2115 w.Write([]byte("?."))
2116 } else {
2117 if group {
2118 w.Write([]byte(")"))
2119 }
2120 w.Write([]byte("."))
2121 }
2122 n.Y.JS(w)
2123 }
2124
2125 // NewTargetExpr is a new target meta property.
2126 type NewTargetExpr struct{}
2127
2128 func (n NewTargetExpr) String() string {
2129 return "(new.target)"
2130 }
2131
2132 // JS writes JavaScript to writer.
2133 func (n NewTargetExpr) JS(w io.Writer) {
2134 w.Write([]byte("new.target"))
2135 }
2136
2137 // ImportMetaExpr is a import meta meta property.
2138 type ImportMetaExpr struct{}
2139
2140 func (n ImportMetaExpr) String() string {
2141 return "(import.meta)"
2142 }
2143
2144 // JS writes JavaScript to writer.
2145 func (n ImportMetaExpr) JS(w io.Writer) {
2146 w.Write([]byte("import.meta"))
2147 }
2148
2149 type Arg struct {
2150 Value IExpr
2151 Rest bool
2152 }
2153
2154 func (n Arg) String() string {
2155 s := ""
2156 if n.Rest {
2157 s += "..."
2158 }
2159 return s + n.Value.String()
2160 }
2161
2162 // JS writes JavaScript to writer.
2163 func (n Arg) JS(w io.Writer) {
2164 if n.Rest {
2165 w.Write([]byte("..."))
2166 }
2167 n.Value.JS(w)
2168 }
2169
2170 // Args is a list of arguments as used by new and call expressions.
2171 type Args struct {
2172 List []Arg
2173 }
2174
2175 func (n Args) String() string {
2176 var s strings.Builder
2177 s.WriteString("(")
2178 for i, item := range n.List {
2179 if i != 0 {
2180 s.WriteString(", ")
2181 }
2182 s.WriteString(item.String())
2183 }
2184 return s.String() + ")"
2185 }
2186
2187 // JS writes JavaScript to writer.
2188 func (n Args) JS(w io.Writer) {
2189 for j, item := range n.List {
2190 if j != 0 {
2191 w.Write([]byte(", "))
2192 }
2193 item.JS(w)
2194 }
2195 }
2196
2197 // NewExpr is a new expression or new member expression.
2198 type NewExpr struct {
2199 X IExpr
2200 Args *Args // can be nil
2201 }
2202
2203 func (n NewExpr) String() string {
2204 if n.Args != nil {
2205 return "(new " + n.X.String() + n.Args.String() + ")"
2206 }
2207 return "(new " + n.X.String() + ")"
2208 }
2209
2210 // JS writes JavaScript to writer.
2211 func (n NewExpr) JS(w io.Writer) {
2212 w.Write([]byte("new "))
2213 n.X.JS(w)
2214 if n.Args != nil {
2215 w.Write([]byte("("))
2216 n.Args.JS(w)
2217 w.Write([]byte(")"))
2218 } else {
2219 w.Write([]byte("()"))
2220 }
2221 }
2222
2223 // CallExpr is a call expression.
2224 type CallExpr struct {
2225 X IExpr
2226 Args Args
2227 Prec OpPrec
2228 Optional bool
2229 }
2230
2231 func (n CallExpr) String() string {
2232 if n.Optional {
2233 return "(" + n.X.String() + "?." + n.Args.String() + ")"
2234 }
2235 return "(" + n.X.String() + n.Args.String() + ")"
2236 }
2237
2238 // JS writes JavaScript to writer.
2239 func (n CallExpr) JS(w io.Writer) {
2240 n.X.JS(w)
2241 if n.Optional {
2242 w.Write([]byte("?.("))
2243 } else {
2244 w.Write([]byte("("))
2245 }
2246 n.Args.JS(w)
2247 w.Write([]byte(")"))
2248 }
2249
2250 // UnaryExpr is an update or unary expression.
2251 type UnaryExpr struct {
2252 Op TokenType
2253 X IExpr
2254 }
2255
2256 func (n UnaryExpr) String() string {
2257 if n.Op == PostIncrToken || n.Op == PostDecrToken {
2258 return "(" + n.X.String() + n.Op.String() + ")"
2259 } else if IsIdentifierName(n.Op) {
2260 return "(" + n.Op.String() + " " + n.X.String() + ")"
2261 }
2262 return "(" + n.Op.String() + n.X.String() + ")"
2263 }
2264
2265 // JS writes JavaScript to writer.
2266 func (n UnaryExpr) JS(w io.Writer) {
2267 if n.Op == PostIncrToken || n.Op == PostDecrToken {
2268 n.X.JS(w)
2269 w.Write(n.Op.Bytes())
2270 return
2271 } else if unary, ok := n.X.(*UnaryExpr); ok && (n.Op == PosToken && (unary.Op == PreIncrToken || unary.Op == PosToken) || n.Op == NegToken && (unary.Op == PreDecrToken || unary.Op == NegToken)) || IsIdentifierName(n.Op) {
2272 w.Write(n.Op.Bytes())
2273 w.Write([]byte(" "))
2274 n.X.JS(w)
2275 return
2276 }
2277 w.Write(n.Op.Bytes())
2278 n.X.JS(w)
2279 }
2280
2281 // JSON writes JSON to writer.
2282 func (n UnaryExpr) JSON(w io.Writer) error {
2283 if lit, ok := n.X.(*LiteralExpr); ok && n.Op == NegToken && (lit.TokenType == DecimalToken || lit.TokenType == IntegerToken) {
2284 w.Write([]byte("-"))
2285 w.Write(lit.Data)
2286 return nil
2287 } else if n.Op == NotToken && lit.TokenType == IntegerToken && (lit.Data[0] == '0' || lit.Data[0] == '1') {
2288 if lit.Data[0] == '0' {
2289 w.Write([]byte("true"))
2290 } else {
2291 w.Write([]byte("false"))
2292 }
2293 return nil
2294 }
2295 js := &strings.Builder{}
2296 n.JS(js)
2297 return fmt.Errorf("%v: unary expression is not valid JSON: %v", ErrInvalidJSON, js.String())
2298 }
2299
2300 // BinaryExpr is a binary expression.
2301 type BinaryExpr struct {
2302 Op TokenType
2303 X, Y IExpr
2304 }
2305
2306 func (n BinaryExpr) String() string {
2307 if IsIdentifierName(n.Op) {
2308 return "(" + n.X.String() + " " + n.Op.String() + " " + n.Y.String() + ")"
2309 }
2310 return "(" + n.X.String() + n.Op.String() + n.Y.String() + ")"
2311 }
2312
2313 // JS writes JavaScript to writer.
2314 func (n BinaryExpr) JS(w io.Writer) {
2315 n.X.JS(w)
2316 w.Write([]byte(" "))
2317 w.Write(n.Op.Bytes())
2318 w.Write([]byte(" "))
2319 n.Y.JS(w)
2320 }
2321
2322 // CondExpr is a conditional expression.
2323 type CondExpr struct {
2324 Cond, X, Y IExpr
2325 }
2326
2327 func (n CondExpr) String() string {
2328 return "(" + n.Cond.String() + " ? " + n.X.String() + " : " + n.Y.String() + ")"
2329 }
2330
2331 // JS writes JavaScript to writer.
2332 func (n CondExpr) JS(w io.Writer) {
2333 n.Cond.JS(w)
2334 w.Write([]byte(" ? "))
2335 n.X.JS(w)
2336 w.Write([]byte(" : "))
2337 n.Y.JS(w)
2338 }
2339
2340 // YieldExpr is a yield expression.
2341 type YieldExpr struct {
2342 Generator bool
2343 X IExpr // can be nil
2344 }
2345
2346 func (n YieldExpr) String() string {
2347 if n.X == nil {
2348 return "(yield)"
2349 }
2350 s := "(yield"
2351 if n.Generator {
2352 s += "*"
2353 }
2354 return s + " " + n.X.String() + ")"
2355 }
2356
2357 // JS writes JavaScript to writer.
2358 func (n YieldExpr) JS(w io.Writer) {
2359 w.Write([]byte("yield"))
2360 if n.X == nil {
2361 return
2362 }
2363 if n.Generator {
2364 w.Write([]byte("*"))
2365 }
2366 w.Write([]byte(" "))
2367 n.X.JS(w)
2368 }
2369
2370 // ArrowFunc is an (async) arrow function.
2371 type ArrowFunc struct {
2372 Async bool
2373 Params Params
2374 Body BlockStmt
2375 }
2376
2377 func (n ArrowFunc) String() string {
2378 s := "("
2379 if n.Async {
2380 s += "async "
2381 }
2382 return s + n.Params.String() + " => " + n.Body.String() + ")"
2383 }
2384
2385 // JS writes JavaScript to writer.
2386 func (n ArrowFunc) JS(w io.Writer) {
2387 if n.Async {
2388 w.Write([]byte("async "))
2389 }
2390 n.Params.JS(w)
2391 w.Write([]byte(" => "))
2392 n.Body.JS(w)
2393 }
2394
2395 // CommaExpr is a series of comma expressions.
2396 type CommaExpr struct {
2397 List []IExpr
2398 }
2399
2400 func (n CommaExpr) String() string {
2401 var s strings.Builder
2402 s.WriteString("(")
2403 for i, item := range n.List {
2404 if i != 0 {
2405 s.WriteString(",")
2406 }
2407 s.WriteString(item.String())
2408 }
2409 return s.String() + ")"
2410 }
2411
2412 // JS writes JavaScript to writer.
2413 func (n CommaExpr) JS(w io.Writer) {
2414 for j, item := range n.List {
2415 if j != 0 {
2416 w.Write([]byte(","))
2417 }
2418 item.JS(w)
2419 }
2420 }
2421
2422 func (v *Var) exprNode() {}
2423 func (n LiteralExpr) exprNode() {}
2424 func (n ArrayExpr) exprNode() {}
2425 func (n ObjectExpr) exprNode() {}
2426 func (n TemplateExpr) exprNode() {}
2427 func (n GroupExpr) exprNode() {}
2428 func (n DotExpr) exprNode() {}
2429 func (n IndexExpr) exprNode() {}
2430 func (n NewTargetExpr) exprNode() {}
2431 func (n ImportMetaExpr) exprNode() {}
2432 func (n NewExpr) exprNode() {}
2433 func (n CallExpr) exprNode() {}
2434 func (n UnaryExpr) exprNode() {}
2435 func (n BinaryExpr) exprNode() {}
2436 func (n CondExpr) exprNode() {}
2437 func (n YieldExpr) exprNode() {}
2438 func (n ArrowFunc) exprNode() {}
2439 func (n CommaExpr) exprNode() {}