private ASTNode notBoundInExistingAst(
     PsiFileImpl file, FileElement treeElement, StubTree stubTree) {
   @NonNls
   String message =
       "this="
           + this.getClass()
           + "; file.isPhysical="
           + file.isPhysical()
           + "; node="
           + myNode
           + "; file="
           + file
           + "; tree="
           + treeElement
           + "; stubTree="
           + stubTree;
   PsiElement each = this;
   while (each != null) {
     message += "\n each of class " + each.getClass();
     if (each instanceof StubBasedPsiElementBase) {
       message +=
           "; node="
               + ((StubBasedPsiElementBase) each).myNode
               + "; stub="
               + ((StubBasedPsiElementBase) each).myStub;
       each = ((StubBasedPsiElementBase) each).getParentByStub();
     } else {
       break;
     }
   }
   throw new AssertionError(message);
 }
 public void processInjectableElements(
     Collection<PsiElement> in, Processor<PsiElement> processor) {
   ClassMapCachingNulls<MultiHostInjector> map = getInjectorMap();
   for (PsiElement element : in) {
     if (map.get(element.getClass()) != null) processor.process(element);
   }
 }
 private static void convertToUsageTarget(
     @NotNull List<PsiElement2UsageTargetAdapter> targets, @NotNull PsiElement elementToSearch) {
   if (elementToSearch instanceof NavigationItem) {
     targets.add(new PsiElement2UsageTargetAdapter(elementToSearch));
   } else {
     throw new IllegalArgumentException(
         "Wrong usage target:" + elementToSearch + "; " + elementToSearch.getClass());
   }
 }
 public static SQLRefReference getAnnoRefIdFromMethodCallExpressionElement(PsiElement psiElement) {
   if (psiElement instanceof PsiMethodCallExpression) {
     final PsiReferenceExpression methodExpression =
         ((PsiMethodCallExpression) psiElement).getMethodExpression();
     if (methodExpression != null
         && methodExpression.getQualifierExpression() != null
         && methodExpression.getQualifierExpression().getType() != null) {
       final PsiType type = methodExpression.getQualifierExpression().getType();
       final PsiClassReferenceType classReferenceType = (PsiClassReferenceType) type;
       if (type instanceof PsiClassReferenceType && classReferenceType.getReference() != null) {
         final Project project = psiElement.getProject();
         if (AnnoRefConfigSettings.getInstance(project)
             .getAnnoRefState()
             .ANNOREF_UTIL_CLASS_FQN
             .equals(classReferenceType.getReference().getQualifiedName())) {
           if (((PsiCall) psiElement).getArgumentList().getExpressions().length == 1) {
             final PsiExpression psiExpression =
                 ((PsiCall) psiElement).getArgumentList().getExpressions()[0];
             final String refId = String.valueOf(((PsiLiteral) psiExpression).getValue());
             final SQLRefReference refReference =
                 ServiceManager.getService(project, SQLRefRepository.class)
                     .getSQLRefReferenceForID(refId);
             return refReference;
           } else {
             throw new IllegalArgumentException(
                 String.format(
                     "Argument %s for parameter of %s.%s must not be null",
                     new Object[] {
                       "0",
                       classReferenceType.getReference().getQualifiedName(),
                       methodExpression.getQualifiedName()
                     }));
           }
         } else {
           log.warn(
               "getAnnoRefIdFromMethodCallExpressionElement(): PsiElement ClassReferenceType FQA="
                   + classReferenceType.getReference().getQualifiedName()
                   + " different"
                   + " from ANNOREF_UTIL_CLASS_FQN="
                   + AnnoRefConfigSettings.getInstance(project)
                       .getAnnoRefState()
                       .ANNOREF_UTIL_CLASS_FQN);
         }
       } else {
         log.warn(
             "getAnnoRefIdFromMethodCallExpressionElement(): PsiElement ReferenceType="
                 + classReferenceType);
       }
     } else {
       log.warn(
           "getAnnoRefIdFromMethodCallExpressionElement(): PsiElement is of type="
               + psiElement.getClass());
     }
   }
   return null;
 }
 AnchorElementInfo(@NotNull PsiElement anchor, @NotNull PsiFile containingFile) {
   super(
       containingFile.getProject(),
       ProperTextRange.create(anchor.getTextRange()),
       anchor.getClass(),
       containingFile,
       LanguageUtil.getRootLanguage(anchor));
   assert !(anchor instanceof PsiFile) : "FileElementInfo must be used for file: " + anchor;
   myStubElementTypeAndId = pack(-1, null);
 }
