Search in sources :

Example 11 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project che 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));
            fBuffer.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));
            fBuffer.append('.');
        }
        int parentType = parent.getElementType();
        if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) {
            // anonymous or local
            appendElementLabel(parent, 0);
            fBuffer.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;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        supertypeName = getSimpleTypeName(type, type.getSuperclassTypeSignature());
                    }
                    typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName);
                }
            } catch (JavaModelException e) {
                //ignore
                typeName = JavaUIMessages.JavaElementLabels_anonym;
            }
        }
    }
    fBuffer.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
            }
        }
    }
    // category
    if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) {
        try {
            appendCategoryLabel(type, flags);
        } catch (JavaModelException e) {
        // ignore
        }
    }
    // post qualification
    if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        fBuffer.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
                fBuffer.append('.');
                appendElementLabel(parent, 0);
            }
        } else {
            appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
        }
        if (getFlag(flags, JavaElementLabels.COLORIZE)) {
            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        }
    }
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) JavaModelException(org.eclipse.jdt.core.JavaModelException) BindingKey(org.eclipse.jdt.core.BindingKey) StyledString(org.eclipse.jface.viewers.StyledString) IField(org.eclipse.jdt.core.IField) IType(org.eclipse.jdt.core.IType) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 12 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project che by eclipse.

the class SourceMapper method mapSource.

/**
     * Maps the given source code to the given binary type and its children.
     * If a non-null java element is passed, finds the name range for the
     * given java element without storing it.
     */
public synchronized ISourceRange mapSource(IType type, char[] contents, IBinaryType info, IJavaElement elementToFind) {
    this.binaryType = (BinaryType) type;
    // check whether it is already mapped
    if (this.sourceRanges.get(type) != null)
        return (elementToFind != null) ? getNameRange(elementToFind) : null;
    this.importsTable.remove(this.binaryType);
    this.importsCounterTable.remove(this.binaryType);
    this.searchedElement = elementToFind;
    this.types = new IType[1];
    this.typeDeclarationStarts = new int[1];
    this.typeNameRanges = new SourceRange[1];
    this.typeModifiers = new int[1];
    this.typeDepth = -1;
    this.memberDeclarationStart = new int[1];
    this.memberName = new String[1];
    this.memberNameRange = new SourceRange[1];
    this.methodParameterTypes = new char[1][][];
    this.methodParameterNames = new char[1][][];
    this.anonymousCounter = 0;
    HashMap oldSourceRanges = null;
    if (elementToFind != null) {
        oldSourceRanges = (HashMap) this.sourceRanges.clone();
    }
    try {
        IProblemFactory factory = new DefaultProblemFactory();
        SourceElementParser parser = null;
        this.anonymousClassName = 0;
        if (info == null) {
            try {
                info = (IBinaryType) this.binaryType.getElementInfo();
            } catch (JavaModelException e) {
                return null;
            }
        }
        boolean isAnonymousClass = info.isAnonymous();
        char[] fullName = info.getName();
        if (isAnonymousClass) {
            String eltName = this.binaryType.getParent().getElementName();
            eltName = eltName.substring(eltName.lastIndexOf('$') + 1, eltName.length());
            try {
                this.anonymousClassName = Integer.parseInt(eltName);
            } catch (NumberFormatException e) {
            // ignore
            }
        }
        boolean doFullParse = hasToRetrieveSourceRangesForLocalClass(fullName);
        parser = new SourceElementParser(this, factory, new CompilerOptions(this.options), doFullParse, true);
        // disable javadoc parsing
        parser.javadocParser.checkDocComment = false;
        IJavaElement javaElement = this.binaryType.getCompilationUnit();
        if (javaElement == null)
            javaElement = this.binaryType.getParent();
        parser.parseCompilationUnit(new BasicCompilationUnit(contents, null, this.binaryType.sourceFileName(info), javaElement), doFullParse, null);
        if (elementToFind != null) {
            ISourceRange range = getNameRange(elementToFind);
            return range;
        } else {
            return null;
        }
    } finally {
        if (elementToFind != null) {
            this.sourceRanges = oldSourceRanges;
        }
        this.binaryType = null;
        this.searchedElement = null;
        this.types = null;
        this.typeDeclarationStarts = null;
        this.typeNameRanges = null;
        this.typeDepth = -1;
    }
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaModelException(org.eclipse.jdt.core.JavaModelException) HashMap(java.util.HashMap) BasicCompilationUnit(org.eclipse.jdt.internal.core.BasicCompilationUnit) SourceElementParser(org.eclipse.jdt.internal.compiler.SourceElementParser) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 13 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project che 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;
    }
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) IMethod(org.eclipse.jdt.core.IMethod) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 14 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project che by eclipse.

