Java Code Examples for org.eclipse.jdt.core.dom.Type#resolveBinding()

The following examples show how to use org.eclipse.jdt.core.dom.Type#resolveBinding() . 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: UiBinderJavaValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static ITypeBinding getOwnerTypeBinding(
    TypeDeclaration uiBinderSubtype) {
  List<Type> superInterfaces = uiBinderSubtype.superInterfaceTypes();
  for (Type superInterface : superInterfaces) {
    ITypeBinding binding = superInterface.resolveBinding();
    if (binding != null) {
      if (binding.getErasure().getQualifiedName().equals(
          UiBinderConstants.UI_BINDER_TYPE_NAME)) {
        if (superInterface instanceof ParameterizedType) {
          ParameterizedType uiBinderType = (ParameterizedType) superInterface;
          List<Type> typeArgs = uiBinderType.typeArguments();
          if (typeArgs.size() == 2) {
            Type ownerType = typeArgs.get(1);
            return ownerType.resolveBinding();
          }
        }
      }
    }
  }
  return null;
}
 
Example 2
Source File: ReferenceFinderUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) {
	if (methodDeclaration == null)
		return new HashSet<ITypeBinding>(0);
	Set<ITypeBinding> result= new HashSet<ITypeBinding>();
	ITypeBinding binding= null;
	Type returnType= methodDeclaration.getReturnType2();
	if (returnType != null) {
		binding = returnType.resolveBinding();
		if (binding != null)
			result.add(binding);
	}

	for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
		binding = iter.next().getType().resolveBinding();
		if (binding != null)
			result.add(binding);
	}

	for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) {
		binding= iter.next().resolveBinding();
		if (binding != null)
			result.add(binding);
	}
	return result;
}
 
Example 3
Source File: ReturnTypeSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addMethodRetunsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (!(selectedNode instanceof ReturnStatement)) {
		return;
	}
	ReturnStatement returnStatement= (ReturnStatement) selectedNode;
	Expression expression= returnStatement.getExpression();
	if (expression == null) {
		return;
	}
	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methDecl= (MethodDeclaration) decl;
		Type retType= methDecl.getReturnType2();
		if (retType == null || retType.resolveBinding() == null) {
			return;
		}
		TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals);
	}
}
 
Example 4
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus createExceptionInfoList() {
	if (fExceptionInfos == null || fExceptionInfos.isEmpty()) {
		fExceptionInfos= new ArrayList<ExceptionInfo>(0);
		try {
			ASTNode nameNode= NodeFinder.perform(fBaseCuRewrite.getRoot(), fMethod.getNameRange());
			if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof MethodDeclaration))
				return null;
			MethodDeclaration methodDeclaration= (MethodDeclaration) nameNode.getParent();
			List<Type> exceptions= methodDeclaration.thrownExceptionTypes();
			List<ExceptionInfo> result= new ArrayList<ExceptionInfo>(exceptions.size());
			for (int i= 0; i < exceptions.size(); i++) {
				Type type= exceptions.get(i);
				ITypeBinding typeBinding= type.resolveBinding();
				if (typeBinding == null)
					return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding);
				IJavaElement element= typeBinding.getJavaElement();
				result.add(ExceptionInfo.createInfoForOldException(element, typeBinding));
			}
			fExceptionInfos= result;
		} catch (JavaModelException e) {
			JavaPlugin.log(e);
		}
	}
	return null;
}
 
Example 5
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
	Assert.isNotNull(type);
	Assert.isNotNull(targetRewrite);
	final ITypeBinding binding= type.resolveBinding();
	if (binding != null) {
		final ITypeBinding declaring= binding.getDeclaringClass();
		if (declaring != null) {
			if (type instanceof SimpleType) {
				final SimpleType simpleType= (SimpleType) type;
				addSimpleTypeQualification(targetRewrite, declaring, simpleType, group);
			} else if (type instanceof ParameterizedType) {
				final ParameterizedType parameterizedType= (ParameterizedType) type;
				final Type rawType= parameterizedType.getType();
				if (rawType instanceof SimpleType)
					addSimpleTypeQualification(targetRewrite, declaring, (SimpleType) rawType, group);
			}
		}
	}
}
 
