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