org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Extractor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
    Annotation[] annotations = memberTypeDeclaration.annotations;
    if (hasRelevantAnnotations(annotations)) {
        SourceTypeBinding binding = memberTypeDeclaration.binding;
        if (!(binding instanceof MemberTypeBinding)) {
            return true;
        }
        if (binding.isAnnotationType() || binding.isAnonymousType()) {
            return false;
        }

        String fqn = new String(memberTypeDeclaration.binding.readableName());
        Item item = ClassItem.create(fqn, ClassKind.forType(memberTypeDeclaration));
        addItem(fqn, item);
        addAnnotations(annotations, item);
    }
    return true;
}
 
Example #2
Source File: Extractor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
    Annotation[] annotations = typeDeclaration.annotations;
    if (hasRelevantAnnotations(annotations)) {
        SourceTypeBinding binding = typeDeclaration.binding;
        if (binding == null) {
            return true;
        }
        String fqn = new String(typeDeclaration.binding.readableName());
        Item item = ClassItem.create(fqn, ClassKind.forType(typeDeclaration));
        addItem(fqn, item);
        addAnnotations(annotations, item);

    }
    return true;
}
 
Example #3
Source File: Extractor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) {
    Annotation[] annotations = localTypeDeclaration.annotations;
    if (hasRelevantAnnotations(annotations)) {
        SourceTypeBinding binding = localTypeDeclaration.binding;
        if (binding == null) {
            return true;
        }

        String fqn = getFqn(scope);
        if (fqn == null) {
            fqn = new String(localTypeDeclaration.binding.readableName());
        }
        Item item = ClassItem.create(fqn, ClassKind.forType(localTypeDeclaration));
        addItem(fqn, item);
        addAnnotations(annotations, item);

    }
    return true;
}
 
Example #4
Source File: SourceExtraction.java    From immutables with Apache License 2.0 6 votes vote down vote up
private static CharSequence readSourceDeclaration(SourceTypeBinding binding) {
  TypeDeclaration referenceContext = binding.scope.referenceContext;
  char[] content = referenceContext.compilationResult.compilationUnit.getContents();
  int start = referenceContext.declarationSourceStart;
  int end = referenceContext.declarationSourceEnd;

  StringBuilder declaration = new StringBuilder();
  for (int p = start; p <= end; p++) {
    char c = content[p];
    if (c == '{') {
      break;
    }
    declaration.append(c);
  }
  return declaration;
}
 
Example #5
Source File: SourceExtraction.java    From immutables with Apache License 2.0 6 votes vote down vote up
private static CharSequence extractSuperclass(SourceTypeBinding binding) {
  CharSequence declaration = readSourceDeclaration(binding);
  StringTokenizer tokenizer = new StringTokenizer(declaration.toString(), "<>, \t\n\r", true);
  int genericsOpened = 0;
  while (tokenizer.hasMoreTokens()) {
    String t = tokenizer.nextToken();
    if (t.equals("<")) {
      genericsOpened++;
      continue;
    }
    if (t.equals(">")) {
      genericsOpened--;
      continue;
    }
    if (genericsOpened > 0) {
      continue;
    }
    if (t.equals("extends")) {
      return readSourceSuperclass(tokenizer);
    }
  }
  return UNABLE_TO_EXTRACT;
}
 
Example #6
Source File: SourceOrdering.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Override
public Ordering<Element> enclosedBy(Element element) {
  if (element instanceof ElementImpl
      && Iterables.all(element.getEnclosedElements(), Predicates.instanceOf(ElementImpl.class))) {

    ElementImpl implementation = (ElementImpl) element;
    if (implementation._binding instanceof SourceTypeBinding) {
      SourceTypeBinding sourceBinding = (SourceTypeBinding) implementation._binding;

      return Ordering.natural().onResultOf(
          Functions.compose(bindingsToSourceOrder(sourceBinding), this));
    }
  }

  return DEFAULT_PROVIDER.enclosedBy(element);
}
 
