public static void replaceMovedMemberTypeParameters(
      final PsiElement member,
      final Iterable<PsiTypeParameter> parametersIterable,
      final PsiSubstitutor substitutor,
      final GroovyPsiElementFactory factory) {
    final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<PsiElement, PsiElement>();
    for (PsiTypeParameter parameter : parametersIterable) {
      PsiType substitutedType = substitutor.substitute(parameter);
      if (substitutedType == null) {
        substitutedType = TypeConversionUtil.erasure(factory.createType(parameter));
      }

      PsiElement scopeElement = member instanceof GrField ? member.getParent() : member;
      for (PsiReference reference :
          ReferencesSearch.search(parameter, new LocalSearchScope(scopeElement))) {
        final PsiElement element = reference.getElement();
        final PsiElement parent = element.getParent();
        if (parent instanceof PsiTypeElement) {
          replacement.put(parent, factory.createTypeElement(substitutedType));
        } else if (element instanceof GrCodeReferenceElement
            && substitutedType instanceof PsiClassType) {
          replacement.put(
              element, factory.createReferenceElementByType((PsiClassType) substitutedType));
        }
      }
    }

    for (PsiElement element : replacement.keySet()) {
      if (element.isValid()) {
        element.replace(replacement.get(element));
      }
    }
  }
  @Nullable
  private static PsiElement findParent(
      int syncStartOffset, int syncEndOffset, @NotNull AnchorTypeInfo type, PsiElement anchor) {
    TextRange range = anchor.getTextRange();

    if (range.getStartOffset() != syncStartOffset) return null;
    while (range.getEndOffset() < syncEndOffset) {
      anchor = anchor.getParent();
      if (anchor == null || anchor.getTextRange() == null) {
        return null;
      }
      range = anchor.getTextRange();
    }

    while (range.getEndOffset() == syncEndOffset) {
      if (type.isAcceptable(anchor)) {
        return anchor;
      }
      anchor = anchor.getParent();
      if (anchor == null || anchor.getTextRange() == null) break;
      range = anchor.getTextRange();
    }

    return null;
  }
  private static boolean shouldInsertParentheses(PsiClass psiClass, PsiElement position) {
    final PsiJavaCodeReferenceElement ref =
        PsiTreeUtil.getParentOfType(position, PsiJavaCodeReferenceElement.class);
    if (ref == null) {
      return false;
    }

    final PsiReferenceParameterList parameterList = ref.getParameterList();
    if (parameterList != null && parameterList.getTextLength() > 0) {
      return false;
    }

    final PsiElement prevElement = FilterPositionUtil.searchNonSpaceNonCommentBack(ref);
    if (prevElement != null && prevElement.getParent() instanceof PsiNewExpression) {

      Set<PsiType> expectedTypes = new HashSet<PsiType>();
      for (ExpectedTypeInfo info :
          ExpectedTypesProvider.getExpectedTypes((PsiExpression) prevElement.getParent(), true)) {
        expectedTypes.add(info.getType());
      }

      return JavaCompletionUtil.isDefinitelyExpected(psiClass, expectedTypes, position);
    }

    return false;
  }
  @Override
  @Nullable
  protected PsiElement getStatementAtCaret(Editor editor, PsiFile psiFile) {
    final PsiElement atCaret = super.getStatementAtCaret(editor, psiFile);

    if (atCaret instanceof PsiWhiteSpace) return null;
    if (atCaret instanceof PsiJavaToken
        && "}".equals(atCaret.getText())
        && !(atCaret.getParent() instanceof PsiArrayInitializerExpression)) return null;

    PsiElement statementAtCaret =
        PsiTreeUtil.getParentOfType(
            atCaret,
            PsiStatement.class,
            PsiCodeBlock.class,
            PsiMember.class,
            PsiComment.class,
            PsiImportStatementBase.class);

    if (statementAtCaret instanceof PsiBlockStatement) return null;

    if (statementAtCaret != null && statementAtCaret.getParent() instanceof PsiForStatement) {
      if (!PsiTreeUtil.hasErrorElements(statementAtCaret)) {
        statementAtCaret = statementAtCaret.getParent();
      }
    }

    return statementAtCaret instanceof PsiStatement
            || statementAtCaret instanceof PsiMember
            || statementAtCaret instanceof PsiImportStatementBase
        ? statementAtCaret
        : null;
  }
