@Override protected void collectAdditionalElementsToRename(List<Pair<PsiElement, TextRange>> stringUsages) { if (isReplaceAllOccurrences()) { for (E expression : getOccurrences()) { LOG.assertTrue(expression.isValid(), expression.getText()); stringUsages.add( Pair.<PsiElement, TextRange>create( expression, new TextRange(0, expression.getTextLength()))); } } else if (getExpr() != null) { correctExpression(); final E expr = getExpr(); LOG.assertTrue(expr.isValid(), expr.getText()); stringUsages.add( Pair.<PsiElement, TextRange>create(expr, new TextRange(0, expr.getTextLength()))); } final V localVariable = getLocalVariable(); if (localVariable != null) { final PsiElement nameIdentifier = localVariable.getNameIdentifier(); if (nameIdentifier != null) { int length = nameIdentifier.getTextLength(); stringUsages.add( Pair.<PsiElement, TextRange>create(nameIdentifier, new TextRange(0, length))); } } }
public static MultiMap<PsiElement, UsageInfo> classifyUsages( Collection<? extends PsiElement> elements, UsageInfo[] usages) { final MultiMap<PsiElement, UsageInfo> result = new MultiMap<PsiElement, UsageInfo>(); for (UsageInfo usage : usages) { LOG.assertTrue(usage instanceof MoveRenameUsageInfo); if (usage.getReference() instanceof LightElement) { continue; // filter out implicit references (e.g. from derived class to super class' default // constructor) } MoveRenameUsageInfo usageInfo = (MoveRenameUsageInfo) usage; if (usage instanceof RelatedUsageInfo) { final PsiElement relatedElement = ((RelatedUsageInfo) usage).getRelatedElement(); if (elements.contains(relatedElement)) { result.putValue(relatedElement, usage); } } else { PsiElement referenced = usageInfo.getReferencedElement(); if (elements.contains(referenced)) { result.putValue(referenced, usage); } else if (referenced != null) { PsiElement indirect = referenced.getNavigationElement(); if (elements.contains(indirect)) { result.putValue(indirect, usage); } } } } return result; }
public static boolean validElement(@NotNull PsiElement element) { if (element instanceof PsiFile) return true; if (!element.isPhysical()) return false; final RefactoringSupportProvider provider = LanguageRefactoringSupport.INSTANCE.forLanguage(element.getLanguage()); return provider.isSafeDeleteAvailable(element); }
private void processUsagesPerFile(UsageInfo[] usages) { Map<PsiFile, List<EncapsulateFieldUsageInfo>> usagesInFiles = new HashMap<PsiFile, List<EncapsulateFieldUsageInfo>>(); for (UsageInfo usage : usages) { PsiElement element = usage.getElement(); if (element == null) continue; final PsiFile file = element.getContainingFile(); List<EncapsulateFieldUsageInfo> usagesInFile = usagesInFiles.get(file); if (usagesInFile == null) { usagesInFile = new ArrayList<EncapsulateFieldUsageInfo>(); usagesInFiles.put(file, usagesInFile); } usagesInFile.add(((EncapsulateFieldUsageInfo) usage)); } for (List<EncapsulateFieldUsageInfo> usageInfos : usagesInFiles.values()) { // this is to avoid elements to become invalid as a result of processUsage final EncapsulateFieldUsageInfo[] infos = usageInfos.toArray(new EncapsulateFieldUsageInfo[usageInfos.size()]); CommonRefactoringUtil.sortDepthFirstRightLeftOrder(infos); for (EncapsulateFieldUsageInfo info : infos) { EncapsulateFieldHelper helper = EncapsulateFieldHelper.getHelper(info.getElement().getLanguage()); helper.processUsage( info, myDescriptor, myNameToSetter.get(info.getFieldDescriptor().getSetterName()), myNameToGetter.get(info.getFieldDescriptor().getGetterName())); } } }
private void fixReferencesToStatic(PsiElement classMember) throws IncorrectOperationException { final StaticReferencesCollector collector = new StaticReferencesCollector(); classMember.accept(collector); ArrayList<PsiJavaCodeReferenceElement> refs = collector.getReferences(); ArrayList<PsiElement> members = collector.getReferees(); ArrayList<PsiClass> classes = collector.getRefereeClasses(); PsiElementFactory factory = JavaPsiFacade.getInstance(classMember.getProject()).getElementFactory(); for (int i = 0; i < refs.size(); i++) { PsiJavaCodeReferenceElement ref = refs.get(i); PsiElement namedElement = members.get(i); PsiClass aClass = classes.get(i); if (namedElement instanceof PsiNamedElement) { PsiReferenceExpression newRef = (PsiReferenceExpression) factory.createExpressionFromText( "a." + ((PsiNamedElement) namedElement).getName(), null); PsiExpression qualifierExpression = newRef.getQualifierExpression(); assert qualifierExpression != null; qualifierExpression = (PsiExpression) qualifierExpression.replace(factory.createReferenceExpression(aClass)); qualifierExpression.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified()); ref.replace(newRef); } } }
private static PsiElement getNextElement(PsiElement element) { PsiElement sibling = element.getNextSibling(); if (sibling != null) return sibling; element = element.getParent(); if (element != null) return getNextElement(element); return null; }
@Override @Nullable public Collection<PsiImportStatementBase> findRedundantImports(final PsiJavaFile file) { final PsiImportList importList = file.getImportList(); if (importList == null) return null; final PsiImportStatementBase[] imports = importList.getAllImportStatements(); if (imports.length == 0) return null; Set<PsiImportStatementBase> allImports = new THashSet<PsiImportStatementBase>(Arrays.asList(imports)); final Collection<PsiImportStatementBase> redundant; if (FileTypeUtils.isInServerPageFile(file)) { // remove only duplicate imports redundant = ContainerUtil.newIdentityTroveSet(); ContainerUtil.addAll(redundant, imports); redundant.removeAll(allImports); for (PsiImportStatementBase importStatement : imports) { if (importStatement instanceof JspxImportStatement && importStatement.isForeignFileImport()) { redundant.remove(importStatement); } } } else { redundant = allImports; final List<PsiFile> roots = file.getViewProvider().getAllFiles(); for (PsiElement root : roots) { root.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { if (!reference.isQualified()) { final JavaResolveResult resolveResult = reference.advancedResolve(false); if (!inTheSamePackage(file, resolveResult.getElement())) { final PsiElement resolveScope = resolveResult.getCurrentFileResolveScope(); if (resolveScope instanceof PsiImportStatementBase) { final PsiImportStatementBase importStatementBase = (PsiImportStatementBase) resolveScope; redundant.remove(importStatementBase); } } } super.visitReferenceElement(reference); } private boolean inTheSamePackage(PsiJavaFile file, PsiElement element) { if (element instanceof PsiClass && ((PsiClass) element).getContainingClass() == null) { final PsiFile containingFile = element.getContainingFile(); if (containingFile instanceof PsiJavaFile) { return Comparing.strEqual( file.getPackageName(), ((PsiJavaFile) containingFile).getPackageName()); } } return false; } }); } } return redundant; }
@Override protected void previewRefactoring(@NotNull final UsageInfo[] usages) { MigrationPanel panel = new MigrationPanel(myRoot, myLabeler, myProject, isPreviewUsages()); String name; if (myRoot.length == 1) { String fromType = assertNotNull(TypeMigrationLabeler.getElementType(myRoot[0])).getPresentableText(); String toType = myRootTypes.fun(myRoot[0]).getPresentableText(); String text; text = getPresentation(myRoot[0]); name = "Migrate Type of " + text + " from \'" + fromType + "\' to \'" + toType + "\'"; } else { final int rootsInPresentationCount = myRoot.length > MAX_ROOT_IN_PREVIEW_PRESENTATION ? MAX_ROOT_IN_PREVIEW_PRESENTATION : myRoot.length; String[] rootsPresentation = new String[rootsInPresentationCount]; for (int i = 0; i < rootsInPresentationCount; i++) { final PsiElement root = myRoot[i]; rootsPresentation[i] = root instanceof PsiNamedElement ? ((PsiNamedElement) root).getName() : root.getText(); } rootsPresentation = StringUtil.surround(rootsPresentation, "\'", "\'"); name = "Migrate Type of " + StringUtil.join(rootsPresentation, ", "); if (myRoot.length > MAX_ROOT_IN_PREVIEW_PRESENTATION) { name += "..."; } } Content content = UsageViewManager.getInstance(myProject).addContent(name, false, panel, true, true); panel.setContent(content); ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.FIND).activate(null); }
private static Condition<PsiElement> findFieldUsages( final PsiField psiField, final List<UsageInfo> usages, final PsiElement[] allElementsToDelete) { final Condition<PsiElement> isInsideDeleted = getUsageInsideDeletedFilter(allElementsToDelete); ReferencesSearch.search(psiField) .forEach( reference -> { if (!isInsideDeleted.value(reference.getElement())) { final PsiElement element = reference.getElement(); final PsiElement parent = element.getParent(); if (parent instanceof PsiAssignmentExpression && element == ((PsiAssignmentExpression) parent).getLExpression()) { usages.add( new SafeDeleteFieldWriteReference( (PsiAssignmentExpression) parent, psiField)); } else { TextRange range = reference.getRangeInElement(); usages.add( new SafeDeleteReferenceJavaDeleteUsageInfo( reference.getElement(), psiField, range.getStartOffset(), range.getEndOffset(), false, PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class) != null)); } } return true; }); return isInsideDeleted; }
@Nullable public static JetElement getEnclosingElementForLocalDeclaration( @Nullable JetNamedDeclaration declaration) { if (declaration instanceof JetTypeParameter) { declaration = PsiTreeUtil.getParentOfType(declaration, JetNamedDeclaration.class); } else if (declaration instanceof JetParameter) { PsiElement parent = declaration.getParent(); if (parent != null && parent.getParent() instanceof JetNamedFunction) { declaration = (JetNamedFunction) parent.getParent(); } } //noinspection unchecked JetElement container = PsiTreeUtil.getParentOfType( declaration, JetBlockExpression.class, JetClassInitializer.class, JetProperty.class, JetFunction.class, JetParameter.class); if (container == null) return null; return (container instanceof JetClassInitializer) ? ((JetClassInitializer) container).getBody() : container; }
@Nullable public static JetClassOrObject getOutermostClassOrObject( @NotNull JetClassOrObject classOrObject) { JetClassOrObject current = classOrObject; while (true) { PsiElement parent = current.getParent(); assert classOrObject.getParent() != null : "Class with no parent: " + classOrObject.getText(); if (parent instanceof PsiFile) { return current; } if (parent instanceof JetClassObject) { // current class IS the class object declaration parent = parent.getParent(); assert parent instanceof JetClassBody : "Parent of class object is not a class body: " + parent; } if (!(parent instanceof JetClassBody)) { // It is a local class, no legitimate outer return current; } current = (JetClassOrObject) parent.getParent(); } }
@NotNull public static String getElementTextWithContext(@NotNull JetElement element) { if (element instanceof JetFile) { return element.getContainingFile().getText(); } // Find parent for element among file children PsiElement inFileParent = PsiTreeUtil.findFirstParent( element, new Condition<PsiElement>() { @Override public boolean value(PsiElement parentCandidate) { return parentCandidate != null && parentCandidate.getParent() instanceof JetFile; } }); assert inFileParent != null : "For non-file element we should always be able to find parent in file children"; int startContextOffset = inFileParent.getTextRange().getStartOffset(); int elementContextOffset = element.getTextRange().getStartOffset(); int inFileParentOffset = elementContextOffset - startContextOffset; return new StringBuilder(inFileParent.getText()) .insert(inFileParentOffset, "<caret>") .toString(); }
@Override public final void actionPerformed(final AnActionEvent event) { final DataContext dataContext = event.getDataContext(); final HierarchyBrowserBaseEx browser = (HierarchyBrowserBaseEx) dataContext.getData(myBrowserDataKey); if (browser == null) return; final PsiElement selectedElement = browser.getSelectedElement(); if (selectedElement == null || !browser.isApplicableElement(selectedElement)) return; final String currentViewType = browser.myCurrentViewType; Disposer.dispose(browser); final HierarchyProvider provider = BrowseHierarchyActionBase.findProvider( myProviderLanguageExtension, selectedElement, selectedElement.getContainingFile(), event.getDataContext()); final HierarchyBrowser newBrowser = BrowseHierarchyActionBase.createAndAddToPanel( selectedElement.getProject(), provider, selectedElement); ApplicationManager.getApplication() .invokeLater( () -> ((HierarchyBrowserBaseEx) newBrowser) .changeView(correctViewType(browser, currentViewType))); }
protected void restoreState(@NotNull final V psiField) { if (!ReadonlyStatusHandler.ensureDocumentWritable( myProject, InjectedLanguageUtil.getTopLevelEditor(myEditor).getDocument())) return; ApplicationManager.getApplication() .runWriteAction( () -> { final PsiFile containingFile = psiField.getContainingFile(); final RangeMarker exprMarker = getExprMarker(); if (exprMarker != null) { myExpr = restoreExpression(containingFile, psiField, exprMarker, myExprText); } if (myLocalMarker != null) { final PsiElement refVariableElement = containingFile.findElementAt(myLocalMarker.getStartOffset()); if (refVariableElement != null) { final PsiElement parent = refVariableElement.getParent(); if (parent instanceof PsiNamedElement) { ((PsiNamedElement) parent).setName(myLocalName); } } final V localVariable = getLocalVariable(); if (localVariable != null && localVariable.isPhysical()) { myLocalVariable = localVariable; final PsiElement nameIdentifier = localVariable.getNameIdentifier(); if (nameIdentifier != null) { myLocalMarker = createMarker(nameIdentifier); } } } final List<RangeMarker> occurrenceMarkers = getOccurrenceMarkers(); for (int i = 0, occurrenceMarkersSize = occurrenceMarkers.size(); i < occurrenceMarkersSize; i++) { RangeMarker marker = occurrenceMarkers.get(i); if (getExprMarker() != null && marker.getStartOffset() == getExprMarker().getStartOffset() && myExpr != null) { myOccurrences[i] = myExpr; continue; } final E psiExpression = restoreExpression( containingFile, psiField, marker, getLocalVariable() != null ? myLocalName : myExprText); if (psiExpression != null) { myOccurrences[i] = psiExpression; } } if (myExpr != null && myExpr.isPhysical()) { myExprMarker = createMarker(myExpr); } myOccurrenceMarkers = null; deleteTemplateField(psiField); }); }
public static void initOffsets(final PsiFile file, final OffsetMap offsetMap) { int offset = Math.max( offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET), offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET)); PsiElement element = file.findElementAt(offset); if (element instanceof PsiWhiteSpace && (!element.textContains('\n') || CodeStyleSettingsManager.getSettings(file.getProject()) .getCommonSettings(JavaLanguage.INSTANCE) .METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE)) { element = file.findElementAt(element.getTextRange().getEndOffset()); } if (element == null) return; if (LEFT_PAREN.accepts(element)) { offsetMap.addOffset(LPAREN_OFFSET, element.getTextRange().getStartOffset()); PsiElement list = element.getParent(); PsiElement last = list.getLastChild(); if (last instanceof PsiJavaToken && ((PsiJavaToken) last).getTokenType() == JavaTokenType.RPARENTH) { offsetMap.addOffset(RPAREN_OFFSET, last.getTextRange().getStartOffset()); } offsetMap.addOffset(ARG_LIST_END_OFFSET, list.getTextRange().getEndOffset()); } }
@Nullable public static ArrayCreationExpression getCompletableArrayCreationElement(PsiElement psiElement) { // array('<test>' => '') if (PhpPatterns.psiElement(PhpElementTypes.ARRAY_KEY).accepts(psiElement.getContext())) { PsiElement arrayKey = psiElement.getContext(); if (arrayKey != null) { PsiElement arrayHashElement = arrayKey.getContext(); if (arrayHashElement instanceof ArrayHashElement) { PsiElement arrayCreationExpression = arrayHashElement.getContext(); if (arrayCreationExpression instanceof ArrayCreationExpression) { return (ArrayCreationExpression) arrayCreationExpression; } } } } // on array creation key dont have value, so provide completion here also // array('foo' => 'bar', '<test>') if (PhpPatterns.psiElement(PhpElementTypes.ARRAY_VALUE).accepts(psiElement.getContext())) { PsiElement arrayKey = psiElement.getContext(); if (arrayKey != null) { PsiElement arrayCreationExpression = arrayKey.getContext(); if (arrayCreationExpression instanceof ArrayCreationExpression) { return (ArrayCreationExpression) arrayCreationExpression; } } } return null; }
public static TextWithImports getEditorText(final Editor editor) { if (editor == null) { return null; } final Project project = editor.getProject(); if (project == null) return null; String defaultExpression = editor.getSelectionModel().getSelectedText(); if (defaultExpression == null) { int offset = editor.getCaretModel().getOffset(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { PsiElement elementAtCursor = psiFile.findElementAt(offset); if (elementAtCursor != null) { final EditorTextProvider textProvider = EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage()); if (textProvider != null) { final TextWithImports editorText = textProvider.getEditorText(elementAtCursor); if (editorText != null) return editorText; } } } } else { return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression); } return null; }
/** * Get array string values mapped with their PsiElements * * <p>["value", "value2"] */ @NotNull public static Map<String, PsiElement> getArrayValuesAsMap( @NotNull ArrayCreationExpression arrayCreationExpression) { List<PsiElement> arrayValues = PhpPsiUtil.getChildren( arrayCreationExpression, new Condition<PsiElement>() { @Override public boolean value(PsiElement psiElement) { return psiElement.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE; } }); if (arrayValues == null) { return Collections.emptyMap(); } Map<String, PsiElement> keys = new HashMap<String, PsiElement>(); for (PsiElement child : arrayValues) { String stringValue = PhpElementsUtil.getStringValue(child.getFirstChild()); if (stringValue != null && StringUtils.isNotBlank(stringValue)) { keys.put(stringValue, child); } } return keys; }
public boolean commitTransaction(final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document); if (documentChangeTransaction == null) return false; final PsiElement changeScope = documentChangeTransaction.getChangeScope(); try { mySyncDocument = document; final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager()); fakeEvent.setParent(changeScope); fakeEvent.setFile(changeScope.getContainingFile()); doSync( fakeEvent, true, new DocSyncAction() { @Override public void syncDocument(Document document, PsiTreeChangeEventImpl event) { doCommitTransaction(document, documentChangeTransaction); } }); myBus .syncPublisher(PsiDocumentTransactionListener.TOPIC) .transactionCompleted(document, (PsiFile) changeScope); } finally { mySyncDocument = null; } return true; }
private void findUsagesForMethod(PsiMethod method, List<FixableUsageInfo> usages) { final PsiManager psiManager = method.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope); for (PsiReference reference : calls) { final PsiElement referenceElement = reference.getElement(); final PsiElement parent = referenceElement.getParent(); if (parent instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression) parent; if (isInMovedElement(call)) { continue; } final PsiReferenceExpression methodExpression = call.getMethodExpression(); final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (qualifier == null || qualifier instanceof PsiThisExpression) { usages.add(new ReplaceThisCallWithDelegateCall(call, delegateFieldName)); } delegationRequired = true; } } if (!delegationRequired && MethodInheritanceUtils.hasSiblingMethods(method)) { delegationRequired = true; } if (delegationRequired) { usages.add(new MakeMethodDelegate(method, delegateFieldName)); } else { usages.add(new RemoveMethod(method)); } }
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) { final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); checkExistingMethods(conflicts, true); checkExistingMethods(conflicts, false); final Collection<PsiClass> classes = ClassInheritorsSearch.search(myClass).findAll(); for (FieldDescriptor fieldDescriptor : myFieldDescriptors) { final Set<PsiMethod> setters = new HashSet<PsiMethod>(); final Set<PsiMethod> getters = new HashSet<PsiMethod>(); for (PsiClass aClass : classes) { final PsiMethod getterOverrider = myDescriptor.isToEncapsulateGet() ? aClass.findMethodBySignature(fieldDescriptor.getGetterPrototype(), false) : null; if (getterOverrider != null) { getters.add(getterOverrider); } final PsiMethod setterOverrider = myDescriptor.isToEncapsulateSet() ? aClass.findMethodBySignature(fieldDescriptor.getSetterPrototype(), false) : null; if (setterOverrider != null) { setters.add(setterOverrider); } } if (!getters.isEmpty() || !setters.isEmpty()) { final PsiField field = fieldDescriptor.getField(); for (PsiReference reference : ReferencesSearch.search(field)) { final PsiElement place = reference.getElement(); if (place instanceof PsiReferenceExpression) { final PsiExpression qualifierExpression = ((PsiReferenceExpression) place).getQualifierExpression(); final PsiClass ancestor; if (qualifierExpression == null) { ancestor = PsiTreeUtil.getParentOfType(place, PsiClass.class, false); } else { ancestor = PsiUtil.resolveClassInType(qualifierExpression.getType()); } final boolean isGetter = !PsiUtil.isAccessedForWriting((PsiExpression) place); for (PsiMethod overridden : isGetter ? getters : setters) { if (InheritanceUtil.isInheritorOrSelf(myClass, ancestor, true)) { conflicts.putValue( overridden, "There is already a " + RefactoringUIUtil.getDescription(overridden, true) + " which would hide generated " + (isGetter ? "getter" : "setter") + " for " + place.getText()); break; } } } } } } return showConflicts(conflicts, refUsages.get()); }
private void findUsagesForStaticMethod(PsiMethod method, List<FixableUsageInfo> usages) { final PsiManager psiManager = method.getManager(); final Project project = psiManager.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope); final String fullyQualifiedName = getQualifiedName(); for (PsiReference reference : calls) { final PsiElement referenceElement = reference.getElement(); final PsiElement parent = referenceElement.getParent(); if (parent instanceof PsiMethodCallExpression) { final PsiMethodCallExpression call = (PsiMethodCallExpression) parent; if (!isInMovedElement(call)) { usages.add(new RetargetStaticMethodCall(call, fullyQualifiedName)); } } else if (parent instanceof PsiImportStaticStatement) { final PsiJavaCodeReferenceElement importReference = ((PsiImportStaticStatement) parent).getImportReference(); if (importReference != null) { final PsiElement qualifier = importReference.getQualifier(); if (qualifier instanceof PsiJavaCodeReferenceElement) { usages.add( new ReplaceClassReference( (PsiJavaCodeReferenceElement) qualifier, fullyQualifiedName)); } } } } usages.add(new RemoveMethod(method)); }
public static boolean isValidName( final Project project, final PsiElement psiElement, final String newName) { if (newName == null || newName.length() == 0) { return false; } final Condition<String> inputValidator = RenameInputValidatorRegistry.getInputValidator(psiElement); if (inputValidator != null) { return inputValidator.value(newName); } if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) { return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0; } if (psiElement instanceof PomTargetPsiElement) { return !StringUtil.isEmptyOrSpaces(newName); } final PsiFile file = psiElement.getContainingFile(); final Language elementLanguage = psiElement.getLanguage(); final Language fileLanguage = file == null ? null : file.getLanguage(); Language language = fileLanguage == null ? elementLanguage : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage; return LanguageNamesValidation.INSTANCE .forLanguage(language) .isIdentifier(newName.trim(), project); }
private void handleBranchingInstruction( ProblemsHolder holder, StandardInstructionVisitor visitor, Set<Instruction> trueSet, Set<Instruction> falseSet, HashSet<PsiElement> reportedAnchors, BranchingInstruction instruction, final boolean onTheFly) { PsiElement psiAnchor = instruction.getPsiAnchor(); boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor); if (instruction instanceof InstanceofInstruction && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) { if (visitor.canBeNull((BinopInstruction) instruction)) { holder.registerProblem( psiAnchor, InspectionsBundle.message("dataflow.message.redundant.instanceof"), new RedundantInstanceofFix()); } else { final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true); holder.registerProblem( psiAnchor, InspectionsBundle.message( underBinary ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(true)), localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix}); } } else if (psiAnchor instanceof PsiSwitchLabelStatement) { if (falseSet.contains(instruction)) { holder.registerProblem( psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label")); } } else if (psiAnchor != null && !reportedAnchors.contains(psiAnchor) && !isFlagCheck(psiAnchor)) { boolean evaluatesToTrue = trueSet.contains(instruction); final PsiElement parent = psiAnchor.getParent(); if (parent instanceof PsiAssignmentExpression && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) { holder.registerProblem( psiAnchor, InspectionsBundle.message( "dataflow.message.pointless.assignment.expression", Boolean.toString(evaluatesToTrue)), createConditionalAssignmentFixes( evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly)); } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) { final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue); String message = InspectionsBundle.message( underBinary ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(evaluatesToTrue)); holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix}); } reportedAnchors.add(psiAnchor); } }
@Nullable private static PsiClass getFieldOrMethodAccessedClass( PsiReferenceExpression ref, PsiClass fieldOrMethodClass) { PsiElement[] children = ref.getChildren(); if (children.length > 1 && children[0] instanceof PsiExpression) { PsiExpression expr = (PsiExpression) children[0]; PsiType type = expr.getType(); if (type != null) { if (!(type instanceof PsiClassType)) return null; return PsiUtil.resolveClassInType(type); } else { if (expr instanceof PsiReferenceExpression) { PsiElement refElement = ((PsiReferenceExpression) expr).resolve(); if (refElement instanceof PsiClass) return (PsiClass) refElement; } return null; } } PsiManager manager = ref.getManager(); for (PsiElement parent = ref; parent != null; parent = parent.getParent()) { if (parent instanceof PsiClass && (manager.areElementsEquivalent(parent, fieldOrMethodClass) || ((PsiClass) parent).isInheritor(fieldOrMethodClass, true))) { return (PsiClass) parent; } } return null; }
void loadFromEditor(@NotNull Editor editor) { assertDispatchThread(); LOG.assertTrue(!editor.isDisposed()); clear(); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); documentManager.commitDocument(editor.getDocument()); PsiFile file = documentManager.getPsiFile(editor.getDocument()); SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject); EditorFoldingInfo info = EditorFoldingInfo.get(editor); FoldRegion[] foldRegions = editor.getFoldingModel().getAllFoldRegions(); for (FoldRegion region : foldRegions) { if (!region.isValid()) continue; PsiElement element = info.getPsiElement(region); boolean expanded = region.isExpanded(); boolean collapseByDefault = element != null && FoldingPolicy.isCollapseByDefault(element) && !FoldingUtil.caretInsideRange(editor, TextRange.create(region)); if (collapseByDefault == expanded || element == null) { FoldingInfo fi = new FoldingInfo(region.getPlaceholderText(), expanded); if (element != null) { myPsiElements.add(smartPointerManager.createSmartPsiElementPointer(element, file)); element.putUserData(FOLDING_INFO_KEY, fi); } else if (region.isValid()) { myRangeMarkers.add(region); region.putUserData(FOLDING_INFO_KEY, fi); } } } }
@Override protected void performRefactoring(@NotNull UsageInfo[] usages) { try { for (UsageInfo usage : usages) { if (usage instanceof SafeDeleteCustomUsageInfo) { ((SafeDeleteCustomUsageInfo) usage).performRefactoring(); } } DumbService.allowStartingDumbModeInside( DumbModePermission.MAY_START_MODAL, () -> { for (PsiElement element : myElements) { for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { if (delegate.handlesElement(element)) { delegate.prepareForDeletion(element); } } element.delete(); } }); } catch (IncorrectOperationException e) { RefactoringUIUtil.processIncorrectOperation(myProject, e); } }
private void analyzeDfaWithNestedClosures( PsiElement scope, ProblemsHolder holder, StandardDataFlowRunner dfaRunner, Collection<DfaMemoryState> initialStates) { final DataFlowInstructionVisitor visitor = new DataFlowInstructionVisitor(dfaRunner); final RunnerResult rc = dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS, initialStates); if (rc == RunnerResult.OK) { createDescription(dfaRunner, holder, visitor); MultiMap<PsiElement, DfaMemoryState> nestedClosures = dfaRunner.getNestedClosures(); for (PsiElement closure : nestedClosures.keySet()) { analyzeDfaWithNestedClosures(closure, holder, dfaRunner, nestedClosures.get(closure)); } } else if (rc == RunnerResult.TOO_COMPLEX) { if (scope.getParent() instanceof PsiMethod) { PsiMethod method = (PsiMethod) scope.getParent(); final PsiIdentifier name = method.getNameIdentifier(); if (name != null) { // Might be null for synthetic methods like JSP page. holder.registerProblem( name, InspectionsBundle.message("dataflow.too.complex"), ProblemHighlightType.WEAK_WARNING); } } } }
private PsiElement getStatementToInsertBefore() { PsiElement declarationScope = myVariable instanceof PsiParameter ? ((PsiParameter) myVariable).getDeclarationScope() : PsiUtil.getVariableCodeBlock(myVariable, null); if (declarationScope == null) return null; PsiElement statement = myClass; nextInnerClass: do { statement = PsiUtil.getEnclosingStatement(statement); if (statement == null || statement.getParent() == null) { return null; } PsiElement element = statement; while (element != declarationScope && !(element instanceof PsiFile)) { if (element instanceof PsiClass) { statement = statement.getParent(); continue nextInnerClass; } element = element.getParent(); } return statement; } while (true); }
@Override public PsiType[] guessContainerElementType(PsiExpression containerExpr, TextRange rangeToIgnore) { HashSet<PsiType> typesSet = new HashSet<>(); PsiType type = containerExpr.getType(); PsiType elemType; if ((elemType = getGenericElementType(type)) != null) return new PsiType[] {elemType}; if (containerExpr instanceof PsiReferenceExpression) { PsiElement refElement = ((PsiReferenceExpression) containerExpr).resolve(); if (refElement instanceof PsiVariable) { PsiFile file = refElement.getContainingFile(); if (file == null) { file = containerExpr.getContainingFile(); // implicit variable in jsp } HashSet<PsiVariable> checkedVariables = new HashSet<>(); addTypesByVariable( typesSet, (PsiVariable) refElement, file, checkedVariables, CHECK_USAGE | CHECK_DOWN, rangeToIgnore); checkedVariables.clear(); addTypesByVariable( typesSet, (PsiVariable) refElement, file, checkedVariables, CHECK_UP, rangeToIgnore); } } return typesSet.toArray(PsiType.createArray(typesSet.size())); }