Search in sources :

Example 26 with ISourceRange

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

the class InlineConstantRefactoring method initialize.

private RefactoringStatus initialize(JavaRefactoringArguments arguments) {
    final String selection = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
    if (selection != null) {
        int offset = -1;
        int length = -1;
        final StringTokenizer tokenizer = new StringTokenizer(selection);
        if (tokenizer.hasMoreTokens())
            offset = Integer.valueOf(tokenizer.nextToken()).intValue();
        if (tokenizer.hasMoreTokens())
            length = Integer.valueOf(tokenizer.nextToken()).intValue();
        if (offset >= 0 && length >= 0) {
            fSelectionStart = offset;
            fSelectionLength = length;
        } else
            return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION }));
    }
    final String handle = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
    if (handle != null) {
        final IJavaElement element = JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false);
        if (element == null || !element.exists())
            return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getName(), IJavaRefactorings.INLINE_CONSTANT);
        else {
            if (element instanceof ICompilationUnit) {
                fSelectionCu = (ICompilationUnit) element;
                if (selection == null)
                    return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
            } else if (element instanceof IField) {
                final IField field = (IField) element;
                try {
                    final ISourceRange range = field.getNameRange();
                    if (range != null) {
                        fSelectionStart = range.getOffset();
                        fSelectionLength = range.getLength();
                    } else
                        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, IJavaRefactorings.INLINE_CONSTANT));
                } catch (JavaModelException exception) {
                    return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getName(), IJavaRefactorings.INLINE_CONSTANT);
                }
                fSelectionCu = field.getCompilationUnit();
            } else
                return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { handle, JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT }));
            final ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setResolveBindings(true);
            parser.setSource(fSelectionCu);
            final CompilationUnit unit = (CompilationUnit) parser.createAST(null);
            initialize(fSelectionCu, unit);
            if (checkStaticFinalConstantNameSelected().hasFatalError())
                return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getName(), IJavaRefactorings.INLINE_CONSTANT);
        }
    } else
        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
    final String replace = arguments.getAttribute(ATTRIBUTE_REPLACE);
    if (replace != null) {
        fReplaceAllReferences = Boolean.valueOf(replace).booleanValue();
    } else
        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE));
    final String remove = arguments.getAttribute(ATTRIBUTE_REMOVE);
    if (remove != null)
        fRemoveDeclaration = Boolean.valueOf(remove).booleanValue();
    else
        return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REMOVE));
    return new RefactoringStatus();
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) StringTokenizer(java.util.StringTokenizer) JavaModelException(org.eclipse.jdt.core.JavaModelException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IField(org.eclipse.jdt.core.IField) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 27 with ISourceRange

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

the class InlineTempRefactoring method checkAssignments.

private RefactoringStatus checkAssignments(VariableDeclaration decl) {
    TempAssignmentFinder assignmentFinder = new TempAssignmentFinder(decl);
    getASTRoot().accept(assignmentFinder);
    if (!assignmentFinder.hasAssignments())
        return new RefactoringStatus();
    ASTNode firstAssignment = assignmentFinder.getFirstAssignment();
    int start = firstAssignment.getStartPosition();
    int length = firstAssignment.getLength();
    ISourceRange range = new SourceRange(start, length);
    RefactoringStatusContext context = JavaStatusContext.create(fCu, range);
    String message = Messages.format(RefactoringCoreMessages.InlineTempRefactoring_assigned_more_once, BasicElementLabels.getJavaElementName(decl.getName().getIdentifier()));
    return RefactoringStatus.createFatalErrorStatus(message, context);
}
Also used : RefactoringStatusContext(org.eclipse.ltk.core.refactoring.RefactoringStatusContext) ASTNode(org.eclipse.jdt.core.dom.ASTNode) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) ISourceRange(org.eclipse.jdt.core.ISourceRange) SourceRange(org.eclipse.jdt.core.SourceRange) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 28 with ISourceRange

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

the class CorrectPackageDeclarationProposal method addEdits.