the class Rename18Test method renameLocalVariable.

private void renameLocalVariable(String newFieldName, boolean updateReferences) throws Exception {
    ParticipantTesting.reset();
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
    ISourceRange selection = getSelection(cu);
    IJavaElement[] elements = cu.codeSelect(selection.getOffset(), selection.getLength());
    assertEquals(1, elements.length);
    RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_LOCAL_VARIABLE);
    descriptor.setJavaElement(elements[0]);
    descriptor.setNewName(newFieldName);
    descriptor.setUpdateReferences(updateReferences);
    descriptor.setUpdateTextualOccurrences(false);
    RenameRefactoring refactoring = (RenameRefactoring) createRefactoring(descriptor);
    List list = new ArrayList();
    list.add(elements[0]);
    List args = new ArrayList();
    args.add(new RenameArguments(newFieldName, updateReferences));
    String[] renameHandles = ParticipantTesting.createHandles(list.toArray());
    RefactoringStatus result = performRefactoring(refactoring);
    assertEquals("was supposed to pass", null, result);
    assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource());
    ParticipantTesting.testRename(renameHandles, (RenameArguments[]) args.toArray(new RenameArguments[args.size()]));
    assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo());
    assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo());
    RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor());
    assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource());
    assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo());
    assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo());
    RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor());
    assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource());
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) RenameArguments(org.eclipse.ltk.core.refactoring.participants.RenameArguments) RenameRefactoring(org.eclipse.ltk.core.refactoring.participants.RenameRefactoring) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) ArrayList(java.util.ArrayList) List(java.util.List) RenameJavaElementDescriptor(org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 15 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project tdi-studio-se by Talend.

the class OpenDeclarationAction method getMethodNameRange.

/**
     * Gets the source range.
     * 
     * @param editorInput The editor input
     * @return The source range
     * @throws JavaModelException
     */
private ISourceRange getMethodNameRange(IEditorInput editorInput) throws JavaModelException {
    ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editorInput);
    LinkedList<ISourceRange> sourceRanges = new LinkedList<ISourceRange>();
    if (typeRoot instanceof IClassFile) {
        // class file
        IType type = ((IClassFile) typeRoot).getType();
        getMethodNameRange(type.getChildren(), 0, sourceRanges);
    } else if (typeRoot instanceof ICompilationUnit) {
        // java file
        ICompilationUnit unit = (ICompilationUnit) typeRoot;
        IType[] allTypes = unit.getAllTypes();
        for (IType type : allTypes) {
            getMethodNameRange(type.getChildren(), 0, sourceRanges);
        }
    } else {
        return null;
    }
    if (sourceRanges.isEmpty()) {
        return null;
    }
    return sourceRanges.getFirst();
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IClassFile(org.eclipse.jdt.core.IClassFile) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) LinkedList(java.util.LinkedList) ISourceRange(org.eclipse.jdt.core.ISourceRange) IType(org.eclipse.jdt.core.IType)

Aggregations

ISourceRange (org.eclipse.jdt.core.ISourceRange)53 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)18 IJavaElement (org.eclipse.jdt.core.IJavaElement)14 JavaModelException (org.eclipse.jdt.core.JavaModelException)13 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)10 ISourceReference (org.eclipse.jdt.core.ISourceReference)9 IType (org.eclipse.jdt.core.IType)8 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)6 SourceRange (org.eclipse.jdt.core.SourceRange)6 IBuffer (org.eclipse.jdt.core.IBuffer)5 IMethod (org.eclipse.jdt.core.IMethod)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)5 ArrayList (java.util.ArrayList)4 IField (org.eclipse.jdt.core.IField)4 IMember (org.eclipse.jdt.core.IMember)4 CoreException (org.eclipse.core.runtime.CoreException)3 IClassFile (org.eclipse.jdt.core.IClassFile)3