Example #7
Source File: ClassFilePool.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public synchronized ClassFile acquire(SourceTypeBinding typeBinding) {
	for (int i = 0; i < POOL_SIZE; i++) {
		ClassFile classFile = this.classFiles[i];
		if (classFile == null) {
			ClassFile newClassFile = new ClassFile(typeBinding);
			this.classFiles[i] = newClassFile;
			newClassFile.isShared = true;
			return newClassFile;
		}
		if (!classFile.isShared) {
			classFile.reset(typeBinding);
			classFile.isShared = true;
			return classFile;
		}
	}
	return new ClassFile(typeBinding);
}
 
Example #8
Source File: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void acceptLocalType(TypeBinding typeBinding) {
	IJavaElement res =  null;
	if(typeBinding instanceof ParameterizedTypeBinding) {
		LocalTypeBinding localTypeBinding = (LocalTypeBinding)((ParameterizedTypeBinding)typeBinding).genericType();
		res = findLocalElement(localTypeBinding.sourceStart());
	} else if(typeBinding instanceof SourceTypeBinding) {
		res = findLocalElement(((SourceTypeBinding)typeBinding).sourceStart());
	}
	if(res != null && res.getElementType() == IJavaElement.TYPE) {
		res = ((JavaElement)res).resolved(typeBinding);
		addElement(res);
		if(SelectionEngine.DEBUG){
			System.out.print("SELECTION - accept type("); //$NON-NLS-1$
			System.out.print(res.toString());
			System.out.println(")"); //$NON-NLS-1$
		}
	}
}
 
Example #9
Source File: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void acceptLocalTypeParameter(TypeVariableBinding typeVariableBinding) {
	IJavaElement res;
	if(typeVariableBinding.declaringElement instanceof ParameterizedTypeBinding) {
		LocalTypeBinding localTypeBinding = (LocalTypeBinding)((ParameterizedTypeBinding)typeVariableBinding.declaringElement).genericType();
		res = findLocalElement(localTypeBinding.sourceStart());
	} else {
		SourceTypeBinding typeBinding = (SourceTypeBinding)typeVariableBinding.declaringElement;
		res = findLocalElement(typeBinding.sourceStart());
	}
	if (res != null && res.getElementType() == IJavaElement.TYPE) {
		IType type = (IType) res;
		ITypeParameter typeParameter = type.getTypeParameter(new String(typeVariableBinding.sourceName));
		if (typeParameter.exists()) {
			addElement(typeParameter);
			if(SelectionEngine.DEBUG){
				System.out.print("SELECTION - accept type parameter("); //$NON-NLS-1$
				System.out.print(typeParameter.toString());
				System.out.println(")"); //$NON-NLS-1$
			}
		}
	}
}
 
Example #10
Source File: ExplicitConstructorCall.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) == 0)	{
		// if constructor from parameterized type got found, use the original constructor at codegen time
		MethodBinding codegenBinding = this.binding.original();

		// perform some emulation work in case there is some and we are inside a local type only
		if (this.binding.isPrivate() && this.accessMode != ExplicitConstructorCall.This) {
			ReferenceBinding declaringClass = codegenBinding.declaringClass;
			// from 1.4 on, local type constructor can lose their private flag to ease emulation
			if ((declaringClass.tagBits & TagBits.IsLocalType) != 0 && currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
				// constructor will not be dumped as private, no emulation required thus
				codegenBinding.tagBits |= TagBits.ClearPrivateModifier;
			} else {
				this.syntheticAccessor = ((SourceTypeBinding) declaringClass).addSyntheticMethod(codegenBinding, isSuperAccess());
				currentScope.problemReporter().needToEmulateMethodAccess(codegenBinding, this);
			}
		}
	}
}
 
