com.intellij.psi.util.PsiTreeUtil#findFirstParent ( )源码实例Demo

下面列出了com.intellij.psi.util.PsiTreeUtil#findFirstParent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String toolId) {
    if (!toolId.equals("PhpUnused")) {
        return false;
    }

    if (isActionMethod(element)) {
        PsiElement classParent = PsiTreeUtil.findFirstParent(element, e -> e instanceof PhpClass);
        if (classParent == null) {
            return false;
        }

        return isControllerPhpClass((PhpClass) classParent);
    }

    if (isControllerClassElement(element)) {
        return isControllerPhpClass((PhpClass) element);
    }

    return false;
}
 
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createTagModeForLoopTemplate(expression);
    tagTemplate.addVariable("EACH", new TextExpression(expression.getText()), true);
    tagTemplate.addVariable("AS", new TextExpression("myVar"), true);

    int textOffset = expression.getTextOffset();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
@Override
public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
    FluidInlineStatement expression = (FluidInlineStatement) PsiTreeUtil.findFirstParent(context, psiElement -> psiElement instanceof FluidInlineStatement);
    if (expression == null) {
        return;
    }

    Template tagTemplate = LiveTemplateFactory.createTagModeAliasTemplate(expression);
    tagTemplate.addVariable("ALIAS", new TextExpression("myVar"), true);
    tagTemplate.addVariable("EXPR", new TextExpression("'" + expression.getText() + "'"), true);

    int textOffset = expression.getTextOffset() + expression.getTextLength();
    editor.getCaretModel().moveToOffset(textOffset);

    TemplateManager.getInstance(context.getProject()).startTemplate(editor, tagTemplate);
    PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());

    expression.delete();
}
 
private void assertCanResolveReference(@NotNull String content) {
    PsiFile psiFile = myFixture.configureByText("foo.fluid", content);

    PsiElement elementAtCaret = psiFile.findElementAt(myFixture.getEditor().getCaretModel().getOffset());
    FluidViewHelperReference viewHelperExpr = (FluidViewHelperReference) PsiTreeUtil.findFirstParent(elementAtCaret, e -> e instanceof FluidViewHelperReference);
    PsiReference[] references = viewHelperExpr.getReferences();
    for (PsiReference reference : references) {
        if (reference instanceof ViewHelperReference) {
            PsiElement resolve = reference.resolve();
            if (resolve instanceof PhpClass) {

                return;
            }

            fail("Could not resolve element");
        }
    }

}
 
源代码5 项目: BashSupport   文件: InjectionReferenceTest.java
@NotNull
private PsiElement findInjectedBashReference(String fileName, String lookupText) {
    PsiElement javaLiteral = configurePsiAtCaret(fileName);
    Assert.assertTrue(javaLiteral instanceof PsiLanguageInjectionHost);

    //inject bash into the literal
    InjectLanguageAction.invokeImpl(getProject(), myFixture.getEditor(), javaLiteral.getContainingFile(), Injectable.fromLanguage(BashFileType.BASH_LANGUAGE));

    String fileContent = javaLiteral.getContainingFile().getText();
    PsiElement bashPsiLeaf = InjectedLanguageManager.getInstance(getProject()).findInjectedElementAt(myFixture.getFile(), fileContent.indexOf(lookupText) + 1);
    Assert.assertNotNull(bashPsiLeaf);

    PsiElement reference = PsiTreeUtil.findFirstParent(bashPsiLeaf, psiElement -> psiElement.getReference() != null);
    Assert.assertNotNull(reference);

    return reference;
}
 
源代码6 项目: intellij-haxe   文件: HaxeParameterInfoHandler.java
private HaxeExpression getExpressionAtPlace(@NotNull PsiElement place, final List<HaxeExpression> expressionList) {
  return (HaxeExpression)PsiTreeUtil.findFirstParent(place, new Condition<PsiElement>() {
    @Override
    public boolean value(PsiElement element) {
      return element instanceof HaxeExpression && expressionList.indexOf(element) >= 0;
    }
  });
}
 
