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