Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#equals()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Rewrites the computed adjustments for the specified compilation unit.
 *
 * @param unit the compilation unit to rewrite the adjustments
 * @param monitor the progress monitor to use
 * @throws JavaModelException if an error occurs during search
 */
public final void rewriteVisibility(final ICompilationUnit unit, final IProgressMonitor monitor) throws JavaModelException {
	try {
		monitor.beginTask("", fAdjustments.keySet().size()); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MemberVisibilityAdjustor_adjusting);
		IMember member= null;
		IVisibilityAdjustment adjustment= null;
		for (final Iterator<IMember> iterator= fAdjustments.keySet().iterator(); iterator.hasNext();) {
			member= iterator.next();
			if (unit.equals(member.getCompilationUnit())) {
				adjustment= fAdjustments.get(member);
				if (adjustment != null)
					adjustment.rewriteVisibility(this, new SubProgressMonitor(monitor, 1));
			}
		}
	} finally {
		fTypeHierarchies.clear();
		monitor.done();
	}
}
 
Example 2
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param unitHandle
 * @return an AST for the given compilation unit handle.<br>
 * If this is the unit containing the selection or the unit in which the factory
 * is to reside, checks the appropriate field (<code>fCU</code> or <code>fFactoryCU</code>,
 * respectively) and initializes the field with a new AST only if not already done.
 */
private CompilationUnit getASTFor(ICompilationUnit unitHandle) {
	if (unitHandle.equals(fCUHandle)) { // is this the unit containing the selection?
		if (fCU == null) {
			fCU= ASTCreator.createAST(unitHandle, null);
			if (fCU.equals(fFactoryUnitHandle)) // if selection unit and factory unit are the same...
				fFactoryCU= fCU; // ...make sure the factory unit gets initialized
		}
		return fCU;
	} else if (unitHandle.equals(fFactoryUnitHandle)) { // is this the "factory unit"?
		if (fFactoryCU == null)
			fFactoryCU= ASTCreator.createAST(unitHandle, null);
		return fFactoryCU;
	} else
		return ASTCreator.createAST(unitHandle, null);
}
 
Example 3
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean simpleReferencesNeedNewImport(ICompilationUnit movedUnit, ICompilationUnit referencingCu, List<ICompilationUnit> cuList) {
	if (referencingCu.equals(movedUnit))
		return false;
	if (cuList.contains(referencingCu))
		return false;
	if (isReferenceInAnotherFragmentOfSamePackage(referencingCu, movedUnit)) {
		/* Destination package is different from source, since
		 * isDestinationAnotherFragmentOfSamePackage(movedUnit) was false in addUpdates(.) */
		return true;
	}

	//heuristic
	if (referencingCu.getImport(movedUnit.getParent().getElementName() + ".*").exists()) //$NON-NLS-1$
		return true; // has old star import
	if (referencingCu.getParent().equals(movedUnit.getParent()))
		return true; //is moved away from same package
	return false;
}
 
Example 4
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param searchHits
 * @return the set of compilation units that will be affected by this
 * particular invocation of this refactoring. This in general includes
 * the class containing the constructor in question, as well as all
 * call sites to the constructor.
 */
private ICompilationUnit[] collectAffectedUnits(SearchResultGroup[] searchHits) {
	Collection<ICompilationUnit>	result= new ArrayList<ICompilationUnit>();
	boolean hitInFactoryClass= false;

	for(int i=0; i < searchHits.length; i++) {
		SearchResultGroup	rg=  searchHits[i];
		ICompilationUnit	icu= rg.getCompilationUnit();

		result.add(icu);
		if (icu.equals(fFactoryUnitHandle))
			hitInFactoryClass= true;
	}
	if (!hitInFactoryClass)
		result.add(fFactoryUnitHandle);
	return result.toArray(new ICompilationUnit[result.size()]);
}
 
Example 5
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/** Removes the found SearchResultGroup from the list iff found.
 *  @param cu the cu
 *  @param searchResultGroups List of SearchResultGroup
 *  @return the SearchResultGroup for cu, or null iff not found */
private static SearchResultGroup extractGroupFor(ICompilationUnit cu, List<SearchResultGroup> searchResultGroups) {
	for (Iterator<SearchResultGroup> iter= searchResultGroups.iterator(); iter.hasNext();) {
		SearchResultGroup group= iter.next();
		if (cu.equals(group.getCompilationUnit())) {
			iter.remove();
			return group;
		}
	}
	return null;
}
 
