1// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4#if !defined(DART_PRECOMPILED_RUNTIME)
5
6#include "vm/scopes.h"
7
8#include "vm/compiler/backend/slot.h"
9#include "vm/object.h"
10#include "vm/stack_frame.h"
11#include "vm/symbols.h"
12
13
14namespace dart {
15
16DEFINE_FLAG(bool,
17 share_enclosing_context,
18 true,
19 "Allocate captured variables in the existing context of an "
20 "enclosing scope (up to innermost loop) and spare the allocation "
21 "of a local context.");
22
23int SourceLabel::FunctionLevel() const {
24 ASSERT(owner() != NULL);
25 return owner()->function_level();
26}
27
28LocalScope::LocalScope(LocalScope* parent, int function_level, int loop_level)
29 : parent_(parent),
30 child_(NULL),
31 sibling_(NULL),
32 function_level_(function_level),
33 loop_level_(loop_level),
34 context_level_(LocalScope::kUninitializedContextLevel),
35 begin_token_pos_(TokenPosition::kNoSourcePos),
36 end_token_pos_(TokenPosition::kNoSourcePos),
37 variables_(),
38 labels_(),
39 context_variables_(),
40 context_slots_(new (Thread::Current()->zone())
41 ZoneGrowableArray<const Slot*>()),
42 referenced_() {
43 // Hook this node into the children of the parent, unless the parent has a
44 // different function_level, since the local scope of a nested function can
45 // be discarded after it has been parsed.
46 if ((parent != NULL) && (parent->function_level() == function_level)) {
47 sibling_ = parent->child_;
48 parent->child_ = this;
49 }
50}
51
52bool LocalScope::IsNestedWithin(LocalScope* scope) const {
53 const LocalScope* current_scope = this;
54 while (current_scope != NULL) {
55 if (current_scope == scope) {
56 return true;
57 }
58 current_scope = current_scope->parent();
59 }
60 return false;
61}
62
63bool LocalScope::AddVariable(LocalVariable* variable) {
64 ASSERT(variable != NULL);
65 if (LocalLookupVariable(variable->name()) != NULL) {
66 return false;
67 }
68 variables_.Add(variable);
69 if (variable->owner() == NULL) {
70 // Variables must be added to their owner scope first. Subsequent calls
71 // to 'add' treat the variable as an alias.
72 variable->set_owner(this);
73 }
74 return true;
75}
76
77bool LocalScope::InsertParameterAt(intptr_t pos, LocalVariable* parameter) {
78 ASSERT(parameter != NULL);
79 if (LocalLookupVariable(parameter->name()) != NULL) {
80 return false;
81 }
82 variables_.InsertAt(pos, parameter);
83 // InsertParameterAt is not used to add aliases of parameters.
84 ASSERT(parameter->owner() == NULL);
85 parameter->set_owner(this);
86 return true;
87}
88
89bool LocalScope::AddLabel(SourceLabel* label) {
90 if (LocalLookupLabel(label->name()) != NULL) {
91 return false;
92 }
93 labels_.Add(label);
94 if (label->owner() == NULL) {
95 // Labels must be added to their owner scope first. Subsequent calls
96 // to 'add' treat the label as an alias.
97 label->set_owner(this);
98 }
99 return true;
100}
101
102void LocalScope::MoveLabel(SourceLabel* label) {
103 ASSERT(LocalLookupLabel(label->name()) == NULL);
104 ASSERT(label->kind() == SourceLabel::kForward);
105 labels_.Add(label);
106 label->set_owner(this);
107}
108
109NameReference* LocalScope::FindReference(const String& name) const {
110 ASSERT(name.IsSymbol());
111 intptr_t num_references = referenced_.length();
112 for (intptr_t i = 0; i < num_references; i++) {
113 if (name.raw() == referenced_[i]->name().raw()) {
114 return referenced_[i];
115 }
116 }
117 return NULL;
118}
119
120void LocalScope::AddReferencedName(TokenPosition token_pos,
121 const String& name) {
122 if (LocalLookupVariable(name) != NULL) {
123 return;
124 }
125 NameReference* ref = FindReference(name);
126 if (ref != NULL) {
127 ref->set_token_pos(token_pos);
128 return;
129 }
130 ref = new NameReference(token_pos, name);
131 referenced_.Add(ref);
132 // Add name reference in innermost enclosing scopes that do not
133 // define a local variable with this name.
134 LocalScope* scope = this->parent();
135 while (scope != NULL && (scope->LocalLookupVariable(name) == NULL)) {
136 scope->referenced_.Add(ref);
137 scope = scope->parent();
138 }
139}
140
141TokenPosition LocalScope::PreviousReferencePos(const String& name) const {
142 NameReference* ref = FindReference(name);
143 if (ref != NULL) {
144 return ref->token_pos();
145 }
146 return TokenPosition::kNoSource;
147}
148
149void LocalScope::AllocateContextVariable(LocalVariable* variable,
150 LocalScope** context_owner) {
151 ASSERT(variable->is_captured());
152 ASSERT(variable->owner() == this);
153 // The context level in the owner scope of a captured variable indicates at
154 // code generation time how far to walk up the context chain in order to
155 // access the variable from the current context level.
156 if ((*context_owner) == NULL) {
157 ASSERT(num_context_variables() == 0);
158 // This scope becomes the current context owner.
159 set_context_level(1);
160 *context_owner = this;
161 } else if (!FLAG_share_enclosing_context && ((*context_owner) != this)) {
162 // The captured variable is in a child scope of the context owner and we do
163 // not share contexts.
164 // This scope will allocate and chain a new context.
165 ASSERT(num_context_variables() == 0);
166 // This scope becomes the current context owner.
167 set_context_level((*context_owner)->context_level() + 1);
168 *context_owner = this;
169 } else if ((*context_owner)->loop_level() < loop_level()) {
170 ASSERT(FLAG_share_enclosing_context);
171 // The captured variable is at a deeper loop level than the current context.
172 // This scope will allocate and chain a new context.
173 ASSERT(num_context_variables() == 0);
174 // This scope becomes the current context owner.
175 set_context_level((*context_owner)->context_level() + 1);
176 *context_owner = this;
177 } else {
178 // Allocate the captured variable in the current context.
179 if (!HasContextLevel()) {
180 ASSERT(variable->owner() != *context_owner);
181 set_context_level((*context_owner)->context_level());
182 } else {
183 ASSERT(context_level() == (*context_owner)->context_level());
184 }
185 }
186
187 (*context_owner)->AddContextVariable(variable);
188}
189
190void LocalScope::AddContextVariable(LocalVariable* variable) {
191 variable->set_index(VariableIndex(context_variables_.length()));
192 context_variables_.Add(variable);
193 context_slots_->Add(
194 &Slot::GetContextVariableSlotFor(Thread::Current(), *variable));
195}
196
197VariableIndex LocalScope::AllocateVariables(VariableIndex first_parameter_index,
198 int num_parameters,
199 VariableIndex first_local_index,
200 LocalScope* context_owner,
201 bool* found_captured_variables) {
202 // We should not allocate variables of nested functions while compiling an
203 // enclosing function.
204 ASSERT(function_level() == 0);
205 ASSERT(num_parameters >= 0);
206 // Parameters must be listed first and must all appear in the top scope.
207 ASSERT(num_parameters <= num_variables());
208 int pos = 0; // Current variable position.
209 VariableIndex next_index =
210 first_parameter_index; // Current free frame index.
211
212 LocalVariable* await_jump_var = nullptr;
213 LocalVariable* async_completer = nullptr;
214 LocalVariable* controller = nullptr;
215 LocalVariable* chained_future = nullptr;
216 for (intptr_t i = 0; i < num_variables(); i++) {
217 LocalVariable* variable = VariableAt(i);
218 if (variable->owner() == this) {
219 if (variable->is_captured()) {
220 if (variable->name().Equals(Symbols::AwaitJumpVar())) {
221 await_jump_var = variable;
222 } else if (variable->name().Equals(Symbols::AsyncCompleter())) {
223 async_completer = variable;
224 } else if (variable->name().Equals(Symbols::Controller())) {
225 controller = variable;
226 } else if (variable->is_chained_future()) {
227 chained_future = variable;
228 }
229 }
230 }
231 }
232 // If we are in an async/async* function, force :await_jump_var and
233 // :async_completer_var to be at fixed locations in the slot.
234 if (await_jump_var != nullptr) {
235 AllocateContextVariable(await_jump_var, &context_owner);
236 *found_captured_variables = true;
237 ASSERT(await_jump_var->index().value() == Context::kAwaitJumpVarIndex);
238 }
239 if (async_completer != nullptr) {
240 AllocateContextVariable(async_completer, &context_owner);
241 *found_captured_variables = true;
242 ASSERT(async_completer->index().value() == Context::kAsyncCompleterIndex);
243 }
244 if (controller != nullptr) {
245 AllocateContextVariable(controller, &context_owner);
246 *found_captured_variables = true;
247 ASSERT(controller->index().value() == Context::kControllerIndex);
248 }
249 if (chained_future != nullptr) {
250 AllocateContextVariable(chained_future, &context_owner);
251 *found_captured_variables = true;
252 ASSERT(chained_future->index().value() ==
253 chained_future->expected_context_index());
254 }
255
256 while (pos < num_parameters) {
257 LocalVariable* parameter = VariableAt(pos);
258 pos++;
259 // Parsing formal parameter default values may add local variable aliases
260 // to the local scope before the formal parameters are added. However,
261 // the parameters get inserted in front of the aliases, therefore, no
262 // aliases can be encountered among the first num_parameters variables.
263 ASSERT(parameter->owner() == this);
264 if (parameter->is_captured()) {
265 // A captured parameter has a slot allocated in the frame and one in the
266 // context, where it gets copied to. The parameter index reflects the
267 // context allocation index.
268 next_index = VariableIndex(next_index.value() - 1);
269 AllocateContextVariable(parameter, &context_owner);
270 *found_captured_variables = true;
271 } else {
272 parameter->set_index(next_index);
273 next_index = VariableIndex(next_index.value() - 1);
274 }
275 }
276 // No overlapping of parameters and locals.
277 ASSERT(next_index.value() >= first_local_index.value());
278 next_index = first_local_index;
279 while (pos < num_variables()) {
280 LocalVariable* variable = VariableAt(pos);
281 if (variable->owner() == this) {
282 if (variable->is_captured()) {
283 // Skip the variables already pre-allocated above.
284 if (variable != await_jump_var && variable != async_completer &&
285 variable != controller && variable != chained_future) {
286 AllocateContextVariable(variable, &context_owner);
287 *found_captured_variables = true;
288 }
289 } else {
290 variable->set_index(next_index);
291 next_index = VariableIndex(next_index.value() - 1);
292 }
293 }
294 pos++;
295 }
296 // Allocate variables of all children.
297 VariableIndex min_index = next_index;
298 LocalScope* child = this->child();
299 while (child != NULL) {
300 // Ignored, since no parameters.
301 const VariableIndex dummy_parameter_index(0);
302
303 // No parameters in children scopes.
304 const int num_parameters_in_child = 0;
305 VariableIndex child_next_index = child->AllocateVariables(
306 dummy_parameter_index, num_parameters_in_child, next_index,
307 context_owner, found_captured_variables);
308 if (child_next_index.value() < min_index.value()) {
309 min_index = child_next_index;
310 }
311 child = child->sibling();
312 }
313 return min_index;
314}
315
316// The parser creates internal variables that start with ":"
317static bool IsFilteredIdentifier(const String& str) {
318 ASSERT(str.Length() > 0);
319 if (str.raw() == Symbols::AsyncOperation().raw()) {
320 // Keep :async_op for asynchronous debugging.
321 return false;
322 }
323 if (str.raw() == Symbols::AsyncCompleter().raw()) {
324 // Keep :async_completer for asynchronous debugging.
325 return false;
326 }
327 if (str.raw() == Symbols::ControllerStream().raw()) {
328 // Keep :controller_stream for asynchronous debugging.
329 return false;
330 }
331 if (str.raw() == Symbols::AwaitJumpVar().raw()) {
332 // Keep :await_jump_var for asynchronous debugging.
333 return false;
334 }
335 if (str.raw() == Symbols::AsyncStackTraceVar().raw()) {
336 // Keep :async_stack_trace for asynchronous debugging.
337 return false;
338 }
339 if (str.raw() == Symbols::FunctionTypeArgumentsVar().raw()) {
340 // Keep :function_type_arguments for accessing type variables in debugging.
341 return false;
342 }
343 return str.CharAt(0) == ':';
344}
345
346LocalVarDescriptorsPtr LocalScope::GetVarDescriptors(
347 const Function& func,
348 ZoneGrowableArray<intptr_t>* context_level_array) {
349 LocalVarDescriptorsBuilder vars;
350 vars.AddDeoptIdToContextLevelMappings(context_level_array);
351
352 // First enter all variables from scopes of outer functions.
353 const ContextScope& context_scope =
354 ContextScope::Handle(func.context_scope());
355 if (!context_scope.IsNull()) {
356 ASSERT(func.IsLocalFunction());
357 for (int i = 0; i < context_scope.num_variables(); i++) {
358 String& name = String::Handle(context_scope.NameAt(i));
359 LocalVarDescriptorsLayout::VarInfoKind kind;
360 if (!IsFilteredIdentifier(name)) {
361 kind = LocalVarDescriptorsLayout::kContextVar;
362 } else {
363 continue;
364 }
365
366 LocalVarDescriptorsBuilder::VarDesc desc;
367 desc.name = &name;
368 desc.info.set_kind(kind);
369 desc.info.scope_id = context_scope.ContextLevelAt(i);
370 desc.info.declaration_pos = context_scope.DeclarationTokenIndexAt(i);
371 desc.info.begin_pos = begin_token_pos();
372 desc.info.end_pos = end_token_pos();
373 ASSERT(desc.info.begin_pos <= desc.info.end_pos);
374 desc.info.set_index(context_scope.ContextIndexAt(i));
375 vars.Add(desc);
376 }
377 }
378 // Now collect all variables from local scopes.
379 int16_t scope_id = 0;
380 CollectLocalVariables(&vars, &scope_id);
381
382 return vars.Done();
383}
384
385// Add visible variables that are declared in this scope to vars, then
386// collect visible variables of children, followed by siblings.
387void LocalScope::CollectLocalVariables(LocalVarDescriptorsBuilder* vars,
388 int16_t* scope_id) {
389 (*scope_id)++;
390 for (int i = 0; i < this->variables_.length(); i++) {
391 LocalVariable* var = variables_[i];
392 if ((var->owner() == this) && !var->is_invisible()) {
393 if (var->name().raw() == Symbols::CurrentContextVar().raw()) {
394 // This is the local variable in which the function saves its
395 // own context before calling a closure function.
396 LocalVarDescriptorsBuilder::VarDesc desc;
397 desc.name = &var->name();
398 desc.info.set_kind(LocalVarDescriptorsLayout::kSavedCurrentContext);
399 desc.info.scope_id = 0;
400 desc.info.declaration_pos = TokenPosition::kMinSource;
401 desc.info.begin_pos = TokenPosition::kMinSource;
402 desc.info.end_pos = TokenPosition::kMinSource;
403 desc.info.set_index(var->index().value());
404 vars->Add(desc);
405 } else if (!IsFilteredIdentifier(var->name())) {
406 // This is a regular Dart variable, either stack-based or captured.
407 LocalVarDescriptorsBuilder::VarDesc desc;
408 desc.name = &var->name();
409 if (var->is_captured()) {
410 desc.info.set_kind(LocalVarDescriptorsLayout::kContextVar);
411 ASSERT(var->owner() != NULL);
412 ASSERT(var->owner()->context_level() >= 0);
413 desc.info.scope_id = var->owner()->context_level();
414 } else {
415 desc.info.set_kind(LocalVarDescriptorsLayout::kStackVar);
416 desc.info.scope_id = *scope_id;
417 }
418 desc.info.set_index(var->index().value());
419 desc.info.declaration_pos = var->declaration_token_pos();
420 desc.info.begin_pos = var->token_pos();
421 desc.info.end_pos = var->owner()->end_token_pos();
422 vars->Add(desc);
423 }
424 }
425 }
426 LocalScope* child = this->child();
427 while (child != NULL) {
428 child->CollectLocalVariables(vars, scope_id);
429 child = child->sibling();
430 }
431}
432
433SourceLabel* LocalScope::LocalLookupLabel(const String& name) const {
434 ASSERT(name.IsSymbol());
435 for (intptr_t i = 0; i < labels_.length(); i++) {
436 SourceLabel* label = labels_[i];
437 if (label->name().raw() == name.raw()) {
438 return label;
439 }
440 }
441 return NULL;
442}
443
444LocalVariable* LocalScope::LocalLookupVariable(const String& name) const {
445 ASSERT(name.IsSymbol());
446 for (intptr_t i = 0; i < variables_.length(); i++) {
447 LocalVariable* var = variables_[i];
448 ASSERT(var->name().IsSymbol());
449 if (var->name().raw() == name.raw()) {
450 return var;
451 }
452 }
453 return NULL;
454}
455
456LocalVariable* LocalScope::LookupVariable(const String& name, bool test_only) {
457 LocalScope* current_scope = this;
458 while (current_scope != NULL) {
459 LocalVariable* var = current_scope->LocalLookupVariable(name);
460 // If testing only, return the variable even if invisible.
461 if ((var != NULL) && (!var->is_invisible_ || test_only)) {
462 if (!test_only && (var->owner()->function_level() != function_level())) {
463 CaptureVariable(var);
464 }
465 return var;
466 }
467 current_scope = current_scope->parent();
468 }
469 return NULL;
470}
471
472void LocalScope::CaptureVariable(LocalVariable* variable) {
473 ASSERT(variable != NULL);
474
475 // The variable must exist in an enclosing scope, not necessarily in this one.
476 variable->set_is_captured();
477 const int variable_function_level = variable->owner()->function_level();
478 LocalScope* scope = this;
479 while (scope->function_level() != variable_function_level) {
480 // Insert an alias of the variable in the top scope of each function
481 // level so that the variable is found in the context.
482 LocalScope* parent_scope = scope->parent();
483 while ((parent_scope != NULL) &&
484 (parent_scope->function_level() == scope->function_level())) {
485 scope = parent_scope;
486 parent_scope = scope->parent();
487 }
488 // An alias may already have been added in this scope, and in that case,
489 // in parent scopes as needed. If so, we are done.
490 if (!scope->AddVariable(variable)) {
491 return;
492 }
493 ASSERT(variable->owner() != scope); // Item is an alias.
494 scope = parent_scope;
495 }
496}
497
498SourceLabel* LocalScope::LookupLabel(const String& name) {
499 LocalScope* current_scope = this;
500 while (current_scope != NULL) {
501 SourceLabel* label = current_scope->LocalLookupLabel(name);
502 if (label != NULL) {
503 return label;
504 }
505 current_scope = current_scope->parent();
506 }
507 return NULL;
508}
509
510SourceLabel* LocalScope::LookupInnermostLabel(Token::Kind jump_kind) {
511 ASSERT((jump_kind == Token::kCONTINUE) || (jump_kind == Token::kBREAK));
512 LocalScope* current_scope = this;
513 while (current_scope != NULL) {
514 for (intptr_t i = 0; i < current_scope->labels_.length(); i++) {
515 SourceLabel* label = current_scope->labels_[i];
516 if ((label->kind() == SourceLabel::kWhile) ||
517 (label->kind() == SourceLabel::kFor) ||
518 (label->kind() == SourceLabel::kDoWhile) ||
519 ((jump_kind == Token::kBREAK) &&
520 (label->kind() == SourceLabel::kSwitch))) {
521 return label;
522 }
523 }
524 current_scope = current_scope->parent();
525 }
526 return NULL;
527}
528
529LocalScope* LocalScope::LookupSwitchScope() {
530 LocalScope* current_scope = this->parent();
531 int this_level = this->function_level();
532 while (current_scope != NULL &&
533 current_scope->function_level() == this_level) {
534 for (int i = 0; i < current_scope->labels_.length(); i++) {
535 SourceLabel* label = current_scope->labels_[i];
536 if (label->kind() == SourceLabel::kSwitch) {
537 // This scope contains a label that is bound to a switch statement,
538 // so it is the scope of the a statement body.
539 return current_scope;
540 }
541 }
542 current_scope = current_scope->parent();
543 }
544 // We did not find a switch statement scope at the same function level.
545 return NULL;
546}
547
548SourceLabel* LocalScope::CheckUnresolvedLabels() {
549 for (int i = 0; i < this->labels_.length(); i++) {
550 SourceLabel* label = this->labels_[i];
551 if (label->kind() == SourceLabel::kForward) {
552 LocalScope* outer_switch = LookupSwitchScope();
553 if (outer_switch == NULL) {
554 return label;
555 } else {
556 outer_switch->MoveLabel(label);
557 }
558 }
559 }
560 return NULL;
561}
562
563int LocalScope::NumCapturedVariables() const {
564 // It is not necessary to traverse parent scopes, since we are only interested
565 // in the captured variables referenced in this scope. If this scope is the
566 // top scope at function level 1 and it (or its children scopes) references a
567 // captured variable declared in a parent scope at function level 0, it will
568 // contain an alias for that variable.
569
570 // Since code generation for nested functions is postponed until first
571 // invocation, the function level of the closure scope can only be 1.
572 ASSERT(function_level() == 1);
573
574 int num_captured = 0;
575 for (int i = 0; i < num_variables(); i++) {
576 LocalVariable* variable = VariableAt(i);
577 // Count the aliases of captured variables belonging to outer scopes.
578 if (variable->owner()->function_level() != 1) {
579 ASSERT(variable->is_captured());
580 ASSERT(variable->owner()->function_level() == 0);
581 num_captured++;
582 }
583 }
584 return num_captured;
585}
586
587ContextScopePtr LocalScope::PreserveOuterScope(
588 int current_context_level) const {
589 // Since code generation for nested functions is postponed until first
590 // invocation, the function level of the closure scope can only be 1.
591 ASSERT(function_level() == 1);
592
593 // Count the number of referenced captured variables.
594 intptr_t num_captured_vars = NumCapturedVariables();
595
596 // Create a ContextScope with space for num_captured_vars descriptors.
597 const ContextScope& context_scope =
598 ContextScope::Handle(ContextScope::New(num_captured_vars, false));
599
600 // Create a descriptor for each referenced captured variable of enclosing
601 // functions to preserve its name and its context allocation information.
602 int captured_idx = 0;
603 for (int i = 0; i < num_variables(); i++) {
604 LocalVariable* variable = VariableAt(i);
605 // Preserve the aliases of captured variables belonging to outer scopes.
606 if (variable->owner()->function_level() != 1) {
607 context_scope.SetTokenIndexAt(captured_idx, variable->token_pos());
608 context_scope.SetDeclarationTokenIndexAt(
609 captured_idx, variable->declaration_token_pos());
610 context_scope.SetNameAt(captured_idx, variable->name());
611 context_scope.ClearFlagsAt(captured_idx);
612 context_scope.SetIsFinalAt(captured_idx, variable->is_final());
613 context_scope.SetIsLateAt(captured_idx, variable->is_late());
614 if (variable->is_late()) {
615 context_scope.SetLateInitOffsetAt(captured_idx,
616 variable->late_init_offset());
617 }
618 context_scope.SetIsConstAt(captured_idx, variable->IsConst());
619 if (variable->IsConst()) {
620 context_scope.SetConstValueAt(captured_idx, *variable->ConstValue());
621 } else {
622 context_scope.SetTypeAt(captured_idx, variable->type());
623 }
624 context_scope.SetContextIndexAt(captured_idx, variable->index().value());
625 // Adjust the context level relative to the current context level,
626 // since the context of the current scope will be at level 0 when
627 // compiling the nested function.
628 int adjusted_context_level =
629 variable->owner()->context_level() - current_context_level;
630 context_scope.SetContextLevelAt(captured_idx, adjusted_context_level);
631 captured_idx++;
632 }
633 }
634 ASSERT(context_scope.num_variables() == captured_idx); // Verify count.
635 return context_scope.raw();
636}
637
638LocalScope* LocalScope::RestoreOuterScope(const ContextScope& context_scope) {
639 // The function level of the outer scope is one less than the function level
640 // of the current function, which is 0.
641 LocalScope* outer_scope = new LocalScope(NULL, -1, 0);
642 // Add all variables as aliases to the outer scope.
643 for (int i = 0; i < context_scope.num_variables(); i++) {
644 LocalVariable* variable;
645 if (context_scope.IsConstAt(i)) {
646 variable = new LocalVariable(context_scope.DeclarationTokenIndexAt(i),
647 context_scope.TokenIndexAt(i),
648 String::ZoneHandle(context_scope.NameAt(i)),
649 Object::dynamic_type());
650 variable->SetConstValue(
651 Instance::ZoneHandle(context_scope.ConstValueAt(i)));
652 } else {
653 variable =
654 new LocalVariable(context_scope.DeclarationTokenIndexAt(i),
655 context_scope.TokenIndexAt(i),
656 String::ZoneHandle(context_scope.NameAt(i)),
657 AbstractType::ZoneHandle(context_scope.TypeAt(i)));
658 }
659 variable->set_is_captured();
660 variable->set_index(VariableIndex(context_scope.ContextIndexAt(i)));
661 if (context_scope.IsFinalAt(i)) {
662 variable->set_is_final();
663 }
664 if (context_scope.IsLateAt(i)) {
665 variable->set_is_late();
666 variable->set_late_init_offset(context_scope.LateInitOffsetAt(i));
667 }
668 // Create a fake owner scope describing the index and context level of the
669 // variable. Function level and loop level are unused (set to 0), since
670 // context level has already been assigned.
671 LocalScope* owner_scope = new LocalScope(NULL, 0, 0);
672 owner_scope->set_context_level(context_scope.ContextLevelAt(i));
673 owner_scope->AddVariable(variable);
674 outer_scope->AddVariable(variable); // As alias.
675 ASSERT(variable->owner() == owner_scope);
676 }
677 return outer_scope;
678}
679
680void LocalScope::CaptureLocalVariables(LocalScope* top_scope) {
681 ASSERT(top_scope->function_level() == function_level());
682 LocalScope* scope = this;
683 while (scope != top_scope->parent()) {
684 for (intptr_t i = 0; i < scope->num_variables(); i++) {
685 LocalVariable* variable = scope->VariableAt(i);
686 if (variable->is_forced_stack() ||
687 (variable->name().raw() == Symbols::StackTraceVar().raw()) ||
688 (variable->name().raw() == Symbols::ExceptionVar().raw()) ||
689 (variable->name().raw() == Symbols::SavedTryContextVar().raw()) ||
690 (variable->name().raw() == Symbols::ArgDescVar().raw()) ||
691 (variable->name().raw() ==
692 Symbols::FunctionTypeArgumentsVar().raw())) {
693 // Don't capture those variables because the VM expects them to be on
694 // the stack.
695 continue;
696 }
697 scope->CaptureVariable(variable);
698 }
699 scope = scope->parent();
700 }
701}
702
703ContextScopePtr LocalScope::CreateImplicitClosureScope(const Function& func) {
704 static const intptr_t kNumCapturedVars = 1;
705
706 // Create a ContextScope with space for kNumCapturedVars descriptors.
707 const ContextScope& context_scope =
708 ContextScope::Handle(ContextScope::New(kNumCapturedVars, true));
709
710 // Create a descriptor for 'this' variable.
711 context_scope.SetTokenIndexAt(0, func.token_pos());
712 context_scope.SetDeclarationTokenIndexAt(0, func.token_pos());
713 context_scope.SetNameAt(0, Symbols::This());
714 context_scope.ClearFlagsAt(0);
715 context_scope.SetIsFinalAt(0, true);
716 context_scope.SetIsConstAt(0, false);
717 const AbstractType& type = AbstractType::Handle(func.ParameterTypeAt(0));
718 context_scope.SetTypeAt(0, type);
719 context_scope.SetContextIndexAt(0, 0);
720 context_scope.SetContextLevelAt(0, 0);
721 ASSERT(context_scope.num_variables() == kNumCapturedVars); // Verify count.
722 return context_scope.raw();
723}
724
725bool LocalVariable::Equals(const LocalVariable& other) const {
726 if (HasIndex() && other.HasIndex() && (index() == other.index())) {
727 if (is_captured() == other.is_captured()) {
728 if (!is_captured()) {
729 return true;
730 }
731 if (owner()->context_level() == other.owner()->context_level()) {
732 return true;
733 }
734 }
735 }
736 return false;
737}
738
739void LocalVarDescriptorsBuilder::AddAll(Zone* zone,
740 const LocalVarDescriptors& var_descs) {
741 for (intptr_t i = 0, n = var_descs.Length(); i < n; ++i) {
742 VarDesc desc;
743 desc.name = &String::Handle(zone, var_descs.GetName(i));
744 var_descs.GetInfo(i, &desc.info);
745 Add(desc);
746 }
747}
748
749void LocalVarDescriptorsBuilder::AddDeoptIdToContextLevelMappings(
750 ZoneGrowableArray<intptr_t>* context_level_array) {
751 // Record deopt-id -> context-level mappings, using ranges of deopt-ids with
752 // the same context-level. [context_level_array] contains (deopt_id,
753 // context_level) tuples.
754 for (intptr_t start = 0; start < context_level_array->length();) {
755 intptr_t start_deopt_id = (*context_level_array)[start];
756 intptr_t start_context_level = (*context_level_array)[start + 1];
757 intptr_t end = start;
758 intptr_t end_deopt_id = start_deopt_id;
759 for (intptr_t peek = start + 2; peek < context_level_array->length();
760 peek += 2) {
761 intptr_t peek_deopt_id = (*context_level_array)[peek];
762 intptr_t peek_context_level = (*context_level_array)[peek + 1];
763 // The range encoding assumes the tuples have ascending deopt_ids.
764 ASSERT(peek_deopt_id > end_deopt_id);
765 if (peek_context_level != start_context_level) break;
766 end = peek;
767 end_deopt_id = peek_deopt_id;
768 }
769
770 VarDesc desc;
771 desc.name = &Symbols::Empty(); // No name.
772 desc.info.set_kind(LocalVarDescriptorsLayout::kContextLevel);
773 desc.info.scope_id = 0;
774 desc.info.begin_pos = TokenPosition(start_deopt_id);
775 desc.info.end_pos = TokenPosition(end_deopt_id);
776 desc.info.set_index(start_context_level);
777 Add(desc);
778
779 start = end + 2;
780 }
781}
782
783LocalVarDescriptorsPtr LocalVarDescriptorsBuilder::Done() {
784 if (vars_.is_empty()) {
785 return Object::empty_var_descriptors().raw();
786 }
787 const LocalVarDescriptors& var_desc =
788 LocalVarDescriptors::Handle(LocalVarDescriptors::New(vars_.length()));
789 for (int i = 0; i < vars_.length(); i++) {
790 var_desc.SetVar(i, *(vars_[i].name), &vars_[i].info);
791 }
792 return var_desc.raw();
793}
794
795} // namespace dart
796
797#endif // !defined(DART_PRECOMPILED_RUNTIME)
798