Scope tree serialization and ScopeIterator cleanup.
authorkeuchel@chromium.org <keuchel@chromium.org@ce2b1a6d-e550-0410-aec6-3dcde31c8c00>
Tue, 18 Oct 2011 08:46:46 +0000 (08:46 +0000)
committerkeuchel@chromium.org <keuchel@chromium.org@ce2b1a6d-e550-0410-aec6-3dcde31c8c00>
Tue, 18 Oct 2011 08:46:46 +0000 (08:46 +0000)
The intention is to store enough scope information for the debugger to
handle stack allocation of block scoped variables introduced by
http://codereview.chromium.org/7860045/ .

This CL is based on
http://codereview.chromium.org/7904008/ .

Review URL: http://codereview.chromium.org/7979001

git-svn-id: http://v8.googlecode.com/svn/branches/bleeding_edge@9673 ce2b1a6d-e550-0410-aec6-3dcde31c8c00

14 files changed:
src/ast-inl.h
src/ast.h
src/contexts.h
src/objects.h
src/parser.cc
src/parser.h
src/runtime.cc
src/scopeinfo.cc
src/scopeinfo.h
src/scopes.cc
src/scopes.h
src/v8globals.h
test/cctest/test-parsing.cc
test/mjsunit/debug-scopes.js

index 731ad2f..a3af259 100644 (file)
@@ -111,6 +111,16 @@ ForInStatement::ForInStatement(Isolate* isolate, ZoneStringList* labels)
 }
 
 
+int FunctionLiteral::start_position() const {
+  return scope()->start_position();
+}
+
+
+int FunctionLiteral::end_position() const {
+  return scope()->end_position();
+}
+
+
 bool FunctionLiteral::strict_mode() const {
   return scope()->is_strict_mode();
 }
index 2ae1364..cb7763b 100644 (file)
--- a/src/ast.h
+++ b/src/ast.h
@@ -1617,8 +1617,6 @@ class FunctionLiteral: public Expression {
                   bool has_only_simple_this_property_assignments,
                   Handle<FixedArray> this_property_assignments,
                   int num_parameters,
-                  int start_position,
-                  int end_position,
                   Type type,
                   bool has_duplicate_parameters)
       : Expression(isolate),
@@ -1631,8 +1629,6 @@ class FunctionLiteral: public Expression {
             has_only_simple_this_property_assignments),
         this_property_assignments_(this_property_assignments),
         num_parameters_(num_parameters),
-        start_position_(start_position),
-        end_position_(end_position),
         function_token_position_(RelocInfo::kNoPosition),
         inferred_name_(HEAP->empty_string()),
         is_expression_(type != DECLARATION),