Example 6
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the visibility threshold from a type to another type.
 *
 * @param referencing the referencing type
 * @param referenced the referenced type
 * @param monitor the progress monitor to use
 * @return the visibility keyword corresponding to the threshold, or <code>null</code> for default visibility
 * @throws JavaModelException if the java elements could not be accessed
 */
private ModifierKeyword thresholdTypeToType(final IType referencing, final IType referenced, final IProgressMonitor monitor) throws JavaModelException {
	ModifierKeyword keyword= ModifierKeyword.PUBLIC_KEYWORD;
	final ICompilationUnit referencedUnit= referenced.getCompilationUnit();
	if (referencing.equals(referenced.getDeclaringType()))
		keyword= ModifierKeyword.PRIVATE_KEYWORD;
	else {
		final ITypeHierarchy hierarchy= getTypeHierarchy(referencing, new SubProgressMonitor(monitor, 1));
		final IType[] types= hierarchy.getSupertypes(referencing);
		IType superType= null;
		for (int index= 0; index < types.length; index++) {
			superType= types[index];
			if (superType.equals(referenced)) {
				keyword= null;
				return keyword;
			}
		}
	}
	final ICompilationUnit typeUnit= referencing.getCompilationUnit();
	if (referencedUnit != null && referencedUnit.equals(typeUnit)) {
		if (referenced.getDeclaringType() != null)
			keyword= null;
		else
			keyword= ModifierKeyword.PRIVATE_KEYWORD;
	} else if (referencedUnit != null && typeUnit != null && referencedUnit.getParent().equals(typeUnit.getParent()))
		keyword= null;
	return keyword;
}
 
Example 7
Source File: GenerateNewConstructorUsingFieldsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IField[] getSelectedFields(IStructuredSelection selection) {
	List<?> elements= selection.toList();
	if (elements.size() > 0) {
		IField[] fields= new IField[elements.size()];
		ICompilationUnit unit= null;
		for (int index= 0; index < elements.size(); index++) {
			if (elements.get(index) instanceof IField) {
				IField field= (IField) elements.get(index);
				if (index == 0) {
					// remember the CU of the first element
					unit= field.getCompilationUnit();
					if (unit == null) {
						return null;
					}
				} else if (!unit.equals(field.getCompilationUnit())) {
					// all fields must be in the same CU
					return null;
				}
				try {
					final IType declaringType= field.getDeclaringType();
					if (declaringType.isInterface() || declaringType.isAnnotation() || declaringType.isAnonymous())
						return null;
				} catch (JavaModelException exception) {
					JavaPlugin.log(exception);
					return null;
				}
				fields[index]= field;
			} else {
				return null;
			}
		}
		return fields;
	}
	return null;
}
 
Example 8
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/** Removes the found SearchResultGroup from the list iff found.
 *  @param cu the cu
 *  @param searchResultGroups List of SearchResultGroup
 *  @return the SearchResultGroup for cu, or null iff not found */
private static SearchResultGroup extractGroupFor(ICompilationUnit cu, List<SearchResultGroup> searchResultGroups) {
	for (Iterator<SearchResultGroup> iter= searchResultGroups.iterator(); iter.hasNext();) {
		SearchResultGroup group= iter.next();
		if (cu.equals(group.getCompilationUnit())) {
			iter.remove();
			return group;
		}
	}
	return null;
}
 
Example 9
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private CompilationUnit makeOrReuseWorkingCopy(@Nonnull ICompilationUnit originalUnit) throws JavaModelException {
    if (originalUnit.equals(cachedCompilationUnitKey)) {
        return cachedCompilationUnit;
    }

    cachedCompilationUnit = createWorkingCopy(originalUnit);
    cachedCompilationUnitKey = originalUnit;
    return cachedCompilationUnit;

}
 