示例#6
0
  // Delete given element and all the elements separating it from the neighboring elements of the
  // same class
  public static void deleteElementWithDelimiters(@NotNull PsiElement element) {
    PsiElement paramBefore = PsiTreeUtil.getPrevSiblingOfType(element, element.getClass());

    PsiElement from;
    PsiElement to;
    if (paramBefore != null) {
      from = paramBefore.getNextSibling();
      to = element;
    } else {
      PsiElement paramAfter = PsiTreeUtil.getNextSiblingOfType(element, element.getClass());

      from = element;
      to = paramAfter != null ? paramAfter.getPrevSibling() : element;
    }

    PsiElement parent = element.getParent();

    parent.deleteChildRange(from, to);
  }
示例#7
0
 static <T extends PsiElement> T getPsi(@NotNull Class<T> clazz, PsiElement element, Logger log) {
   log.assertTrue(
       clazz.isInstance(element),
       "unexpected psi class. expected: "
           + clazz
           + " got: "
           + (element == null ? null : element.getClass()));
   //noinspection unchecked
   return (T) element;
 }
  @NotNull
  private static Couple<Collection<TextRange>> getUsages(
      @NotNull PsiElement target,
      PsiElement psiElement,
      boolean withDeclarations,
      boolean detectAccess) {
    List<TextRange> readRanges = new ArrayList<TextRange>();
    List<TextRange> writeRanges = new ArrayList<TextRange>();
    final ReadWriteAccessDetector detector =
        detectAccess ? ReadWriteAccessDetector.findDetector(target) : null;
    final FindUsagesManager findUsagesManager =
        ((FindManagerImpl) FindManager.getInstance(target.getProject())).getFindUsagesManager();
    final FindUsagesHandler findUsagesHandler =
        findUsagesManager.getFindUsagesHandler(target, true);
    final LocalSearchScope scope = new LocalSearchScope(psiElement);
    Collection<PsiReference> refs =
        findUsagesHandler != null
            ? findUsagesHandler.findReferencesToHighlight(target, scope)
            : ReferencesSearch.search(target, scope).findAll();
    for (PsiReference psiReference : refs) {
      if (psiReference == null) {
        LOG.error(
            "Null reference returned, findUsagesHandler="
                + findUsagesHandler
                + "; target="
                + target
                + " of "
                + target.getClass());
        continue;
      }
      List<TextRange> destination;
      if (detector == null
          || detector.getReferenceAccess(target, psiReference)
              == ReadWriteAccessDetector.Access.Read) {
        destination = readRanges;
      } else {
        destination = writeRanges;
      }
      HighlightUsagesHandler.collectRangesToHighlight(psiReference, destination);
    }

    if (withDeclarations) {
      final TextRange declRange =
          HighlightUsagesHandler.getNameIdentifierRange(psiElement.getContainingFile(), target);
      if (declRange != null) {
        if (detector != null && detector.isDeclarationWriteAccess(target)) {
          writeRanges.add(declRange);
        } else {
          readRanges.add(declRange);
        }
      }
    }

    return Couple.<Collection<TextRange>>of(readRanges, writeRanges);
  }
 public boolean satisfies(@NotNull PsiElement element, @NotNull ResolveState state) {
   final String name = PsiUtilCore.getName(element);
   if (StringUtil.isNotEmpty(name) && (myMatcher == null || myMatcher.value(name))) {
     if (myFilter.isClassAcceptable(element.getClass())
         && myFilter.isAcceptable(
             new CandidateInfo(element, state.get(PsiSubstitutor.KEY)), myElement)) {
       return true;
     }
   }
   return false;
 }
    @Override
    public void visitCaseLabel(GrCaseLabel caseLabel) {
      final PsiElement parent = caseLabel.getParent().getParent();
      assert parent instanceof GrSwitchStatement : parent + " of class " + parent.getClass();
      final GrExpression condition = ((GrSwitchStatement) parent).getCondition();
      if (condition == null) return;

      final PsiType type = condition.getType();
      if (type == null) return;

      myResult = new TypeConstraint[] {SubtypeConstraint.create(type)};
    }
  void processInPlaceInjectorsFor(@NotNull PsiElement element, @NotNull InjProcessor processor) {
    MultiHostInjector[] infos = getInjectorMap().get(element.getClass());
    if (infos != null) {
      final boolean dumb = myDumbService.isDumb();
      for (MultiHostInjector injector : infos) {
        if (dumb && !DumbService.isDumbAware(injector)) {
          continue;
        }

        if (!processor.process(element, injector)) return;
      }
    }
  }
 // will restore by stub index until file tree get loaded
 AnchorElementInfo(
     @NotNull PsiElement anchor,
     @NotNull PsiFileWithStubSupport containingFile,
     int stubId,
     @NotNull IStubElementType stubElementType) {
   super(
       containingFile.getProject(),
       new ProperTextRange(0, 0),
       anchor.getClass(),
       containingFile,
       containingFile.getLanguage());
   myStubElementTypeAndId = pack(stubId, stubElementType);
   assert !(anchor instanceof PsiFile) : "FileElementInfo must be used for file: " + anchor;
 }
