com.intellij.psi.PsiIdentifier Java Examples

The following examples show how to use com.intellij.psi.PsiIdentifier. 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: MethodChainLookupElement.java    From litho with Apache License 2.0 6 votes vote down vote up
private static Template createTemplate(PsiElement from) {
  TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(from);
  PsiTreeUtil.processElements(
      from,
      psiElement -> {
        if (psiElement instanceof PsiIdentifier) {
          PsiIdentifier psiIdentifier = (PsiIdentifier) psiElement;
          String identifier = psiIdentifier.getText();
          if (TEMPLATE_INSERT_PLACEHOLDER.equals(identifier)) {
            templateBuilder.replaceElement(psiIdentifier, new TextExpression(""));
          } else if (TEMPLATE_INSERT_PLACEHOLDER_C.equals(identifier)) {
            templateBuilder.replaceElement(psiIdentifier, new TextExpression("c"));
          }
        }
        return true;
      });
  Template template = templateBuilder.buildTemplate();
  return template;
}
 
Example #2
Source File: VarTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testIntParameter() {
  myFixture.configureByText("a.java", "import lombok.experimental.var;\n" +
    "abstract class Test {\n" +
    "    private void test() {\n" +
    "       int[] myArray = new int[] {1, 2, 3, 4, 5};\n" +
    "       for(var my<caret>Var: myArray) {" +
    "       }\n" +
    "    } \n" +
    "}\n");
  final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
  assertTrue(elementAtCaret instanceof PsiIdentifier);
  final PsiElement localParameter = elementAtCaret.getParent();
  assertTrue(localParameter.toString(), localParameter instanceof PsiParameter);
  final PsiType type = ((PsiParameter) localParameter).getType();
  assertNotNull(localParameter.toString(), type);
  assertTrue(type.getCanonicalText(), type.equalsToText("int"));
}
 
Example #3
Source File: ValTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testIntParameter() {
  myFixture.configureByText("a.java", "import lombok.val;\n" +
    "abstract class Test {\n" +
    "    private void test() {\n" +
    "       int[] myArray = new int[] {1, 2, 3, 4, 5};\n" +
    "       for(val my<caret>Var: myArray) {" +
    "       }\n" +
    "    } \n" +
    "}\n");

  final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
  assertTrue(elementAtCaret instanceof PsiIdentifier);
  final PsiElement localParameter = elementAtCaret.getParent();
  assertTrue(localParameter.toString(), localParameter instanceof PsiParameter);
  final PsiType type = ((PsiParameter) localParameter).getType();
  assertNotNull(localParameter.toString(), type);
  assertTrue(type.getCanonicalText(), type.equalsToText("int"));
}
 
Example #4
Source File: LazyGetterHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static boolean isInitializedInConstructors(@NotNull PsiElement element) {
  if (!(element instanceof PsiIdentifier)) {
    return false;
  }
  PsiElement parent = element.getParent();
  if (!(parent instanceof PsiReferenceExpression)) {
    return false;
  }
  PsiElement qualifier = ((PsiReferenceExpression) parent).getQualifier();
  if (qualifier == null) {
    return false;
  }
  PsiReference reference = qualifier.getReference();
  if (reference == null) {
    return false;
  }
  PsiElement field = reference.resolve();
  if (!(field instanceof PsiField)) {
    return false;
  }
  PsiClass containingClass = ((PsiField) field).getContainingClass();
  if (containingClass == null) {
    return false;
  }
  return isInitializedInConstructors((PsiField) field, containingClass);
}
 