Example #11
Source File: SingleNameReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo, boolean isReadAccess) {
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)	return;

	//If inlinable field, forget the access emulation, the code gen will directly target it
	if (this.constant != Constant.NotAConstant)
		return;

	if ((this.bits & Binding.FIELD) != 0) {
		FieldBinding fieldBinding = (FieldBinding) this.binding;
		FieldBinding codegenField = fieldBinding.original();
		if (((this.bits & ASTNode.DepthMASK) != 0)
			&& (codegenField.isPrivate() // private access
				|| (codegenField.isProtected() // implicit protected access
						&& codegenField.declaringClass.getPackage() != currentScope.enclosingSourceType().getPackage()))) {
			if (this.syntheticAccessors == null)
				this.syntheticAccessors = new MethodBinding[2];
			this.syntheticAccessors[isReadAccess ? SingleNameReference.READ : SingleNameReference.WRITE] =
			    ((SourceTypeBinding)currentScope.enclosingSourceType().
					enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT)).addSyntheticMethod(codegenField, isReadAccess, false /*not super access*/);
			currentScope.problemReporter().needToEmulateFieldAccess(codegenField, this, isReadAccess);
			return;
		}
	}
}
 
Example #12
Source File: SourceExtraction.java    From immutables with Apache License 2.0 5 votes vote down vote up
public static String getSuperclassString(TypeElement element) {
  if (Compiler.ECJ.isPresent()) {
    if (element instanceof TypeElementImpl) {
      TypeElementImpl elementImpl = ((TypeElementImpl) element);
      if (elementImpl._binding instanceof SourceTypeBinding) {
        return EclipseSourceExtractor.extractSuperclass((SourceTypeBinding) elementImpl._binding).toString();
      }
    }
  }
  return element.getSuperclass().toString();
}
 
Example #13
Source File: SourceExtraction.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence extract(ProcessingEnvironment environment, TypeElement typeElement) throws IOException {
  if (typeElement instanceof ElementImpl) {
    Binding binding = ((ElementImpl) typeElement)._binding;
    if (binding instanceof SourceTypeBinding) {
      CompilationUnitDeclaration unit = ((SourceTypeBinding) binding).scope.referenceCompilationUnit();
      char[] contents = unit.compilationResult.compilationUnit.getContents();
      return CharBuffer.wrap(contents);
    }
  }
  return UNABLE_TO_EXTRACT;
}
 
Example #14
Source File: AnnotationProcessorManager.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Given {@code Element}, returns source file that defines the element. Returns {@code null} if the element is not defined in a source file.
 */
private File getSourceFile(ElementImpl element) {
  TypeElementImpl topLevelType = getTopLevelType(element);
  if (topLevelType == null) {
    // TODO package-info.java annotation?
    return null;
  }
  Binding binding = topLevelType._binding;
  if (binding instanceof SourceTypeBinding) {
    return new File(new String(((SourceTypeBinding) binding).getFileName()));
  }
  return null;
}
 
Example #15
Source File: CompilationResult.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * For now, remember the compiled type using its compound name.
 */
public void record(char[] typeName, ClassFile classFile) {
    SourceTypeBinding sourceType = classFile.referenceBinding;
    if (!sourceType.isLocalType() && sourceType.isHierarchyInconsistent()) {
        this.hasInconsistentToplevelHierarchies = true;
    }
	this.compiledTypes.put(typeName, classFile);
}
 
Example #16
Source File: Clinit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void setAssertionSupport(FieldBinding assertionSyntheticFieldBinding, boolean needClassLiteralField) {

		this.assertionSyntheticFieldBinding = assertionSyntheticFieldBinding;

		// we need to add the field right now, because the field infos are generated before the methods
		if (needClassLiteralField) {
			SourceTypeBinding sourceType =
				this.scope.outerMostClassScope().enclosingSourceType();
			// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=22334
			if (!sourceType.isInterface() && !sourceType.isBaseType()) {
				this.classLiteralSyntheticField = sourceType.addSyntheticFieldForClassLiteral(sourceType, this.scope);
			}
		}
	}
 
