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
    public boolean satisfiedBy(@NotNull PsiElement element) {
      if (!(element instanceof JSStatement)) {
        return false;
      }
      if (element instanceof JSBlockStatement) {
        return false;
      }

      final PsiElement parentElement = element.getParent();
      if (!(parentElement instanceof JSElement)) return false;
      final JSElement parent = (JSElement) parentElement;

      if (parent instanceof JSIfStatement) {
        final JSIfStatement ifStatement = (JSIfStatement) parent;

        return (!(element instanceof JSIfStatement && element.equals(ifStatement.getElse())));
      }

      if (parent instanceof JSForStatement || parent instanceof JSForInStatement) {
        return element.equals(((JSLoopStatement) parent).getBody());
      }

      return (parent instanceof JSWhileStatement || parent instanceof JSDoWhileStatement);
    }
  private static void findClassUsages(
      final PsiClass psiClass,
      final PsiElement[] allElementsToDelete,
      final List<UsageInfo> usages) {
    final boolean justPrivates = containsOnlyPrivates(psiClass);
    final String qualifiedName = psiClass.getQualifiedName();
    final boolean annotationType = psiClass.isAnnotationType() && qualifiedName != null;

    ReferencesSearch.search(psiClass)
        .forEach(
            reference -> {
              final PsiElement element = reference.getElement();

              if (!isInside(element, allElementsToDelete)) {
                PsiElement parent = element.getParent();
                if (parent instanceof PsiReferenceList) {
                  final PsiElement pparent = parent.getParent();
                  if (pparent instanceof PsiClass
                      && element instanceof PsiJavaCodeReferenceElement) {
                    final PsiClass inheritor = (PsiClass) pparent;
                    // If psiClass contains only private members, then it is safe to remove it and
                    // change inheritor's extends/implements accordingly
                    if (justPrivates) {
                      if (parent.equals(inheritor.getExtendsList())
                          || parent.equals(inheritor.getImplementsList())) {
                        usages.add(
                            new SafeDeleteExtendsClassUsageInfo(
                                (PsiJavaCodeReferenceElement) element, psiClass, inheritor));
                        return true;
                      }
                    }
                  }
                }
                LOG.assertTrue(element.getTextRange() != null);
                final PsiFile containingFile = psiClass.getContainingFile();
                boolean sameFileWithSingleClass = false;
                if (containingFile instanceof PsiClassOwner) {
                  final PsiClass[] classes = ((PsiClassOwner) containingFile).getClasses();
                  sameFileWithSingleClass =
                      classes.length == 1
                          && classes[0] == psiClass
                          && element.getContainingFile() == containingFile;
                }

                final boolean safeDelete = sameFileWithSingleClass || isInNonStaticImport(element);
                if (annotationType && parent instanceof PsiAnnotation) {
                  usages.add(
                      new SafeDeleteAnnotation((PsiAnnotation) parent, psiClass, safeDelete));
                } else {
                  usages.add(
                      new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, safeDelete));
                }
              }
              return true;
            });
  }
 private static void appendElementText(
     @NotNull PsiElement element,
     @NotNull PsiElement elementToReplace,
     @Nullable PsiExpression replacementExpression,
     @NotNull StringBuilder out) {
   if (element.equals(elementToReplace)) {
     final String replacementText =
         (replacementExpression == null) ? "" : replacementExpression.getText();
     out.append(replacementText);
     return;
   }
   final PsiElement[] children = element.getChildren();
   if (children.length == 0) {
     out.append(element.getText());
     if (element instanceof PsiComment) {
       final PsiComment comment = (PsiComment) element;
       final IElementType tokenType = comment.getTokenType();
       if (tokenType == JavaTokenType.END_OF_LINE_COMMENT) {
         out.append('\n');
       }
     }
     return;
   }
   for (PsiElement child : children) {
     appendElementText(child, elementToReplace, replacementExpression, out);
   }
 }
 @Nullable
 private static PsiType guessElementTypeFromReference(
     MethodPatternMap methodPatternMap, PsiElement ref, TextRange rangeToIgnore) {
   PsiElement refParent = ref.getParent();
   if (refParent instanceof PsiReferenceExpression) {
     PsiReferenceExpression parentExpr = (PsiReferenceExpression) refParent;
     if (ref.equals(parentExpr.getQualifierExpression())
         && parentExpr.getParent() instanceof PsiMethodCallExpression) {
       String methodName = parentExpr.getReferenceName();
       PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parentExpr.getParent();
       PsiExpression[] args = methodCall.getArgumentList().getExpressions();
       MethodPattern pattern = methodPatternMap.findPattern(methodName, args.length);
       if (pattern != null) {
         if (pattern.parameterIndex < 0) { // return value
           if (methodCall.getParent() instanceof PsiTypeCastExpression
               && (rangeToIgnore == null || !rangeToIgnore.contains(methodCall.getTextRange()))) {
             return ((PsiTypeCastExpression) methodCall.getParent()).getType();
           }
         } else {
           return args[pattern.parameterIndex].getType();
         }
       }
     }
   }
   return null;
 }
 private static PsiDeclarationStatement moveDeclarationToReference(
     @NotNull PsiElement referenceElement,
     @NotNull PsiLocalVariable variable,
     @NotNull PsiCodeBlock block)
     throws IncorrectOperationException {
   PsiStatement statement = PsiTreeUtil.getParentOfType(referenceElement, PsiStatement.class);
   assert statement != null;
   if (statement.getParent() instanceof PsiForStatement) {
     statement = (PsiStatement) statement.getParent();
   }
   final PsiElement referenceParent = referenceElement.getParent();
   if (referenceParent instanceof PsiAssignmentExpression) {
     final PsiAssignmentExpression assignmentExpression =
         (PsiAssignmentExpression) referenceParent;
     if (referenceElement.equals(assignmentExpression.getLExpression())) {
       PsiDeclarationStatement newDeclaration =
           createNewDeclaration(variable, assignmentExpression.getRExpression());
       newDeclaration = (PsiDeclarationStatement) block.addBefore(newDeclaration, statement);
       final PsiElement parent = assignmentExpression.getParent();
       assert parent != null;
       parent.delete();
       return newDeclaration;
     }
   }
   return createNewDeclaration(variable, null);
 }
 @Override
 public boolean equals(final PsiElement o1, final PsiElement o2) {
   if (o1 instanceof PsiNamedElement && o2 instanceof PsiNamedElement) {
     return Comparing.equal(
         ((PsiNamedElement) o1).getName(), ((PsiNamedElement) o2).getName());
   }
   return o1.equals(o2);
 }
 @Nullable
 private InstructionImpl findInstruction(PsiElement element) {
   final Iterator<InstructionImpl> iterator = myProcessingStack.descendingIterator();
   while (iterator.hasNext()) {
     final InstructionImpl instruction = iterator.next();
     if (element.equals(instruction.getElement())) return instruction;
   }
   return null;
 }