Esempio n. 5
0
  @Nullable
  public static KtExpression getParentCallIfPresent(@NotNull KtExpression expression) {
    PsiElement parent = expression.getParent();
    while (parent != null) {
      if (parent instanceof KtBinaryExpression
          || parent instanceof KtUnaryExpression
          || parent instanceof KtLabeledExpression
          || parent instanceof KtDotQualifiedExpression
          || parent instanceof KtCallExpression
          || parent instanceof KtArrayAccessExpression
          || parent instanceof KtDestructuringDeclaration) {

        if (parent instanceof KtLabeledExpression) {
          parent = parent.getParent();
          continue;
        }

        // check that it's in inlineable call would be in resolve call of parent
        return (KtExpression) parent;
      } else if (parent instanceof KtParenthesizedExpression
          || parent instanceof KtBinaryExpressionWithTypeRHS) {
        parent = parent.getParent();
      } else if (parent instanceof KtValueArgument || parent instanceof KtValueArgumentList) {
        parent = parent.getParent();
      } else if (parent instanceof KtLambdaExpression || parent instanceof KtAnnotatedExpression) {
        parent = parent.getParent();
      } else {
        return null;
      }
    }
    return null;
  }
  @Override
  public void handleCompletePath() {
    final PsiElement position = getContext().getPosition();
    if (position instanceof GosuIdentifierImpl) {
      if (position.getParent() instanceof GosuTypeLiteralImpl) {
        if (position.getParent().getParent() instanceof GosuUsesStatementImpl) {
          return;
        }
      }
    }

    // primitives are always available
    addPrimitives();

    addScratchpadInnerClasses(position);

    // ## THIS IS DOGASS SLOW, the eventual call to CustomPsiClassCache.getByShortName() is f*****g
    // molasses, don't do this here.
    //    AllClassesGetter.processJavaClasses( _params, _prefixMatcher, _params.getInvocationCount()
    // <= 1, new Consumer<PsiClass>() {
    //  ...
    //    } );

    addTypeLoaderTypes();
    if (getTotalCompletions() == 0 && _params.getInvocationCount() < 2) {
      stopFilterByInvocationCount();
      addTypeLoaderTypes();
    }
  }
  private static String findPrefixStatic(PsiElement element, int i) {
    String prefix = CompletionData.findPrefixStatic(element, i);

    if (element.getParent() instanceof XPathVariableReference) {
      prefix = "$" + prefix;
    }

    if (element.getParent() instanceof XPathNodeTest) {
      final XPathNodeTest nodeTest = ((XPathNodeTest) element.getParent());
      if (nodeTest.isNameTest()) {
        final PrefixedName prefixedName = nodeTest.getQName();
        assert prefixedName != null;
        final String p = prefixedName.getPrefix();

        int endIndex = prefixedName.getLocalName().indexOf(CompletionLists.INTELLIJ_IDEA_RULEZ);
        if (endIndex != -1) {
          prefix = prefixedName.getLocalName().substring(0, endIndex);
        } else if (p != null) {
          endIndex = p.indexOf(CompletionLists.INTELLIJ_IDEA_RULEZ);
          if (endIndex != -1) {
            prefix = p.substring(0, endIndex);
          }
        }
      }
    }

    return prefix;
  }
Esempio n. 8
0
  // Returns null if standalone closing brace is not found
  private static BraceStatus checkForMovableClosingBrace(
      @NotNull Editor editor, @NotNull PsiFile file, @NotNull MoveInfo info, boolean down) {
    PsiElement closingBrace = getStandaloneClosingBrace(file, editor);
    if (closingBrace == null) return BraceStatus.NOT_FOUND;

    PsiElement blockLikeElement = closingBrace.getParent();
    if (!(blockLikeElement instanceof JetBlockExpression)) return BraceStatus.NOT_MOVABLE;

    PsiElement blockParent = blockLikeElement.getParent();
    if (blockParent instanceof JetWhenEntry) return BraceStatus.NOT_FOUND;
    if (PsiTreeUtil.instanceOf(blockParent, FUNCTIONLIKE_ELEMENT_CLASSES))
      return BraceStatus.NOT_FOUND;

    PsiElement enclosingExpression =
        PsiTreeUtil.getParentOfType(blockLikeElement, JetExpression.class);

    if (enclosingExpression instanceof JetDoWhileExpression) return BraceStatus.NOT_MOVABLE;

    if (enclosingExpression instanceof JetIfExpression) {
      JetIfExpression ifExpression = (JetIfExpression) enclosingExpression;

      if (blockLikeElement == ifExpression.getThen() && ifExpression.getElse() != null)
        return BraceStatus.NOT_MOVABLE;
    }

    return down
        ? checkForMovableDownClosingBrace(closingBrace, blockLikeElement, editor, info)
        : checkForMovableUpClosingBrace(closingBrace, blockLikeElement, editor, info);
  }
  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);
        }
      }
    }
  }