Example 6
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(final ClassInstanceCreation node) {
	Assert.isNotNull(node);
	if (fCreateInstanceField) {
		final AST ast= node.getAST();
		final Type type= node.getType();
		final ITypeBinding binding= type.resolveBinding();
		if (binding != null && binding.getDeclaringClass() != null && !Bindings.equals(binding, fTypeBinding) && fSourceRewrite.getRoot().findDeclaringNode(binding) != null) {
			if (!Modifier.isStatic(binding.getModifiers())) {
				Expression expression= null;
				if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
					final FieldAccess access= ast.newFieldAccess();
					access.setExpression(ast.newThisExpression());
					access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
					expression= access;
				} else
					expression= ast.newSimpleName(fEnclosingInstanceFieldName);
				if (node.getExpression() != null)
					fSourceRewrite.getImportRemover().registerRemovedNode(node.getExpression());
				fSourceRewrite.getASTRewrite().set(node, ClassInstanceCreation.EXPRESSION_PROPERTY, expression, fGroup);
			} else
				addTypeQualification(type, fSourceRewrite, fGroup);
		}
	}
	return true;
}
 
Example 7
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ITypeBinding[] getInferredTypeArguments(Expression invocation) {
	IMethodBinding methodBinding;
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			methodBinding= ((MethodInvocation) invocation).resolveMethodBinding();
			return methodBinding == null ? null : methodBinding.getTypeArguments();
		case ASTNode.SUPER_METHOD_INVOCATION:
			methodBinding= ((SuperMethodInvocation) invocation).resolveMethodBinding();
			return methodBinding == null ? null : methodBinding.getTypeArguments();
		case ASTNode.CLASS_INSTANCE_CREATION:
			Type type= ((ClassInstanceCreation) invocation).getType();
			ITypeBinding typeBinding= type.resolveBinding();
			return typeBinding == null ? null : typeBinding.getTypeArguments();
			
		default:
			throw new IllegalArgumentException(invocation.toString());
	}
}
 
Example 8
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates the normalized form and adds the required imports for a given
 * {@link Type}.
 */
public static Type normalizeTypeAndAddImport(AST ast, Type type,
    ImportRewrite imports) {
  ITypeBinding binding = type.resolveBinding();

  // Eliminate type variables in the generated type
  // TODO(): maybe leave the type variables, if we can verify that the type
  // parameters on the target type are exactly the same as those on the source
  // type (all names and type bounds are identical)
  if (JavaASTUtils.containsTypeVariable(type)) {
    binding = binding.getErasure();
  }

  // Report the type binding to the import rewriter, which will record the
  // import and give us either a SimpleType or a QualifiedType to use.
  return imports.addImport(binding, ast);
}
 
Example 9
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkTempTypeForLocalTypeUsage(){
  	VariableDeclarationStatement vds= getTempDeclarationStatement();
  	if (vds == null)
  		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);
  	Type type= 	vds.getType();
  	ITypeBinding binding= type.resolveBinding();
  	if (binding == null)
  		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_cannot_promote);

IMethodBinding declaringMethodBinding= getMethodDeclaration().resolveBinding();
ITypeBinding[] methodTypeParameters= declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
LocalTypeAndVariableUsageAnalyzer analyzer= new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
type.accept(analyzer);
boolean usesLocalTypes= ! analyzer.getUsageOfEnclosingNodes().isEmpty();
fTempTypeUsesClassTypeVariables= analyzer.getClassTypeVariablesUsed();
if (usesLocalTypes)
	return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_uses_type_declared_locally);
return null;
  }
 
Example 10
Source File: AbstractMethodFragment.java    From JDeodorant with MIT License 5 votes vote down vote up
protected void processArrayCreations(List<Expression> arrayCreations) {
	for(Expression arrayCreationExpression : arrayCreations) {
		ArrayCreation arrayCreation = (ArrayCreation)arrayCreationExpression;
		Type type = arrayCreation.getType();
		ITypeBinding typeBinding = type.resolveBinding();
		String qualifiedTypeName = typeBinding.getQualifiedName();
		TypeObject typeObject = TypeObject.extractTypeObject(qualifiedTypeName);
		ArrayCreationObject creationObject = new ArrayCreationObject(typeObject);
		creationObject.setArrayCreation(arrayCreation);
		addCreation(creationObject);
	}
}
 
Example 11
Source File: AbstractExceptionAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationExpression node) {
	if (node.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
		Type type = node.getType();
		ITypeBinding resourceTypeBinding = type.resolveBinding();
		if (resourceTypeBinding != null) {
			IMethodBinding methodBinding = Bindings.findMethodInHierarchy(resourceTypeBinding, "close", new ITypeBinding[0]); //$NON-NLS-1$
			if (methodBinding != null) {
				addExceptions(methodBinding.getExceptionTypes(), node.getAST());
			}
		}
	}
	return super.visit(node);
}
 
