1// Copyright 2012 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "rewriter.h"
31
32#include "ast.h"
33#include "compiler.h"
34#include "scopes.h"
35
36namespace v8 {
37namespace internal {
38
39class Processor: public AstVisitor {
40 public:
41  explicit Processor(Variable* result)
42      : result_(result),
43        result_assigned_(false),
44        is_set_(false),
45        in_try_(false),
46        factory_(isolate()) { }
47
48  virtual ~Processor() { }
49
50  void Process(ZoneList<Statement*>* statements);
51  bool result_assigned() const { return result_assigned_; }
52
53  AstNodeFactory<AstNullVisitor>* factory() {
54    return &factory_;
55  }
56
57 private:
58  Variable* result_;
59
60  // We are not tracking result usage via the result_'s use
61  // counts (we leave the accurate computation to the
62  // usage analyzer). Instead we simple remember if
63  // there was ever an assignment to result_.
64  bool result_assigned_;
65
66  // To avoid storing to .result all the time, we eliminate some of
67  // the stores by keeping track of whether or not we're sure .result
68  // will be overwritten anyway. This is a bit more tricky than what I
69  // was hoping for
70  bool is_set_;
71  bool in_try_;
72
73  AstNodeFactory<AstNullVisitor> factory_;
74
75  Expression* SetResult(Expression* value) {
76    result_assigned_ = true;
77    VariableProxy* result_proxy = factory()->NewVariableProxy(result_);
78    return factory()->NewAssignment(
79        Token::ASSIGN, result_proxy, value, RelocInfo::kNoPosition);
80  }
81
82  // Node visitors.
83#define DEF_VISIT(type) \
84  virtual void Visit##type(type* node);
85  AST_NODE_LIST(DEF_VISIT)
86#undef DEF_VISIT
87
88  void VisitIterationStatement(IterationStatement* stmt);
89};
90
91
92void Processor::Process(ZoneList<Statement*>* statements) {
93  for (int i = statements->length() - 1; i >= 0; --i) {
94    Visit(statements->at(i));
95  }
96}
97
98
99void Processor::VisitBlock(Block* node) {
100  // An initializer block is the rewritten form of a variable declaration
101  // with initialization expressions. The initializer block contains the
102  // list of assignments corresponding to the initialization expressions.
103  // While unclear from the spec (ECMA-262, 3rd., 12.2), the value of
104  // a variable declaration with initialization expression is 'undefined'
105  // with some JS VMs: For instance, using smjs, print(eval('var x = 7'))
106  // returns 'undefined'. To obtain the same behavior with v8, we need
107  // to prevent rewriting in that case.
108  if (!node->is_initializer_block()) Process(node->statements());
109}
110
111
112void Processor::VisitExpressionStatement(ExpressionStatement* node) {
113  // Rewrite : <x>; -> .result = <x>;
114  if (!is_set_) {
115    node->set_expression(SetResult(node->expression()));
116    if (!in_try_) is_set_ = true;
117  }
118}
119
120
121void Processor::VisitIfStatement(IfStatement* node) {
122  // Rewrite both then and else parts (reversed).
123  bool save = is_set_;
124  Visit(node->else_statement());
125  bool set_after_then = is_set_;
126  is_set_ = save;
127  Visit(node->then_statement());
128  is_set_ = is_set_ && set_after_then;
129}
130
131
132void Processor::VisitIterationStatement(IterationStatement* node) {
133  // Rewrite the body.
134  bool set_after_loop = is_set_;
135  Visit(node->body());
136  is_set_ = is_set_ && set_after_loop;
137}
138
139
140void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
141  VisitIterationStatement(node);
142}
143
144
145void Processor::VisitWhileStatement(WhileStatement* node) {
146  VisitIterationStatement(node);
147}
148
149
150void Processor::VisitForStatement(ForStatement* node) {
151  VisitIterationStatement(node);
152}
153
154
155void Processor::VisitForInStatement(ForInStatement* node) {
156  VisitIterationStatement(node);
157}
158
159
160void Processor::VisitTryCatchStatement(TryCatchStatement* node) {
161  // Rewrite both try and catch blocks (reversed order).
162  bool set_after_catch = is_set_;
163  Visit(node->catch_block());
164  is_set_ = is_set_ && set_after_catch;
165  bool save = in_try_;
166  in_try_ = true;
167  Visit(node->try_block());
168  in_try_ = save;
169}
170
171
172void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
173  // Rewrite both try and finally block (reversed order).
174  Visit(node->finally_block());
175  bool save = in_try_;
176  in_try_ = true;
177  Visit(node->try_block());
178  in_try_ = save;
179}
180
181
182void Processor::VisitSwitchStatement(SwitchStatement* node) {
183  // Rewrite statements in all case clauses in reversed order.
184  ZoneList<CaseClause*>* clauses = node->cases();
185  bool set_after_switch = is_set_;
186  for (int i = clauses->length() - 1; i >= 0; --i) {
187    CaseClause* clause = clauses->at(i);
188    Process(clause->statements());
189  }
190  is_set_ = is_set_ && set_after_switch;
191}
192
193
194void Processor::VisitContinueStatement(ContinueStatement* node) {
195  is_set_ = false;
196}
197
198
199void Processor::VisitBreakStatement(BreakStatement* node) {
200  is_set_ = false;
201}
202
203
204void Processor::VisitWithStatement(WithStatement* node) {
205  bool set_after_body = is_set_;
206  Visit(node->statement());
207  is_set_ = is_set_ && set_after_body;
208}
209
210
211// Do nothing:
212void Processor::VisitVariableDeclaration(VariableDeclaration* node) {}
213void Processor::VisitFunctionDeclaration(FunctionDeclaration* node) {}
214void Processor::VisitModuleDeclaration(ModuleDeclaration* node) {}
215void Processor::VisitImportDeclaration(ImportDeclaration* node) {}
216void Processor::VisitExportDeclaration(ExportDeclaration* node) {}
217void Processor::VisitModuleLiteral(ModuleLiteral* node) {}
218void Processor::VisitModuleVariable(ModuleVariable* node) {}
219void Processor::VisitModulePath(ModulePath* node) {}
220void Processor::VisitModuleUrl(ModuleUrl* node) {}
221void Processor::VisitEmptyStatement(EmptyStatement* node) {}
222void Processor::VisitReturnStatement(ReturnStatement* node) {}
223void Processor::VisitDebuggerStatement(DebuggerStatement* node) {}
224
225
226// Expressions are never visited yet.
227#define DEF_VISIT(type)                                         \
228  void Processor::Visit##type(type* expr) { UNREACHABLE(); }
229EXPRESSION_NODE_LIST(DEF_VISIT)
230#undef DEF_VISIT
231
232
233// Assumes code has been parsed and scopes have been analyzed.  Mutates the
234// AST, so the AST should not continue to be used in the case of failure.
235bool Rewriter::Rewrite(CompilationInfo* info) {
236  FunctionLiteral* function = info->function();
237  ASSERT(function != NULL);
238  Scope* scope = function->scope();
239  ASSERT(scope != NULL);
240  if (!scope->is_global_scope() && !scope->is_eval_scope()) return true;
241
242  ZoneList<Statement*>* body = function->body();
243  if (!body->is_empty()) {
244    Variable* result = scope->NewTemporary(
245        info->isolate()->factory()->result_symbol());
246    Processor processor(result);
247    processor.Process(body);
248    if (processor.HasStackOverflow()) return false;
249
250    if (processor.result_assigned()) {
251      ASSERT(function->end_position() != RelocInfo::kNoPosition);
252      // Set the position of the assignment statement one character past the
253      // source code, such that it definitely is not in the source code range
254      // of an immediate inner scope. For example in
255      //   eval('with ({x:1}) x = 1');
256      // the end position of the function generated for executing the eval code
257      // coincides with the end of the with scope which is the position of '1'.
258      int position = function->end_position();
259      VariableProxy* result_proxy = processor.factory()->NewVariableProxy(
260          result->name(), false, position);
261      result_proxy->BindTo(result);
262      Statement* result_statement =
263          processor.factory()->NewReturnStatement(result_proxy);
264      result_statement->set_statement_pos(position);
265      body->Add(result_statement);
266    }
267  }
268
269  return true;
270}
271
272
273} }  // namespace v8::internal
274