Esempio n. 10
0
  @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();
    }
  }
Esempio n. 11
0
 private static List<? extends PsiElement> resolveSimpleReference(
     @NotNull DartReference reference) {
   final List<? extends PsiElement> result =
       resolveSimpleReference(reference, reference.getCanonicalText());
   final PsiElement parent = reference.getParent();
   final PsiElement superParent = parent.getParent();
   final boolean isSimpleConstructor =
       parent instanceof DartType
           && superParent instanceof DartNewExpression
           && ((DartNewExpression) superParent).getReferenceExpression() == null;
   if (!isSimpleConstructor || result.isEmpty()) {
     return result;
   }
   final List<PsiElement> filteredResult = new ArrayList<PsiElement>(result.size());
   for (PsiElement element : result) {
     final PsiElement elementParent = element.getParent();
     if (element instanceof DartComponentName && elementParent instanceof DartClass) {
       final DartComponent component =
           ((DartClass) elementParent).findNamedConstructor(reference.getCanonicalText());
       if (component != null
           && DartComponentType.typeOf(component) == DartComponentType.CONSTRUCTOR) {
         filteredResult.add(component.getComponentName());
         continue;
       }
     }
     filteredResult.add(element);
   }
   return filteredResult;
 }
Esempio n. 12
0
  @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;
  }
  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);
  }
