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/parsing/rewriter.h"
6
7 #include "src/ast/ast.h"
8 #include "src/ast/scopes.h"
9 #include "src/logging/runtime-call-stats-scope.h"
10 #include "src/objects/objects-inl.h"
11 #include "src/parsing/parse-info.h"
12 #include "src/parsing/parser.h"
13 #include "src/zone/zone-list-inl.h"
14
15 namespace v8 {
16 namespace internal {
17
18 class Processor final : public AstVisitor<Processor> {
19 public:
Processor(uintptr_t stack_limit,DeclarationScope * closure_scope,Variable * result,AstValueFactory * ast_value_factory,Zone * zone)20 Processor(uintptr_t stack_limit, DeclarationScope* closure_scope,
21 Variable* result, AstValueFactory* ast_value_factory, Zone* zone)
22 : result_(result),
23 replacement_(nullptr),
24 zone_(zone),
25 closure_scope_(closure_scope),
26 factory_(ast_value_factory, zone),
27 result_assigned_(false),
28 is_set_(false),
29 breakable_(false) {
30 DCHECK_EQ(closure_scope, closure_scope->GetClosureScope());
31 InitializeAstVisitor(stack_limit);
32 }
33
Processor(Parser * parser,DeclarationScope * closure_scope,Variable * result,AstValueFactory * ast_value_factory,Zone * zone)34 Processor(Parser* parser, DeclarationScope* closure_scope, Variable* result,
35 AstValueFactory* ast_value_factory, Zone* zone)
36 : result_(result),
37 replacement_(nullptr),
38 zone_(zone),
39 closure_scope_(closure_scope),
40 factory_(ast_value_factory, zone_),
41 result_assigned_(false),
42 is_set_(false),
43 breakable_(false) {
44 DCHECK_EQ(closure_scope, closure_scope->GetClosureScope());
45 InitializeAstVisitor(parser->stack_limit());
46 }
47
48 void Process(ZonePtrList<Statement>* statements);
result_assigned() const49 bool result_assigned() const { return result_assigned_; }
50
zone()51 Zone* zone() { return zone_; }
closure_scope()52 DeclarationScope* closure_scope() { return closure_scope_; }
factory()53 AstNodeFactory* factory() { return &factory_; }
54
55 // Returns ".result = value"
SetResult(Expression * value)56 Expression* SetResult(Expression* value) {
57 result_assigned_ = true;
58 VariableProxy* result_proxy = factory()->NewVariableProxy(result_);
59 return factory()->NewAssignment(Token::ASSIGN, result_proxy, value,
60 kNoSourcePosition);
61 }
62
63 // Inserts '.result = undefined' in front of the given statement.
64 Statement* AssignUndefinedBefore(Statement* s);
65
66 private:
67 Variable* result_;
68
69 // When visiting a node, we "return" a replacement for that node in
70 // [replacement_]. In many cases this will just be the original node.
71 Statement* replacement_;
72
73 class V8_NODISCARD BreakableScope final {
74 public:
BreakableScope(Processor * processor,bool breakable=true)75 explicit BreakableScope(Processor* processor, bool breakable = true)
76 : processor_(processor), previous_(processor->breakable_) {
77 processor->breakable_ = processor->breakable_ || breakable;
78 }
79
~BreakableScope()80 ~BreakableScope() { processor_->breakable_ = previous_; }
81
82 private:
83 Processor* processor_;
84 bool previous_;
85 };
86
87 Zone* zone_;
88 DeclarationScope* closure_scope_;
89 AstNodeFactory factory_;
90
91 // Node visitors.
92 #define DEF_VISIT(type) void Visit##type(type* node);
93 AST_NODE_LIST(DEF_VISIT)
94 #undef DEF_VISIT
95
96 void VisitIterationStatement(IterationStatement* stmt);
97
98 DEFINE_AST_VISITOR_SUBCLASS_MEMBERS();
99
100 // We are not tracking result usage via the result_'s use
101 // counts (we leave the accurate computation to the
102 // usage analyzer). Instead we simple remember if
103 // there was ever an assignment to result_.
104 bool result_assigned_;
105
106 // To avoid storing to .result all the time, we eliminate some of
107 // the stores by keeping track of whether or not we're sure .result
108 // will be overwritten anyway. This is a bit more tricky than what I
109 // was hoping for.
110 bool is_set_;
111
112 bool breakable_;
113 };
114
115
AssignUndefinedBefore(Statement * s)116 Statement* Processor::AssignUndefinedBefore(Statement* s) {
117 Expression* undef = factory()->NewUndefinedLiteral(kNoSourcePosition);
118 Expression* assignment = SetResult(undef);
119 Block* b = factory()->NewBlock(2, false);
120 b->statements()->Add(
121 factory()->NewExpressionStatement(assignment, kNoSourcePosition), zone());
122 b->statements()->Add(s, zone());
123 return b;
124 }
125
Process(ZonePtrList<Statement> * statements)126 void Processor::Process(ZonePtrList<Statement>* statements) {
127 // If we're in a breakable scope (named block, iteration, or switch), we walk
128 // all statements. The last value producing statement before the break needs
129 // to assign to .result. If we're not in a breakable scope, only the last
130 // value producing statement in the block assigns to .result, so we can stop
131 // early.
132 for (int i = statements->length() - 1; i >= 0 && (breakable_ || !is_set_);
133 --i) {
134 Visit(statements->at(i));
135 statements->Set(i, replacement_);
136 }
137 }
138
139
VisitBlock(Block * node)140 void Processor::VisitBlock(Block* node) {
141 // An initializer block is the rewritten form of a variable declaration
142 // with initialization expressions. The initializer block contains the
143 // list of assignments corresponding to the initialization expressions.
144 // While unclear from the spec (ECMA-262, 3rd., 12.2), the value of
145 // a variable declaration with initialization expression is 'undefined'
146 // with some JS VMs: For instance, using smjs, print(eval('var x = 7'))
147 // returns 'undefined'. To obtain the same behavior with v8, we need
148 // to prevent rewriting in that case.
149 if (!node->ignore_completion_value()) {
150 BreakableScope scope(this, node->is_breakable());
151 Process(node->statements());
152 }
153 replacement_ = node;
154 }
155
156
VisitExpressionStatement(ExpressionStatement * node)157 void Processor::VisitExpressionStatement(ExpressionStatement* node) {
158 // Rewrite : <x>; -> .result = <x>;
159 if (!is_set_) {
160 node->set_expression(SetResult(node->expression()));
161 is_set_ = true;
162 }
163 replacement_ = node;
164 }
165
166
VisitIfStatement(IfStatement * node)167 void Processor::VisitIfStatement(IfStatement* node) {
168 // Rewrite both branches.
169 bool set_after = is_set_;
170
171 Visit(node->then_statement());
172 node->set_then_statement(replacement_);
173 bool set_in_then = is_set_;
174
175 is_set_ = set_after;
176 Visit(node->else_statement());
177 node->set_else_statement(replacement_);
178
179 replacement_ = set_in_then && is_set_ ? node : AssignUndefinedBefore(node);
180 is_set_ = true;
181 }
182
183
VisitIterationStatement(IterationStatement * node)184 void Processor::VisitIterationStatement(IterationStatement* node) {
185 // The statement may have to produce a value, so always assign undefined
186 // before.
187 // TODO(verwaest): Omit it if we know that there's no break/continue leaving
188 // it early.
189 DCHECK(breakable_ || !is_set_);
190 BreakableScope scope(this);
191
192 Visit(node->body());
193 node->set_body(replacement_);
194
195 replacement_ = AssignUndefinedBefore(node);
196 is_set_ = true;
197 }
198
199
VisitDoWhileStatement(DoWhileStatement * node)200 void Processor::VisitDoWhileStatement(DoWhileStatement* node) {
201 VisitIterationStatement(node);
202 }
203
204
VisitWhileStatement(WhileStatement * node)205 void Processor::VisitWhileStatement(WhileStatement* node) {
206 VisitIterationStatement(node);
207 }
208
209
VisitForStatement(ForStatement * node)210 void Processor::VisitForStatement(ForStatement* node) {
211 VisitIterationStatement(node);
212 }
213
214
VisitForInStatement(ForInStatement * node)215 void Processor::VisitForInStatement(ForInStatement* node) {
216 VisitIterationStatement(node);
217 }
218
219
VisitForOfStatement(ForOfStatement * node)220 void Processor::VisitForOfStatement(ForOfStatement* node) {
221 VisitIterationStatement(node);
222 }
223
224
VisitTryCatchStatement(TryCatchStatement * node)225 void Processor::VisitTryCatchStatement(TryCatchStatement* node) {
226 // Rewrite both try and catch block.
227 bool set_after = is_set_;
228
229 Visit(node->try_block());
230 node->set_try_block(static_cast<Block*>(replacement_));
231 bool set_in_try = is_set_;
232
233 is_set_ = set_after;
234 Visit(node->catch_block());
235 node->set_catch_block(static_cast<Block*>(replacement_));
236
237 replacement_ = is_set_ && set_in_try ? node : AssignUndefinedBefore(node);
238 is_set_ = true;
239 }
240
241
VisitTryFinallyStatement(TryFinallyStatement * node)242 void Processor::VisitTryFinallyStatement(TryFinallyStatement* node) {
243 // Only rewrite finally if it could contain 'break' or 'continue'. Always
244 // rewrite try.
245 if (breakable_) {
246 // Only set result before a 'break' or 'continue'.
247 is_set_ = true;
248 Visit(node->finally_block());
249 node->set_finally_block(replacement_->AsBlock());
250 CHECK_NOT_NULL(closure_scope());
251 if (is_set_) {
252 // Save .result value at the beginning of the finally block and restore it
253 // at the end again: ".backup = .result; ...; .result = .backup" This is
254 // necessary because the finally block does not normally contribute to the
255 // completion value.
256 Variable* backup = closure_scope()->NewTemporary(
257 factory()->ast_value_factory()->dot_result_string());
258 Expression* backup_proxy = factory()->NewVariableProxy(backup);
259 Expression* result_proxy = factory()->NewVariableProxy(result_);
260 Expression* save = factory()->NewAssignment(
261 Token::ASSIGN, backup_proxy, result_proxy, kNoSourcePosition);
262 Expression* restore = factory()->NewAssignment(
263 Token::ASSIGN, result_proxy, backup_proxy, kNoSourcePosition);
264 node->finally_block()->statements()->InsertAt(
265 0, factory()->NewExpressionStatement(save, kNoSourcePosition),
266 zone());
267 node->finally_block()->statements()->Add(
268 factory()->NewExpressionStatement(restore, kNoSourcePosition),
269 zone());
270 } else {
271 // If is_set_ is false, it means the finally block has a 'break' or a
272 // 'continue' and was not preceded by a statement that assigned to
273 // .result. Try-finally statements return the abrupt completions from the
274 // finally block, meaning this case should get an undefined.
275 //
276 // Since the finally block will definitely result in an abrupt completion,
277 // there's no need to save and restore the .result.
278 Expression* undef = factory()->NewUndefinedLiteral(kNoSourcePosition);
279 Expression* assignment = SetResult(undef);
280 node->finally_block()->statements()->InsertAt(
281 0, factory()->NewExpressionStatement(assignment, kNoSourcePosition),
282 zone());
283 }
284 // We can't tell whether the finally-block is guaranteed to set .result, so
285 // reset is_set_ before visiting the try-block.
286 is_set_ = false;
287 }
288 Visit(node->try_block());
289 node->set_try_block(replacement_->AsBlock());
290
291 replacement_ = is_set_ ? node : AssignUndefinedBefore(node);
292 is_set_ = true;
293 }
294
295
VisitSwitchStatement(SwitchStatement * node)296 void Processor::VisitSwitchStatement(SwitchStatement* node) {
297 // The statement may have to produce a value, so always assign undefined
298 // before.
299 // TODO(verwaest): Omit it if we know that there's no break/continue leaving
300 // it early.
301 DCHECK(breakable_ || !is_set_);
302 BreakableScope scope(this);
303 // Rewrite statements in all case clauses.
304 ZonePtrList<CaseClause>* clauses = node->cases();
305 for (int i = clauses->length() - 1; i >= 0; --i) {
306 CaseClause* clause = clauses->at(i);
307 Process(clause->statements());
308 }
309
310 replacement_ = AssignUndefinedBefore(node);
311 is_set_ = true;
312 }
313
314
VisitContinueStatement(ContinueStatement * node)315 void Processor::VisitContinueStatement(ContinueStatement* node) {
316 is_set_ = false;
317 replacement_ = node;
318 }
319
320
VisitBreakStatement(BreakStatement * node)321 void Processor::VisitBreakStatement(BreakStatement* node) {
322 is_set_ = false;
323 replacement_ = node;
324 }
325
326
VisitWithStatement(WithStatement * node)327 void Processor::VisitWithStatement(WithStatement* node) {
328 Visit(node->statement());
329 node->set_statement(replacement_);
330
331 replacement_ = is_set_ ? node : AssignUndefinedBefore(node);
332 is_set_ = true;
333 }
334
335
VisitSloppyBlockFunctionStatement(SloppyBlockFunctionStatement * node)336 void Processor::VisitSloppyBlockFunctionStatement(
337 SloppyBlockFunctionStatement* node) {
338 Visit(node->statement());
339 node->set_statement(replacement_);
340 replacement_ = node;
341 }
342
343
VisitEmptyStatement(EmptyStatement * node)344 void Processor::VisitEmptyStatement(EmptyStatement* node) {
345 replacement_ = node;
346 }
347
348
VisitReturnStatement(ReturnStatement * node)349 void Processor::VisitReturnStatement(ReturnStatement* node) {
350 is_set_ = true;
351 replacement_ = node;
352 }
353
354
VisitDebuggerStatement(DebuggerStatement * node)355 void Processor::VisitDebuggerStatement(DebuggerStatement* node) {
356 replacement_ = node;
357 }
358
VisitInitializeClassMembersStatement(InitializeClassMembersStatement * node)359 void Processor::VisitInitializeClassMembersStatement(
360 InitializeClassMembersStatement* node) {
361 replacement_ = node;
362 }
363
VisitInitializeClassStaticElementsStatement(InitializeClassStaticElementsStatement * node)364 void Processor::VisitInitializeClassStaticElementsStatement(
365 InitializeClassStaticElementsStatement* node) {
366 replacement_ = node;
367 }
368
369 // Expressions are never visited.
370 #define DEF_VISIT(type) \
371 void Processor::Visit##type(type* expr) { UNREACHABLE(); }
372 EXPRESSION_NODE_LIST(DEF_VISIT)
373 #undef DEF_VISIT
374
375
376 // Declarations are never visited.
377 #define DEF_VISIT(type) \
378 void Processor::Visit##type(type* expr) { UNREACHABLE(); }
DECLARATION_NODE_LIST(DEF_VISIT)379 DECLARATION_NODE_LIST(DEF_VISIT)
380 #undef DEF_VISIT
381
382
383 // Assumes code has been parsed. Mutates the AST, so the AST should not
384 // continue to be used in the case of failure.
385 bool Rewriter::Rewrite(ParseInfo* info) {
386 RCS_SCOPE(info->runtime_call_stats(),
387 RuntimeCallCounterId::kCompileRewriteReturnResult,
388 RuntimeCallStats::kThreadSpecific);
389
390 FunctionLiteral* function = info->literal();
391 DCHECK_NOT_NULL(function);
392 Scope* scope = function->scope();
393 DCHECK_NOT_NULL(scope);
394 DCHECK_EQ(scope, scope->GetClosureScope());
395
396 if (scope->is_repl_mode_scope()) return true;
397 if (!(scope->is_script_scope() || scope->is_eval_scope() ||
398 scope->is_module_scope())) {
399 return true;
400 }
401
402 ZonePtrList<Statement>* body = function->body();
403 return RewriteBody(info, scope, body).has_value();
404 }
405
RewriteBody(ParseInfo * info,Scope * scope,ZonePtrList<Statement> * body)406 base::Optional<VariableProxy*> Rewriter::RewriteBody(
407 ParseInfo* info, Scope* scope, ZonePtrList<Statement>* body) {
408 DisallowGarbageCollection no_gc;
409 DisallowHandleAllocation no_handles;
410 DisallowHandleDereference no_deref;
411
412 DCHECK_IMPLIES(scope->is_module_scope(), !body->is_empty());
413 if (!body->is_empty()) {
414 Variable* result = scope->AsDeclarationScope()->NewTemporary(
415 info->ast_value_factory()->dot_result_string());
416 Processor processor(info->stack_limit(), scope->AsDeclarationScope(),
417 result, info->ast_value_factory(), info->zone());
418 processor.Process(body);
419
420 DCHECK_IMPLIES(scope->is_module_scope(), processor.result_assigned());
421 if (processor.result_assigned()) {
422 int pos = kNoSourcePosition;
423 VariableProxy* result_value =
424 processor.factory()->NewVariableProxy(result, pos);
425 if (!info->flags().is_repl_mode()) {
426 Statement* result_statement =
427 processor.factory()->NewReturnStatement(result_value, pos);
428 body->Add(result_statement, info->zone());
429 }
430 return result_value;
431 }
432
433 if (processor.HasStackOverflow()) {
434 info->pending_error_handler()->set_stack_overflow();
435 return base::nullopt;
436 }
437 }
438 return nullptr;
439 }
440
441 } // namespace internal
442 } // namespace v8
443