c81950e8ed6b2f597a0bc4a2b0ad265962c7c48b
[platform/upstream/nodejs.git] / deps / v8 / src / rewriter.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/v8.h"
6
7 #include "src/rewriter.h"
8
9 #include "src/ast.h"
10 #include "src/compiler.h"
11 #include "src/scopes.h"
12
13 namespace v8 {
14 namespace internal {
15
16 class Processor: public AstVisitor {
17  public:
18   Processor(Isolate* isolate, Variable* result,
19             AstValueFactory* ast_value_factory)
20       : result_(result),
21         result_assigned_(false),
22         is_set_(false),
23         in_try_(false),
24         factory_(ast_value_factory) {
25     InitializeAstVisitor(isolate, ast_value_factory->zone());
26   }
27
28   virtual ~Processor() { }
29
30   void Process(ZoneList<Statement*>* statements);
31   bool result_assigned() const { return result_assigned_; }
32
33   AstNodeFactory* factory() { return &factory_; }
34
35  private:
36   Variable* result_;
37
38   // We are not tracking result usage via the result_'s use
39   // counts (we leave the accurate computation to the
40   // usage analyzer). Instead we simple remember if
41   // there was ever an assignment to result_.
42   bool result_assigned_;
43
44   // To avoid storing to .result all the time, we eliminate some of
45   // the stores by keeping track of whether or not we're sure .result
46   // will be overwritten anyway. This is a bit more tricky than what I
47   // was hoping for
48   bool is_set_;
49   bool in_try_;
50
51   AstNodeFactory factory_;
52
53   Expression* SetResult(Expression* value) {
54     result_assigned_ = true;
55     VariableProxy* result_proxy = factory()->NewVariableProxy(result_);
56     return factory()->NewAssignment(
57         Token::ASSIGN, result_proxy, value, RelocInfo::kNoPosition);
58   }
59
60   // Node visitors.
61 #define DEF_VISIT(type) virtual void Visit##type(type* node) OVERRIDE;
62   AST_NODE_LIST(DEF_VISIT)
63 #undef DEF_VISIT
64
65   void VisitIterationStatement(IterationStatement* stmt);
66
67   DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
68 };
69
70
71 void Processor::Process(ZoneList<Statement*>* statements) {
72   for (int i = statements->length() - 1; i >= 0; --i) {
73     Visit(statements->at(i));
74   }
75 }
76
77
78 void Processor::VisitBlock(Block* node) {
79   // An initializer block is the rewritten form of a variable declaration
80   // with initialization expressions. The initializer block contains the
81   // list of assignments corresponding to the initialization expressions.
82   // While unclear from the spec (ECMA-262, 3rd., 12.2), the value of
83   // a variable declaration with initialization expression is 'undefined'
84   // with some JS VMs: For instance, using smjs, print(eval('var x = 7'))
85   // returns 'undefined'. To obtain the same behavior with v8, we need
86   // to prevent rewriting in that case.
87   if (!node->is_initializer_block()) Process(node->statements());
88 }
89
90
91 void Processor::VisitModuleStatement(ModuleStatement* node) {
92   bool set_after_body = is_set_;
93   Visit(node->body());
94   is_set_ = is_set_ && set_after_body;
95 }
96
97
98 void Processor::VisitExpressionStatement(ExpressionStatement* node) {
99   // Rewrite : <x>; -> .result = <x>;
100   if (!is_set_ && !node->expression()->IsThrow()) {
101     node->set_expression(SetResult(node->expression()));
102     if (!in_try_) is_set_ = true;
103   }
104 }
105
106
107 void Processor::VisitIfStatement(IfStatement* node) {
108   // Rewrite both then and else parts (reversed).
109   bool save = is_set_;
110   Visit(node->else_statement());
111   bool set_after_then = is_set_;
112   is_set_ = save;
113   Visit(node->then_statement());
114   is_set_ = is_set_ && set_after_then;
115 }
116
117
118 void Processor::VisitIterationStatement(IterationStatement* node) {
119   // Rewrite the body.
120   bool set_after_loop = is_set_;
121   Visit(node->body());
122   is_set_ = is_set_ && set_after_loop;
123 }
124
125
126 void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
127   VisitIterationStatement(node);
128 }
129
130
131 void Processor::VisitWhileStatement(WhileStatement* node) {
132   VisitIterationStatement(node);
133 }
134
135
136 void Processor::VisitForStatement(ForStatement* node) {
137   VisitIterationStatement(node);
138 }
139
140
141 void Processor::VisitForInStatement(ForInStatement* node) {
142   VisitIterationStatement(node);
143 }
144
145
146 void Processor::VisitForOfStatement(ForOfStatement* node) {
147   VisitIterationStatement(node);
148 }
149
150
151 void Processor::VisitTryCatchStatement(TryCatchStatement* node) {
152   // Rewrite both try and catch blocks (reversed order).
153   bool set_after_catch = is_set_;
154   Visit(node->catch_block());
155   is_set_ = is_set_ && set_after_catch;
156   bool save = in_try_;
157   in_try_ = true;
158   Visit(node->try_block());
159   in_try_ = save;
160 }
161
162
163 void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
164   // Rewrite both try and finally block (reversed order).
165   Visit(node->finally_block());
166   bool save = in_try_;
167   in_try_ = true;
168   Visit(node->try_block());
169   in_try_ = save;
170 }
171
172
173 void Processor::VisitSwitchStatement(SwitchStatement* node) {
174   // Rewrite statements in all case clauses in reversed order.
175   ZoneList<CaseClause*>* clauses = node->cases();
176   bool set_after_switch = is_set_;
177   for (int i = clauses->length() - 1; i >= 0; --i) {
178     CaseClause* clause = clauses->at(i);
179     Process(clause->statements());
180   }
181   is_set_ = is_set_ && set_after_switch;
182 }
183
184
185 void Processor::VisitContinueStatement(ContinueStatement* node) {
186   is_set_ = false;
187 }
188
189
190 void Processor::VisitBreakStatement(BreakStatement* node) {
191   is_set_ = false;
192 }
193
194
195 void Processor::VisitWithStatement(WithStatement* node) {
196   bool set_after_body = is_set_;
197   Visit(node->statement());
198   is_set_ = is_set_ && set_after_body;
199 }
200
201
202 // Do nothing:
203 void Processor::VisitVariableDeclaration(VariableDeclaration* node) {}
204 void Processor::VisitFunctionDeclaration(FunctionDeclaration* node) {}
205 void Processor::VisitModuleDeclaration(ModuleDeclaration* node) {}
206 void Processor::VisitImportDeclaration(ImportDeclaration* node) {}
207 void Processor::VisitExportDeclaration(ExportDeclaration* node) {}
208 void Processor::VisitModuleLiteral(ModuleLiteral* node) {}
209 void Processor::VisitModulePath(ModulePath* node) {}
210 void Processor::VisitModuleUrl(ModuleUrl* node) {}
211 void Processor::VisitEmptyStatement(EmptyStatement* node) {}
212 void Processor::VisitReturnStatement(ReturnStatement* node) {}
213 void Processor::VisitDebuggerStatement(DebuggerStatement* node) {}
214
215
216 // Expressions are never visited yet.
217 #define DEF_VISIT(type)                                         \
218   void Processor::Visit##type(type* expr) { UNREACHABLE(); }
219 EXPRESSION_NODE_LIST(DEF_VISIT)
220 #undef DEF_VISIT
221
222
223 // Assumes code has been parsed.  Mutates the AST, so the AST should not
224 // continue to be used in the case of failure.
225 bool Rewriter::Rewrite(CompilationInfo* info) {
226   FunctionLiteral* function = info->function();
227   DCHECK(function != NULL);
228   Scope* scope = function->scope();
229   DCHECK(scope != NULL);
230   if (!scope->is_script_scope() && !scope->is_eval_scope()) return true;
231
232   ZoneList<Statement*>* body = function->body();
233   if (!body->is_empty()) {
234     Variable* result =
235         scope->NewTemporary(info->ast_value_factory()->dot_result_string());
236     // The name string must be internalized at this point.
237     DCHECK(!result->name().is_null());
238     Processor processor(info->isolate(), result, info->ast_value_factory());
239     processor.Process(body);
240     if (processor.HasStackOverflow()) return false;
241
242     if (processor.result_assigned()) {
243       DCHECK(function->end_position() != RelocInfo::kNoPosition);
244       // Set the position of the assignment statement one character past the
245       // source code, such that it definitely is not in the source code range
246       // of an immediate inner scope. For example in
247       //   eval('with ({x:1}) x = 1');
248       // the end position of the function generated for executing the eval code
249       // coincides with the end of the with scope which is the position of '1'.
250       int pos = function->end_position();
251       VariableProxy* result_proxy =
252           processor.factory()->NewVariableProxy(result, pos);
253       Statement* result_statement =
254           processor.factory()->NewReturnStatement(result_proxy, pos);
255       body->Add(result_statement, info->zone());
256     }
257   }
258
259   return true;
260 }
261
262
263 } }  // namespace v8::internal