Example 12
Source File: ReferenceFinderUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) {
	if (methodDeclaration == null) {
		return new HashSet<>(0);
	}
	Set<ITypeBinding> result= new HashSet<>();
	ITypeBinding binding= null;
	Type returnType= methodDeclaration.getReturnType2();
	if (returnType != null) {
		binding = returnType.resolveBinding();
		if (binding != null) {
			result.add(binding);
		}
	}

	for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
		binding = iter.next().getType().resolveBinding();
		if (binding != null) {
			result.add(binding);
		}
	}

	for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) {
		binding= iter.next().resolveBinding();
		if (binding != null) {
			result.add(binding);
		}
	}
	return result;
}
 
Example 13
Source File: ClientBundleValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static ITypeBinding getReturnTypeBinding(MethodDeclaration methodDecl) {
  Type returnType = methodDecl.getReturnType2();
  if (returnType != null) {
    return returnType.resolveBinding();
  }
  return null;
}
 
Example 14
Source File: MethodExitsFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void markReferences() {
	fCaughtExceptions= new ArrayList<ITypeBinding>();
	boolean isVoid= true;
	Type returnType= fMethodDeclaration.getReturnType2();
	if (returnType != null) {
		ITypeBinding returnTypeBinding= returnType.resolveBinding();
		isVoid= returnTypeBinding != null && Bindings.isVoidType(returnTypeBinding);
	}
	fMethodDeclaration.accept(this);
	Block block= fMethodDeclaration.getBody();
	if (block != null) {
		List<Statement> statements= block.statements();
		if (statements.size() > 0) {
			Statement last= statements.get(statements.size() - 1);
			int maxVariableId= LocalVariableIndex.perform(fMethodDeclaration);
			FlowContext flowContext= new FlowContext(0, maxVariableId + 1);
			flowContext.setConsiderAccessMode(false);
			flowContext.setComputeMode(FlowContext.ARGUMENTS);
			InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(flowContext);
			FlowInfo info= flowAnalyzer.perform(new ASTNode[] {last});
			if (!info.isNoReturn() && !isVoid) {
				if (!info.isPartialReturn())
					return;
			}
		}
		int offset= fMethodDeclaration.getStartPosition() + fMethodDeclaration.getLength() - 1; // closing bracket
		fResult.add(new OccurrenceLocation(offset, 1, 0, fExitDescription));
	}
}
 
Example 15
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, Type type2) {
	ITypeBinding binding= type2.resolveBinding();
	if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptionTypes())) {
		Type newType= (Type) ASTNode.copySubtree(ast, type2);

		ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY);
		listRewriter.insertLast(newType, null);
	}
}
 
Example 16
Source File: Resolver.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
private void inferTypeInfo(SM_Project parentProject, TypeInfo typeInfo, Type typeOfVar, SM_Type callerType) {
	ITypeBinding iType = typeOfVar.resolveBinding();
	/*
	 * In some cases, the above statement doesnt resolve the binding even if the
	 * type is present in the same project (and we dont know the reason). We need to
	 * handle this situation explicitly by checking the 'binding' property of iType.
	 * if it is of type MissingTypeBinding, we need to search the type in the
	 * present project. We may have to use import statements to identify the package
	 * in which this (to be resolved) type exists.
	 */

	// The case that the iType is RecoveredTypeBinding which leads to
	// ProblemReferenceBinding and consequently to MissingTypeBinding
	if (iType == null) {
		inferPrimitiveType(parentProject, typeInfo, iType);
		infereParametrized(parentProject, typeInfo, iType);
	} else if (iType.isRecovered()) {
		// Search in the ast explicitly and assign
		String unresolvedTypeName = typeOfVar.toString().replace("[]", ""); // cover the Array case
		SM_Type matchedType = manualLookupForUnresolvedType(parentProject, unresolvedTypeName, callerType);
		if (matchedType != null) {
			manualInferUnresolvedTypeType(typeInfo, matchedType);
		}
	} else {
		inferPrimitiveType(parentProject, typeInfo, iType);
		infereParametrized(parentProject, typeInfo, iType);
	}
}
 
Example 17
Source File: MethodExitsFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void addCaughtException(Type type) {
	ITypeBinding typeBinding= type.resolveBinding();
	if (typeBinding != null) {
		fCaughtExceptions.add(typeBinding);
	}
}
 
Example 18
Source File: ExceptionOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void addCaughtException(Type type) {
	ITypeBinding typeBinding= type.resolveBinding();
	if (typeBinding != null) {
		fCaughtExceptions.add(typeBinding);
	}
}
 