Example 10
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public MoveMethodRefactoring(CompilationUnit sourceCompilationUnit, CompilationUnit targetCompilationUnit, 
		TypeDeclaration sourceTypeDeclaration, TypeDeclaration targetTypeDeclaration, MethodDeclaration sourceMethod,
		Map<MethodInvocation, MethodDeclaration> additionalMethodsToBeMoved, boolean leaveDelegate, String movedMethodName) {
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.targetCompilationUnit = targetCompilationUnit;
	this.sourceTypeDeclaration = sourceTypeDeclaration;
	this.targetTypeDeclaration = targetTypeDeclaration;
	this.sourceMethod = sourceMethod;
	this.targetClassVariableName = null;
	this.additionalArgumentsAddedToMovedMethod = new LinkedHashSet<String>();
	this.additionalTypeBindingsToBeImportedInTargetClass = new LinkedHashSet<ITypeBinding>();
	this.additionalMethodsToBeMoved = additionalMethodsToBeMoved;
	this.fieldDeclarationsChangedWithPublicModifier = new LinkedHashSet<FieldDeclaration>();
	this.memberTypeDeclarationsChangedWithPublicModifier = new LinkedHashSet<BodyDeclaration>();
	this.leaveDelegate = leaveDelegate;
	this.movedMethodName = movedMethodName;
	this.isTargetClassVariableParameter = false;
	this.targetClassVariableParameterIndex = -1;
	this.fChanges = new LinkedHashMap<ICompilationUnit, CompilationUnitChange>();
	
	ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
	this.sourceMultiTextEdit = new MultiTextEdit();
	this.sourceCompilationUnitChange = new CompilationUnitChange("", sourceICompilationUnit);
	sourceCompilationUnitChange.setEdit(sourceMultiTextEdit);
	fChanges.put(sourceICompilationUnit, sourceCompilationUnitChange);
	
	ICompilationUnit targetICompilationUnit = (ICompilationUnit)targetCompilationUnit.getJavaElement();
	if(sourceICompilationUnit.equals(targetICompilationUnit)) {
		this.targetMultiTextEdit = sourceMultiTextEdit;
		this.targetCompilationUnitChange = sourceCompilationUnitChange;
	}
	else {
		this.targetMultiTextEdit = new MultiTextEdit();
		this.targetCompilationUnitChange = new CompilationUnitChange("", targetICompilationUnit);
		targetCompilationUnitChange.setEdit(targetMultiTextEdit);
		fChanges.put(targetICompilationUnit, targetCompilationUnitChange);
	}
}
 
Example 11
Source File: WorkspaceEventsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public void didChangeWatchedFiles(DidChangeWatchedFilesParams param) {
	List<FileEvent> changes = param.getChanges().stream().distinct().collect(Collectors.toList());
	for (FileEvent fileEvent : changes) {
		CHANGE_TYPE changeType = toChangeType(fileEvent.getType());
		if (changeType == CHANGE_TYPE.DELETED) {
			cleanUpDiagnostics(fileEvent.getUri());
			handler.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(fileEvent.getUri())));
			discardWorkingCopies(fileEvent.getUri());
		}
		ICompilationUnit unit = JDTUtils.resolveCompilationUnit(fileEvent.getUri());
		if (unit != null && changeType == CHANGE_TYPE.CREATED && !unit.exists()) {
			final ICompilationUnit[] units = new ICompilationUnit[1];
			units[0] = unit;
			try {
				ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
					@Override
					public void run(IProgressMonitor monitor) throws CoreException {
						units[0] = createCompilationUnit(units[0]);
					}
				}, new NullProgressMonitor());
			} catch (CoreException e) {
				JavaLanguageServerPlugin.logException(e.getMessage(), e);
			}
			unit = units[0];
		}
		if (unit != null) {
			if (unit.isWorkingCopy()) {
				continue;
			}
			if (changeType == CHANGE_TYPE.DELETED || changeType == CHANGE_TYPE.CHANGED) {
				if (unit.equals(CoreASTProvider.getInstance().getActiveJavaElement())) {
					CoreASTProvider.getInstance().disposeAST();
				}
			}
		}
		pm.fileChanged(fileEvent.getUri(), changeType);
	}
}
 
Example 12
Source File: AddGetterSetterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IField[] getSelectedFields(IStructuredSelection selection) {
	List<?> elements= selection.toList();
	int nElements= elements.size();
	if (nElements > 0) {
		IField[] res= new IField[nElements];
		ICompilationUnit cu= null;
		for (int i= 0; i < nElements; i++) {
			Object curr= elements.get(i);
			if (curr instanceof IField) {
				IField fld= (IField) curr;

				if (i == 0) {
					// remember the cu of the first element
					cu= fld.getCompilationUnit();
					if (cu == null) {
						return null;
					}
				} else if (!cu.equals(fld.getCompilationUnit())) {
					// all fields must be in the same CU
					return null;
				}
				try {
					final IType declaringType= fld.getDeclaringType();
					if (declaringType.isInterface() || declaringType.isAnonymous())
						return null;
				} catch (JavaModelException e) {
					JavaPlugin.log(e);
					return null;
				}

				res[i]= fld;
			} else {
				return null;
			}
		}
		return res;
	}
	return null;
}
 