Example #5
Source File: PsiAnnotationProxyUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
private Object invoke(Method method, Object[] args) throws IllegalAccessException {
  Class<?> returnType = method.getReturnType();
  if (returnType.isEnum()) {
    PsiAnnotation currentAnnotation =
        AnnotationUtil.findAnnotationInHierarchy(
            mListOwner, Collections.singleton(mAnnotationClass.getCanonicalName()));
    PsiReferenceExpression declaredValue =
        (PsiReferenceExpression) currentAnnotation.findAttributeValue(method.getName());
    if (declaredValue == null) {
      return method.getDefaultValue();
    }
    PsiIdentifier identifier = PsiTreeUtil.getChildOfType(declaredValue, PsiIdentifier.class);
    return Enum.valueOf((Class<Enum>) returnType, identifier.getText());
  }

  try {
    if (args == null) {
      return method.invoke(mStubbed);
    }
    return method.invoke(mStubbed, args);
  } catch (InvocationTargetException e) {
    return method.getDefaultValue();
  }
}
 
Example #6
Source File: ComponentsMethodDeclarationHandlerTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void getGotoDeclarationTargets() {
  ApplicationManager.getApplication()
      .invokeAndWait(
          () -> {
            final PsiFile file =
                testHelper
                    .getFixture()
                    .configureByFile("ComponentsMethodDeclarationHandlerTest.java");
            PsiClass testSpecClass = findClass("TestSpec", file);
            PsiSearchUtils.addMock("TestSpec", testSpecClass);
            final PsiIdentifier componentMethodCall =
                findIdentifier(testSpecClass.findMethodsByName("test", false)[0], "method1");

            final PsiElement[] specMethods =
                new ComponentsMethodDeclarationHandler()
                    .getGotoDeclarationTargets(
                        componentMethodCall, 0, testHelper.getFixture().getEditor());
            assertThat(specMethods.length).isOne();
            PsiMethod targetMethod = (PsiMethod) specMethods[0];
            assertThat(targetMethod.getName()).isEqualTo("method1");
            assertThat(targetMethod.getContainingClass()).isSameAs(testSpecClass);
          });
}
 
Example #7
Source File: JavaCamelRouteLineMarkerProviderTestIT.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
public void testCamelGutterForMethodCallFrom() {
    myFixture.configureByFiles("JavaCamelRouteLineMarkerProviderFromMethodCallTestData.java");
    List<GutterMark> gutters = myFixture.findAllGutters();
    assertNotNull(gutters);

    //remove first element since it is navigate to super implementation gutter icon
    gutters.remove(0);
    // remove last element since it is from method returning route uri
    gutters.remove(gutters.size() - 1);

    assertEquals("Should contain 1 Camel gutters", 1, gutters.size());

    assertGuttersHasCamelIcon(gutters);

    LineMarkerInfo.LineMarkerGutterIconRenderer firstGutter = (LineMarkerInfo.LineMarkerGutterIconRenderer) gutters.get(0);
    assertTrue(firstGutter.getLineMarkerInfo().getElement() instanceof PsiIdentifier);
    assertEquals("The navigation start element doesn't match", "calcEndpoint",
        firstGutter.getLineMarkerInfo().getElement().getText());

    List<GotoRelatedItem> firstGutterTargets = GutterTestUtil.getGutterNavigationDestinationElements(firstGutter);
    assertEquals("Navigation should have two targets", 2, firstGutterTargets.size());
    assertEquals("The navigation variable target element doesn't match", "calcEndpoint",
        GutterTestUtil.getGuttersWithMethodTarget(firstGutterTargets).get(0).getName());
}
 
Example #8
Source File: JavaCamelRouteLineMarkerProviderTestIT.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
public void testCamelGutterForVariableAndConstant() {
    myFixture.configureByFiles("JavaCamelRouteLineMarkerProviderFromVariableTestData.java");
    List<GutterMark> gutters = myFixture.findAllGutters();
    assertNotNull(gutters);

    //remove first element since it is navigate to super implementation gutter icon
    gutters.remove(0);

    assertEquals("Should contain 2 Camel gutters", 2, gutters.size());

    assertGuttersHasCamelIcon(gutters);

    LineMarkerInfo.LineMarkerGutterIconRenderer firstGutter = (LineMarkerInfo.LineMarkerGutterIconRenderer) gutters.get(0);
    assertTrue(firstGutter.getLineMarkerInfo().getElement() instanceof PsiIdentifier);
    assertEquals("The navigation start element doesn't match", "uriVar",
        firstGutter.getLineMarkerInfo().getElement().getText());

    List<GotoRelatedItem> firstGutterTargets = GutterTestUtil.getGutterNavigationDestinationElements(firstGutter);
    assertEquals("Navigation should have two targets", 2, firstGutterTargets.size());
}
 
