use of org.eclipse.jdt.core.dom.SuperMethodInvocation in project xtext-eclipse by eclipse.
the class JvmImplementationOpener method openImplementations.
/**
* Main parts of the logic is taken from {@link org.eclipse.jdt.internal.ui.javaeditor.JavaElementImplementationHyperlink}
*
* @param element - Element to show implementations for
* @param textviewer - Viewer to show hierarchy view on
* @param region - Region where to show hierarchy view
*/
public void openImplementations(final IJavaElement element, ITextViewer textviewer, IRegion region) {
if (element instanceof IMethod) {
ITypeRoot typeRoot = ((IMethod) element).getTypeRoot();
CompilationUnit ast = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_YES, null);
if (ast == null) {
openQuickHierarchy(textviewer, element, region);
return;
}
try {
ISourceRange nameRange = ((IMethod) element).getNameRange();
ASTNode node = NodeFinder.perform(ast, nameRange);
ITypeBinding parentTypeBinding = null;
if (node instanceof SimpleName) {
ASTNode parent = node.getParent();
if (parent instanceof MethodInvocation) {
Expression expression = ((MethodInvocation) parent).getExpression();
if (expression == null) {
parentTypeBinding = Bindings.getBindingOfParentType(node);
} else {
parentTypeBinding = expression.resolveTypeBinding();
}
} else if (parent instanceof SuperMethodInvocation) {
// Directly go to the super method definition
openEditor(element);
return;
} else if (parent instanceof MethodDeclaration) {
parentTypeBinding = Bindings.getBindingOfParentType(node);
}
}
final IType type = parentTypeBinding != null ? (IType) parentTypeBinding.getJavaElement() : null;
if (type == null) {
openQuickHierarchy(textviewer, element, region);
return;
}
final String earlyExitIndicator = "EarlyExitIndicator";
final ArrayList<IJavaElement> links = Lists.newArrayList();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
String methodLabel = JavaElementLabels.getElementLabel(element, JavaElementLabels.DEFAULT_QUALIFIED);
monitor.beginTask(Messages.format("Searching for implementors of ''{0}''", methodLabel), 100);
SearchRequestor requestor = new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
IJavaElement element = (IJavaElement) match.getElement();
if (element instanceof IMethod && !JdtFlags.isAbstract((IMethod) element)) {
links.add(element);
if (links.size() > 1) {
throw new OperationCanceledException(earlyExitIndicator);
}
}
}
}
};
int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
SearchPattern pattern = SearchPattern.createPattern(element, limitTo);
Assert.isNotNull(pattern);
SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
SearchEngine engine = new SearchEngine();
engine.search(pattern, participants, SearchEngine.createHierarchyScope(type), requestor, SubMonitor.convert(monitor, 100));
if (monitor.isCanceled()) {
throw new InterruptedException();
}
} catch (OperationCanceledException e) {
throw new InterruptedException(e.getMessage());
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
try {
PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
} catch (InvocationTargetException e) {
IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format("An error occurred while searching for implementations of method ''{0}''. See error log for details.", element.getElementName()), e.getCause());
JavaPlugin.log(status);
ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Open Implementation", "Problems finding implementations.", status);
} catch (InterruptedException e) {
if (e.getMessage() != earlyExitIndicator) {
return;
}
}
if (links.size() == 1) {
openEditor(links.get(0));
} else {
openQuickHierarchy(textviewer, element, region);
}
} catch (JavaModelException e) {
log.error("An error occurred while searching for implementations", e.getCause());
} catch (PartInitException e) {
log.error("An error occurred while searching for implementations", e.getCause());
}
}
}
use of org.eclipse.jdt.core.dom.SuperMethodInvocation in project eclipse.jdt.ls by eclipse.
the class StubUtility method getBaseNameFromExpression.
private static String getBaseNameFromExpression(IJavaProject project, Expression assignedExpression, int variableKind) {
String name = null;
if (assignedExpression instanceof CastExpression) {
assignedExpression = ((CastExpression) assignedExpression).getExpression();
}
if (assignedExpression instanceof Name) {
Name simpleNode = (Name) assignedExpression;
IBinding binding = simpleNode.resolveBinding();
if (binding instanceof IVariableBinding) {
return getBaseName((IVariableBinding) binding, project);
}
return ASTNodes.getSimpleNameIdentifier(simpleNode);
} else if (assignedExpression instanceof MethodInvocation) {
name = ((MethodInvocation) assignedExpression).getName().getIdentifier();
} else if (assignedExpression instanceof SuperMethodInvocation) {
name = ((SuperMethodInvocation) assignedExpression).getName().getIdentifier();
} else if (assignedExpression instanceof FieldAccess) {
return ((FieldAccess) assignedExpression).getName().getIdentifier();
} else if (variableKind == NamingConventions.VK_STATIC_FINAL_FIELD && (assignedExpression instanceof StringLiteral || assignedExpression instanceof NumberLiteral)) {
String string = assignedExpression instanceof StringLiteral ? ((StringLiteral) assignedExpression).getLiteralValue() : ((NumberLiteral) assignedExpression).getToken();
StringBuffer res = new StringBuffer();
boolean needsUnderscore = false;
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (Character.isJavaIdentifierPart(ch)) {
if (res.length() == 0 && !Character.isJavaIdentifierStart(ch) || needsUnderscore) {
res.append('_');
}
res.append(ch);
needsUnderscore = false;
} else {
needsUnderscore = res.length() > 0;
}
}
if (res.length() > 0) {
return res.toString();
}
}
if (name != null) {
for (int i = 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
String curr = KNOWN_METHOD_NAME_PREFIXES[i];
if (name.startsWith(curr)) {
if (name.equals(curr)) {
// don't suggest 'get' as variable name
return null;
} else if (Character.isUpperCase(name.charAt(curr.length()))) {
return name.substring(curr.length());
}
}
}
}
return name;
}
use of org.eclipse.jdt.core.dom.SuperMethodInvocation in project eclipse.jdt.ls by eclipse.
the class StubUtility2 method createImplementationStub.
public static MethodDeclaration createImplementationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String[] parameterNames, ITypeBinding targetType, CodeGenerationSettings settings, boolean inInterface, IBinding contextBinding, boolean snippetStringSupport) throws CoreException {
Assert.isNotNull(imports);
Assert.isNotNull(rewrite);
AST ast = rewrite.getAST();
String type = Bindings.getTypeQualifiedName(targetType);
IJavaProject javaProject = unit.getJavaProject();
IAnnotationBinding nullnessDefault = null;
if (contextBinding != null && JavaCore.ENABLED.equals(javaProject.getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true))) {
nullnessDefault = findNullnessDefault(contextBinding, javaProject);
}
MethodDeclaration decl = ast.newMethodDeclaration();
decl.modifiers().addAll(getImplementationModifiers(ast, binding, inInterface, imports, context, nullnessDefault));
decl.setName(ast.newSimpleName(binding.getName()));
decl.setConstructor(false);
ITypeBinding bindingReturnType = binding.getReturnType();
bindingReturnType = StubUtility2.replaceWildcardsAndCaptures(bindingReturnType);
if (JavaModelUtil.is50OrHigher(javaProject)) {
createTypeParameters(imports, context, ast, binding, decl);
} else {
bindingReturnType = bindingReturnType.getErasure();
}
decl.setReturnType2(imports.addImport(bindingReturnType, ast, context, TypeLocation.RETURN_TYPE));
List<SingleVariableDeclaration> parameters = createParameters(javaProject, imports, context, ast, binding, parameterNames, decl, nullnessDefault);
createThrownExceptions(decl, binding, imports, context, ast);
String delimiter = unit.findRecommendedLineSeparator();
int modifiers = binding.getModifiers();
ITypeBinding declaringType = binding.getDeclaringClass();
// $NON-NLS-1$
ITypeBinding typeObject = ast.resolveWellKnownType("java.lang.Object");
if (!inInterface || (declaringType != typeObject && JavaModelUtil.is18OrHigher(javaProject))) {
// generate a method body
Map<String, String> options = javaProject.getOptions(true);
Block body = ast.newBlock();
decl.setBody(body);
// $NON-NLS-1$
String bodyStatement = "";
if (Modifier.isAbstract(modifiers)) {
Expression expression = ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
if (expression != null) {
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(expression);
bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
}
} else {
SuperMethodInvocation invocation = ast.newSuperMethodInvocation();
if (declaringType.isInterface()) {
ITypeBinding supertype = Bindings.findImmediateSuperTypeInHierarchy(targetType, declaringType.getTypeDeclaration().getQualifiedName());
if (supertype == null) {
// should not happen, but better use the type we have rather than failing
supertype = declaringType;
}
if (supertype.isInterface()) {
String qualifier = imports.addImport(supertype.getTypeDeclaration(), context);
Name name = ASTNodeFactory.newName(ast, qualifier);
invocation.setQualifier(name);
}
}
invocation.setName(ast.newSimpleName(binding.getName()));
for (SingleVariableDeclaration varDecl : parameters) {
invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
}
Expression expression = invocation;
Type returnType = decl.getReturnType2();
if (returnType instanceof PrimitiveType && ((PrimitiveType) returnType).getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
bodyStatement = ASTNodes.asFormattedString(ast.newExpressionStatement(expression), 0, delimiter, options);
} else {
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(expression);
bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
}
}
if (bodyStatement != null) {
StringBuilder placeHolder = new StringBuilder();
if (snippetStringSupport) {
placeHolder.append("${0");
if (!bodyStatement.isEmpty()) {
placeHolder.append(":");
}
bodyStatement = CompletionUtils.sanitizeCompletion(bodyStatement);
}
placeHolder.append(bodyStatement);
if (snippetStringSupport) {
placeHolder.append("}");
}
ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder.toString(), ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
}
/* jdt.ls doesn't create comments at that point
if (settings != null && settings.createComments) {
String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
*/
// According to JLS8 9.2, an interface doesn't implicitly declare non-public members of Object,
// and JLS8 9.6.4.4 doesn't allow @Override for these methods (clone and finalize).
boolean skipOverride = inInterface && declaringType == typeObject && !Modifier.isPublic(modifiers);
if (!skipOverride) {
addOverrideAnnotation(settings, javaProject, rewrite, imports, decl, binding.getDeclaringClass().isInterface(), null);
}
return decl;
}
use of org.eclipse.jdt.core.dom.SuperMethodInvocation in project eclipse.jdt.ls by eclipse.
the class UnresolvedElementsSubProcessor method getMethodProposals.
public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean isOnlyParameterMismatch, Collection<CUCorrectionProposal> proposals) throws CoreException {
ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName nameNode = (SimpleName) selectedNode;
List<Expression> arguments;
Expression sender;
boolean isSuperInvocation;
ASTNode invocationNode = nameNode.getParent();
if (invocationNode instanceof MethodInvocation) {
MethodInvocation methodImpl = (MethodInvocation) invocationNode;
arguments = methodImpl.arguments();
sender = methodImpl.getExpression();
isSuperInvocation = false;
} else if (invocationNode instanceof SuperMethodInvocation) {
SuperMethodInvocation methodImpl = (SuperMethodInvocation) invocationNode;
arguments = methodImpl.arguments();
sender = methodImpl.getQualifier();
isSuperInvocation = true;
} else {
return;
}
String methodName = nameNode.getIdentifier();
int nArguments = arguments.size();
// corrections
IBinding[] bindings = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
HashSet<String> suggestedRenames = new HashSet<>();
for (int i = 0; i < bindings.length; i++) {
IMethodBinding binding = (IMethodBinding) bindings[i];
String curr = binding.getName();
if (!curr.equals(methodName) && binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr) && suggestedRenames.add(curr)) {
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changemethod_description, BasicElementLabels.getJavaElementName(curr));
proposals.add(new RenameNodeCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, IProposalRelevance.CHANGE_METHOD));
}
}
suggestedRenames = null;
if (isOnlyParameterMismatch) {
ArrayList<IMethodBinding> parameterMismatchs = new ArrayList<>();
for (int i = 0; i < bindings.length; i++) {
IMethodBinding binding = (IMethodBinding) bindings[i];
if (binding.getName().equals(methodName)) {
parameterMismatchs.add(binding);
}
}
addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals);
}
if (sender == null) {
addStaticImportFavoriteProposals(context, nameNode, true, proposals);
}
// new method
addNewMethodProposals(cu, astRoot, sender, arguments, isSuperInvocation, invocationNode, methodName, proposals);
if (!isOnlyParameterMismatch && !isSuperInvocation && sender != null) {
addMissingCastParentsProposal(cu, (MethodInvocation) invocationNode, proposals);
}
if (!isSuperInvocation && sender == null && invocationNode.getParent() instanceof ThrowStatement) {
// $NON-NLS-1$ // do it the manual way, copting all the arguments is nasty
String str = "new ";
String label = CorrectionMessages.UnresolvedElementsSubProcessor_addnewkeyword_description;
int relevance = Character.isUpperCase(methodName.charAt(0)) ? IProposalRelevance.ADD_NEW_KEYWORD_UPPERCASE : IProposalRelevance.ADD_NEW_KEYWORD;
ReplaceCorrectionProposal proposal = new ReplaceCorrectionProposal(label, cu, invocationNode.getStartPosition(), 0, str, relevance);
proposals.add(proposal);
}
}
use of org.eclipse.jdt.core.dom.SuperMethodInvocation in project eclipse.jdt.ls by eclipse.
the class NewMethodCorrectionProposal method getNewName.
@Override
protected SimpleName getNewName(ASTRewrite rewrite) {
ASTNode invocationNode = getInvocationNode();
String name;
if (invocationNode instanceof MethodInvocation) {
name = ((MethodInvocation) invocationNode).getName().getIdentifier();
} else if (invocationNode instanceof SuperMethodInvocation) {
name = ((SuperMethodInvocation) invocationNode).getName().getIdentifier();
} else {
// name of the class
name = getSenderBinding().getName();
}
AST ast = rewrite.getAST();
SimpleName newNameNode = ast.newSimpleName(name);
return newNameNode;
}
Aggregations