Esempio n. 14
0
  private static void collectAllElements(
      PsiElement atCaret, List<PsiElement> res, boolean recurse) {
    res.add(0, atCaret);
    if (doNotStepInto(atCaret)) {
      if (!recurse) return;
      recurse = false;
    }

    PsiElement parent = atCaret.getParent();
    if (atCaret instanceof GrClosableBlock
        && parent instanceof GrStringInjection
        && parent.getParent() instanceof GrString) {
      res.add(parent.getParent());
    }

    if (parent instanceof GrArgumentList) {
      res.add(parent.getParent());
    }

    // if (parent instanceof GrWhileStatement) {
    //  res.add(parent);
    // }

    final PsiElement[] children = getChildren(atCaret);

    for (PsiElement child : children) {
      if (atCaret instanceof GrStatement && child instanceof GrStatement) continue;
      collectAllElements(child, res, recurse);
    }
  }
  @Nullable
  private static List<String> getTasksTarget(Location location) {
    if (location instanceof GradleTaskLocation) {
      return ((GradleTaskLocation) location).getTasks();
    }

    PsiElement parent = location.getPsiElement();
    while (parent.getParent() != null && !(parent.getParent() instanceof PsiFile)) {
      parent = parent.getParent();
    }

    if (isCreateTaskMethod(parent)) {
      final GrExpression[] arguments = ((GrMethodCallExpression) parent).getExpressionArguments();
      if (arguments.length > 0
          && arguments[0] instanceof GrLiteral
          && ((GrLiteral) arguments[0]).getValue() instanceof String) {
        return Collections.singletonList((String) ((GrLiteral) arguments[0]).getValue());
      }
    } else if (parent instanceof GrApplicationStatement) {
      PsiElement shiftExpression = parent.getChildren()[1].getChildren()[0];
      if (shiftExpression instanceof GrShiftExpressionImpl) {
        PsiElement shiftiesChild = shiftExpression.getChildren()[0];
        if (shiftiesChild instanceof GrReferenceExpression) {
          return Collections.singletonList(shiftiesChild.getText());
        } else if (shiftiesChild instanceof GrMethodCallExpression) {
          return Collections.singletonList(shiftiesChild.getChildren()[0].getText());
        }
      } else if (shiftExpression instanceof GrMethodCallExpression) {
        return Collections.singletonList(shiftExpression.getChildren()[0].getText());
      }
    }

    return null;
  }
  private static boolean isStatementPosition(PsiElement position) {
    if (PsiTreeUtil.getNonStrictParentOfType(position, PsiLiteralExpression.class, PsiComment.class)
        != null) {
      return false;
    }

    if (psiElement()
        .withSuperParent(2, PsiConditionalExpression.class)
        .andNot(psiElement().insideStarting(psiElement(PsiConditionalExpression.class)))
        .accepts(position)) {
      return false;
    }

    if (END_OF_BLOCK.getValue().isAcceptable(position, position)
        && PsiTreeUtil.getParentOfType(position, PsiCodeBlock.class, true, PsiMember.class)
            != null) {
      return true;
    }

    if (psiElement()
        .withParents(
            PsiReferenceExpression.class, PsiExpressionStatement.class, PsiIfStatement.class)
        .andNot(psiElement().afterLeaf("."))
        .accepts(position)) {
      PsiElement stmt = position.getParent().getParent();
      PsiIfStatement ifStatement = (PsiIfStatement) stmt.getParent();
      if (ifStatement.getElseBranch() == stmt || ifStatement.getThenBranch() == stmt) {
        return true;
      }
    }

    return false;
  }
  @Override
  public String getSignature(@NotNull final PsiElement element) {
    StringBuilder buffer = null;
    for (PsiElement current = element;
        current != null && !(current instanceof PsiFile);
        current = current.getParent()) {
      int length = buffer == null ? 0 : buffer.length();
      StringBuilder b = getSignature(current, buffer);
      if (b == null
          && buffer != null
          && current.getParent() instanceof PsiFile
          && canResolveTopLevelChild(current)) {
        buffer
            .append(TYPE_MARKER)
            .append(ELEMENT_TOKENS_SEPARATOR)
            .append(TOP_LEVEL_CHILD_MARKER)
            .append(ELEMENTS_SEPARATOR);
        break;
      }
      buffer = b;
      if (buffer == null || length >= buffer.length()) {
        return null;
      }
      buffer.append(ELEMENTS_SEPARATOR);
    }

    if (buffer == null) {
      return null;
    }

    buffer.setLength(buffer.length() - 1);
    return buffer.toString();
  }
  @Nullable
  private static PsiClass[] getTopLevelClasses(PsiElement element) {
    while (true) {
      if (element == null || element instanceof PsiFile) break;
      if (element instanceof PsiClass
          && element.getParent() != null
          && ((PsiClass) element).getContainingClass() == null
          && !(element instanceof PsiAnonymousClass)) break;
      element = element.getParent();
    }
    if (element instanceof PsiCompiledElement) return null;
    if (element instanceof PsiClassOwner) {
      PsiClass[] classes = ((PsiClassOwner) element).getClasses();
      if (classes.length > 0) {
        for (final PsiClass aClass : classes) {
          if (aClass instanceof SyntheticElement) {
            return null;
          }
        }

        return classes;
      }
    }
    return element instanceof PsiClass ? new PsiClass[] {(PsiClass) element} : null;
  }
Esempio n. 19
0
  public static PsiElement[] parsePattern(
      Project project,
      String context,
      String pattern,
      FileType fileType,
      Language language,
      String extension,
      boolean physical) {
    int offset = context.indexOf(PATTERN_PLACEHOLDER);

    final int patternLength = pattern.length();
    final String patternInContext = context.replace(PATTERN_PLACEHOLDER, pattern);

    final String ext = extension != null ? extension : fileType.getDefaultExtension();
    final String name = "__dummy." + ext;
    final PsiFileFactory factory = PsiFileFactory.getInstance(project);

    final PsiFile file =
        language == null
            ? factory.createFileFromText(
                name, fileType, patternInContext, LocalTimeCounter.currentTime(), physical, true)
            : factory.createFileFromText(name, language, patternInContext, physical, true);
    if (file == null) {
      return PsiElement.EMPTY_ARRAY;
    }

    final List<PsiElement> result = new ArrayList<PsiElement>();

    PsiElement element = file.findElementAt(offset);
    if (element == null) {
      return PsiElement.EMPTY_ARRAY;
    }

    PsiElement topElement = element;
    element = element.getParent();

    while (element != null) {
      if (element.getTextRange().getStartOffset() == offset
          && element.getTextLength() <= patternLength) {
        topElement = element;
      }
      element = element.getParent();
    }

    if (topElement instanceof PsiFile) {
      return topElement.getChildren();
    }

    final int endOffset = offset + patternLength;
    result.add(topElement);
    topElement = topElement.getNextSibling();

    while (topElement != null && topElement.getTextRange().getEndOffset() <= endOffset) {
      result.add(topElement);
      topElement = topElement.getNextSibling();
    }

    return result.toArray(new PsiElement[result.size()]);
  }