Example #9
Source File: VarTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void verifyLocalVariableType(final String expectedType) {
  final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
  assertTrue(elementAtCaret instanceof PsiIdentifier);
  final PsiElement localVariable = elementAtCaret.getParent();
  assertTrue(localVariable.toString(), localVariable instanceof PsiLocalVariable);
  final PsiType type = ((PsiLocalVariable) localVariable).getType();
  assertNotNull(localVariable.toString(), type);
  assertTrue(type.getCanonicalText(), type.equalsToText(expectedType));
}
 
Example #10
Source File: ValTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void verifyLocalVariableType(final String expectedType) {
  final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
  assertTrue(elementAtCaret instanceof PsiIdentifier);
  final PsiElement localVariable = elementAtCaret.getParent();
  assertTrue(localVariable.toString(), localVariable instanceof PsiLocalVariable);
  final PsiType type = ((PsiLocalVariable) localVariable).getType();
  assertNotNull(localVariable.toString(), type);
  assertTrue(type.getCanonicalText(), type.equalsToText(expectedType));
}
 
Example #11
Source File: LazyGetterHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean isLazyGetterHandled(@NotNull PsiElement element) {
  if (!(element instanceof PsiIdentifier)) {
    return false;
  }
  PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class);
  if (field == null) {
    return false;
  }

  final PsiAnnotation getterAnnotation = PsiAnnotationSearchUtil.findAnnotation(field, Getter.class);
  return null != getterAnnotation && PsiAnnotationUtil.getBooleanAnnotationValue(getterAnnotation, "lazy", false);
}
 
Example #12
Source File: PsiJavaElementVisitor.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
private Set<String> getMethods(final PsiReferenceExpression methodExpr) {
    Set<String> methods = new HashSet<>();
    if (WindowObjects.getInstance().isIncludeMethods()) {
        PsiIdentifier[] identifiers =
                PsiTreeUtil.getChildrenOfType(methodExpr, PsiIdentifier.class);
        if (identifiers != null) {
            for (PsiIdentifier identifier : identifiers) {
                methods.add(identifier.getText());
            }
        }
    }
    return methods;
}
 
Example #13
Source File: BeanInjectLineMarkerProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
private PsiAnnotation getBeanInjectAnnotation(PsiElement element) {
    if (element instanceof PsiIdentifier && element.getText().equals("BeanInject")) {
        PsiAnnotation annotation = PsiTreeUtil.getParentOfType(element, PsiAnnotation.class);
        if (annotation != null && CamelIdeaUtils.BEAN_INJECT_ANNOTATION.equals(annotation.getQualifiedName())) {
            return annotation;
        }
    }
    return null;
}
 
Example #14
Source File: CamelRouteLineMarkerProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Camel route from a PsiElement
 *
 * @param element the element
 * @return the String route or null if there nothing can be found
 */
private String findRouteFromElement(PsiElement element) {
    XmlTag xml = PsiTreeUtil.getParentOfType(element, XmlTag.class);
    if (xml != null) {
        return ((XmlTagImpl) element.getParent()).getAttributeValue("uri");
    }


    if (element instanceof PsiIdentifier) {
        PsiIdentifier id = (PsiIdentifier) element;
        String text = id.getText();
        if (text != null) {
            return text;
        }
    }

    if (element instanceof PsiJavaToken) {
        return element.getText();
    }

    // Only variables can be resolved?
    Optional<PsiVariable> variable = resolvedIdentifier(element)
        .filter(PsiVariable.class::isInstance)
        .map(PsiVariable.class::cast);
    if (variable.isPresent()) {
        // Try to resolve variable and recursive search route
        return variable.map(PsiVariable::getInitializer)
            .map(this::findRouteFromElement)
            .orElse(null);
    }

    return null;
}
 