Example 13
Source File: AddDelegateMethodsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IField[] getSelectedFields(IStructuredSelection selection) {
	List<?> elements= selection.toList();
	if (elements.size() > 0) {
		IField[] result= new IField[elements.size()];
		ICompilationUnit unit= null;
		for (int index= 0; index < elements.size(); index++) {
			if (elements.get(index) instanceof IField) {
				IField field= (IField) elements.get(index);

				if (index == 0) {
					// remember the CU of the first element
					unit= field.getCompilationUnit();
					if (unit == null) {
						return null;
					}
				} else if (!unit.equals(field.getCompilationUnit())) {
					// all fields must be in the same CU
					return null;
				}
				try {
					final IType type= field.getDeclaringType();
					if (type.isInterface() || type.isAnonymous()) {
						return null;
					}
				} catch (JavaModelException exception) {
					JavaPlugin.log(exception);
					return null;
				}

				result[index]= field;
			} else {
				return null;
			}
		}
		return result;
	}
	return null;
}
 
Example 14
Source File: SourcePositionComparator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
	if (!(e1 instanceof ISourceReference))
		return 0;
	if (!(e2 instanceof ISourceReference))
		return 0;

	IJavaElement parent1= ((IJavaElement)e1).getParent();
	if (parent1 == null || !parent1.equals(((IJavaElement)e2).getParent())) {
			IType t1= getOutermostDeclaringType(e1);
			if (t1 == null)
				return 0;

			IType t2= getOutermostDeclaringType(e2);
			try {
				if (!t1.equals(t2)) {
					if (t2 == null)
						return 0;

					if (Flags.isPublic(t1.getFlags()) && Flags.isPublic(t2.getFlags()))
						return 0;

					if (!t1.getPackageFragment().equals(t2.getPackageFragment()))
						return 0;

					ICompilationUnit cu1= (ICompilationUnit)((IJavaElement)e1).getAncestor(IJavaElement.COMPILATION_UNIT);
					if (cu1 != null) {
						if (!cu1.equals(((IJavaElement)e2).getAncestor(IJavaElement.COMPILATION_UNIT)))
							return 0;
					} else {
						IClassFile cf1= (IClassFile)((IJavaElement)e1).getAncestor(IJavaElement.CLASS_FILE);
						if (cf1 == null)
							return 0;
						IClassFile cf2= (IClassFile)((IJavaElement)e2).getAncestor(IJavaElement.CLASS_FILE);
						String source1= cf1.getSource();
						if (source1 != null && !source1.equals(cf2.getSource()))
							return 0;
					}
				}
			} catch (JavaModelException e3) {
				return 0;
			}
	}

	try {
		ISourceRange sr1= ((ISourceReference)e1).getSourceRange();
		ISourceRange sr2= ((ISourceReference)e2).getSourceRange();
		if (sr1 == null || sr2 == null)
			return 0;

		return sr1.getOffset() - sr2.getOffset();

	} catch (JavaModelException e) {
		return 0;
	}
}
 