Example #17
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
	if (this.shouldCaptureInstance) {
		this.binding.modifiers &= ~ClassFileConstants.AccStatic;
	} else {
		this.binding.modifiers |= ClassFileConstants.AccStatic;
	}
	SourceTypeBinding sourceType = currentScope.enclosingSourceType();
	this.binding = sourceType.addSyntheticMethod(this);
	int pc = codeStream.position;
	StringBuffer signature = new StringBuffer();
	signature.append('(');
	if (this.shouldCaptureInstance) {
		codeStream.aload_0();
		signature.append(sourceType.signature());
	}
	for (int i = 0, length = this.outerLocalVariables == null ? 0 : this.outerLocalVariables.length; i < length; i++) {
		SyntheticArgumentBinding syntheticArgument = this.outerLocalVariables[i];
		if (this.shouldCaptureInstance) {
			syntheticArgument.resolvedPosition++;
		}
		signature.append(syntheticArgument.type.signature());
		LocalVariableBinding capturedOuterLocal = syntheticArgument.actualOuterLocalVariable;
		VariableBinding[] path = currentScope.getEmulationPath(capturedOuterLocal);
		codeStream.generateOuterAccess(path, this, capturedOuterLocal, currentScope);
	}
	signature.append(')');
	if (this.expectedType instanceof IntersectionCastTypeBinding) {
		signature.append(((IntersectionCastTypeBinding)this.expectedType).getSAMType(currentScope).signature());
	} else {
		signature.append(this.expectedType.signature());
	}
	int invokeDynamicNumber = codeStream.classFile.recordBootstrapMethod(this);
	codeStream.invokeDynamic(invokeDynamicNumber, (this.shouldCaptureInstance ? 1 : 0) + this.outerLocalVariablesSlotSize, 1, this.descriptor.selector, signature.toString().toCharArray());
	if (!valueRequired)
		codeStream.pop();
	codeStream.recordPositionsFrom(pc, this.sourceStart);		
}
 
Example #18
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
	SourceTypeBinding binding = typeDeclaration.binding;
	if (binding == null) {
		return false;
	}
	Annotation[] annotations = typeDeclaration.annotations;
	if (annotations != null) {
		this.resolveAnnotations(
				typeDeclaration.staticInitializerScope,
				annotations,
				binding);
	}
	return true;
}
 
Example #19
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
	SourceTypeBinding binding = memberTypeDeclaration.binding;
	if (binding == null) {
		return false;
	}
	Annotation[] annotations = memberTypeDeclaration.annotations;
	if (annotations != null) {
		this.resolveAnnotations(
				memberTypeDeclaration.staticInitializerScope,
				annotations,
				binding);
	}
	return true;
}
 
Example #20
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
	Annotation[] annotations = methodDeclaration.annotations;
	if (annotations != null) {
		MethodBinding methodBinding = methodDeclaration.binding;
		if (methodBinding == null) {
			return false;
		}
		((SourceTypeBinding) methodBinding.declaringClass).resolveTypesFor(methodBinding);
		this.resolveAnnotations(
				methodDeclaration.scope,
				annotations,
				methodBinding);
	}
	
	TypeParameter[] typeParameters = methodDeclaration.typeParameters;
	if (typeParameters != null) {
		int typeParametersLength = typeParameters.length;
		for (int i = 0; i < typeParametersLength; i++) {
			typeParameters[i].traverse(this, methodDeclaration.scope);
		}
	}
	
	Argument[] arguments = methodDeclaration.arguments;
	if (arguments != null) {
		int argumentLength = arguments.length;
		for (int i = 0; i < argumentLength; i++) {
			arguments[i].traverse(this, methodDeclaration.scope);
		}
	}
	return false;
}
 
Example #21
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(TypeParameter typeParameter, BlockScope scope) {
	Annotation[] annotations = typeParameter.annotations;
	if (annotations != null) {
		TypeVariableBinding binding = typeParameter.binding;
		if (binding == null) {
			return false;
		}
		// when we get here, it is guaranteed that class type parameters are connected, but method type parameters may not be.			
		MethodBinding methodBinding = (MethodBinding) binding.declaringElement;
		((SourceTypeBinding) methodBinding.declaringClass).resolveTypesFor(methodBinding);
		this.resolveAnnotations(scope, annotations, binding);
	}
	return false;
}
 