예제 #10
0
 public static boolean isChild(PsiElement child, PsiElement parent) {
   PsiElement el = child;
   while ((el = el.getParent()) != null && !(el instanceof XmlFile)) {
     if (el.equals(parent)) {
       return true;
     }
   }
   return false;
 }
 private static boolean isRecursiveReferencedParameter(
     final PsiExpression argument, final PsiParameter param) {
   if (argument instanceof PsiReferenceExpression) {
     final PsiElement element = ((PsiReferenceExpression) argument).resolve();
     if (element instanceof PsiParameter) {
       return element.equals(param);
     }
   }
   return false;
 }
 @Override
 public boolean execute(PsiElement psiElement, ResolveState resolveState) {
   if (!psiElement.equals(hackVariableReference)
       && psiElement instanceof HackVariableNameHolder
       && psiElement.getText().equals(myVariableName)) {
     result = (HackVariableNameHolder) psiElement;
     if (result.getParent() instanceof HackFunction) return false;
   }
   return true;
 }
 private static int getBlockElementIndex(@NotNull PsiElement element) {
   int i = 0;
   for (PsiElement sibling : element.getParent().getChildren()) {
     if (element.equals(sibling)) {
       return i;
     }
     if (isBlockElement(sibling)) {
       i++;
     }
   }
   throw new RuntimeException("Malformed PSI");
 }
예제 #14
0
    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      ColorIconRenderer renderer = (ColorIconRenderer) o;

      if (myElement != null ? !myElement.equals(renderer.myElement) : renderer.myElement != null)
        return false;

      return true;
    }
 private static boolean referencesEqual(
     PsiReferenceExpression reference1, PsiReferenceExpression reference2) {
   if (reference1 == null || reference2 == null) {
     return false;
   }
   final PsiElement target1 = reference1.resolve();
   if (target1 == null) {
     return false;
   }
   final PsiElement target2 = reference2.resolve();
   return target1.equals(target2);
 }
