Java Code Examples for org.eclipse.jdt.internal.corext.dom.Bindings#normalizeForDeclarationUse()

The following examples show how to use org.eclipse.jdt.internal.corext.dom.Bindings#normalizeForDeclarationUse() . 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: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkTempTypeForLocalTypeUsage() throws JavaModelException {
	Expression expression = getSelectedExpression().getAssociatedExpression();
	Type resultingType = null;
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	AST ast = fCURewrite.getAST();

	if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) {
		resultingType = ((ClassInstanceCreation) expression).getType();
	} else if (expression instanceof CastExpression) {
		resultingType = ((CastExpression) expression).getType();
	} else {
		if (typeBinding == null) {
			typeBinding = ASTResolving.guessBindingForReference(expression);
		}
		if (typeBinding != null) {
			typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
			ImportRewrite importRewrite = fCURewrite.getImportRewrite();
			ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite);
			resultingType = importRewrite.addImport(typeBinding, ast, context, TypeLocation.LOCAL_VARIABLE);
		} else {
			resultingType = ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
		}
	}

	IMethodBinding declaringMethodBinding = getMethodDeclaration().resolveBinding();
	ITypeBinding[] methodTypeParameters = declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
	LocalTypeAndVariableUsageAnalyzer analyzer = new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
	resultingType.accept(analyzer);
	boolean usesLocalTypes = !analyzer.getUsageOfEnclosingNodes().isEmpty();
	if (usesLocalTypes) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractFieldRefactoring_uses_type_declared_locally);
	}
	return null;
}
 
Example 2
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Type getConstantType() throws JavaModelException {
	if (fConstantTypeCache == null) {
		IExpressionFragment fragment = getSelectedExpression();
		ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
		AST ast = fCuRewrite.getAST();
		typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
		ImportRewrite importRewrite = fCuRewrite.getImportRewrite();
		ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite);
		fConstantTypeCache = importRewrite.addImport(typeBinding, ast, context, TypeLocation.FIELD);
	}
	return fConstantTypeCache;
}
 
Example 3
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public AssignToVariableAssistProposal(ICompilationUnit cu, int variableKind, ExpressionStatement node, ITypeBinding typeBinding, int relevance) {
	super("", JavaCodeActionKind.QUICK_ASSIST, cu, null, relevance); //$NON-NLS-1$

	fVariableKind= variableKind;
	fNodesToAssign= new ArrayList<>();
	fNodesToAssign.add(node);

	fTypeBinding= Bindings.normalizeForDeclarationUse(typeBinding, node.getAST());
	if (variableKind == LOCAL) {
		setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntolocal_description);
	} else {
		setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntofield_description);
	}
	createImportRewrite((CompilationUnit) node.getRoot());
}
 
Example 4
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public AssignToVariableAssistProposal(ICompilationUnit cu, String kind, int variableKind, ExpressionStatement node, ITypeBinding typeBinding, int relevance) {
	super("", kind, cu, null, relevance); //$NON-NLS-1$

	fVariableKind = variableKind;
	fNodesToAssign = new ArrayList<>();
	fNodesToAssign.add(node);

	fTypeBinding = Bindings.normalizeForDeclarationUse(typeBinding, node.getAST());
	if (variableKind == LOCAL) {
		setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntolocal_description);
	} else {
		setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntofield_description);
	}
	createImportRewrite((CompilationUnit) node.getRoot());
}
 
Example 5
Source File: IntroduceParameterRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addParameterInfo(CompilationUnitRewrite cuRewrite) throws JavaModelException {
	ITypeBinding typeBinding= Bindings.normalizeForDeclarationUse(fSelectedExpression.resolveTypeBinding(), fSelectedExpression.getAST());
	String name= fParameterName != null ? fParameterName : guessedParameterName();
	Expression expression= fSelectedExpression instanceof ParenthesizedExpression ? ((ParenthesizedExpression)fSelectedExpression).getExpression() : fSelectedExpression;
	
	ImportRewrite importRewrite= cuRewrite.getImportRewrite();			
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fSelectedExpression, importRewrite);
	String typeName= importRewrite.addImport(typeBinding, importRewriteContext);
	
	String defaultValue= null;
	if (expression instanceof ClassInstanceCreation && typeBinding.isParameterizedType()) {
		ClassInstanceCreation classInstanceCreation= (ClassInstanceCreation) expression;
		Type cicType= classInstanceCreation.getType();
		if (cicType instanceof ParameterizedType && ((ParameterizedType) cicType).typeArguments().size() == 0) {
			// expand the diamond:
			AST ast= cuRewrite.getAST();				
			Type type= importRewrite.addImport(typeBinding, ast, importRewriteContext);				
			classInstanceCreation.setType(type);    // Should not touch the original AST ...
			defaultValue= ASTNodes.asFormattedString(classInstanceCreation,  0, StubUtility.getLineDelimiterUsed(cuRewrite.getCu()), cuRewrite.getCu().getJavaProject().getOptions(true));
			classInstanceCreation.setType(cicType); // ... so let's restore it right away.
		}
	}
	
	if (defaultValue == null) {
		defaultValue= fSourceCU.getBuffer().getText(expression.getStartPosition(), expression.getLength());
	}
	fParameter= ParameterInfo.createInfoForAddedParameter(typeBinding, typeName, name, defaultValue);
	if (fArguments == null) {
		List<ParameterInfo> parameterInfos= fChangeSignatureProcessor.getParameterInfos();
		int parametersCount= parameterInfos.size();
		if (parametersCount > 0 && parameterInfos.get(parametersCount - 1).isOldVarargs())
			parameterInfos.add(parametersCount - 1, fParameter);
		else
			parameterInfos.add(fParameter);
	}
}
 
