use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class JavaContext method addImport.
/**
* Adds an import for type with type name <code>type</code> if possible.
* Returns a string which can be used to reference the type.
*
* @param type the fully qualified name of the type to import
* @return returns a type to which the type binding can be assigned to.
* The returned type contains is unqualified when an import could be added or was already known.
* It is fully qualified, if an import conflict prevented the import.
* @since 3.4
*/
public String addImport(String type) {
if (isReadOnly())
return type;
ICompilationUnit cu = getCompilationUnit();
if (cu == null)
return type;
try {
boolean qualified = type.indexOf('.') != -1;
if (!qualified) {
IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
SimpleName nameNode = null;
TypeNameMatch[] matches = findAllTypes(type, searchScope, nameNode, null, cu);
if (// only add import if we have a single match
matches.length != 1)
return type;
type = matches[0].getFullyQualifiedName();
}
CompilationUnit root = getASTRoot(cu);
if (fImportRewrite == null) {
if (root == null) {
fImportRewrite = StubUtility.createImportRewrite(cu, true);
} else {
fImportRewrite = StubUtility.createImportRewrite(root, true);
}
}
ImportRewriteContext context;
if (root == null)
context = null;
else
context = new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite);
return fImportRewrite.addImport(type, context);
} catch (JavaModelException e) {
handleException(null, e);
return type;
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class IntroduceFactoryRefactoring method createFactoryMethod.
/**
* Creates and returns a new MethodDeclaration that represents the factory method to be used in
* place of direct calls to the constructor in question.
*
* @param ast An AST used as a factory for various AST nodes
* @param ctorBinding binding for the constructor being wrapped
* @param unitRewriter the ASTRewrite to be used
* @return the new method declaration
* @throws CoreException if an exception occurs while accessing its corresponding resource
*/
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException {
MethodDeclaration newMethod = ast.newMethodDeclaration();
SimpleName newMethodName = ast.newSimpleName(fNewMethodName);
ClassInstanceCreation newCtorCall = ast.newClassInstanceCreation();
ReturnStatement ret = ast.newReturnStatement();
Block body = ast.newBlock();
List<Statement> stmts = body.statements();
String retTypeName = ctorBinding.getName();
createFactoryMethodSignature(ast, newMethod);
newMethod.setName(newMethodName);
newMethod.setBody(body);
ITypeBinding declaringClass = fCtorBinding.getDeclaringClass();
ITypeBinding[] ctorOwnerTypeParameters = declaringClass.getTypeParameters();
setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);
newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));
setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);
createFactoryMethodConstructorArgs(ast, newCtorCall);
if (Modifier.isAbstract(declaringClass.getModifiers())) {
AnonymousClassDeclaration decl = ast.newAnonymousClassDeclaration();
IMethodBinding[] unimplementedMethods = getUnimplementedMethods(declaringClass);
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
for (int i = 0; i < unimplementedMethods.length; i++) {
IMethodBinding unImplementedMethod = unimplementedMethods[i];
MethodDeclaration newMethodDecl = StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass().getName(), settings, false);
decl.bodyDeclarations().add(newMethodDecl);
}
newCtorCall.setAnonymousClassDeclaration(decl);
}
ret.setExpression(newCtorCall);
stmts.add(ret);
return newMethod;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class TypeMismatchSubProcessor method addTypeMismatchProposals.
public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
String[] args = problem.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
AST ast = astRoot.getAST();
ASTNode selectedNode = problem.getCoveredNode(astRoot);
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast = (Expression) selectedNode;
Name receiverNode = null;
ITypeBinding castTypeBinding = null;
int parentNodeType = selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign = (Assignment) selectedNode.getParent();
Expression leftHandSide = assign.getLeftHandSide();
if (selectedNode.equals(leftHandSide)) {
nodeToCast = assign.getRightHandSide();
}
castTypeBinding = assign.getLeftHandSide().resolveTypeBinding();
if (leftHandSide instanceof Name) {
receiverNode = (Name) leftHandSide;
} else if (leftHandSide instanceof FieldAccess) {
receiverNode = ((FieldAccess) leftHandSide).getName();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag = (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName()) || selectedNode.equals(frag.getInitializer())) {
nodeToCast = frag.getInitializer();
castTypeBinding = ASTNodes.getType(frag).resolveBinding();
receiverNode = frag.getName();
}
} else if (parentNodeType == ASTNode.MEMBER_VALUE_PAIR) {
receiverNode = ((MemberValuePair) selectedNode.getParent()).getName();
castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
} else if (parentNodeType == ASTNode.SINGLE_MEMBER_ANNOTATION) {
// use the type name
receiverNode = ((SingleMemberAnnotation) selectedNode.getParent()).getTypeName();
castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
} else {
// try to find the binding corresponding to 'castTypeName'
castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
}
if (castTypeBinding == null) {
return;
}
ITypeBinding currBinding = nodeToCast.resolveTypeBinding();
if (!(nodeToCast instanceof ArrayInitializer)) {
ITypeBinding castFixType = null;
if (currBinding == null || castTypeBinding.isCastCompatible(currBinding) || nodeToCast instanceof CastExpression) {
castFixType = castTypeBinding;
} else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
ITypeBinding boxUnboxedTypeBinding = boxUnboxPrimitives(castTypeBinding, currBinding, ast);
if (boxUnboxedTypeBinding != castTypeBinding && boxUnboxedTypeBinding.isCastCompatible(currBinding)) {
castFixType = boxUnboxedTypeBinding;
}
}
if (castFixType != null) {
proposals.add(createCastProposal(context, castFixType, nodeToCast, IProposalRelevance.CREATE_CAST));
}
}
//$NON-NLS-1$
boolean nullOrVoid = currBinding == null || "void".equals(currBinding.getName());
// change method return statement to actual type
if (!nullOrVoid && parentNodeType == ASTNode.RETURN_STATEMENT) {
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
currBinding = Bindings.normalizeTypeBinding(currBinding);
if (currBinding == null) {
//$NON-NLS-1$
currBinding = ast.resolveWellKnownType("java.lang.Object");
}
if (currBinding.isWildcardType()) {
currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
}
ASTRewrite rewrite = ASTRewrite.create(ast);
String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturntype_description, BasicElementLabels.getJavaElementName(currBinding.getName()));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_METHOD_RETURN_TYPE, image);
ImportRewrite imports = proposal.createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
Type newReturnType = imports.addImport(currBinding, ast, importRewriteContext);
rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
//$NON-NLS-1$
String returnKey = "return";
proposal.addLinkedPosition(rewrite.track(newReturnType), true, returnKey);
ITypeBinding[] typeSuggestions = ASTResolving.getRelaxingTypes(ast, currBinding);
for (int i = 0; i < typeSuggestions.length; i++) {
proposal.addLinkedPositionProposal(returnKey, typeSuggestions[i]);
}
proposals.add(proposal);
}
}
if (!nullOrVoid && receiverNode != null) {
currBinding = Bindings.normalizeTypeBinding(currBinding);
if (currBinding == null) {
//$NON-NLS-1$
currBinding = ast.resolveWellKnownType("java.lang.Object");
}
if (currBinding.isWildcardType()) {
currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
}
addChangeSenderTypeProposals(context, receiverNode, currBinding, true, IProposalRelevance.CHANGE_TYPE_OF_RECEIVER_NODE, proposals);
}
addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, IProposalRelevance.CHANGE_TYPE_OF_NODE_TO_CAST, proposals);
if (castTypeBinding == ast.resolveWellKnownType("boolean") && currBinding != null && !currBinding.isPrimitive() && !Bindings.isVoidType(currBinding)) {
//$NON-NLS-1$
String label = CorrectionMessages.TypeMismatchSubProcessor_insertnullcheck_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
InfixExpression expression = ast.newInfixExpression();
expression.setLeftOperand((Expression) rewrite.createMoveTarget(nodeToCast));
expression.setRightOperand(ast.newNullLiteral());
expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
rewrite.replace(nodeToCast, expression, null);
proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_NULL_CHECK, image));
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class TypeMismatchSubProcessor method addTypeMismatchInForEachProposals.
public static void addTypeMismatchInForEachProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (selectedNode == null || selectedNode.getLocationInParent() != EnhancedForStatement.EXPRESSION_PROPERTY) {
return;
}
EnhancedForStatement forStatement = (EnhancedForStatement) selectedNode.getParent();
ITypeBinding expressionBinding = forStatement.getExpression().resolveTypeBinding();
if (expressionBinding == null) {
return;
}
ITypeBinding expectedBinding;
if (expressionBinding.isArray()) {
expectedBinding = expressionBinding.getComponentType();
} else {
//$NON-NLS-1$
IMethodBinding iteratorMethod = Bindings.findMethodInHierarchy(expressionBinding, "iterator", new String[0]);
if (iteratorMethod == null) {
return;
}
ITypeBinding[] typeArguments = iteratorMethod.getReturnType().getTypeArguments();
if (typeArguments.length != 1) {
return;
}
expectedBinding = typeArguments[0];
}
AST ast = astRoot.getAST();
expectedBinding = Bindings.normalizeForDeclarationUse(expectedBinding, ast);
SingleVariableDeclaration parameter = forStatement.getParameter();
ICompilationUnit cu = context.getCompilationUnit();
if (parameter.getName().getLength() == 0) {
SimpleName simpleName = null;
if (parameter.getType() instanceof SimpleType) {
SimpleType type = (SimpleType) parameter.getType();
if (type.getName() instanceof SimpleName) {
simpleName = (SimpleName) type.getName();
}
} else if (parameter.getType() instanceof NameQualifiedType) {
simpleName = ((NameQualifiedType) parameter.getType()).getName();
}
if (simpleName != null) {
String name = simpleName.getIdentifier();
int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
return;
}
}
String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_incompatible_for_each_type_description, new String[] { BasicElementLabels.getJavaElementName(parameter.getName().getIdentifier()), BindingLabelProvider.getBindingLabel(expectedBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS) });
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewrite rewrite = ASTRewrite.create(ast);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.INCOMPATIBLE_FOREACH_TYPE, image);
ImportRewrite importRewrite = proposal.createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(selectedNode), importRewrite);
Type newType = importRewrite.addImport(expectedBinding, ast, importRewriteContext);
rewrite.replace(parameter.getType(), newType, null);
proposals.add(proposal);
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project che by eclipse.
the class UnresolvedElementsSubProcessor method addQualifierToOuterProposal.
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection<ICommandAccess> proposals) {
ITypeBinding declaringType = binding.getDeclaringClass();
ITypeBinding parentType = Bindings.getBindingOfParentType(invocationNode);
ITypeBinding currType = parentType;
boolean isInstanceMethod = !Modifier.isStatic(binding.getModifiers());
while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
return;
}
currType = currType.getDeclaringClass();
}
if (currType == null || currType == parentType) {
return;
}
ASTRewrite rewrite = ASTRewrite.create(invocationNode.getAST());
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description, ASTResolving.getTypeSignature(currType));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE, image);
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(invocationNode, imports);
AST ast = invocationNode.getAST();
String qualifier = imports.addImport(currType, importRewriteContext);
Name name = ASTNodeFactory.newName(ast, qualifier);
Expression newExpression;
if (isInstanceMethod) {
ThisExpression expr = ast.newThisExpression();
expr.setQualifier(name);
newExpression = expr;
} else {
newExpression = name;
}
rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);
proposals.add(proposal);
}
Aggregations