Esempio n. 20
0
  @Nullable
  public static KtElement getEnclosingElementForLocalDeclaration(
      @NotNull KtDeclaration declaration, boolean skipParameters) {
    if (declaration instanceof KtTypeParameter && skipParameters) {
      declaration = PsiTreeUtil.getParentOfType(declaration, KtNamedDeclaration.class);
    } else if (declaration instanceof KtParameter) {
      KtFunctionType functionType = PsiTreeUtil.getParentOfType(declaration, KtFunctionType.class);
      if (functionType != null) {
        return functionType;
      }

      PsiElement parent = declaration.getParent();

      // val/var parameter of primary constructor should be considered as local according to
      // containing class
      if (((KtParameter) declaration).hasValOrVar()
          && parent != null
          && parent.getParent() instanceof KtPrimaryConstructor) {
        return getEnclosingElementForLocalDeclaration(
            ((KtPrimaryConstructor) parent.getParent()).getContainingClassOrObject(),
            skipParameters);
      } else if (skipParameters
          && parent != null
          && parent.getParent() instanceof KtNamedFunction) {
        declaration = (KtNamedFunction) parent.getParent();
      }
    }

    if (declaration instanceof PsiFile) {
      return declaration;
    }

    // No appropriate stub-tolerant method in PsiTreeUtil, nor JetStubbedPsiUtil, writing manually
    PsiElement current = PsiTreeUtil.getStubOrPsiParent(declaration);
    while (current != null) {
      PsiElement parent = PsiTreeUtil.getStubOrPsiParent(current);
      if (parent instanceof KtScript) return null;
      if (current instanceof KtAnonymousInitializer) {
        return ((KtAnonymousInitializer) current).getBody();
      }
      if (current instanceof KtProperty || current instanceof KtFunction) {
        if (parent instanceof KtFile) {
          return (KtElement) current;
        } else if (parent instanceof KtClassBody
            && !isMemberOfObjectExpression((KtCallableDeclaration) current)) {
          return (KtElement) parent;
        }
      }
      if (current instanceof KtBlockExpression || current instanceof KtParameter) {
        return (KtElement) current;
      }
      if (current instanceof KtValueArgument) {
        return (KtElement) current;
      }

      current = parent;
    }
    return null;
  }
Esempio n. 21
0
  private boolean checkMovingInsideOutside(
      PsiFile file,
      final Editor editor,
      LineRange range,
      @NotNull final MoveInfo info,
      final boolean down) {
    final int offset = editor.getCaretModel().getOffset();

    PsiElement elementAtOffset = file.getViewProvider().findElementAt(offset, StdLanguages.JAVA);
    if (elementAtOffset == null) return false;

    PsiElement guard = elementAtOffset;
    do {
      guard =
          PsiTreeUtil.getParentOfType(
              guard, PsiMethod.class, PsiClassInitializer.class, PsiClass.class, PsiComment.class);
    } while (guard instanceof PsiAnonymousClass);

    PsiElement brace = itIsTheClosingCurlyBraceWeAreMoving(file, editor);
    if (brace != null) {
      int line = editor.getDocument().getLineNumber(offset);
      final LineRange toMove = new LineRange(line, line + 1);
      toMove.firstElement = toMove.lastElement = brace;
      info.toMove = toMove;
    }

    // cannot move in/outside method/class/initializer/comment
    if (!calcInsertOffset(file, editor, info.toMove, info, down)) return false;
    int insertOffset =
        down
            ? getLineStartSafeOffset(editor.getDocument(), info.toMove2.endLine)
            : editor.getDocument().getLineStartOffset(info.toMove2.startLine);
    PsiElement elementAtInsertOffset =
        file.getViewProvider().findElementAt(insertOffset, StdLanguages.JAVA);
    PsiElement newGuard = elementAtInsertOffset;
    do {
      newGuard =
          PsiTreeUtil.getParentOfType(
              newGuard,
              PsiMethod.class,
              PsiClassInitializer.class,
              PsiClass.class,
              PsiComment.class);
    } while (newGuard instanceof PsiAnonymousClass);

    if (brace != null
        && PsiTreeUtil.getParentOfType(brace, PsiCodeBlock.class, false)
            != PsiTreeUtil.getParentOfType(elementAtInsertOffset, PsiCodeBlock.class, false)) {
      info.indentSource = true;
    }
    if (newGuard == guard && isInside(insertOffset, newGuard) == isInside(offset, guard))
      return true;

    // moving in/out nested class is OK
    if (guard instanceof PsiClass && guard.getParent() instanceof PsiClass) return true;
    if (newGuard instanceof PsiClass && newGuard.getParent() instanceof PsiClass) return true;

    return false;
  }
