use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class ConstructorFromSuperclassProposal method createNewMethodDeclaration.
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
String name = fTypeNode.getName().getIdentifier();
MethodDeclaration decl = ast.newMethodDeclaration();
decl.setConstructor(true);
decl.setName(ast.newSimpleName(name));
Block body = ast.newBlock();
decl.setBody(body);
SuperConstructorInvocation invocation = null;
List<SingleVariableDeclaration> parameters = decl.parameters();
String[] paramNames = getArgumentNames(binding);
ITypeBinding enclosingInstance = getEnclosingInstance();
if (enclosingInstance != null) {
invocation = addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
}
if (binding == null) {
decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
} else {
decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));
ITypeBinding[] params = binding.getParameterTypes();
for (int i = 0; i < params.length; i++) {
SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List<Type> thrownExceptions = decl.thrownExceptionTypes();
ITypeBinding[] excTypes = binding.getExceptionTypes();
for (int i = 0; i < excTypes.length; i++) {
Type excType = getImportRewrite().addImport(excTypes[i], ast, importRewriteContext);
thrownExceptions.add(excType);
}
if (invocation == null) {
invocation = ast.newSuperConstructorInvocation();
}
List<Expression> arguments = invocation.arguments();
for (int i = 0; i < paramNames.length; i++) {
Name argument = ast.newSimpleName(paramNames[i]);
arguments.add(argument);
//$NON-NLS-1$
addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]);
}
}
String bodyStatement = (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
//$NON-NLS-1$
String placeHolder = CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode = rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string = CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class UnresolvedElementsSubProcessor method getAnnotationMemberProposals.
public static void getAnnotationMemberProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
CompilationUnit astRoot = context.getASTRoot();
ICompilationUnit cu = context.getCompilationUnit();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
Annotation annotation;
String memberName;
if (selectedNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
if (selectedNode.getParent().getLocationInParent() != NormalAnnotation.VALUES_PROPERTY) {
return;
}
annotation = (Annotation) selectedNode.getParent().getParent();
memberName = ((SimpleName) selectedNode).getIdentifier();
} else if (selectedNode.getLocationInParent() == SingleMemberAnnotation.VALUE_PROPERTY) {
annotation = (Annotation) selectedNode.getParent();
//$NON-NLS-1$
memberName = "value";
} else {
return;
}
ITypeBinding annotBinding = annotation.resolveTypeBinding();
if (annotBinding == null) {
return;
}
if (annotation instanceof NormalAnnotation) {
// similar names
IMethodBinding[] otherMembers = annotBinding.getDeclaredMethods();
for (int i = 0; i < otherMembers.length; i++) {
IMethodBinding binding = otherMembers[i];
String curr = binding.getName();
int relevance = NameMatcher.isSimilarName(memberName, curr) ? IProposalRelevance.CHANGE_TO_ATTRIBUTE_SIMILAR_NAME : IProposalRelevance.CHANGE_TO_ATTRIBUTE;
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_changetoattribute_description, BasicElementLabels.getJavaElementName(curr));
proposals.add(new RenameNodeCorrectionProposal(label, cu, problem.getOffset(), problem.getLength(), curr, relevance));
}
}
if (annotBinding.isFromSource()) {
ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, annotBinding);
if (targetCU != null) {
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_UnresolvedElementsSubProcessor_createattribute_description, BasicElementLabels.getJavaElementName(memberName));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
proposals.add(new NewAnnotationMemberProposal(label, targetCU, selectedNode, annotBinding, IProposalRelevance.CREATE_ATTRIBUTE, image));
}
}
}
use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class UnresolvedElementsSubProcessor method addSimilarVariableProposals.
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, IVariableBinding resolvedField, SimpleName node, boolean isWriteAccess, Collection<ICommandAccess> proposals) {
int kind = ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
if (!isWriteAccess) {
// also try to find similar methods
kind |= ScopeAnalyzer.METHODS;
}
IBinding[] varsAndMethodsInScope = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
if (varsAndMethodsInScope.length > 0) {
// avoid corrections like int i= i;
String otherNameInAssign = null;
// help with x.getString() -> y.getString()
String methodSenderName = null;
String fieldSenderName = null;
ASTNode parent = node.getParent();
switch(parent.getNodeType()) {
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
// node must be initializer
otherNameInAssign = ((VariableDeclarationFragment) parent).getName().getIdentifier();
break;
case ASTNode.ASSIGNMENT:
Assignment assignment = (Assignment) parent;
if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
otherNameInAssign = ((SimpleName) assignment.getRightHandSide()).getIdentifier();
} else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
otherNameInAssign = ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
}
break;
case ASTNode.METHOD_INVOCATION:
MethodInvocation inv = (MethodInvocation) parent;
if (inv.getExpression() == node) {
methodSenderName = inv.getName().getIdentifier();
}
break;
case ASTNode.QUALIFIED_NAME:
QualifiedName qualName = (QualifiedName) parent;
if (qualName.getQualifier() == node) {
fieldSenderName = qualName.getName().getIdentifier();
}
break;
}
ITypeBinding guessedType = ASTResolving.guessBindingForReference(node);
//$NON-NLS-1$
ITypeBinding objectBinding = astRoot.getAST().resolveWellKnownType("java.lang.Object");
String identifier = node.getIdentifier();
boolean isInStaticContext = ASTResolving.isInStaticContext(node);
ArrayList<CUCorrectionProposal> newProposals = new ArrayList<CUCorrectionProposal>(51);
loop: for (int i = 0; i < varsAndMethodsInScope.length && newProposals.size() <= 50; i++) {
IBinding varOrMeth = varsAndMethodsInScope[i];
if (varOrMeth instanceof IVariableBinding) {
IVariableBinding curr = (IVariableBinding) varOrMeth;
String currName = curr.getName();
if (currName.equals(otherNameInAssign)) {
continue loop;
}
if (resolvedField != null && Bindings.equals(resolvedField, curr)) {
continue loop;
}
boolean isFinal = Modifier.isFinal(curr.getModifiers());
if (isFinal && curr.isField() && isWriteAccess) {
continue loop;
}
if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
continue loop;
}
int relevance = IProposalRelevance.SIMILAR_VARIABLE_PROPOSAL;
if (NameMatcher.isSimilarName(currName, identifier)) {
// variable with a similar name than the unresolved variable
relevance += 3;
}
if (currName.equalsIgnoreCase(identifier)) {
relevance += 5;
}
ITypeBinding varType = curr.getType();
if (varType != null) {
if (guessedType != null && guessedType != objectBinding) {
// variable type is compatible with the guessed type
if (!isWriteAccess && canAssign(varType, guessedType) || isWriteAccess && canAssign(guessedType, varType)) {
// unresolved variable can be assign to this variable
relevance += 2;
}
}
if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
relevance += 2;
}
if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
relevance += 2;
}
}
if (relevance > 0) {
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, BasicElementLabels.getJavaElementName(currName));
newProposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
} else if (varOrMeth instanceof IMethodBinding) {
IMethodBinding curr = (IMethodBinding) varOrMeth;
if (!curr.isConstructor() && guessedType != null && canAssign(curr.getReturnType(), guessedType)) {
if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
AST ast = astRoot.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description, ASTResolving.getMethodSignature(curr));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_METHOD, image);
newProposals.add(proposal);
MethodInvocation newInv = ast.newMethodInvocation();
newInv.setName(ast.newSimpleName(curr.getName()));
ITypeBinding[] parameterTypes = curr.getParameterTypes();
for (int k = 0; k < parameterTypes.length; k++) {
ASTNode arg = ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
newInv.arguments().add(arg);
proposal.addLinkedPosition(rewrite.track(arg), false, null);
}
rewrite.replace(node, newInv, null);
}
}
}
}
if (newProposals.size() <= 50)
proposals.addAll(newProposals);
}
if (binding != null && binding.isArray()) {
//$NON-NLS-1$
String idLength = "length";
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, IProposalRelevance.CHANGE_VARIABLE));
}
}
use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class UnresolvedElementsSubProcessor method addMissingCastParentsProposal.
private static void addMissingCastParentsProposal(ICompilationUnit cu, MethodInvocation invocationNode, Collection<ICommandAccess> proposals) {
Expression sender = invocationNode.getExpression();
if (sender instanceof ThisExpression) {
return;
}
ITypeBinding senderBinding = sender.resolveTypeBinding();
if (senderBinding == null || Modifier.isFinal(senderBinding.getModifiers())) {
return;
}
if (sender instanceof Name && ((Name) sender).resolveBinding() instanceof ITypeBinding) {
// static access
return;
}
ASTNode parent = invocationNode.getParent();
while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) {
parent = parent.getParent();
}
boolean hasCastProposal = false;
if (parent instanceof CastExpression) {
// (TestCase) x.getName() -> ((TestCase) x).getName
hasCastProposal = useExistingParentCastProposal(cu, (CastExpression) parent, sender, invocationNode.getName(), getArgumentTypes(invocationNode.arguments()), proposals);
}
if (!hasCastProposal) {
// x.getName() -> ((TestCase) x).getName
Expression target = sender;
while (target instanceof ParenthesizedExpression) {
target = ((ParenthesizedExpression) target).getExpression();
}
String label;
if (target.getNodeType() != ASTNode.CAST_EXPRESSION) {
String targetName = null;
if (target.getLength() <= 18) {
targetName = ASTNodes.asString(target);
}
if (targetName == null) {
label = CorrectionMessages.UnresolvedElementsSubProcessor_methodtargetcast_description;
} else {
label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_methodtargetcast2_description, BasicElementLabels.getJavaCodeString(targetName));
}
} else {
String targetName = null;
if (target.getLength() <= 18) {
targetName = ASTNodes.asString(((CastExpression) target).getExpression());
}
if (targetName == null) {
label = CorrectionMessages.UnresolvedElementsSubProcessor_changemethodtargetcast_description;
} else {
label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changemethodtargetcast2_description, BasicElementLabels.getJavaCodeString(targetName));
}
}
proposals.add(new CastCorrectionProposal(label, cu, target, (ITypeBinding) null, IProposalRelevance.CHANGE_CAST));
}
}
use of org.eclipse.jdt.core.dom.ASTNode in project che by eclipse.
the class VarargsWarningsSubProcessor method addRemoveSafeVarargsProposals.
public static void addRemoveSafeVarargsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ASTNode coveringNode = problem.getCoveringNode(context.getASTRoot());
if (!(coveringNode instanceof MethodDeclaration))
return;
MethodDeclaration methodDeclaration = (MethodDeclaration) coveringNode;
MarkerAnnotation annotation = null;
List<? extends ASTNode> modifiers = methodDeclaration.modifiers();
for (Iterator<? extends ASTNode> iterator = modifiers.iterator(); iterator.hasNext(); ) {
ASTNode node = iterator.next();
if (node instanceof MarkerAnnotation) {
annotation = (MarkerAnnotation) node;
if ("SafeVarargs".equals(annotation.resolveAnnotationBinding().getName())) {
//$NON-NLS-1$
break;
}
}
}
if (annotation == null)
return;
ASTRewrite rewrite = ASTRewrite.create(coveringNode.getAST());
rewrite.remove(annotation, null);
String label = CorrectionMessages.VarargsWarningsSubProcessor_remove_safevarargs_label;
//JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
Image image = JavaPluginImages.get(JavaPluginImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_SAFEVARARGS, image);
proposals.add(proposal);
}
Aggregations