blob: 76f761dba3ceaf8cd0681982be7541dec60b3772 [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// 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#ifndef V8_AST_SCOPES_H_
6#define V8_AST_SCOPES_H_
7
8#include "src/ast/ast.h"
9#include "src/hashmap.h"
10#include "src/pending-compilation-error-handler.h"
11#include "src/zone.h"
12
13namespace v8 {
14namespace internal {
15
16class ParseInfo;
17
18// A hash map to support fast variable declaration and lookup.
19class VariableMap: public ZoneHashMap {
20 public:
21 explicit VariableMap(Zone* zone);
22
23 virtual ~VariableMap();
24
25 Variable* Declare(Scope* scope, const AstRawString* name, VariableMode mode,
26 Variable::Kind kind, InitializationFlag initialization_flag,
Ben Murdoch097c5b22016-05-18 11:27:45 +010027 MaybeAssignedFlag maybe_assigned_flag = kNotAssigned);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000028
29 Variable* Lookup(const AstRawString* name);
30
31 Zone* zone() const { return zone_; }
32
33 private:
34 Zone* zone_;
35};
36
37
38// The dynamic scope part holds hash maps for the variables that will
39// be looked up dynamically from within eval and with scopes. The objects
40// are allocated on-demand from Scope::NonLocal to avoid wasting memory
41// and setup time for scopes that don't need them.
42class DynamicScopePart : public ZoneObject {
43 public:
44 explicit DynamicScopePart(Zone* zone) {
45 for (int i = 0; i < 3; i++)
46 maps_[i] = new(zone->New(sizeof(VariableMap))) VariableMap(zone);
47 }
48
49 VariableMap* GetMap(VariableMode mode) {
50 int index = mode - DYNAMIC;
51 DCHECK(index >= 0 && index < 3);
52 return maps_[index];
53 }
54
55 private:
56 VariableMap *maps_[3];
57};
58
59
60// Sloppy block-scoped function declarations to var-bind
61class SloppyBlockFunctionMap : public ZoneHashMap {
62 public:
63 explicit SloppyBlockFunctionMap(Zone* zone);
64
65 virtual ~SloppyBlockFunctionMap();
66
67 void Declare(const AstRawString* name,
68 SloppyBlockFunctionStatement* statement);
69
70 typedef ZoneVector<SloppyBlockFunctionStatement*> Vector;
71
72 private:
73 Zone* zone_;
74};
75
76
77// Global invariants after AST construction: Each reference (i.e. identifier)
78// to a JavaScript variable (including global properties) is represented by a
79// VariableProxy node. Immediately after AST construction and before variable
80// allocation, most VariableProxy nodes are "unresolved", i.e. not bound to a
81// corresponding variable (though some are bound during parse time). Variable
82// allocation binds each unresolved VariableProxy to one Variable and assigns
83// a location. Note that many VariableProxy nodes may refer to the same Java-
84// Script variable.
85
86class Scope: public ZoneObject {
87 public:
88 // ---------------------------------------------------------------------------
89 // Construction
90
91 Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type,
92 AstValueFactory* value_factory,
93 FunctionKind function_kind = kNormalFunction);
94
95 // Compute top scope and allocate variables. For lazy compilation the top
96 // scope only contains the single lazily compiled function, so this
97 // doesn't re-allocate variables repeatedly.
98 static bool Analyze(ParseInfo* info);
99
100 static Scope* DeserializeScopeChain(Isolate* isolate, Zone* zone,
101 Context* context, Scope* script_scope);
102
103 // The scope name is only used for printing/debugging.
104 void SetScopeName(const AstRawString* scope_name) {
105 scope_name_ = scope_name;
106 }
107
108 void Initialize();
109
110 // Checks if the block scope is redundant, i.e. it does not contain any
111 // block scoped declarations. In that case it is removed from the scope
112 // tree and its children are reparented.
113 Scope* FinalizeBlockScope();
114
115 // Inserts outer_scope into this scope's scope chain (and removes this
116 // from the current outer_scope_'s inner_scopes_).
117 // Assumes outer_scope_ is non-null.
118 void ReplaceOuterScope(Scope* outer_scope);
119
120 // Propagates any eagerly-gathered scope usage flags (such as calls_eval())
121 // to the passed-in scope.
122 void PropagateUsageFlagsToScope(Scope* other);
123
124 Zone* zone() const { return zone_; }
125
126 // ---------------------------------------------------------------------------
127 // Declarations
128
129 // Lookup a variable in this scope. Returns the variable or NULL if not found.
130 Variable* LookupLocal(const AstRawString* name);
131
132 // This lookup corresponds to a lookup in the "intermediate" scope sitting
133 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
134 // the name of named function literal is kept in an intermediate scope
135 // in between this scope and the next outer scope.)
136 Variable* LookupFunctionVar(const AstRawString* name,
137 AstNodeFactory* factory);
138
139 // Lookup a variable in this scope or outer scopes.
140 // Returns the variable or NULL if not found.
141 Variable* Lookup(const AstRawString* name);
142
143 // Declare the function variable for a function literal. This variable
144 // is in an intermediate scope between this function scope and the the
145 // outer scope. Only possible for function scopes; at most one variable.
146 void DeclareFunctionVar(VariableDeclaration* declaration) {
147 DCHECK(is_function_scope());
148 // Handle implicit declaration of the function name in named function
149 // expressions before other declarations.
150 decls_.InsertAt(0, declaration, zone());
151 function_ = declaration;
152 }
153
154 // Declare a parameter in this scope. When there are duplicated
155 // parameters the rightmost one 'wins'. However, the implementation
156 // expects all parameters to be declared and from left to right.
157 Variable* DeclareParameter(
158 const AstRawString* name, VariableMode mode,
159 bool is_optional, bool is_rest, bool* is_duplicate);
160
161 // Declare a local variable in this scope. If the variable has been
162 // declared before, the previously declared variable is returned.
163 Variable* DeclareLocal(const AstRawString* name, VariableMode mode,
164 InitializationFlag init_flag, Variable::Kind kind,
Ben Murdoch097c5b22016-05-18 11:27:45 +0100165 MaybeAssignedFlag maybe_assigned_flag = kNotAssigned);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000166
167 // Declare an implicit global variable in this scope which must be a
168 // script scope. The variable was introduced (possibly from an inner
169 // scope) by a reference to an unresolved variable with no intervening
170 // with statements or eval calls.
171 Variable* DeclareDynamicGlobal(const AstRawString* name);
172
173 // Create a new unresolved variable.
174 VariableProxy* NewUnresolved(AstNodeFactory* factory,
175 const AstRawString* name,
176 Variable::Kind kind = Variable::NORMAL,
177 int start_position = RelocInfo::kNoPosition,
178 int end_position = RelocInfo::kNoPosition) {
179 // Note that we must not share the unresolved variables with
180 // the same name because they may be removed selectively via
181 // RemoveUnresolved().
182 DCHECK(!already_resolved());
183 VariableProxy* proxy =
184 factory->NewVariableProxy(name, kind, start_position, end_position);
185 unresolved_.Add(proxy, zone_);
186 return proxy;
187 }
188
189 void AddUnresolved(VariableProxy* proxy) {
190 DCHECK(!already_resolved());
191 DCHECK(!proxy->is_resolved());
192 unresolved_.Add(proxy, zone_);
193 }
194
195 // Remove a unresolved variable. During parsing, an unresolved variable
196 // may have been added optimistically, but then only the variable name
197 // was used (typically for labels). If the variable was not declared, the
198 // addition introduced a new unresolved variable which may end up being
199 // allocated globally as a "ghost" variable. RemoveUnresolved removes
200 // such a variable again if it was added; otherwise this is a no-op.
201 bool RemoveUnresolved(VariableProxy* var);
202
203 // Creates a new temporary variable in this scope's TemporaryScope. The
204 // name is only used for printing and cannot be used to find the variable.
205 // In particular, the only way to get hold of the temporary is by keeping the
206 // Variable* around. The name should not clash with a legitimate variable
207 // names.
208 Variable* NewTemporary(const AstRawString* name);
209
210 // Remove a temporary variable. This is for adjusting the scope of
211 // temporaries used when desugaring parameter initializers.
212 bool RemoveTemporary(Variable* var);
213
214 // Adds a temporary variable in this scope's TemporaryScope. This is for
215 // adjusting the scope of temporaries used when desugaring parameter
216 // initializers.
217 void AddTemporary(Variable* var) { temps_.Add(var, zone()); }
218
219 // Adds the specific declaration node to the list of declarations in
220 // this scope. The declarations are processed as part of entering
221 // the scope; see codegen.cc:ProcessDeclarations.
222 void AddDeclaration(Declaration* declaration);
223
224 // ---------------------------------------------------------------------------
225 // Illegal redeclaration support.
226
227 // Set an expression node that will be executed when the scope is
228 // entered. We only keep track of one illegal redeclaration node per
229 // scope - the first one - so if you try to set it multiple times
230 // the additional requests will be silently ignored.
231 void SetIllegalRedeclaration(Expression* expression);
232
233 // Retrieve the illegal redeclaration expression. Do not call if the
234 // scope doesn't have an illegal redeclaration node.
235 Expression* GetIllegalRedeclaration();
236
237 // Check if the scope has (at least) one illegal redeclaration.
238 bool HasIllegalRedeclaration() const { return illegal_redecl_ != NULL; }
239
240 // For harmony block scoping mode: Check if the scope has conflicting var
241 // declarations, i.e. a var declaration that has been hoisted from a nested
242 // scope over a let binding of the same name.
243 Declaration* CheckConflictingVarDeclarations();
244
245 // ---------------------------------------------------------------------------
246 // Scope-specific info.
247
248 // Inform the scope that the corresponding code contains a with statement.
249 void RecordWithStatement() { scope_contains_with_ = true; }
250
251 // Inform the scope that the corresponding code contains an eval call.
252 void RecordEvalCall() { scope_calls_eval_ = true; }
253
254 // Inform the scope that the corresponding code uses "arguments".
255 void RecordArgumentsUsage() { scope_uses_arguments_ = true; }
256
257 // Inform the scope that the corresponding code uses "super".
258 void RecordSuperPropertyUsage() { scope_uses_super_property_ = true; }
259
260 // Set the language mode flag (unless disabled by a global flag).
261 void SetLanguageMode(LanguageMode language_mode) {
262 language_mode_ = language_mode;
263 }
264
265 // Set the ASM module flag.
266 void SetAsmModule() { asm_module_ = true; }
267
268 // Inform the scope that the scope may execute declarations nonlinearly.
269 // Currently, the only nonlinear scope is a switch statement. The name is
270 // more general in case something else comes up with similar control flow,
271 // for example the ability to break out of something which does not have
272 // its own lexical scope.
273 // The bit does not need to be stored on the ScopeInfo because none of
274 // the three compilers will perform hole check elimination on a variable
275 // located in VariableLocation::CONTEXT. So, direct eval and closures
276 // will not expose holes.
277 void SetNonlinear() { scope_nonlinear_ = true; }
278
279 // Position in the source where this scope begins and ends.
280 //
281 // * For the scope of a with statement
282 // with (obj) stmt
283 // start position: start position of first token of 'stmt'
284 // end position: end position of last token of 'stmt'
285 // * For the scope of a block
286 // { stmts }
287 // start position: start position of '{'
288 // end position: end position of '}'
289 // * For the scope of a function literal or decalaration
290 // function fun(a,b) { stmts }
291 // start position: start position of '('
292 // end position: end position of '}'
293 // * For the scope of a catch block
294 // try { stms } catch(e) { stmts }
295 // start position: start position of '('
296 // end position: end position of ')'
297 // * For the scope of a for-statement
298 // for (let x ...) stmt
299 // start position: start position of '('
300 // end position: end position of last token of 'stmt'
301 // * For the scope of a switch statement
302 // switch (tag) { cases }
303 // start position: start position of '{'
304 // end position: end position of '}'
305 int start_position() const { return start_position_; }
306 void set_start_position(int statement_pos) {
307 start_position_ = statement_pos;
308 }
309 int end_position() const { return end_position_; }
310 void set_end_position(int statement_pos) {
311 end_position_ = statement_pos;
312 }
313
314 // In some cases we want to force context allocation for a whole scope.
315 void ForceContextAllocation() {
316 DCHECK(!already_resolved());
317 force_context_allocation_ = true;
318 }
319 bool has_forced_context_allocation() const {
320 return force_context_allocation_;
321 }
322
323 // ---------------------------------------------------------------------------
324 // Predicates.
325
326 // Specific scope types.
327 bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
328 bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
329 bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
330 bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
331 bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
332 bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
333 bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
334 bool is_arrow_scope() const {
335 return is_function_scope() && IsArrowFunction(function_kind_);
336 }
337 bool is_declaration_scope() const { return is_declaration_scope_; }
338
339 void set_is_declaration_scope() { is_declaration_scope_ = true; }
340
341 // Information about which scopes calls eval.
342 bool calls_eval() const { return scope_calls_eval_; }
343 bool calls_sloppy_eval() const {
344 return scope_calls_eval_ && is_sloppy(language_mode_);
345 }
346 bool outer_scope_calls_sloppy_eval() const {
347 return outer_scope_calls_sloppy_eval_;
348 }
349 bool asm_module() const { return asm_module_; }
350 bool asm_function() const { return asm_function_; }
351
352 // Is this scope inside a with statement.
353 bool inside_with() const { return scope_inside_with_; }
354
355 // Does this scope access "arguments".
356 bool uses_arguments() const { return scope_uses_arguments_; }
357 // Does this scope access "super" property (super.foo).
358 bool uses_super_property() const { return scope_uses_super_property_; }
359 // Does this scope have the potential to execute declarations non-linearly?
360 bool is_nonlinear() const { return scope_nonlinear_; }
361
362 // Whether this needs to be represented by a runtime context.
363 bool NeedsContext() const {
364 // Catch and module scopes always have heap slots.
365 DCHECK(!is_catch_scope() || num_heap_slots() > 0);
366 DCHECK(!is_module_scope() || num_heap_slots() > 0);
367 return is_with_scope() || num_heap_slots() > 0;
368 }
369
370 bool NeedsHomeObject() const {
371 return scope_uses_super_property_ ||
372 ((scope_calls_eval_ || inner_scope_calls_eval_) &&
373 (IsConciseMethod(function_kind()) ||
374 IsAccessorFunction(function_kind()) ||
375 IsClassConstructor(function_kind())));
376 }
377
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000378 // ---------------------------------------------------------------------------
379 // Accessors.
380
381 // The type of this scope.
382 ScopeType scope_type() const { return scope_type_; }
383
384 FunctionKind function_kind() const { return function_kind_; }
385
386 // The language mode of this scope.
387 LanguageMode language_mode() const { return language_mode_; }
388
389 // The variable corresponding to the 'this' value.
390 Variable* receiver() {
391 DCHECK(has_this_declaration());
392 DCHECK_NOT_NULL(receiver_);
393 return receiver_;
394 }
395
396 // TODO(wingo): Add a GLOBAL_SCOPE scope type which will lexically allocate
397 // "this" (and no other variable) on the native context. Script scopes then
398 // will not have a "this" declaration.
399 bool has_this_declaration() const {
400 return (is_function_scope() && !is_arrow_scope()) || is_module_scope();
401 }
402
403 // The variable corresponding to the 'new.target' value.
404 Variable* new_target_var() { return new_target_; }
405
406 // The variable holding the function literal for named function
407 // literals, or NULL. Only valid for function scopes.
408 VariableDeclaration* function() const {
409 DCHECK(is_function_scope());
410 return function_;
411 }
412
413 // Parameters. The left-most parameter has index 0.
414 // Only valid for function scopes.
415 Variable* parameter(int index) const {
416 DCHECK(is_function_scope());
417 return params_[index];
418 }
419
420 // Returns the default function arity excluding default or rest parameters.
421 int default_function_length() const { return arity_; }
422
Ben Murdoch097c5b22016-05-18 11:27:45 +0100423 // Returns the number of formal parameters, up to but not including the
424 // rest parameter index (if the function has rest parameters), i.e. it
425 // says 2 for
426 //
427 // function foo(a, b) { ... }
428 //
429 // and
430 //
431 // function foo(a, b, ...c) { ... }
432 //
433 // but for
434 //
435 // function foo(a, b, c = 1) { ... }
436 //
437 // we return 3 here.
438 int num_parameters() const {
439 return has_rest_parameter() ? params_.length() - 1 : params_.length();
440 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000441
442 // A function can have at most one rest parameter. Returns Variable* or NULL.
443 Variable* rest_parameter(int* index) const {
444 *index = rest_index_;
445 if (rest_index_ < 0) return NULL;
446 return rest_parameter_;
447 }
448
449 bool has_rest_parameter() const { return rest_index_ >= 0; }
450
451 bool has_simple_parameters() const {
452 return has_simple_parameters_;
453 }
454
455 // TODO(caitp): manage this state in a better way. PreParser must be able to
456 // communicate that the scope is non-simple, without allocating any parameters
457 // as the Parser does. This is necessary to ensure that TC39's proposed early
458 // error can be reported consistently regardless of whether lazily parsed or
459 // not.
460 void SetHasNonSimpleParameters() {
461 DCHECK(is_function_scope());
462 has_simple_parameters_ = false;
463 }
464
465 // Retrieve `IsSimpleParameterList` of current or outer function.
466 bool HasSimpleParameters() {
467 Scope* scope = ClosureScope();
468 return !scope->is_function_scope() || scope->has_simple_parameters();
469 }
470
471 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
472 Variable* arguments() const {
473 DCHECK(!is_arrow_scope() || arguments_ == nullptr);
474 return arguments_;
475 }
476
477 Variable* this_function_var() const {
478 // This is only used in derived constructors atm.
479 DCHECK(this_function_ == nullptr ||
480 (is_function_scope() && (IsClassConstructor(function_kind()) ||
481 IsConciseMethod(function_kind()) ||
482 IsAccessorFunction(function_kind()))));
483 return this_function_;
484 }
485
486 // Declarations list.
487 ZoneList<Declaration*>* declarations() { return &decls_; }
488
489 // Inner scope list.
490 ZoneList<Scope*>* inner_scopes() { return &inner_scopes_; }
491
492 // The scope immediately surrounding this scope, or NULL.
493 Scope* outer_scope() const { return outer_scope_; }
494
495 // The ModuleDescriptor for this scope; only for module scopes.
496 ModuleDescriptor* module() const { return module_descriptor_; }
497
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000498 // ---------------------------------------------------------------------------
499 // Variable allocation.
500
501 // Collect stack and context allocated local variables in this scope. Note
502 // that the function variable - if present - is not collected and should be
503 // handled separately.
Ben Murdoch097c5b22016-05-18 11:27:45 +0100504 void CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
505 ZoneList<Variable*>* context_locals,
506 ZoneList<Variable*>* context_globals);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000507
508 // Current number of var or const locals.
509 int num_var_or_const() { return num_var_or_const_; }
510
511 // Result of variable allocation.
512 int num_stack_slots() const { return num_stack_slots_; }
513 int num_heap_slots() const { return num_heap_slots_; }
514 int num_global_slots() const { return num_global_slots_; }
515
516 int StackLocalCount() const;
517 int ContextLocalCount() const;
518 int ContextGlobalCount() const;
519
520 // Make sure this scope and all outer scopes are eagerly compiled.
521 void ForceEagerCompilation() { force_eager_compilation_ = true; }
522
523 // Determine if we can parse a function literal in this scope lazily.
524 bool AllowsLazyParsing() const;
525
526 // Determine if we can use lazy compilation for this scope.
527 bool AllowsLazyCompilation() const;
528
529 // Determine if we can use lazy compilation for this scope without a context.
530 bool AllowsLazyCompilationWithoutContext() const;
531
532 // True if the outer context of this scope is always the native context.
533 bool HasTrivialOuterContext() const;
534
535 // The number of contexts between this and scope; zero if this == scope.
536 int ContextChainLength(Scope* scope);
537
538 // The maximum number of nested contexts required for this scope and any inner
539 // scopes.
540 int MaxNestedContextChainLength();
541
542 // Find the first function, script, eval or (declaration) block scope. This is
543 // the scope where var declarations will be hoisted to in the implementation.
544 Scope* DeclarationScope();
545
546 // Find the first non-block declaration scope. This should be either a script,
547 // function, or eval scope. Same as DeclarationScope(), but skips
548 // declaration "block" scopes. Used for differentiating associated
549 // function objects (i.e., the scope for which a function prologue allocates
550 // a context) or declaring temporaries.
551 Scope* ClosureScope();
552
553 // Find the first (non-arrow) function or script scope. This is where
554 // 'this' is bound, and what determines the function kind.
555 Scope* ReceiverScope();
556
557 Handle<ScopeInfo> GetScopeInfo(Isolate* isolate);
558
559 // Get the chain of nested scopes within this scope for the source statement
560 // position. The scopes will be added to the list from the outermost scope to
561 // the innermost scope. Only nested block, catch or with scopes are tracked
562 // and will be returned, but no inner function scopes.
563 void GetNestedScopeChain(Isolate* isolate, List<Handle<ScopeInfo> >* chain,
564 int statement_position);
565
566 void CollectNonLocals(HashMap* non_locals);
567
568 // ---------------------------------------------------------------------------
569 // Strict mode support.
570 bool IsDeclared(const AstRawString* name) {
571 // During formal parameter list parsing the scope only contains
572 // two variables inserted at initialization: "this" and "arguments".
573 // "this" is an invalid parameter name and "arguments" is invalid parameter
574 // name in strict mode. Therefore looking up with the map which includes
575 // "this" and "arguments" in addition to all formal parameters is safe.
576 return variables_.Lookup(name) != NULL;
577 }
578
579 bool IsDeclaredParameter(const AstRawString* name) {
580 // If IsSimpleParameterList is false, duplicate parameters are not allowed,
581 // however `arguments` may be allowed if function is not strict code. Thus,
582 // the assumptions explained above do not hold.
583 return params_.Contains(variables_.Lookup(name));
584 }
585
586 SloppyBlockFunctionMap* sloppy_block_function_map() {
587 return &sloppy_block_function_map_;
588 }
589
590 // Error handling.
591 void ReportMessage(int start_position, int end_position,
592 MessageTemplate::Template message,
593 const AstRawString* arg);
594
595 // ---------------------------------------------------------------------------
596 // Debugging.
597
598#ifdef DEBUG
599 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
600#endif
601
602 // ---------------------------------------------------------------------------
603 // Implementation.
604 private:
605 // Scope tree.
606 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
607 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes
608
609 // The scope type.
610 ScopeType scope_type_;
611 // If the scope is a function scope, this is the function kind.
612 FunctionKind function_kind_;
613
614 // Debugging support.
615 const AstRawString* scope_name_;
616
617 // The variables declared in this scope:
618 //
619 // All user-declared variables (incl. parameters). For script scopes
620 // variables may be implicitly 'declared' by being used (possibly in
621 // an inner scope) with no intervening with statements or eval calls.
622 VariableMap variables_;
623 // Compiler-allocated (user-invisible) temporaries.
624 ZoneList<Variable*> temps_;
625 // Parameter list in source order.
626 ZoneList<Variable*> params_;
627 // Variables that must be looked up dynamically.
628 DynamicScopePart* dynamics_;
629 // Unresolved variables referred to from this scope.
630 ZoneList<VariableProxy*> unresolved_;
631 // Declarations.
632 ZoneList<Declaration*> decls_;
633 // Convenience variable.
634 Variable* receiver_;
635 // Function variable, if any; function scopes only.
636 VariableDeclaration* function_;
637 // new.target variable, function scopes only.
638 Variable* new_target_;
639 // Convenience variable; function scopes only.
640 Variable* arguments_;
641 // Convenience variable; Subclass constructor only
642 Variable* this_function_;
643 // Module descriptor; module scopes only.
644 ModuleDescriptor* module_descriptor_;
645
646 // Map of function names to lists of functions defined in sloppy blocks
647 SloppyBlockFunctionMap sloppy_block_function_map_;
648
649 // Illegal redeclaration.
650 Expression* illegal_redecl_;
651
652 // Scope-specific information computed during parsing.
653 //
654 // This scope is inside a 'with' of some outer scope.
655 bool scope_inside_with_;
656 // This scope contains a 'with' statement.
657 bool scope_contains_with_;
658 // This scope or a nested catch scope or with scope contain an 'eval' call. At
659 // the 'eval' call site this scope is the declaration scope.
660 bool scope_calls_eval_;
661 // This scope uses "arguments".
662 bool scope_uses_arguments_;
663 // This scope uses "super" property ('super.foo').
664 bool scope_uses_super_property_;
665 // This scope contains an "use asm" annotation.
666 bool asm_module_;
667 // This scope's outer context is an asm module.
668 bool asm_function_;
669 // This scope's declarations might not be executed in order (e.g., switch).
670 bool scope_nonlinear_;
671 // The language mode of this scope.
672 LanguageMode language_mode_;
673 // Source positions.
674 int start_position_;
675 int end_position_;
676
677 // Computed via PropagateScopeInfo.
678 bool outer_scope_calls_sloppy_eval_;
679 bool inner_scope_calls_eval_;
680 bool force_eager_compilation_;
681 bool force_context_allocation_;
682
683 // True if it doesn't need scope resolution (e.g., if the scope was
684 // constructed based on a serialized scope info or a catch context).
685 bool already_resolved_;
686
687 // True if it holds 'var' declarations.
688 bool is_declaration_scope_;
689
690 // Computed as variables are declared.
691 int num_var_or_const_;
692
693 // Computed via AllocateVariables; function, block and catch scopes only.
694 int num_stack_slots_;
695 int num_heap_slots_;
696 int num_global_slots_;
697
698 // Info about the parameter list of a function.
699 int arity_;
700 bool has_simple_parameters_;
701 Variable* rest_parameter_;
702 int rest_index_;
703
704 // Serialized scope info support.
705 Handle<ScopeInfo> scope_info_;
706 bool already_resolved() { return already_resolved_; }
707
708 // Create a non-local variable with a given name.
709 // These variables are looked up dynamically at runtime.
710 Variable* NonLocal(const AstRawString* name, VariableMode mode);
711
712 // Variable resolution.
713 // Possible results of a recursive variable lookup telling if and how a
714 // variable is bound. These are returned in the output parameter *binding_kind
715 // of the LookupRecursive function.
716 enum BindingKind {
717 // The variable reference could be statically resolved to a variable binding
718 // which is returned. There is no 'with' statement between the reference and
719 // the binding and no scope between the reference scope (inclusive) and
720 // binding scope (exclusive) makes a sloppy 'eval' call.
721 BOUND,
722
723 // The variable reference could be statically resolved to a variable binding
724 // which is returned. There is no 'with' statement between the reference and
725 // the binding, but some scope between the reference scope (inclusive) and
726 // binding scope (exclusive) makes a sloppy 'eval' call, that might
727 // possibly introduce variable bindings shadowing the found one. Thus the
728 // found variable binding is just a guess.
729 BOUND_EVAL_SHADOWED,
730
731 // The variable reference could not be statically resolved to any binding
732 // and thus should be considered referencing a global variable. NULL is
733 // returned. The variable reference is not inside any 'with' statement and
734 // no scope between the reference scope (inclusive) and script scope
735 // (exclusive) makes a sloppy 'eval' call.
736 UNBOUND,
737
738 // The variable reference could not be statically resolved to any binding
739 // NULL is returned. The variable reference is not inside any 'with'
740 // statement, but some scope between the reference scope (inclusive) and
741 // script scope (exclusive) makes a sloppy 'eval' call, that might
742 // possibly introduce a variable binding. Thus the reference should be
743 // considered referencing a global variable unless it is shadowed by an
744 // 'eval' introduced binding.
745 UNBOUND_EVAL_SHADOWED,
746
747 // The variable could not be statically resolved and needs to be looked up
748 // dynamically. NULL is returned. There are two possible reasons:
749 // * A 'with' statement has been encountered and there is no variable
750 // binding for the name between the variable reference and the 'with'.
751 // The variable potentially references a property of the 'with' object.
752 // * The code is being executed as part of a call to 'eval' and the calling
753 // context chain contains either a variable binding for the name or it
754 // contains a 'with' context.
755 DYNAMIC_LOOKUP
756 };
757
758 // Lookup a variable reference given by name recursively starting with this
759 // scope. If the code is executed because of a call to 'eval', the context
760 // parameter should be set to the calling context of 'eval'.
761 Variable* LookupRecursive(VariableProxy* proxy, BindingKind* binding_kind,
762 AstNodeFactory* factory);
763 MUST_USE_RESULT
764 bool ResolveVariable(ParseInfo* info, VariableProxy* proxy,
765 AstNodeFactory* factory);
766 MUST_USE_RESULT
767 bool ResolveVariablesRecursively(ParseInfo* info, AstNodeFactory* factory);
768
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000769 // Scope analysis.
770 void PropagateScopeInfo(bool outer_scope_calls_sloppy_eval);
771 bool HasTrivialContext() const;
772
773 // Predicates.
774 bool MustAllocate(Variable* var);
775 bool MustAllocateInContext(Variable* var);
776 bool HasArgumentsParameter(Isolate* isolate);
777
778 // Variable allocation.
779 void AllocateStackSlot(Variable* var);
780 void AllocateHeapSlot(Variable* var);
781 void AllocateParameterLocals(Isolate* isolate);
782 void AllocateNonParameterLocal(Isolate* isolate, Variable* var);
783 void AllocateDeclaredGlobal(Isolate* isolate, Variable* var);
784 void AllocateNonParameterLocalsAndDeclaredGlobals(Isolate* isolate);
785 void AllocateVariablesRecursively(Isolate* isolate);
786 void AllocateParameter(Variable* var, int index);
787 void AllocateReceiver();
788
789 // Resolve and fill in the allocation information for all variables
790 // in this scopes. Must be called *after* all scopes have been
791 // processed (parsed) to ensure that unresolved variables can be
792 // resolved properly.
793 //
794 // In the case of code compiled and run using 'eval', the context
795 // parameter is the context in which eval was called. In all other
796 // cases the context parameter is an empty handle.
797 MUST_USE_RESULT
798 bool AllocateVariables(ParseInfo* info, AstNodeFactory* factory);
799
800 // Construct a scope based on the scope info.
801 Scope(Zone* zone, Scope* inner_scope, ScopeType type,
802 Handle<ScopeInfo> scope_info, AstValueFactory* value_factory);
803
804 // Construct a catch scope with a binding for the name.
805 Scope(Zone* zone, Scope* inner_scope, const AstRawString* catch_variable_name,
806 AstValueFactory* value_factory);
807
808 void AddInnerScope(Scope* inner_scope) {
809 if (inner_scope != NULL) {
810 inner_scopes_.Add(inner_scope, zone_);
811 inner_scope->outer_scope_ = this;
812 }
813 }
814
815 void RemoveInnerScope(Scope* inner_scope) {
816 DCHECK_NOT_NULL(inner_scope);
817 for (int i = 0; i < inner_scopes_.length(); i++) {
818 if (inner_scopes_[i] == inner_scope) {
819 inner_scopes_.Remove(i);
820 break;
821 }
822 }
823 }
824
825 void SetDefaults(ScopeType type, Scope* outer_scope,
826 Handle<ScopeInfo> scope_info,
827 FunctionKind function_kind = kNormalFunction);
828
829 AstValueFactory* ast_value_factory_;
830 Zone* zone_;
831
832 PendingCompilationErrorHandler pending_error_handler_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000833};
834
835} // namespace internal
836} // namespace v8
837
838#endif // V8_AST_SCOPES_H_