Example #15
Source File: CamelRouteLineMarkerProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
private boolean isRouteStartIdentifier(PsiIdentifier identifier, PsiElement resolvedIdentifier) {
    // Eval methods from parent PsiMethodCallExpression to exclude start route method (from)
    PsiElement element = identifier;
    if (resolvedIdentifier instanceof PsiMethod) {
        element = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class);
    }
    if (element == null) {
        return false;
    }
    return getCamelIdeaUtils().isCamelRouteStartExpression(element);
}
 
Example #16
Source File: CamelRouteLineMarkerProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Return the resolved reference to a {@link PsiVariable} or {@link PsiMethod}
 * for the given element if it is a {@link PsiIdentifier}.
 *
 * @param element the element to resolve
 * @return an {@link Optional} representing the resolved reference or empty
 *         if reference could not be resolved.
 */
private Optional<PsiElement> resolvedIdentifier(PsiElement element) {
    if (element instanceof PsiIdentifier) {
        return Optional.ofNullable(element.getParent())
            .map(PsiElement::getReference)
            .map(PsiReference::resolve)
            .filter(resolved -> PsiVariable.class.isInstance(resolved) || PsiMethod.class.isInstance(resolved));
    }
    return Optional.empty();
}
 
Example #17
Source File: JavaCamelIdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public PsiElement getPsiElementForCamelBeanMethod(PsiElement element) {
    if (element instanceof PsiLiteral || element.getParent() instanceof PsiLiteralExpression) {
        final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(element, PsiExpressionList.class);
        if (expressionList != null) {
            final PsiIdentifier identifier = PsiTreeUtil.getChildOfType(expressionList.getPrevSibling(), PsiIdentifier.class);
            if (identifier != null && identifier.getNextSibling() == null && ("method" .equals(identifier.getText()) || "bean" .equals(identifier.getText()))) {
                return expressionList;
            }
        }
    }
    return null;
}
 
Example #18
Source File: ComponentsMethodDeclarationHandlerTest.java    From litho with Apache License 2.0 5 votes vote down vote up
private static PsiIdentifier findIdentifier(PsiElement cls, String name) {
  final Collection<PsiIdentifier> identifiers =
      PsiTreeUtil.findChildrenOfType(cls, PsiIdentifier.class);
  for (PsiIdentifier identifier : identifiers) {
    if (identifier.textMatches(name)) return identifier;
  }
  return null;
}
 
Example #19
Source File: BaseLithoComponentsDeclarationHandler.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * @return Stream of resolved elements from the given element or an empty stream if nothing found.
 */
static Stream<PsiElement> resolve(PsiElement sourceElement) {
  return Optional.of(sourceElement)
      .filter(PsiIdentifier.class::isInstance)
      .map(element -> PsiTreeUtil.getParentOfType(element, PsiJavaCodeReferenceElement.class))
      .map(PsiElement::getReferences)
      .map(
          psiReferences ->
              Stream.of(psiReferences).map(PsiReference::resolve).filter(Objects::nonNull))
      .orElse(Stream.empty());
}
 
Example #20
Source File: CompletionUtils.java    From litho with Apache License 2.0 5 votes vote down vote up
private static ElementPattern<? extends PsiElement> annotationInClass() {
  // PsiIdentifier -> PsiJavaCodeReference -> PsiAnnotation -> PsiModifierList -> PsiClass
  return PlatformPatterns.psiElement(PsiIdentifier.class)
      .withSuperParent(2, PsiAnnotation.class)
      .withSuperParent(4, PsiClass.class)
      .afterLeaf("@");
}
 
