use of com.intellij.util.containers.HashMap in project intellij-community by JetBrains.
the class MoveMembersProcessor method performRefactoring.
protected void performRefactoring(@NotNull final UsageInfo[] usages) {
try {
PsiClass targetClass = JavaPsiFacade.getInstance(myProject).findClass(myOptions.getTargetClassName(), GlobalSearchScope.projectScope(myProject));
if (targetClass == null)
return;
// collect anchors to place moved members at
final Map<PsiMember, SmartPsiElementPointer<PsiElement>> anchors = new HashMap<>();
final Map<PsiMember, PsiMember> anchorsInSourceClass = new HashMap<>();
for (PsiMember member : myMembersToMove) {
final MoveMemberHandler handler = MoveMemberHandler.EP_NAME.forLanguage(member.getLanguage());
if (handler != null) {
final PsiElement anchor = handler.getAnchor(member, targetClass, myMembersToMove);
if (anchor instanceof PsiMember && myMembersToMove.contains((PsiMember) anchor)) {
anchorsInSourceClass.put(member, (PsiMember) anchor);
} else {
anchors.put(member, anchor == null ? null : SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(anchor));
}
}
}
// correct references to moved members from the outside
ArrayList<MoveMembersUsageInfo> otherUsages = new ArrayList<>();
for (UsageInfo usageInfo : usages) {
MoveMembersUsageInfo usage = (MoveMembersUsageInfo) usageInfo;
if (!usage.reference.isValid())
continue;
final MoveMemberHandler handler = MoveMemberHandler.EP_NAME.forLanguage(usageInfo.getElement().getLanguage());
if (handler != null) {
if (handler.changeExternalUsage(myOptions, usage))
continue;
}
otherUsages.add(usage);
}
// correct references inside moved members and outer references to Inner Classes
final Map<PsiMember, PsiMember> movedMembers = new HashMap<>();
for (PsiMember member : myMembersToMove) {
ArrayList<PsiReference> refsToBeRebind = new ArrayList<>();
for (Iterator<MoveMembersUsageInfo> iterator = otherUsages.iterator(); iterator.hasNext(); ) {
MoveMembersUsageInfo info = iterator.next();
if (member.equals(info.member)) {
PsiReference ref = info.getReference();
if (ref != null) {
refsToBeRebind.add(ref);
}
iterator.remove();
}
}
final RefactoringElementListener elementListener = getTransaction().getElementListener(member);
final MoveMemberHandler handler = MoveMemberHandler.EP_NAME.forLanguage(member.getLanguage());
if (handler != null) {
final PsiElement anchor;
if (anchorsInSourceClass.containsKey(member)) {
final PsiMember memberInSourceClass = anchorsInSourceClass.get(member);
//anchor should be already moved as myMembersToMove contains members in order they appear in source class
anchor = memberInSourceClass != null ? movedMembers.get(memberInSourceClass) : null;
} else {
final SmartPsiElementPointer<PsiElement> pointer = anchors.get(member);
anchor = pointer != null ? pointer.getElement() : null;
}
PsiMember newMember = handler.doMove(myOptions, member, anchor, targetClass);
movedMembers.put(member, newMember);
elementListener.elementMoved(newMember);
fixModifierList(member, newMember, usages);
for (PsiReference reference : refsToBeRebind) {
reference.bindToElement(newMember);
}
}
}
// qualifier info must be decoded after members are moved
final MoveMemberHandler handler = MoveMemberHandler.EP_NAME.forLanguage(myTargetClass.getLanguage());
if (handler != null)
handler.decodeContextInfo(myTargetClass);
myMembersToMove.clear();
if (myMoveCallback != null) {
myMoveCallback.refactoringCompleted();
}
if (myOpenInEditor && !movedMembers.isEmpty()) {
final PsiMember item = ContainerUtil.getFirstItem(movedMembers.values());
if (item != null) {
EditorHelper.openInEditor(item);
}
}
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
use of com.intellij.util.containers.HashMap in project intellij-community by JetBrains.
the class GenerateEqualsHelper method createEquals.
private PsiMethod createEquals() throws IncorrectOperationException {
@NonNls StringBuilder buffer = new StringBuilder();
CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(myProject);
ArrayList<PsiField> equalsFields = new ArrayList<>();
ContainerUtil.addAll(equalsFields, myEqualsFields);
Collections.sort(equalsFields, EqualsFieldsComparator.INSTANCE);
final HashMap<String, Object> contextMap = new HashMap<>();
final PsiType classType = JavaPsiFacade.getElementFactory(myClass.getProject()).createType(myClass);
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(myClass.getProject());
String[] nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, null, classType).names;
String instanceBaseName = nameSuggestions.length > 0 && nameSuggestions[0].length() < 10 ? nameSuggestions[0] : "that";
contextMap.put(INSTANCE_NAME, instanceBaseName);
final PsiType objectType = PsiType.getJavaLangObject(myClass.getManager(), myClass.getResolveScope());
nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, objectType).names;
final String objectBaseName = nameSuggestions.length > 0 ? nameSuggestions[0] : "object";
contextMap.put(BASE_PARAM_NAME, objectBaseName);
final MethodSignature equalsSignature = getEqualsSignature(myProject, myClass.getResolveScope());
PsiMethod superEquals = MethodSignatureUtil.findMethodBySignature(myClass, equalsSignature, true);
if (superEquals != null) {
contextMap.put(SUPER_PARAM_NAME, superEquals.getParameterList().getParameters()[0].getName());
}
contextMap.put(SUPER_HAS_EQUALS, superMethodExists(equalsSignature));
contextMap.put(CHECK_PARAMETER_WITH_INSTANCEOF, myCheckParameterWithInstanceof);
final String methodText = GenerationUtil.velocityGenerateCode(myClass, equalsFields, myNonNullSet, new HashMap<>(), contextMap, EqualsHashCodeTemplatesManager.getInstance().getDefaultEqualsTemplate().getTemplate(), 0, false, myUseAccessors);
buffer.append(methodText);
PsiMethod result;
try {
result = myFactory.createMethodFromText(buffer.toString(), myClass);
} catch (IncorrectOperationException e) {
return null;
}
final PsiParameter[] parameters = result.getParameterList().getParameters();
if (parameters.length != 1)
return null;
final PsiParameter parameter = parameters[0];
PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, styleSettings.GENERATE_FINAL_PARAMETERS);
PsiMethod method = (PsiMethod) myCodeStyleManager.reformat(result);
if (superEquals != null) {
OverrideImplementUtil.annotateOnOverrideImplement(method, myClass, superEquals);
}
method = (PsiMethod) myJavaCodeStyleManager.shortenClassReferences(method);
return method;
}
use of com.intellij.util.containers.HashMap in project intellij-community by JetBrains.
the class InheritanceToDelegationProcessor method analyzeConflicts.
private void analyzeConflicts(UsageInfo[] usage, MultiMap<PsiElement, String> conflicts) {
HashMap<PsiElement, HashSet<PsiElement>> reportedNonDelegatedUsages = new HashMap<>();
HashMap<PsiClass, HashSet<PsiElement>> reportedUpcasts = new HashMap<>();
// HashSet reportedObjectUpcasts = new HashSet();
// final String nameJavaLangObject = ConflictsUtil.htmlEmphasize("java.lang.Object");
final String classDescription = RefactoringUIUtil.getDescription(myClass, false);
for (UsageInfo aUsage : usage) {
final PsiElement element = aUsage.getElement();
if (aUsage instanceof InheritanceToDelegationUsageInfo) {
InheritanceToDelegationUsageInfo usageInfo = (InheritanceToDelegationUsageInfo) aUsage;
/*if (usageInfo instanceof ObjectUpcastedUsageInfo) {
PsiElement container = ConflictsUtil.getContainer(usageInfo.element);
if (!reportedObjectUpcasts.contains(container)) {
String message = "An instance of " + classDescription + " is upcasted to "
+ nameJavaLangObject + " in " + ConflictsUtil.getDescription(container, true) + ".";
conflicts.add(message);
reportedObjectUpcasts.add(container);
}
} else*/
if (!myIsDelegateOtherMembers && !usageInfo.getDelegateFieldAccessible().isAccessible()) {
if (usageInfo instanceof NonDelegatedMemberUsageInfo) {
final PsiElement nonDelegatedMember = ((NonDelegatedMemberUsageInfo) usageInfo).nonDelegatedMember;
HashSet<PsiElement> reportedContainers = reportedNonDelegatedUsages.get(nonDelegatedMember);
if (reportedContainers == null) {
reportedContainers = new HashSet<>();
reportedNonDelegatedUsages.put(nonDelegatedMember, reportedContainers);
}
final PsiElement container = ConflictsUtil.getContainer(element);
if (!reportedContainers.contains(container)) {
String message = RefactoringBundle.message("0.uses.1.of.an.instance.of.a.2", RefactoringUIUtil.getDescription(container, true), RefactoringUIUtil.getDescription(nonDelegatedMember, true), classDescription);
conflicts.putValue(container, CommonRefactoringUtil.capitalize(message));
reportedContainers.add(container);
}
} else if (usageInfo instanceof UpcastedUsageInfo) {
final PsiClass upcastedTo = ((UpcastedUsageInfo) usageInfo).upcastedTo;
HashSet<PsiElement> reportedContainers = reportedUpcasts.get(upcastedTo);
if (reportedContainers == null) {
reportedContainers = new HashSet<>();
reportedUpcasts.put(upcastedTo, reportedContainers);
}
final PsiElement container = ConflictsUtil.getContainer(element);
if (!reportedContainers.contains(container)) {
String message = RefactoringBundle.message("0.upcasts.an.instance.of.1.to.2", RefactoringUIUtil.getDescription(container, true), classDescription, RefactoringUIUtil.getDescription(upcastedTo, false));
conflicts.putValue(container, CommonRefactoringUtil.capitalize(message));
reportedContainers.add(container);
}
}
}
} else if (aUsage instanceof NoLongerOverridingSubClassMethodUsageInfo) {
NoLongerOverridingSubClassMethodUsageInfo info = (NoLongerOverridingSubClassMethodUsageInfo) aUsage;
String message = RefactoringBundle.message("0.will.no.longer.override.1", RefactoringUIUtil.getDescription(info.getSubClassMethod(), true), RefactoringUIUtil.getDescription(info.getOverridenMethod(), true));
conflicts.putValue(info.getSubClassMethod(), message);
}
}
}
use of com.intellij.util.containers.HashMap in project intellij-community by JetBrains.
the class InlineMethodProcessor method getInaccessible.
/**
* Given a set of referencedElements, returns a map from containers (in a sense of ConflictsUtil.getContainer)
* to subsets of referencedElemens that are not accessible from that container
*
* @param referencedElements
* @param usages
* @param elementToInline
*/
private static Map<PsiMember, Set<PsiMember>> getInaccessible(HashSet<PsiMember> referencedElements, UsageInfo[] usages, PsiElement elementToInline) {
final Map<PsiMember, Set<PsiMember>> result = new HashMap<>();
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(elementToInline.getProject()).getResolveHelper();
for (UsageInfo usage : usages) {
final PsiElement usageElement = usage.getElement();
if (usageElement == null)
continue;
final PsiElement container = ConflictsUtil.getContainer(usageElement);
// usage in import statement
if (!(container instanceof PsiMember))
continue;
PsiMember memberContainer = (PsiMember) container;
Set<PsiMember> inaccessibleReferenced = result.get(memberContainer);
if (inaccessibleReferenced == null) {
inaccessibleReferenced = new HashSet<>();
result.put(memberContainer, inaccessibleReferenced);
for (PsiMember member : referencedElements) {
if (PsiTreeUtil.isAncestor(elementToInline, member, false))
continue;
if (elementToInline instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass) elementToInline, member.getContainingClass(), true))
continue;
PsiElement resolveScope = usageElement instanceof PsiReferenceExpression ? ((PsiReferenceExpression) usageElement).advancedResolve(false).getCurrentFileResolveScope() : null;
if (!resolveHelper.isAccessible(member, member.getModifierList(), usageElement, null, resolveScope)) {
inaccessibleReferenced.add(member);
}
}
}
}
return result;
}
use of com.intellij.util.containers.HashMap in project intellij-community by JetBrains.
the class ModulesConfigurator method apply.
public void apply() throws ConfigurationException {
// validate content and source roots
final Map<VirtualFile, String> contentRootToModuleNameMap = new HashMap<>();
final Map<VirtualFile, VirtualFile> srcRootsToContentRootMap = new HashMap<>();
for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
final ModifiableRootModel rootModel = moduleEditor.getModifiableRootModel();
final ContentEntry[] contents = rootModel.getContentEntries();
final String moduleName = moduleEditor.getName();
Set<VirtualFile> sourceRoots = new HashSet<>();
for (ContentEntry content : contents) {
for (VirtualFile root : content.getSourceFolderFiles()) {
if (!sourceRoots.add(root)) {
throw new ConfigurationException(ProjectBundle.message("module.paths.validation.duplicate.source.root.in.same.module.error", root.getPresentableUrl(), moduleName));
}
}
}
for (ContentEntry contentEntry : contents) {
final VirtualFile contentRoot = contentEntry.getFile();
if (contentRoot == null) {
continue;
}
final String previousName = contentRootToModuleNameMap.put(contentRoot, moduleName);
if (previousName != null && !previousName.equals(moduleName)) {
throw new ConfigurationException(ProjectBundle.message("module.paths.validation.duplicate.content.error", contentRoot.getPresentableUrl(), previousName, moduleName));
}
for (VirtualFile srcRoot : contentEntry.getSourceFolderFiles()) {
final VirtualFile anotherContentRoot = srcRootsToContentRootMap.put(srcRoot, contentRoot);
if (anotherContentRoot != null) {
final String problematicModule;
final String correctModule;
if (VfsUtilCore.isAncestor(anotherContentRoot, contentRoot, true)) {
problematicModule = contentRootToModuleNameMap.get(anotherContentRoot);
correctModule = contentRootToModuleNameMap.get(contentRoot);
} else {
problematicModule = contentRootToModuleNameMap.get(contentRoot);
correctModule = contentRootToModuleNameMap.get(anotherContentRoot);
}
throw new ConfigurationException(ProjectBundle.message("module.paths.validation.duplicate.source.root.error", problematicModule, srcRoot.getPresentableUrl(), correctModule));
}
}
}
}
// additional validation: directories marked as src roots must belong to the same module as their corresponding content root
for (Map.Entry<VirtualFile, VirtualFile> entry : srcRootsToContentRootMap.entrySet()) {
final VirtualFile srcRoot = entry.getKey();
final VirtualFile correspondingContent = entry.getValue();
final String expectedModuleName = contentRootToModuleNameMap.get(correspondingContent);
for (VirtualFile candidateContent = srcRoot; candidateContent != null && !candidateContent.equals(correspondingContent); candidateContent = candidateContent.getParent()) {
final String moduleName = contentRootToModuleNameMap.get(candidateContent);
if (moduleName != null && !moduleName.equals(expectedModuleName)) {
throw new ConfigurationException(ProjectBundle.message("module.paths.validation.source.root.belongs.to.another.module.error", srcRoot.getPresentableUrl(), expectedModuleName, moduleName));
}
}
}
for (ModuleEditor moduleEditor : myModuleEditors.values()) {
moduleEditor.canApply();
}
final Map<Sdk, Sdk> modifiedToOriginalMap = new THashMap<>();
final ProjectSdksModel projectJdksModel = ProjectStructureConfigurable.getInstance(myProject).getProjectJdksModel();
for (Map.Entry<Sdk, Sdk> entry : projectJdksModel.getProjectSdks().entrySet()) {
modifiedToOriginalMap.put(entry.getValue(), entry.getKey());
}
final Ref<ConfigurationException> exceptionRef = Ref.create();
ApplicationManager.getApplication().runWriteAction(() -> {
final List<ModifiableRootModel> models = new ArrayList<>(myModuleEditors.size());
try {
for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
final ModifiableRootModel model = moduleEditor.apply();
if (model != null) {
if (!model.isSdkInherited()) {
// make sure the sdk is set to original SDK stored in the JDK Table
final Sdk modelSdk = model.getSdk();
if (modelSdk != null) {
final Sdk original = modifiedToOriginalMap.get(modelSdk);
if (original != null) {
model.setSdk(original);
}
}
}
models.add(model);
}
}
myFacetsConfigurator.applyEditors();
} catch (ConfigurationException e) {
exceptionRef.set(e);
return;
}
try {
ModifiableModelCommitter.multiCommit(models, myModuleModel);
myModuleModelCommitted = true;
myFacetsConfigurator.commitFacets();
} finally {
ModuleStructureConfigurable.getInstance(myProject).getFacetEditorFacade().clearMaps(false);
myFacetsConfigurator = createFacetsConfigurator();
myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel();
myModuleModelCommitted = false;
}
});
if (!exceptionRef.isNull()) {
throw exceptionRef.get();
}
myModified = false;
}
Aggregations