Example 6
Source File: IntroduceParameterRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private List<String> guessTempNamesFromExpression(Expression selectedExpression, String[] excluded) {
	ITypeBinding expressionBinding= Bindings.normalizeForDeclarationUse(
		selectedExpression.resolveTypeBinding(),
		selectedExpression.getAST());
	String typeName= getQualifiedName(expressionBinding);
	if (typeName.length() == 0)
		typeName= expressionBinding.getName();
	if (typeName.length() == 0)
		return Collections.emptyList();
	int typeParamStart= typeName.indexOf("<"); //$NON-NLS-1$
	if (typeParamStart != -1)
		typeName= typeName.substring(0, typeParamStart);
	String[] proposals= StubUtility.getLocalNameSuggestions(fSourceCU.getJavaProject(), typeName, expressionBinding.getDimensions(), excluded);
	return Arrays.asList(proposals);
}
 
Example 7
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Type getConstantType() throws JavaModelException {
	if (fConstantTypeCache == null) {
		IExpressionFragment fragment= getSelectedExpression();
		ITypeBinding typeBinding= guessBindingForReference(fragment.getAssociatedExpression());
		AST ast= fCuRewrite.getAST();
		typeBinding= Bindings.normalizeForDeclarationUse(typeBinding, ast);
		ImportRewrite importRewrite= fCuRewrite.getImportRewrite();
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite);
		fConstantTypeCache= importRewrite.addImport(typeBinding, ast, context);
	}
	return fConstantTypeCache;
}
 
Example 8
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extracts the type parameter of the variable contained in fCurrentExpression or the elements
 * type to iterate over an array using <code>foreach</code>.
 * 
 * @param ast the current {@link AST} instance
 * @return the {@link ITypeBinding} of the elements to iterate over
 */
private ITypeBinding extractElementType(AST ast) {
	if (fExpressionType.isArray()) {
		return Bindings.normalizeForDeclarationUse(fExpressionType.getElementType(), ast);
	}

	// extract elements type directly out of the bindings
	IMethodBinding iteratorMethodBinding= Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {}); //$NON-NLS-1$
	IMethodBinding iteratorNextMethodBinding= Bindings.findMethodInHierarchy(iteratorMethodBinding.getReturnType(), "next", new ITypeBinding[] {}); //$NON-NLS-1$

	ITypeBinding currentElementBinding= iteratorNextMethodBinding.getReturnType();

	return Bindings.normalizeForDeclarationUse(currentElementBinding, ast);
}
 
Example 9
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast = fEnclosingBodyDeclaration.getAST();
	fReturnType = null;
	fReturnTypeBinding = null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration = ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType = ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding = declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression = (Expression) getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding = ((ClassInstanceCreation) expression).getType().resolveBinding();
			} else {
				fExpressionBinding = expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding = Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType = rewriter.addImport(normalizedBinding, ast, context, TypeLocation.RETURN_TYPE);
						fReturnTypeBinding = normalizedBinding;
					}
				}
			} else {
				fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType = ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding = methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType = ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding = fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}
 
Example 10
Source File: AbstractExceptionAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
protected void addException(ITypeBinding exception, AST ast) {
	exception = Bindings.normalizeForDeclarationUse(exception, ast);
	if (!fCurrentExceptions.contains(exception)) {
		fCurrentExceptions.add(exception);
	}
}
 
Example 11
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast= fEnclosingBodyDeclaration.getAST();
	fReturnType= null;
	fReturnTypeBinding= null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration= ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType= ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding= declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression= (Expression)getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding= ((ClassInstanceCreation)expression).getType().resolveBinding();
			} else {
				fExpressionBinding= expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding= Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType= rewriter.addImport(normalizedBinding, ast, context);
						fReturnTypeBinding= normalizedBinding;
					}
				}
			} else {
				fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType= ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding= methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType= ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding= fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}
 
Example 12
Source File: AbstractExceptionAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected void addException(ITypeBinding exception, AST ast) {
	exception= Bindings.normalizeForDeclarationUse(exception, ast);
	if (!fCurrentExceptions.contains(exception))
		fCurrentExceptions.add(exception);
}
 
Example 13
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Name) {
		IBinding binding= ((Name) selectedNode).resolveBinding();
		if (binding instanceof IVariableBinding) {
			IVariableBinding variableBinding= (IVariableBinding) binding;
			if (variableBinding.isField()) {
				String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
				String fieldName= variableBinding.getName();
				String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
				if (methodName != null) {
					AST ast= selectedNode.getAST();
					ASTRewrite astRewrite= ASTRewrite.create(ast);
					ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);

					MethodInvocation method= ast.newMethodInvocation();
					String qfn= importRewrite.addImport(methodName[0]);
					method.setExpression(ast.newName(qfn));
					method.setName(ast.newSimpleName(methodName[1]));
					ASTNode parent= selectedNode.getParent();
					ICompilationUnit cu= context.getCompilationUnit();
					// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
					if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
						IMethodBinding methodBinding= Invocations.resolveBinding(parent);
						if (methodBinding != null) {
							ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
							int i= Invocations.getArguments(parent).indexOf(selectedNode);
							if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
								ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments();
								for (int j= 0; j < typeArguments.length; j++) {
									ITypeBinding typeArgument= typeArguments[j];
									typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
									if (! TypeRules.isJavaLangObject(typeArgument)) {
										// add all type arguments if at least one is found to be necessary:
										List<Type> typeArgumentsList= method.typeArguments();
										for (int k= 0; k < typeArguments.length; k++) {
											typeArgument= typeArguments[k];
											typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
											typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
										}
										break;
									}
								}
							}
						}
					}
					
					astRewrite.replace(selectedNode, method, null);

					String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
					ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
					proposal.setImportRewrite(importRewrite);
					proposals.add(proposal);
				}
			}
		}
	}
}