示例#13
0
  protected void completeReference(
      final PsiReference reference,
      final PsiElement position,
      final Set<LookupElement> set,
      final TailType tailType,
      final PsiFile file,
      final ElementFilter filter,
      final CompletionVariant variant) {
    if (reference instanceof PsiMultiReference) {
      for (PsiReference ref : getReferences((PsiMultiReference) reference)) {
        completeReference(ref, position, set, tailType, file, filter, variant);
      }
    } else if (reference instanceof PsiDynaReference) {
      for (PsiReference ref : ((PsiDynaReference<?>) reference).getReferences()) {
        completeReference(ref, position, set, tailType, file, filter, variant);
      }
    } else {
      final Object[] completions = reference.getVariants();
      if (completions == null) return;

      for (Object completion : completions) {
        if (completion == null) {
          LOG.assertTrue(
              false,
              "Position="
                  + position
                  + "\n;Reference="
                  + reference
                  + "\n;variants="
                  + Arrays.toString(completions));
        }
        if (completion instanceof PsiElement) {
          final PsiElement psiElement = (PsiElement) completion;
          if (filter.isClassAcceptable(psiElement.getClass())
              && filter.isAcceptable(psiElement, position)) {
            addLookupItem(set, tailType, completion, file, variant);
          }
        } else {
          if (completion instanceof LookupItem) {
            final Object o = ((LookupItem) completion).getObject();
            if (o instanceof PsiElement) {
              if (!filter.isClassAcceptable(o.getClass()) || !filter.isAcceptable(o, position))
                continue;
            }
          }
          addLookupItem(set, tailType, completion, file, variant);
        }
      }
    }
  }
  @NotNull
  public static List<RatedResolveResult> resolveNameInFromImport(
      PyFromImportStatement importStatement, @NotNull QualifiedName qName) {
    PsiFile file = importStatement.getContainingFile().getOriginalFile();
    String name = qName.getComponents().get(0);

    final List<PsiElement> candidates = importStatement.resolveImportSourceCandidates();
    List<PsiElement> resultList = new ArrayList<PsiElement>();
    for (PsiElement candidate : candidates) {
      if (!candidate.isValid()) {
        throw new PsiInvalidElementAccessException(
            candidate,
            "Got an invalid candidate from resolveImportSourceCandidates(): "
                + candidate.getClass());
      }
      if (candidate instanceof PsiDirectory) {
        candidate = PyUtil.getPackageElement((PsiDirectory) candidate, importStatement);
      }
      List<RatedResolveResult> results = resolveChildren(candidate, name, file, false, true);
      if (!results.isEmpty()) {
        for (RatedResolveResult result : results) {
          final PsiElement element = result.getElement();
          if (element != null) {
            if (!element.isValid()) {
              throw new PsiInvalidElementAccessException(
                  element, "Got an invalid candidate from resolveChild(): " + element.getClass());
            }
            resultList.add(element);
          }
        }
      }
    }
    if (!resultList.isEmpty()) {
      return rateResults(resultList);
    }
    return Collections.emptyList();
  }
  @Override
  public boolean isConfigurationFromContext(
      SubstepsRunConfiguration substepsRunConfiguration,
      ConfigurationContext configurationContext) {

    // return true, if this config was created from this context
    boolean rtn = false;

    log.debug("isConfigurationFromContext?");

    SubstepsRunnerConfigurationModel model = substepsRunConfiguration.getModel();

    String featureFilePath = configurationContext.getLocation().getVirtualFile().getPath();

    if (model.getPathToFeature().equals(featureFilePath)) {

      // it might be the same...

      PsiElement psiElement = configurationContext.getLocation().getPsiElement();
      if (psiElement instanceof ScenarioImpl) {

        ScenarioImpl scenarioImpl = (ScenarioImpl) psiElement;

        if (model.getScenarioName() != null
            && model.getScenarioName().equals(scenarioImpl.getScenarioName())) {
          rtn = true;
        } else {
          log.debug(
              "non matching scenario name model: "
                  + model.getScenarioName()
                  + " ctx: "
                  + scenarioImpl.getScenarioName());
        }
      } else {
        log.debug("not a scenario impl psi element: " + psiElement.getClass());
        if (model.getScenarioName() == null) {
          rtn = true;
        }
      }
    }
    log.debug("isConfigurationFromContext? : " + rtn);
    return rtn;
  }
