private void replaceIteratorNext(
     PsiElement element,
     String contentVariableName,
     String iteratorName,
     PsiElement childToSkip,
     StringBuilder out,
     PsiType contentType) {
   if (isIteratorNext(element, iteratorName, contentType)) {
     out.append(contentVariableName);
   } else {
     final PsiElement[] children = element.getChildren();
     if (children.length == 0) {
       final String text = element.getText();
       if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') {
         out.append(' ');
       }
       out.append(text);
     } else {
       boolean skippingWhiteSpace = false;
       for (final PsiElement child : children) {
         if (child.equals(childToSkip)) {
           skippingWhiteSpace = true;
         } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) {
           // don't do anything
         } else {
           skippingWhiteSpace = false;
           replaceIteratorNext(
               child, contentVariableName, iteratorName, childToSkip, out, contentType);
         }
       }
     }
   }
 }
 private void replaceCollectionGetAccess(
     PsiElement element,
     String contentVariableName,
     PsiVariable listVariable,
     String indexName,
     PsiElement childToSkip,
     StringBuilder out) {
   if (isListGetLookup(element, indexName, listVariable)) {
     out.append(contentVariableName);
   } else {
     final PsiElement[] children = element.getChildren();
     if (children.length == 0) {
       final String text = element.getText();
       if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') {
         out.append(' ');
       }
       out.append(text);
     } else {
       boolean skippingWhiteSpace = false;
       for (final PsiElement child : children) {
         if (child.equals(childToSkip)) {
           skippingWhiteSpace = true;
         } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) {
           // don't do anything
         } else {
           skippingWhiteSpace = false;
           replaceCollectionGetAccess(
               child, contentVariableName, listVariable, indexName, childToSkip, out);
         }
       }
     }
   }
 }
  @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 AddModuleDependencyFix(
      Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) {
    final PsiElement psiElement = reference.getElement();
    final Project project = psiElement.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    for (PsiClass aClass : classes) {
      if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue;
      PsiFile psiFile = aClass.getContainingFile();
      if (psiFile == null) continue;
      VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;
      final Module classModule = fileIndex.getModuleForFile(virtualFile);
      if (classModule != null
          && classModule != currentModule
          && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) {
        myModules.add(classModule);
      }
    }
    myCurrentModule = currentModule;
    myClassVFile = classVFile;
    myClasses = classes;
    myReference = reference;
  }
  private void updateEditorText() {
    disposeNonTextEditor();

    final PsiElement elt = myElements[myIndex].getNavigationElement();
    Project project = elt.getProject();
    PsiFile psiFile = getContainingFile(elt);
    final VirtualFile vFile = psiFile.getVirtualFile();
    if (vFile == null) return;
    final FileEditorProvider[] providers =
        FileEditorProviderManager.getInstance().getProviders(project, vFile);
    for (FileEditorProvider provider : providers) {
      if (provider instanceof TextEditorProvider) {
        updateTextElement(elt);
        myBinarySwitch.show(myViewingPanel, TEXT_PAGE_KEY);
        break;
      } else if (provider.accept(project, vFile)) {
        myCurrentNonTextEditorProvider = provider;
        myNonTextEditor = myCurrentNonTextEditorProvider.createEditor(project, vFile);
        myBinaryPanel.removeAll();
        myBinaryPanel.add(myNonTextEditor.getComponent());
        myBinarySwitch.show(myViewingPanel, BINARY_PAGE_KEY);
        break;
      }
    }
  }
  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);
            });
  }
 @NotNull
 public UsageViewPresentation createPresentation(
     @NotNull FindUsagesHandler handler, @NotNull FindUsagesOptions findUsagesOptions) {
   PsiElement element = handler.getPsiElement();
   LOG.assertTrue(element.isValid());
   return createPresentation(element, findUsagesOptions, myToOpenInNewTab);
 }
  @Nullable
  private String verifyInnerClassDestination() {
    PsiClass targetClass = findTargetClass();
    if (targetClass == null) return null;

    for (PsiElement element : myElementsToMove) {
      if (PsiTreeUtil.isAncestor(element, targetClass, false)) {
        return RefactoringBundle.message("move.class.to.inner.move.to.self.error");
      }
      final Language targetClassLanguage = targetClass.getLanguage();
      if (!element.getLanguage().equals(targetClassLanguage)) {
        return RefactoringBundle.message(
            "move.to.different.language",
            UsageViewUtil.getType(element),
            ((PsiClass) element).getQualifiedName(),
            targetClass.getQualifiedName());
      }
      if (element.getLanguage().equals(Language.findLanguageByID("Groovy"))) {
        return RefactoringBundle.message("dont.support.inner.classes", "Groovy");
      }
    }

    while (targetClass != null) {
      if (targetClass.getContainingClass() != null
          && !targetClass.hasModifierProperty(PsiModifier.STATIC)) {
        return RefactoringBundle.message("move.class.to.inner.nonstatic.error");
      }
      targetClass = targetClass.getContainingClass();
    }

    return null;
  }
 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);
   }
 }
  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);
        }
      }
    }
  }