Example #22
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
	Annotation[] annotations = fieldDeclaration.annotations;
	if (annotations != null) {
		FieldBinding fieldBinding = fieldDeclaration.binding;
		if (fieldBinding == null) {
			return false;
		}
		((SourceTypeBinding) fieldBinding.declaringClass).resolveTypeFor(fieldBinding);
		this.resolveAnnotations(scope, annotations, fieldBinding);
	}
	return false;
}
 
Example #23
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
	Annotation[] annotations = constructorDeclaration.annotations;
	if (annotations != null) {
		MethodBinding constructorBinding = constructorDeclaration.binding;
		if (constructorBinding == null) {
			return false;
		}
		((SourceTypeBinding) constructorBinding.declaringClass).resolveTypesFor(constructorBinding);
		this.resolveAnnotations(
				constructorDeclaration.scope,
				annotations,
				constructorBinding);
	}
	
	TypeParameter[] typeParameters = constructorDeclaration.typeParameters;
	if (typeParameters != null) {
		int typeParametersLength = typeParameters.length;
		for (int i = 0; i < typeParametersLength; i++) {
			typeParameters[i].traverse(this, constructorDeclaration.scope);
		}
	}
	
	Argument[] arguments = constructorDeclaration.arguments;
	if (arguments != null) {
		int argumentLength = arguments.length;
		for (int i = 0; i < argumentLength; i++) {
			arguments[i].traverse(this, constructorDeclaration.scope);
		}
	}
	return false;
}
 
Example #24
Source File: ElementsImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isFunctionalInterface(TypeElement type) {
	if (type != null && type.getKind() == ElementKind.INTERFACE) {
		ReferenceBinding binding = (ReferenceBinding)((TypeElementImpl) type)._binding;
		if (binding instanceof SourceTypeBinding) {
			return binding.isFunctionalInterface(((SourceTypeBinding) binding).scope);
		}
	}
	return false;
}
 
Example #25
Source File: SingleNameReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public TypeBinding checkFieldAccess(BlockScope scope) {
	FieldBinding fieldBinding = (FieldBinding) this.binding;
	this.constant = fieldBinding.constant();

	this.bits &= ~ASTNode.RestrictiveFlagMASK; // clear bits
	this.bits |= Binding.FIELD;
	MethodScope methodScope = scope.methodScope();
	if (fieldBinding.isStatic()) {
		// check if accessing enum static field in initializer
		ReferenceBinding declaringClass = fieldBinding.declaringClass;
		if (declaringClass.isEnum()) {
			SourceTypeBinding sourceType = scope.enclosingSourceType();
			if (this.constant == Constant.NotAConstant
					&& !methodScope.isStatic
					&& (TypeBinding.equalsEquals(sourceType, declaringClass) || TypeBinding.equalsEquals(sourceType.superclass, declaringClass)) // enum constant body
					&& methodScope.isInsideInitializerOrConstructor()) {
				scope.problemReporter().enumStaticFieldUsedDuringInitialization(fieldBinding, this);
			}
		}
	} else {
		if (scope.compilerOptions().getSeverity(CompilerOptions.UnqualifiedFieldAccess) != ProblemSeverities.Ignore) {
			scope.problemReporter().unqualifiedFieldAccess(this, fieldBinding);
		}
		// must check for the static status....
		if (methodScope.isStatic) {
			scope.problemReporter().staticFieldAccessToNonStaticVariable(this, fieldBinding);
			return fieldBinding.type;
		} else {
			scope.tagAsAccessingEnclosingInstanceStateOf(fieldBinding.declaringClass, false /* type variable access */);
		}
	}

	if (isFieldUseDeprecated(fieldBinding, scope, this.bits))
		scope.problemReporter().deprecatedField(fieldBinding, this);

	if ((this.bits & ASTNode.IsStrictlyAssigned) == 0
			&& TypeBinding.equalsEquals(methodScope.enclosingSourceType(), fieldBinding.original().declaringClass)
			&& methodScope.lastVisibleFieldID >= 0
			&& fieldBinding.id >= methodScope.lastVisibleFieldID
			&& (!fieldBinding.isStatic() || methodScope.isStatic)) {
		scope.problemReporter().forwardReference(this, 0, fieldBinding);
		this.bits |= ASTNode.IgnoreNoEffectAssignCheck;
	}
	return fieldBinding.type;

}
 