源代码7 项目: idea-php-typo3-plugin   文件: TranslationIndex.java
void extractTranslationStub(@NotNull XmlTag tag) {
    String id = tag.getAttributeValue("id");
    String languageKeyToUse = String.valueOf(languageKey);

    XmlTag fileTag = (XmlTag) PsiTreeUtil.findFirstParent(tag, t -> PlatformPatterns.psiElement(XmlTag.class).withName("file").accepts(t));

    String sourceValue = "";
    String targetValue = "";
    if (fileTag != null) {
        if (fileTag.getAttributeValue("source-language") != null) {
            sourceValue = fileTag.getAttributeValue("source-language");
        }

        if (fileTag.getAttributeValue("target-language") != null) {
            targetValue = fileTag.getAttributeValue("target-language");
        }
    }

    if (!sourceValue.isEmpty() && !targetValue.isEmpty()) {
        languageKeyToUse = targetValue;
    }

    String[] compileIds;
    try {
        compileIds = compileIds(file, extensionKeyFromFile, id);
    } catch (FileNotFoundException e) {
        return;
    }

    for (String calculatedId : compileIds) {
        if (result.containsKey(calculatedId)) {
            result.get(calculatedId).add(createStubTranslationFromIndex(file, extensionKeyFromFile, languageKeyToUse, tag, id));
        } else {
            ArrayList<StubTranslation> v = new ArrayList<>();
            v.add(createStubTranslationFromIndex(file, extensionKeyFromFile, languageKeyToUse, tag, id));

            result.put(calculatedId, v);
        }
    }
}
 
/**
 * Gets whether the specified element is inside a placeholder in a template
 */
boolean isInsideTemplateElement(PsiElement psiElement) {
    return PsiTreeUtil.findFirstParent(
            psiElement, false,
            el -> el instanceof GraphQLTemplateDefinition || el instanceof GraphQLTemplateSelection || el instanceof GraphQLTemplateVariable
    ) != null;
}
 
@NotNull
@Override
public PsiElementVisitor buildRealVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpStringLiteralExpression(StringLiteralExpression expression) {
            if (!getLoadRequireJsModulePattern().accepts(expression)) {
                super.visitPhpStringLiteralExpression(expression);
                return;
            }

            PsiElement firstParent = PsiTreeUtil.findFirstParent(expression, e -> e instanceof MethodReference);
            if (!(firstParent instanceof MethodReference)) {
                super.visitPhpStringLiteralExpression(expression);
                return;
            }

            MethodReference methodReference = (MethodReference) firstParent;
            if (methodReference.getName() == null || !methodReference.getName().equals("loadRequireJsModule")) {
                super.visitPhpStringLiteralExpression(expression);
                return;
            }

            if (expression.getPrevPsiSibling() instanceof StringLiteralExpression) {
                super.visitPhpStringLiteralExpression(expression);
                return;
            }

            if (JavaScriptUtil.getModuleMap(expression.getProject()).containsKey(expression.getContents())) {
                return;
            }

            problemsHolder.registerProblem(expression, String.format("Unknown JavaScript module \"%s\"", expression.getContents()));
        }
    };
}
 
源代码10 项目: idea-php-laravel-plugin   文件: RouteGroupUtil.java
/**
 * Analyzes Route::group elements and returns string values for specified property.
 * Route::group(['namespace' => 'Foo'], function() {
 *      Route::group(['namespace' => 'Bar'], function() {
 *          Route::get(...
 *      });
 * });
 *
 * getRouteGroupPropertiesCollection(Route::get element, "namespace") will return list with 'Foo', 'Bar'
 */
@NotNull
public static List<String> getRouteGroupPropertiesCollection(PsiElement element, String propertyName)
{
    List<String> values = new ArrayList<>();

    RouteGroupCondition routeGroupCondition = new RouteGroupCondition();

    PsiElement routeGroup = PsiTreeUtil.findFirstParent(element, true, routeGroupCondition);

    while (routeGroup != null) {
        ArrayCreationExpression arrayCreation = PsiTreeUtil.getChildOfType(((MethodReference)routeGroup).getParameterList(), ArrayCreationExpression.class);

        if (arrayCreation != null) {
            for (ArrayHashElement hashElement : arrayCreation.getHashElements()) {
                if (hashElement.getKey() instanceof StringLiteralExpression) {
                    if (propertyName.equals(((StringLiteralExpression) hashElement.getKey()).getContents())) {
                        if (hashElement.getValue() instanceof StringLiteralExpression) {
                            values.add(((StringLiteralExpression) hashElement.getValue()).getContents());
                        }
                        break;
                    }
                }
            }
        }

        routeGroup = PsiTreeUtil.findFirstParent(routeGroup, true, routeGroupCondition);
    }

    Collections.reverse(values);
    return values;
}
 