Пример #11
0
  public String getAttributeValue(String _name, String namespace) {
    if (namespace == null) {
      return getAttributeValue(_name);
    }

    XmlTagImpl current = this;
    PsiElement parent = getParent();

    while (current != null) {
      BidirectionalMap<String, String> map = current.initNamespaceMaps(parent);
      if (map != null) {
        List<String> keysByValue = map.getKeysByValue(namespace);
        if (keysByValue != null && !keysByValue.isEmpty()) {

          for (String prefix : keysByValue) {
            if (prefix != null && prefix.length() > 0) {
              final String value = getAttributeValue(prefix + ":" + _name);
              if (value != null) return value;
            }
          }
        }
      }

      current = parent instanceof XmlTag ? (XmlTagImpl) parent : null;
      parent = parent.getParent();
    }

    if (namespace.length() == 0 || getNamespace().equals(namespace)) {
      return getAttributeValue(_name);
    }
    return null;
  }
    @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)));
    }
 public PsiDirectory[] getSelectedDirectories() {
   final PsiElement[] elements = getSelectedPSIElements();
   if (elements.length == 1) {
     final PsiElement element = elements[0];
     if (element instanceof PsiDirectory) {
       return new PsiDirectory[] {(PsiDirectory) element};
     } else if (element instanceof PsiDirectoryContainer) {
       return ((PsiDirectoryContainer) element).getDirectories();
     } else {
       final PsiFile containingFile = element.getContainingFile();
       if (containingFile != null) {
         final PsiDirectory psiDirectory = containingFile.getContainingDirectory();
         if (psiDirectory != null) {
           return new PsiDirectory[] {psiDirectory};
         }
         final VirtualFile file = containingFile.getVirtualFile();
         if (file instanceof VirtualFileWindow) {
           final VirtualFile delegate = ((VirtualFileWindow) file).getDelegate();
           final PsiFile delegatePsiFile = containingFile.getManager().findFile(delegate);
           if (delegatePsiFile != null && delegatePsiFile.getContainingDirectory() != null) {
             return new PsiDirectory[] {delegatePsiFile.getContainingDirectory()};
           }
         }
         return PsiDirectory.EMPTY_ARRAY;
       }
     }
   } else {
     final DefaultMutableTreeNode selectedNode = getSelectedNode();
     if (selectedNode != null) {
       return getSelectedDirectoriesInAmbiguousCase(selectedNode);
     }
   }
   return PsiDirectory.EMPTY_ARRAY;
 }
Пример #14
0
  public TextRange getRangeInElement() {
    final PsiElement element = commandElement();
    if (element == null) {
      return TextRange.from(0, getTextLength());
    }

    return TextRange.from(element.getStartOffsetInParent(), element.getTextLength());
  }
Пример #15
0
  public String getReferencedName() {
    final PsiElement element = commandElement();
    if (element != null) {
      return element.getText();
    }

    return null;
  }