예제 #16
0
  @Override
  public boolean areElementsEquivalent(PsiElement element1, PsiElement element2) {
    ProgressIndicatorProvider
        .checkCanceled(); // We hope this method is being called often enough to cancel daemon
                          // processes smoothly

    if (element1 == element2) return true;
    if (element1 == null || element2 == null) {
      return false;
    }

    return element1.equals(element2)
        || element1.isEquivalentTo(element2)
        || element2.isEquivalentTo(element1);
  }
 @Override
 public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
   if (used) {
     return;
   }
   super.visitReferenceExpression(expression);
   final PsiElement referent = expression.resolve();
   if (referent == null) {
     return;
   }
   if (referent.equals(variable)) {
     reference = expression;
     used = true;
   }
 }
 private static Indent getControlIndent(PsiElement parent, ASTNode child) {
   final PsiElement psi = child.getPsi();
   final IElementType type = child.getElementType();
   if (parent instanceof GrIfStatement) {
     final GrIfStatement ifStatement = (GrIfStatement) parent;
     if (!BLOCK_SET.contains(type)) {
       if (psi.equals(ifStatement.getThenBranch())) {
         return Indent.getNormalIndent();
       }
       if (psi.equals(ifStatement.getElseBranch())) {
         if (getGroovySettings(parent).SPECIAL_ELSE_IF_TREATMENT && psi instanceof GrIfStatement) {
           return Indent.getNoneIndent();
         }
         return Indent.getNormalIndent();
       }
     }
     if (psi.equals(ifStatement.getCondition())) {
       return Indent.getContinuationWithoutFirstIndent();
     }
   }
   if (parent instanceof GrWhileStatement) {
     if (psi.equals(((GrWhileStatement) parent).getBody()) && !BLOCK_SET.contains(type)) {
       return Indent.getNormalIndent();
     }
     if (psi.equals(((GrWhileStatement) parent).getCondition())) {
       return Indent.getContinuationWithoutFirstIndent();
     }
   }
   if (parent instanceof GrSynchronizedStatement) {
     if (psi.equals(((GrSynchronizedStatement) parent).getMonitor())) {
       return Indent.getContinuationWithoutFirstIndent();
     }
   }
   if (parent instanceof GrForStatement) {
     if (psi.equals(((GrForStatement) parent).getBody()) && !BLOCK_SET.contains(type)) {
       return Indent.getNormalIndent();
     }
     if (psi.equals(((GrForStatement) parent).getClause())) {
       return Indent.getContinuationWithoutFirstIndent();
     }
   }
   return Indent.getNoneIndent();
 }
 public void visitAssignmentExpression(PsiAssignmentExpression assignment) {
   super.visitAssignmentExpression(assignment);
   final PsiExpression lhs = assignment.getLExpression();
   final PsiExpression rhs = assignment.getRExpression();
   if (!(lhs instanceof PsiReferenceExpression)) {
     return;
   }
   if (!(rhs instanceof PsiReferenceExpression)) {
     return;
   }
   final PsiElement referent = ((PsiReference) rhs).resolve();
   if (referent == null || !referent.equals(param)) {
     return;
   }
   final PsiElement assigned = ((PsiReference) lhs).resolve();
   if (assigned == null || !(assigned instanceof PsiField)) {
     return;
   }
   fieldAssigned = (PsiField) assigned;
 }
 private static boolean referenceExpressionsAreEquivalent(
     PsiReferenceExpression referenceExpression1, PsiReferenceExpression referenceExpression2) {
   final PsiElement element1 = referenceExpression1.resolve();
   final PsiElement element2 = referenceExpression2.resolve();
   if (element1 != null) {
     if (!element1.equals(element2)) {
       return false;
     }
   } else {
     return element2 == null;
   }
   if (element1 instanceof PsiMember) {
     final PsiMember member1 = (PsiMember) element1;
     if (member1.hasModifierProperty(PsiModifier.STATIC)) {
       return true;
     } else if (member1 instanceof PsiClass) {
       return true;
     }
   } else {
     return true;
   }
   final PsiExpression qualifier1 = referenceExpression1.getQualifierExpression();
   final PsiExpression qualifier2 = referenceExpression2.getQualifierExpression();
   if (qualifier1 != null
       && !(qualifier1 instanceof PsiThisExpression || qualifier1 instanceof PsiSuperExpression)) {
     if (qualifier2 == null) {
       return false;
     } else if (!expressionsAreEquivalent(qualifier1, qualifier2)) {
       return false;
     }
   } else {
     if (qualifier2 != null
         && !(qualifier2 instanceof PsiThisExpression
             || qualifier2 instanceof PsiSuperExpression)) {
       return false;
     }
   }
   final String text1 = referenceExpression1.getText();
   final String text2 = referenceExpression2.getText();
   return text1.equals(text2);
 }
  @Override
  protected String getTextForElement(PsiElement element) {
    final JSElement parent = (JSElement) element.getParent();
    final String keyword;

    assert (parent != null);

    if (parent instanceof JSIfStatement) {
      final JSIfStatement ifStatement = (JSIfStatement) parent;
      final JSStatement elseBranch = ifStatement.getElse();

      keyword = (element.equals(elseBranch) ? ELSE_KEYWORD : IF_KEYWORD);
    } else {
      final PsiElement firstChild = parent.getFirstChild();

      assert (firstChild != null);
      keyword = firstChild.getText();
    }

    return this.getText(keyword);
  }
  @Nullable
  public static PsiElement getInnerClassVariableReferencedFrom(
      @NotNull PsiVariable variable, @NotNull PsiElement context) {
    final PsiElement[] scope;
    if (variable instanceof PsiResourceVariable) {
      scope = ((PsiResourceVariable) variable).getDeclarationScope();
    } else if (variable instanceof PsiLocalVariable) {
      final PsiElement parent = variable.getParent();
      scope =
          new PsiElement[] {
            parent != null ? parent.getParent() : null
          }; // code block or for statement
    } else if (variable instanceof PsiParameter) {
      scope = new PsiElement[] {((PsiParameter) variable).getDeclarationScope()};
    } else {
      scope = new PsiElement[] {variable.getParent()};
    }
    if (scope.length < 1
        || scope[0] == null
        || scope[0].getContainingFile() != context.getContainingFile()) return null;

    PsiElement parent = context.getParent();
    PsiElement prevParent = context;
    outer:
    while (parent != null) {
      for (PsiElement scopeElement : scope) {
        if (parent.equals(scopeElement)) break outer;
      }
      if (parent instanceof PsiClass
          && !(prevParent instanceof PsiExpressionList && parent instanceof PsiAnonymousClass)) {
        return parent;
      }
      if (parent instanceof PsiLambdaExpression) {
        return parent;
      }
      prevParent = parent;
      parent = parent.getParent();
    }
    return null;
  }
 /** @return true, if a declaration was introduced, false otherwise */
 private static boolean replaceVariableName(
     PsiElement element,
     PsiReferenceExpression firstReference,
     String newName,
     String originalName,
     StringBuilder out) {
   if (element instanceof PsiReferenceExpression) {
     final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) element;
     if (element.equals(firstReference) && isLeftSideOfSimpleAssignment(referenceExpression)) {
       final PsiType type = firstReference.getType();
       if (type != null) {
         out.append(type.getCanonicalText());
         out.append(' ');
         out.append(newName);
         return true;
       }
     }
     final String text = element.getText();
     if (text.equals(originalName)) {
       out.append(newName);
       return false;
     }
   }
   final PsiElement[] children = element.getChildren();
   if (children.length == 0) {
     final String text = element.getText();
     out.append(text);
   } else {
     boolean result = false;
     for (final PsiElement child : children) {
       if (result) {
         out.append(child.getText());
       } else {
         result = replaceVariableName(child, firstReference, newName, originalName, out);
       }
     }
     return result;
   }
   return false;
 }
    public void visitAssignmentExpression(@NotNull GrAssignmentExpression assignment) {
      super.visitAssignmentExpression(assignment);

      final IElementType sign = assignment.getOperationTokenType();
      if (!sign.equals(GroovyTokenTypes.mASSIGN)) {
        return;
      }
      final GrExpression lhs = assignment.getLValue();
      final GrExpression rhs = assignment.getRValue();
      if (rhs == null) {
        return;
      }
      if (!(rhs instanceof GrReferenceExpression) || !(lhs instanceof GrReferenceExpression)) {
        return;
      }
      final GrReferenceExpression rhsReference = (GrReferenceExpression) rhs;
      final GrReferenceExpression lhsReference = (GrReferenceExpression) lhs;
      final GrExpression rhsQualifier = rhsReference.getQualifierExpression();
      final GrExpression lhsQualifier = lhsReference.getQualifierExpression();
      if (rhsQualifier != null || lhsQualifier != null) {
        if (!EquivalenceChecker.expressionsAreEquivalent(rhsQualifier, lhsQualifier)) {
          return;
        }
      }
      final String rhsName = rhsReference.getReferenceName();
      final String lhsName = lhsReference.getReferenceName();
      if (rhsName == null || lhsName == null) {
        return;
      }
      if (!rhsName.equals(lhsName)) {
        return;
      }
      final PsiElement rhsReferent = rhsReference.resolve();
      final PsiElement lhsReferent = lhsReference.resolve();
      if (rhsReferent == null || lhsReferent == null || !rhsReferent.equals(lhsReferent)) {
        return;
      }
      registerError(assignment);
    }
 protected boolean isEnabled(
     @NotNull HierarchyBrowserBaseEx browser, @NotNull PsiElement element) {
   return !element.equals(browser.mySmartPsiElementPointer.getElement()) && element.isValid();
 }