Example 19
Source File: InferTypeArgumentsConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
	public void endVisit(CastExpression node) {
//		if (! (expressionCv instanceof CollectionElementVariable2))
//			return; //TODO: returns too early when dealing with nested collections.

		Type type= node.getType();
		ITypeBinding typeBinding= type.resolveBinding();
		if (typeBinding.isPrimitive()) {
			ImmutableTypeVariable2 boxed= fTCModel.makeImmutableTypeVariable(typeBinding, node);
			setConstraintVariable(node, boxed);
			return; // avoid removing numeric conversions
		}

		ConstraintVariable2 typeCv= getConstraintVariable(type);
		if (typeCv == null)
			return;

		//TODO: can this be loosened when we remove casts?
		setConstraintVariable(node, typeCv);

		Expression expression= node.getExpression();
		ConstraintVariable2 expressionCv= getConstraintVariable(expression);

		//Avoid removing casts that have not been made obsolete by this refactoring:
		if (expressionCv == null)
			return;
		if (expressionCv instanceof ImmutableTypeVariable2)
			return;
		if (! (expressionCv instanceof TypeVariable2 || expressionCv instanceof IndependentTypeVariable2 || expressionCv instanceof CollectionElementVariable2)
				&& fTCModel.getElementVariables(expressionCv).size() == 0 && fTCModel.getArrayElementVariable(expressionCv) == null)
			return;

		fTCModel.createAssignmentElementConstraints(typeCv, expressionCv);

		if (expression instanceof MethodInvocation) {
			MethodInvocation invoc= (MethodInvocation) expression;
			if (! isSpecialCloneInvocation(invoc.resolveMethodBinding(), invoc.getExpression())) {
				fTCModel.makeCastVariable(node, expressionCv);
			}
		} else {
			fTCModel.makeCastVariable(node, expressionCv);
		}

		boolean eitherIsIntf= typeBinding.isInterface() || expression.resolveTypeBinding().isInterface();
		if (eitherIsIntf)
			return;

		//TODO: preserve up- and down-castedness!

	}
 
Example 20
Source File: ASTReader.java    From JDeodorant with MIT License 4 votes vote down vote up
private ClassObject processEnumDeclaration(IFile iFile, IDocument document, EnumDeclaration enumDeclaration, List<Comment> comments) {
	final ClassObject classObject = new ClassObject();
	classObject.setEnum(true);
	classObject.setIFile(iFile);
	classObject.addComments(processComments(iFile, document, enumDeclaration, comments));
	classObject.setName(enumDeclaration.resolveBinding().getQualifiedName());
	classObject.setAbstractTypeDeclaration(enumDeclaration);
	
	int modifiers = enumDeclaration.getModifiers();
	if((modifiers & Modifier.ABSTRACT) != 0)
		classObject.setAbstract(true);
	
	if((modifiers & Modifier.PUBLIC) != 0)
		classObject.setAccess(Access.PUBLIC);
	else if((modifiers & Modifier.PROTECTED) != 0)
		classObject.setAccess(Access.PROTECTED);
	else if((modifiers & Modifier.PRIVATE) != 0)
		classObject.setAccess(Access.PRIVATE);
	else
		classObject.setAccess(Access.NONE);
	
	if((modifiers & Modifier.STATIC) != 0)
		classObject.setStatic(true);
	
	List<Type> superInterfaceTypes = enumDeclaration.superInterfaceTypes();
	for(Type interfaceType : superInterfaceTypes) {
		ITypeBinding binding = interfaceType.resolveBinding();
		String qualifiedName = binding.getQualifiedName();
		TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
		classObject.addInterface(typeObject);
	}
	
	List<EnumConstantDeclaration> enumConstantDeclarations = enumDeclaration.enumConstants();
	for(EnumConstantDeclaration enumConstantDeclaration : enumConstantDeclarations) {
		EnumConstantDeclarationObject enumConstantDeclarationObject = new EnumConstantDeclarationObject(enumConstantDeclaration.getName().getIdentifier());
		enumConstantDeclarationObject.setEnumName(classObject.getName());
		enumConstantDeclarationObject.setEnumConstantDeclaration(enumConstantDeclaration);
		List<Expression> arguments = enumConstantDeclaration.arguments();
		for(Expression argument : arguments) {
			AbstractExpression abstractExpression = new AbstractExpression(argument);
			enumConstantDeclarationObject.addArgument(abstractExpression);
		}
		classObject.addEnumConstantDeclaration(enumConstantDeclarationObject);
	}
	
	List<BodyDeclaration> bodyDeclarations = enumDeclaration.bodyDeclarations();
	for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
		if(bodyDeclaration instanceof MethodDeclaration) {
			processMethodDeclaration(classObject, (MethodDeclaration)bodyDeclaration);
		}
		else if(bodyDeclaration instanceof FieldDeclaration) {
			processFieldDeclaration(classObject, (FieldDeclaration)bodyDeclaration);
		}
	}
	return classObject;
}