Пример #16
0
 public Info(@NotNull PsiElement elementAtPointer) {
   this(
       elementAtPointer,
       Collections.singletonList(
           new TextRange(
               elementAtPointer.getTextOffset(),
               elementAtPointer.getTextOffset() + elementAtPointer.getTextLength())));
 }
  final boolean isValidBase() {
    if (PsiDocumentManager.getInstance(myProject).getUncommittedDocuments().length > 0) {
      return myCachedIsValidBase;
    }

    final PsiElement element = mySmartPsiElementPointer.getElement();
    myCachedIsValidBase = element != null && isApplicableElement(element) && element.isValid();
    return myCachedIsValidBase;
  }
  private static boolean isStaticOk(GroovyResolveResult resolveResult) {
    if (resolveResult.isStaticsOK()) return true;

    PsiElement resolved = resolveResult.getElement();
    LOG.assertTrue(resolved != null);
    LOG.assertTrue(resolved instanceof PsiModifierListOwner, resolved + " : " + resolved.getText());

    return ((PsiModifierListOwner) resolved).hasModifierProperty(STATIC);
  }
 @Override
 public Icon getIcon() {
   Icon icon = myIcon;
   if (icon == null) {
     PsiElement psiElement = getElement();
     myIcon = icon = psiElement != null && psiElement.isValid() ? psiElement.getIcon(0) : null;
   }
   return icon;
 }
  public static boolean isClassEquivalentTo(@NotNull PsiClass aClass, PsiElement another) {
    if (aClass == another) return true;
    if (!(another instanceof PsiClass)) return false;
    String name1 = aClass.getName();
    if (name1 == null) return false;
    if (!another.isValid()) return false;
    String name2 = ((PsiClass) another).getName();
    if (name2 == null) return false;
    if (name1.hashCode() != name2.hashCode()) return false;
    if (!name1.equals(name2)) return false;
    String qName1 = aClass.getQualifiedName();
    String qName2 = ((PsiClass) another).getQualifiedName();
    if (qName1 == null || qName2 == null) {
      //noinspection StringEquality
      if (qName1 != qName2) return false;

      if (aClass instanceof PsiTypeParameter && another instanceof PsiTypeParameter) {
        PsiTypeParameter p1 = (PsiTypeParameter) aClass;
        PsiTypeParameter p2 = (PsiTypeParameter) another;

        return p1.getIndex() == p2.getIndex()
            && aClass.getManager().areElementsEquivalent(p1.getOwner(), p2.getOwner());
      } else {
        return false;
      }
    }
    if (qName1.hashCode() != qName2.hashCode() || !qName1.equals(qName2)) {
      return false;
    }

    if (originalElement(aClass).equals(originalElement((PsiClass) another))) {
      return true;
    }

    final PsiFile file1 = aClass.getContainingFile().getOriginalFile();
    final PsiFile file2 = another.getContainingFile().getOriginalFile();

    // see com.intellij.openapi.vcs.changes.PsiChangeTracker
    // see com.intellij.psi.impl.PsiFileFactoryImpl#createFileFromText(CharSequence,PsiFile)
    final PsiFile original1 = file1.getUserData(PsiFileFactory.ORIGINAL_FILE);
    final PsiFile original2 = file2.getUserData(PsiFileFactory.ORIGINAL_FILE);
    if (original1 == original2 && original1 != null
        || original1 == file2
        || original2 == file1
        || file1 == file2) {
      return compareClassSeqNumber(aClass, (PsiClass) another);
    }

    final FileIndexFacade fileIndex =
        ServiceManager.getService(file1.getProject(), FileIndexFacade.class);
    final VirtualFile vfile1 = file1.getViewProvider().getVirtualFile();
    final VirtualFile vfile2 = file2.getViewProvider().getVirtualFile();
    boolean lib1 = fileIndex.isInLibraryClasses(vfile1);
    boolean lib2 = fileIndex.isInLibraryClasses(vfile2);

    return (fileIndex.isInSource(vfile1) || lib1) && (fileIndex.isInSource(vfile2) || lib2);
  }
Пример #21
0
  public boolean isFunctionCall() {
    PsiElement commandElement = commandElement();
    if (commandElement == null || commandElement.getNode() == null) {
      return false;
    }

    return commandElement.getNode().getElementType() == BashElementTypes.GENERIC_COMMAND_ELEMENT
        && internalResolve() != null;
  }
  @Override
  public UsageGroup groupUsage(@NotNull Usage usage) {
    if (!(usage instanceof PsiElementUsage)) {
      return null;
    }
    final PsiElement psiElement = ((PsiElementUsage) usage).getElement();
    final PsiFile containingFile = psiElement.getContainingFile();
    if (containingFile == null) return null;

    PsiFile topLevelFile =
        InjectedLanguageManager.getInstance(containingFile.getProject())
            .getTopLevelFile(containingFile);

    if (!(topLevelFile instanceof PsiJavaFile) || topLevelFile instanceof JspFile) {
      return null;
    }
    PsiElement containingClass =
        topLevelFile == containingFile
            ? psiElement
            : InjectedLanguageManager.getInstance(containingFile.getProject())
                .getInjectionHost(containingFile);
    do {
      containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class, true);
      if (containingClass == null || ((PsiClass) containingClass).getQualifiedName() != null) break;
    } while (true);

    if (containingClass == null) {
      // check whether the element is in the import list
      PsiImportList importList = PsiTreeUtil.getParentOfType(psiElement, PsiImportList.class, true);
      if (importList != null) {
        final String fileName = getFileNameWithoutExtension(topLevelFile);
        final PsiClass[] classes = ((PsiJavaFile) topLevelFile).getClasses();
        for (final PsiClass aClass : classes) {
          if (fileName.equals(aClass.getName())) {
            containingClass = aClass;
            break;
          }
        }
      }
    } else {
      // skip JspClass synthetic classes.
      if (containingClass.getParent() instanceof PsiFile
          && JspPsiUtil.isInJspFile(containingClass)) {
        containingClass = null;
      }
    }

    if (containingClass != null) {
      return new ClassUsageGroup((PsiClass) containingClass);
    }

    final VirtualFile virtualFile = topLevelFile.getVirtualFile();
    if (virtualFile != null) {
      return new FileGroupingRule.FileUsageGroup(topLevelFile.getProject(), virtualFile);
    }
    return null;
  }
 @Nullable
 protected PsiElement getPSIElement(@Nullable final Object element) {
   if (element instanceof PsiElement) {
     PsiElement psiElement = (PsiElement) element;
     if (psiElement.isValid()) {
       return psiElement;
     }
   }
   return null;
 }
