Java Code Examples for com.intellij.psi.util.PsiTreeUtil#findFirstParent()

The following examples show how to use com.intellij.psi.util.PsiTreeUtil#findFirstParent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InjectionReferenceTest.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: UnusedActionControllerMethodInspectionSuppressor.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example 3
Source File: ForEachPostfixTemplate.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@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();
}
 
Example 4
Source File: ViewHelperReferenceContributorTest.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
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");
        }
    }

}
 
Example 5
Source File: AliasPostfixTemplate.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@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();
}
 
Example 6
Source File: RouteGroupUtil.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 7
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 8
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example 9
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example 10
Source File: BazelTestConfigProducerTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example 11
Source File: InTemplateDeclarationVariableProvider.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@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);
}
 
Example 12
Source File: HaxeParameterInfoHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
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;
    }
  });
}
 
Example 13
Source File: MissingModulePHPInspection.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@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()));
        }
    };
}
 
Example 14
Source File: GraphQLValidationAnnotator.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source File: TranslationIndex.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
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);
        }
    }
}
 
Example 16
Source File: YamlCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@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));
            }
        }
    }

}
 
Example 17
Source File: ParamUtils.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
private static SoyTemplateBlock getParentTemplateBlock(PsiElement element) {
  return (SoyTemplateBlock)
      PsiTreeUtil.findFirstParent(element, psiElement -> psiElement instanceof SoyTemplateBlock);
}
 
Example 18
Source File: Scope.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
@Nullable
static PsiElement getFirstScopeParent(PsiElement element) {
  return PsiTreeUtil.findFirstParent(element, true, psiElement -> psiElement instanceof Scope);
}
 
Example 19
Source File: BashResolveUtil.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
/**
 * @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;
}
 
Example 20
Source File: EventHandlerAnnotator.java    From litho with Apache License 2.0 4 votes vote down vote up
@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);
}