示例#16
0
  private void doEnter(PsiElement atCaret, Editor editor) throws IncorrectOperationException {
    final PsiFile psiFile = atCaret.getContainingFile();

    final RangeMarker rangeMarker = createRangeMarker(atCaret);
    if (myFirstErrorOffset != Integer.MAX_VALUE) {
      editor.getCaretModel().moveToOffset(myFirstErrorOffset);
      reformat(atCaret);
      return;
    }

    reformat(atCaret);
    commit(editor);

    atCaret =
        GroovyRefactoringUtil.findElementInRange(
            ((GroovyFileBase) psiFile),
            rangeMarker.getStartOffset(),
            rangeMarker.getEndOffset(),
            atCaret.getClass());

    //    atCaret = CodeInsightUtil.findElementInRange(psiFile, rangeMarker.getStartOffset(),
    // rangeMarker.getEndOffset(), atCaret.getClass());

    for (EnterProcessor processor : ourEnterProcessors) {
      if (atCaret == null) {
        // Can't restore element at caret after enter processor execution!
        break;
      }

      if (processor.doEnter(editor, atCaret, isModified(editor))) return;
    }

    if (!isModified(editor)) {
      plainEnter(editor);
    } else {
      if (myFirstErrorOffset == Integer.MAX_VALUE) {
        editor.getCaretModel().moveToOffset(rangeMarker.getEndOffset());
      } else {
        editor.getCaretModel().moveToOffset(myFirstErrorOffset);
      }
    }
  }
  @NotNull
  static PsiElement loadTree(@NotNull PsiElement host, @NotNull PsiFile containingFile) {
    if (containingFile instanceof DummyHolder) {
      PsiElement context = containingFile.getContext();
      if (context != null) {
        PsiFile topFile = context.getContainingFile();
        topFile.getNode(); // load tree
        TextRange textRange =
            host.getTextRange().shiftRight(context.getTextRange().getStartOffset());

        PsiElement inLoadedTree =
            PsiTreeUtil.findElementOfClassAtRange(
                topFile, textRange.getStartOffset(), textRange.getEndOffset(), host.getClass());
        if (inLoadedTree != null) {
          host = inLoadedTree;
        }
      }
    }
    return host;
  }
  @NotNull
  @Override
  public String getDescriptiveName(@NotNull PsiElement element) {
    if (element instanceof CeylonPsi.AttributeDeclarationPsi) {
      return ((CeylonPsi.AttributeDeclarationPsi) element)
          .getCeylonNode()
          .getDeclarationModel()
          .getQualifiedNameString();
    } else if (element instanceof CeylonPsi.ClassOrInterfacePsi) {
      Tree.Declaration ceylonNode = ((CeylonPsi.ClassOrInterfacePsi) element).getCeylonNode();
      //            if (ceylonNode == null) {
      //                // perhaps a stub
      //                return ((CeylonPsi.ClassOrInterfacePsi) element).getQualifiedName();
      //            }
      Declaration model = ceylonNode.getDeclarationModel();
      return model == null ? ceylonNode.getIdentifier().getText() : model.getQualifiedNameString();
    } else if (element instanceof CeylonPsi.AnyMethodPsi) {
      Function model = ((CeylonPsi.AnyMethodPsi) element).getCeylonNode().getDeclarationModel();
      return model == null
          ? ((CeylonPsi.AnyMethodPsi) element).getCeylonNode().getIdentifier().getText()
          : model.getQualifiedNameString();
    } else if (element instanceof CeylonPsi.ParameterDeclarationPsi) {
      return ((CeylonPsi.ParameterDeclarationPsi) element)
          .getCeylonNode()
          .getTypedDeclaration()
          .getIdentifier()
          .getText();
    } else if (element instanceof CeylonPsi.TypeParameterDeclarationPsi) {
      return ((CeylonPsi.TypeParameterDeclarationPsi) element)
          .getCeylonNode()
          .getIdentifier()
          .getText();
    } else if (element instanceof CeylonFile) {
      return ((CeylonFile) element).getName();
    } else if (element instanceof CeylonPsi.ObjectDefinitionPsi) {
      return ((CeylonPsi.ObjectDefinitionPsi) element).getCeylonNode().getIdentifier().getText();
    }

    throw new UnsupportedOperationException(
        "Descriptive name not implemented for " + element.getClass());
  }