Example 15
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createCompilationUnitRewrite(final ITypeBinding[] parameters, final CompilationUnitRewrite targetRewrite, final Map<ICompilationUnit, SearchMatch[]> typeReferences, final Map<ICompilationUnit, SearchMatch[]> constructorReferences, boolean visibilityWasAdjusted, final ICompilationUnit sourceUnit, final ICompilationUnit targetUnit, final boolean remove, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(parameters);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(typeReferences);
	Assert.isNotNull(constructorReferences);
	Assert.isNotNull(sourceUnit);
	Assert.isNotNull(targetUnit);
	final CompilationUnit root= targetRewrite.getRoot();
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	if (targetUnit.equals(sourceUnit)) {
		final AbstractTypeDeclaration declaration= findTypeDeclaration(fType, root);
		final TextEditGroup qualifierGroup= fSourceRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_qualifier);
		ITypeBinding binding= declaration.resolveBinding();
		if (!remove) {
			if (!JdtFlags.isStatic(fType) && fCreateInstanceField) {
				if (JavaElementUtil.getAllConstructors(fType).length == 0)
					createConstructor(declaration, rewrite);
				else
					modifyConstructors(declaration, rewrite);
				addInheritedTypeQualifications(declaration, targetRewrite, qualifierGroup);
				addEnclosingInstanceDeclaration(declaration, rewrite);
			}
			fTypeImports= new HashSet<ITypeBinding>();
			fStaticImports= new HashSet<IBinding>();
			ImportRewriteUtil.collectImports(fType.getJavaProject(), declaration, fTypeImports, fStaticImports, false);
			if (binding != null)
				fTypeImports.remove(binding);
		}
		addEnclosingInstanceTypeParameters(parameters, declaration, rewrite);
		modifyAccessToEnclosingInstance(targetRewrite, declaration, monitor);
		if (binding != null) {
			modifyInterfaceMemberModifiers(binding);
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null)
				declaration.accept(new TypeReferenceQualifier(binding, null));
		}
		final TextEditGroup groupMove= targetRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_label);
		if (remove) {
			rewrite.remove(declaration, groupMove);
			targetRewrite.getImportRemover().registerRemovedNode(declaration);
		} else {
			// Bug 101017/96308: Rewrite the visibility of the element to be
			// moved and add a warning.

			// Note that this cannot be done in the MemberVisibilityAdjustor, as the private and
			// static flags must always be cleared when moving to new type.
			int newFlags= JdtFlags.clearFlag(Modifier.STATIC, declaration.getModifiers());

			if (!visibilityWasAdjusted) {
				if (Modifier.isPrivate(declaration.getModifiers()) || Modifier.isProtected(declaration.getModifiers())) {
					newFlags= JdtFlags.clearFlag(Modifier.PROTECTED | Modifier.PRIVATE, newFlags);
					final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(fSourceRewrite.getCu()));
					if (!containsStatusEntry(status, entry))
						status.addEntry(entry);
				}
			}

			ModifierRewrite.create(rewrite, declaration).setModifiers(newFlags, groupMove);
		}
	}
	ASTNode[] references= getReferenceNodesIn(root, typeReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateTypeReference(parameters, references[index], targetRewrite, targetUnit);
	references= getReferenceNodesIn(root, constructorReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateConstructorReference(parameters, references[index], targetRewrite, targetUnit);
}
 
Example 16
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private CompilationUnitRewrite getCompilationUnitRewrite(final ICompilationUnit unit) {
	Assert.isNotNull(unit);
	if (unit.equals(fType.getCompilationUnit()))
		return fSourceRewrite;
	return new CompilationUnitRewrite(unit);
}
 
Example 17
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus updateReferences(IType type, ParameterObjectFactory pof, IProgressMonitor pm) throws CoreException {
	RefactoringStatus status= new RefactoringStatus();
	pm.beginTask(RefactoringCoreMessages.ExtractClassRefactoring_progress_updating_references, 100);
	try {
		pm.worked(10);
		if (pm.isCanceled())
			throw new OperationCanceledException();
		List<IField> validIFields= new ArrayList<IField>();
		for (Iterator<FieldInfo> iterator= fVariables.values().iterator(); iterator.hasNext();) {
			FieldInfo info= iterator.next();
			if (isCreateField(info))
				validIFields.add(info.ifield);
		}
		if (validIFields.size() == 0) {
			status.addWarning(RefactoringCoreMessages.ExtractClassRefactoring_warning_no_fields_moved, JavaStatusContext.create(type));
			return status;
		}
		SearchPattern pattern= RefactoringSearchEngine.createOrPattern(validIFields.toArray(new IField[validIFields.size()]), IJavaSearchConstants.ALL_OCCURRENCES);
		SearchResultGroup[] results= RefactoringSearchEngine.search(pattern, RefactoringScopeFactory.create(type), pm, status);
		SubProgressMonitor spm= new SubProgressMonitor(pm, 90);
		spm.beginTask(RefactoringCoreMessages.ExtractClassRefactoring_progress_updating_references, results.length * 10);
		try {
			for (int i= 0; i < results.length; i++) {
				SearchResultGroup group= results[i];
				ICompilationUnit unit= group.getCompilationUnit();

				CompilationUnitRewrite cuRewrite;
				if (unit.equals(fBaseCURewrite.getCu()))
					cuRewrite= fBaseCURewrite;
				else
					cuRewrite= new CompilationUnitRewrite(unit);
				spm.worked(1);

				status.merge(replaceReferences(pof, group, cuRewrite));
				if (cuRewrite != fBaseCURewrite) //Change for fBaseCURewrite will be generated later
					fChangeManager.manage(unit, cuRewrite.createChange(true, new SubProgressMonitor(spm, 9)));
				if (spm.isCanceled())
					throw new OperationCanceledException();
			}
		} finally {
			spm.done();
		}
	} finally {
		pm.done();
	}
	return status;
}
 
Example 18
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender,
		List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig = org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(methodName, parameterTypes, false);
				boolean is18OrHigher= JavaModelUtil.is18OrHigher(targetCU.getJavaProject());

				boolean isSenderBindingInterface= senderDeclBinding.isInterface();
				if (nodeParentType == senderDeclBinding) {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
				} else {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
				}
				if (is18OrHigher || !isSenderBindingInterface
						|| (nodeParentType != senderDeclBinding && (!(sender instanceof SimpleName) || !((SimpleName) sender).getIdentifier().equals(senderDeclBinding.getName())))) {
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments,
							senderDeclBinding, IProposalRelevance.CREATE_METHOD));
				}

				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						isSenderBindingInterface= senderDeclBinding.isInterface();
						if (!senderDeclBinding.isAnonymous()) {
							if (is18OrHigher || !isSenderBindingInterface) {
								String[] args = new String[] { sig,
										org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) };
								label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
								proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode,
										arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD));
							}
						}
					}
				}
			}
		}
	}
}
 