Example #26
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
	this.actualMethodBinding = this.binding; // grab before synthetics come into play.
	// Handle some special cases up front and transform them into implicit lambdas.
	if (shouldGenerateImplicitLambda(currentScope)) {
		generateImplicitLambda(currentScope, codeStream, valueRequired);
		return;
	}
	SourceTypeBinding sourceType = currentScope.enclosingSourceType();
	if (this.receiverType.isArrayType()) {
		if (isConstructorReference()) {
			this.actualMethodBinding = this.binding = sourceType.addSyntheticArrayMethod((ArrayBinding) this.receiverType, SyntheticMethodBinding.ArrayConstructor);
		} else if (CharOperation.equals(this.selector, TypeConstants.CLONE)) {
			this.actualMethodBinding = this.binding = sourceType.addSyntheticArrayMethod((ArrayBinding) this.receiverType, SyntheticMethodBinding.ArrayClone);
		}
	} else if (this.syntheticAccessor != null) {
		if (this.lhs.isSuper() || isMethodReference())
			this.binding = this.syntheticAccessor;
	} else { // cf. MessageSend.generateCode()'s call to CodeStream.getConstantPoolDeclaringClass. We have extracted the relevant portions sans side effect here. 
		if (this.binding != null && isMethodReference()) {
			if (TypeBinding.notEquals(this.binding.declaringClass, this.lhs.resolvedType.erasure())) {
				if (!this.binding.declaringClass.canBeSeenBy(currentScope)) {
					this.binding = new MethodBinding(this.binding, (ReferenceBinding) this.lhs.resolvedType.erasure());
				}
			}
		}
	}
	
	int pc = codeStream.position;
	StringBuffer buffer = new StringBuffer();
	int argumentsSize = 0;
	buffer.append('(');
	if (this.haveReceiver) {
		this.lhs.generateCode(currentScope, codeStream, true);
		if (this.lhs.isSuper() && !this.actualMethodBinding.isPrivate()) {
			if (this.lhs instanceof QualifiedSuperReference) {
				QualifiedSuperReference qualifiedSuperReference = (QualifiedSuperReference) this.lhs;
				TypeReference qualification = qualifiedSuperReference.qualification;
				if (qualification.resolvedType.isInterface()) {
					buffer.append(sourceType.signature());
				} else {
					buffer.append(((QualifiedSuperReference) this.lhs).currentCompatibleType.signature());
				}
			} else { 
				buffer.append(sourceType.signature());
			}
		} else {
			buffer.append(this.receiverType.signature());
		}
		argumentsSize = 1;
	} else {
		if (this.isConstructorReference()) {
			ReferenceBinding[] enclosingInstances = Binding.UNINITIALIZED_REFERENCE_TYPES;
			if (this.receiverType.isNestedType()) {
				ReferenceBinding nestedType = (ReferenceBinding) this.receiverType;
				if ((enclosingInstances = nestedType.syntheticEnclosingInstanceTypes()) != null) {
					int length = enclosingInstances.length;
					argumentsSize = length;
					for (int i = 0 ; i < length; i++) {
						ReferenceBinding syntheticArgumentType = enclosingInstances[i];
						buffer.append(syntheticArgumentType.signature());
						Object[] emulationPath = currentScope.getEmulationPath(
								syntheticArgumentType,
								false /* allow compatible match */,
								true /* disallow instance reference in explicit constructor call */);
						codeStream.generateOuterAccess(emulationPath, this, syntheticArgumentType, currentScope);
					}
				} else {
					enclosingInstances = Binding.NO_REFERENCE_TYPES;
				}
				// Reject types that capture outer local arguments, these cannot be manufactured by the metafactory.
				if (nestedType.syntheticOuterLocalVariables() != null) {
					currentScope.problemReporter().noSuchEnclosingInstance(nestedType.enclosingType(), this, false);
					return;
				}
			}
			if (this.syntheticAccessor != null) {
				this.binding = sourceType.addSyntheticFactoryMethod(this.binding, this.syntheticAccessor, enclosingInstances);
			}
		}
	}
	buffer.append(')');
	buffer.append('L');
	buffer.append(this.resolvedType.constantPoolName());
	buffer.append(';');
	int invokeDynamicNumber = codeStream.classFile.recordBootstrapMethod(this);
	codeStream.invokeDynamic(invokeDynamicNumber, argumentsSize, 1, this.descriptor.selector, buffer.toString().toCharArray(), 
			this.isConstructorReference(), (this.lhs instanceof TypeReference? (TypeReference) this.lhs : null), this.typeArguments);
	if (!valueRequired)
		codeStream.pop();
	codeStream.recordPositionsFrom(pc, this.sourceStart);
}
 
