/** * Creates a location for a given java element. * Element can be a {@link ICompilationUnit} or {@link IClassFile} * * @param element * @return location or null * @throws JavaModelException */ public static Location toLocation(IJavaElement element) throws JavaModelException{ ICompilationUnit unit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE); if (unit == null && cf == null) { return null; } if (element instanceof ISourceReference) { ISourceRange nameRange = getNameRange(element); if (SourceRange.isAvailable(nameRange)) { if (cf == null) { return toLocation(unit, nameRange.getOffset(), nameRange.getLength()); } else { return toLocation(cf, nameRange.getOffset(), nameRange.getLength()); } } } return null; }
private static ISourceRange getNameRange(IJavaElement element) throws JavaModelException { ISourceRange nameRange = null; if (element instanceof IMember) { IMember member = (IMember) element; nameRange = member.getNameRange(); if ( (!SourceRange.isAvailable(nameRange))) { nameRange = member.getSourceRange(); } } else if (element instanceof ITypeParameter || element instanceof ILocalVariable) { nameRange = ((ISourceReference) element).getNameRange(); } else if (element instanceof ISourceReference) { nameRange = ((ISourceReference) element).getSourceRange(); } if (!SourceRange.isAvailable(nameRange) && element.getParent() != null) { nameRange = getNameRange(element.getParent()); } return nameRange; }
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; } }
public static Integer getLineNumber(IMember member) throws JavaModelException { ITypeRoot typeRoot = member.getTypeRoot(); IBuffer buffer = typeRoot.getBuffer(); if (buffer == null) { return null; } Document document = new Document(buffer.getContents()); int offset = 0; if (SourceRange.isAvailable(member.getNameRange())) { offset = member.getNameRange().getOffset(); } else if (SourceRange.isAvailable(member.getSourceRange())) { offset = member.getSourceRange().getOffset(); } try { return document.getLineOfOffset(offset); } catch (BadLocationException e) { return null; } }
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; } }
/** @see org.eclipse.jdt.internal.compiler.ISourceElementRequestor */ public void enterField(FieldInfo fieldInfo) { if (this.typeDepth >= 0) { this.memberDeclarationStart[this.typeDepth] = fieldInfo.declarationStart; this.memberNameRange[this.typeDepth] = new SourceRange( fieldInfo.nameSourceStart, fieldInfo.nameSourceEnd - fieldInfo.nameSourceStart + 1); String fieldName = new String(fieldInfo.name); this.memberName[this.typeDepth] = fieldName; // categories IType currentType = this.types[this.typeDepth]; IField field = currentType.getField(fieldName); addCategories(field, fieldInfo.categories); } }
@Override public final void endVisit(final QualifiedName node) { final ASTNode parent= node.getParent(); final Name qualifier= node.getQualifier(); IBinding binding= qualifier.resolveBinding(); if (binding instanceof ITypeBinding) { final ConstraintVariable2 variable= fModel.createTypeVariable((ITypeBinding) binding, new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(node), new SourceRange(qualifier.getStartPosition(), qualifier.getLength()))); if (variable != null) qualifier.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable); } binding= node.getName().resolveBinding(); if (binding instanceof IVariableBinding && !(parent instanceof ImportDeclaration)) endVisit((IVariableBinding) binding, qualifier, node); else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration) endVisit((ITypeBinding) binding, node); }
private void initializeSelectedExpression(CompilationUnitRewrite cuRewrite) throws JavaModelException { IASTFragment fragment= ASTFragmentFactory.createFragmentForSourceRange( new SourceRange(fSelectionStart, fSelectionLength), cuRewrite.getRoot(), cuRewrite.getCu()); if (! (fragment instanceof IExpressionFragment)) return; //TODO: doesn't handle selection of partial Expressions Expression expression= ((IExpressionFragment) fragment).getAssociatedExpression(); if (fragment.getStartPosition() != expression.getStartPosition() || fragment.getLength() != expression.getLength()) return; if (Checks.isInsideJavadoc(expression)) return; //TODO: exclude invalid selections if (Checks.isEnumCase(expression.getParent())) return; fSelectedExpression= expression; }
private static RefactoringStatus checkKey(String key) { RefactoringStatus result= new RefactoringStatus(); if (key == null) result.addFatalError(NLSMessages.NLSRefactoring_null); if (key.startsWith("!") || key.startsWith("#")) { //$NON-NLS-1$ //$NON-NLS-2$ RefactoringStatusContext context= new JavaStringStatusContext(key, new SourceRange(0, 0)); result.addWarning(NLSMessages.NLSRefactoring_warning, context); } if ("".equals(key.trim())) //$NON-NLS-1$ result.addFatalError(NLSMessages.NLSRefactoring_empty); final String[] UNWANTED_STRINGS= {" ", ":", "\"", "\\", "'", "?", "="}; //$NON-NLS-7$ //$NON-NLS-6$ //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ //feature in resource bundle - does not work properly if keys have ":" for (int i= 0; i < UNWANTED_STRINGS.length; i++) { if (key.indexOf(UNWANTED_STRINGS[i]) != -1) { String[] args= {key, UNWANTED_STRINGS[i]}; String msg= Messages.format(NLSMessages.NLSRefactoring_should_not_contain, args); result.addError(msg); } } return result; }
public ISourceRange getNameRange() throws JavaModelException { SourceMapper mapper= getSourceMapper(); if (mapper != null) { ClassFile classFile = (ClassFile)getClassFile(); if (classFile != null) { // ensure the class file's buffer is open so that source ranges are computed classFile.getBuffer(); return mapper.getNameRange(this); } } Object info = getElementInfo(); if (info instanceof AnnotationInfo) { AnnotationInfo annotationInfo = (AnnotationInfo) info; return new SourceRange(annotationInfo.nameStart, annotationInfo.nameEnd - annotationInfo.nameStart + 1); } return null; }
private void exitAbstractMethod(int declarationEnd) { if (this.typeDepth >= 0) { IType currentType = this.types[this.typeDepth]; SourceRange sourceRange = new SourceRange( this.memberDeclarationStart[this.typeDepth], declarationEnd - this.memberDeclarationStart[this.typeDepth] + 1); IMethod method = currentType.getMethod( this.memberName[this.typeDepth], convertTypeNamesToSigs(this.methodParameterTypes[this.typeDepth])); setSourceRange( method, sourceRange, this.memberNameRange[this.typeDepth]); setMethodParameterNames( method, this.methodParameterNames[this.typeDepth]); } }
static boolean isSourceAvailable(ISourceReference sourceReference) { try { return SourceRange.isAvailable(sourceReference.getSourceRange()); } catch (JavaModelException e) { return false; } }
@Override public ISourceRange getSourceRange() { try { return fMember.getSourceRange(); } catch (JavaModelException e) { return new SourceRange(0, 0); } }
@Override public ISourceRange getSourceRange() { try { return fImportDeclartion.getSourceRange(); } catch (JavaModelException e) { return new SourceRange(0, 0); } }
private String shortDescription(String javadoc) throws Exception { IMember member = mock(IMember.class); IOpenable openable = (IOpenable)mock(JavaElement.class, withSettings().extraInterfaces(IOpenable.class)); when(member.getOpenable()).thenReturn(openable); IBuffer buffer = BufferManager.createBuffer(openable); buffer.setContents(javadoc); when(openable.getBuffer()).thenReturn(buffer); when(member.getJavadocRange()).thenReturn(new SourceRange(0, javadoc.length())); return javadocCommentProvider.getJavadocCommentShortDescription(member); }
private ISourceRange getSelection(ICompilationUnit cu) throws Exception { String source = cu.getSource(); // Warning: this *includes* the SQUARE_BRACKET_OPEN! int offset = source.indexOf(SQUARE_BRACKET_OPEN); int end = source.indexOf(SQUARE_BRACKET_CLOSE); return new SourceRange(offset + SQUARE_BRACKET_OPEN.length(), end - offset); }
private static ISourceRange getRangeOfOperands(List<Expression> operands) { Expression first = operands.get(0); Expression last = operands.get(operands.size() - 1); return new SourceRange( first.getStartPosition(), last.getStartPosition() + last.getLength() - first.getStartPosition()); }
private static void addShadowsError( ICompilationUnit cu, SearchMatch oldMatch, RefactoringStatus result) { // Old match not found in new matches -> reference has been shadowed // TODO: should not have to filter declarations: if (oldMatch instanceof MethodDeclarationMatch || oldMatch instanceof FieldDeclarationMatch) return; ISourceRange range = new SourceRange(oldMatch.getOffset(), oldMatch.getLength()); RefactoringStatusContext context = JavaStatusContext.create(cu, range); String message = Messages.format( RefactoringCoreMessages.RenameAnalyzeUtil_shadows, BasicElementLabels.getFileName(cu)); result.addError(message, context); }
public static boolean isInlineMethodAvailable(IMethod method) throws JavaModelException { if (method == null) return false; if (!method.exists()) return false; if (!method.isStructureKnown()) return false; if (!method.isBinary()) return true; if (method.isConstructor()) return false; return SourceRange.isAvailable(method.getNameRange()); }
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); }
public static boolean isSourceAvailable(ISourceReference sourceReference) { try { return SourceRange.isAvailable(sourceReference.getSourceRange()); } catch (JavaModelException e) { return false; } }
/** @see org.eclipse.jdt.internal.compiler.ISourceElementRequestor */ public void exitType(int declarationEnd) { if (this.typeDepth >= 0) { IType currentType = this.types[this.typeDepth]; setSourceRange( currentType, new SourceRange( this.typeDeclarationStarts[this.typeDepth], declarationEnd - this.typeDeclarationStarts[this.typeDepth] + 1), this.typeNameRanges[this.typeDepth]); this.typeDepth--; } }
/** @see org.eclipse.jdt.internal.compiler.ISourceElementRequestor */ public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) { if (this.typeDepth >= 0) { IType currentType = this.types[this.typeDepth]; setSourceRange( currentType.getField(this.memberName[this.typeDepth]), new SourceRange( this.memberDeclarationStart[this.typeDepth], declarationEnd - this.memberDeclarationStart[this.typeDepth] + 1), this.memberNameRange[this.typeDepth]); } }
private void exitAbstractMethod(int declarationEnd) { if (this.typeDepth >= 0) { IType currentType = this.types[this.typeDepth]; SourceRange sourceRange = new SourceRange( this.memberDeclarationStart[this.typeDepth], declarationEnd - this.memberDeclarationStart[this.typeDepth] + 1); IMethod method = currentType.getMethod( this.memberName[this.typeDepth], convertTypeNamesToSigs(this.methodParameterTypes[this.typeDepth])); setSourceRange(method, sourceRange, this.memberNameRange[this.typeDepth]); setMethodParameterNames(method, this.methodParameterNames[this.typeDepth]); } }
/** * Creates the necessary changes to update tag references to the original * method. * * @param rewrites * the map of compilation units to compilation unit rewrites * @param declaration * the source method declaration * @param groups * the search result groups representing all references to the * moved method, including references in comments * @param status * the refactoring status * @param monitor * the progress monitor to use */ protected void createMethodJavadocReferences(Map<ICompilationUnit, CompilationUnitRewrite> rewrites, MethodDeclaration declaration, SearchResultGroup[] groups, RefactoringStatus status, IProgressMonitor monitor) { Assert.isNotNull(rewrites); Assert.isNotNull(declaration); Assert.isNotNull(status); Assert.isNotNull(monitor); try { monitor.beginTask("", groups.length); //$NON-NLS-1$ monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_creating); SearchMatch[] matches= null; IJavaElement element= null; ICompilationUnit unit= null; CompilationUnitRewrite rewrite= null; SearchResultGroup group= null; for (int index= 0; index < groups.length; index++) { group= groups[index]; element= JavaCore.create(group.getResource()); unit= group.getCompilationUnit(); if (element instanceof ICompilationUnit) { matches= group.getSearchResults(); unit= (ICompilationUnit) element; rewrite= getCompilationUnitRewrite(rewrites, unit); SearchMatch match= null; for (int offset= 0; offset < matches.length; offset++) { match= matches[offset]; if (match.getAccuracy() == SearchMatch.A_INACCURATE) { status.merge(RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_inline_inaccurate, BasicElementLabels.getFileName(unit)), JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength())))); } else createMethodJavadocReference(rewrite, declaration, match, status); } } monitor.worked(1); } } finally { monitor.done(); } }
@Override public ISourceRange getSourceRange() { try { return fMember.getSourceRange(); } catch (JavaModelException e) { return new SourceRange(0,0); } }
@Override public ISourceRange getSourceRange() { try { return fImportDeclartion.getSourceRange(); } catch (JavaModelException e) { return new SourceRange(0,0); } }
private static void addShadowsError(ICompilationUnit cu, SearchMatch oldMatch, RefactoringStatus result) { // Old match not found in new matches -> reference has been shadowed //TODO: should not have to filter declarations: if (oldMatch instanceof MethodDeclarationMatch || oldMatch instanceof FieldDeclarationMatch) return; ISourceRange range= new SourceRange(oldMatch.getOffset(), oldMatch.getLength()); RefactoringStatusContext context= JavaStatusContext.create(cu, range); String message= Messages.format(RefactoringCoreMessages.RenameAnalyzeUtil_shadows, BasicElementLabels.getFileName(cu)); result.addError(message, context); }
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); }
@Override public ICompilationUnit[] getAffectedCompilationUnits(final RefactoringStatus status, ReferencesInBinaryContext binaryRefs, IProgressMonitor pm) throws CoreException { IMethod method= (IMethod)fMethodBinding.getJavaElement(); Assert.isTrue(method != null); SearchPattern pattern= SearchPattern.createPattern(method, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE); IJavaSearchScope scope= RefactoringScopeFactory.create(method, true, false); final HashSet<ICompilationUnit> affectedCompilationUnits= new HashSet<ICompilationUnit>(); CollectingSearchRequestor requestor= new CollectingSearchRequestor(binaryRefs) { private ICompilationUnit fLastCU; @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if (filterMatch(match)) return; if (match.isInsideDocComment()) return; // TODO: should warn user (with something like a ReferencesInBinaryContext) ICompilationUnit unit= SearchUtils.getCompilationUnit(match); if (match.getAccuracy() == SearchMatch.A_INACCURATE) { if (unit != null) { status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match, JavaStatusContext.create(unit, new SourceRange(match.getOffset(), match.getLength()))); } else { status.addError(RefactoringCoreMessages.TargetProvider_inaccurate_match); } } else if (unit != null) { if (! unit.equals(fLastCU)) { fLastCU= unit; affectedCompilationUnits.add(unit); } } } }; new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, new SubProgressMonitor(pm, 1)); return affectedCompilationUnits.toArray(new ICompilationUnit[affectedCompilationUnits.size()]); }