OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2017, 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 library kernerl.interpreter; |
| 5 |
| 6 import 'dart:collection'; |
| 7 import '../ast.dart'; |
| 8 |
| 9 class NotImplemented { |
| 10 String message; |
| 11 |
| 12 NotImplemented(this.message); |
| 13 |
| 14 String toString() => message; |
| 15 } |
| 16 |
| 17 class Interpreter { |
| 18 Program program; |
| 19 |
| 20 Interpreter(this.program); |
| 21 |
| 22 void evalProgram() { |
| 23 assert(program.libraries.isEmpty); |
| 24 Procedure mainMethod = program.mainMethod; |
| 25 Statement statementBlock = mainMethod.function.body; |
| 26 // Evaluate only statement with one expression, ExpressionStatement, which |
| 27 // is StaticInvocation of the method print. |
| 28 if (statementBlock is Block) { |
| 29 Statement statement = statementBlock.statements.first; |
| 30 if (statement is ExpressionStatement) { |
| 31 statement.expression.accept1(new ExpressionEval1(), |
| 32 new ExpressionState(new HashMap<String, Object>())); |
| 33 } |
| 34 } else { |
| 35 throw new NotImplemented('Evaluation for statement type ' |
| 36 '${statementBlock.runtimeType} is not implemented'); |
| 37 } |
| 38 } |
| 39 } |
| 40 |
| 41 class InvalidExpressionError { |
| 42 InvalidExpression expression; |
| 43 |
| 44 InvalidExpressionError(this.expression); |
| 45 |
| 46 String toString() => 'Invalid expression at ' |
| 47 '${expression.location.toString()}'; |
| 48 } |
| 49 |
| 50 class ExpressionState { |
| 51 Map<String, Object> environment; |
| 52 |
| 53 ExpressionState(this.environment); |
| 54 } |
| 55 |
| 56 class ExpressionEval1 extends ExpressionVisitor1<Object> { |
| 57 @override |
| 58 Object defaultExpression(Expression node, arg) { |
| 59 throw new NotImplemented('Evaluation for expressions of type ' |
| 60 '${node.runtimeType} is not implemented.'); |
| 61 } |
| 62 |
| 63 Object visitInvalidExpression1(InvalidExpression node, arg) => |
| 64 throw new InvalidExpressionError(node); |
| 65 |
| 66 Object visitStaticInvocation(StaticInvocation node, arg) { |
| 67 if ('print' == node.name.toString()) { |
| 68 // Special evaluation of print. |
| 69 var res = node.arguments.positional[0].accept1(this, arg); |
| 70 print(res); |
| 71 } else { |
| 72 throw new NotImplemented('Support for statement type ' |
| 73 '${node.runtimeType} is not implemented'); |
| 74 } |
| 75 } |
| 76 |
| 77 // Evaluation of BasicLiterals. |
| 78 Object visitStringLiteral(StringLiteral node, arg) => node.value; |
| 79 Object visitIntLiteral(IntLiteral node, arg) => node.value; |
| 80 Object visitDoubleLiteral(DoubleLiteral node, arg) => node.value; |
| 81 Object visitBoolLiteral(BoolLiteral node, arg) => node.value; |
| 82 Object visitNullLiteral(NullLiteral node, arg) => node.value; |
| 83 } |
OLD | NEW |