1 /*******************************************************************************
2 * Copyright (c) 2000, 2003 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.compiler.lookup;
13 import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding;
15 import net.sourceforge.phpdt.core.compiler.CharOperation;
16 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
17 import net.sourceforge.phpeclipse.internal.compiler.ast.AbstractMethodDeclaration;
18 import net.sourceforge.phpeclipse.internal.compiler.ast.ConstructorDeclaration;
19 import net.sourceforge.phpeclipse.internal.compiler.ast.TypeDeclaration;
21 public class BlockScope extends Scope {
23 // Local variable management
24 public LocalVariableBinding[] locals;
25 public int localIndex; // position for next variable
26 public int startIndex; // start position in this scope - for ordering scopes vs. variables
27 public int offset; // for variable allocation throughout scopes
28 public int maxOffset; // for variable allocation throughout scopes
30 // finally scopes must be shifted behind respective try&catch scope(s) so as to avoid
31 // collisions of secret variables (return address, save value).
32 public BlockScope[] shiftScopes;
34 public final static VariableBinding[] EmulationPathToImplicitThis = {};
35 public final static VariableBinding[] NoEnclosingInstanceInConstructorCall = {};
36 public final static VariableBinding[] NoEnclosingInstanceInStaticContext = {};
38 public Scope[] subscopes = new Scope[1]; // need access from code assist
39 public int scopeIndex = 0; // need access from code assist
41 protected BlockScope(int kind, Scope parent) {
46 public BlockScope(BlockScope parent) {
51 public BlockScope(BlockScope parent, boolean addToParentScope) {
53 this(BLOCK_SCOPE, parent);
54 locals = new LocalVariableBinding[5];
55 if (addToParentScope) parent.addSubscope(this);
56 this.startIndex = parent.localIndex;
59 public BlockScope(BlockScope parent, int variableCount) {
61 this(BLOCK_SCOPE, parent);
62 locals = new LocalVariableBinding[variableCount];
63 parent.addSubscope(this);
64 this.startIndex = parent.localIndex;
67 /* Create the class scope & binding for the anonymous type.
69 public final void addAnonymousType(
70 TypeDeclaration anonymousType,
71 ReferenceBinding superBinding) {
73 ClassScope anonymousClassScope = new ClassScope(this, anonymousType);
74 anonymousClassScope.buildAnonymousTypeBinding(
75 enclosingSourceType(),
79 /* Create the class scope & binding for the local type.
81 public final void addLocalType(TypeDeclaration localType) {
83 // check that the localType does not conflict with an enclosing type
84 ReferenceBinding type = enclosingSourceType();
86 if (CharOperation.equals(type.sourceName, localType.name)) {
87 problemReporter().hidingEnclosingType(localType);
90 type = type.enclosingType();
91 } while (type != null);
93 // check that the localType does not conflict with another sibling local type
96 if (((BlockScope) scope).findLocalType(localType.name) != null) {
97 problemReporter().duplicateNestedType(localType);
100 } while ((scope = scope.parent) instanceof BlockScope);
102 ClassScope localTypeScope = new ClassScope(this, localType);
103 addSubscope(localTypeScope);
104 localTypeScope.buildLocalTypeBinding(enclosingSourceType());
107 /* Insert a local variable into a given scope, updating its position
108 * and checking there are not too many locals or arguments allocated.
110 public final void addLocalVariable(LocalVariableBinding binding) {
112 checkAndSetModifiersForVariable(binding);
114 // insert local in scope
115 if (localIndex == locals.length)
119 (locals = new LocalVariableBinding[localIndex * 2]),
122 locals[localIndex++] = binding;
124 // update local variable binding
125 binding.declaringScope = this;
126 binding.id = this.outerMostMethodScope().analysisIndex++;
127 // share the outermost method scope analysisIndex
130 public void addSubscope(Scope childScope) {
131 if (scopeIndex == subscopes.length)
135 (subscopes = new Scope[scopeIndex * 2]),
138 subscopes[scopeIndex++] = childScope;
141 /* Answer true if the receiver is suitable for assigning final blank fields.
143 * in other words, it is inside an initializer, a constructor or a clinit
145 public final boolean allowBlankFinalFieldAssignment(FieldBinding binding) {
147 if (enclosingSourceType() != binding.declaringClass)
150 MethodScope methodScope = methodScope();
151 if (methodScope.isStatic != binding.isStatic())
153 return methodScope.isInsideInitializer() // inside initializer
154 || ((AbstractMethodDeclaration) methodScope.referenceContext)
155 .isInitializationMethod(); // inside constructor or clinit
157 String basicToString(int tab) {
158 String newLine = "\n"; //$NON-NLS-1$
159 for (int i = tab; --i >= 0;)
160 newLine += "\t"; //$NON-NLS-1$
162 String s = newLine + "--- Block Scope ---"; //$NON-NLS-1$
163 newLine += "\t"; //$NON-NLS-1$
164 s += newLine + "locals:"; //$NON-NLS-1$
165 for (int i = 0; i < localIndex; i++)
166 s += newLine + "\t" + locals[i].toString(); //$NON-NLS-1$
167 s += newLine + "startIndex = " + startIndex; //$NON-NLS-1$
171 private void checkAndSetModifiersForVariable(LocalVariableBinding varBinding) {
173 int modifiers = varBinding.modifiers;
174 if ((modifiers & AccAlternateModifierProblem) != 0 && varBinding.declaration != null){
175 problemReporter().duplicateModifierForVariable(varBinding.declaration, this instanceof MethodScope);
177 int realModifiers = modifiers & AccJustFlag;
179 int unexpectedModifiers = ~AccFinal;
180 if ((realModifiers & unexpectedModifiers) != 0 && varBinding.declaration != null){
181 problemReporter().illegalModifierForVariable(varBinding.declaration, this instanceof MethodScope);
183 varBinding.modifiers = modifiers;
186 /* Compute variable positions in scopes given an initial position offset
187 * ignoring unused local variables.
189 * No argument is expected here (ilocal is the first non-argument local of the outermost scope)
190 * Arguments are managed by the MethodScope method
192 // void computeLocalVariablePositions(int ilocal, int initOffset, CodeStream codeStream) {
194 // this.offset = initOffset;
195 // this.maxOffset = initOffset;
197 // // local variable init
198 // int maxLocals = this.localIndex;
199 // boolean hasMoreVariables = ilocal < maxLocals;
202 // int iscope = 0, maxScopes = this.scopeIndex;
203 // boolean hasMoreScopes = maxScopes > 0;
205 // // iterate scopes and variables in parallel
206 // while (hasMoreVariables || hasMoreScopes) {
208 // && (!hasMoreVariables || (subscopes[iscope].startIndex() <= ilocal))) {
209 // // consider subscope first
210 // if (subscopes[iscope] instanceof BlockScope) {
211 // BlockScope subscope = (BlockScope) subscopes[iscope];
212 // int subOffset = subscope.shiftScopes == null ? this.offset : subscope.maxShiftedOffset();
213 // subscope.computeLocalVariablePositions(0, subOffset, codeStream);
214 // if (subscope.maxOffset > this.maxOffset)
215 // this.maxOffset = subscope.maxOffset;
217 // hasMoreScopes = ++iscope < maxScopes;
220 // // consider variable first
221 // LocalVariableBinding local = locals[ilocal]; // if no local at all, will be locals[ilocal]==null
223 // // check if variable is actually used, and may force it to be preserved
224 // boolean generateCurrentLocalVar = (local.useFlag == LocalVariableBinding.USED && (local.constant == Constant.NotAConstant));
226 // // do not report fake used variable
227 // if (local.useFlag == LocalVariableBinding.UNUSED
228 // && (local.declaration != null) // unused (and non secret) local
229 // && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachableMASK) != 0)) { // declaration is reachable
231 // if (!(local.declaration instanceof Argument)) // do not report unused catch arguments
232 // this.problemReporter().unusedLocalVariable(local.declaration);
235 // // could be optimized out, but does need to preserve unread variables ?
236 //// if (!generateCurrentLocalVar) {
237 //// if (local.declaration != null && environment().options.preserveAllLocalVariables) {
238 //// generateCurrentLocalVar = true; // force it to be preserved in the generated code
239 //// local.useFlag = LocalVariableBinding.USED;
243 // // allocate variable
244 // if (generateCurrentLocalVar) {
246 // if (local.declaration != null) {
247 // codeStream.record(local); // record user-defined local variables for attribute generation
249 // // assign variable position
250 // local.resolvedPosition = this.offset;
252 // if ((local.type == LongBinding) || (local.type == DoubleBinding)) {
257 // if (this.offset > 0xFFFF) { // no more than 65535 words of locals
258 // this.problemReporter().noMoreAvailableSpaceForLocal(
260 // local.declaration == null ? (ASTNode)this.methodScope().referenceContext : local.declaration);
263 // local.resolvedPosition = -1; // not generated
265 // hasMoreVariables = ++ilocal < maxLocals;
268 // if (this.offset > this.maxOffset)
269 // this.maxOffset = this.offset;
272 /* Answer true if the variable name already exists within the receiver's scope.
274 public final LocalVariableBinding duplicateName(char[] name) {
275 for (int i = 0; i < localIndex; i++)
276 if (CharOperation.equals(name, locals[i].name))
279 if (this instanceof MethodScope)
282 return ((BlockScope) parent).duplicateName(name);
286 * Record the suitable binding denoting a synthetic field or constructor argument,
287 * mapping to the actual outer local variable in the scope context.
288 * Note that this may not need any effect, in case the outer local variable does not
289 * need to be emulated and can directly be used as is (using its back pointer to its
292 public void emulateOuterAccess(LocalVariableBinding outerLocalVariable) {
294 MethodScope currentMethodScope;
295 if ((currentMethodScope = this.methodScope())
296 != outerLocalVariable.declaringScope.methodScope()) {
297 NestedTypeBinding currentType = (NestedTypeBinding) this.enclosingSourceType();
299 //do nothing for member types, pre emulation was performed already
300 if (!currentType.isLocalType()) {
303 // must also add a synthetic field if we're not inside a constructor
304 if (!currentMethodScope.isInsideInitializerOrConstructor()) {
305 currentType.addSyntheticArgumentAndField(outerLocalVariable);
307 currentType.addSyntheticArgument(outerLocalVariable);
312 /* Note that it must never produce a direct access to the targetEnclosingType,
313 * but instead a field sequence (this$2.this$1.this$0) so as to handle such a test case:
321 * return (Object) A.this == (Object) B.this;
326 * new A().new B().new C();
329 * where we only want to deal with ONE enclosing instance for C (could not figure out an A for C)
331 public final ReferenceBinding findLocalType(char[] name) {
333 for (int i = 0, length = scopeIndex; i < length; i++) {
334 if (subscopes[i] instanceof ClassScope) {
335 SourceTypeBinding sourceType =
336 ((ClassScope) subscopes[i]).referenceContext.binding;
337 if (CharOperation.equals(sourceType.sourceName(), name))
344 public LocalVariableBinding findVariable(char[] variable) {
346 int variableLength = variable.length;
347 for (int i = 0, length = locals.length; i < length; i++) {
348 LocalVariableBinding local = locals[i];
351 if (local.name.length == variableLength
352 && CharOperation.prefixEquals(local.name, variable))
358 * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE.
359 * Only bindings corresponding to the mask will be answered.
361 * if the VARIABLE mask is set then
362 * If the first name provided is a field (or local) then the field (or local) is answered
363 * Otherwise, package names and type names are consumed until a field is found.
364 * In this case, the field is answered.
366 * if the TYPE mask is set,
367 * package names and type names are consumed until the end of the input.
368 * Only if all of the input is consumed is the type answered
370 * All other conditions are errors, and a problem binding is returned.
372 * NOTE: If a problem binding is returned, senders should extract the compound name
373 * from the binding & not assume the problem applies to the entire compoundName.
375 * The VARIABLE mask has precedence over the TYPE mask.
377 * InvocationSite implements
378 * isSuperAccess(); this is used to determine if the discovered field is visible.
379 * setFieldIndex(int); this is used to record the number of names that were consumed.
381 * For example, getBinding({"foo","y","q", VARIABLE, site) will answer
382 * the binding for the field or local named "foo" (or an error binding if none exists).
383 * In addition, setFieldIndex(1) will be sent to the invocation site.
384 * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
386 * IMPORTANT NOTE: This method is written under the assumption that compoundName is longer than length 1.
388 public Binding getBinding(char[][] compoundName, int mask, InvocationSite invocationSite) {
390 Binding binding = getBinding(compoundName[0], mask | TYPE | PACKAGE, invocationSite);
391 invocationSite.setFieldIndex(1);
392 if (binding instanceof VariableBinding) return binding;
393 compilationUnitScope().recordSimpleReference(compoundName[0]);
394 if (!binding.isValidBinding()) return binding;
396 int length = compoundName.length;
397 int currentIndex = 1;
398 foundType : if (binding instanceof PackageBinding) {
399 PackageBinding packageBinding = (PackageBinding) binding;
400 while (currentIndex < length) {
401 compilationUnitScope().recordReference(packageBinding.compoundName, compoundName[currentIndex]);
402 binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]);
403 invocationSite.setFieldIndex(currentIndex);
404 if (binding == null) {
405 if (currentIndex == length)
406 // must be a type if its the last name, otherwise we have no idea if its a package or type
407 return new ProblemReferenceBinding(
408 CharOperation.subarray(compoundName, 0, currentIndex),
411 return new ProblemBinding(
412 CharOperation.subarray(compoundName, 0, currentIndex),
415 if (binding instanceof ReferenceBinding) {
416 if (!binding.isValidBinding())
417 return new ProblemReferenceBinding(
418 CharOperation.subarray(compoundName, 0, currentIndex),
419 binding.problemId());
420 if (!((ReferenceBinding) binding).canBeSeenBy(this))
421 return new ProblemReferenceBinding(
422 CharOperation.subarray(compoundName, 0, currentIndex),
423 (ReferenceBinding)binding,
427 packageBinding = (PackageBinding) binding;
430 // It is illegal to request a PACKAGE from this method.
431 return new ProblemReferenceBinding(
432 CharOperation.subarray(compoundName, 0, currentIndex),
436 // know binding is now a ReferenceBinding
437 while (currentIndex < length) {
438 ReferenceBinding typeBinding = (ReferenceBinding) binding;
439 char[] nextName = compoundName[currentIndex++];
440 invocationSite.setFieldIndex(currentIndex);
441 invocationSite.setActualReceiverType(typeBinding);
442 if ((mask & FIELD) != 0 && (binding = findField(typeBinding, nextName, invocationSite)) != null) {
443 if (!binding.isValidBinding())
444 return new ProblemFieldBinding(
445 ((FieldBinding) binding).declaringClass,
446 CharOperation.subarray(compoundName, 0, currentIndex),
447 binding.problemId());
448 break; // binding is now a field
450 if ((binding = findMemberType(nextName, typeBinding)) == null) {
451 if ((mask & FIELD) != 0) {
452 return new ProblemBinding(
453 CharOperation.subarray(compoundName, 0, currentIndex),
457 return new ProblemReferenceBinding(
458 CharOperation.subarray(compoundName, 0, currentIndex),
463 if (!binding.isValidBinding())
464 return new ProblemReferenceBinding(
465 CharOperation.subarray(compoundName, 0, currentIndex),
466 binding.problemId());
469 if ((mask & FIELD) != 0 && (binding instanceof FieldBinding)) {
470 // was looking for a field and found a field
471 FieldBinding field = (FieldBinding) binding;
472 if (!field.isStatic())
473 return new ProblemFieldBinding(
474 field.declaringClass,
475 CharOperation.subarray(compoundName, 0, currentIndex),
476 NonStaticReferenceInStaticContext);
479 if ((mask & TYPE) != 0 && (binding instanceof ReferenceBinding)) {
480 // was looking for a type and found a type
484 // handle the case when a field or type was asked for but we resolved the compoundName to a type or field
485 return new ProblemBinding(
486 CharOperation.subarray(compoundName, 0, currentIndex),
490 // Added for code assist... NOT Public API
491 public final Binding getBinding(
492 char[][] compoundName,
493 InvocationSite invocationSite) {
494 int currentIndex = 0;
495 int length = compoundName.length;
498 compoundName[currentIndex++],
499 VARIABLE | TYPE | PACKAGE,
501 if (!binding.isValidBinding())
504 foundType : if (binding instanceof PackageBinding) {
505 while (currentIndex < length) {
506 PackageBinding packageBinding = (PackageBinding) binding;
507 binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]);
508 if (binding == null) {
509 if (currentIndex == length)
510 // must be a type if its the last name, otherwise we have no idea if its a package or type
511 return new ProblemReferenceBinding(
512 CharOperation.subarray(compoundName, 0, currentIndex),
515 return new ProblemBinding(
516 CharOperation.subarray(compoundName, 0, currentIndex),
519 if (binding instanceof ReferenceBinding) {
520 if (!binding.isValidBinding())
521 return new ProblemReferenceBinding(
522 CharOperation.subarray(compoundName, 0, currentIndex),
523 binding.problemId());
524 if (!((ReferenceBinding) binding).canBeSeenBy(this))
525 return new ProblemReferenceBinding(
526 CharOperation.subarray(compoundName, 0, currentIndex),
527 (ReferenceBinding)binding,
535 foundField : if (binding instanceof ReferenceBinding) {
536 while (currentIndex < length) {
537 ReferenceBinding typeBinding = (ReferenceBinding) binding;
538 char[] nextName = compoundName[currentIndex++];
539 if ((binding = findField(typeBinding, nextName, invocationSite)) != null) {
540 if (!binding.isValidBinding())
541 return new ProblemFieldBinding(
542 ((FieldBinding) binding).declaringClass,
543 CharOperation.subarray(compoundName, 0, currentIndex),
544 binding.problemId());
545 if (!((FieldBinding) binding).isStatic())
546 return new ProblemFieldBinding(
547 ((FieldBinding) binding).declaringClass,
548 CharOperation.subarray(compoundName, 0, currentIndex),
549 NonStaticReferenceInStaticContext);
550 break foundField; // binding is now a field
552 if ((binding = findMemberType(nextName, typeBinding)) == null)
553 return new ProblemBinding(
554 CharOperation.subarray(compoundName, 0, currentIndex),
557 if (!binding.isValidBinding())
558 return new ProblemReferenceBinding(
559 CharOperation.subarray(compoundName, 0, currentIndex),
560 binding.problemId());
565 VariableBinding variableBinding = (VariableBinding) binding;
566 while (currentIndex < length) {
567 TypeBinding typeBinding = variableBinding.type;
568 if (typeBinding == null)
569 return new ProblemFieldBinding(
571 CharOperation.subarray(compoundName, 0, currentIndex + 1),
574 findField(typeBinding, compoundName[currentIndex++], invocationSite);
575 if (variableBinding == null)
576 return new ProblemFieldBinding(
578 CharOperation.subarray(compoundName, 0, currentIndex),
580 if (!variableBinding.isValidBinding())
581 return variableBinding;
583 return variableBinding;
588 * Answer the binding that corresponds to the argument name.
589 * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE, PACKAGE.
590 * Only bindings corresponding to the mask can be answered.
592 * For example, getBinding("foo", VARIABLE, site) will answer
593 * the binding for the field or local named "foo" (or an error binding if none exists).
594 * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
596 * The VARIABLE mask has precedence over the TYPE mask.
598 * If the VARIABLE mask is not set, neither fields nor locals will be looked for.
600 * InvocationSite implements:
601 * isSuperAccess(); this is used to determine if the discovered field is visible.
603 * Limitations: cannot request FIELD independently of LOCAL, or vice versa
605 public Binding getBinding(char[] name, int mask, InvocationSite invocationSite) {
607 Binding binding = null;
608 FieldBinding problemField = null;
609 if ((mask & VARIABLE) != 0) {
610 if (this.kind == BLOCK_SCOPE || this.kind == METHOD_SCOPE) {
611 LocalVariableBinding variableBinding = findVariable(name);
612 // looks in this scope only
613 if (variableBinding != null) return variableBinding;
616 boolean insideStaticContext = false;
617 boolean insideConstructorCall = false;
618 if (this.kind == METHOD_SCOPE) {
619 MethodScope methodScope = (MethodScope) this;
620 insideStaticContext |= methodScope.isStatic;
621 insideConstructorCall |= methodScope.isConstructorCall;
624 FieldBinding foundField = null;
625 // can be a problem field which is answered if a valid field is not found
626 ProblemFieldBinding foundInsideProblem = null;
627 // inside Constructor call or inside static context
628 Scope scope = parent;
631 ReferenceBinding foundActualReceiverType = null;
632 done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
633 switch (scope.kind) {
635 MethodScope methodScope = (MethodScope) scope;
636 insideStaticContext |= methodScope.isStatic;
637 insideConstructorCall |= methodScope.isConstructorCall;
638 // Fall through... could duplicate the code below to save a cast - questionable optimization
640 LocalVariableBinding variableBinding = ((BlockScope) scope).findVariable(name);
641 // looks in this scope only
642 if (variableBinding != null) {
643 if (foundField != null && foundField.isValidBinding())
644 return new ProblemFieldBinding(
645 foundField.declaringClass,
647 InheritedNameHidesEnclosingName);
649 invocationSite.setDepth(depth);
650 return variableBinding;
654 ClassScope classScope = (ClassScope) scope;
655 SourceTypeBinding enclosingType = classScope.referenceContext.binding;
656 FieldBinding fieldBinding =
657 classScope.findField(enclosingType, name, invocationSite);
658 // Use next line instead if willing to enable protected access accross inner types
659 // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);
660 if (fieldBinding != null) { // skip it if we did not find anything
661 if (fieldBinding.problemId() == Ambiguous) {
662 if (foundField == null || foundField.problemId() == NotVisible)
663 // supercedes any potential InheritedNameHidesEnclosingName problem
666 // make the user qualify the field, likely wants the first inherited field (javac generates an ambiguous error instead)
667 return new ProblemFieldBinding(
668 fieldBinding.declaringClass,
670 InheritedNameHidesEnclosingName);
673 ProblemFieldBinding insideProblem = null;
674 if (fieldBinding.isValidBinding()) {
675 if (!fieldBinding.isStatic()) {
676 if (insideConstructorCall) {
678 new ProblemFieldBinding(
679 fieldBinding.declaringClass,
681 NonStaticReferenceInConstructorInvocation);
682 } else if (insideStaticContext) {
684 new ProblemFieldBinding(
685 fieldBinding.declaringClass,
687 NonStaticReferenceInStaticContext);
690 // if (enclosingType == fieldBinding.declaringClass
691 // || environment().options.complianceLevel >= CompilerOptions.JDK1_4){
692 // // found a valid field in the 'immediate' scope (ie. not inherited)
693 // // OR in 1.4 mode (inherited shadows enclosing)
694 // if (foundField == null) {
696 // invocationSite.setDepth(depth);
697 // invocationSite.setActualReceiverType(enclosingType);
699 // // return the fieldBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
700 // return insideProblem == null ? fieldBinding : insideProblem;
702 // if (foundField.isValidBinding())
703 // // if a valid field was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
704 // if (foundField.declaringClass != fieldBinding.declaringClass)
705 // // ie. have we found the same field - do not trust field identity yet
706 // return new ProblemFieldBinding(
707 // fieldBinding.declaringClass,
709 // InheritedNameHidesEnclosingName);
713 if (foundField == null
714 || (foundField.problemId() == NotVisible
715 && fieldBinding.problemId() != NotVisible)) {
716 // only remember the fieldBinding if its the first one found or the previous one was not visible & fieldBinding is...
718 foundActualReceiverType = enclosingType;
719 foundInsideProblem = insideProblem;
720 foundField = fieldBinding;
724 insideStaticContext |= enclosingType.isStatic();
725 // 1EX5I8Z - accessing outer fields within a constructor call is permitted
726 // in order to do so, we change the flag as we exit from the type, not the method
727 // itself, because the class scope is used to retrieve the fields.
728 MethodScope enclosingMethodScope = scope.methodScope();
729 insideConstructorCall =
730 enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
732 case COMPILATION_UNIT_SCOPE :
735 scope = scope.parent;
738 if (foundInsideProblem != null){
739 return foundInsideProblem;
741 if (foundField != null) {
742 if (foundField.isValidBinding()){
744 invocationSite.setDepth(foundDepth);
745 invocationSite.setActualReceiverType(foundActualReceiverType);
749 problemField = foundField;
753 // We did not find a local or instance variable.
754 if ((mask & TYPE) != 0) {
755 if ((binding = getBaseType(name)) != null)
757 binding = getTypeOrPackage(name, (mask & PACKAGE) == 0 ? TYPE : TYPE | PACKAGE);
758 if (binding.isValidBinding() || mask == TYPE)
760 // answer the problem type binding if we are only looking for a type
761 } else if ((mask & PACKAGE) != 0) {
762 compilationUnitScope().recordSimpleReference(name);
763 if ((binding = environment().getTopLevelPackage(name)) != null)
766 if (problemField != null)
769 return new ProblemBinding(name, enclosingSourceType(), NotFound);
774 * Answer the constructor binding that corresponds to receiverType, argumentTypes.
776 * InvocationSite implements
777 * isSuperAccess(); this is used to determine if the discovered constructor is visible.
779 * If no visible constructor is discovered, an error binding is answered.
781 public MethodBinding getConstructor(
782 ReferenceBinding receiverType,
783 TypeBinding[] argumentTypes,
784 InvocationSite invocationSite) {
786 compilationUnitScope().recordTypeReference(receiverType);
787 compilationUnitScope().recordTypeReferences(argumentTypes);
788 MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
789 if (methodBinding != null) {
790 if (methodBinding.canBeSeenBy(invocationSite, this))
791 return methodBinding;
793 MethodBinding[] methods =
794 receiverType.getMethods(ConstructorDeclaration.ConstantPoolName);
795 if (methods == NoMethods) {
796 return new ProblemMethodBinding(
797 ConstructorDeclaration.ConstantPoolName,
801 MethodBinding[] compatible = new MethodBinding[methods.length];
802 int compatibleIndex = 0;
803 for (int i = 0, length = methods.length; i < length; i++)
804 if (areParametersAssignable(methods[i].parameters, argumentTypes))
805 compatible[compatibleIndex++] = methods[i];
806 if (compatibleIndex == 0)
807 return new ProblemMethodBinding(
808 ConstructorDeclaration.ConstantPoolName,
811 // need a more descriptive error... cannot convert from X to Y
813 MethodBinding[] visible = new MethodBinding[compatibleIndex];
814 int visibleIndex = 0;
815 for (int i = 0; i < compatibleIndex; i++) {
816 MethodBinding method = compatible[i];
817 if (method.canBeSeenBy(invocationSite, this))
818 visible[visibleIndex++] = method;
820 if (visibleIndex == 1)
822 if (visibleIndex == 0)
823 return new ProblemMethodBinding(
825 ConstructorDeclaration.ConstantPoolName,
826 compatible[0].parameters,
828 return mostSpecificClassMethodBinding(visible, visibleIndex);
832 * This retrieves the argument that maps to an enclosing instance of the suitable type,
833 * if not found then answers nil -- do not create one
835 * #implicitThis : the implicit this will be ok
836 * #((arg) this$n) : available as a constructor arg
837 * #((arg) this$n ... this$p) : available as as a constructor arg + a sequence of fields
838 * #((fieldDescr) this$n ... this$p) : available as a sequence of fields
841 * Note that this algorithm should answer the shortest possible sequence when
842 * shortcuts are available:
843 * this$0 . this$0 . this$0
845 * this$2 . this$1 . this$0 . this$1 . this$0
846 * thus the code generation will be more compact and runtime faster
848 public VariableBinding[] getEmulationPath(LocalVariableBinding outerLocalVariable) {
850 MethodScope currentMethodScope = this.methodScope();
851 SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType();
854 if (currentMethodScope == outerLocalVariable.declaringScope.methodScope()) {
855 return new VariableBinding[] { outerLocalVariable };
856 // implicit this is good enough
858 // use synthetic constructor arguments if possible
859 if (currentMethodScope.isInsideInitializerOrConstructor()
860 && (sourceType.isNestedType())) {
861 SyntheticArgumentBinding syntheticArg;
862 if ((syntheticArg = ((NestedTypeBinding) sourceType).getSyntheticArgument(outerLocalVariable)) != null) {
863 return new VariableBinding[] { syntheticArg };
866 // use a synthetic field then
867 if (!currentMethodScope.isStatic) {
868 FieldBinding syntheticField;
869 if ((syntheticField = sourceType.getSyntheticField(outerLocalVariable)) != null) {
870 return new VariableBinding[] { syntheticField };
877 * This retrieves the argument that maps to an enclosing instance of the suitable type,
878 * if not found then answers nil -- do not create one
880 * #implicitThis : the implicit this will be ok
881 * #((arg) this$n) : available as a constructor arg
882 * #((arg) this$n access$m... access$p) : available as as a constructor arg + a sequence of synthetic accessors to synthetic fields
883 * #((fieldDescr) this$n access#m... access$p) : available as a first synthetic field + a sequence of synthetic accessors to synthetic fields
887 public Object[] getEmulationPath(
888 ReferenceBinding targetEnclosingType,
889 boolean onlyExactMatch,
890 boolean ignoreEnclosingArgInConstructorCall) {
891 //TODO: (philippe) investigate why exactly test76 fails if ignoreEnclosingArgInConstructorCall is always false
892 MethodScope currentMethodScope = this.methodScope();
893 SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType();
896 if (!currentMethodScope.isStatic
897 && (!currentMethodScope.isConstructorCall || ignoreEnclosingArgInConstructorCall)
898 && (sourceType == targetEnclosingType
899 || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(sourceType)))) {
900 if (currentMethodScope.isConstructorCall) {
901 return NoEnclosingInstanceInConstructorCall;
903 if (currentMethodScope.isStatic){
904 return NoEnclosingInstanceInStaticContext;
906 return EmulationPathToImplicitThis; // implicit this is good enough
908 if (!sourceType.isNestedType() || sourceType.isStatic()) { // no emulation from within non-inner types
909 if (currentMethodScope.isConstructorCall) {
910 return NoEnclosingInstanceInConstructorCall;
912 if (currentMethodScope.isStatic){
913 return NoEnclosingInstanceInStaticContext;
917 boolean insideConstructor = currentMethodScope.isInsideInitializerOrConstructor();
918 // use synthetic constructor arguments if possible
919 if (insideConstructor) {
920 SyntheticArgumentBinding syntheticArg;
921 if ((syntheticArg = ((NestedTypeBinding) sourceType).getSyntheticArgument(targetEnclosingType, onlyExactMatch)) != null) {
922 return new Object[] { syntheticArg };
926 // use a direct synthetic field then
927 if (currentMethodScope.isStatic) {
928 return NoEnclosingInstanceInStaticContext;
930 FieldBinding syntheticField = sourceType.getSyntheticField(targetEnclosingType, onlyExactMatch);
931 if (syntheticField != null) {
932 if (currentMethodScope.isConstructorCall){
933 return NoEnclosingInstanceInConstructorCall;
935 return new Object[] { syntheticField };
937 // could be reached through a sequence of enclosing instance link (nested members)
938 Object[] path = new Object[2]; // probably at least 2 of them
939 ReferenceBinding currentType = sourceType.enclosingType();
940 if (insideConstructor) {
941 path[0] = ((NestedTypeBinding) sourceType).getSyntheticArgument((SourceTypeBinding) currentType, onlyExactMatch);
943 if (currentMethodScope.isConstructorCall){
944 return NoEnclosingInstanceInConstructorCall;
946 path[0] = sourceType.getSyntheticField((SourceTypeBinding) currentType, onlyExactMatch);
948 if (path[0] != null) { // keep accumulating
951 ReferenceBinding currentEnclosingType;
952 while ((currentEnclosingType = currentType.enclosingType()) != null) {
955 if (currentType == targetEnclosingType
956 || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(currentType))) break;
958 if (currentMethodScope != null) {
959 currentMethodScope = currentMethodScope.enclosingMethodScope();
960 if (currentMethodScope != null && currentMethodScope.isConstructorCall){
961 return NoEnclosingInstanceInConstructorCall;
963 if (currentMethodScope != null && currentMethodScope.isStatic){
964 return NoEnclosingInstanceInStaticContext;
968 syntheticField = ((NestedTypeBinding) currentType).getSyntheticField((SourceTypeBinding) currentEnclosingType, onlyExactMatch);
969 if (syntheticField == null) break;
971 // append inside the path
972 if (count == path.length) {
973 System.arraycopy(path, 0, (path = new Object[count + 1]), 0, count);
975 // private access emulation is necessary since synthetic field is private
976 path[count++] = ((SourceTypeBinding) syntheticField.declaringClass).addSyntheticMethod(syntheticField, true);
977 currentType = currentEnclosingType;
979 if (currentType == targetEnclosingType
980 || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(currentType))) {
989 * Answer the field binding that corresponds to fieldName.
990 * Start the lookup at the receiverType.
991 * InvocationSite implements
992 * isSuperAccess(); this is used to determine if the discovered field is visible.
993 * Only fields defined by the receiverType or its supertypes are answered;
994 * a field of an enclosing type will not be found using this API.
996 * If no visible field is discovered, an error binding is answered.
998 public FieldBinding getField(
999 TypeBinding receiverType,
1001 InvocationSite invocationSite) {
1003 FieldBinding field = findField(receiverType, fieldName, invocationSite);
1005 return new ProblemFieldBinding(
1006 receiverType instanceof ReferenceBinding
1007 ? (ReferenceBinding) receiverType
1017 * Answer the method binding that corresponds to selector, argumentTypes.
1018 * Start the lookup at the enclosing type of the receiver.
1019 * InvocationSite implements
1020 * isSuperAccess(); this is used to determine if the discovered method is visible.
1021 * setDepth(int); this is used to record the depth of the discovered method
1022 * relative to the enclosing type of the receiver. (If the method is defined
1023 * in the enclosing type of the receiver, the depth is 0; in the next enclosing
1024 * type, the depth is 1; and so on
1026 * If no visible method is discovered, an error binding is answered.
1028 public MethodBinding getImplicitMethod(
1030 TypeBinding[] argumentTypes,
1031 InvocationSite invocationSite) {
1033 boolean insideStaticContext = false;
1034 boolean insideConstructorCall = false;
1035 MethodBinding foundMethod = null;
1036 ProblemMethodBinding foundFuzzyProblem = null;
1037 // the weird method lookup case (matches method name in scope, then arg types, then visibility)
1038 ProblemMethodBinding foundInsideProblem = null;
1039 // inside Constructor call or inside static context
1042 done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
1043 switch (scope.kind) {
1045 MethodScope methodScope = (MethodScope) scope;
1046 insideStaticContext |= methodScope.isStatic;
1047 insideConstructorCall |= methodScope.isConstructorCall;
1050 ClassScope classScope = (ClassScope) scope;
1051 SourceTypeBinding receiverType = classScope.referenceContext.binding;
1052 boolean isExactMatch = true;
1053 // retrieve an exact visible match (if possible)
1054 MethodBinding methodBinding =
1055 (foundMethod == null)
1056 ? classScope.findExactMethod(
1061 : classScope.findExactMethod(
1063 foundMethod.selector,
1064 foundMethod.parameters,
1066 // ? findExactMethod(receiverType, selector, argumentTypes, invocationSite)
1067 // : findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite);
1068 if (methodBinding == null) {
1069 // answers closest approximation, may not check argumentTypes or visibility
1070 isExactMatch = false;
1072 classScope.findMethod(receiverType, selector, argumentTypes, invocationSite);
1073 // methodBinding = findMethod(receiverType, selector, argumentTypes, invocationSite);
1075 if (methodBinding != null) { // skip it if we did not find anything
1076 if (methodBinding.problemId() == Ambiguous) {
1077 if (foundMethod == null || foundMethod.problemId() == NotVisible)
1078 // supercedes any potential InheritedNameHidesEnclosingName problem
1079 return methodBinding;
1081 // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
1082 return new ProblemMethodBinding(
1085 InheritedNameHidesEnclosingName);
1088 ProblemMethodBinding fuzzyProblem = null;
1089 ProblemMethodBinding insideProblem = null;
1090 if (methodBinding.isValidBinding()) {
1091 if (!isExactMatch) {
1092 if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) {
1093 if (foundMethod == null || foundMethod.problemId() == NotVisible){
1094 // inherited mismatch is reported directly, not looking at enclosing matches
1095 return new ProblemMethodBinding(methodBinding, selector, argumentTypes, NotFound);
1097 // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
1098 fuzzyProblem = new ProblemMethodBinding(selector, methodBinding.parameters, InheritedNameHidesEnclosingName);
1100 } else if (!methodBinding.canBeSeenBy(receiverType, invocationSite, classScope)) {
1101 // using <classScope> instead of <this> for visibility check does grant all access to innerclass
1103 new ProblemMethodBinding(
1106 methodBinding.parameters,
1110 if (fuzzyProblem == null && !methodBinding.isStatic()) {
1111 if (insideConstructorCall) {
1113 new ProblemMethodBinding(
1114 methodBinding.selector,
1115 methodBinding.parameters,
1116 NonStaticReferenceInConstructorInvocation);
1117 } else if (insideStaticContext) {
1119 new ProblemMethodBinding(
1120 methodBinding.selector,
1121 methodBinding.parameters,
1122 NonStaticReferenceInStaticContext);
1126 // if (receiverType == methodBinding.declaringClass
1127 // || (receiverType.getMethods(selector)) != NoMethods
1128 // || ((fuzzyProblem == null || fuzzyProblem.problemId() != NotVisible) && environment().options.complianceLevel >= CompilerOptions.JDK1_4)){
1129 // // found a valid method in the 'immediate' scope (ie. not inherited)
1130 // // OR the receiverType implemented a method with the correct name
1131 // // OR in 1.4 mode (inherited visible shadows enclosing)
1132 // if (foundMethod == null) {
1134 // invocationSite.setDepth(depth);
1135 // invocationSite.setActualReceiverType(receiverType);
1137 // // return the methodBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
1138 // if (fuzzyProblem != null)
1139 // return fuzzyProblem;
1140 // if (insideProblem != null)
1141 // return insideProblem;
1142 // return methodBinding;
1144 // // if a method was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
1145 // // NOTE: Unlike fields, a non visible method hides a visible method
1146 // if (foundMethod.declaringClass != methodBinding.declaringClass)
1147 // // ie. have we found the same method - do not trust field identity yet
1148 // return new ProblemMethodBinding(
1149 // methodBinding.selector,
1150 // methodBinding.parameters,
1151 // InheritedNameHidesEnclosingName);
1155 if (foundMethod == null
1156 || (foundMethod.problemId() == NotVisible
1157 && methodBinding.problemId() != NotVisible)) {
1158 // only remember the methodBinding if its the first one found or the previous one was not visible & methodBinding is...
1159 // remember that private methods are visible if defined directly by an enclosing class
1161 invocationSite.setDepth(depth);
1162 invocationSite.setActualReceiverType(receiverType);
1164 foundFuzzyProblem = fuzzyProblem;
1165 foundInsideProblem = insideProblem;
1166 if (fuzzyProblem == null)
1167 foundMethod = methodBinding; // only keep it if no error was found
1171 insideStaticContext |= receiverType.isStatic();
1172 // 1EX5I8Z - accessing outer fields within a constructor call is permitted
1173 // in order to do so, we change the flag as we exit from the type, not the method
1174 // itself, because the class scope is used to retrieve the fields.
1175 MethodScope enclosingMethodScope = scope.methodScope();
1176 insideConstructorCall =
1177 enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
1179 case COMPILATION_UNIT_SCOPE :
1182 scope = scope.parent;
1185 if (foundFuzzyProblem != null)
1186 return foundFuzzyProblem;
1187 if (foundInsideProblem != null)
1188 return foundInsideProblem;
1189 if (foundMethod != null)
1191 return new ProblemMethodBinding(selector, argumentTypes, NotFound);
1196 * Answer the method binding that corresponds to selector, argumentTypes.
1197 * Start the lookup at the receiverType.
1198 * InvocationSite implements
1199 * isSuperAccess(); this is used to determine if the discovered method is visible.
1201 * Only methods defined by the receiverType or its supertypes are answered;
1202 * use getImplicitMethod() to discover methods of enclosing types.
1204 * If no visible method is discovered, an error binding is answered.
1206 public MethodBinding getMethod(
1207 TypeBinding receiverType,
1209 TypeBinding[] argumentTypes,
1210 InvocationSite invocationSite) {
1212 if (receiverType.isArrayType())
1213 return findMethodForArray(
1214 (ArrayBinding) receiverType,
1218 if (receiverType.isBaseType())
1219 return new ProblemMethodBinding(selector, argumentTypes, NotFound);
1221 ReferenceBinding currentType = (ReferenceBinding) receiverType;
1222 if (!currentType.canBeSeenBy(this))
1223 return new ProblemMethodBinding(selector, argumentTypes, ReceiverTypeNotVisible);
1225 // retrieve an exact visible match (if possible)
1226 MethodBinding methodBinding =
1227 findExactMethod(currentType, selector, argumentTypes, invocationSite);
1228 if (methodBinding != null)
1229 return methodBinding;
1231 // answers closest approximation, may not check argumentTypes or visibility
1233 findMethod(currentType, selector, argumentTypes, invocationSite);
1234 if (methodBinding == null)
1235 return new ProblemMethodBinding(selector, argumentTypes, NotFound);
1236 if (methodBinding.isValidBinding()) {
1237 if (!areParametersAssignable(methodBinding.parameters, argumentTypes))
1238 return new ProblemMethodBinding(
1243 if (!methodBinding.canBeSeenBy(currentType, invocationSite, this))
1244 return new ProblemMethodBinding(
1247 methodBinding.parameters,
1250 return methodBinding;
1253 public int maxShiftedOffset() {
1255 if (this.shiftScopes != null){
1256 for (int i = 0, length = this.shiftScopes.length; i < length; i++){
1257 int subMaxOffset = this.shiftScopes[i].maxOffset;
1258 if (subMaxOffset > max) max = subMaxOffset;
1264 /* Answer the problem reporter to use for raising new problems.
1266 * Note that as a side-effect, this updates the current reference context
1267 * (unit, type or method) in case the problem handler decides it is necessary
1270 public ProblemReporter problemReporter() {
1272 return outerMostMethodScope().problemReporter();
1276 * Code responsible to request some more emulation work inside the invocation type, so as to supply
1277 * correct synthetic arguments to any allocation of the target type.
1279 public void propagateInnerEmulation(ReferenceBinding targetType, boolean isEnclosingInstanceSupplied) {
1281 // no need to propagate enclosing instances, they got eagerly allocated already.
1283 SyntheticArgumentBinding[] syntheticArguments;
1284 if ((syntheticArguments = targetType.syntheticOuterLocalVariables()) != null) {
1285 for (int i = 0, max = syntheticArguments.length; i < max; i++) {
1286 SyntheticArgumentBinding syntheticArg = syntheticArguments[i];
1287 // need to filter out the one that could match a supplied enclosing instance
1288 if (!(isEnclosingInstanceSupplied
1289 && (syntheticArg.type == targetType.enclosingType()))) {
1290 this.emulateOuterAccess(syntheticArg.actualOuterLocalVariable);
1296 /* Answer the reference type of this scope.
1298 * It is the nearest enclosing type of this scope.
1300 public TypeDeclaration referenceType() {
1302 return methodScope().referenceType();
1305 // start position in this scope - for ordering scopes vs. variables
1310 public String toString() {
1314 public String toString(int tab) {
1316 String s = basicToString(tab);
1317 for (int i = 0; i < scopeIndex; i++)
1318 if (subscopes[i] instanceof BlockScope)
1319 s += ((BlockScope) subscopes[i]).toString(tab + 1) + "\n"; //$NON-NLS-1$