Esempio n. 22
0
 private static PsiElement getAnchorElement(
     final PsiCodeBlock anchorBlock, @NotNull PsiElement firstElement) {
   PsiElement element = firstElement;
   while (element != null && element.getParent() != anchorBlock) {
     element = element.getParent();
   }
   return element;
 }
 private static boolean shouldSuggestClassNameCompletion(final PsiElement element) {
   if (element == null) return false;
   final PsiElement parent = element.getParent();
   if (parent == null) return false;
   return parent.getParent() instanceof PsiTypeElement
       || parent.getParent() instanceof PsiExpressionStatement
       || parent.getParent() instanceof PsiReferenceList;
 }
  private boolean checkAccessibility(final PsiClass aClass) {
    // We don't care about accessibility in javadoc
    if (JavaResolveUtil.isInJavaDoc(myPlace)) {
      return true;
    }

    if (PsiImplUtil.isInServerPage(aClass.getContainingFile())) {
      PsiFile file = FileContextUtil.getContextFile(myPlace);
      if (PsiImplUtil.isInServerPage(file)) {
        return true;
      }
    }

    boolean accessible = true;
    if (aClass instanceof PsiTypeParameter) {
      accessible = !myStaticContext;
    }

    PsiManager manager = aClass.getManager();
    if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) {
      PsiElement parent = aClass.getParent();
      while (true) {
        PsiElement parentScope = parent.getParent();
        if (parentScope instanceof PsiJavaFile) break;
        parent = parentScope;
        if (!(parentScope instanceof PsiClass)) break;
      }
      if (parent instanceof PsiDeclarationStatement) {
        parent = parent.getParent();
      }
      accessible = false;
      for (PsiElement placeParent = myPlace;
          placeParent != null;
          placeParent = placeParent.getContext()) {
        if (manager.areElementsEquivalent(placeParent, parent)) accessible = true;
      }
    }
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
      accessible = false;
      if (myPlace != null && facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = true;
      } else {
        if (aClass.getContainingClass() != null) {
          accessible =
              myAccessClass == null
                  || myPlace != null
                      && facade.getResolveHelper().isAccessible(aClass, myPlace, myAccessClass);
        }
      }
    }
    if (aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
      if (myPlace == null || !facade.arePackagesTheSame(aClass, myPlace)) {
        accessible = false;
      }
    }
    return accessible;
  }
 @Nullable
 public static PsiElement getParentSkipParentheses(PsiElement element) {
   PsiElement parent = element.getParent();
   while (parent instanceof PsiParenthesizedExpression
       || parent instanceof PsiTypeCastExpression) {
     parent = parent.getParent();
   }
   return parent;
 }
Esempio n. 26
0
 @Nullable
 public static JetScript getScript(@NotNull JetDeclaration namedDeclaration) {
   PsiElement parent = namedDeclaration.getParent();
   if (parent != null && parent.getParent() instanceof JetScript) {
     return (JetScript) parent.getParent();
   } else {
     return null;
   }
 }
 private static PsiElement getParent(PsiElement element) {
   PsiElement parent = element.getParent();
   while (parent instanceof PsiParenthesizedExpression
       || parent instanceof PsiTypeCastExpression
       || parent instanceof PsiConditionalExpression) {
     parent = parent.getParent();
   }
   return parent;
 }
 @Override
 public boolean canFindUsagesFor(@NotNull PsiElement element) {
   if (element instanceof Argument && element.getParent() instanceof Import) {
     // if the Argument is the first child of Import, then it is hte file reference
     // everything else will be covered by Variables
     return element == element.getParent().getFirstChild();
   }
   return element instanceof PsiNamedElement;
 }
  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;
            });
  }
Esempio n. 30
0
  @Nullable
  public static PsiElement getOutermostParent(
      @NotNull PsiElement element, @NotNull PsiElement upperBound, boolean strict) {
    PsiElement parent = strict ? element.getParent() : element;
    while (parent != null && parent.getParent() != upperBound) {
      parent = parent.getParent();
    }

    return parent;
  }