示例#19
0
  protected static <T extends PsiNamedElement> int getChildIndex(
      T element, PsiElement parent, String name, Class<T> hisClass) {
    PsiElement[] children = parent.getChildren();
    int index = 0;

    for (PsiElement child : children) {
      if (ReflectionCache.isAssignable(hisClass, child.getClass())) {
        T namedChild = (T) child;
        final String childName = namedChild.getName();

        if (Comparing.equal(name, childName)) {
          if (namedChild.equals(element)) {
            return index;
          }
          index++;
        }
      }
    }

    return index;
  }
示例#20
0
  @Nullable
  protected static <T extends PsiNamedElement> T restoreElementInternal(
      @NotNull PsiElement parent, String name, int index, Class<T> hisClass) {
    PsiElement[] children = parent.getChildren();

    for (PsiElement child : children) {
      if (ReflectionCache.isAssignable(hisClass, child.getClass())) {
        T namedChild = (T) child;
        final String childName = namedChild.getName();

        if (Comparing.equal(name, childName)) {
          if (index == 0) {
            return namedChild;
          }
          index--;
        }
      }
    }

    return null;
  }
  public LocalSearchScope(
      @NotNull PsiElement[] scope,
      @Nullable final String displayName,
      final boolean ignoreInjectedPsi) {
    myIgnoreInjectedPsi = ignoreInjectedPsi;
    myDisplayName = displayName;
    Set<PsiElement> localScope = new LinkedHashSet<PsiElement>(scope.length);

    for (final PsiElement element : scope) {
      LOG.assertTrue(element != null, "null element");
      LOG.assertTrue(element.getContainingFile() != null, element.getClass().getName());
      if (element instanceof PsiFile) {
        for (PsiFile file : ((PsiFile) element).getViewProvider().getAllFiles()) {
          if (file == null)
            throw new IllegalArgumentException(
                "file " + element + " returned null in its getAllFiles()");
          localScope.add(file);
        }
      } else if (element instanceof StubBasedPsiElement || element.getTextRange() != null) {
        localScope.add(element);
      }
    }
    myScope = PsiUtilCore.toPsiElementArray(localScope);
  }
