blob: d767a33de05a285ab9b97112ca1f7ff4acabb7d8 [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.
Ben Murdochc5610432016-08-08 18:44:38 +0100212 // Returns the index at which it was found in this scope, or -1 if
213 // it was not found.
214 int RemoveTemporary(Variable* var);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000215
216 // Adds a temporary variable in this scope's TemporaryScope. This is for
217 // adjusting the scope of temporaries used when desugaring parameter
218 // initializers.
219 void AddTemporary(Variable* var) { temps_.Add(var, zone()); }
220
221 // Adds the specific declaration node to the list of declarations in
222 // this scope. The declarations are processed as part of entering
223 // the scope; see codegen.cc:ProcessDeclarations.
224 void AddDeclaration(Declaration* declaration);
225
226 // ---------------------------------------------------------------------------
227 // Illegal redeclaration support.
228
Ben Murdochda12d292016-06-02 14:46:10 +0100229 // Check if the scope has conflicting var
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000230 // declarations, i.e. a var declaration that has been hoisted from a nested
231 // scope over a let binding of the same name.
232 Declaration* CheckConflictingVarDeclarations();
233
234 // ---------------------------------------------------------------------------
235 // Scope-specific info.
236
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000237 // Inform the scope that the corresponding code contains an eval call.
238 void RecordEvalCall() { scope_calls_eval_ = true; }
239
240 // Inform the scope that the corresponding code uses "arguments".
241 void RecordArgumentsUsage() { scope_uses_arguments_ = true; }
242
243 // Inform the scope that the corresponding code uses "super".
244 void RecordSuperPropertyUsage() { scope_uses_super_property_ = true; }
245
246 // Set the language mode flag (unless disabled by a global flag).
247 void SetLanguageMode(LanguageMode language_mode) {
Ben Murdochc5610432016-08-08 18:44:38 +0100248 DCHECK(!is_module_scope() || is_strict(language_mode));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000249 language_mode_ = language_mode;
250 }
251
252 // Set the ASM module flag.
253 void SetAsmModule() { asm_module_ = true; }
254
255 // Inform the scope that the scope may execute declarations nonlinearly.
256 // Currently, the only nonlinear scope is a switch statement. The name is
257 // more general in case something else comes up with similar control flow,
258 // for example the ability to break out of something which does not have
259 // its own lexical scope.
260 // The bit does not need to be stored on the ScopeInfo because none of
261 // the three compilers will perform hole check elimination on a variable
262 // located in VariableLocation::CONTEXT. So, direct eval and closures
263 // will not expose holes.
264 void SetNonlinear() { scope_nonlinear_ = true; }
265
266 // Position in the source where this scope begins and ends.
267 //
268 // * For the scope of a with statement
269 // with (obj) stmt
270 // start position: start position of first token of 'stmt'
271 // end position: end position of last token of 'stmt'
272 // * For the scope of a block
273 // { stmts }
274 // start position: start position of '{'
275 // end position: end position of '}'
276 // * For the scope of a function literal or decalaration
277 // function fun(a,b) { stmts }
278 // start position: start position of '('
279 // end position: end position of '}'
280 // * For the scope of a catch block
281 // try { stms } catch(e) { stmts }
282 // start position: start position of '('
283 // end position: end position of ')'
284 // * For the scope of a for-statement
285 // for (let x ...) stmt
286 // start position: start position of '('
287 // end position: end position of last token of 'stmt'
288 // * For the scope of a switch statement
289 // switch (tag) { cases }
290 // start position: start position of '{'
291 // end position: end position of '}'
292 int start_position() const { return start_position_; }
293 void set_start_position(int statement_pos) {
294 start_position_ = statement_pos;
295 }
296 int end_position() const { return end_position_; }
297 void set_end_position(int statement_pos) {
298 end_position_ = statement_pos;
299 }
300
Ben Murdochc5610432016-08-08 18:44:38 +0100301 // Scopes created for desugaring are hidden. I.e. not visible to the debugger.
302 bool is_hidden() const { return is_hidden_; }
303 void set_is_hidden() { is_hidden_ = true; }
304
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000305 // In some cases we want to force context allocation for a whole scope.
306 void ForceContextAllocation() {
307 DCHECK(!already_resolved());
308 force_context_allocation_ = true;
309 }
310 bool has_forced_context_allocation() const {
311 return force_context_allocation_;
312 }
313
314 // ---------------------------------------------------------------------------
315 // Predicates.
316
317 // Specific scope types.
318 bool is_eval_scope() const { return scope_type_ == EVAL_SCOPE; }
319 bool is_function_scope() const { return scope_type_ == FUNCTION_SCOPE; }
320 bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
321 bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
322 bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
323 bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
324 bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
325 bool is_arrow_scope() const {
326 return is_function_scope() && IsArrowFunction(function_kind_);
327 }
328 bool is_declaration_scope() const { return is_declaration_scope_; }
329
330 void set_is_declaration_scope() { is_declaration_scope_ = true; }
331
332 // Information about which scopes calls eval.
333 bool calls_eval() const { return scope_calls_eval_; }
334 bool calls_sloppy_eval() const {
335 return scope_calls_eval_ && is_sloppy(language_mode_);
336 }
337 bool outer_scope_calls_sloppy_eval() const {
338 return outer_scope_calls_sloppy_eval_;
339 }
340 bool asm_module() const { return asm_module_; }
341 bool asm_function() const { return asm_function_; }
342
343 // Is this scope inside a with statement.
344 bool inside_with() const { return scope_inside_with_; }
345
346 // Does this scope access "arguments".
347 bool uses_arguments() const { return scope_uses_arguments_; }
348 // Does this scope access "super" property (super.foo).
349 bool uses_super_property() const { return scope_uses_super_property_; }
350 // Does this scope have the potential to execute declarations non-linearly?
351 bool is_nonlinear() const { return scope_nonlinear_; }
352
353 // Whether this needs to be represented by a runtime context.
354 bool NeedsContext() const {
355 // Catch and module scopes always have heap slots.
356 DCHECK(!is_catch_scope() || num_heap_slots() > 0);
357 DCHECK(!is_module_scope() || num_heap_slots() > 0);
358 return is_with_scope() || num_heap_slots() > 0;
359 }
360
361 bool NeedsHomeObject() const {
362 return scope_uses_super_property_ ||
363 ((scope_calls_eval_ || inner_scope_calls_eval_) &&
364 (IsConciseMethod(function_kind()) ||
365 IsAccessorFunction(function_kind()) ||
366 IsClassConstructor(function_kind())));
367 }
368
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000369 // ---------------------------------------------------------------------------
370 // Accessors.
371
372 // The type of this scope.
373 ScopeType scope_type() const { return scope_type_; }
374
375 FunctionKind function_kind() const { return function_kind_; }
376
377 // The language mode of this scope.
378 LanguageMode language_mode() const { return language_mode_; }
379
380 // The variable corresponding to the 'this' value.
381 Variable* receiver() {
382 DCHECK(has_this_declaration());
383 DCHECK_NOT_NULL(receiver_);
384 return receiver_;
385 }
386
387 // TODO(wingo): Add a GLOBAL_SCOPE scope type which will lexically allocate
388 // "this" (and no other variable) on the native context. Script scopes then
389 // will not have a "this" declaration.
390 bool has_this_declaration() const {
391 return (is_function_scope() && !is_arrow_scope()) || is_module_scope();
392 }
393
394 // The variable corresponding to the 'new.target' value.
395 Variable* new_target_var() { return new_target_; }
396
397 // The variable holding the function literal for named function
398 // literals, or NULL. Only valid for function scopes.
399 VariableDeclaration* function() const {
400 DCHECK(is_function_scope());
401 return function_;
402 }
403
404 // Parameters. The left-most parameter has index 0.
405 // Only valid for function scopes.
406 Variable* parameter(int index) const {
407 DCHECK(is_function_scope());
408 return params_[index];
409 }
410
411 // Returns the default function arity excluding default or rest parameters.
412 int default_function_length() const { return arity_; }
413
Ben Murdoch097c5b22016-05-18 11:27:45 +0100414 // Returns the number of formal parameters, up to but not including the
415 // rest parameter index (if the function has rest parameters), i.e. it
416 // says 2 for
417 //
418 // function foo(a, b) { ... }
419 //
420 // and
421 //
422 // function foo(a, b, ...c) { ... }
423 //
424 // but for
425 //
426 // function foo(a, b, c = 1) { ... }
427 //
428 // we return 3 here.
429 int num_parameters() const {
430 return has_rest_parameter() ? params_.length() - 1 : params_.length();
431 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000432
433 // A function can have at most one rest parameter. Returns Variable* or NULL.
434 Variable* rest_parameter(int* index) const {
435 *index = rest_index_;
436 if (rest_index_ < 0) return NULL;
437 return rest_parameter_;
438 }
439
440 bool has_rest_parameter() const { return rest_index_ >= 0; }
441
442 bool has_simple_parameters() const {
443 return has_simple_parameters_;
444 }
445
446 // TODO(caitp): manage this state in a better way. PreParser must be able to
447 // communicate that the scope is non-simple, without allocating any parameters
448 // as the Parser does. This is necessary to ensure that TC39's proposed early
449 // error can be reported consistently regardless of whether lazily parsed or
450 // not.
451 void SetHasNonSimpleParameters() {
452 DCHECK(is_function_scope());
453 has_simple_parameters_ = false;
454 }
455
456 // Retrieve `IsSimpleParameterList` of current or outer function.
457 bool HasSimpleParameters() {
458 Scope* scope = ClosureScope();
459 return !scope->is_function_scope() || scope->has_simple_parameters();
460 }
461
462 // The local variable 'arguments' if we need to allocate it; NULL otherwise.
463 Variable* arguments() const {
464 DCHECK(!is_arrow_scope() || arguments_ == nullptr);
465 return arguments_;
466 }
467
468 Variable* this_function_var() const {
469 // This is only used in derived constructors atm.
470 DCHECK(this_function_ == nullptr ||
471 (is_function_scope() && (IsClassConstructor(function_kind()) ||
472 IsConciseMethod(function_kind()) ||
473 IsAccessorFunction(function_kind()))));
474 return this_function_;
475 }
476
477 // Declarations list.
478 ZoneList<Declaration*>* declarations() { return &decls_; }
479
480 // Inner scope list.
481 ZoneList<Scope*>* inner_scopes() { return &inner_scopes_; }
482
483 // The scope immediately surrounding this scope, or NULL.
484 Scope* outer_scope() const { return outer_scope_; }
485
486 // The ModuleDescriptor for this scope; only for module scopes.
487 ModuleDescriptor* module() const { return module_descriptor_; }
488
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000489 // ---------------------------------------------------------------------------
490 // Variable allocation.
491
492 // Collect stack and context allocated local variables in this scope. Note
493 // that the function variable - if present - is not collected and should be
494 // handled separately.
Ben Murdoch097c5b22016-05-18 11:27:45 +0100495 void CollectStackAndContextLocals(ZoneList<Variable*>* stack_locals,
496 ZoneList<Variable*>* context_locals,
497 ZoneList<Variable*>* context_globals);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000498
499 // Current number of var or const locals.
500 int num_var_or_const() { return num_var_or_const_; }
501
502 // Result of variable allocation.
503 int num_stack_slots() const { return num_stack_slots_; }
504 int num_heap_slots() const { return num_heap_slots_; }
505 int num_global_slots() const { return num_global_slots_; }
506
507 int StackLocalCount() const;
508 int ContextLocalCount() const;
509 int ContextGlobalCount() const;
510
511 // Make sure this scope and all outer scopes are eagerly compiled.
512 void ForceEagerCompilation() { force_eager_compilation_ = true; }
513
514 // Determine if we can parse a function literal in this scope lazily.
515 bool AllowsLazyParsing() const;
516
517 // Determine if we can use lazy compilation for this scope.
518 bool AllowsLazyCompilation() const;
519
520 // Determine if we can use lazy compilation for this scope without a context.
521 bool AllowsLazyCompilationWithoutContext() const;
522
523 // True if the outer context of this scope is always the native context.
524 bool HasTrivialOuterContext() const;
525
526 // The number of contexts between this and scope; zero if this == scope.
527 int ContextChainLength(Scope* scope);
528
529 // The maximum number of nested contexts required for this scope and any inner
530 // scopes.
531 int MaxNestedContextChainLength();
532
533 // Find the first function, script, eval or (declaration) block scope. This is
534 // the scope where var declarations will be hoisted to in the implementation.
535 Scope* DeclarationScope();
536
537 // Find the first non-block declaration scope. This should be either a script,
538 // function, or eval scope. Same as DeclarationScope(), but skips
539 // declaration "block" scopes. Used for differentiating associated
540 // function objects (i.e., the scope for which a function prologue allocates
541 // a context) or declaring temporaries.
542 Scope* ClosureScope();
543
544 // Find the first (non-arrow) function or script scope. This is where
545 // 'this' is bound, and what determines the function kind.
546 Scope* ReceiverScope();
547
548 Handle<ScopeInfo> GetScopeInfo(Isolate* isolate);
549
Ben Murdochda12d292016-06-02 14:46:10 +0100550 Handle<StringSet> CollectNonLocals(Handle<StringSet> non_locals);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000551
552 // ---------------------------------------------------------------------------
553 // Strict mode support.
554 bool IsDeclared(const AstRawString* name) {
555 // During formal parameter list parsing the scope only contains
556 // two variables inserted at initialization: "this" and "arguments".
557 // "this" is an invalid parameter name and "arguments" is invalid parameter
558 // name in strict mode. Therefore looking up with the map which includes
559 // "this" and "arguments" in addition to all formal parameters is safe.
560 return variables_.Lookup(name) != NULL;
561 }
562
563 bool IsDeclaredParameter(const AstRawString* name) {
564 // If IsSimpleParameterList is false, duplicate parameters are not allowed,
565 // however `arguments` may be allowed if function is not strict code. Thus,
566 // the assumptions explained above do not hold.
567 return params_.Contains(variables_.Lookup(name));
568 }
569
570 SloppyBlockFunctionMap* sloppy_block_function_map() {
571 return &sloppy_block_function_map_;
572 }
573
574 // Error handling.
575 void ReportMessage(int start_position, int end_position,
576 MessageTemplate::Template message,
577 const AstRawString* arg);
578
579 // ---------------------------------------------------------------------------
580 // Debugging.
581
582#ifdef DEBUG
583 void Print(int n = 0); // n = indentation; n < 0 => don't print recursively
Ben Murdochc5610432016-08-08 18:44:38 +0100584
585 // Check that the scope has positions assigned.
586 void CheckScopePositions();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000587#endif
588
589 // ---------------------------------------------------------------------------
590 // Implementation.
591 private:
592 // Scope tree.
593 Scope* outer_scope_; // the immediately enclosing outer scope, or NULL
594 ZoneList<Scope*> inner_scopes_; // the immediately enclosed inner scopes
595
596 // The scope type.
597 ScopeType scope_type_;
598 // If the scope is a function scope, this is the function kind.
599 FunctionKind function_kind_;
600
601 // Debugging support.
602 const AstRawString* scope_name_;
603
604 // The variables declared in this scope:
605 //
606 // All user-declared variables (incl. parameters). For script scopes
607 // variables may be implicitly 'declared' by being used (possibly in
608 // an inner scope) with no intervening with statements or eval calls.
609 VariableMap variables_;
Ben Murdochc5610432016-08-08 18:44:38 +0100610 // Compiler-allocated (user-invisible) temporaries. Due to the implementation
611 // of RemoveTemporary(), may contain nulls, which must be skipped-over during
612 // allocation and printing.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000613 ZoneList<Variable*> temps_;
614 // Parameter list in source order.
615 ZoneList<Variable*> params_;
616 // Variables that must be looked up dynamically.
617 DynamicScopePart* dynamics_;
618 // Unresolved variables referred to from this scope.
619 ZoneList<VariableProxy*> unresolved_;
620 // Declarations.
621 ZoneList<Declaration*> decls_;
622 // Convenience variable.
623 Variable* receiver_;
624 // Function variable, if any; function scopes only.
625 VariableDeclaration* function_;
626 // new.target variable, function scopes only.
627 Variable* new_target_;
628 // Convenience variable; function scopes only.
629 Variable* arguments_;
630 // Convenience variable; Subclass constructor only
631 Variable* this_function_;
632 // Module descriptor; module scopes only.
633 ModuleDescriptor* module_descriptor_;
634
635 // Map of function names to lists of functions defined in sloppy blocks
636 SloppyBlockFunctionMap sloppy_block_function_map_;
637
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000638 // Scope-specific information computed during parsing.
639 //
640 // This scope is inside a 'with' of some outer scope.
641 bool scope_inside_with_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000642 // This scope or a nested catch scope or with scope contain an 'eval' call. At
643 // the 'eval' call site this scope is the declaration scope.
644 bool scope_calls_eval_;
645 // This scope uses "arguments".
646 bool scope_uses_arguments_;
647 // This scope uses "super" property ('super.foo').
648 bool scope_uses_super_property_;
649 // This scope contains an "use asm" annotation.
650 bool asm_module_;
651 // This scope's outer context is an asm module.
652 bool asm_function_;
653 // This scope's declarations might not be executed in order (e.g., switch).
654 bool scope_nonlinear_;
655 // The language mode of this scope.
656 LanguageMode language_mode_;
657 // Source positions.
658 int start_position_;
659 int end_position_;
Ben Murdochc5610432016-08-08 18:44:38 +0100660 bool is_hidden_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000661
662 // Computed via PropagateScopeInfo.
663 bool outer_scope_calls_sloppy_eval_;
664 bool inner_scope_calls_eval_;
665 bool force_eager_compilation_;
666 bool force_context_allocation_;
667
668 // True if it doesn't need scope resolution (e.g., if the scope was
669 // constructed based on a serialized scope info or a catch context).
670 bool already_resolved_;
671
672 // True if it holds 'var' declarations.
673 bool is_declaration_scope_;
674
675 // Computed as variables are declared.
676 int num_var_or_const_;
677
678 // Computed via AllocateVariables; function, block and catch scopes only.
679 int num_stack_slots_;
680 int num_heap_slots_;
681 int num_global_slots_;
682
683 // Info about the parameter list of a function.
684 int arity_;
685 bool has_simple_parameters_;
686 Variable* rest_parameter_;
687 int rest_index_;
688
689 // Serialized scope info support.
690 Handle<ScopeInfo> scope_info_;
691 bool already_resolved() { return already_resolved_; }
692
693 // Create a non-local variable with a given name.
694 // These variables are looked up dynamically at runtime.
695 Variable* NonLocal(const AstRawString* name, VariableMode mode);
696
697 // Variable resolution.
698 // Possible results of a recursive variable lookup telling if and how a
699 // variable is bound. These are returned in the output parameter *binding_kind
700 // of the LookupRecursive function.
701 enum BindingKind {
702 // The variable reference could be statically resolved to a variable binding
703 // which is returned. There is no 'with' statement between the reference and
704 // the binding and no scope between the reference scope (inclusive) and
705 // binding scope (exclusive) makes a sloppy 'eval' call.
706 BOUND,
707
708 // The variable reference could be statically resolved to a variable binding
709 // which is returned. There is no 'with' statement between the reference and
710 // the binding, but some scope between the reference scope (inclusive) and
711 // binding scope (exclusive) makes a sloppy 'eval' call, that might
712 // possibly introduce variable bindings shadowing the found one. Thus the
713 // found variable binding is just a guess.
714 BOUND_EVAL_SHADOWED,
715
716 // The variable reference could not be statically resolved to any binding
717 // and thus should be considered referencing a global variable. NULL is
718 // returned. The variable reference is not inside any 'with' statement and
719 // no scope between the reference scope (inclusive) and script scope
720 // (exclusive) makes a sloppy 'eval' call.
721 UNBOUND,
722
723 // The variable reference could not be statically resolved to any binding
724 // NULL is returned. The variable reference is not inside any 'with'
725 // statement, but some scope between the reference scope (inclusive) and
726 // script scope (exclusive) makes a sloppy 'eval' call, that might
727 // possibly introduce a variable binding. Thus the reference should be
728 // considered referencing a global variable unless it is shadowed by an
729 // 'eval' introduced binding.
730 UNBOUND_EVAL_SHADOWED,
731
732 // The variable could not be statically resolved and needs to be looked up
733 // dynamically. NULL is returned. There are two possible reasons:
734 // * A 'with' statement has been encountered and there is no variable
735 // binding for the name between the variable reference and the 'with'.
736 // The variable potentially references a property of the 'with' object.
737 // * The code is being executed as part of a call to 'eval' and the calling
738 // context chain contains either a variable binding for the name or it
739 // contains a 'with' context.
740 DYNAMIC_LOOKUP
741 };
742
743 // Lookup a variable reference given by name recursively starting with this
744 // scope. If the code is executed because of a call to 'eval', the context
745 // parameter should be set to the calling context of 'eval'.
746 Variable* LookupRecursive(VariableProxy* proxy, BindingKind* binding_kind,
747 AstNodeFactory* factory);
748 MUST_USE_RESULT
749 bool ResolveVariable(ParseInfo* info, VariableProxy* proxy,
750 AstNodeFactory* factory);
751 MUST_USE_RESULT
752 bool ResolveVariablesRecursively(ParseInfo* info, AstNodeFactory* factory);
753
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000754 // Scope analysis.
755 void PropagateScopeInfo(bool outer_scope_calls_sloppy_eval);
756 bool HasTrivialContext() const;
757
758 // Predicates.
759 bool MustAllocate(Variable* var);
760 bool MustAllocateInContext(Variable* var);
761 bool HasArgumentsParameter(Isolate* isolate);
762
763 // Variable allocation.
764 void AllocateStackSlot(Variable* var);
765 void AllocateHeapSlot(Variable* var);
766 void AllocateParameterLocals(Isolate* isolate);
767 void AllocateNonParameterLocal(Isolate* isolate, Variable* var);
768 void AllocateDeclaredGlobal(Isolate* isolate, Variable* var);
769 void AllocateNonParameterLocalsAndDeclaredGlobals(Isolate* isolate);
770 void AllocateVariablesRecursively(Isolate* isolate);
771 void AllocateParameter(Variable* var, int index);
772 void AllocateReceiver();
773
774 // Resolve and fill in the allocation information for all variables
775 // in this scopes. Must be called *after* all scopes have been
776 // processed (parsed) to ensure that unresolved variables can be
777 // resolved properly.
778 //
779 // In the case of code compiled and run using 'eval', the context
780 // parameter is the context in which eval was called. In all other
781 // cases the context parameter is an empty handle.
782 MUST_USE_RESULT
783 bool AllocateVariables(ParseInfo* info, AstNodeFactory* factory);
784
785 // Construct a scope based on the scope info.
786 Scope(Zone* zone, Scope* inner_scope, ScopeType type,
787 Handle<ScopeInfo> scope_info, AstValueFactory* value_factory);
788
789 // Construct a catch scope with a binding for the name.
790 Scope(Zone* zone, Scope* inner_scope, const AstRawString* catch_variable_name,
791 AstValueFactory* value_factory);
792
793 void AddInnerScope(Scope* inner_scope) {
794 if (inner_scope != NULL) {
795 inner_scopes_.Add(inner_scope, zone_);
796 inner_scope->outer_scope_ = this;
797 }
798 }
799
800 void RemoveInnerScope(Scope* inner_scope) {
801 DCHECK_NOT_NULL(inner_scope);
802 for (int i = 0; i < inner_scopes_.length(); i++) {
803 if (inner_scopes_[i] == inner_scope) {
804 inner_scopes_.Remove(i);
805 break;
806 }
807 }
808 }
809
810 void SetDefaults(ScopeType type, Scope* outer_scope,
811 Handle<ScopeInfo> scope_info,
812 FunctionKind function_kind = kNormalFunction);
813
814 AstValueFactory* ast_value_factory_;
815 Zone* zone_;
816
817 PendingCompilationErrorHandler pending_error_handler_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000818};
819
820} // namespace internal
821} // namespace v8
822
823#endif // V8_AST_SCOPES_H_