@@ -1648,8 +1644,8 @@ class FunctionLiteral: public Expression {
   ZoneList<Statement*>* body() const { return body_; }
   void set_function_token_position(int pos) { function_token_position_ = pos; }
   int function_token_position() const { return function_token_position_; }
-  int start_position() const { return start_position_; }
-  int end_position() const { return end_position_; }
+  int start_position() const;
+  int end_position() const;
   bool is_expression() const { return is_expression_; }
   bool is_anonymous() const { return is_anonymous_; }
   bool strict_mode() const;
index ba5ee87..fe0e22e 100644 (file)
@@ -194,7 +194,8 @@ class Context: public FixedArray {
     PREVIOUS_INDEX,
     // The extension slot is used for either the global object (in global
     // contexts), eval extension object (function contexts), subject of with
-    // (with contexts), or the variable name (catch contexts).
+    // (with contexts), or the variable name (catch contexts), the serialized
+    // scope info (block contexts).
     EXTENSION_INDEX,
     GLOBAL_INDEX,
     MIN_CONTEXT_SLOTS,
index fd5dc4a..1a42811 100644 (file)
@@ -3020,6 +3020,9 @@ class SerializedScopeInfo : public FixedArray {
     return reinterpret_cast<SerializedScopeInfo*>(object);
   }
 
+  // Return the type of this scope.
+  ScopeType Type();
+
   // Does this scope call eval?
   bool CallsEval();
 
@@ -3035,6 +3038,9 @@ class SerializedScopeInfo : public FixedArray {
   // Return if this has context slots besides MIN_CONTEXT_SLOTS;
   bool HasHeapAllocatedLocals();
 
+  // Return if contexts are allocated for this scope.
+  bool HasContext();
+
   // Lookup support for serialized scope info. Returns the
   // the stack slot index for a given slot name if the slot is
   // present; otherwise returns a value < 0. The name must be a symbol
index edd2e53..b272fa9 100644 (file)
@@ -407,7 +407,7 @@ unsigned* ScriptDataImpl::ReadAddress(int position) {
 }
 
 
-Scope* Parser::NewScope(Scope* parent, Scope::Type type) {
+Scope* Parser::NewScope(Scope* parent, ScopeType type) {
   Scope* result = new(zone()) Scope(parent, type);
   result->Initialize();
   return result;
@@ -643,14 +643,13 @@ FunctionLiteral* Parser::DoParseProgram(Handle<String> source,
   mode_ = FLAG_lazy ? PARSE_LAZILY : PARSE_EAGERLY;
   if (allow_natives_syntax_ || extension_ != NULL) mode_ = PARSE_EAGERLY;
 
-  Scope::Type type =
-    in_global_context
-      ? Scope::GLOBAL_SCOPE
-      : Scope::EVAL_SCOPE;
+  ScopeType type = in_global_context ? GLOBAL_SCOPE : EVAL_SCOPE;
   Handle<String> no_name = isolate()->factory()->empty_symbol();
 
   FunctionLiteral* result = NULL;
   { Scope* scope = NewScope(top_scope_, type);
+    scope->set_start_position(0);
+    scope->set_end_position(source->length());
     LexicalScope lexical_scope(this, scope, isolate());
     if (strict_mode == kStrictMode) {
       top_scope_->EnableStrictMode();
@@ -678,8 +677,6 @@ FunctionLiteral* Parser::DoParseProgram(Handle<String> source,
           lexical_scope.only_simple_this_property_assignments(),
           lexical_scope.this_property_assignments(),
           0,
-          0,
-          source->length(),
           FunctionLiteral::ANONYMOUS_EXPRESSION,
           false);  // Does not have duplicate parameters.
     } else if (stack_overflow_) {
@@ -740,7 +737,7 @@ FunctionLiteral* Parser::ParseLazy(CompilationInfo* info,
 
   {
     // Parse the function literal.
-    Scope* scope = NewScope(top_scope_, Scope::GLOBAL_SCOPE);
+    Scope* scope = NewScope(top_scope_, GLOBAL_SCOPE);
     if (!info->closure().is_null()) {
       scope = Scope::DeserializeScopeChain(info, scope);
     }
@@ -1595,13 +1592,14 @@ Block* Parser::ParseScopedBlock(ZoneStringList* labels, bool* ok) {
 
   // Construct block expecting 16 statements.
   Block* body = new(zone()) Block(isolate(), labels, 16, false);
-  Scope* block_scope = NewScope(top_scope_, Scope::BLOCK_SCOPE);
+  Scope* block_scope = NewScope(top_scope_, BLOCK_SCOPE);
   if (top_scope_->is_strict_mode()) {
     block_scope->EnableStrictMode();
   }
 
   // Parse the statements and collect escaping labels.
   Expect(Token::LBRACE, CHECK_OK);
+  block_scope->set_start_position(scanner().location().beg_pos);
   { SaveScope save_scope(this, block_scope);
     TargetCollector collector;
     Target target(&this->target_stack_, &collector);
@@ -1617,7 +1615,7 @@ Block* Parser::ParseScopedBlock(ZoneStringList* labels, bool* ok) {
     }
   }
   Expect(Token::RBRACE, CHECK_OK);
-
+  block_scope->set_end_position(scanner().location().end_pos);
   block_scope = block_scope->FinalizeBlockScope();
   body->set_block_scope(block_scope);
   return body;
@@ -2114,10 +2112,12 @@ Statement* Parser::ParseWithStatement(ZoneStringList* labels, bool* ok) {
   Expect(Token::RPAREN, CHECK_OK);
 
   top_scope_->DeclarationScope()->RecordWithStatement();
-  Scope* with_scope = NewScope(top_scope_, Scope::WITH_SCOPE);
+  Scope* with_scope = NewScope(top_scope_, WITH_SCOPE);
   Statement* stmt;
   { SaveScope save_scope(this, with_scope);
+    with_scope->set_start_position(scanner().peek_location().beg_pos);
     stmt = ParseStatement(labels, CHECK_OK);
+    with_scope->set_end_position(scanner().location().end_pos);
   }
   return new(zone()) WithStatement(expr, stmt);
 }
@@ -2243,6 +2243,11 @@ TryStatement* Parser::ParseTryStatement(bool* ok) {
     Consume(Token::CATCH);
 
     Expect(Token::LPAREN, CHECK_OK);
+    catch_scope = NewScope(top_scope_, CATCH_SCOPE);
+    if (top_scope_->is_strict_mode()) {
+      catch_scope->EnableStrictMode();
+    }
+    catch_scope->set_start_position(scanner().location().beg_pos);
     name = ParseIdentifier(CHECK_OK);
 
     if (top_scope_->is_strict_mode() && IsEvalOrArguments(name)) {
@@ -2255,10 +2260,6 @@ TryStatement* Parser::ParseTryStatement(bool* ok) {
 
     if (peek() == Token::LBRACE) {
       Target target(&this->target_stack_, &catch_collector);
-      catch_scope = NewScope(top_scope_, Scope::CATCH_SCOPE);
-      if (top_scope_->is_strict_mode()) {
-        catch_scope->EnableStrictMode();
-      }
       VariableMode mode = harmony_scoping_ ? LET : VAR;
       catch_variable = catch_scope->DeclareLocal(name, mode);
 
@@ -2267,7 +2268,7 @@ TryStatement* Parser::ParseTryStatement(bool* ok) {
     } else {
       Expect(Token::LBRACE, CHECK_OK);
     }
-
+    catch_scope->set_end_position(scanner().location().end_pos);
     tok = peek();
   }
 
@@ -2375,7 +2376,7 @@ Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
 
   // Create an in-between scope for let-bound iteration variables.
   Scope* saved_scope = top_scope_;
-  Scope* for_scope = NewScope(top_scope_, Scope::BLOCK_SCOPE);
+  Scope* for_scope = NewScope(top_scope_, BLOCK_SCOPE);
   if (top_scope_->is_strict_mode()) {
     for_scope->EnableStrictMode();
   }
@@ -2383,6 +2384,7 @@ Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
 
   Expect(Token::FOR, CHECK_OK);
   Expect(Token::LPAREN, CHECK_OK);
+  for_scope->set_start_position(scanner().location().beg_pos);
   if (peek() != Token::SEMICOLON) {
     if (peek() == Token::VAR || peek() == Token::CONST) {
       Handle<String> name;
@@ -2404,6 +2406,7 @@ Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
         result->AddStatement(variable_statement);
         result->AddStatement(loop);
         top_scope_ = saved_scope;
+        for_scope->set_end_position(scanner().location().end_pos);
         for_scope = for_scope->FinalizeBlockScope();
         ASSERT(for_scope == NULL);
         // Parsed for-in loop w/ variable/const declaration.
@@ -2460,6 +2463,7 @@ Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
         body_block->AddStatement(body);
         loop->Initialize(temp_proxy, enumerable, body_block);
         top_scope_ = saved_scope;
+        for_scope->set_end_position(scanner().location().end_pos);
         for_scope = for_scope->FinalizeBlockScope();
         body_block->set_block_scope(for_scope);
         // Parsed for-in loop w/ let declaration.
@@ -2490,6 +2494,7 @@ Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
         Statement* body = ParseStatement(NULL, CHECK_OK);
         if (loop) loop->Initialize(expression, enumerable, body);
         top_scope_ = saved_scope;
+        for_scope->set_end_position(scanner().location().end_pos);
         for_scope = for_scope->FinalizeBlockScope();
         ASSERT(for_scope == NULL);
         // Parsed for-in loop.
@@ -2523,6 +2528,7 @@ Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
 
   Statement* body = ParseStatement(NULL, CHECK_OK);
   top_scope_ = saved_scope;
+  for_scope->set_end_position(scanner().location().end_pos);
   for_scope = for_scope->FinalizeBlockScope();
   if (for_scope != NULL) {
     // Rewrite a for statement of the form
@@ -3812,15 +3818,12 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
   // Function declarations are function scoped in normal mode, so they are
   // hoisted. In harmony block scoping mode they are block scoped, so they
   // are not hoisted.
-  Scope* scope = (type == FunctionLiteral::DECLARATION &&
-                  !harmony_scoping_)
-      ? NewScope(top_scope_->DeclarationScope(), Scope::FUNCTION_SCOPE)
-      : NewScope(top_scope_, Scope::FUNCTION_SCOPE);
+  Scope* scope = (type == FunctionLiteral::DECLARATION && !harmony_scoping_)
+      ? NewScope(top_scope_->DeclarationScope(), FUNCTION_SCOPE)
+      : NewScope(top_scope_, FUNCTION_SCOPE);
   ZoneList<Statement*>* body = new(zone()) ZoneList<Statement*>(8);
   int materialized_literal_count;
   int expected_property_count;
-  int start_pos;
-  int end_pos;
   bool only_simple_this_property_assignments;
   Handle<FixedArray> this_property_assignments;
   bool has_duplicate_parameters = false;
@@ -3831,7 +3834,7 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
     //  FormalParameterList ::
     //    '(' (Identifier)*[','] ')'
     Expect(Token::LPAREN, CHECK_OK);
-    start_pos = scanner().location().beg_pos;
+    scope->set_start_position(scanner().location().beg_pos);
     Scanner::Location name_loc = Scanner::Location::invalid();
     Scanner::Location dupe_loc = Scanner::Location::invalid();
     Scanner::Location reserved_loc = Scanner::Location::invalid();
@@ -3906,15 +3909,15 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
         // compile after all.
         is_lazily_compiled = false;
       } else {
-        end_pos = entry.end_pos();
-        if (end_pos <= function_block_pos) {
+        scope->set_end_position(entry.end_pos());
+        if (scope->end_position() <= function_block_pos) {
           // End position greater than end of stream is safe, and hard to check.
           ReportInvalidPreparseData(function_name, CHECK_OK);
         }
         isolate()->counters()->total_preparse_skipped()->Increment(
-            end_pos - function_block_pos);
+            scope->end_position() - function_block_pos);
         // Seek to position just before terminal '}'.
-        scanner().SeekForward(end_pos - 1);
+        scanner().SeekForward(scope->end_position() - 1);
         materialized_literal_count = entry.literal_count();
         expected_property_count = entry.property_count();
         if (entry.strict_mode()) top_scope_->EnableStrictMode();
@@ -3934,12 +3937,13 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
       this_property_assignments = lexical_scope.this_property_assignments();
 
       Expect(Token::RBRACE, CHECK_OK);
-      end_pos = scanner().location().end_pos;
+      scope->set_end_position(scanner().location().end_pos);
     }
 
     // Validate strict mode.
     if (top_scope_->is_strict_mode()) {
       if (IsEvalOrArguments(function_name)) {
+        int start_pos = scope->start_position();
         int position = function_token_position != RelocInfo::kNoPosition
             ? function_token_position
             : (start_pos > 0 ? start_pos - 1 : start_pos);
@@ -3962,6 +3966,7 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
         return NULL;
       }
       if (name_is_strict_reserved) {
+        int start_pos = scope->start_position();
         int position = function_token_position != RelocInfo::kNoPosition
             ? function_token_position
             : (start_pos > 0 ? start_pos - 1 : start_pos);
@@ -3977,7 +3982,9 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
         *ok = false;
         return NULL;
       }
-      CheckOctalLiteral(start_pos, end_pos, CHECK_OK);
+      CheckOctalLiteral(scope->start_position(),
+                        scope->end_position(),
+                        CHECK_OK);
     }
   }
 
@@ -3995,8 +4002,6 @@ FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
                                   only_simple_this_property_assignments,
                                   this_property_assignments,
                                   num_parameters,
-                                  start_pos,
-                                  end_pos,
                                   type,
                                   has_duplicate_parameters);
   function_literal->set_function_token_position(function_token_position);
index 8db44be..5c53cf8 100644 (file)
@@ -678,7 +678,7 @@ class Parser {
     return &empty;
   }
 
-  Scope* NewScope(Scope* parent, Scope::Type type);
+  Scope* NewScope(Scope* parent, ScopeType type);
 
   Handle<String> LookupSymbol(int symbol_id);
 
index e614103..eb1385c 100644 (file)
@@ -11068,9 +11068,10 @@ static Handle<JSObject> MaterializeBlockScope(
 }
 
 
-// Iterate over the actual scopes visible from a stack frame. All scopes are
+// Iterate over the actual scopes visible from a stack frame. The iteration
+// proceeds from the innermost visible nested scope outwards. All scopes are
 // backed by an actual context except the local scope, which is inserted
-// "artifically" in the context chain.
+// "artificially" in the context chain.
 class ScopeIterator {
  public:
   enum ScopeType {
@@ -11090,28 +11091,44 @@ class ScopeIterator {
       inlined_frame_index_(inlined_frame_index),
       function_(JSFunction::cast(frame->function())),
       context_(Context::cast(frame->context())),
-      local_done_(false),
-      at_local_(false) {
+      nested_scope_chain_(4) {
 
-    // Check whether the first scope is actually a local scope.
-    // If there is a stack slot for .result then this local scope has been
-    // created for evaluating top level code and it is not a real local scope.
+    // Check whether we are in global code or function code. If there is a stack
+    // slot for .result then this function has been created for evaluating
+    // global code and it is not a real function.
     // Checking for the existence of .result seems fragile, but the scope info
     // saved with the code object does not otherwise have that information.
     int index = function_->shared()->scope_info()->
         StackSlotIndex(isolate_->heap()->result_symbol());
+
+    // Reparse the code and analyze the scopes.
+    ZoneScope zone_scope(isolate, DELETE_ON_EXIT);
+    Handle<SharedFunctionInfo> shared_info(function_->shared());
+    Handle<Script> script(Script::cast(shared_info->script()));
+    Scope* scope;
     if (index >= 0) {
-      local_done_ = true;
-    } else if (context_->IsGlobalContext() ||
-               context_->IsFunctionContext()) {
-      at_local_ = true;
-    } else if (context_->closure() != *function_) {
-      // The context_ is a block or with or catch block from the outer function.
-      ASSERT(context_->IsWithContext() ||
-             context_->IsCatchContext() ||
-             context_->IsBlockContext());
-      at_local_ = true;
+      // Global code
+      CompilationInfo info(script);
+      info.MarkAsGlobal();
+      bool result = ParserApi::Parse(&info);
+      ASSERT(result);
+      result = Scope::Analyze(&info);
+      ASSERT(result);
+      scope = info.function()->scope();
+    } else {
+      // Function code
+      CompilationInfo info(shared_info);
+      bool result = ParserApi::Parse(&info);
+      ASSERT(result);
+      result = Scope::Analyze(&info);
+      ASSERT(result);
+      scope = info.function()->scope();
     }
+
+    // Retrieve the scope chain for the current position.
+    int statement_position =
+        shared_info->code()->SourceStatementPosition(frame_->pc());
+    scope->GetNestedScopeChain(&nested_scope_chain_, statement_position);
   }
 
   // More scopes?
@@ -11119,40 +11136,48 @@ class ScopeIterator {
 
   // Move to the next scope.
   void Next() {
-    // If at a local scope mark the local scope as passed.
-    if (at_local_) {
-      at_local_ = false;
-      local_done_ = true;
-
-      // If the current context is not associated with the local scope the
-      // current context is the next real scope, so don't move to the next
-      // context in this case.
-      if (context_->closure() != *function_) {
-        return;
-      }
-    }
-
-    // The global scope is always the last in the chain.
-    if (context_->IsGlobalContext()) {
+    ScopeType scope_type = Type();
+    if (scope_type == ScopeTypeGlobal) {
+      // The global scope is always the last in the chain.
+      ASSERT(context_->IsGlobalContext());
       context_ = Handle<Context>();
       return;
     }
-
-    // Move to the next context.
-    context_ = Handle<Context>(context_->previous(), isolate_);
-
-    // If passing the local scope indicate that the current scope is now the
-    // local scope.
-    if (!local_done_ &&
-        (context_->IsGlobalContext() || context_->IsFunctionContext())) {
-      at_local_ = true;
+    if (nested_scope_chain_.is_empty()) {
+      context_ = Handle<Context>(context_->previous(), isolate_);
+    } else {
+      if (nested_scope_chain_.last()->HasContext()) {
+        context_ = Handle<Context>(context_->previous(), isolate_);
+      }
+      nested_scope_chain_.RemoveLast();
     }
   }
 
   // Return the type of the current scope.
   ScopeType Type() {
-    if (at_local_) {
-      return ScopeTypeLocal;
+    if (!nested_scope_chain_.is_empty()) {
+      Handle<SerializedScopeInfo> scope_info = nested_scope_chain_.last();
+      switch (scope_info->Type()) {
+        case FUNCTION_SCOPE:
+          ASSERT(context_->IsFunctionContext() ||
+                 !scope_info->HasContext());
+          return ScopeTypeLocal;
+        case GLOBAL_SCOPE:
+          ASSERT(context_->IsGlobalContext());
+          return ScopeTypeGlobal;
+        case WITH_SCOPE:
+          ASSERT(context_->IsWithContext());
+          return ScopeTypeWith;
+        case CATCH_SCOPE:
+          ASSERT(context_->IsCatchContext());
+          return ScopeTypeCatch;
+        case BLOCK_SCOPE:
+          ASSERT(!scope_info->HasContext() ||
+                 context_->IsBlockContext());
+          return ScopeTypeBlock;
+        case EVAL_SCOPE:
+          UNREACHABLE();
+      }
     }
     if (context_->IsGlobalContext()) {
       ASSERT(context_->global()->IsGlobalObject());
@@ -11178,6 +11203,7 @@ class ScopeIterator {
         return Handle<JSObject>(CurrentContext()->global());
       case ScopeIterator::ScopeTypeLocal:
         // Materialize the content of the local scope into a JSObject.
+        ASSERT(nested_scope_chain_.length() == 1);
         return MaterializeLocalScope(isolate_, frame_, inlined_frame_index_);
       case ScopeIterator::ScopeTypeWith:
         // Return the with object.
@@ -11194,13 +11220,30 @@ class ScopeIterator {
     return Handle<JSObject>();
   }
 
+  Handle<SerializedScopeInfo> CurrentScopeInfo() {
+    if (!nested_scope_chain_.is_empty()) {
+      return nested_scope_chain_.last();
+    } else if (context_->IsBlockContext()) {
+      return Handle<SerializedScopeInfo>(
+          SerializedScopeInfo::cast(context_->extension()));
+    } else if (context_->IsFunctionContext()) {
+      return Handle<SerializedScopeInfo>(
+          context_->closure()->shared()->scope_info());
+    }
+    return Handle<SerializedScopeInfo>::null();
+  }
+
   // Return the context for this scope. For the local context there might not
   // be an actual context.
   Handle<Context> CurrentContext() {
-    if (at_local_ && context_->closure() != *function_) {
+    if (Type() == ScopeTypeGlobal ||
+        nested_scope_chain_.is_empty()) {
+      return context_;
+    } else if (nested_scope_chain_.last()->HasContext()) {
+      return context_;
+    } else {
       return Handle<Context>();
     }
-    return context_;
   }
 
 #ifdef DEBUG
@@ -11263,8 +11306,7 @@ class ScopeIterator {
   int inlined_frame_index_;
   Handle<JSFunction> function_;
   Handle<Context> context_;
-  bool local_done_;
-  bool at_local_;
+  List<Handle<SerializedScopeInfo> > nested_scope_chain_;
 
   DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeIterator);
 };
@@ -11727,46 +11769,65 @@ RUNTIME_FUNCTION(MaybeObject*, Runtime_ClearStepping) {
 
 // Creates a copy of the with context chain. The copy of the context chain is
 // is linked to the function context supplied.
-static Handle<Context> CopyWithContextChain(Isolate* isolate,
-                                            Handle<JSFunction> function,
-                                            Handle<Context> current,
-                                            Handle<Context> base) {
-  // At the end of the chain. Return the base context to link to.
-  if (current->IsFunctionContext() || current->IsGlobalContext()) {
-    return base;
+static Handle<Context> CopyNestedScopeContextChain(Isolate* isolate,
+                                                   Handle<JSFunction> function,
+                                                   Handle<Context> base,
+                                                   JavaScriptFrame* frame,
+                                                   int inlined_frame_index) {
+  HandleScope scope(isolate);
+  List<Handle<SerializedScopeInfo> > scope_chain;
+  List<Handle<Context> > context_chain;
+
+  ScopeIterator it(isolate, frame, inlined_frame_index);
+  for (; it.Type() != ScopeIterator::ScopeTypeGlobal &&
+         it.Type() != ScopeIterator::ScopeTypeLocal ; it.Next()) {
+    ASSERT(!it.Done());
+    scope_chain.Add(it.CurrentScopeInfo());
+    context_chain.Add(it.CurrentContext());
   }
 
-  // Recursively copy the with and catch contexts.
-  HandleScope scope(isolate);
-  Handle<Context> previous(current->previous());
-  Handle<Context> new_previous =
-      CopyWithContextChain(isolate, function, previous, base);
-  Handle<Context> new_current;
-  if (current->IsCatchContext()) {
-    Handle<String> name(String::cast(current->extension()));
-    Handle<Object> thrown_object(current->get(Context::THROWN_OBJECT_INDEX));
-    new_current =
-        isolate->factory()->NewCatchContext(function,
-                                            new_previous,
-                                            name,
-                                            thrown_object);
-  } else if (current->IsBlockContext()) {
-    Handle<SerializedScopeInfo> scope_info(
-        SerializedScopeInfo::cast(current->extension()));
-    new_current =
-        isolate->factory()->NewBlockContext(function, new_previous, scope_info);
-    // Copy context slots.
-    int num_context_slots = scope_info->NumberOfContextSlots();
-    for (int i = Context::MIN_CONTEXT_SLOTS; i < num_context_slots; ++i) {
-      new_current->set(i, current->get(i));
+  // At the end of the chain. Return the base context to link to.
+  Handle<Context> context = base;
+
+  // Iteratively copy and or materialize the nested contexts.
+  while (!scope_chain.is_empty()) {
+    Handle<SerializedScopeInfo> scope_info = scope_chain.RemoveLast();
+    Handle<Context> current = context_chain.RemoveLast();
+    ASSERT(!(scope_info->HasContext() & current.is_null()));
+
+    if (scope_info->Type() == CATCH_SCOPE) {
+      Handle<String> name(String::cast(current->extension()));
+      Handle<Object> thrown_object(current->get(Context::THROWN_OBJECT_INDEX));
+      context =
+          isolate->factory()->NewCatchContext(function,
+                                              context,
+                                              name,
+                                              thrown_object);
+    } else if (scope_info->Type() == BLOCK_SCOPE) {
+      // Materialize the contents of the block scope into a JSObject.
+      Handle<JSObject> block_scope_object =
+          MaterializeBlockScope(isolate, current);
+      if (block_scope_object.is_null()) {
+        return Handle<Context>::null();
+      }
+      // Allocate a new function context for the debug evaluation and set the
+      // extension object.
+      Handle<Context> new_context =
+          isolate->factory()->NewFunctionContext(Context::MIN_CONTEXT_SLOTS,
+                                                 function);
+      new_context->set_extension(*block_scope_object);
+      new_context->set_previous(*context);
+      context = new_context;
+    } else {
+      ASSERT(scope_info->Type() == WITH_SCOPE);
+      ASSERT(current->IsWithContext());
+      Handle<JSObject> extension(JSObject::cast(current->extension()));
+      context =
+          isolate->factory()->NewWithContext(function, context, extension);
     }
-  } else {
-    ASSERT(current->IsWithContext());
-    Handle<JSObject> extension(JSObject::cast(current->extension()));
-    new_current =
-        isolate->factory()->NewWithContext(function, new_previous, extension);
   }
-  return scope.CloseAndEscape(new_current);
+
+  return scope.CloseAndEscape(context);
 }
 
 
@@ -11904,7 +11965,11 @@ RUNTIME_FUNCTION(MaybeObject*, Runtime_DebugEvaluate) {
   if (scope_info->HasHeapAllocatedLocals()) {
     function_context = Handle<Context>(frame_context->declaration_context());
   }
-  context = CopyWithContextChain(isolate, go_between, frame_context, context);
+  context = CopyNestedScopeContextChain(isolate,
+                                        go_between,
+                                        context,
+                                        frame,
+                                        inlined_frame_index);
 
   if (additional_context->IsJSObject()) {
     Handle<JSObject> extension = Handle<JSObject>::cast(additional_context);
index 1aa5160..47b541e 100644 (file)
@@ -51,6 +51,7 @@ ScopeInfo<Allocator>::ScopeInfo(Scope* scope)
     : function_name_(FACTORY->empty_symbol()),
       calls_eval_(scope->calls_eval()),
       is_strict_mode_(scope->is_strict_mode()),
+      type_(scope->type()),
       parameters_(scope->num_parameters()),
       stack_slots_(scope->num_stack_slots()),
       context_slots_(scope->num_heap_slots()),
@@ -150,6 +151,10 @@ ScopeInfo<Allocator>::ScopeInfo(Scope* scope)
 //
 // - calls eval boolean flag
 //
+// - is strict mode scope
+//
+// - scope type
+//
 // - number of variables in the context object (smi) (= function context
 //   slot index + 1)
 // - list of pairs (name, Var mode) of context-allocated variables (starting
@@ -181,8 +186,9 @@ ScopeInfo<Allocator>::ScopeInfo(Scope* scope)
 //   present)
 
 
-static inline Object** ReadInt(Object** p, int* x) {
-  *x = (reinterpret_cast<Smi*>(*p++))->value();
+template <class T>
+static inline Object** ReadInt(Object** p, T* x) {
+  *x = static_cast<T>((reinterpret_cast<Smi*>(*p++))->value());
   return p;
 }
 
@@ -193,20 +199,21 @@ static inline Object** ReadBool(Object** p, bool* x) {
 }
 
 
-static inline Object** ReadSymbol(Object** p, Handle<String>* s) {
-  *s = Handle<String>(reinterpret_cast<String*>(*p++));
+template <class T>
+static inline Object** ReadObject(Object** p, Handle<T>* s) {
+  *s = Handle<T>::cast(Handle<Object>(*p++));
   return p;
 }
 
 
-template <class Allocator>
-static Object** ReadList(Object** p, List<Handle<String>, Allocator >* list) {
+template <class Allocator, class T>
+static Object** ReadList(Object** p, List<Handle<T>, Allocator >* list) {
   ASSERT(list->is_empty());
   int n;
   p = ReadInt(p, &n);
   while (n-- > 0) {
-    Handle<String> s;
-    p = ReadSymbol(p, &s);
+    Handle<T> s;
+    p = ReadObject(p, &s);
     list->Add(s);
   }
   return p;
@@ -223,7 +230,7 @@ static Object** ReadList(Object** p,
   while (n-- > 0) {
     Handle<String> s;
     int m;
-    p = ReadSymbol(p, &s);
+    p = ReadObject(p, &s);
     p = ReadInt(p, &m);
     list->Add(s);
     modes->Add(static_cast<VariableMode>(m));
@@ -242,9 +249,10 @@ ScopeInfo<Allocator>::ScopeInfo(SerializedScopeInfo* data)
   if (data->length() > 0) {
     Object** p0 = data->data_start();
     Object** p = p0;
-    p = ReadSymbol(p, &function_name_);
+    p = ReadObject(p, &function_name_);
     p = ReadBool(p, &calls_eval_);
     p = ReadBool(p, &is_strict_mode_);
+    p = ReadInt(p, &type_);
     p = ReadList<Allocator>(p, &context_slots_, &context_modes_);
     p = ReadList<Allocator>(p, &parameters_);
     p = ReadList<Allocator>(p, &stack_slots_);
@@ -265,18 +273,19 @@ static inline Object** WriteBool(Object** p, bool b) {
 }
 
 
-static inline Object** WriteSymbol(Object** p, Handle<String> s) {
+template <class T>
+static inline Object** WriteObject(Object** p, Handle<T> s) {
   *p++ = *s;
   return p;
 }
 
 
-template <class Allocator>
-static Object** WriteList(Object** p, List<Handle<String>, Allocator >* list) {
+template <class Allocator, class T>
+static Object** WriteList(Object** p, List<Handle<T>, Allocator >* list) {
   const int n = list->length();
   p = WriteInt(p, n);
   for (int i = 0; i < n; i++) {
-    p = WriteSymbol(p, list->at(i));
+    p = WriteObject(p, list->at(i));
   }
   return p;
 }
@@ -289,7 +298,7 @@ static Object** WriteList(Object** p,
   const int n = list->length();
   p = WriteInt(p, n);
   for (int i = 0; i < n; i++) {
-    p = WriteSymbol(p, list->at(i));
+    p = WriteObject(p, list->at(i));
     p = WriteInt(p, modes->at(i));
   }
   return p;
@@ -298,8 +307,9 @@ static Object** WriteList(Object** p,
 
 template<class Allocator>
 Handle<SerializedScopeInfo> ScopeInfo<Allocator>::Serialize() {
-  // function name, calls eval, is_strict_mode, length for 3 tables:
-  const int extra_slots = 1 + 1 + 1 + 3;
+  // function name, calls eval, is_strict_mode, scope type,
+  // length for 3 tables:
+  const int extra_slots = 1 + 1 + 1 + 1 + 3;
   int length = extra_slots +
                context_slots_.length() * 2 +
                parameters_.length() +
@@ -311,9 +321,10 @@ Handle<SerializedScopeInfo> ScopeInfo<Allocator>::Serialize() {
 
   Object** p0 = data->data_start();
   Object** p = p0;
-  p = WriteSymbol(p, function_name_);
+  p = WriteObject(p, function_name_);
   p = WriteBool(p, calls_eval_);
   p = WriteBool(p, is_strict_mode_);
+  p = WriteInt(p, type_);
   p = WriteList(p, &context_slots_, &context_modes_);
   p = WriteList(p, &parameters_);
   p = WriteList(p, &stack_slots_);
@@ -361,8 +372,8 @@ SerializedScopeInfo* SerializedScopeInfo::Empty() {
 
 Object** SerializedScopeInfo::ContextEntriesAddr() {
   ASSERT(length() > 0);
-  // +3 for function name, calls eval, strict mode.
-  return data_start() + 3;
+  // +4 for function name, calls eval, strict mode, scope type.
+  return data_start() + 4;
 }
 
 
@@ -406,6 +417,16 @@ bool SerializedScopeInfo::IsStrictMode() {
 }
 
 
+ScopeType SerializedScopeInfo::Type() {
+  ASSERT(length() > 0);
+  // +3 for function name, calls eval, strict mode.
+  Object** p = data_start() + 3;
+  ScopeType type;
+  p = ReadInt(p, &type);
+  return type;
+}
+
+
 int SerializedScopeInfo::NumberOfStackSlots() {
   if (length() > 0) {
     Object** p = StackSlotEntriesAddr();
@@ -439,6 +460,12 @@ bool SerializedScopeInfo::HasHeapAllocatedLocals() {
 }
 
 
+bool SerializedScopeInfo::HasContext() {
+  return HasHeapAllocatedLocals() ||
+      Type() == WITH_SCOPE;
+}
+
+
 int SerializedScopeInfo::StackSlotIndex(String* name) {
   ASSERT(name->IsSymbol());
   if (length() > 0) {
index 03f321b..eeb3047 100644 (file)
 namespace v8 {
 namespace internal {
 
-// Scope information represents information about a functions's
-// scopes (currently only one, because we don't do any inlining)
-// and the allocation of the scope's variables. Scope information
-// is stored in a compressed form in FixedArray objects and is used
+// ScopeInfo represents information about different scopes of a source
+// program  and the allocation of the scope's variables. Scope information
+// is stored in a compressed form in SerializedScopeInfo objects and is used
 // at runtime (stack dumps, deoptimization, etc.).
-//
-// Historical note: In other VMs built by this team, ScopeInfo was
-// usually called DebugInfo since the information was used (among
-// other things) for on-demand debugging (Self, Smalltalk). However,
-// DebugInfo seems misleading, since this information is primarily used
-// in debugging-unrelated contexts.
 
 // Forward defined as
 // template <class Allocator = FreeStoreAllocationPolicy> class ScopeInfo;
@@ -83,6 +76,7 @@ class ScopeInfo BASE_EMBEDDED {
   Handle<String> LocalName(int i) const;
   int NumberOfLocals() const;
 
+  ScopeType type() const { return type_; }
   // --------------------------------------------------------------------------
   // Debugging support
 
@@ -94,6 +88,7 @@ class ScopeInfo BASE_EMBEDDED {
   Handle<String> function_name_;
   bool calls_eval_;
   bool is_strict_mode_;
+  ScopeType type_;
   List<Handle<String>, Allocator > parameters_;
   List<Handle<String>, Allocator > stack_slots_;
   List<Handle<String>, Allocator > context_slots_;
index 0ceecb2..9672bd6 100644 (file)
@@ -114,7 +114,7 @@ Variable* VariableMap::Lookup(Handle<String> name) {
 
 
 // Dummy constructor
-Scope::Scope(Type type)
+Scope::Scope(ScopeType type)
     : isolate_(Isolate::Current()),
       inner_scopes_(0),
       variables_(false),
@@ -127,7 +127,7 @@ Scope::Scope(Type type)
 }
 
 
-Scope::Scope(Scope* outer_scope, Type type)
+Scope::Scope(Scope* outer_scope, ScopeType type)
     : isolate_(Isolate::Current()),
       inner_scopes_(4),
       variables_(),
@@ -146,7 +146,7 @@ Scope::Scope(Scope* outer_scope, Type type)
 
 
 Scope::Scope(Scope* inner_scope,
-             Type type,
+             ScopeType type,
              Handle<SerializedScopeInfo> scope_info)
     : isolate_(Isolate::Current()),
       inner_scopes_(4),
@@ -185,7 +185,7 @@ Scope::Scope(Scope* inner_scope, Handle<String> catch_variable_name)
 }
 
 
-void Scope::SetDefaults(Type type,
+void Scope::SetDefaults(ScopeType type,
                         Scope* outer_scope,
                         Handle<SerializedScopeInfo> scope_info) {
   outer_scope_ = outer_scope;
@@ -208,6 +208,8 @@ void Scope::SetDefaults(Type type,
   num_stack_slots_ = 0;
   num_heap_slots_ = 0;
   scope_info_ = scope_info;
+  start_position_ = RelocInfo::kNoPosition;
+  end_position_ = RelocInfo::kNoPosition;
 }
 
 
@@ -630,15 +632,33 @@ Handle<SerializedScopeInfo> Scope::GetSerializedScopeInfo() {
 }
 
 
+void Scope::GetNestedScopeChain(
+    List<Handle<SerializedScopeInfo> >* chain,
+    int position) {
+  chain->Add(Handle<SerializedScopeInfo>(GetSerializedScopeInfo()));
+
+  for (int i = 0; i < inner_scopes_.length(); i++) {
+    Scope* scope = inner_scopes_[i];
+    int beg_pos = scope->start_position();
+    int end_pos = scope->end_position();
+    ASSERT(beg_pos >= 0 && end_pos >= 0);
+    if (beg_pos <= position && position <= end_pos) {
+      scope->GetNestedScopeChain(chain, position);
+      return;
+    }
+  }
+}
+
+
 #ifdef DEBUG
-static const char* Header(Scope::Type type) {
+static const char* Header(ScopeType type) {
   switch (type) {
-    case Scope::EVAL_SCOPE: return "eval";
-    case Scope::FUNCTION_SCOPE: return "function";
-    case Scope::GLOBAL_SCOPE: return "global";
-    case Scope::CATCH_SCOPE: return "catch";
-    case Scope::BLOCK_SCOPE: return "block";
-    case Scope::WITH_SCOPE: return "with";
+    case EVAL_SCOPE: return "eval";
+    case FUNCTION_SCOPE: return "function";
+    case GLOBAL_SCOPE: return "global";
+    case CATCH_SCOPE: return "catch";
+    case BLOCK_SCOPE: return "block";
+    case WITH_SCOPE: return "with";
   }
   UNREACHABLE();
   return NULL;
index 72f1e31..58b683b 100644 (file)
@@ -89,16 +89,7 @@ class Scope: public ZoneObject {
   // ---------------------------------------------------------------------------
   // Construction
 
-  enum Type {
-    EVAL_SCOPE,      // The top-level scope for an eval source.
-    FUNCTION_SCOPE,  // The top-level scope for a function.
-    GLOBAL_SCOPE,    // The top-level scope for a program or a top-level eval.
-    CATCH_SCOPE,     // The scope introduced by catch.
-    BLOCK_SCOPE,     // The scope introduced by a new block.
-    WITH_SCOPE       // The scope introduced by with.
-  };
-
-  Scope(Scope* outer_scope, Type type);
+  Scope(Scope* outer_scope, ScopeType type);
 
   // Compute top scope and allocate variables. For lazy compilation the top
   // scope only contains the single lazily compiled function, so this
@@ -206,6 +197,37 @@ class Scope: public ZoneObject {
     strict_mode_ = FLAG_strict_mode;
   }
 
+  // Position in the source where this scope begins and ends.
+  //
+  // * For the scope of a with statement
+  //     with (obj) stmt
+  //   start position: start position of first token of 'stmt'
+  //   end position: end position of last token of 'stmt'
+  // * For the scope of a block
+  //     { stmts }
+  //   start position: start position of '{'
+  //   end position: end position of '}'
+  // * For the scope of a function literal or decalaration
+  //     function fun(a,b) { stmts }
+  //   start position: start position of '('
+  //   end position: end position of '}'
+  // * For the scope of a catch block
+  //     try { stms } catch(e) { stmts }
+  //   start position: start position of '('
+  //   end position: end position of ')'
+  // * For the scope of a for-statement
+  //     for (let x ...) stmt
+  //   start position: start position of '('
+  //   end position: end position of last token of 'stmt'
+  int start_position() const { return start_position_; }
+  void set_start_position(int statement_pos) {
+    start_position_ = statement_pos;
+  }
+  int end_position() const { return end_position_; }
+  void set_end_position(int statement_pos) {
+    end_position_ = statement_pos;
+  }
+
   // ---------------------------------------------------------------------------
   // Predicates.
 
@@ -244,6 +266,9 @@ class Scope: public ZoneObject {
   // ---------------------------------------------------------------------------
   // Accessors.
 
+  // The type of this scope.
+  ScopeType type() const { return type_; }
+
   // The variable corresponding the 'this' value.
   Variable* receiver() { return receiver_; }
 
@@ -270,6 +295,8 @@ class Scope: public ZoneObject {
   // Declarations list.
   ZoneList<Declaration*>* declarations() { return &decls_; }
 
+  // Inner scope list.
+  ZoneList<Scope*>* inner_scopes() { return &inner_scopes_; }
 
   // ---------------------------------------------------------------------------
   // Variable allocation.
@@ -313,6 +340,13 @@ class Scope: public ZoneObject {
 
   Handle<SerializedScopeInfo> GetSerializedScopeInfo();
 
+  // Get the chain of nested scopes within this scope for the source statement
+  // position. The scopes will be added to the list from the outermost scope to
+  // the innermost scope. Only nested block, catch or with scopes are tracked
+  // and will be returned, but no inner function scopes.
+  void GetNestedScopeChain(List<Handle<SerializedScopeInfo> >* chain,
+                           int statement_position);
+
   // ---------------------------------------------------------------------------
   // Strict mode support.
   bool IsDeclared(Handle<String> name) {
@@ -336,7 +370,7 @@ class Scope: public ZoneObject {
  protected:
   friend class ParserFactory;
 
-  explicit Scope(Type type);
+  explicit Scope(ScopeType type);
 
   Isolate* const isolate_;
 
@@ -345,7 +379,7 @@ class Scope: public ZoneObject {
   ZoneList<Scope*> inner_scopes_;  // the immediately enclosed inner scopes
 
   // The scope type.
-  Type type_;
+  ScopeType type_;
 
   // Debugging support.
   Handle<String> scope_name_;
@@ -387,6 +421,9 @@ class Scope: public ZoneObject {
   bool scope_calls_eval_;
   // This scope is a strict mode scope.
   bool strict_mode_;
+  // Source positions.
+  int start_position_;
+  int end_position_;
 
   // Computed via PropagateScopeInfo.
   bool outer_scope_calls_non_strict_eval_;
@@ -489,7 +526,9 @@ class Scope: public ZoneObject {
 
  private:
   // Construct a scope based on the scope info.
-  Scope(Scope* inner_scope, Type type, Handle<SerializedScopeInfo> scope_info);
+  Scope(Scope* inner_scope,
+        ScopeType type,
+        Handle<SerializedScopeInfo> scope_info);
 
   // Construct a catch scope with a binding for the name.
   Scope(Scope* inner_scope, Handle<String> catch_variable_name);
@@ -501,7 +540,7 @@ class Scope: public ZoneObject {
     }
   }
 
-  void SetDefaults(Type type,
+  void SetDefaults(ScopeType type,
                    Scope* outer_scope,
                    Handle<SerializedScopeInfo> scope_info);
 };
index 09d26d2..ebbfd2b 100644 (file)
@@ -509,6 +509,16 @@ enum CallKind {
 };
 
 
+enum ScopeType {
+  EVAL_SCOPE,      // The top-level scope for an eval source.
+  FUNCTION_SCOPE,  // The top-level scope for a function.
+  GLOBAL_SCOPE,    // The top-level scope for a program or a top-level eval.
+  CATCH_SCOPE,     // The scope introduced by catch.
+  BLOCK_SCOPE,     // The scope introduced by a new block.
+  WITH_SCOPE       // The scope introduced by with.
+};
+
+
 static const uint32_t kHoleNanUpper32 = 0x7FFFFFFF;
 static const uint32_t kHoleNanLower32 = 0xFFFFFFFF;
 static const uint32_t kNaNOrInfinityLowerBoundUpper32 = 0x7FF00000;
index 8d51f8c..f2effbb 100755 (executable)
@@ -744,3 +744,133 @@ TEST(RegExpScanning) {
   TestScanRegExp("/=/", "=");
   TestScanRegExp("/=?/", "=?");
 }
+
+
+TEST(ScopePositiosn) {
+  // Test the parser for correctly setting the start and end positions
+  // of a scope. We check the scope positions of exactly one scope
+  // nested in the global scope of a program. 'inner source' is the
+  // source code that determines the part of the source belonging
+  // to the nested scope. 'outer_prefix' and 'outer_suffix' are
+  // parts of the source that belong to the global scope.
+  struct SourceData {
+    const char* outer_prefix;
+    const char* inner_source;
+    const char* outer_suffix;
+    i::ScopeType scope_type;
+  };
+
+  const SourceData source_data[] = {
+    { "  with ({}) ", "{ block; }", " more;", i::WITH_SCOPE },
+    { "  with ({}) ", "{ block; }", "; more;", i::WITH_SCOPE },
+    { "  with ({}) ", "{\n"
+      "    block;\n"
+      "  }", "\n"
+      "  more;", i::WITH_SCOPE },
+    { "  with ({}) ", "statement;", " more;", i::WITH_SCOPE },
+    { "  with ({}) ", "statement", "\n"
+      "  more;", i::WITH_SCOPE },
+    { "  with ({})\n"
+      "    ", "statement;", "\n"
+      "  more;", i::WITH_SCOPE },
+    { "  try {} catch ", "(e) { block; }", " more;", i::CATCH_SCOPE },
+    { "  try {} catch ", "(e) { block; }", "; more;", i::CATCH_SCOPE },
+    { "  try {} catch ", "(e) {\n"
+      "    block;\n"
+      "  }", "\n"
+      "  more;", i::CATCH_SCOPE },
+    { "  try {} catch ", "(e) { block; }", " finally { block; } more;",
+      i::CATCH_SCOPE },
+    { "  start;\n"
+      "  ", "{ let block; }", " more;", i::BLOCK_SCOPE },
+    { "  start;\n"
+      "  ", "{ let block; }", "; more;", i::BLOCK_SCOPE },
+    { "  start;\n"
+      "  ", "{\n"
+      "    let block;\n"
+      "  }", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { "  start;\n"
+      "  function fun", "(a,b) { infunction; }", " more;",
+      i::FUNCTION_SCOPE },
+    { "  start;\n"
+      "  function fun", "(a,b) {\n"
+      "    infunction;\n"
+      "  }", "\n"
+      "  more;", i::FUNCTION_SCOPE },
+    { "  (function fun", "(a,b) { infunction; }", ")();",
+      i::FUNCTION_SCOPE },
+    { "  for ", "(let x = 1 ; x < 10; ++ x) { block; }", " more;",
+      i::BLOCK_SCOPE },
+    { "  for ", "(let x = 1 ; x < 10; ++ x) { block; }", "; more;",
+      i::BLOCK_SCOPE },
+    { "  for ", "(let x = 1 ; x < 10; ++ x) {\n"
+      "    block;\n"
+      "  }", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x = 1 ; x < 10; ++ x) statement;", " more;",
+      i::BLOCK_SCOPE },
+    { "  for ", "(let x = 1 ; x < 10; ++ x) statement", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x = 1 ; x < 10; ++ x)\n"
+      "    statement;", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x in {}) { block; }", " more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x in {}) { block; }", "; more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x in {}) {\n"
+      "    block;\n"
+      "  }", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x in {}) statement;", " more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x in {}) statement", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { "  for ", "(let x in {})\n"
+      "    statement;", "\n"
+      "  more;", i::BLOCK_SCOPE },
+    { NULL, NULL, NULL, i::EVAL_SCOPE }
+  };
+
+  v8::HandleScope handles;
+  v8::Persistent<v8::Context> context = v8::Context::New();
+  v8::Context::Scope context_scope(context);
+
+  int marker;
+  i::Isolate::Current()->stack_guard()->SetStackLimit(
+      reinterpret_cast<uintptr_t>(&marker) - 128 * 1024);
+
+  for (int i = 0; source_data[i].outer_prefix; i++) {
+    size_t kPrefixLen = strlen(source_data[i].outer_prefix);
+    size_t kInnerLen = strlen(source_data[i].inner_source);
+    size_t kSuffixLen = strlen(source_data[i].outer_suffix);
+    size_t kProgramSize = kPrefixLen + kInnerLen + kSuffixLen;
+    i::SmartArrayPointer<char> program(
+        reinterpret_cast<char*>(malloc(kProgramSize + 1)));
+    snprintf(*program, kProgramSize + 1, "%s%s%s",
+             source_data[i].outer_prefix,
+             source_data[i].inner_source,
+             source_data[i].outer_suffix);
+
+    // Parse program source.
+    i::Handle<i::String> source(
+        FACTORY->NewStringFromAscii(i::CStrVector(*program)));
+    i::Handle<i::Script> script = FACTORY->NewScript(source);
+    i::Parser parser(script, false, NULL, NULL);
+    parser.SetHarmonyScoping(true);
+    i::FunctionLiteral* function =
+        parser.ParseProgram(source, true, i::kNonStrictMode);
+
+    // Check scope types and positions.
+    i::Scope* scope = function->scope();
+    CHECK(scope->is_global_scope());
+    CHECK_EQ(scope->start_position(), 0);
+    CHECK_EQ(scope->end_position(), kProgramSize);
+    CHECK_EQ(scope->inner_scopes()->length(), 1);
+
+    i::Scope* inner_scope = scope->inner_scopes()->at(0);
+    CHECK_EQ(inner_scope->type(), source_data[i].scope_type);
+    CHECK_EQ(inner_scope->start_position(), kPrefixLen);
+    // The end position of a token is one position after the last
+    // character belonging to that token.
+    CHECK_EQ(inner_scope->end_position(), kPrefixLen + kInnerLen);
+  }
+}
index 1c23b0b..0788a55 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2008 the V8 project authors. All rights reserved.
+// Copyright 2011 the V8 project authors. All rights reserved.
 // Redistribution and use in source and binary forms, with or without
 // modification, are permitted provided that the following conditions are
 // met:
@@ -25,7 +25,7 @@
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-// Flags: --expose-debug-as debug
+// Flags: --expose-debug-as debug --allow-natives-syntax
 // The functions used for testing backtraces. They are at the top to make the
 // testing of source line/column easier.
 
@@ -439,6 +439,26 @@ with(with_object) {
 EndTest();
 
 
+// With block in function that is marked for optimization while being executed.
+BeginTest("With 7");
+
+function with_7() {
+  with({}) {
+    %OptimizeFunctionOnNextCall(with_7);
+    debugger;
+  }
+}
+
+listener_delegate = function(exec_state) {
+  CheckScopeChain([debug.ScopeType.With,
+                   debug.ScopeType.Local,
+                   debug.ScopeType.Global], exec_state);
+  CheckScopeContent({}, 0, exec_state);
+};
+with_7();
+EndTest();
+
+
 // Simple closure formed by returning an inner function referering the outer
 // functions arguments.
 BeginTest("Closure 1");
@@ -950,6 +970,28 @@ try {
 EndTest();
 
 
+// Catch block in function that is marked for optimization while being executed.
+BeginTest("Catch block 7");
+function catch_block_7() {
+  %OptimizeFunctionOnNextCall(catch_block_7);
+  try {
+    throw 'Exception';
+  } catch (e) {
+    debugger;
+  }
+};
+
+
+listener_delegate = function(exec_state) {
+  CheckScopeChain([debug.ScopeType.Catch,
+                   debug.ScopeType.Local,
+                   debug.ScopeType.Global], exec_state);
+  CheckScopeContent({e:'Exception'}, 0, exec_state);
+};
+catch_block_7();
+EndTest();
+
+
 assertEquals(begin_test_count, break_count,
              'one or more tests did not enter the debugger');
 assertEquals(begin_test_count, end_test_count,