Example 19
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	pm.beginTask(NO_NAME, 12);
	pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);

	RefactoringStatus result = new RefactoringStatus();
	fRewriter = ASTRewrite.create(fRoot.getAST());
	fChangeManager.clear();

	boolean usingLocalGetter = isUsingLocalGetter();
	boolean usingLocalSetter = isUsingLocalSetter();
	result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter));
	pm.worked(1);
	if (result.hasFatalError()) {
		return result;
	}
	pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
	final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
	ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result,
			true);

	checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
	if (result.hasFatalError()) {
		return result;
	}

	pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
	IProgressMonitor sub = new SubProgressMonitor(pm, 5);
	sub.beginTask(NO_NAME, affectedCUs.length);
	IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding();
	ITypeBinding declaringClass = ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class).resolveBinding();
	List<TextEditGroup> ownerDescriptions = new ArrayList<>();
	ICompilationUnit owner = fField.getCompilationUnit();
	fImportRewrite = StubUtility.createImportRewrite(fRoot, true);

	for (int i = 0; i < affectedCUs.length; i++) {
		ICompilationUnit unit = affectedCUs[i];
		sub.subTask(BasicElementLabels.getFileName(unit));
		CompilationUnit root = null;
		ASTRewrite rewriter = null;
		ImportRewrite importRewrite;
		List<TextEditGroup> descriptions;
		if (owner.equals(unit)) {
			root = fRoot;
			rewriter = fRewriter;
			importRewrite = fImportRewrite;
			descriptions = ownerDescriptions;
		} else {
			root = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(unit, true);
			rewriter = ASTRewrite.create(root.getAST());
			descriptions = new ArrayList<>();
			importRewrite = StubUtility.createImportRewrite(root, true);
		}
		checkCompileErrors(result, root, unit);
		AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
		root.accept(analyzer);
		result.merge(analyzer.getStatus());
		if (!fSetterMustReturnValue) {
			fSetterMustReturnValue= analyzer.getSetterMustReturnValue();
		}
		if (result.hasFatalError()) {
			fChangeManager.clear();
			return result;
		}
		descriptions.addAll(analyzer.getGroupDescriptions());
		if (!owner.equals(unit)) {
			createEdits(unit, rewriter, descriptions, importRewrite);
		}
		sub.worked(1);
		if (pm.isCanceled()) {
			throw new OperationCanceledException();
		}
	}
	ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter));
	createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);

	sub.done();
	IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
	result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext(), pm));
	if (result.hasFatalError()) {
		return result;
	}
	ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
	return result;
}
 
Example 20
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * @param unit
 * @return true iff the given <code>ICompilationUnit</code> is the unit
 * containing the original constructor
 */
private boolean isConstructorUnit(ICompilationUnit unit) {
	return unit.equals(ASTCreator.getCu(fCtorOwningClass));
}