@Override
public void visitXmlTag(XmlTag tag) {
    if (tag.getName().equals("f:alias")) {
        XmlAttribute map = tag.getAttribute("map");
        if (map != null) {
            XmlAttributeValue valueElement = map.getValueElement();
            if (valueElement != null) {
                TextRange valueTextRange = valueElement.getValueTextRange();

                PsiElement fluidElement = extractLanguagePsiElementForElementAtPosition(FluidLanguage.INSTANCE, tag, valueTextRange.getStartOffset() + 1);

                FluidArrayCreationExpr fluidArray = (FluidArrayCreationExpr) PsiTreeUtil.findFirstParent(fluidElement, x -> x instanceof FluidArrayCreationExpr);
                if (fluidArray != null) {
                    fluidArray.getArrayKeyList().forEach(fluidArrayKey -> {
                        if (fluidArrayKey.getFirstChild() instanceof FluidStringLiteral) {
                            String key = ((FluidStringLiteral) fluidArrayKey.getFirstChild()).getContents();
                            variables.put(key, new FluidVariable(key));

                            return;
                        }

                        variables.put(fluidArrayKey.getText(), new FluidVariable(fluidArrayKey.getText()));
                    });
                }
            }
        }
    }

    super.visitXmlTag(tag);
}
 
private ConfigurationContext getTest1Context() {
  // Set up fake source code.
  final PsiElement testIdentifier = setUpDartElement(
    TEST_FILE_PATH, fileContents, "test 1", LeafPsiElement.class);
  final PsiElement test =
    PsiTreeUtil.findFirstParent(testIdentifier, element -> element instanceof DartStringLiteralExpression);
  assertThat(test, not(equalTo(null)));
  return new ConfigurationContext(test);
}
 