Пример #24
0
 public PomModelEvent runInner() throws IncorrectOperationException {
   final ASTNode anchor = expandTag();
   if (myChild.getElementType() == XmlElementType.XML_TAG) {
     // compute where to insert tag according to DTD or XSD
     final XmlElementDescriptor parentDescriptor = getDescriptor();
     final XmlTag[] subTags = getSubTags();
     final PsiElement declaration =
         parentDescriptor != null ? parentDescriptor.getDeclaration() : null;
     // filtring out generated dtds
     if (declaration != null
         && declaration.getContainingFile() != null
         && declaration.getContainingFile().isPhysical()
         && subTags.length > 0) {
       final XmlElementDescriptor[] childElementDescriptors =
           parentDescriptor.getElementsDescriptors(XmlTagImpl.this);
       int subTagNum = -1;
       for (final XmlElementDescriptor childElementDescriptor : childElementDescriptors) {
         final String childElementName = childElementDescriptor.getName();
         while (subTagNum < subTags.length - 1
             && subTags[subTagNum + 1].getName().equals(childElementName)) {
           subTagNum++;
         }
         if (childElementName.equals(
             XmlChildRole.START_TAG_NAME_FINDER.findChild(myChild).getText())) {
           // insert child just after anchor
           // insert into the position specified by index
           if (subTagNum >= 0) {
             final ASTNode subTag = (ASTNode) subTags[subTagNum];
             if (subTag.getTreeParent() != XmlTagImpl.this) {
               // in entity
               final XmlEntityRef entityRef =
                   PsiTreeUtil.getParentOfType(subTags[subTagNum], XmlEntityRef.class);
               throw new IncorrectOperationException(
                   "Can't insert subtag to the entity. Entity reference text: "
                       + (entityRef == null ? "" : entityRef.getText()));
             }
             myNewElement =
                 XmlTagImpl.super.addInternal(myChild, myChild, subTag, Boolean.FALSE);
           } else {
             final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(XmlTagImpl.this);
             myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, child, Boolean.FALSE);
           }
           return null;
         }
       }
     } else {
       final ASTNode child = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(XmlTagImpl.this);
       myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, child, Boolean.TRUE);
       return null;
     }
   }
   myNewElement = XmlTagImpl.super.addInternal(myChild, myChild, anchor, Boolean.TRUE);
   return null;
 }
 @Override
 public boolean isValid() {
   PsiElement element = getElement();
   if (element == null || !element.isValid()) {
     return false;
   }
   for (UsageInfo usageInfo : getMergedInfos()) {
     if (usageInfo.getSegment() == null) return false;
   }
   return true;
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   if (!FileModificationService.getInstance()
       .preparePsiElementForWrite(descriptor.getPsiElement())) return;
   PsiElement castTypeElement = descriptor.getPsiElement();
   PsiTypeCastExpression cast =
       castTypeElement == null ? null : (PsiTypeCastExpression) castTypeElement.getParent();
   if (cast != null) {
     RedundantCastUtil.removeCast(cast);
   }
 }
  @Nullable
  private ProblemDescriptor createDescription(
      @NotNull PsiTypeCastExpression cast, @NotNull InspectionManager manager, boolean onTheFly) {
    PsiExpression operand = cast.getOperand();
    PsiTypeElement castType = cast.getCastType();
    if (operand == null || castType == null) return null;
    PsiElement parent = cast.getParent();
    while (parent instanceof PsiParenthesizedExpression) {
      parent = parent.getParent();
    }
    if (parent instanceof PsiReferenceExpression) {
      if (IGNORE_ANNOTATED_METHODS) {
        final PsiElement gParent = parent.getParent();
        if (gParent instanceof PsiMethodCallExpression) {
          final PsiMethod psiMethod = ((PsiMethodCallExpression) gParent).resolveMethod();
          if (psiMethod != null && NullableNotNullManager.isNotNull(psiMethod)) {
            final PsiClass superClass = PsiUtil.resolveClassInType(operand.getType());
            final PsiClass containingClass = psiMethod.getContainingClass();
            if (containingClass != null
                && superClass != null
                && containingClass.isInheritor(superClass, true)) {
              for (PsiMethod method : psiMethod.findSuperMethods(superClass)) {
                if (NullableNotNullManager.isNullable(method)) {
                  return null;
                }
              }
            }
          }
        }
      }
    } else if (parent instanceof PsiExpressionList) {
      final PsiElement gParent = parent.getParent();
      if (gParent instanceof PsiMethodCallExpression && IGNORE_SUSPICIOUS_METHOD_CALLS) {
        final String message =
            SuspiciousCollectionsMethodCallsInspection.getSuspiciousMethodCallMessage(
                (PsiMethodCallExpression) gParent,
                operand.getType(),
                true,
                new ArrayList<PsiMethod>(),
                new IntArrayList());
        if (message != null) {
          return null;
        }
      }
    }

    String message =
        InspectionsBundle.message(
            "inspection.redundant.cast.problem.descriptor",
            "<code>" + operand.getText() + "</code>",
            "<code>#ref</code> #loc");
    return manager.createProblemDescriptor(
        castType, message, myQuickFixAction, ProblemHighlightType.LIKE_UNUSED_SYMBOL, onTheFly);
  }
