Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(99)

Side by Side Diff: lib/src/js/nodes.dart

Issue 1879373004: Implement modular compilation (Closed) Base URL: git@github.com:dart-lang/dev_compiler.git@master
Patch Set: Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « lib/src/js/module_transform.dart ('k') | lib/src/js/precedence.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 part of js_ast;
6
7 abstract class NodeVisitor<T> implements TypeRefVisitor<T> {
8 T visitProgram(Program node);
9
10 T visitBlock(Block node);
11 T visitExpressionStatement(ExpressionStatement node);
12 T visitEmptyStatement(EmptyStatement node);
13 T visitIf(If node);
14 T visitFor(For node);
15 T visitForIn(ForIn node);
16 T visitForOf(ForOf node);
17 T visitWhile(While node);
18 T visitDo(Do node);
19 T visitContinue(Continue node);
20 T visitBreak(Break node);
21 T visitReturn(Return node);
22 T visitThrow(Throw node);
23 T visitTry(Try node);
24 T visitCatch(Catch node);
25 T visitSwitch(Switch node);
26 T visitCase(Case node);
27 T visitDefault(Default node);
28 T visitFunctionDeclaration(FunctionDeclaration node);
29 T visitLabeledStatement(LabeledStatement node);
30 T visitLiteralStatement(LiteralStatement node);
31 T visitDartYield(DartYield node);
32
33 T visitLiteralExpression(LiteralExpression node);
34 T visitVariableDeclarationList(VariableDeclarationList node);
35 T visitAssignment(Assignment node);
36 T visitVariableInitialization(VariableInitialization node);
37 T visitConditional(Conditional cond);
38 T visitNew(New node);
39 T visitCall(Call node);
40 T visitBinary(Binary node);
41 T visitPrefix(Prefix node);
42 T visitPostfix(Postfix node);
43 T visitSpread(Spread node);
44 T visitYield(Yield node);
45
46 T visitIdentifier(Identifier node);
47 T visitThis(This node);
48 T visitSuper(Super node);
49 T visitAccess(PropertyAccess node);
50 T visitRestParameter(RestParameter node);
51
52 T visitNamedFunction(NamedFunction node);
53 T visitFun(Fun node);
54 T visitArrowFun(ArrowFun node);
55
56 T visitLiteralBool(LiteralBool node);
57 T visitLiteralString(LiteralString node);
58 T visitLiteralNumber(LiteralNumber node);
59 T visitLiteralNull(LiteralNull node);
60
61 T visitArrayInitializer(ArrayInitializer node);
62 T visitArrayHole(ArrayHole node);
63 T visitObjectInitializer(ObjectInitializer node);
64 T visitProperty(Property node);
65 T visitRegExpLiteral(RegExpLiteral node);
66 T visitTemplateString(TemplateString node);
67 T visitTaggedTemplate(TaggedTemplate node);
68
69 T visitAwait(Await node);
70
71 T visitClassDeclaration(ClassDeclaration node);
72 T visitClassExpression(ClassExpression node);
73 T visitMethod(Method node);
74
75 T visitImportDeclaration(ImportDeclaration node);
76 T visitExportDeclaration(ExportDeclaration node);
77 T visitExportClause(ExportClause node);
78 T visitNameSpecifier(NameSpecifier node);
79 T visitModule(Module node);
80
81 T visitComment(Comment node);
82 T visitCommentExpression(CommentExpression node);
83
84 T visitInterpolatedExpression(InterpolatedExpression node);
85 T visitInterpolatedLiteral(InterpolatedLiteral node);
86 T visitInterpolatedParameter(InterpolatedParameter node);
87 T visitInterpolatedSelector(InterpolatedSelector node);
88 T visitInterpolatedStatement(InterpolatedStatement node);
89 T visitInterpolatedMethod(InterpolatedMethod node);
90 T visitInterpolatedIdentifier(InterpolatedIdentifier node);
91
92 T visitArrayBindingPattern(ArrayBindingPattern node);
93 T visitObjectBindingPattern(ObjectBindingPattern node);
94 T visitDestructuredVariable(DestructuredVariable node);
95 T visitSimpleBindingPattern(SimpleBindingPattern node);
96 }
97
98 abstract class TypeRefVisitor<T> {
99 T visitQualifiedTypeRef(QualifiedTypeRef node);
100 T visitGenericTypeRef(GenericTypeRef node);
101 T visitUnionTypeRef(UnionTypeRef node);
102 T visitRecordTypeRef(RecordTypeRef node);
103 T visitOptionalTypeRef(OptionalTypeRef node);
104 T visitFunctionTypeRef(FunctionTypeRef node);
105 T visitAnyTypeRef(AnyTypeRef node);
106 T visitUnknownTypeRef(UnknownTypeRef node);
107 T visitArrayTypeRef(ArrayTypeRef node);
108 }
109
110 class BaseVisitor<T> implements NodeVisitor<T> {
111 T visitNode(Node node) {
112 node.visitChildren(this);
113 return null;
114 }
115
116 T visitProgram(Program node) => visitNode(node);
117
118 T visitStatement(Statement node) => visitModuleItem(node);
119 T visitLoop(Loop node) => visitStatement(node);
120 T visitJump(Statement node) => visitStatement(node);
121
122 T visitBlock(Block node) => visitStatement(node);
123 T visitExpressionStatement(ExpressionStatement node)
124 => visitStatement(node);
125 T visitEmptyStatement(EmptyStatement node) => visitStatement(node);
126 T visitIf(If node) => visitStatement(node);
127 T visitFor(For node) => visitLoop(node);
128 T visitForIn(ForIn node) => visitLoop(node);
129 T visitForOf(ForOf node) => visitLoop(node);
130 T visitWhile(While node) => visitLoop(node);
131 T visitDo(Do node) => visitLoop(node);
132 T visitContinue(Continue node) => visitJump(node);
133 T visitBreak(Break node) => visitJump(node);
134 T visitReturn(Return node) => visitJump(node);
135 T visitThrow(Throw node) => visitJump(node);
136 T visitTry(Try node) => visitStatement(node);
137 T visitSwitch(Switch node) => visitStatement(node);
138 T visitFunctionDeclaration(FunctionDeclaration node)
139 => visitStatement(node);
140 T visitLabeledStatement(LabeledStatement node) => visitStatement(node);
141 T visitLiteralStatement(LiteralStatement node) => visitStatement(node);
142
143 T visitCatch(Catch node) => visitNode(node);
144 T visitCase(Case node) => visitNode(node);
145 T visitDefault(Default node) => visitNode(node);
146
147 T visitExpression(Expression node) => visitNode(node);
148
149 T visitLiteralExpression(LiteralExpression node) => visitExpression(node);
150 T visitVariableDeclarationList(VariableDeclarationList node)
151 => visitExpression(node);
152 T visitAssignment(Assignment node) => visitExpression(node);
153 T visitVariableInitialization(VariableInitialization node) {
154 if (node.value != null) {
155 return visitAssignment(node);
156 } else {
157 return visitExpression(node);
158 }
159 }
160 T visitConditional(Conditional node) => visitExpression(node);
161 T visitNew(New node) => visitExpression(node);
162 T visitCall(Call node) => visitExpression(node);
163 T visitBinary(Binary node) => visitExpression(node);
164 T visitPrefix(Prefix node) => visitExpression(node);
165 T visitPostfix(Postfix node) => visitExpression(node);
166 T visitSpread(Spread node) => visitPrefix(node);
167 T visitYield(Yield node) => visitExpression(node);
168 T visitAccess(PropertyAccess node) => visitExpression(node);
169
170 T visitIdentifier(Identifier node) => visitExpression(node);
171 T visitThis(This node) => visitExpression(node);
172 T visitSuper(Super node) => visitExpression(node);
173
174 T visitRestParameter(RestParameter node) => visitNode(node);
175
176 T visitNamedFunction(NamedFunction node) => visitExpression(node);
177 T visitFunctionExpression(FunctionExpression node) => visitExpression(node);
178 T visitFun(Fun node) => visitFunctionExpression(node);
179 T visitArrowFun(ArrowFun node) => visitFunctionExpression(node);
180
181 T visitLiteral(Literal node) => visitExpression(node);
182
183 T visitLiteralBool(LiteralBool node) => visitLiteral(node);
184 T visitLiteralString(LiteralString node) => visitLiteral(node);
185 T visitLiteralNumber(LiteralNumber node) => visitLiteral(node);
186 T visitLiteralNull(LiteralNull node) => visitLiteral(node);
187
188 T visitArrayInitializer(ArrayInitializer node) => visitExpression(node);
189 T visitArrayHole(ArrayHole node) => visitExpression(node);
190 T visitObjectInitializer(ObjectInitializer node) => visitExpression(node);
191 T visitProperty(Property node) => visitNode(node);
192 T visitRegExpLiteral(RegExpLiteral node) => visitExpression(node);
193 T visitTemplateString(TemplateString node) => visitExpression(node);
194 T visitTaggedTemplate(TaggedTemplate node) => visitExpression(node);
195
196 T visitClassDeclaration(ClassDeclaration node) => visitStatement(node);
197 T visitClassExpression(ClassExpression node) => visitExpression(node);
198 T visitMethod(Method node) => visitProperty(node);
199
200 T visitModuleItem(ModuleItem node) => visitNode(node);
201 T visitImportDeclaration(ImportDeclaration node) => visitModuleItem(node);
202 T visitExportDeclaration(ExportDeclaration node) => visitModuleItem(node);
203 T visitExportClause(ExportClause node) => visitNode(node);
204 T visitNameSpecifier(NameSpecifier node) => visitNode(node);
205 T visitModule(Module node) => visitNode(node);
206
207 T visitInterpolatedNode(InterpolatedNode node) => visitNode(node);
208
209 T visitInterpolatedExpression(InterpolatedExpression node)
210 => visitInterpolatedNode(node);
211 T visitInterpolatedLiteral(InterpolatedLiteral node)
212 => visitInterpolatedNode(node);
213 T visitInterpolatedParameter(InterpolatedParameter node)
214 => visitInterpolatedNode(node);
215 T visitInterpolatedSelector(InterpolatedSelector node)
216 => visitInterpolatedNode(node);
217 T visitInterpolatedStatement(InterpolatedStatement node)
218 => visitInterpolatedNode(node);
219 T visitInterpolatedMethod(InterpolatedMethod node)
220 => visitInterpolatedNode(node);
221 T visitInterpolatedIdentifier(InterpolatedIdentifier node)
222 => visitInterpolatedNode(node);
223
224 // Ignore comments by default.
225 T visitComment(Comment node) => null;
226 T visitCommentExpression(CommentExpression node) => null;
227
228 T visitAwait(Await node) => visitExpression(node);
229 T visitDartYield(DartYield node) => visitStatement(node);
230
231 T visitBindingPattern(BindingPattern node) => visitNode(node);
232 T visitArrayBindingPattern(ArrayBindingPattern node)
233 => visitBindingPattern(node);
234 T visitObjectBindingPattern(ObjectBindingPattern node)
235 => visitBindingPattern(node);
236 T visitDestructuredVariable(DestructuredVariable node) => visitNode(node);
237 T visitSimpleBindingPattern(SimpleBindingPattern node) => visitNode(node);
238
239 T visitTypeRef(TypeRef node) => visitNode(node);
240 T visitQualifiedTypeRef(QualifiedTypeRef node) => visitTypeRef(node);
241 T visitGenericTypeRef(GenericTypeRef node) => visitTypeRef(node);
242 T visitOptionalTypeRef(OptionalTypeRef node) => visitTypeRef(node);
243 T visitRecordTypeRef(RecordTypeRef node) => visitTypeRef(node);
244 T visitUnionTypeRef(UnionTypeRef node) => visitTypeRef(node);
245 T visitFunctionTypeRef(FunctionTypeRef node) => visitTypeRef(node);
246 T visitAnyTypeRef(AnyTypeRef node) => visitTypeRef(node);
247 T visitUnknownTypeRef(UnknownTypeRef node) => visitTypeRef(node);
248 T visitArrayTypeRef(ArrayTypeRef node) => visitTypeRef(node);
249 }
250
251 abstract class Node {
252 /// Sets the source location of this node. For performance reasons, we allow
253 /// setting this after construction.
254 Object sourceInformation;
255
256 ClosureAnnotation _closureAnnotation;
257 /// Closure annotation of this node.
258 ClosureAnnotation get closureAnnotation => _closureAnnotation;
259
260 accept(NodeVisitor visitor);
261 void visitChildren(NodeVisitor visitor);
262
263 // Shallow clone of node. Does not clone positions since the only use of this
264 // private method is create a copy with a new position.
265 Node _clone();
266
267 withClosureAnnotation(ClosureAnnotation closureAnnotation) {
268 if (this.closureAnnotation == closureAnnotation) return this;
269
270 return _clone()
271 ..sourceInformation = sourceInformation
272 .._closureAnnotation = closureAnnotation;
273 }
274 // Returns a node equivalent to [this], but with new source position and end
275 // source position.
276 Node withSourceInformation(sourceInformation) {
277 if (sourceInformation == this.sourceInformation) {
278 return this;
279 }
280 Node clone = _clone();
281 // TODO(sra): Should existing data be 'sticky' if we try to overwrite with
282 // `null`?
283 clone.sourceInformation = sourceInformation;
284 return clone;
285 }
286
287 bool get isCommaOperator => false;
288
289 Statement toStatement() {
290 throw new UnsupportedError('toStatement');
291 }
292 Statement toReturn() {
293 throw new UnsupportedError('toReturn');
294 }
295
296 // For debugging
297 String toString() {
298 var context = new SimpleJavaScriptPrintingContext();
299 var opts = new JavaScriptPrintingOptions(allowKeywordsInProperties: true);
300 context.buffer.write('js_ast `');
301 accept(new Printer(opts, context));
302 context.buffer.write('`');
303 return context.getText();
304 }
305 }
306
307 class Program extends Node {
308 /// Script tag hash-bang, e.g. `#!/usr/bin/env node`
309 final String scriptTag;
310
311 /// Top-level statements in the program.
312 final List<ModuleItem> body;
313
314 Program(this.body, {this.scriptTag});
315
316 accept(NodeVisitor visitor) => visitor.visitProgram(this);
317 void visitChildren(NodeVisitor visitor) {
318 for (ModuleItem statement in body) statement.accept(visitor);
319 }
320 Program _clone() => new Program(body);
321 }
322
323 abstract class Statement extends ModuleItem {
324 Statement toStatement() => this;
325 Statement toReturn() => new Block([this, new Return()]);
326 }
327
328 class Block extends Statement {
329 final List<Statement> statements;
330
331 /// True to preserve this [Block] for scoping reasons.
332 final bool isScope;
333
334 Block(this.statements, {this.isScope: false}) {
335 assert(!statements.any((s) => s is! Statement));
336 }
337 Block.empty() : statements = <Statement>[], isScope = false;
338
339 accept(NodeVisitor visitor) => visitor.visitBlock(this);
340 void visitChildren(NodeVisitor visitor) {
341 for (Statement statement in statements) statement.accept(visitor);
342 }
343 Block _clone() => new Block(statements);
344 }
345
346 class ExpressionStatement extends Statement {
347 final Expression expression;
348 ExpressionStatement(this.expression);
349
350 accept(NodeVisitor visitor) => visitor.visitExpressionStatement(this);
351 void visitChildren(NodeVisitor visitor) { expression.accept(visitor); }
352 ExpressionStatement _clone() => new ExpressionStatement(expression);
353 }
354
355 class EmptyStatement extends Statement {
356 EmptyStatement();
357
358 accept(NodeVisitor visitor) => visitor.visitEmptyStatement(this);
359 void visitChildren(NodeVisitor visitor) {}
360 EmptyStatement _clone() => new EmptyStatement();
361 }
362
363 class If extends Statement {
364 final Expression condition;
365 final Node then;
366 final Node otherwise;
367
368 If(this.condition, this.then, this.otherwise);
369 If.noElse(this.condition, this.then) : this.otherwise = null;
370
371 bool get hasElse => otherwise != null;
372
373 accept(NodeVisitor visitor) => visitor.visitIf(this);
374
375 void visitChildren(NodeVisitor visitor) {
376 condition.accept(visitor);
377 then.accept(visitor);
378 if (otherwise != null) otherwise.accept(visitor);
379 }
380
381 If _clone() => new If(condition, then, otherwise);
382 }
383
384 abstract class Loop extends Statement {
385 final Statement body;
386 Loop(this.body);
387 }
388
389 class For extends Loop {
390 final Expression init;
391 final Expression condition;
392 final Expression update;
393
394 For(this.init, this.condition, this.update, Statement body) : super(body);
395
396 accept(NodeVisitor visitor) => visitor.visitFor(this);
397
398 void visitChildren(NodeVisitor visitor) {
399 if (init != null) init.accept(visitor);
400 if (condition != null) condition.accept(visitor);
401 if (update != null) update.accept(visitor);
402 body.accept(visitor);
403 }
404
405 For _clone() => new For(init, condition, update, body);
406 }
407
408 class ForIn extends Loop {
409 // Note that [VariableDeclarationList] is a subclass of [Expression].
410 // Therefore we can type the leftHandSide as [Expression].
411 final Expression leftHandSide;
412 final Expression object;
413
414 ForIn(this.leftHandSide, this.object, Statement body) : super(body);
415
416 accept(NodeVisitor visitor) => visitor.visitForIn(this);
417
418 void visitChildren(NodeVisitor visitor) {
419 leftHandSide.accept(visitor);
420 object.accept(visitor);
421 body.accept(visitor);
422 }
423
424 ForIn _clone() => new ForIn(leftHandSide, object, body);
425 }
426
427 class ForOf extends Loop {
428 // Note that [VariableDeclarationList] is a subclass of [Expression].
429 // Therefore we can type the leftHandSide as [Expression].
430 final Expression leftHandSide;
431 final Expression iterable;
432
433 ForOf(this.leftHandSide, this.iterable, Statement body) : super(body);
434
435 accept(NodeVisitor visitor) => visitor.visitForOf(this);
436
437 void visitChildren(NodeVisitor visitor) {
438 leftHandSide.accept(visitor);
439 iterable.accept(visitor);
440 body.accept(visitor);
441 }
442
443 ForIn _clone() => new ForIn(leftHandSide, iterable, body);
444 }
445
446 class While extends Loop {
447 final Node condition;
448
449 While(this.condition, Statement body) : super(body);
450
451 accept(NodeVisitor visitor) => visitor.visitWhile(this);
452
453 void visitChildren(NodeVisitor visitor) {
454 condition.accept(visitor);
455 body.accept(visitor);
456 }
457
458 While _clone() => new While(condition, body);
459 }
460
461 class Do extends Loop {
462 final Expression condition;
463
464 Do(Statement body, this.condition) : super(body);
465
466 accept(NodeVisitor visitor) => visitor.visitDo(this);
467
468 void visitChildren(NodeVisitor visitor) {
469 body.accept(visitor);
470 condition.accept(visitor);
471 }
472
473 Do _clone() => new Do(body, condition);
474 }
475
476 class Continue extends Statement {
477 final String targetLabel; // Can be null.
478
479 Continue(this.targetLabel);
480
481 accept(NodeVisitor visitor) => visitor.visitContinue(this);
482 void visitChildren(NodeVisitor visitor) {}
483
484 Continue _clone() => new Continue(targetLabel);
485 }
486
487 class Break extends Statement {
488 final String targetLabel; // Can be null.
489
490 Break(this.targetLabel);
491
492 accept(NodeVisitor visitor) => visitor.visitBreak(this);
493 void visitChildren(NodeVisitor visitor) {}
494
495 Break _clone() => new Break(targetLabel);
496 }
497
498 class Return extends Statement {
499 final Expression value; // Can be null.
500
501 Return([this.value = null]);
502
503 Statement toReturn() => this;
504
505 accept(NodeVisitor visitor) => visitor.visitReturn(this);
506
507 void visitChildren(NodeVisitor visitor) {
508 if (value != null) value.accept(visitor);
509 }
510
511 Return _clone() => new Return(value);
512
513 static bool foundIn(Node node) {
514 _returnFinder.found = false;
515 node.accept(_returnFinder);
516 return _returnFinder.found;
517 }
518 }
519
520 final _returnFinder = new _ReturnFinder();
521 class _ReturnFinder extends BaseVisitor {
522 bool found = false;
523 visitReturn(Return node) {
524 found = true;
525 }
526 visitNode(Node node) {
527 if (!found) super.visitNode(node);
528 }
529 }
530
531
532 class Throw extends Statement {
533 final Expression expression;
534
535 Throw(this.expression);
536
537 accept(NodeVisitor visitor) => visitor.visitThrow(this);
538
539 void visitChildren(NodeVisitor visitor) {
540 expression.accept(visitor);
541 }
542
543 Throw _clone() => new Throw(expression);
544 }
545
546 class Try extends Statement {
547 final Block body;
548 final Catch catchPart; // Can be null if [finallyPart] is non-null.
549 final Block finallyPart; // Can be null if [catchPart] is non-null.
550
551 Try(this.body, this.catchPart, this.finallyPart) {
552 assert(catchPart != null || finallyPart != null);
553 }
554
555 accept(NodeVisitor visitor) => visitor.visitTry(this);
556
557 void visitChildren(NodeVisitor visitor) {
558 body.accept(visitor);
559 if (catchPart != null) catchPart.accept(visitor);
560 if (finallyPart != null) finallyPart.accept(visitor);
561 }
562
563 Try _clone() => new Try(body, catchPart, finallyPart);
564 }
565
566 class Catch extends Node {
567 final Identifier declaration;
568 final Block body;
569
570 Catch(this.declaration, this.body);
571
572 accept(NodeVisitor visitor) => visitor.visitCatch(this);
573
574 void visitChildren(NodeVisitor visitor) {
575 declaration.accept(visitor);
576 body.accept(visitor);
577 }
578
579 Catch _clone() => new Catch(declaration, body);
580 }
581
582 class Switch extends Statement {
583 final Expression key;
584 final List<SwitchClause> cases;
585
586 Switch(this.key, this.cases);
587
588 accept(NodeVisitor visitor) => visitor.visitSwitch(this);
589
590 void visitChildren(NodeVisitor visitor) {
591 key.accept(visitor);
592 for (SwitchClause clause in cases) clause.accept(visitor);
593 }
594
595 Switch _clone() => new Switch(key, cases);
596 }
597
598 abstract class SwitchClause extends Node {
599 final Block body;
600
601 SwitchClause(this.body);
602 }
603
604 class Case extends SwitchClause {
605 final Expression expression;
606
607 Case(this.expression, Block body) : super(body);
608
609 accept(NodeVisitor visitor) => visitor.visitCase(this);
610
611 void visitChildren(NodeVisitor visitor) {
612 expression.accept(visitor);
613 body.accept(visitor);
614 }
615
616 Case _clone() => new Case(expression, body);
617 }
618
619 class Default extends SwitchClause {
620 Default(Block body) : super(body);
621
622 accept(NodeVisitor visitor) => visitor.visitDefault(this);
623
624 void visitChildren(NodeVisitor visitor) {
625 body.accept(visitor);
626 }
627
628 Default _clone() => new Default(body);
629 }
630
631 class FunctionDeclaration extends Statement {
632 final Identifier name;
633 final Fun function;
634
635 FunctionDeclaration(this.name, this.function);
636
637 accept(NodeVisitor visitor) => visitor.visitFunctionDeclaration(this);
638
639 void visitChildren(NodeVisitor visitor) {
640 name.accept(visitor);
641 function.accept(visitor);
642 }
643
644 FunctionDeclaration _clone() => new FunctionDeclaration(name, function);
645 }
646
647 class LabeledStatement extends Statement {
648 final String label;
649 final Statement body;
650
651 LabeledStatement(this.label, this.body);
652
653 accept(NodeVisitor visitor) => visitor.visitLabeledStatement(this);
654
655 void visitChildren(NodeVisitor visitor) {
656 body.accept(visitor);
657 }
658
659 LabeledStatement _clone() => new LabeledStatement(label, body);
660 }
661
662 class LiteralStatement extends Statement {
663 final String code;
664
665 LiteralStatement(this.code);
666
667 accept(NodeVisitor visitor) => visitor.visitLiteralStatement(this);
668 void visitChildren(NodeVisitor visitor) { }
669
670 LiteralStatement _clone() => new LiteralStatement(code);
671 }
672
673 // Not a real JavaScript node, but represents the yield statement from a dart
674 // program translated to JavaScript.
675 class DartYield extends Statement {
676 final Expression expression;
677
678 final bool hasStar;
679
680 DartYield(this.expression, this.hasStar);
681
682 accept(NodeVisitor visitor) => visitor.visitDartYield(this);
683
684 void visitChildren(NodeVisitor visitor) {
685 expression.accept(visitor);
686 }
687
688 DartYield _clone() => new DartYield(expression, hasStar);
689 }
690
691 abstract class Expression extends Node {
692 Expression();
693
694 factory Expression.binary(List<Expression> exprs, String op) {
695 Expression comma = null;
696 for (var node in exprs) {
697 comma = (comma == null) ? node : new Binary(op, comma, node);
698 }
699 return comma;
700 }
701
702 int get precedenceLevel;
703
704 Statement toStatement() => new ExpressionStatement(toVoidExpression());
705 Statement toReturn() => new Return(this);
706 Statement toYieldStatement({bool star: false}) =>
707 new ExpressionStatement(new Yield(this, star: star));
708
709 Expression toVoidExpression() => this;
710 Expression toAssignExpression(Expression left) => new Assignment(left, this);
711 Statement toVariableDeclaration(Identifier name) =>
712 new VariableDeclarationList('let',
713 [new VariableInitialization(name, this)]).toStatement();
714 }
715
716 class LiteralExpression extends Expression {
717 final String template;
718 final List<Expression> inputs;
719
720 LiteralExpression(this.template) : inputs = const [];
721 LiteralExpression.withData(this.template, this.inputs);
722
723 accept(NodeVisitor visitor) => visitor.visitLiteralExpression(this);
724
725 void visitChildren(NodeVisitor visitor) {
726 if (inputs != null) {
727 for (Expression expr in inputs) expr.accept(visitor);
728 }
729 }
730
731 LiteralExpression _clone() =>
732 new LiteralExpression.withData(template, inputs);
733
734 // Code that uses JS must take care of operator precedences, and
735 // put parenthesis if needed.
736 int get precedenceLevel => PRIMARY;
737 }
738
739 /**
740 * [VariableDeclarationList] is a subclass of [Expression] to simplify the
741 * AST.
742 */
743 class VariableDeclarationList extends Expression {
744 /** The `var` or `let` keyword used for this variable declaration list. */
745 final String keyword;
746 final List<VariableInitialization> declarations;
747
748 VariableDeclarationList(this.keyword, this.declarations);
749
750 accept(NodeVisitor visitor) => visitor.visitVariableDeclarationList(this);
751
752 void visitChildren(NodeVisitor visitor) {
753 for (VariableInitialization declaration in declarations) {
754 declaration.accept(visitor);
755 }
756 }
757
758 VariableDeclarationList _clone() =>
759 new VariableDeclarationList(keyword, declarations);
760
761 int get precedenceLevel => EXPRESSION;
762 }
763
764 class Assignment extends Expression {
765 final Expression leftHandSide;
766 final String op; // Null, if the assignment is not compound.
767 final Expression value; // May be null, for [VariableInitialization]s.
768
769 Assignment(leftHandSide, value)
770 : this.compound(leftHandSide, null, value);
771 Assignment.compound(this.leftHandSide, this.op, this.value);
772
773 int get precedenceLevel => ASSIGNMENT;
774
775 bool get isCompound => op != null;
776
777 accept(NodeVisitor visitor) => visitor.visitAssignment(this);
778
779 void visitChildren(NodeVisitor visitor) {
780 leftHandSide.accept(visitor);
781 if (value != null) value.accept(visitor);
782 }
783
784 Assignment _clone() =>
785 new Assignment.compound(leftHandSide, op, value);
786 }
787
788 class VariableInitialization extends Assignment {
789 /** [value] may be null. */
790 VariableInitialization(VariableBinding declaration, Expression value)
791 : super(declaration, value);
792
793 VariableBinding get declaration => leftHandSide;
794
795 accept(NodeVisitor visitor) => visitor.visitVariableInitialization(this);
796
797 VariableInitialization _clone() =>
798 new VariableInitialization(declaration, value);
799 }
800
801 abstract class VariableBinding extends Expression {
802 }
803
804 class DestructuredVariable extends Expression implements Parameter {
805 /// [LiteralString] or [Identifier].
806 final Expression name;
807 final BindingPattern structure;
808 final Expression defaultValue;
809 final TypeRef type;
810 DestructuredVariable({this.name, this.structure, this.defaultValue, this.type} ) {
811 assert(name != null || structure != null);
812 }
813
814 accept(NodeVisitor visitor) => visitor.visitDestructuredVariable(this);
815 void visitChildren(NodeVisitor visitor) {
816 name?.accept(visitor);
817 structure?.accept(visitor);
818 defaultValue?.accept(visitor);
819 }
820
821 /// Avoid parenthesis when pretty-printing.
822 @override int get precedenceLevel => PRIMARY;
823 @override Node _clone() =>
824 new DestructuredVariable(
825 name: name, structure: structure, defaultValue: defaultValue);
826 }
827
828 abstract class BindingPattern extends Expression implements VariableBinding {
829 final List<DestructuredVariable> variables;
830 BindingPattern(this.variables);
831
832 void visitChildren(NodeVisitor visitor) {
833 for (DestructuredVariable v in variables) v.accept(visitor);
834 }
835 }
836
837 class SimpleBindingPattern extends BindingPattern {
838 final Identifier name;
839 SimpleBindingPattern(Identifier name)
840 : super([new DestructuredVariable(name: name)]), this.name = name;
841 accept(NodeVisitor visitor) => visitor.visitSimpleBindingPattern(this);
842
843 /// Avoid parenthesis when pretty-printing.
844 @override int get precedenceLevel => PRIMARY;
845 @override Node _clone() => new SimpleBindingPattern(name);
846 }
847
848 class ObjectBindingPattern extends BindingPattern {
849 ObjectBindingPattern(List<DestructuredVariable> variables)
850 : super(variables);
851 accept(NodeVisitor visitor) => visitor.visitObjectBindingPattern(this);
852
853 /// Avoid parenthesis when pretty-printing.
854 @override int get precedenceLevel => PRIMARY;
855 @override Node _clone() => new ObjectBindingPattern(variables);
856 }
857
858 class ArrayBindingPattern extends BindingPattern {
859 ArrayBindingPattern(List<DestructuredVariable> variables)
860 : super(variables);
861 accept(NodeVisitor visitor) => visitor.visitArrayBindingPattern(this);
862
863 /// Avoid parenthesis when pretty-printing.
864 @override int get precedenceLevel => PRIMARY;
865 @override Node _clone() => new ObjectBindingPattern(variables);
866 }
867
868 class Conditional extends Expression {
869 final Expression condition;
870 final Expression then;
871 final Expression otherwise;
872
873 Conditional(this.condition, this.then, this.otherwise);
874
875 accept(NodeVisitor visitor) => visitor.visitConditional(this);
876
877 void visitChildren(NodeVisitor visitor) {
878 condition.accept(visitor);
879 then.accept(visitor);
880 otherwise.accept(visitor);
881 }
882
883 Conditional _clone() => new Conditional(condition, then, otherwise);
884
885 int get precedenceLevel => ASSIGNMENT;
886 }
887
888 class Call extends Expression {
889 Expression target;
890 List<Expression> arguments;
891
892 Call(this.target, this.arguments);
893
894 accept(NodeVisitor visitor) => visitor.visitCall(this);
895
896 void visitChildren(NodeVisitor visitor) {
897 target.accept(visitor);
898 for (Expression arg in arguments) arg.accept(visitor);
899 }
900
901 Call _clone() => new Call(target, arguments);
902
903 int get precedenceLevel => CALL;
904 }
905
906 class New extends Call {
907 New(Expression cls, List<Expression> arguments) : super(cls, arguments);
908
909 accept(NodeVisitor visitor) => visitor.visitNew(this);
910
911 New _clone() => new New(target, arguments);
912
913 int get precedenceLevel => ACCESS;
914 }
915
916 class Binary extends Expression {
917 final String op;
918 final Expression left;
919 final Expression right;
920
921 Binary(this.op, this.left, this.right);
922
923 accept(NodeVisitor visitor) => visitor.visitBinary(this);
924
925 Binary _clone() => new Binary(op, left, right);
926
927 void visitChildren(NodeVisitor visitor) {
928 left.accept(visitor);
929 right.accept(visitor);
930 }
931
932 bool get isCommaOperator => op == ',';
933
934 Expression toVoidExpression() {
935 if (!isCommaOperator) return super.toVoidExpression();
936 var l = left.toVoidExpression();
937 var r = right.toVoidExpression();
938 if (l == left && r == right) return this;
939 return new Binary(',', l, r);
940 }
941
942 Statement toStatement() {
943 if (!isCommaOperator) return super.toStatement();
944 return new Block([left.toStatement(), right.toStatement()]);
945 }
946
947 Statement toReturn() {
948 if (!isCommaOperator) return super.toReturn();
949 return new Block([left.toStatement(), right.toReturn()]);
950 }
951
952 Statement toYieldStatement({bool star: false}) {
953 if (!isCommaOperator) return super.toYieldStatement(star: star);
954 return new Block([left.toStatement(), right.toYieldStatement(star: star)]);
955 }
956
957 List<Expression> commaToExpressionList() {
958 if (!isCommaOperator) throw new StateError('not a comma expression');
959 var exprs = [];
960 _flattenComma(exprs, left);
961 _flattenComma(exprs, right);
962 return exprs;
963 }
964
965 static void _flattenComma(List<Expression> exprs, Expression node) {
966 if (node is Binary && node.isCommaOperator) {
967 _flattenComma(exprs, node.left);
968 _flattenComma(exprs, node.right);
969 } else {
970 exprs.add(node);
971 }
972 }
973
974 int get precedenceLevel {
975 // TODO(floitsch): switch to constant map.
976 switch (op) {
977 case "*":
978 case "/":
979 case "%":
980 return MULTIPLICATIVE;
981 case "+":
982 case "-":
983 return ADDITIVE;
984 case "<<":
985 case ">>":
986 case ">>>":
987 return SHIFT;
988 case "<":
989 case ">":
990 case "<=":
991 case ">=":
992 case "instanceof":
993 case "in":
994 return RELATIONAL;
995 case "==":
996 case "===":
997 case "!=":
998 case "!==":
999 return EQUALITY;
1000 case "&":
1001 return BIT_AND;
1002 case "^":
1003 return BIT_XOR;
1004 case "|":
1005 return BIT_OR;
1006 case "&&":
1007 return LOGICAL_AND;
1008 case "||":
1009 return LOGICAL_OR;
1010 case ',':
1011 return EXPRESSION;
1012 default:
1013 throw "Internal Error: Unhandled binary operator: $op";
1014 }
1015 }
1016 }
1017
1018 class Prefix extends Expression {
1019 final String op;
1020 final Expression argument;
1021
1022 Prefix(this.op, this.argument);
1023
1024 accept(NodeVisitor visitor) => visitor.visitPrefix(this);
1025
1026 Prefix _clone() => new Prefix(op, argument);
1027
1028 void visitChildren(NodeVisitor visitor) {
1029 argument.accept(visitor);
1030 }
1031
1032 int get precedenceLevel => UNARY;
1033 }
1034
1035 // SpreadElement isn't really a prefix expression, as it can only appear in
1036 // certain places such as ArgumentList and BindingPattern, but we pretend
1037 // it is for simplicity's sake.
1038 class Spread extends Prefix {
1039 Spread(Expression operand) : super('...', operand);
1040 int get precedenceLevel => SPREAD;
1041
1042 accept(NodeVisitor visitor) => visitor.visitSpread(this);
1043 Spread _clone() => new Spread(argument);
1044 }
1045
1046 class Postfix extends Expression {
1047 final String op;
1048 final Expression argument;
1049
1050 Postfix(this.op, this.argument);
1051
1052 accept(NodeVisitor visitor) => visitor.visitPostfix(this);
1053
1054 Postfix _clone() => new Postfix(op, argument);
1055
1056 void visitChildren(NodeVisitor visitor) {
1057 argument.accept(visitor);
1058 }
1059
1060 int get precedenceLevel => UNARY;
1061 }
1062
1063 abstract class Parameter implements Expression, VariableBinding {
1064 TypeRef get type;
1065 }
1066
1067 class Identifier extends Expression implements Parameter, VariableBinding {
1068 final String name;
1069 final bool allowRename;
1070 final TypeRef type;
1071
1072 Identifier(this.name, {this.allowRename: true, this.type}) {
1073 if (!_identifierRE.hasMatch(name)) {
1074 throw new ArgumentError.value(name, "name", "not a valid identifier");
1075 }
1076 }
1077 static RegExp _identifierRE = new RegExp(r'^[A-Za-z_$][A-Za-z_$0-9]*$');
1078
1079 Identifier _clone() =>
1080 new Identifier(name, allowRename: allowRename);
1081 accept(NodeVisitor visitor) => visitor.visitIdentifier(this);
1082 int get precedenceLevel => PRIMARY;
1083 void visitChildren(NodeVisitor visitor) {}
1084 }
1085
1086 // This is an expression for convenience in the AST.
1087 class RestParameter extends Expression implements Parameter {
1088 final Identifier parameter;
1089 TypeRef get type => null;
1090
1091 RestParameter(this.parameter);
1092
1093 RestParameter _clone() => new RestParameter(parameter);
1094 accept(NodeVisitor visitor) => visitor.visitRestParameter(this);
1095 void visitChildren(NodeVisitor visitor) {
1096 parameter.accept(visitor);
1097 }
1098 int get precedenceLevel => PRIMARY;
1099 }
1100
1101 class This extends Expression {
1102 accept(NodeVisitor visitor) => visitor.visitThis(this);
1103 This _clone() => new This();
1104 int get precedenceLevel => PRIMARY;
1105 void visitChildren(NodeVisitor visitor) {}
1106
1107 static bool foundIn(Node node) {
1108 _thisFinder.found = false;
1109 node.accept(_thisFinder);
1110 return _thisFinder.found;
1111 }
1112 }
1113
1114 final _thisFinder = new _ThisFinder();
1115 class _ThisFinder extends BaseVisitor {
1116 bool found = false;
1117 visitThis(This node) {
1118 found = true;
1119 }
1120 visitNode(Node node) {
1121 if (!found) super.visitNode(node);
1122 }
1123 }
1124
1125
1126 // `super` is more restricted in the ES6 spec, but for simplicity we accept
1127 // it anywhere that `this` is accepted.
1128 class Super extends Expression {
1129 accept(NodeVisitor visitor) => visitor.visitSuper(this);
1130 Super _clone() => new Super();
1131 int get precedenceLevel => PRIMARY;
1132 void visitChildren(NodeVisitor visitor) {}
1133 }
1134
1135 class NamedFunction extends Expression {
1136 final Identifier name;
1137 final Fun function;
1138
1139 NamedFunction(this.name, this.function);
1140
1141 accept(NodeVisitor visitor) => visitor.visitNamedFunction(this);
1142
1143 void visitChildren(NodeVisitor visitor) {
1144 name.accept(visitor);
1145 function.accept(visitor);
1146 }
1147 NamedFunction _clone() => new NamedFunction(name, function);
1148
1149 int get precedenceLevel => PRIMARY_LOW_PRECEDENCE;
1150 }
1151
1152 abstract class FunctionExpression extends Expression {
1153 List<Parameter> get params;
1154
1155 get body; // Expression or block
1156 /// Type parameters passed to this generic function, if any. `null` otherwise.
1157 // TODO(ochafik): Support type bounds.
1158 List<Identifier> get typeParams;
1159 /// Return type of this function, if any. `null` otherwise.
1160 TypeRef get returnType;
1161 }
1162
1163 class Fun extends FunctionExpression {
1164 final List<Parameter> params;
1165 final Block body;
1166 @override final List<Identifier> typeParams;
1167 @override final TypeRef returnType;
1168 /** Whether this is a JS generator (`function*`) that may contain `yield`. */
1169 final bool isGenerator;
1170
1171 final AsyncModifier asyncModifier;
1172
1173 Fun(this.params, this.body, {this.isGenerator: false,
1174 this.asyncModifier: const AsyncModifier.sync(),
1175 this.typeParams, this.returnType});
1176
1177 accept(NodeVisitor visitor) => visitor.visitFun(this);
1178
1179 void visitChildren(NodeVisitor visitor) {
1180 for (Parameter param in params) param.accept(visitor);
1181 body.accept(visitor);
1182 }
1183
1184 Fun _clone() => new Fun(params, body,
1185 isGenerator: isGenerator, asyncModifier: asyncModifier);
1186
1187 int get precedenceLevel => PRIMARY_LOW_PRECEDENCE;
1188 }
1189
1190 class ArrowFun extends FunctionExpression {
1191 final List<Parameter> params;
1192 final body; // Expression or Block
1193 @override final List<Identifier> typeParams;
1194 @override final TypeRef returnType;
1195
1196 ArrowFun(this.params, this.body, {this.typeParams, this.returnType});
1197
1198 accept(NodeVisitor visitor) => visitor.visitArrowFun(this);
1199
1200 void visitChildren(NodeVisitor visitor) {
1201 for (Parameter param in params) param.accept(visitor);
1202 body.accept(visitor);
1203 }
1204
1205 int get precedenceLevel => PRIMARY_LOW_PRECEDENCE;
1206
1207 ArrowFun _clone() => new ArrowFun(params, body);
1208 }
1209
1210 /**
1211 * The Dart sync, sync*, async, and async* modifier.
1212 * See [DartYield].
1213 *
1214 * This is not used for JS functions.
1215 */
1216 class AsyncModifier {
1217 final bool isAsync;
1218 final bool isYielding;
1219 final String description;
1220
1221 const AsyncModifier.sync()
1222 : isAsync = false,
1223 isYielding = false,
1224 description = "sync";
1225 const AsyncModifier.async()
1226 : isAsync = true,
1227 isYielding = false,
1228 description = "async";
1229 const AsyncModifier.asyncStar()
1230 : isAsync = true,
1231 isYielding = true,
1232 description = "async*";
1233 const AsyncModifier.syncStar()
1234 : isAsync = false,
1235 isYielding = true,
1236 description = "sync*";
1237 toString() => description;
1238 }
1239
1240 class PropertyAccess extends Expression {
1241 final Expression receiver;
1242 final Expression selector;
1243
1244 PropertyAccess(this.receiver, this.selector);
1245 PropertyAccess.field(this.receiver, String fieldName)
1246 : selector = new LiteralString('"$fieldName"');
1247 PropertyAccess.indexed(this.receiver, int index)
1248 : selector = new LiteralNumber('$index');
1249
1250 accept(NodeVisitor visitor) => visitor.visitAccess(this);
1251
1252 void visitChildren(NodeVisitor visitor) {
1253 receiver.accept(visitor);
1254 selector.accept(visitor);
1255 }
1256
1257 PropertyAccess _clone() => new PropertyAccess(receiver, selector);
1258
1259 int get precedenceLevel => ACCESS;
1260 }
1261
1262 abstract class Literal extends Expression {
1263 void visitChildren(NodeVisitor visitor) {}
1264
1265 int get precedenceLevel => PRIMARY;
1266 }
1267
1268 class LiteralBool extends Literal {
1269 final bool value;
1270
1271 LiteralBool(this.value);
1272
1273 accept(NodeVisitor visitor) => visitor.visitLiteralBool(this);
1274 // [visitChildren] inherited from [Literal].
1275 LiteralBool _clone() => new LiteralBool(value);
1276 }
1277
1278 class LiteralNull extends Literal {
1279 LiteralNull();
1280
1281 accept(NodeVisitor visitor) => visitor.visitLiteralNull(this);
1282 LiteralNull _clone() => new LiteralNull();
1283 }
1284
1285 class LiteralString extends Literal {
1286 final String value;
1287
1288 /**
1289 * Constructs a LiteralString from a string value.
1290 *
1291 * The constructor does not add the required quotes. If [value] is not
1292 * surrounded by quotes and property escaped, the resulting object is invalid
1293 * as a JS value.
1294 *
1295 * TODO(sra): Introduce variants for known valid strings that don't allocate a
1296 * new string just to add quotes.
1297 */
1298 LiteralString(this.value);
1299
1300 /// Gets the value inside the string without the beginning and end quotes.
1301 String get valueWithoutQuotes => value.substring(1, value.length - 1);
1302
1303 accept(NodeVisitor visitor) => visitor.visitLiteralString(this);
1304 LiteralString _clone() => new LiteralString(value);
1305 }
1306
1307 class LiteralNumber extends Literal {
1308 final String value; // Must be a valid JavaScript number literal.
1309
1310 LiteralNumber(this.value);
1311
1312 accept(NodeVisitor visitor) => visitor.visitLiteralNumber(this);
1313 LiteralNumber _clone() => new LiteralNumber(value);
1314
1315 /**
1316 * Use a different precedence level depending on whether the value contains a
1317 * dot to ensure we generate `(1).toString()` and `1.0.toString()`.
1318 */
1319 int get precedenceLevel => value.contains('.') ? PRIMARY : UNARY;
1320 }
1321
1322 class ArrayInitializer extends Expression {
1323 final List<Expression> elements;
1324 final bool multiline;
1325
1326 ArrayInitializer(this.elements, {this.multiline: false});
1327
1328 accept(NodeVisitor visitor) => visitor.visitArrayInitializer(this);
1329
1330 void visitChildren(NodeVisitor visitor) {
1331 for (Expression element in elements) element.accept(visitor);
1332 }
1333
1334 ArrayInitializer _clone() => new ArrayInitializer(elements);
1335
1336 int get precedenceLevel => PRIMARY;
1337 }
1338
1339 /**
1340 * An empty place in an [ArrayInitializer].
1341 * For example the list [1, , , 2] would contain two holes.
1342 */
1343 class ArrayHole extends Expression {
1344 accept(NodeVisitor visitor) => visitor.visitArrayHole(this);
1345
1346 void visitChildren(NodeVisitor visitor) {}
1347
1348 ArrayHole _clone() => new ArrayHole();
1349
1350 int get precedenceLevel => PRIMARY;
1351 }
1352
1353 class ObjectInitializer extends Expression {
1354 final List<Property> properties;
1355 final bool _multiline;
1356
1357 /**
1358 * Constructs a new object-initializer containing the given [properties].
1359 */
1360 ObjectInitializer(this.properties, {multiline: false})
1361 : _multiline = multiline;
1362
1363 accept(NodeVisitor visitor) => visitor.visitObjectInitializer(this);
1364
1365 void visitChildren(NodeVisitor visitor) {
1366 for (Property init in properties) init.accept(visitor);
1367 }
1368
1369 ObjectInitializer _clone() => new ObjectInitializer(properties);
1370
1371 int get precedenceLevel => PRIMARY;
1372 /**
1373 * If set to true, forces a vertical layout when using the [Printer].
1374 * Otherwise, layout will be vertical if and only if any [properties]
1375 * are [FunctionExpression]s.
1376 */
1377 bool get multiline {
1378 return _multiline || properties.any((p) => p.value is FunctionExpression);
1379 }
1380 }
1381
1382 class Property extends Node {
1383 final Expression name;
1384 final Expression value;
1385
1386 Property(this.name, this.value);
1387
1388 accept(NodeVisitor visitor) => visitor.visitProperty(this);
1389
1390 void visitChildren(NodeVisitor visitor) {
1391 name.accept(visitor);
1392 value.accept(visitor);
1393 }
1394
1395 Property _clone() => new Property(name, value);
1396 }
1397
1398 // TODO(jmesserly): parser does not support this yet.
1399 class TemplateString extends Expression {
1400 /**
1401 * The parts of this template string: a sequence of [String]s and
1402 * [Expression]s. Strings and expressions will alternate, for example:
1403 *
1404 * `foo${1 + 2} bar ${'hi'}`
1405 *
1406 * would be represented by:
1407 *
1408 * ['foo', new JS.Binary('+', js.number(1), js.number(2)),
1409 * ' bar ', new JS.LiteralString("'hi'")]
1410 */
1411 final List elements;
1412 TemplateString(this.elements);
1413
1414 accept(NodeVisitor visitor) => visitor.visitTemplateString(this);
1415
1416 void visitChildren(NodeVisitor visitor) {
1417 for (var element in elements) {
1418 if (element is Expression) element.accept(visitor);
1419 }
1420 }
1421
1422 TemplateString _clone() => new TemplateString(elements);
1423
1424 int get precedenceLevel => PRIMARY;
1425 }
1426
1427 // TODO(jmesserly): parser does not support this yet.
1428 class TaggedTemplate extends Expression {
1429 final Expression tag;
1430 final TemplateString template;
1431
1432 TaggedTemplate(this.tag, this.template);
1433
1434 accept(NodeVisitor visitor) => visitor.visitTaggedTemplate(this);
1435
1436 void visitChildren(NodeVisitor visitor) {
1437 tag.accept(visitor);
1438 template.accept(visitor);
1439 }
1440
1441 TaggedTemplate _clone() => new TaggedTemplate(tag, template);
1442
1443 int get precedenceLevel => CALL;
1444 }
1445
1446 // TODO(jmesserly): parser does not support this yet.
1447 class Yield extends Expression {
1448 final Expression value; // Can be null.
1449
1450 /**
1451 * Whether this yield expression is a `yield*` that iterates each item in
1452 * [value].
1453 */
1454 final bool star;
1455
1456 Yield(this.value, {this.star: false});
1457
1458 accept(NodeVisitor visitor) => visitor.visitYield(this);
1459
1460 void visitChildren(NodeVisitor visitor) {
1461 if (value != null) value.accept(visitor);
1462 }
1463
1464 Yield _clone() => new Yield(value);
1465
1466 int get precedenceLevel => YIELD;
1467 }
1468
1469 class ClassDeclaration extends Statement {
1470 final ClassExpression classExpr;
1471
1472 ClassDeclaration(this.classExpr);
1473
1474 accept(NodeVisitor visitor) => visitor.visitClassDeclaration(this);
1475 visitChildren(NodeVisitor visitor) => classExpr.accept(visitor);
1476 ClassDeclaration _clone() => new ClassDeclaration(classExpr);
1477 }
1478
1479 class ClassExpression extends Expression {
1480 final Identifier name;
1481 final Expression heritage; // Can be null.
1482 final List<Method> methods;
1483 /// Type parameters of this class, if any. `null` otherwise.
1484 // TODO(ochafik): Support type bounds.
1485 final List<Identifier> typeParams;
1486 /// Field declarations of this class (TypeScript / ES6_TYPED).
1487 final List<VariableDeclarationList> fields;
1488
1489 ClassExpression(this.name, this.heritage, this.methods,
1490 {this.typeParams, this.fields});
1491
1492 accept(NodeVisitor visitor) => visitor.visitClassExpression(this);
1493
1494 void visitChildren(NodeVisitor visitor) {
1495 name.accept(visitor);
1496 if (heritage != null) heritage.accept(visitor);
1497 for (Method element in methods) element.accept(visitor);
1498 if (fields != null) {
1499 for (var field in fields) {
1500 field.accept(visitor);
1501 }
1502 }
1503 if (typeParams != null) {
1504 for (var typeParam in typeParams) {
1505 typeParam.accept(visitor);
1506 }
1507 }
1508 }
1509
1510 ClassExpression _clone() => new ClassExpression(
1511 name, heritage, methods, typeParams: typeParams, fields: fields);
1512
1513 int get precedenceLevel => PRIMARY_LOW_PRECEDENCE;
1514 }
1515
1516 class Method extends Property {
1517 final bool isGetter;
1518 final bool isSetter;
1519 final bool isStatic;
1520
1521 Method(Expression name, Fun function,
1522 {this.isGetter: false, this.isSetter: false, this.isStatic: false})
1523 : super(name, function) {
1524 assert(!isGetter || function.params.length == 0);
1525 assert(!isSetter || function.params.length == 1);
1526 assert(!isGetter && !isSetter || !function.isGenerator);
1527 }
1528
1529 Fun get function => super.value;
1530
1531 accept(NodeVisitor visitor) => visitor.visitMethod(this);
1532
1533 void visitChildren(NodeVisitor visitor) {
1534 name.accept(visitor);
1535 function.accept(visitor);
1536 }
1537
1538 Method _clone() => new Method(name, function,
1539 isGetter: isGetter, isSetter: isSetter, isStatic: isStatic);
1540 }
1541
1542 /// Tag class for all interpolated positions.
1543 abstract class InterpolatedNode implements Node {
1544 get nameOrPosition;
1545
1546 bool get isNamed => nameOrPosition is String;
1547 bool get isPositional => nameOrPosition is int;
1548 }
1549
1550 class InterpolatedExpression extends Expression with InterpolatedNode {
1551 final nameOrPosition;
1552
1553 InterpolatedExpression(this.nameOrPosition);
1554
1555 accept(NodeVisitor visitor) => visitor.visitInterpolatedExpression(this);
1556 void visitChildren(NodeVisitor visitor) {}
1557 InterpolatedExpression _clone() =>
1558 new InterpolatedExpression(nameOrPosition);
1559
1560 int get precedenceLevel => PRIMARY;
1561 }
1562
1563 class InterpolatedLiteral extends Literal with InterpolatedNode {
1564 final nameOrPosition;
1565
1566 InterpolatedLiteral(this.nameOrPosition);
1567
1568 accept(NodeVisitor visitor) => visitor.visitInterpolatedLiteral(this);
1569 void visitChildren(NodeVisitor visitor) {}
1570 InterpolatedLiteral _clone() => new InterpolatedLiteral(nameOrPosition);
1571 }
1572
1573 class InterpolatedParameter extends Expression with InterpolatedNode
1574 implements Identifier {
1575 final nameOrPosition;
1576 TypeRef get type => null;
1577
1578 String get name { throw "InterpolatedParameter.name must not be invoked"; }
1579 bool get allowRename => false;
1580
1581 InterpolatedParameter(this.nameOrPosition);
1582
1583 accept(NodeVisitor visitor) => visitor.visitInterpolatedParameter(this);
1584 void visitChildren(NodeVisitor visitor) {}
1585 InterpolatedParameter _clone() => new InterpolatedParameter(nameOrPosition);
1586
1587 int get precedenceLevel => PRIMARY;
1588 }
1589
1590 class InterpolatedSelector extends Expression with InterpolatedNode {
1591 final nameOrPosition;
1592
1593 InterpolatedSelector(this.nameOrPosition);
1594
1595 accept(NodeVisitor visitor) => visitor.visitInterpolatedSelector(this);
1596 void visitChildren(NodeVisitor visitor) {}
1597 InterpolatedSelector _clone() => new InterpolatedSelector(nameOrPosition);
1598
1599 int get precedenceLevel => PRIMARY;
1600 }
1601
1602 class InterpolatedStatement extends Statement with InterpolatedNode {
1603 final nameOrPosition;
1604
1605 InterpolatedStatement(this.nameOrPosition);
1606
1607 accept(NodeVisitor visitor) => visitor.visitInterpolatedStatement(this);
1608 void visitChildren(NodeVisitor visitor) {}
1609 InterpolatedStatement _clone() => new InterpolatedStatement(nameOrPosition);
1610 }
1611
1612 // TODO(jmesserly): generalize this to InterpolatedProperty?
1613 class InterpolatedMethod extends Expression with InterpolatedNode
1614 implements Method {
1615 final nameOrPosition;
1616
1617 InterpolatedMethod(this.nameOrPosition);
1618
1619 accept(NodeVisitor visitor) => visitor.visitInterpolatedMethod(this);
1620 void visitChildren(NodeVisitor visitor) {}
1621 InterpolatedMethod _clone() => new InterpolatedMethod(nameOrPosition);
1622
1623 int get precedenceLevel => PRIMARY;
1624 Expression get name => _unsupported;
1625 Expression get value => _unsupported;
1626 bool get isGetter => _unsupported;
1627 bool get isSetter => _unsupported;
1628 bool get isStatic => _unsupported;
1629 Fun get function => _unsupported;
1630 get _unsupported => throw '$runtimeType does not support this member.';
1631 }
1632
1633 class InterpolatedIdentifier extends Expression with InterpolatedNode
1634 implements Identifier {
1635 final nameOrPosition;
1636 TypeRef get type => null;
1637
1638 InterpolatedIdentifier(this.nameOrPosition);
1639
1640 accept(NodeVisitor visitor) =>
1641 visitor.visitInterpolatedIdentifier(this);
1642 void visitChildren(NodeVisitor visitor) {}
1643 InterpolatedIdentifier _clone() => new InterpolatedIdentifier(nameOrPosition);
1644
1645 int get precedenceLevel => PRIMARY;
1646 String get name => throw '$runtimeType does not support this member.';
1647 bool get allowRename => false;
1648 }
1649
1650 /**
1651 * [RegExpLiteral]s, despite being called "Literal", do not inherit from
1652 * [Literal]. Indeed, regular expressions in JavaScript have a side-effect and
1653 * are thus not in the same category as numbers or strings.
1654 */
1655 class RegExpLiteral extends Expression {
1656 /** Contains the pattern and the flags.*/
1657 final String pattern;
1658
1659 RegExpLiteral(this.pattern);
1660
1661 accept(NodeVisitor visitor) => visitor.visitRegExpLiteral(this);
1662 void visitChildren(NodeVisitor visitor) {}
1663 RegExpLiteral _clone() => new RegExpLiteral(pattern);
1664
1665 int get precedenceLevel => PRIMARY;
1666 }
1667
1668 /**
1669 * An asynchronous await.
1670 *
1671 * Not part of JavaScript. We desugar this expression before outputting.
1672 * Should only occur in a [Fun] with `asyncModifier` async or asyncStar.
1673 */
1674 class Await extends Expression {
1675 /** The awaited expression. */
1676 final Expression expression;
1677
1678 Await(this.expression);
1679
1680 int get precedenceLevel => UNARY;
1681 accept(NodeVisitor visitor) => visitor.visitAwait(this);
1682 void visitChildren(NodeVisitor visitor) => expression.accept(visitor);
1683 Await _clone() => new Await(expression);
1684 }
1685
1686 /**
1687 * A comment.
1688 *
1689 * Extends [Statement] so we can add comments before statements in
1690 * [Block] and [Program].
1691 */
1692 class Comment extends Statement {
1693 final String comment;
1694
1695 Comment(this.comment);
1696
1697 accept(NodeVisitor visitor) => visitor.visitComment(this);
1698 Comment _clone() => new Comment(comment);
1699
1700 void visitChildren(NodeVisitor visitor) {}
1701 }
1702
1703 /**
1704 * A comment for expressions.
1705 *
1706 * Extends [Expression] so we can add comments before expressions.
1707 * Has the highest possible precedence, so we don't add parentheses around it.
1708 */
1709 class CommentExpression extends Expression {
1710 final String comment;
1711 final Expression expression;
1712
1713 CommentExpression(this.comment, this.expression);
1714
1715 int get precedenceLevel => PRIMARY;
1716 accept(NodeVisitor visitor) => visitor.visitCommentExpression(this);
1717 CommentExpression _clone() => new CommentExpression(comment, expression);
1718
1719 void visitChildren(NodeVisitor visitor) => expression.accept(visitor);
1720 }
1721
1722 /**
1723 * Represents allowed module items:
1724 * [Statement], [ImportDeclaration], and [ExportDeclaration].
1725 */
1726 abstract class ModuleItem extends Node {}
1727
1728 class ImportDeclaration extends ModuleItem {
1729 final Identifier defaultBinding; // Can be null.
1730
1731 // Can be null, a single specifier of `* as name`, or a list.
1732 final List<NameSpecifier> namedImports;
1733
1734 final LiteralString from;
1735
1736 ImportDeclaration({this.defaultBinding, this.namedImports, this.from});
1737
1738 /** The `import "name.js"` form of import */
1739 ImportDeclaration.all(LiteralString module) : this(from: module);
1740
1741 /** If this import has `* as name` returns the name, otherwise null. */
1742 String get importStarAs {
1743 if (namedImports != null && namedImports.length == 1 &&
1744 namedImports[0].name == '*') {
1745 return namedImports[0].asName;
1746 }
1747 return null;
1748 }
1749
1750 accept(NodeVisitor visitor) => visitor.visitImportDeclaration(this);
1751 void visitChildren(NodeVisitor visitor) {
1752 if (namedImports != null) {
1753 for (NameSpecifier name in namedImports) name.accept(visitor);
1754 }
1755 from.accept(visitor);
1756 }
1757 ImportDeclaration _clone() => new ImportDeclaration(
1758 defaultBinding: defaultBinding, namedImports: namedImports, from: from);
1759 }
1760
1761 class ExportDeclaration extends ModuleItem {
1762 /**
1763 * Exports a name from this module.
1764 *
1765 * This can be a [ClassDeclaration] or [FunctionDeclaration].
1766 * If [isDefault] is true, it can also be an [Expression].
1767 * Otherwise it can be a [VariableDeclarationList] or an [ExportClause].
1768 */
1769 final Node exported;
1770
1771 /** True if this is an `export default`. */
1772 final bool isDefault;
1773
1774 ExportDeclaration(this.exported, {this.isDefault: false}) {
1775 assert(exported is ClassDeclaration ||
1776 exported is FunctionDeclaration ||
1777 isDefault
1778 ? exported is Expression
1779 : exported is VariableDeclarationList ||
1780 exported is ExportClause);
1781 }
1782
1783 accept(NodeVisitor visitor) => visitor.visitExportDeclaration(this);
1784 visitChildren(NodeVisitor visitor) => exported.accept(visitor);
1785 ExportDeclaration _clone() =>
1786 new ExportDeclaration(exported, isDefault: isDefault);
1787 }
1788
1789 class ExportClause extends Node {
1790 final List<NameSpecifier> exports;
1791 final LiteralString from; // Can be null.
1792
1793 ExportClause(this.exports, {this.from});
1794
1795 /** The `export * from 'name.js'` form. */
1796 ExportClause.star(LiteralString from)
1797 : this([new NameSpecifier('*')], from: from);
1798
1799 /** True if this is an `export *`. */
1800 bool get exportStar => exports.length == 1 && exports[0].name == '*';
1801
1802 accept(NodeVisitor visitor) => visitor.visitExportClause(this);
1803 void visitChildren(NodeVisitor visitor) {
1804 for (NameSpecifier name in exports) name.accept(visitor);
1805 if (from != null) from.accept(visitor);
1806 }
1807 ExportClause _clone() => new ExportClause(exports, from: from);
1808 }
1809
1810 /** An import or export specifier. */
1811 class NameSpecifier extends Node {
1812 // TODO(jmesserly): should we wrap this in a node of some sort?
1813 final String name;
1814 final String asName; // Can be null.
1815
1816 NameSpecifier(this.name, {this.asName});
1817
1818 accept(NodeVisitor visitor) => visitor.visitNameSpecifier(this);
1819 void visitChildren(NodeVisitor visitor) {}
1820 NameSpecifier _clone() => new NameSpecifier(name, asName: asName);
1821 }
1822
1823 // TODO(jmesserly): should this be related to [Program]?
1824 class Module extends Node {
1825 /// The module's name
1826 // TODO(jmesserly): this is not declared in ES6, but is known by the loader.
1827 // We use this because some ES5 desugarings require it.
1828 final String name;
1829
1830 final List<ModuleItem> body;
1831 Module(this.body, {this.name});
1832
1833 accept(NodeVisitor visitor) => visitor.visitModule(this);
1834 void visitChildren(NodeVisitor visitor) {
1835 for (ModuleItem item in body) item.accept(visitor);
1836 }
1837 Module _clone() => new Module(body);
1838 }
OLDNEW
« no previous file with comments | « lib/src/js/module_transform.dart ('k') | lib/src/js/precedence.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698