Example #21
Source File: CompletionUtils.java    From litho with Apache License 2.0 5 votes vote down vote up
private static ElementPattern<? extends PsiElement> annotationAboveMethod() {
  // PsiIdentifier -> PsiJavaCodeReference -> PsiAnnotation -> PsiModifierList -> PsiMethod
  return PlatformPatterns.psiElement(PsiIdentifier.class)
      .withSuperParent(2, PsiAnnotation.class)
      .withSuperParent(4, PsiMethod.class)
      .afterLeaf("@");
}
 
Example #22
Source File: SqliteMagicLightParameter.java    From sqlitemagic with Apache License 2.0 4 votes vote down vote up
@Override
public PsiIdentifier getNameIdentifier() {
  return myNameIdentifier;
}
 
Example #23
Source File: HaxeClassModel.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Nullable
public PsiIdentifier getNamePsi() {
  return haxeClass.getNameIdentifier();
}
 
Example #24
Source File: AnonymousHaxeTypeImpl.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public PsiIdentifier getNameIdentifier() {
  return new HaxeIdentifierImpl(new HaxeDummyASTNode("AnonymousType"));
}
 
Example #25
Source File: LombokLightFieldBuilder.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@NotNull
@Override
public PsiIdentifier getNameIdentifier() {
  return myNameIdentifier;
}
 
Example #26
Source File: LombokLightParameter.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public PsiIdentifier getNameIdentifier() {
  return myNameIdentifier;
}
 
Example #27
Source File: StatePropCompletionContributor.java    From litho with Apache License 2.0 4 votes vote down vote up
private static ElementPattern<? extends PsiElement> codeReferencePattern() {
  return PlatformPatterns.psiElement(PsiIdentifier.class)
      .withParent(PsiJavaCodeReferenceElement.class)
      .withLanguage(JavaLanguage.INSTANCE);
}
 
Example #28
Source File: DefaultPropertyFoldingBuilder.java    From litho with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(
    @NotNull PsiElement root, @NotNull Document document, boolean quick) {
  FoldingGroup group = FoldingGroup.newGroup(FOLDING_GROUP_NAME);

  final Map<String, PsiExpression> defaultProps =
      PsiTreeUtil.findChildrenOfType(root, PsiField.class).stream()
          .filter(LithoPluginUtils::isPropDefault)
          .filter(field -> field.getInitializer() != null)
          .collect(Collectors.toMap(PsiField::getName, PsiField::getInitializer));

  if (defaultProps.isEmpty()) {
    return FoldingDescriptor.EMPTY;
  }

  return PsiTreeUtil.findChildrenOfType(root, PsiParameter.class).stream()
      .filter(LithoPluginUtils::isProp)
      .map(
          parameter -> {
            String name = parameter.getName();
            if (name == null) {
              return null;
            }
            PsiExpression nameExpression = defaultProps.get(name);
            if (nameExpression == null) {
              return null;
            }
            PsiIdentifier nameIdentifier = parameter.getNameIdentifier();
            if (nameIdentifier == null) {
              return null;
            }
            return new FoldingDescriptor(
                nameIdentifier.getNode(), nameIdentifier.getTextRange(), group) {
              @Override
              public String getPlaceholderText() {
                return name + ": " + nameExpression.getText();
              }
            };
          })
      .filter(Objects::nonNull)
      .toArray(FoldingDescriptor[]::new);
}
 
Example #29
Source File: CamelRouteLineMarkerProvider.java    From camel-idea-plugin with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true it the give element is an identifier inside a route start expression.
 *
 * @param element the element to evaluate
 * @return true it the give element is an identifier inside a route start expression
 */
private boolean isCamelRouteStartIdentifierExpression(@NotNull PsiElement element) {
    return resolvedIdentifier(element)
        .filter(resolved -> isRouteStartIdentifier((PsiIdentifier) element, resolved))
        .isPresent();
}