예제 #26
0
  @NotNull
  public static PsiElement[] findStatementsInRange(
      @NotNull PsiFile file, int startOffset, int endOffset) {
    Language language = findJavaOrLikeLanguage(file);
    if (language == null) return PsiElement.EMPTY_ARRAY;
    FileViewProvider viewProvider = file.getViewProvider();
    PsiElement element1 = viewProvider.findElementAt(startOffset, language);
    PsiElement element2 = viewProvider.findElementAt(endOffset - 1, language);
    if (element1 instanceof PsiWhiteSpace) {
      startOffset = element1.getTextRange().getEndOffset();
      element1 = file.findElementAt(startOffset);
    }
    if (element2 instanceof PsiWhiteSpace) {
      endOffset = element2.getTextRange().getStartOffset();
      element2 = file.findElementAt(endOffset - 1);
    }
    if (element1 == null || element2 == null) return PsiElement.EMPTY_ARRAY;

    PsiElement parent = PsiTreeUtil.findCommonParent(element1, element2);
    if (parent == null) return PsiElement.EMPTY_ARRAY;
    while (true) {
      if (parent instanceof PsiStatement) {
        parent = parent.getParent();
        break;
      }
      if (parent instanceof PsiCodeBlock) break;
      // if (JspPsiUtil.isInJspFile(parent) && parent instanceof PsiFile) break;
      if (parent instanceof PsiCodeFragment) break;
      if (parent == null || parent instanceof PsiFile) return PsiElement.EMPTY_ARRAY;
      parent = parent.getParent();
    }

    if (!parent.equals(element1)) {
      while (!parent.equals(element1.getParent())) {
        element1 = element1.getParent();
      }
    }
    if (startOffset != element1.getTextRange().getStartOffset()) return PsiElement.EMPTY_ARRAY;

    if (!parent.equals(element2)) {
      while (!parent.equals(element2.getParent())) {
        element2 = element2.getParent();
      }
    }
    if (endOffset != element2.getTextRange().getEndOffset()) return PsiElement.EMPTY_ARRAY;

    if (parent instanceof PsiCodeBlock
        && parent.getParent() instanceof PsiBlockStatement
        && element1 == ((PsiCodeBlock) parent).getLBrace()
        && element2 == ((PsiCodeBlock) parent).getRBrace()) {
      return new PsiElement[] {parent.getParent()};
    }

    /*
        if(parent instanceof PsiCodeBlock && parent.getParent() instanceof PsiBlockStatement) {
          return new PsiElement[]{parent.getParent()};
        }
    */

    PsiElement[] children = parent.getChildren();
    ArrayList<PsiElement> array = new ArrayList<PsiElement>();
    boolean flag = false;
    for (PsiElement child : children) {
      if (child.equals(element1)) {
        flag = true;
      }
      if (flag && !(child instanceof PsiWhiteSpace)) {
        array.add(child);
      }
      if (child.equals(element2)) {
        break;
      }
    }

    for (PsiElement element : array) {
      if (!(element instanceof PsiStatement
          || element instanceof PsiWhiteSpace
          || element instanceof PsiComment)) {
        return PsiElement.EMPTY_ARRAY;
      }
    }

    return PsiUtilCore.toPsiElementArray(array);
  }
  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    if (myPsiElements.isEmpty() && myRangeMarkers.isEmpty() && mySerializedElements.isEmpty()) {
      throw new WriteExternalException();
    }

    if (mySerializedElements.isEmpty()) {
      for (SmartPsiElementPointer<PsiElement> ptr : myPsiElements) {
        PsiElement psiElement = ptr.getElement();
        if (psiElement == null || !psiElement.isValid()) {
          continue;
        }
        FoldingInfo fi = psiElement.getUserData(FOLDING_INFO_KEY);
        boolean state = fi != null && fi.expanded;
        String signature = FoldingPolicy.getSignature(psiElement);
        if (signature == null) {
          continue;
        }

        PsiFile containingFile = psiElement.getContainingFile();
        PsiElement restoredElement = FoldingPolicy.restoreBySignature(containingFile, signature);
        if (!psiElement.equals(restoredElement)) {
          StringBuilder trace = new StringBuilder();
          PsiElement restoredAgain =
              FoldingPolicy.restoreBySignature(containingFile, signature, trace);
          LOG.error(
              "element: "
                  + psiElement
                  + "("
                  + psiElement.getText()
                  + "); restoredElement: "
                  + restoredElement
                  + "; signature: '"
                  + signature
                  + "'; file: "
                  + containingFile
                  + "; injected: "
                  + InjectedLanguageManager.getInstance(myProject)
                      .isInjectedFragment(containingFile)
                  + "; languages: "
                  + containingFile.getViewProvider().getLanguages()
                  + "; restored again: "
                  + restoredAgain
                  + "; restore produces same results: "
                  + (restoredAgain == restoredElement)
                  + "; trace:\n"
                  + trace);
        }

        Element e = new Element(ELEMENT_TAG);
        e.setAttribute(SIGNATURE_ATT, signature);
        e.setAttribute(EXPANDED_ATT, Boolean.toString(state));
        element.addContent(e);
      }
    } else {
      // get back postponed state (before folding initialization)
      for (SerializedPsiElement entry : mySerializedElements) {
        Element e = new Element(ELEMENT_TAG);
        e.setAttribute(SIGNATURE_ATT, entry.mySerializedElement);
        e.setAttribute(EXPANDED_ATT, Boolean.toString(entry.myFoldingInfo.getExpanded()));
        element.addContent(e);
      }
    }
    String date = null;
    for (RangeMarker marker : myRangeMarkers) {
      FoldingInfo fi = marker.getUserData(FOLDING_INFO_KEY);
      boolean state = fi != null && fi.expanded;

      Element e = new Element(MARKER_TAG);
      if (date == null) {
        date = getTimeStamp();
      }
      if (date.isEmpty()) {
        continue;
      }

      e.setAttribute(DATE_ATT, date);
      e.setAttribute(EXPANDED_ATT, Boolean.toString(state));
      String signature =
          Integer.valueOf(marker.getStartOffset()) + ":" + Integer.valueOf(marker.getEndOffset());
      e.setAttribute(SIGNATURE_ATT, signature);
      String placeHolderText = fi == null ? DEFAULT_PLACEHOLDER : fi.placeHolder;
      e.setAttribute(PLACEHOLDER_ATT, placeHolderText);
      element.addContent(e);
    }
  }
  @Nullable
  private PsiType getNominalTypeInner(PsiElement resolved) {
    if (resolved == null && !"class".equals(getReferenceName())) {
      resolved = resolve();
    }

    if (resolved instanceof PsiClass) {
      final PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
      if (PsiUtil.isInstanceThisRef(this)) {
        final PsiClassType categoryType = GdkMethodUtil.getCategoryType((PsiClass) resolved);
        if (categoryType != null) {
          return categoryType;
        } else {
          return factory.createType((PsiClass) resolved);
        }
      }
      if (getParent() instanceof GrReferenceExpression || PsiUtil.isSuperReference(this)) {
        return factory.createType((PsiClass) resolved);
      } else {
        return TypesUtil.createJavaLangClassType(
            factory.createType((PsiClass) resolved), getProject(), getResolveScope());
      }
    }

    if (resolved instanceof GrVariable) {
      return ((GrVariable) resolved).getDeclaredType();
    }

    if (resolved instanceof PsiVariable) {
      return ((PsiVariable) resolved).getType();
    }

    if (resolved instanceof PsiMethod) {
      PsiMethod method = (PsiMethod) resolved;
      if (PropertyUtil.isSimplePropertySetter(method)
          && !method.getName().equals(getReferenceName())) {
        return method.getParameterList().getParameters()[0].getType();
      }

      // 'class' property with explicit generic
      PsiClass containingClass = method.getContainingClass();
      if (containingClass != null
          && CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName())
          && "getClass".equals(method.getName())) {
        return TypesUtil.createJavaLangClassType(
            GrReferenceResolveUtil.getQualifierType(this), getProject(), getResolveScope());
      }

      return PsiUtil.getSmartReturnType(method);
    }

    if (resolved instanceof GrReferenceExpression) {
      PsiElement parent = resolved.getParent();
      if (parent instanceof GrAssignmentExpression) {
        GrAssignmentExpression assignment = (GrAssignmentExpression) parent;
        if (resolved.equals(assignment.getLValue())) {
          GrExpression rValue = assignment.getRValue();
          if (rValue != null) {
            PsiType rType = rValue.getType();
            if (rType != null) {
              return rType;
            }
          }
        }
      }
    }

    if (resolved == null) {
      final PsiType fromClassRef = getTypeFromClassRef(this);
      if (fromClassRef != null) {
        return fromClassRef;
      }

      final PsiType fromMapAccess = getTypeFromMapAccess(this);
      if (fromMapAccess != null) {
        return fromMapAccess;
      }

      final PsiType fromSpreadOperator = getTypeFromSpreadOperator(this);
      if (fromSpreadOperator != null) {
        return fromSpreadOperator;
      }
    }

    return null;
  }
  static HighlightInfo checkDuplicateAnnotations(@NotNull PsiAnnotation annotationToCheck) {
    PsiAnnotationOwner owner = annotationToCheck.getOwner();
    if (owner == null) return null;

    PsiJavaCodeReferenceElement element = annotationToCheck.getNameReferenceElement();
    if (element == null) return null;
    PsiElement resolved = element.resolve();
    if (!(resolved instanceof PsiClass)) return null;

    PsiClass annotationType = (PsiClass) resolved;

    PsiClass contained = contained(annotationType);
    String containedElementFQN = contained == null ? null : contained.getQualifiedName();

    if (containedElementFQN != null) {
      PsiClass container = annotationType;
      String containerName = container.getQualifiedName();
      if (isAnnotationRepeatedTwice(owner, containedElementFQN)) {
        String description =
            JavaErrorMessages.message("annotation.container.wrong.place", containerName);
        return annotationError(annotationToCheck, description);
      }
    } else if (isAnnotationRepeatedTwice(owner, annotationType.getQualifiedName())) {
      if (!PsiUtil.isLanguageLevel8OrHigher(annotationToCheck)) {
        String description = JavaErrorMessages.message("annotation.duplicate.annotation");
        return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
            .range(element)
            .descriptionAndTooltip(description)
            .create();
      }
      PsiAnnotation metaAnno =
          PsiImplUtil.findAnnotation(
              annotationType.getModifierList(), CommonClassNames.JAVA_LANG_ANNOTATION_REPEATABLE);

      if (metaAnno == null) {
        String explanation =
            JavaErrorMessages.message(
                "annotation.non.repeatable", annotationType.getQualifiedName());
        String description =
            JavaErrorMessages.message("annotation.duplicate.explained", explanation);
        return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
            .range(element)
            .descriptionAndTooltip(description)
            .create();
      }

      String explanation = doCheckRepeatableAnnotation(metaAnno);
      if (explanation != null) {
        String description =
            JavaErrorMessages.message("annotation.duplicate.explained", explanation);
        return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
            .range(element)
            .descriptionAndTooltip(description)
            .create();
      }

      PsiClass container = getRepeatableContainer(metaAnno);
      if (container != null) {
        PsiAnnotation.TargetType[] targets = PsiImplUtil.getTargetsForLocation(owner);
        PsiAnnotation.TargetType applicable = PsiImplUtil.findApplicableTarget(container, targets);
        if (applicable == null) {
          String target = JavaErrorMessages.message("annotation.target." + targets[0]);
          String message =
              JavaErrorMessages.message(
                  "annotation.container.not.applicable", container.getName(), target);
          return annotationError(annotationToCheck, message);
        }
      }
    }

    for (PsiAnnotation annotation : owner.getAnnotations()) {
      if (annotation == annotationToCheck) continue;
      PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
      if (nameRef == null) continue;
      PsiElement aClass = nameRef.resolve();
      if (!resolved.equals(aClass)) continue;
    }

    return null;
  }