Example #27
Source File: CodeSnippetClassFile.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * INTERNAL USE-ONLY
 * Request the creation of a ClassFile compatible representation of a problematic type
 *
 * @param typeDeclaration org.eclipse.jdt.internal.compiler.ast.TypeDeclaration
 * @param unitResult org.eclipse.jdt.internal.compiler.CompilationUnitResult
 */
public static void createProblemType(TypeDeclaration typeDeclaration, CompilationResult unitResult) {
	SourceTypeBinding typeBinding = typeDeclaration.binding;
	ClassFile classFile = new CodeSnippetClassFile(typeBinding, null, true);

	// inner attributes
	if (typeBinding.hasMemberTypes()) {
		// see bug 180109
		ReferenceBinding[] members = typeBinding.memberTypes;
		for (int i = 0, l = members.length; i < l; i++)
			classFile.recordInnerClasses(members[i]);
	}
	// TODO (olivier) handle cases where a field cannot be generated (name too long)
	// TODO (olivier) handle too many methods
	// inner attributes
	if (typeBinding.isNestedType()) {
		classFile.recordInnerClasses(typeBinding);
	}
	TypeVariableBinding[] typeVariables = typeBinding.typeVariables();
	for (int i = 0, max = typeVariables.length; i < max; i++) {
		TypeVariableBinding typeVariableBinding = typeVariables[i];
		if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
			Util.recordNestedType(classFile, typeVariableBinding);
		}
	}

	// add its fields
	FieldBinding[] fields = typeBinding.fields();
	if ((fields != null) && (fields != Binding.NO_FIELDS)) {
		classFile.addFieldInfos();
	} else {
		// we have to set the number of fields to be equals to 0
		classFile.contents[classFile.contentsOffset++] = 0;
		classFile.contents[classFile.contentsOffset++] = 0;
	}
	// leave some space for the methodCount
	classFile.setForMethodInfos();
	// add its user defined methods
	int problemsLength;
	CategorizedProblem[] problems = unitResult.getErrors();
	if (problems == null) {
		problems = new CategorizedProblem[0];
	}
	CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
	System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
	AbstractMethodDeclaration[] methodDecls = typeDeclaration.methods;
	boolean abstractMethodsOnly = false;
	if (methodDecls != null) {
		if (typeBinding.isInterface()) {
			if (typeBinding.scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_8)
				abstractMethodsOnly = true;
			// We generate a clinit which contains all the problems, since we may not be able to generate problem methods (< 1.8) and problem constructors (all levels).
			classFile.addProblemClinit(problemsCopy);
		}
		for (int i = 0, length = methodDecls.length; i < length; i++) {
			AbstractMethodDeclaration methodDecl = methodDecls[i];
			MethodBinding method = methodDecl.binding;
			if (method == null) continue;
			if (abstractMethodsOnly) {
				method.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccAbstract;
			}
			if (method.isConstructor()) {
				if (typeBinding.isInterface()) continue;
				classFile.addProblemConstructor(methodDecl, method, problemsCopy);
			} else if (method.isAbstract()) {
				classFile.addAbstractMethod(methodDecl, method);
			} else {
				classFile.addProblemMethod(methodDecl, method, problemsCopy);
			}
		}
		// add abstract methods
		classFile.addDefaultAbstractMethods();
	}
	// propagate generation of (problem) member types
	if (typeDeclaration.memberTypes != null) {
		for (int i = 0, max = typeDeclaration.memberTypes.length; i < max; i++) {
			TypeDeclaration memberType = typeDeclaration.memberTypes[i];
			if (memberType.binding != null) {
				ClassFile.createProblemType(memberType, unitResult);
			}
		}
	}
	classFile.addAttributes();
	unitResult.record(typeBinding.constantPoolName(), classFile);
}
 
