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
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.
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.
39 class Processor: public AstVisitor {
41 explicit Processor(Variable* result)
43 result_assigned_(false),
46 factory_(isolate()) { }
48 virtual ~Processor() { }
50 void Process(ZoneList<Statement*>* statements);
51 bool result_assigned() const { return result_assigned_; }
53 AstNodeFactory<AstNullVisitor>* factory() {
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_;
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
73 AstNodeFactory<AstNullVisitor> factory_;
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);
83 #define DEF_VISIT(type) \
84 virtual void Visit##type(type* node);
85 AST_NODE_LIST(DEF_VISIT)
88 void VisitIterationStatement(IterationStatement* stmt);
92 void Processor::Process(ZoneList<Statement*>* statements) {
93 for (int i = statements->length() - 1; i >= 0; --i) {
94 Visit(statements->at(i));
99 void 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());
112 void Processor::VisitExpressionStatement(ExpressionStatement* node) {
113 // Rewrite : <x>; -> .result = <x>;
114 if (!is_set_ && !node->expression()->IsThrow()) {
115 node->set_expression(SetResult(node->expression()));
116 if (!in_try_) is_set_ = true;
121 void Processor::VisitIfStatement(IfStatement* node) {
122 // Rewrite both then and else parts (reversed).
124 Visit(node->else_statement());
125 bool set_after_then = is_set_;
127 Visit(node->then_statement());
128 is_set_ = is_set_ && set_after_then;
132 void Processor::VisitIterationStatement(IterationStatement* node) {
134 bool set_after_loop = is_set_;
136 is_set_ = is_set_ && set_after_loop;
140 void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
141 VisitIterationStatement(node);
145 void Processor::VisitWhileStatement(WhileStatement* node) {
146 VisitIterationStatement(node);
150 void Processor::VisitForStatement(ForStatement* node) {
151 VisitIterationStatement(node);
155 void Processor::VisitForInStatement(ForInStatement* node) {
156 VisitIterationStatement(node);
160 void 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;
167 Visit(node->try_block());
172 void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
173 // Rewrite both try and finally block (reversed order).
174 Visit(node->finally_block());
177 Visit(node->try_block());
182 void 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());
190 is_set_ = is_set_ && set_after_switch;
194 void Processor::VisitContinueStatement(ContinueStatement* node) {
199 void Processor::VisitBreakStatement(BreakStatement* node) {
204 void Processor::VisitWithStatement(WithStatement* node) {
205 bool set_after_body = is_set_;
206 Visit(node->statement());
207 is_set_ = is_set_ && set_after_body;
212 void Processor::VisitVariableDeclaration(VariableDeclaration* node) {}
213 void Processor::VisitFunctionDeclaration(FunctionDeclaration* node) {}
214 void Processor::VisitModuleDeclaration(ModuleDeclaration* node) {}
215 void Processor::VisitImportDeclaration(ImportDeclaration* node) {}
216 void Processor::VisitExportDeclaration(ExportDeclaration* node) {}
217 void Processor::VisitModuleLiteral(ModuleLiteral* node) {}
218 void Processor::VisitModuleVariable(ModuleVariable* node) {}
219 void Processor::VisitModulePath(ModulePath* node) {}
220 void Processor::VisitModuleUrl(ModuleUrl* node) {}
221 void Processor::VisitEmptyStatement(EmptyStatement* node) {}
222 void Processor::VisitReturnStatement(ReturnStatement* node) {}
223 void Processor::VisitDebuggerStatement(DebuggerStatement* node) {}
226 // Expressions are never visited yet.
227 #define DEF_VISIT(type) \
228 void Processor::Visit##type(type* expr) { UNREACHABLE(); }
229 EXPRESSION_NODE_LIST(DEF_VISIT)
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.
235 bool 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;
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;
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);
273 } } // namespace v8::internal