/* (non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#addEdits(org.eclipse.jdt.internal.corext.textmanipulation
	 * .TextBuffer)
	 */
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
    super.addEdits(doc, root);
    ICompilationUnit cu = getCompilationUnit();
    IPackageFragment parentPack = (IPackageFragment) cu.getParent();
    IPackageDeclaration[] decls = cu.getPackageDeclarations();
    if (parentPack.isDefaultPackage() && decls.length > 0) {
        for (int i = 0; i < decls.length; i++) {
            ISourceRange range = decls[i].getSourceRange();
            root.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
        }
        return;
    }
    if (!parentPack.isDefaultPackage() && decls.length == 0) {
        String lineDelim = StubUtility.getLineDelimiterUsed(cu);
        //$NON-NLS-1$
        String str = "package " + parentPack.getElementName() + ';' + lineDelim + lineDelim;
        root.addChild(new InsertEdit(0, str));
        return;
    }
    root.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), parentPack.getElementName()));
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) InsertEdit(org.eclipse.text.edits.InsertEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IPackageDeclaration(org.eclipse.jdt.core.IPackageDeclaration) DeleteEdit(org.eclipse.text.edits.DeleteEdit) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 29 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project che 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());
        // creates a type that extends the super type
        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()) {
            // add an extra block: helps the AST to recover
            workingCopyContents.insert(insertPosition, '{' + dummyClassContent + '}');
            insertPosition++;
        } else {
            /*
				 * The two empty lines are added because the trackedDeclaration uses the covered range
				 * and hence would also included comments that directly follow the dummy class.
				 */
            //$NON-NLS-1$
            workingCopyContents.insert(insertPosition, dummyClassContent + "\n\n");
        }
        workingCopy.getBuffer().setContents(workingCopyContents.toString());
        CheASTParser parser = CheASTParser.newParser(ASTProvider.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 = JavaPreferencesSettings.getCodeGenerationSettings(fSuperType.getJavaProject());
        IMethodBinding[] methodsToOverride = null;
        IType type = null;
        if (!fSuperType.isInterface() && !fSuperType.isAnnotation()) {
            IJavaElement typeElement = dummyTypeBinding.getJavaElement();
            // add extra checks here as the recovered code is fragile
            if (typeElement instanceof IType && name.equals(typeElement.getElementName()) && typeElement.exists()) {
                type = (IType) typeElement;
            }
        }
        if (type != null) {
            //TODO window
            throw new UnsupportedOperationException();
        } else {
            settings.createComments = false;
            List<IMethodBinding> result = new ArrayList<IMethodBinding>();
            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()]);
        }
        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++) {
            IMethodBinding curr = methodsToOverride[i];
            MethodDeclaration stub = StubUtility2.createImplementationStub(workingCopy, rewrite, importRewrite, null, curr, dummyTypeBinding.getName(), settings, dummyTypeBinding.isInterface());
            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) {
            JavaPlugin.log(exception);
        } catch (BadLocationException exception) {
            JavaPlugin.log(exception);
        }
        return null;
    } finally {
        if (workingCopy != null)
            workingCopy.discardWorkingCopy();
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) ArrayList(java.util.ArrayList) StyledString(org.eclipse.jface.viewers.StyledString) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IType(org.eclipse.jdt.core.IType) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ITrackedNodePosition(org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition) ISourceRange(org.eclipse.jdt.core.ISourceRange) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) CheASTParser(org.eclipse.jdt.core.dom.CheASTParser) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 30 with ISourceRange

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

the class TypeContextChecker method createSupertypeStubTypeContext.

private static StubTypeContext createSupertypeStubTypeContext(String typeName, boolean isInterface, IType enclosingType, IPackageFragment packageFragment) {
    StubTypeContext stubTypeContext;
    //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    String prolog = "class " + typeName + (isInterface ? " implements " : " extends ");
    //$NON-NLS-1$
    String epilog = " {} ";
    if (enclosingType != null) {
        try {
            ICompilationUnit cu = enclosingType.getCompilationUnit();
            ISourceRange typeSourceRange = enclosingType.getSourceRange();
            // before closing brace
            int focalPosition = typeSourceRange.getOffset() + typeSourceRange.getLength() - 1;
            ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(cu);
            parser.setFocalPosition(focalPosition);
            CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
            stubTypeContext = createStubTypeContext(cu, compilationUnit, focalPosition);
            stubTypeContext = new StubTypeContext(stubTypeContext.getCuHandle(), stubTypeContext.getBeforeString() + prolog, epilog + stubTypeContext.getAfterString());
        } catch (CoreException e) {
            JavaPlugin.log(e);
            stubTypeContext = new StubTypeContext(null, null, null);
        }
    } else if (packageFragment != null) {
        ICompilationUnit cu = packageFragment.getCompilationUnit(JavaTypeCompletionProcessor.DUMMY_CU_NAME);
        stubTypeContext = new StubTypeContext(cu, "package " + packageFragment.getElementName() + ";" + prolog, //$NON-NLS-1$//$NON-NLS-2$
        epilog);
    } else {
        stubTypeContext = new StubTypeContext(null, null, null);
    }
    return stubTypeContext;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CoreException(org.eclipse.core.runtime.CoreException) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTParser(org.eclipse.jdt.core.dom.ASTParser) ISourceRange(org.eclipse.jdt.core.ISourceRange)

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