Пример #28
0
  public PsiElement handleElementRename(String newName) throws IncorrectOperationException {
    if (StringUtil.isEmpty(newName)) {
      return null;
    }

    final PsiElement original = commandElement();
    final PsiElement replacement = BashChangeUtil.createWord(getProject(), newName);

    getNode().replaceChild(original.getNode(), replacement.getNode());
    return this;
  }
 @NotNull
 private static PsiElement originalElement(@NotNull PsiClass aClass) {
   final PsiElement originalElement = aClass.getOriginalElement();
   ASTNode node = originalElement.getNode();
   if (node != null) {
     final PsiCompiledElement compiled = node.getUserData(ClsElementImpl.COMPILED_ELEMENT);
     if (compiled != null) {
       return compiled;
     }
   }
   return originalElement;
 }
  public MoveClassesOrPackagesDialog(
      Project project,
      boolean searchTextOccurences,
      PsiElement[] elementsToMove,
      final PsiElement initialTargetElement,
      MoveCallback moveCallback) {
    super(project, true);
    myElementsToMove = elementsToMove;
    myMoveCallback = moveCallback;
    myManager = PsiManager.getInstance(myProject);
    setTitle(MoveHandler.REFACTORING_NAME);
    mySearchTextOccurencesEnabled = searchTextOccurences;

    selectInitialCard();

    init();

    if (initialTargetElement instanceof PsiClass) {
      myMakeInnerClassOfRadioButton.setSelected(true);

      myInnerClassChooser.setText(((PsiClass) initialTargetElement).getQualifiedName());

      ApplicationManager.getApplication()
          .invokeLater(
              () -> myInnerClassChooser.requestFocus(),
              ModalityState.stateForComponent(myMainPanel));
    } else if (initialTargetElement instanceof PsiPackage) {
      myClassPackageChooser.setText(((PsiPackage) initialTargetElement).getQualifiedName());
    }

    updateControlsEnabled();
    myToPackageRadioButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateControlsEnabled();
            myClassPackageChooser.requestFocus();
          }
        });
    myMakeInnerClassOfRadioButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateControlsEnabled();
            myInnerClassChooser.requestFocus();
          }
        });

    for (PsiElement element : elementsToMove) {
      if (element.getContainingFile() != null) {
        myOpenInEditorPanel.add(initOpenInEditorCb(), BorderLayout.EAST);
        break;
      }
    }
  }