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.core.compiler.CharOperation;
14 import net.sourceforge.phpdt.internal.compiler.ast.AbstractMethodDeclaration;
15 import net.sourceforge.phpdt.internal.compiler.ast.ConstructorDeclaration;
16 import net.sourceforge.phpdt.internal.compiler.ast.TypeDeclaration;
17 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
19 public class BlockScope extends Scope {
21 // Local variable management
22 public LocalVariableBinding[] locals;
23 public int localIndex; // position for next variable
24 public int startIndex; // start position in this scope - for ordering scopes vs. variables
25 public int offset; // for variable allocation throughout scopes
26 public int maxOffset; // for variable allocation throughout scopes
28 // finally scopes must be shifted behind respective try&catch scope(s) so as to avoid
29 // collisions of secret variables (return address, save value).
30 public BlockScope[] shiftScopes;
32 public final static VariableBinding[] EmulationPathToImplicitThis = {};
33 public final static VariableBinding[] NoEnclosingInstanceInConstructorCall = {};
34 public final static VariableBinding[] NoEnclosingInstanceInStaticContext = {};
36 public Scope[] subscopes = new Scope[1]; // need access from code assist
37 public int scopeIndex = 0; // need access from code assist
39 protected BlockScope(int kind, Scope parent) {
44 public BlockScope(BlockScope parent) {
49 public BlockScope(BlockScope parent, boolean addToParentScope) {
51 this(BLOCK_SCOPE, parent);
52 locals = new LocalVariableBinding[5];
53 if (addToParentScope) parent.addSubscope(this);
54 this.startIndex = parent.localIndex;
57 public BlockScope(BlockScope parent, int variableCount) {
59 this(BLOCK_SCOPE, parent);
60 locals = new LocalVariableBinding[variableCount];
61 parent.addSubscope(this);
62 this.startIndex = parent.localIndex;
65 /* Create the class scope & binding for the anonymous type.
67 public final void addAnonymousType(
68 TypeDeclaration anonymousType,
69 ReferenceBinding superBinding) {
71 ClassScope anonymousClassScope = new ClassScope(this, anonymousType);
72 anonymousClassScope.buildAnonymousTypeBinding(
73 enclosingSourceType(),
77 /* Create the class scope & binding for the local type.
79 public final void addLocalType(TypeDeclaration localType) {
81 // check that the localType does not conflict with an enclosing type
82 ReferenceBinding type = enclosingSourceType();
84 if (CharOperation.equals(type.sourceName, localType.name)) {
85 problemReporter().hidingEnclosingType(localType);
88 type = type.enclosingType();
89 } while (type != null);
91 // check that the localType does not conflict with another sibling local type
94 if (((BlockScope) scope).findLocalType(localType.name) != null) {
95 problemReporter().duplicateNestedType(localType);
98 } while ((scope = scope.parent) instanceof BlockScope);
100 ClassScope localTypeScope = new ClassScope(this, localType);
101 addSubscope(localTypeScope);
102 localTypeScope.buildLocalTypeBinding(enclosingSourceType());
105 /* Insert a local variable into a given scope, updating its position
106 * and checking there are not too many locals or arguments allocated.
108 public final void addLocalVariable(LocalVariableBinding binding) {
110 checkAndSetModifiersForVariable(binding);
112 // insert local in scope
113 if (localIndex == locals.length)
117 (locals = new LocalVariableBinding[localIndex * 2]),
120 locals[localIndex++] = binding;
122 // update local variable binding
123 binding.declaringScope = this;
124 binding.id = this.outerMostMethodScope().analysisIndex++;
125 // share the outermost method scope analysisIndex
128 public void addSubscope(Scope childScope) {
129 if (scopeIndex == subscopes.length)
133 (subscopes = new Scope[scopeIndex * 2]),
136 subscopes[scopeIndex++] = childScope;
139 /* Answer true if the receiver is suitable for assigning final blank fields.
141 * in other words, it is inside an initializer, a constructor or a clinit
143 public final boolean allowBlankFinalFieldAssignment(FieldBinding binding) {
145 if (enclosingSourceType() != binding.declaringClass)
148 MethodScope methodScope = methodScope();
149 if (methodScope.isStatic != binding.isStatic())
151 return methodScope.isInsideInitializer() // inside initializer
152 || ((AbstractMethodDeclaration) methodScope.referenceContext)
153 .isInitializationMethod(); // inside constructor or clinit
155 String basicToString(int tab) {
156 String newLine = "\n"; //$NON-NLS-1$
157 for (int i = tab; --i >= 0;)
158 newLine += "\t"; //$NON-NLS-1$
160 String s = newLine + "--- Block Scope ---"; //$NON-NLS-1$
161 newLine += "\t"; //$NON-NLS-1$
162 s += newLine + "locals:"; //$NON-NLS-1$
163 for (int i = 0; i < localIndex; i++)
164 s += newLine + "\t" + locals[i].toString(); //$NON-NLS-1$
165 s += newLine + "startIndex = " + startIndex; //$NON-NLS-1$
169 private void checkAndSetModifiersForVariable(LocalVariableBinding varBinding) {
171 int modifiers = varBinding.modifiers;
172 if ((modifiers & AccAlternateModifierProblem) != 0 && varBinding.declaration != null){
173 problemReporter().duplicateModifierForVariable(varBinding.declaration, this instanceof MethodScope);
175 int realModifiers = modifiers & AccJustFlag;
177 int unexpectedModifiers = ~AccFinal;
178 if ((realModifiers & unexpectedModifiers) != 0 && varBinding.declaration != null){
179 problemReporter().illegalModifierForVariable(varBinding.declaration, this instanceof MethodScope);
181 varBinding.modifiers = modifiers;
184 /* Compute variable positions in scopes given an initial position offset
185 * ignoring unused local variables.
187 * No argument is expected here (ilocal is the first non-argument local of the outermost scope)
188 * Arguments are managed by the MethodScope method
190 // void computeLocalVariablePositions(int ilocal, int initOffset, CodeStream codeStream) {
192 // this.offset = initOffset;
193 // this.maxOffset = initOffset;
195 // // local variable init
196 // int maxLocals = this.localIndex;
197 // boolean hasMoreVariables = ilocal < maxLocals;
200 // int iscope = 0, maxScopes = this.scopeIndex;
201 // boolean hasMoreScopes = maxScopes > 0;
203 // // iterate scopes and variables in parallel
204 // while (hasMoreVariables || hasMoreScopes) {
206 // && (!hasMoreVariables || (subscopes[iscope].startIndex() <= ilocal))) {
207 // // consider subscope first
208 // if (subscopes[iscope] instanceof BlockScope) {
209 // BlockScope subscope = (BlockScope) subscopes[iscope];
210 // int subOffset = subscope.shiftScopes == null ? this.offset : subscope.maxShiftedOffset();
211 // subscope.computeLocalVariablePositions(0, subOffset, codeStream);
212 // if (subscope.maxOffset > this.maxOffset)
213 // this.maxOffset = subscope.maxOffset;
215 // hasMoreScopes = ++iscope < maxScopes;
218 // // consider variable first
219 // LocalVariableBinding local = locals[ilocal]; // if no local at all, will be locals[ilocal]==null
221 // // check if variable is actually used, and may force it to be preserved
222 // boolean generateCurrentLocalVar = (local.useFlag == LocalVariableBinding.USED && (local.constant == Constant.NotAConstant));
224 // // do not report fake used variable
225 // if (local.useFlag == LocalVariableBinding.UNUSED
226 // && (local.declaration != null) // unused (and non secret) local
227 // && ((local.declaration.bits & ASTNode.IsLocalDeclarationReachableMASK) != 0)) { // declaration is reachable
229 // if (!(local.declaration instanceof Argument)) // do not report unused catch arguments
230 // this.problemReporter().unusedLocalVariable(local.declaration);
233 // // could be optimized out, but does need to preserve unread variables ?
234 //// if (!generateCurrentLocalVar) {
235 //// if (local.declaration != null && environment().options.preserveAllLocalVariables) {
236 //// generateCurrentLocalVar = true; // force it to be preserved in the generated code
237 //// local.useFlag = LocalVariableBinding.USED;
241 // // allocate variable
242 // if (generateCurrentLocalVar) {
244 // if (local.declaration != null) {
245 // codeStream.record(local); // record user-defined local variables for attribute generation
247 // // assign variable position
248 // local.resolvedPosition = this.offset;
250 // if ((local.type == LongBinding) || (local.type == DoubleBinding)) {
255 // if (this.offset > 0xFFFF) { // no more than 65535 words of locals
256 // this.problemReporter().noMoreAvailableSpaceForLocal(
258 // local.declaration == null ? (ASTNode)this.methodScope().referenceContext : local.declaration);
261 // local.resolvedPosition = -1; // not generated
263 // hasMoreVariables = ++ilocal < maxLocals;
266 // if (this.offset > this.maxOffset)
267 // this.maxOffset = this.offset;
270 /* Answer true if the variable name already exists within the receiver's scope.
272 public final LocalVariableBinding duplicateName(char[] name) {
273 for (int i = 0; i < localIndex; i++)
274 if (CharOperation.equals(name, locals[i].name))
277 if (this instanceof MethodScope)
280 return ((BlockScope) parent).duplicateName(name);
284 * Record the suitable binding denoting a synthetic field or constructor argument,
285 * mapping to the actual outer local variable in the scope context.
286 * Note that this may not need any effect, in case the outer local variable does not
287 * need to be emulated and can directly be used as is (using its back pointer to its
290 public void emulateOuterAccess(LocalVariableBinding outerLocalVariable) {
292 MethodScope currentMethodScope;
293 if ((currentMethodScope = this.methodScope())
294 != outerLocalVariable.declaringScope.methodScope()) {
295 NestedTypeBinding currentType = (NestedTypeBinding) this.enclosingSourceType();
297 //do nothing for member types, pre emulation was performed already
298 if (!currentType.isLocalType()) {
301 // must also add a synthetic field if we're not inside a constructor
302 if (!currentMethodScope.isInsideInitializerOrConstructor()) {
303 currentType.addSyntheticArgumentAndField(outerLocalVariable);
305 currentType.addSyntheticArgument(outerLocalVariable);
310 /* Note that it must never produce a direct access to the targetEnclosingType,
311 * but instead a field sequence (this$2.this$1.this$0) so as to handle such a test case:
319 * return (Object) A.this == (Object) B.this;
324 * new A().new B().new C();
327 * where we only want to deal with ONE enclosing instance for C (could not figure out an A for C)
329 public final ReferenceBinding findLocalType(char[] name) {
331 for (int i = 0, length = scopeIndex; i < length; i++) {
332 if (subscopes[i] instanceof ClassScope) {
333 SourceTypeBinding sourceType =
334 ((ClassScope) subscopes[i]).referenceContext.binding;
335 if (CharOperation.equals(sourceType.sourceName(), name))
342 public LocalVariableBinding findVariable(char[] variable) {
344 int variableLength = variable.length;
345 for (int i = 0, length = locals.length; i < length; i++) {
346 LocalVariableBinding local = locals[i];
349 if (local.name.length == variableLength
350 && CharOperation.prefixEquals(local.name, variable))
356 * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE.
357 * Only bindings corresponding to the mask will be answered.
359 * if the VARIABLE mask is set then
360 * If the first name provided is a field (or local) then the field (or local) is answered
361 * Otherwise, package names and type names are consumed until a field is found.
362 * In this case, the field is answered.
364 * if the TYPE mask is set,
365 * package names and type names are consumed until the end of the input.
366 * Only if all of the input is consumed is the type answered
368 * All other conditions are errors, and a problem binding is returned.
370 * NOTE: If a problem binding is returned, senders should extract the compound name
371 * from the binding & not assume the problem applies to the entire compoundName.
373 * The VARIABLE mask has precedence over the TYPE mask.
375 * InvocationSite implements
376 * isSuperAccess(); this is used to determine if the discovered field is visible.
377 * setFieldIndex(int); this is used to record the number of names that were consumed.
379 * For example, getBinding({"foo","y","q", VARIABLE, site) will answer
380 * the binding for the field or local named "foo" (or an error binding if none exists).
381 * In addition, setFieldIndex(1) will be sent to the invocation site.
382 * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
384 * IMPORTANT NOTE: This method is written under the assumption that compoundName is longer than length 1.
386 public Binding getBinding(char[][] compoundName, int mask, InvocationSite invocationSite) {
388 Binding binding = getBinding(compoundName[0], mask | TYPE | PACKAGE, invocationSite);
389 invocationSite.setFieldIndex(1);
390 if (binding instanceof VariableBinding) return binding;
391 compilationUnitScope().recordSimpleReference(compoundName[0]);
392 if (!binding.isValidBinding()) return binding;
394 int length = compoundName.length;
395 int currentIndex = 1;
396 foundType : if (binding instanceof PackageBinding) {
397 PackageBinding packageBinding = (PackageBinding) binding;
398 while (currentIndex < length) {
399 compilationUnitScope().recordReference(packageBinding.compoundName, compoundName[currentIndex]);
400 binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]);
401 invocationSite.setFieldIndex(currentIndex);
402 if (binding == null) {
403 if (currentIndex == length)
404 // must be a type if its the last name, otherwise we have no idea if its a package or type
405 return new ProblemReferenceBinding(
406 CharOperation.subarray(compoundName, 0, currentIndex),
409 return new ProblemBinding(
410 CharOperation.subarray(compoundName, 0, currentIndex),
413 if (binding instanceof ReferenceBinding) {
414 if (!binding.isValidBinding())
415 return new ProblemReferenceBinding(
416 CharOperation.subarray(compoundName, 0, currentIndex),
417 binding.problemId());
418 if (!((ReferenceBinding) binding).canBeSeenBy(this))
419 return new ProblemReferenceBinding(
420 CharOperation.subarray(compoundName, 0, currentIndex),
421 (ReferenceBinding)binding,
425 packageBinding = (PackageBinding) binding;
428 // It is illegal to request a PACKAGE from this method.
429 return new ProblemReferenceBinding(
430 CharOperation.subarray(compoundName, 0, currentIndex),
434 // know binding is now a ReferenceBinding
435 while (currentIndex < length) {
436 ReferenceBinding typeBinding = (ReferenceBinding) binding;
437 char[] nextName = compoundName[currentIndex++];
438 invocationSite.setFieldIndex(currentIndex);
439 invocationSite.setActualReceiverType(typeBinding);
440 if ((mask & FIELD) != 0 && (binding = findField(typeBinding, nextName, invocationSite)) != null) {
441 if (!binding.isValidBinding())
442 return new ProblemFieldBinding(
443 ((FieldBinding) binding).declaringClass,
444 CharOperation.subarray(compoundName, 0, currentIndex),
445 binding.problemId());
446 break; // binding is now a field
448 if ((binding = findMemberType(nextName, typeBinding)) == null) {
449 if ((mask & FIELD) != 0) {
450 return new ProblemBinding(
451 CharOperation.subarray(compoundName, 0, currentIndex),
455 return new ProblemReferenceBinding(
456 CharOperation.subarray(compoundName, 0, currentIndex),
461 if (!binding.isValidBinding())
462 return new ProblemReferenceBinding(
463 CharOperation.subarray(compoundName, 0, currentIndex),
464 binding.problemId());
467 if ((mask & FIELD) != 0 && (binding instanceof FieldBinding)) {
468 // was looking for a field and found a field
469 FieldBinding field = (FieldBinding) binding;
470 if (!field.isStatic())
471 return new ProblemFieldBinding(
472 field.declaringClass,
473 CharOperation.subarray(compoundName, 0, currentIndex),
474 NonStaticReferenceInStaticContext);
477 if ((mask & TYPE) != 0 && (binding instanceof ReferenceBinding)) {
478 // was looking for a type and found a type
482 // handle the case when a field or type was asked for but we resolved the compoundName to a type or field
483 return new ProblemBinding(
484 CharOperation.subarray(compoundName, 0, currentIndex),
488 // Added for code assist... NOT Public API
489 public final Binding getBinding(
490 char[][] compoundName,
491 InvocationSite invocationSite) {
492 int currentIndex = 0;
493 int length = compoundName.length;
496 compoundName[currentIndex++],
497 VARIABLE | TYPE | PACKAGE,
499 if (!binding.isValidBinding())
502 foundType : if (binding instanceof PackageBinding) {
503 while (currentIndex < length) {
504 PackageBinding packageBinding = (PackageBinding) binding;
505 binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]);
506 if (binding == null) {
507 if (currentIndex == length)
508 // must be a type if its the last name, otherwise we have no idea if its a package or type
509 return new ProblemReferenceBinding(
510 CharOperation.subarray(compoundName, 0, currentIndex),
513 return new ProblemBinding(
514 CharOperation.subarray(compoundName, 0, currentIndex),
517 if (binding instanceof ReferenceBinding) {
518 if (!binding.isValidBinding())
519 return new ProblemReferenceBinding(
520 CharOperation.subarray(compoundName, 0, currentIndex),
521 binding.problemId());
522 if (!((ReferenceBinding) binding).canBeSeenBy(this))
523 return new ProblemReferenceBinding(
524 CharOperation.subarray(compoundName, 0, currentIndex),
525 (ReferenceBinding)binding,
533 foundField : if (binding instanceof ReferenceBinding) {
534 while (currentIndex < length) {
535 ReferenceBinding typeBinding = (ReferenceBinding) binding;
536 char[] nextName = compoundName[currentIndex++];
537 if ((binding = findField(typeBinding, nextName, invocationSite)) != null) {
538 if (!binding.isValidBinding())
539 return new ProblemFieldBinding(
540 ((FieldBinding) binding).declaringClass,
541 CharOperation.subarray(compoundName, 0, currentIndex),
542 binding.problemId());
543 if (!((FieldBinding) binding).isStatic())
544 return new ProblemFieldBinding(
545 ((FieldBinding) binding).declaringClass,
546 CharOperation.subarray(compoundName, 0, currentIndex),
547 NonStaticReferenceInStaticContext);
548 break foundField; // binding is now a field
550 if ((binding = findMemberType(nextName, typeBinding)) == null)
551 return new ProblemBinding(
552 CharOperation.subarray(compoundName, 0, currentIndex),
555 if (!binding.isValidBinding())
556 return new ProblemReferenceBinding(
557 CharOperation.subarray(compoundName, 0, currentIndex),
558 binding.problemId());
563 VariableBinding variableBinding = (VariableBinding) binding;
564 while (currentIndex < length) {
565 TypeBinding typeBinding = variableBinding.type;
566 if (typeBinding == null)
567 return new ProblemFieldBinding(
569 CharOperation.subarray(compoundName, 0, currentIndex + 1),
572 findField(typeBinding, compoundName[currentIndex++], invocationSite);
573 if (variableBinding == null)
574 return new ProblemFieldBinding(
576 CharOperation.subarray(compoundName, 0, currentIndex),
578 if (!variableBinding.isValidBinding())
579 return variableBinding;
581 return variableBinding;
586 * Answer the binding that corresponds to the argument name.
587 * flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE, PACKAGE.
588 * Only bindings corresponding to the mask can be answered.
590 * For example, getBinding("foo", VARIABLE, site) will answer
591 * the binding for the field or local named "foo" (or an error binding if none exists).
592 * If a type named "foo" exists, it will not be detected (and an error binding will be answered)
594 * The VARIABLE mask has precedence over the TYPE mask.
596 * If the VARIABLE mask is not set, neither fields nor locals will be looked for.
598 * InvocationSite implements:
599 * isSuperAccess(); this is used to determine if the discovered field is visible.
601 * Limitations: cannot request FIELD independently of LOCAL, or vice versa
603 public Binding getBinding(char[] name, int mask, InvocationSite invocationSite) {
605 Binding binding = null;
606 FieldBinding problemField = null;
607 if ((mask & VARIABLE) != 0) {
608 if (this.kind == BLOCK_SCOPE || this.kind == METHOD_SCOPE) {
609 LocalVariableBinding variableBinding = findVariable(name);
610 // looks in this scope only
611 if (variableBinding != null) return variableBinding;
614 boolean insideStaticContext = false;
615 boolean insideConstructorCall = false;
616 if (this.kind == METHOD_SCOPE) {
617 MethodScope methodScope = (MethodScope) this;
618 insideStaticContext |= methodScope.isStatic;
619 insideConstructorCall |= methodScope.isConstructorCall;
622 FieldBinding foundField = null;
623 // can be a problem field which is answered if a valid field is not found
624 ProblemFieldBinding foundInsideProblem = null;
625 // inside Constructor call or inside static context
626 Scope scope = parent;
629 ReferenceBinding foundActualReceiverType = null;
630 done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
631 switch (scope.kind) {
633 MethodScope methodScope = (MethodScope) scope;
634 insideStaticContext |= methodScope.isStatic;
635 insideConstructorCall |= methodScope.isConstructorCall;
636 // Fall through... could duplicate the code below to save a cast - questionable optimization
638 LocalVariableBinding variableBinding = ((BlockScope) scope).findVariable(name);
639 // looks in this scope only
640 if (variableBinding != null) {
641 if (foundField != null && foundField.isValidBinding())
642 return new ProblemFieldBinding(
643 foundField.declaringClass,
645 InheritedNameHidesEnclosingName);
647 invocationSite.setDepth(depth);
648 return variableBinding;
652 ClassScope classScope = (ClassScope) scope;
653 SourceTypeBinding enclosingType = classScope.referenceContext.binding;
654 FieldBinding fieldBinding =
655 classScope.findField(enclosingType, name, invocationSite);
656 // Use next line instead if willing to enable protected access accross inner types
657 // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);
658 if (fieldBinding != null) { // skip it if we did not find anything
659 if (fieldBinding.problemId() == Ambiguous) {
660 if (foundField == null || foundField.problemId() == NotVisible)
661 // supercedes any potential InheritedNameHidesEnclosingName problem
664 // make the user qualify the field, likely wants the first inherited field (javac generates an ambiguous error instead)
665 return new ProblemFieldBinding(
666 fieldBinding.declaringClass,
668 InheritedNameHidesEnclosingName);
671 ProblemFieldBinding insideProblem = null;
672 if (fieldBinding.isValidBinding()) {
673 if (!fieldBinding.isStatic()) {
674 if (insideConstructorCall) {
676 new ProblemFieldBinding(
677 fieldBinding.declaringClass,
679 NonStaticReferenceInConstructorInvocation);
680 } else if (insideStaticContext) {
682 new ProblemFieldBinding(
683 fieldBinding.declaringClass,
685 NonStaticReferenceInStaticContext);
688 // if (enclosingType == fieldBinding.declaringClass
689 // || environment().options.complianceLevel >= CompilerOptions.JDK1_4){
690 // // found a valid field in the 'immediate' scope (ie. not inherited)
691 // // OR in 1.4 mode (inherited shadows enclosing)
692 // if (foundField == null) {
694 // invocationSite.setDepth(depth);
695 // invocationSite.setActualReceiverType(enclosingType);
697 // // return the fieldBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
698 // return insideProblem == null ? fieldBinding : insideProblem;
700 // if (foundField.isValidBinding())
701 // // if a valid field was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
702 // if (foundField.declaringClass != fieldBinding.declaringClass)
703 // // ie. have we found the same field - do not trust field identity yet
704 // return new ProblemFieldBinding(
705 // fieldBinding.declaringClass,
707 // InheritedNameHidesEnclosingName);
711 if (foundField == null
712 || (foundField.problemId() == NotVisible
713 && fieldBinding.problemId() != NotVisible)) {
714 // only remember the fieldBinding if its the first one found or the previous one was not visible & fieldBinding is...
716 foundActualReceiverType = enclosingType;
717 foundInsideProblem = insideProblem;
718 foundField = fieldBinding;
722 insideStaticContext |= enclosingType.isStatic();
723 // 1EX5I8Z - accessing outer fields within a constructor call is permitted
724 // in order to do so, we change the flag as we exit from the type, not the method
725 // itself, because the class scope is used to retrieve the fields.
726 MethodScope enclosingMethodScope = scope.methodScope();
727 insideConstructorCall =
728 enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
730 case COMPILATION_UNIT_SCOPE :
733 scope = scope.parent;
736 if (foundInsideProblem != null){
737 return foundInsideProblem;
739 if (foundField != null) {
740 if (foundField.isValidBinding()){
742 invocationSite.setDepth(foundDepth);
743 invocationSite.setActualReceiverType(foundActualReceiverType);
747 problemField = foundField;
751 // We did not find a local or instance variable.
752 if ((mask & TYPE) != 0) {
753 if ((binding = getBaseType(name)) != null)
755 binding = getTypeOrPackage(name, (mask & PACKAGE) == 0 ? TYPE : TYPE | PACKAGE);
756 if (binding.isValidBinding() || mask == TYPE)
758 // answer the problem type binding if we are only looking for a type
759 } else if ((mask & PACKAGE) != 0) {
760 compilationUnitScope().recordSimpleReference(name);
761 if ((binding = environment().getTopLevelPackage(name)) != null)
764 if (problemField != null)
767 return new ProblemBinding(name, enclosingSourceType(), NotFound);
772 * Answer the constructor binding that corresponds to receiverType, argumentTypes.
774 * InvocationSite implements
775 * isSuperAccess(); this is used to determine if the discovered constructor is visible.
777 * If no visible constructor is discovered, an error binding is answered.
779 public MethodBinding getConstructor(
780 ReferenceBinding receiverType,
781 TypeBinding[] argumentTypes,
782 InvocationSite invocationSite) {
784 compilationUnitScope().recordTypeReference(receiverType);
785 compilationUnitScope().recordTypeReferences(argumentTypes);
786 MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
787 if (methodBinding != null) {
788 if (methodBinding.canBeSeenBy(invocationSite, this))
789 return methodBinding;
791 MethodBinding[] methods =
792 receiverType.getMethods(ConstructorDeclaration.ConstantPoolName);
793 if (methods == NoMethods) {
794 return new ProblemMethodBinding(
795 ConstructorDeclaration.ConstantPoolName,
799 MethodBinding[] compatible = new MethodBinding[methods.length];
800 int compatibleIndex = 0;
801 for (int i = 0, length = methods.length; i < length; i++)
802 if (areParametersAssignable(methods[i].parameters, argumentTypes))
803 compatible[compatibleIndex++] = methods[i];
804 if (compatibleIndex == 0)
805 return new ProblemMethodBinding(
806 ConstructorDeclaration.ConstantPoolName,
809 // need a more descriptive error... cannot convert from X to Y
811 MethodBinding[] visible = new MethodBinding[compatibleIndex];
812 int visibleIndex = 0;
813 for (int i = 0; i < compatibleIndex; i++) {
814 MethodBinding method = compatible[i];
815 if (method.canBeSeenBy(invocationSite, this))
816 visible[visibleIndex++] = method;
818 if (visibleIndex == 1)
820 if (visibleIndex == 0)
821 return new ProblemMethodBinding(
823 ConstructorDeclaration.ConstantPoolName,
824 compatible[0].parameters,
826 return mostSpecificClassMethodBinding(visible, visibleIndex);
830 * This retrieves the argument that maps to an enclosing instance of the suitable type,
831 * if not found then answers nil -- do not create one
833 * #implicitThis : the implicit this will be ok
834 * #((arg) this$n) : available as a constructor arg
835 * #((arg) this$n ... this$p) : available as as a constructor arg + a sequence of fields
836 * #((fieldDescr) this$n ... this$p) : available as a sequence of fields
839 * Note that this algorithm should answer the shortest possible sequence when
840 * shortcuts are available:
841 * this$0 . this$0 . this$0
843 * this$2 . this$1 . this$0 . this$1 . this$0
844 * thus the code generation will be more compact and runtime faster
846 public VariableBinding[] getEmulationPath(LocalVariableBinding outerLocalVariable) {
848 MethodScope currentMethodScope = this.methodScope();
849 SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType();
852 if (currentMethodScope == outerLocalVariable.declaringScope.methodScope()) {
853 return new VariableBinding[] { outerLocalVariable };
854 // implicit this is good enough
856 // use synthetic constructor arguments if possible
857 if (currentMethodScope.isInsideInitializerOrConstructor()
858 && (sourceType.isNestedType())) {
859 SyntheticArgumentBinding syntheticArg;
860 if ((syntheticArg = ((NestedTypeBinding) sourceType).getSyntheticArgument(outerLocalVariable)) != null) {
861 return new VariableBinding[] { syntheticArg };
864 // use a synthetic field then
865 if (!currentMethodScope.isStatic) {
866 FieldBinding syntheticField;
867 if ((syntheticField = sourceType.getSyntheticField(outerLocalVariable)) != null) {
868 return new VariableBinding[] { syntheticField };
875 * This retrieves the argument that maps to an enclosing instance of the suitable type,
876 * if not found then answers nil -- do not create one
878 * #implicitThis : the implicit this will be ok
879 * #((arg) this$n) : available as a constructor arg
880 * #((arg) this$n access$m... access$p) : available as as a constructor arg + a sequence of synthetic accessors to synthetic fields
881 * #((fieldDescr) this$n access#m... access$p) : available as a first synthetic field + a sequence of synthetic accessors to synthetic fields
885 public Object[] getEmulationPath(
886 ReferenceBinding targetEnclosingType,
887 boolean onlyExactMatch,
888 boolean ignoreEnclosingArgInConstructorCall) {
889 //TODO: (philippe) investigate why exactly test76 fails if ignoreEnclosingArgInConstructorCall is always false
890 MethodScope currentMethodScope = this.methodScope();
891 SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType();
894 if (!currentMethodScope.isStatic
895 && (!currentMethodScope.isConstructorCall || ignoreEnclosingArgInConstructorCall)
896 && (sourceType == targetEnclosingType
897 || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(sourceType)))) {
898 if (currentMethodScope.isConstructorCall) {
899 return NoEnclosingInstanceInConstructorCall;
901 if (currentMethodScope.isStatic){
902 return NoEnclosingInstanceInStaticContext;
904 return EmulationPathToImplicitThis; // implicit this is good enough
906 if (!sourceType.isNestedType() || sourceType.isStatic()) { // no emulation from within non-inner types
907 if (currentMethodScope.isConstructorCall) {
908 return NoEnclosingInstanceInConstructorCall;
910 if (currentMethodScope.isStatic){
911 return NoEnclosingInstanceInStaticContext;
915 boolean insideConstructor = currentMethodScope.isInsideInitializerOrConstructor();
916 // use synthetic constructor arguments if possible
917 if (insideConstructor) {
918 SyntheticArgumentBinding syntheticArg;
919 if ((syntheticArg = ((NestedTypeBinding) sourceType).getSyntheticArgument(targetEnclosingType, onlyExactMatch)) != null) {
920 return new Object[] { syntheticArg };
924 // use a direct synthetic field then
925 if (currentMethodScope.isStatic) {
926 return NoEnclosingInstanceInStaticContext;
928 FieldBinding syntheticField = sourceType.getSyntheticField(targetEnclosingType, onlyExactMatch);
929 if (syntheticField != null) {
930 if (currentMethodScope.isConstructorCall){
931 return NoEnclosingInstanceInConstructorCall;
933 return new Object[] { syntheticField };
935 // could be reached through a sequence of enclosing instance link (nested members)
936 Object[] path = new Object[2]; // probably at least 2 of them
937 ReferenceBinding currentType = sourceType.enclosingType();
938 if (insideConstructor) {
939 path[0] = ((NestedTypeBinding) sourceType).getSyntheticArgument((SourceTypeBinding) currentType, onlyExactMatch);
941 if (currentMethodScope.isConstructorCall){
942 return NoEnclosingInstanceInConstructorCall;
944 path[0] = sourceType.getSyntheticField((SourceTypeBinding) currentType, onlyExactMatch);
946 if (path[0] != null) { // keep accumulating
949 ReferenceBinding currentEnclosingType;
950 while ((currentEnclosingType = currentType.enclosingType()) != null) {
953 if (currentType == targetEnclosingType
954 || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(currentType))) break;
956 if (currentMethodScope != null) {
957 currentMethodScope = currentMethodScope.enclosingMethodScope();
958 if (currentMethodScope != null && currentMethodScope.isConstructorCall){
959 return NoEnclosingInstanceInConstructorCall;
961 if (currentMethodScope != null && currentMethodScope.isStatic){
962 return NoEnclosingInstanceInStaticContext;
966 syntheticField = ((NestedTypeBinding) currentType).getSyntheticField((SourceTypeBinding) currentEnclosingType, onlyExactMatch);
967 if (syntheticField == null) break;
969 // append inside the path
970 if (count == path.length) {
971 System.arraycopy(path, 0, (path = new Object[count + 1]), 0, count);
973 // private access emulation is necessary since synthetic field is private
974 path[count++] = ((SourceTypeBinding) syntheticField.declaringClass).addSyntheticMethod(syntheticField, true);
975 currentType = currentEnclosingType;
977 if (currentType == targetEnclosingType
978 || (!onlyExactMatch && targetEnclosingType.isSuperclassOf(currentType))) {
987 * Answer the field binding that corresponds to fieldName.
988 * Start the lookup at the receiverType.
989 * InvocationSite implements
990 * isSuperAccess(); this is used to determine if the discovered field is visible.
991 * Only fields defined by the receiverType or its supertypes are answered;
992 * a field of an enclosing type will not be found using this API.
994 * If no visible field is discovered, an error binding is answered.
996 public FieldBinding getField(
997 TypeBinding receiverType,
999 InvocationSite invocationSite) {
1001 FieldBinding field = findField(receiverType, fieldName, invocationSite);
1003 return new ProblemFieldBinding(
1004 receiverType instanceof ReferenceBinding
1005 ? (ReferenceBinding) receiverType
1015 * Answer the method binding that corresponds to selector, argumentTypes.
1016 * Start the lookup at the enclosing type of the receiver.
1017 * InvocationSite implements
1018 * isSuperAccess(); this is used to determine if the discovered method is visible.
1019 * setDepth(int); this is used to record the depth of the discovered method
1020 * relative to the enclosing type of the receiver. (If the method is defined
1021 * in the enclosing type of the receiver, the depth is 0; in the next enclosing
1022 * type, the depth is 1; and so on
1024 * If no visible method is discovered, an error binding is answered.
1026 public MethodBinding getImplicitMethod(
1028 TypeBinding[] argumentTypes,
1029 InvocationSite invocationSite) {
1031 boolean insideStaticContext = false;
1032 boolean insideConstructorCall = false;
1033 MethodBinding foundMethod = null;
1034 ProblemMethodBinding foundFuzzyProblem = null;
1035 // the weird method lookup case (matches method name in scope, then arg types, then visibility)
1036 ProblemMethodBinding foundInsideProblem = null;
1037 // inside Constructor call or inside static context
1040 done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found
1041 switch (scope.kind) {
1043 MethodScope methodScope = (MethodScope) scope;
1044 insideStaticContext |= methodScope.isStatic;
1045 insideConstructorCall |= methodScope.isConstructorCall;
1048 ClassScope classScope = (ClassScope) scope;
1049 SourceTypeBinding receiverType = classScope.referenceContext.binding;
1050 boolean isExactMatch = true;
1051 // retrieve an exact visible match (if possible)
1052 MethodBinding methodBinding =
1053 (foundMethod == null)
1054 ? classScope.findExactMethod(
1059 : classScope.findExactMethod(
1061 foundMethod.selector,
1062 foundMethod.parameters,
1064 // ? findExactMethod(receiverType, selector, argumentTypes, invocationSite)
1065 // : findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite);
1066 if (methodBinding == null) {
1067 // answers closest approximation, may not check argumentTypes or visibility
1068 isExactMatch = false;
1070 classScope.findMethod(receiverType, selector, argumentTypes, invocationSite);
1071 // methodBinding = findMethod(receiverType, selector, argumentTypes, invocationSite);
1073 if (methodBinding != null) { // skip it if we did not find anything
1074 if (methodBinding.problemId() == Ambiguous) {
1075 if (foundMethod == null || foundMethod.problemId() == NotVisible)
1076 // supercedes any potential InheritedNameHidesEnclosingName problem
1077 return methodBinding;
1079 // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
1080 return new ProblemMethodBinding(
1083 InheritedNameHidesEnclosingName);
1086 ProblemMethodBinding fuzzyProblem = null;
1087 ProblemMethodBinding insideProblem = null;
1088 if (methodBinding.isValidBinding()) {
1089 if (!isExactMatch) {
1090 if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) {
1091 if (foundMethod == null || foundMethod.problemId() == NotVisible){
1092 // inherited mismatch is reported directly, not looking at enclosing matches
1093 return new ProblemMethodBinding(methodBinding, selector, argumentTypes, NotFound);
1095 // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
1096 fuzzyProblem = new ProblemMethodBinding(selector, methodBinding.parameters, InheritedNameHidesEnclosingName);
1098 } else if (!methodBinding.canBeSeenBy(receiverType, invocationSite, classScope)) {
1099 // using <classScope> instead of <this> for visibility check does grant all access to innerclass
1101 new ProblemMethodBinding(
1104 methodBinding.parameters,
1108 if (fuzzyProblem == null && !methodBinding.isStatic()) {
1109 if (insideConstructorCall) {
1111 new ProblemMethodBinding(
1112 methodBinding.selector,
1113 methodBinding.parameters,
1114 NonStaticReferenceInConstructorInvocation);
1115 } else if (insideStaticContext) {
1117 new ProblemMethodBinding(
1118 methodBinding.selector,
1119 methodBinding.parameters,
1120 NonStaticReferenceInStaticContext);
1124 // if (receiverType == methodBinding.declaringClass
1125 // || (receiverType.getMethods(selector)) != NoMethods
1126 // || ((fuzzyProblem == null || fuzzyProblem.problemId() != NotVisible) && environment().options.complianceLevel >= CompilerOptions.JDK1_4)){
1127 // // found a valid method in the 'immediate' scope (ie. not inherited)
1128 // // OR the receiverType implemented a method with the correct name
1129 // // OR in 1.4 mode (inherited visible shadows enclosing)
1130 // if (foundMethod == null) {
1132 // invocationSite.setDepth(depth);
1133 // invocationSite.setActualReceiverType(receiverType);
1135 // // return the methodBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
1136 // if (fuzzyProblem != null)
1137 // return fuzzyProblem;
1138 // if (insideProblem != null)
1139 // return insideProblem;
1140 // return methodBinding;
1142 // // if a method was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
1143 // // NOTE: Unlike fields, a non visible method hides a visible method
1144 // if (foundMethod.declaringClass != methodBinding.declaringClass)
1145 // // ie. have we found the same method - do not trust field identity yet
1146 // return new ProblemMethodBinding(
1147 // methodBinding.selector,
1148 // methodBinding.parameters,
1149 // InheritedNameHidesEnclosingName);
1153 if (foundMethod == null
1154 || (foundMethod.problemId() == NotVisible
1155 && methodBinding.problemId() != NotVisible)) {
1156 // only remember the methodBinding if its the first one found or the previous one was not visible & methodBinding is...
1157 // remember that private methods are visible if defined directly by an enclosing class
1159 invocationSite.setDepth(depth);
1160 invocationSite.setActualReceiverType(receiverType);
1162 foundFuzzyProblem = fuzzyProblem;
1163 foundInsideProblem = insideProblem;
1164 if (fuzzyProblem == null)
1165 foundMethod = methodBinding; // only keep it if no error was found
1169 insideStaticContext |= receiverType.isStatic();
1170 // 1EX5I8Z - accessing outer fields within a constructor call is permitted
1171 // in order to do so, we change the flag as we exit from the type, not the method
1172 // itself, because the class scope is used to retrieve the fields.
1173 MethodScope enclosingMethodScope = scope.methodScope();
1174 insideConstructorCall =
1175 enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
1177 case COMPILATION_UNIT_SCOPE :
1180 scope = scope.parent;
1183 if (foundFuzzyProblem != null)
1184 return foundFuzzyProblem;
1185 if (foundInsideProblem != null)
1186 return foundInsideProblem;
1187 if (foundMethod != null)
1189 return new ProblemMethodBinding(selector, argumentTypes, NotFound);
1194 * Answer the method binding that corresponds to selector, argumentTypes.
1195 * Start the lookup at the receiverType.
1196 * InvocationSite implements
1197 * isSuperAccess(); this is used to determine if the discovered method is visible.
1199 * Only methods defined by the receiverType or its supertypes are answered;
1200 * use getImplicitMethod() to discover methods of enclosing types.
1202 * If no visible method is discovered, an error binding is answered.
1204 public MethodBinding getMethod(
1205 TypeBinding receiverType,
1207 TypeBinding[] argumentTypes,
1208 InvocationSite invocationSite) {
1210 if (receiverType.isArrayType())
1211 return findMethodForArray(
1212 (ArrayBinding) receiverType,
1216 if (receiverType.isBaseType())
1217 return new ProblemMethodBinding(selector, argumentTypes, NotFound);
1219 ReferenceBinding currentType = (ReferenceBinding) receiverType;
1220 if (!currentType.canBeSeenBy(this))
1221 return new ProblemMethodBinding(selector, argumentTypes, ReceiverTypeNotVisible);
1223 // retrieve an exact visible match (if possible)
1224 MethodBinding methodBinding =
1225 findExactMethod(currentType, selector, argumentTypes, invocationSite);
1226 if (methodBinding != null)
1227 return methodBinding;
1229 // answers closest approximation, may not check argumentTypes or visibility
1231 findMethod(currentType, selector, argumentTypes, invocationSite);
1232 if (methodBinding == null)
1233 return new ProblemMethodBinding(selector, argumentTypes, NotFound);
1234 if (methodBinding.isValidBinding()) {
1235 if (!areParametersAssignable(methodBinding.parameters, argumentTypes))
1236 return new ProblemMethodBinding(
1241 if (!methodBinding.canBeSeenBy(currentType, invocationSite, this))
1242 return new ProblemMethodBinding(
1245 methodBinding.parameters,
1248 return methodBinding;
1251 public int maxShiftedOffset() {
1253 if (this.shiftScopes != null){
1254 for (int i = 0, length = this.shiftScopes.length; i < length; i++){
1255 int subMaxOffset = this.shiftScopes[i].maxOffset;
1256 if (subMaxOffset > max) max = subMaxOffset;
1262 /* Answer the problem reporter to use for raising new problems.
1264 * Note that as a side-effect, this updates the current reference context
1265 * (unit, type or method) in case the problem handler decides it is necessary
1268 public ProblemReporter problemReporter() {
1270 return outerMostMethodScope().problemReporter();
1274 * Code responsible to request some more emulation work inside the invocation type, so as to supply
1275 * correct synthetic arguments to any allocation of the target type.
1277 public void propagateInnerEmulation(ReferenceBinding targetType, boolean isEnclosingInstanceSupplied) {
1279 // no need to propagate enclosing instances, they got eagerly allocated already.
1281 SyntheticArgumentBinding[] syntheticArguments;
1282 if ((syntheticArguments = targetType.syntheticOuterLocalVariables()) != null) {
1283 for (int i = 0, max = syntheticArguments.length; i < max; i++) {
1284 SyntheticArgumentBinding syntheticArg = syntheticArguments[i];
1285 // need to filter out the one that could match a supplied enclosing instance
1286 if (!(isEnclosingInstanceSupplied
1287 && (syntheticArg.type == targetType.enclosingType()))) {
1288 this.emulateOuterAccess(syntheticArg.actualOuterLocalVariable);
1294 /* Answer the reference type of this scope.
1296 * It is the nearest enclosing type of this scope.
1298 public TypeDeclaration referenceType() {
1300 return methodScope().referenceType();
1303 // start position in this scope - for ordering scopes vs. variables
1308 public String toString() {
1312 public String toString(int tab) {
1314 String s = basicToString(tab);
1315 for (int i = 0; i < scopeIndex; i++)
1316 if (subscopes[i] instanceof BlockScope)
1317 s += ((BlockScope) subscopes[i]).toString(tab + 1) + "\n"; //$NON-NLS-1$