示例#22
0
 private static boolean isLastOfItsKind(@NotNull PsiElement element, boolean down) {
   return getSiblingOfType(element, down, element.getClass()) == null;
 }
  public ASTNode processRange(final ASTNode element, final int startOffset, final int endOffset) {
    final PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(element);
    assert psiElement != null;
    final PsiFile file = psiElement.getContainingFile();
    final Document document = file.getViewProvider().getDocument();
    final RangeMarker rangeMarker =
        document != null && endOffset < document.getTextLength()
            ? document.createRangeMarker(startOffset, endOffset)
            : null;

    PsiElement elementToFormat =
        document instanceof DocumentWindow
            ? InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file)
            : psiElement;
    final PsiFile fileToFormat = elementToFormat.getContainingFile();

    final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(fileToFormat);
    if (builder != null) {
      TextRange range = preprocess(element, TextRange.create(startOffset, endOffset));
      if (document instanceof DocumentWindow) {
        DocumentWindow documentWindow = (DocumentWindow) document;
        range = documentWindow.injectedToHost(range);
      }

      // final SmartPsiElementPointer pointer =
      // SmartPointerManager.getInstance(psiElement.getProject()).createSmartPsiElementPointer(psiElement);
      final FormattingModel model =
          CoreFormatterUtil.buildModel(
              builder, elementToFormat, mySettings, FormattingMode.REFORMAT);
      if (file.getTextLength() > 0) {
        try {
          FormatterEx.getInstanceEx()
              .format(
                  model,
                  mySettings,
                  mySettings.getIndentOptions(fileToFormat.getFileType()),
                  new FormatTextRanges(range, true));

          wrapLongLinesIfNecessary(file, document, startOffset, endOffset);
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }

      if (!psiElement.isValid()) {
        if (rangeMarker != null) {
          final PsiElement at = file.findElementAt(rangeMarker.getStartOffset());
          final PsiElement result = PsiTreeUtil.getParentOfType(at, psiElement.getClass(), false);
          assert result != null;
          rangeMarker.dispose();
          return result.getNode();
        } else {
          assert false;
        }
      }
      //      return SourceTreeToPsiMap.psiElementToTree(pointer.getElement());
    }

    if (rangeMarker != null) {
      rangeMarker.dispose();
    }
    return element;
  }
 private static boolean typesEqual(final PsiElement newChild, final PsiElement oldChild) {
   return newChild != null && oldChild != null && newChild.getClass() == oldChild.getClass();
 }
示例#25
0
  @Override
  @NotNull
  public String getType(@NotNull PsiElement element) {
    if (element instanceof PsiDirectory) {
      return LangBundle.message("terms.directory");
    }
    if (element instanceof PsiFile) {
      return LangBundle.message("terms.file");
    }
    if (ThrowSearchUtil.isSearchable(element)) {
      return LangBundle.message("java.terms.exception");
    }
    if (element instanceof PsiPackage) {
      return LangBundle.message("java.terms.package");
    }
    if (element instanceof PsiLabeledStatement) {
      return LangBundle.message("java.terms.label");
    }
    if (element instanceof PsiClass) {
      if (((PsiClass) element).isAnnotationType()) {
        return LangBundle.message("java.terms.annotation.interface");
      }
      if (((PsiClass) element).isEnum()) {
        return LangBundle.message("java.terms.enum");
      }
      if (((PsiClass) element).isInterface()) {
        return LangBundle.message("java.terms.interface");
      }
      if (element instanceof PsiTypeParameter) {
        return LangBundle.message("java.terms.type.parameter");
      }
      return LangBundle.message("java.terms.class");
    }
    if (element instanceof PsiField) {
      return LangBundle.message("java.terms.field");
    }
    if (element instanceof PsiParameter) {
      return LangBundle.message("java.terms.parameter");
    }
    if (element instanceof PsiLocalVariable) {
      return LangBundle.message("java.terms.variable");
    }
    if (element instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod) element;
      final boolean isConstructor = psiMethod.isConstructor();
      if (isConstructor) {
        return LangBundle.message("java.terms.constructor");
      }
      return LangBundle.message("java.terms.method");
    }
    if (element instanceof PsiExpression) {
      return LangBundle.message("java.terms.expression");
    }
    if (element instanceof PsiJavaModule) {
      return LangBundle.message("java.terms.module");
    }

    final String name =
        TypePresentationService.getService().getTypePresentableName(element.getClass());
    if (name != null) {
      return name;
    }
    return "";
  }