private ConfigurationContext getMainContext() {
  // Set up fake source code.
  final PsiElement mainIdentifier = setUpDartElement(
    "workspace/foo/bar.dart", fileContents, "main", LeafPsiElement.class);
  final PsiElement main = PsiTreeUtil.findFirstParent(
    mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
  assertThat(main, not(equalTo(null)));

  return new ConfigurationContext(main);
}
 
private ConfigurationContext getTest1Context() {
  // Set up fake source code.
  final PsiElement testIdentifier = setUpDartElement(
    TEST_FILE_PATH, fileContents, "test 1", LeafPsiElement.class);
  final PsiElement test =
    PsiTreeUtil.findFirstParent(testIdentifier, element -> element instanceof DartStringLiteralExpression);
  assertThat(test, not(equalTo(null)));
  return new ConfigurationContext(test);
}
 
源代码15 项目: camel-idea-plugin   文件: IdeaUtils.java
/**
 * Returns the first parent of the given element which matches the given condition.
 *
 * @param element element from which the search starts
 * @param strict if true, element itself cannot be returned if it matches the condition
 * @param matchCondition condition which the parent must match to be returned
 * @param stopCondition condition which stops the search, causing the method to return null
 */
public PsiElement findFirstParent(@Nullable PsiElement element,
                                  boolean strict,
                                  Predicate<? super PsiElement> matchCondition,
                                  Predicate<? super PsiElement> stopCondition) {
    PsiElement parent = PsiTreeUtil.findFirstParent(element, strict, e -> stopCondition.test(e) || matchCondition.test(e));
    if (parent != null && matchCondition.test(parent)) {
        return parent;
    } else {
        return null;
    }
}
 
源代码16 项目: litho   文件: EventHandlerAnnotator.java
@Override
public void annotate(PsiElement element, AnnotationHolder holder) {
  DEBUG_LOGGER.logStep("start " + element);
  // Implementation similar to {@link HighlightMethodUtil#checkMethodCall}
  if (!(element instanceof PsiMethodCallExpression)) {
    return;
  }
  // MethodCall == method usage
  final PsiMethodCallExpression eventHandlerSetter = (PsiMethodCallExpression) element;
  final PsiExpressionList list = eventHandlerSetter.getArgumentList();
  if (!list.isEmpty()) {
    return;
  }
  final String eventQualifiedName = resolveEventName(eventHandlerSetter);
  if (eventQualifiedName == null) {
    return;
  }
  final PsiClass parentCls =
      (PsiClass) PsiTreeUtil.findFirstParent(eventHandlerSetter, PsiClass.class::isInstance);
  if (parentCls == null) {
    return;
  }
  final LayoutSpecModel parentLayoutModel = ComponentGenerateUtils.createLayoutModel(parentCls);
  if (parentLayoutModel == null) {
    return;
  }
  final ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>>
      implementedEventHandlers = parentLayoutModel.getEventMethods();
  final String componentQualifiedName = parentLayoutModel.getComponentTypeName().toString();
  final Project project = eventHandlerSetter.getProject();
  final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
  final String message = "Add " + AddArgumentFix.getCapitalizedMethoName(eventHandlerSetter);
  final SpecModelValidationError error = new SpecModelValidationError(list, message);

  final List<IntentionAction> fixes =
      implementedEventHandlers.stream()
          .filter(handler -> eventQualifiedName.equals(handler.typeModel.name.reflectionName()))
          .map(handler -> handler.name.toString())
          .distinct()
          .map(
              methodName ->
                  AddArgumentFix.createAddMethodCallFix(
                      eventHandlerSetter, componentQualifiedName, methodName, elementFactory))
          .collect(Collectors.toList());

  final PsiClass event = PsiSearchUtils.findClass(project, eventQualifiedName);
  if (event != null) {
    fixes.add(
        AddArgumentFix.createNewMethodCallFix(
            eventHandlerSetter, componentQualifiedName, event, parentCls));
  }
  AnnotatorUtils.addError(holder, error, fixes);
  DEBUG_LOGGER.logStep("end " + element);
}
 
源代码17 项目: BashSupport   文件: BashResolveUtil.java
/**
 * @return true if the definition of this variable is not child of a conditional command or loop.
 */
public static boolean hasStaticVarDefPath(BashVar bashVar) {
    BashReference reference = bashVar.getNeighborhoodReference();
    if (reference == null) {
        return false;
    }

    PsiElement closestDef = reference.resolve();
    if (closestDef == null) {
        return false;
    }

    // if the closest def is in a different def scope, then we can't handle that
    // (e.g. var is top-level, def is in a function or var is in a function and def in another function, etc.)
    BashFunctionDef varScope = BashPsiUtils.findNextVarDefFunctionDefScope(bashVar);
    BashFunctionDef defScope = BashPsiUtils.findNextVarDefFunctionDefScope(closestDef);
    if (varScope == null && defScope != null) {
        return false;
    }

    // we can't handle different functions as scope
    if (varScope != null && !varScope.isEquivalentTo(defScope)) {
        return false;
    }

    // atm we can't handle different files
    PsiFile psiFile = bashVar.getContainingFile();
    if (varScope == null && !psiFile.isEquivalentTo(closestDef.getContainingFile())) {
        return false;
    }

    Collection<BashVarDef> allDefs = StubIndex.getElements(BashVarDefIndex.KEY, bashVar.getReferenceName(), bashVar.getProject(), GlobalSearchScope.fileScope(psiFile), BashVarDef.class);
    for (BashVarDef candidateDef : allDefs) {
        ProgressManager.checkCanceled();

        // skip var defs which are not in our own def scope
        BashFunctionDef scope = BashPsiUtils.findNextVarDefFunctionDefScope(candidateDef);
        if (varScope != null && !varScope.isEquivalentTo(scope)) {
            continue;
        }

        // it's not a static path if the var def is in a conditional block or loop and if our var is not
        PsiElement parent = PsiTreeUtil.findFirstParent(candidateDef, psi -> psi instanceof BashConditionalBlock || psi instanceof BashLoop);
        if (parent != null && !PsiTreeUtil.isAncestor(parent, bashVar, true)) {
            return false;
        }
    }

    return true;
}
 
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {

    PsiElement position = completionParameters.getPosition();
    if(!Symfony2ProjectComponent.isEnabled(position)) {
        return;
    }

    PsiElement psiElement = PsiTreeUtil.findFirstParent(position, psiElement1 -> {

        if (psiElement1 instanceof YAMLKeyValue) {
            String s = ((YAMLKeyValue) psiElement1).getKeyText().toLowerCase();
            if ("joinTable".equalsIgnoreCase(s)) {
                return true;
            }
        }

        return false;
    });

    if(psiElement == null) {
        return;
    }

    PsiElement yamlCompoundValue = psiElement.getParent();
    if(!(yamlCompoundValue instanceof YAMLCompoundValue)) {
        return;
    }

    String className = YamlHelper.getYamlKeyValueAsString((YAMLCompoundValue) yamlCompoundValue, "targetEntity", false);
    if(className == null) {
        return;
    }

    PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(psiElement.getProject(), className);
    if(phpClass == null) {
        return;
    }

    for(DoctrineModelField field: EntityHelper.getModelFields(phpClass)) {
        if(field.getRelation() == null) {
            String columnName = field.getColumn();
            if(columnName == null) {
                completionResultSet.addElement(LookupElementBuilder.create(field.getName()).withIcon(Symfony2Icons.DOCTRINE));
            } else {
                completionResultSet.addElement(LookupElementBuilder.create(columnName).withTypeText(field.getName(), false).withIcon(Symfony2Icons.DOCTRINE));
            }
        }
    }

}
 
源代码19 项目: bamboo-soy   文件: ParamUtils.java
private static SoyTemplateBlock getParentTemplateBlock(PsiElement element) {
  return (SoyTemplateBlock)
      PsiTreeUtil.findFirstParent(element, psiElement -> psiElement instanceof SoyTemplateBlock);
}
 
源代码20 项目: bamboo-soy   文件: Scope.java
@Nullable
static PsiElement getFirstScopeParent(PsiElement element) {
  return PsiTreeUtil.findFirstParent(element, true, psiElement -> psiElement instanceof Scope);
}