use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.
the class ExtractMethodRefactoring method createNewMethodDeclaration.
private MethodDeclaration createNewMethodDeclaration() {
MethodDeclaration result = fAST.newMethodDeclaration();
int modifiers = fVisibility;
BodyDeclaration enclosingBodyDeclaration = fAnalyzer.getEnclosingBodyDeclaration();
boolean isDestinationInterface = isDestinationInterface();
if (isDestinationInterface && !(enclosingBodyDeclaration instanceof MethodDeclaration && enclosingBodyDeclaration.getParent() == fDestination && Modifier.isPublic(enclosingBodyDeclaration.getModifiers()))) {
modifiers = Modifier.NONE;
}
boolean shouldBeStatic = false;
ASTNode currentParent = enclosingBodyDeclaration;
do {
if (currentParent instanceof BodyDeclaration) {
shouldBeStatic = shouldBeStatic || JdtFlags.isStatic((BodyDeclaration) currentParent);
}
currentParent = currentParent.getParent();
} while (!shouldBeStatic && currentParent != null && currentParent != fDestination);
if (shouldBeStatic || fAnalyzer.getForceStatic() || forceStatic()) {
modifiers |= Modifier.STATIC;
} else if (isDestinationInterface) {
modifiers |= Modifier.DEFAULT;
}
ITypeBinding[] typeVariables = computeLocalTypeVariables(modifiers);
List<TypeParameter> typeParameters = result.typeParameters();
for (int i = 0; i < typeVariables.length; i++) {
TypeParameter parameter = fAST.newTypeParameter();
parameter.setName(fAST.newSimpleName(typeVariables[i].getName()));
ITypeBinding[] bounds = typeVariables[i].getTypeBounds();
for (int j = 0; j < bounds.length; j++) {
if (!"java.lang.Object".equals(bounds[j].getQualifiedName())) {
parameter.typeBounds().add(fImportRewriter.addImport(bounds[j], fAST));
}
}
typeParameters.add(parameter);
}
result.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, modifiers));
result.setReturnType2((Type) ASTNode.copySubtree(fAST, fAnalyzer.getReturnType()));
result.setName(fAST.newSimpleName(fMethodName));
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(enclosingBodyDeclaration, fImportRewriter);
List<SingleVariableDeclaration> parameters = result.parameters();
for (int i = 0; i < fParameterInfos.size(); i++) {
ParameterInfo info = fParameterInfos.get(i);
VariableDeclaration infoDecl = getVariableDeclaration(info);
SingleVariableDeclaration parameter = fAST.newSingleVariableDeclaration();
parameter.modifiers().addAll(ASTNodeFactory.newModifiers(fAST, ASTNodes.getModifiers(infoDecl)));
parameter.setType(ASTNodeFactory.newType(fAST, infoDecl, fImportRewriter, context));
parameter.setName(fAST.newSimpleName(info.getNewName()));
parameter.setVarargs(info.isNewVarargs());
parameters.add(parameter);
}
List<Type> exceptions = result.thrownExceptionTypes();
ITypeBinding[] exceptionTypes = fAnalyzer.getExceptions(fThrowRuntimeExceptions);
for (int i = 0; i < exceptionTypes.length; i++) {
ITypeBinding exceptionType = exceptionTypes[i];
exceptions.add(fImportRewriter.addImport(exceptionType, fAST, context, TypeLocation.EXCEPTION));
}
return result;
}
use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.
the class ExtractTempRefactoring method createRefactoringDescriptor.
private final ExtractLocalDescriptor createRefactoringDescriptor() {
final Map<String, String> arguments = new HashMap<>();
String project = null;
IJavaProject javaProject = fCu.getJavaProject();
if (javaProject != null) {
project = javaProject.getElementName();
}
final String description = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fTempName));
final String expression = ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
final String header = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fTempName), BasicElementLabels.getJavaCodeString(expression) });
final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_name_pattern, BasicElementLabels.getJavaElementName(fTempName)));
final BodyDeclaration decl = (BodyDeclaration) ASTNodes.getParent(fSelectedExpression.getAssociatedExpression(), BodyDeclaration.class);
if (decl instanceof MethodDeclaration) {
final IMethodBinding method = ((MethodDeclaration) decl).resolveBinding();
final String label = method != null ? BindingLabelProvider.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED) : BasicElementLabels.getJavaElementName('{' + JavaElementLabels.ELLIPSIS_STRING + '}');
comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_destination_pattern, label));
}
comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_expression_pattern, BasicElementLabels.getJavaCodeString(expression)));
if (fReplaceAllOccurrences) {
comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences);
}
if (fDeclareFinal) {
comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_final);
}
final ExtractLocalDescriptor descriptor = RefactoringSignatureDescriptorFactory.createExtractLocalDescriptor(project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fTempName);
// $NON-NLS-1$
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString());
arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString());
return descriptor;
}
use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.
the class TypeMismatchSubProcessor method addTypeMismatchProposals.
public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws CoreException {
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 (currBinding == null && nodeToCast instanceof MethodInvocation) {
IMethodBinding methodBinding = ((MethodInvocation) nodeToCast).resolveMethodBinding();
if (methodBinding != null) {
currBinding = methodBinding.getReturnType();
}
}
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()));
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_METHOD_RETURN_TYPE);
ImportRewrite imports = proposal.createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
Type newReturnType = imports.addImport(currBinding, ast, importRewriteContext, TypeLocation.RETURN_TYPE);
rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
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;
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));
}
}
use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.
the class UnresolvedElementsSubProcessor method createTypeRefChangeProposal.
private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance, int maxProposals) {
ImportRewrite importRewrite = null;
String simpleName = fullName;
String packName = Signature.getQualifier(fullName);
if (packName.length() > 0) {
// no imports for primitive types, type variables
importRewrite = CodeStyleConfiguration.createImportRewrite((CompilationUnit) node.getRoot(), true);
// can be null in package-info.java
BodyDeclaration scope = ASTResolving.findParentBodyDeclaration(node);
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(scope != null ? scope : node, importRewrite);
simpleName = importRewrite.addImport(fullName, context);
}
if (!isLikelyTypeName(simpleName)) {
relevance -= 2;
}
ASTRewriteCorrectionProposal proposal;
if (importRewrite != null && node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) {
// import only
// import only
String[] arg = { BasicElementLabels.getJavaElementName(simpleName), BasicElementLabels.getJavaElementName(packName) };
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, arg);
proposal = new AddImportCorrectionProposal(label, cu, relevance + 100, packName, simpleName, (SimpleName) node);
} else {
String label;
if (packName.length() == 0) {
label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_nopack_description, BasicElementLabels.getJavaElementName(simpleName));
} else {
String[] arg = { BasicElementLabels.getJavaElementName(simpleName), BasicElementLabels.getJavaElementName(packName) };
label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetype_description, arg);
}
ASTRewrite rewrite = ASTRewrite.create(node.getAST());
rewrite.replace(node, rewrite.createStringPlaceholder(simpleName, ASTNode.SIMPLE_TYPE), null);
proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, relevance);
}
if (importRewrite != null) {
proposal.setImportRewrite(importRewrite);
}
return proposal;
}
use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.
the class UnresolvedElementsSubProcessor method addNewTypeProposals.
public static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection<CUCorrectionProposal> proposals) throws CoreException {
Name node = refNode;
// type parameter proposals
if (refNode.isSimpleName() && (kind & TypeKinds.VARIABLES) != 0) {
CompilationUnit root = (CompilationUnit) refNode.getRoot();
String name = ((SimpleName) refNode).getIdentifier();
BodyDeclaration declaration = ASTResolving.findParentBodyDeclaration(refNode);
int baseRel = relevance;
if (isLikelyTypeParameterName(name)) {
baseRel += 8;
}
while (declaration != null) {
IBinding binding = null;
int rel = baseRel;
if (declaration instanceof MethodDeclaration) {
binding = ((MethodDeclaration) declaration).resolveBinding();
if (isLikelyMethodTypeParameterName(name)) {
rel += 2;
}
} else if (declaration instanceof TypeDeclaration) {
binding = ((TypeDeclaration) declaration).resolveBinding();
rel++;
}
if (binding != null) {
AddTypeParameterProposal proposal = new AddTypeParameterProposal(cu, binding, root, name, null, rel);
proposals.add(proposal);
}
if (!Modifier.isStatic(declaration.getModifiers())) {
declaration = ASTResolving.findParentBodyDeclaration(declaration.getParent());
} else {
declaration = null;
}
}
}
}
Aggregations