Example #28
Source File: PatchDelegate.java    From EasyMPermission with MIT License 4 votes vote down vote up
private static void addAllMethodBindings0(List<BindingTuple> list, TypeBinding binding, Set<String> banList, char[] fieldName, ASTNode responsible) throws DelegateRecursion {
	if (binding instanceof SourceTypeBinding) ((SourceTypeBinding) binding).scope.environment().globalOptions.storeAnnotations = true;
	if (binding == null) return;
	
	TypeBinding inner;
	
	if (binding instanceof ParameterizedTypeBinding) {
		inner = ((ParameterizedTypeBinding) binding).genericType();
	} else {
		inner = binding;
	}
	
	if (inner instanceof SourceTypeBinding) {
		ClassScope cs = ((SourceTypeBinding)inner).scope;
		if (cs != null) {
			try {
				Reflection.classScopeBuildFieldsAndMethodsMethod.invoke(cs);
			} catch (Exception e) {
				// See 'Reflection' class for why we ignore this exception.
			}
		}
	}
	
	if (binding instanceof ReferenceBinding) {
		ReferenceBinding rb = (ReferenceBinding) binding;
		MethodBinding[] availableMethods = rb.availableMethods();
		FieldBinding[] availableFields = rb.availableFields();
		failIfContainsAnnotation(binding, availableMethods); 
		failIfContainsAnnotation(binding, availableFields); 
		
		MethodBinding[] parameterizedSigs = availableMethods;
		MethodBinding[] baseSigs = parameterizedSigs;
		if (binding instanceof ParameterizedTypeBinding) {
			baseSigs = ((ParameterizedTypeBinding)binding).genericType().availableMethods();
			if (baseSigs.length != parameterizedSigs.length) {
				// The last known state of eclipse source says this can't happen, so we rely on it,
				// but if this invariant is broken, better to go with 'arg0' naming instead of crashing.
				baseSigs = parameterizedSigs;
			}
		}
		for (int i = 0; i < parameterizedSigs.length; i++) {
			MethodBinding mb = parameterizedSigs[i];
			String sig = printSig(mb);
			if (mb.isStatic()) continue;
			if (mb.isBridge()) continue;
			if (mb.isConstructor()) continue;
			if (mb.isDefaultAbstract()) continue;
			if (!mb.isPublic()) continue;
			if (mb.isSynthetic()) continue;
			if (!banList.add(sig)) continue; // If add returns false, it was already in there.
			BindingTuple pair = new BindingTuple(mb, baseSigs[i], fieldName, responsible);
			list.add(pair);
		}
		addAllMethodBindings0(list, rb.superclass(), banList, fieldName, responsible);
		ReferenceBinding[] interfaces = rb.superInterfaces();
		if (interfaces != null) {
			for (ReferenceBinding iface : interfaces) addAllMethodBindings0(list, iface, banList, fieldName, responsible);
		}
	}
}