use of org.eclipse.jdt.core.ISourceRange in project eclipse.jdt.ls by eclipse.
the class StubUtility2 method getNodeToInsertBefore.
//
// public static IMethodBinding[] getVisibleConstructors(ITypeBinding binding, boolean accountExisting, boolean proposeDefault) {
// List<IMethodBinding> constructorMethods= new ArrayList<>();
// List<IMethodBinding> existingConstructors= null;
// ITypeBinding superType= binding.getSuperclass();
// if (superType == null) {
// return new IMethodBinding[0];
// }
// if (accountExisting) {
// IMethodBinding[] methods= binding.getDeclaredMethods();
// existingConstructors= new ArrayList<>(methods.length);
// for (int index= 0; index < methods.length; index++) {
// IMethodBinding method= methods[index];
// if (method.isConstructor() && !method.isDefaultConstructor()) {
// existingConstructors.add(method);
// }
// }
// }
// if (existingConstructors != null) {
// constructorMethods.addAll(existingConstructors);
// }
// IMethodBinding[] methods= binding.getDeclaredMethods();
// IMethodBinding[] superMethods= superType.getDeclaredMethods();
// for (int index= 0; index < superMethods.length; index++) {
// IMethodBinding method= superMethods[index];
// if (method.isConstructor()) {
// if (Bindings.isVisibleInHierarchy(method, binding.getPackage()) && (!accountExisting || !Bindings.containsSignatureEquivalentConstructor(methods, method))) {
// constructorMethods.add(method);
// }
// }
// }
// if (existingConstructors != null) {
// constructorMethods.removeAll(existingConstructors);
// }
// if (constructorMethods.isEmpty()) {
// superType= binding;
// while (superType.getSuperclass() != null) {
// superType= superType.getSuperclass();
// }
// IMethodBinding method= Bindings.findMethodInType(superType, "Object", new ITypeBinding[0]); //$NON-NLS-1$
// if (method != null) {
// if ((proposeDefault || !accountExisting || existingConstructors == null || existingConstructors.isEmpty()) && (!accountExisting || !Bindings.containsSignatureEquivalentConstructor(methods, method))) {
// constructorMethods.add(method);
// }
// }
// }
// return constructorMethods.toArray(new IMethodBinding[constructorMethods.size()]);
// }
/**
* Evaluates the insertion position of a new node.
*
* @param listRewrite The list rewriter to which the new node will be added
* @param sibling The Java element before which the new element should be added.
* @return the AST node of the list to insert before or null to insert as last.
* @throws JavaModelException thrown if accessing the Java element failed
*/
public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException {
if (sibling instanceof IMember) {
ISourceRange sourceRange = ((IMember) sibling).getSourceRange();
if (sourceRange == null) {
return null;
}
int insertPos = sourceRange.getOffset();
List<? extends ASTNode> members = listRewrite.getOriginalList();
for (int i = 0; i < members.size(); i++) {
ASTNode curr = members.get(i);
if (curr.getStartPosition() >= insertPos) {
return curr;
}
}
}
return null;
}
use of org.eclipse.jdt.core.ISourceRange in project eclipse.jdt.ls by eclipse.
the class AnonymousTypeCompletionProposal method createNewBody.
private String createNewBody(ImportRewrite importRewrite) throws CoreException {
if (importRewrite == null) {
return null;
}
ICompilationUnit workingCopy = null;
try {
// $NON-NLS-1$
String name = "Type" + System.currentTimeMillis();
workingCopy = fCompilationUnit.getPrimary().getWorkingCopy(null);
ISourceRange range = fSuperType.getSourceRange();
boolean sameUnit = range != null && fCompilationUnit.equals(fSuperType.getCompilationUnit());
String dummyClassContent = createDummyType(name);
StringBuffer workingCopyContents = new StringBuffer(fCompilationUnit.getSource());
int insertPosition;
if (sameUnit) {
insertPosition = range.getOffset() + range.getLength();
} else {
ISourceRange firstTypeRange = fCompilationUnit.getTypes()[0].getSourceRange();
insertPosition = firstTypeRange.getOffset();
}
if (fSuperType.isLocal()) {
workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
insertPosition++;
} else {
// $NON-NLS-1$
workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
}
workingCopy.getBuffer().setContents(workingCopyContents.toString());
ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
parser.setResolveBindings(true);
parser.setStatementsRecovery(true);
parser.setSource(workingCopy);
CompilationUnit astRoot = (CompilationUnit) parser.createAST(new NullProgressMonitor());
ASTNode newType = NodeFinder.perform(astRoot, insertPosition, dummyClassContent.length());
if (!(newType instanceof AbstractTypeDeclaration)) {
return null;
}
AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) newType;
ITypeBinding dummyTypeBinding = declaration.resolveBinding();
if (dummyTypeBinding == null) {
return null;
}
IMethodBinding[] bindings = StubUtility2.getOverridableMethods(astRoot.getAST(), dummyTypeBinding, true);
if (fSuperType.isInterface()) {
ITypeBinding[] dummySuperInterfaces = dummyTypeBinding.getInterfaces();
if (dummySuperInterfaces.length == 0 || dummySuperInterfaces.length == 1 && dummySuperInterfaces[0].isRawType()) {
bindings = new IMethodBinding[0];
}
} else {
ITypeBinding dummySuperclass = dummyTypeBinding.getSuperclass();
if (dummySuperclass == null || dummySuperclass.isRawType()) {
bindings = new IMethodBinding[0];
}
}
CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
IMethodBinding[] methodsToOverride = null;
settings.createComments = false;
List<IMethodBinding> result = new ArrayList<>();
for (int i = 0; i < bindings.length; i++) {
IMethodBinding curr = bindings[i];
if (Modifier.isAbstract(curr.getModifiers())) {
result.add(curr);
}
}
methodsToOverride = result.toArray(new IMethodBinding[result.size()]);
// used to find @NonNullByDefault effective at that current context
IBinding contextBinding = null;
if (fCompilationUnit.getJavaProject().getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true).equals(JavaCore.ENABLED)) {
ASTNode focusNode = NodeFinder.perform(astRoot, fReplacementOffset + dummyClassContent.length(), 0);
contextBinding = getEnclosingDeclaration(focusNode);
}
ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
ITrackedNodePosition trackedDeclaration = rewrite.track(declaration);
ListRewrite rewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
for (int i = 0; i < methodsToOverride.length; i++) {
boolean snippetSupport = i == methodsToOverride.length - 1 ? fSnippetSupport : false;
IMethodBinding curr = methodsToOverride[i];
MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding, settings, dummyTypeBinding.isInterface(), contextBinding, snippetSupport);
rewriter.insertFirst(stub, null);
}
IDocument document = new Document(workingCopy.getSource());
try {
rewrite.rewriteAST().apply(document);
int bodyStart = trackedDeclaration.getStartPosition() + dummyClassContent.indexOf('{');
int bodyEnd = trackedDeclaration.getStartPosition() + trackedDeclaration.getLength();
return document.get(bodyStart, bodyEnd - bodyStart);
} catch (MalformedTreeException exception) {
JavaLanguageServerPlugin.logException(exception.getMessage(), exception);
} catch (BadLocationException exception) {
JavaLanguageServerPlugin.logException(exception.getMessage(), exception);
}
return null;
} finally {
if (workingCopy != null) {
workingCopy.discardWorkingCopy();
}
}
}
use of org.eclipse.jdt.core.ISourceRange in project eclipse.jdt.ls by eclipse.
the class MethodsSourcePositionComparator method compareInTheSameType.
private int compareInTheSameType(IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) {
try {
IMethod firstMethod = (IMethod) firstMethodBinding.getJavaElement();
IMethod secondMethod = (IMethod) secondMethodBinding.getJavaElement();
if (firstMethod == null || secondMethod == null) {
return 0;
}
ISourceRange firstSourceRange = firstMethod.getSourceRange();
ISourceRange secondSourceRange = secondMethod.getSourceRange();
if (!SourceRange.isAvailable(firstSourceRange) || !SourceRange.isAvailable(secondSourceRange)) {
return firstMethod.getElementName().compareTo(secondMethod.getElementName());
} else {
return firstSourceRange.getOffset() - secondSourceRange.getOffset();
}
} catch (JavaModelException e) {
return 0;
}
}
use of org.eclipse.jdt.core.ISourceRange in project eclipse.jdt.ls by eclipse.
the class JavaElementLabelComposer method appendTypeLabel.
/**
* Appends the label for a type. Considers the T_* flags.
*
* @param type the element to render
* @param flags the rendering flags. Flags with names starting with 'T_' are considered.
*/
public void appendTypeLabel(IType type, long flags) {
if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) {
IPackageFragment pack = type.getPackageFragment();
if (!pack.isDefaultPackage()) {
appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
fBuilder.append('.');
}
}
IJavaElement parent = type.getParent();
if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) {
IType declaringType = type.getDeclaringType();
if (declaringType != null) {
appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS));
fBuilder.append('.');
}
int parentType = parent.getElementType();
if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) {
// anonymous or local
appendElementLabel(parent, 0);
fBuilder.append('.');
}
}
String typeName;
boolean isAnonymous = false;
if (type.isLambda()) {
// $NON-NLS-1$
typeName = "() -> {...}";
try {
String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
if (superInterfaceSignatures.length > 0) {
typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]);
}
} catch (JavaModelException e) {
// ignore
}
} else {
typeName = getElementName(type);
try {
isAnonymous = type.isAnonymous();
} catch (JavaModelException e1) {
// should not happen, but let's play safe:
isAnonymous = typeName.length() == 0;
}
if (isAnonymous) {
try {
if (parent instanceof IField && type.isEnum()) {
typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
} else {
String supertypeName = null;
String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
if (superInterfaceSignatures.length > 0) {
supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
} else {
String supertypeSignature = type.getSuperclassTypeSignature();
if (supertypeSignature != null) {
supertypeName = getSimpleTypeName(type, supertypeSignature);
}
}
if (supertypeName == null) {
typeName = "new Anonymous";
} else {
typeName = NLS.bind("new {0}() '{'...}", supertypeName);
}
}
} catch (JavaModelException e) {
// ignore
typeName = "new Anonymous";
}
}
}
fBuilder.append(typeName);
if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) {
if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) {
BindingKey key = new BindingKey(type.getKey());
if (key.isParameterizedType()) {
String[] typeArguments = key.getTypeArguments();
appendTypeArgumentSignaturesLabel(type, typeArguments, flags);
} else {
String[] typeParameters = Signature.getTypeParameters(key.toSignature());
appendTypeParameterSignaturesLabel(typeParameters, flags);
}
} else if (type.exists()) {
try {
appendTypeParametersLabels(type.getTypeParameters(), flags);
} catch (JavaModelException e) {
// ignore
}
}
}
// post qualification
if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
fBuilder.append(JavaElementLabels.CONCAT_STRING);
IType declaringType = type.getDeclaringType();
if (declaringType == null && type.isBinary() && isAnonymous) {
// workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type
String tqn = type.getTypeQualifiedName();
int lastDollar = tqn.lastIndexOf('$');
if (lastDollar != 1) {
// $NON-NLS-1$
String declaringTypeCF = tqn.substring(0, lastDollar) + ".class";
declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType();
try {
ISourceRange typeSourceRange = type.getSourceRange();
if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) {
IJavaElement realParent = declaringType.getTypeRoot().getElementAt(typeSourceRange.getOffset() - 1);
if (realParent != null) {
parent = realParent;
}
}
} catch (JavaModelException e) {
// ignore
}
}
}
if (declaringType != null) {
appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
int parentType = parent.getElementType();
if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) {
// anonymous or local
fBuilder.append('.');
appendElementLabel(parent, 0);
}
} else {
appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
}
}
}
use of org.eclipse.jdt.core.ISourceRange in project eclipse.jdt.ls by eclipse.
the class CodeLensHandler method getCodeLens.
private CodeLens getCodeLens(String type, IJavaElement element, ITypeRoot typeRoot) throws JavaModelException {
CodeLens lens = new CodeLens();
ISourceRange r = ((ISourceReference) element).getNameRange();
final Range range = JDTUtils.toRange(typeRoot, r.getOffset(), r.getLength());
lens.setRange(range);
String uri = ResourceUtils.toClientUri(JDTUtils.toUri(typeRoot));
lens.setData(Arrays.asList(uri, range.getStart(), type));
return lens;
}
Aggregations