com.intellij.psi.PsiExpression Java Examples

The following examples show how to use com.intellij.psi.PsiExpression. 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: IntroduceLombokVariableHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public IntroduceVariableSettings getSettings(Project project, Editor editor, PsiExpression expr,
                                             PsiExpression[] occurrences, TypeSelectorManagerImpl typeSelectorManager,
                                             boolean declareFinalIfAll, boolean anyAssignmentLHS, InputValidator validator,
                                             PsiElement anchor, JavaReplaceChoice replaceChoice) {
  final IntroduceVariableSettings variableSettings;

  if (ApplicationManager.getApplication().isUnitTestMode()) {
    variableSettings = new UnitTestMockVariableSettings(expr);
  } else {
    variableSettings = super.getSettings(project, editor, expr, occurrences, typeSelectorManager, declareFinalIfAll,
      anyAssignmentLHS, validator, anchor, replaceChoice);
  }

  return getIntroduceVariableSettings(project, variableSettings);
}
 
Example #2
Source File: PsiJavaElementVisitor.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
private void visitPsiFields(final PsiField psiField) {
    if (!ClassUtils.isPrimitive(psiField.getType())) {
        String type = removeSpecialSymbols(psiField.getType().getCanonicalText());
        if (psiField.getInitializer() != null) {
            PsiExpression psiExpression = psiField.getInitializer();
            if (psiExpression != null) {
                PsiType psiType = psiExpression.getType();
                if (psiType != null && !ClassUtils.isPrimitive(psiType)) {
                    String psiFieldInitializer =
                            removeSpecialSymbols(psiType.getCanonicalText());
                    addInMap(psiFieldInitializer, emptySet);
                }
            }
        }
        addInMap(type, emptySet);
    }
}
 
Example #3
Source File: MethodChainLookupElementTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void createMethodChain() {
  testHelper.runInReadAction(
      project -> {
        List<String> names = new ArrayList<>(2);
        names.add("methodName1");
        names.add("otherName");

        PsiExpression methodChain =
            MethodChainLookupElement.createMethodChain(project, "methodNameBase", names);
        assertEquals(
            "methodNameBase(insert_placeholder_c)\n"
                + ".methodName1(insert_placeholder)\n"
                + ".otherName(insert_placeholder)",
            methodChain.getText());
      });
}
 
Example #4
Source File: MethodChainLookupElement.java    From litho with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static PsiExpression createMethodChain(
    Project project, String firstName, List<? extends String> methodNames) {
  PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  StringBuilder expressionText =
      new StringBuilder(firstName + "(" + TEMPLATE_INSERT_PLACEHOLDER_C + ")");
  methodNames.forEach(
      methodName ->
          expressionText
              .append("\n.")
              .append(methodName)
              .append("(")
              .append(TEMPLATE_INSERT_PLACEHOLDER)
              .append(")"));
  return factory.createExpressionFromText(expressionText.toString(), null);
}
 
Example #5
Source File: AbstractExpression.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
public String toString() {
    PsiExpression expression = getExpression();
    if (expression == null || expression.getType() == null) {
        return "";
    } else {
        return expression.getType().getCanonicalText();
    }
}
 
Example #6
Source File: CreateFieldQuickFix.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
  final PsiClass myClass = (PsiClass) startElement;
  final Editor editor = CodeInsightUtil.positionCursor(project, psiFile, myClass.getLBrace());
  if (editor != null) {
    WriteCommandAction.writeCommandAction(project, psiFile).run(() ->
      {
        final PsiElementFactory psiElementFactory = JavaPsiFacade.getElementFactory(project);
        final PsiField psiField = psiElementFactory.createField(myName, myType);

        final PsiModifierList modifierList = psiField.getModifierList();
        if (null != modifierList) {
          for (String modifier : myModifiers) {
            modifierList.setModifierProperty(modifier, true);
          }
        }
        if (null != myInitializerText) {
          PsiExpression psiInitializer = psiElementFactory.createExpressionFromText(myInitializerText, psiField);
          psiField.setInitializer(psiInitializer);
        }

        final List<PsiGenerationInfo<PsiField>> generationInfos = GenerateMembersUtil.insertMembersAtOffset(myClass.getContainingFile(), editor.getCaretModel().getOffset(),
          Collections.singletonList(new PsiGenerationInfo<>(psiField)));
        if (!generationInfos.isEmpty()) {
          PsiField psiMember = generationInfos.iterator().next().getPsiMember();
          editor.getCaretModel().moveToOffset(psiMember.getTextRange().getEndOffset());
        }

        UndoUtil.markPsiFileForUndo(psiFile);
      }
    );
  }
}
 
Example #7
Source File: PolyadicExpressionTranslator.java    From java2typescript with Apache License 2.0 5 votes vote down vote up
public static void translate(PsiPolyadicExpression element, TranslationContext ctx) {
    for (PsiExpression expression : element.getOperands()) {
        PsiJavaToken token = element.getTokenBeforeOperand(expression);
        if (token != null) {
            ctx.append(' ');
            JavaTokenTranslator.translate(token, ctx);
            ctx.append(' ');
        }
        ExpressionTranslator.translate(expression, ctx);
    }
}
 
Example #8
Source File: ExpressionListTranslator.java    From java2typescript with Apache License 2.0 5 votes vote down vote up
public static void translate(PsiExpressionList element, TranslationContext ctx) {
    PsiExpression[] arguments = element.getExpressions();
    for (int i = 0; i < arguments.length; i++) {
        ExpressionTranslator.translate(arguments[i], ctx);
        if (i != arguments.length - 1) {
            ctx.append(", ");
        }
    }
}
 
Example #9
Source File: PsiJavaElementVisitor.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
private void visitPsiReturnStatement(final PsiReturnStatement element) {
    PsiExpression returnValue = element.getReturnValue();
    if (returnValue != null) {
        PsiType returnType = returnValue.getType();
        if (returnType != null) {
            String qualifiedName = removeSpecialSymbols(returnType.getCanonicalText());
            addInMap(qualifiedName, emptySet);
        }
    }
}
 
Example #10
Source File: PsiJavaElementVisitor.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
private void visitPsiReferenceExpression(final PsiReferenceExpression element) {
    PsiExpression psiExpression = element.getQualifierExpression();
    if (psiExpression != null) {
        PsiType psiType = psiExpression.getType();
        if (psiType != null) {
            String qualifiedName = removeSpecialSymbols(psiType.getCanonicalText());
            addInMap(qualifiedName, emptySet);
        }
    }
}
 
Example #11
Source File: CamelRouteLineMarkerProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first operand from a {@link PsiPolyadicExpression}
 *
 * @param psiLiteralExpression the {@link PsiLiteralExpression} that is part of a {@link PsiPolyadicExpression}
 * @return the first {@link PsiExpression} if the given {@link PsiLiteralExpression} is part of a {@link PsiPolyadicExpression}, null otherwise
 */
@Nullable
private static PsiExpression getFirstExpressionFromPolyadicExpression(PsiLiteralExpression psiLiteralExpression) {
    if (isPartOfPolyadicExpression(psiLiteralExpression)) {
        PsiPolyadicExpression psiPolyadicExpression = PsiTreeUtil.getParentOfType(psiLiteralExpression, PsiPolyadicExpression.class);
        if (psiPolyadicExpression != null) {
            return psiPolyadicExpression.getOperands()[0];
        }
    }
    return null;
}
 
Example #12
Source File: CamelDocumentationProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
    if (ServiceManager.getService(element.getProject(), CamelService.class).isCamelPresent()) {
        PsiExpressionList exps = PsiTreeUtil.getNextSiblingOfType(originalElement, PsiExpressionList.class);
        if (exps != null) {
            if (exps.getExpressions().length >= 1) {
                // grab first string parameter (as the string would contain the camel endpoint uri
                final PsiClassType stringType = PsiType.getJavaLangString(element.getManager(), element.getResolveScope());
                PsiExpression exp = Arrays.stream(exps.getExpressions()).filter(
                    e -> e.getType() != null && stringType.isAssignableFrom(e.getType()))
                    .findFirst().orElse(null);
                if (exp instanceof PsiLiteralExpression) {
                    Object o = ((PsiLiteralExpression) exp).getValue();
                    String val = o != null ? o.toString() : null;
                    // okay only allow this popup to work when its from a RouteBuilder class
                    PsiClass clazz = PsiTreeUtil.getParentOfType(originalElement, PsiClass.class);
                    if (clazz != null) {
                        PsiClassType[] types = clazz.getExtendsListTypes();
                        boolean found = Arrays.stream(types).anyMatch(p -> p.getClassName().equals("RouteBuilder"));
                        if (found) {
                            String componentName = asComponentName(val);
                            if (componentName != null) {
                                // the quick info cannot be so wide so wrap at 120 chars
                                return generateCamelComponentDocumentation(componentName, val, 120, element.getProject());
                            }
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
Example #13
Source File: RequiredPropAnnotator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static void handleMethodCall(
    PsiMethodCallExpression currentMethodCall,
    Set<String> methodNamesCalled,
    BiConsumer<Collection<String>, PsiReferenceExpression> errorHandler,
    Function<PsiMethodCallExpression, PsiClass> generatedClassResolver) {
  PsiReferenceExpression methodExpression = currentMethodCall.getMethodExpression();
  methodNamesCalled.add(methodExpression.getReferenceName());

  // Assumption to find next method in a call chain
  PsiMethodCallExpression nextMethodCall =
      PsiTreeUtil.getChildOfType(methodExpression, PsiMethodCallExpression.class);
  if (nextMethodCall != null) {
    handleMethodCall(nextMethodCall, methodNamesCalled, errorHandler, generatedClassResolver);
  } else if ("create".equals(methodExpression.getReferenceName())) {
    // Finish call chain
    // TODO T47712852: allow setting required prop in another statement
    Optional.ofNullable(generatedClassResolver.apply(currentMethodCall))
        .map(generatedCls -> collectMissingRequiredProps(generatedCls, methodNamesCalled))
        .filter(result -> !result.isEmpty())
        .ifPresent(
            missingRequiredProps -> errorHandler.accept(missingRequiredProps, methodExpression));
  }

  PsiExpressionList argumentList = currentMethodCall.getArgumentList();
  for (PsiExpression argument : argumentList.getExpressions()) {
    handleIfMethodCall(argument, errorHandler, generatedClassResolver);
  }
}
 
Example #14
Source File: RequiredPropAnnotator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static void handleIfMethodCall(
    @Nullable PsiExpression expression,
    BiConsumer<Collection<String>, PsiReferenceExpression> errorHandler,
    Function<PsiMethodCallExpression, PsiClass> generatedClassResolver) {
  if (expression instanceof PsiMethodCallExpression) {
    PsiMethodCallExpression rootMethodCall = (PsiMethodCallExpression) expression;
    handleMethodCall(rootMethodCall, new HashSet<>(), errorHandler, generatedClassResolver);
  }
}
 
Example #15
Source File: AbstractExpression.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
private void processExpression(PsiExpression expression) {
    ExpressionExtractor expressionExtractor = new ExpressionExtractor();
    List<PsiExpression> assignments = expressionExtractor.getAssignments(expression);
    List<PsiExpression> postfixExpressions = expressionExtractor.getPostfixExpressions(expression);
    List<PsiExpression> prefixExpressions = expressionExtractor.getPrefixExpressions(expression);
    processVariables(expressionExtractor.getVariableInstructions(expression), assignments, postfixExpressions, prefixExpressions);
    processMethodInvocations(expressionExtractor.getMethodInvocations(expression));
    processClassInstanceCreations(expressionExtractor.getClassInstanceCreations(expression));
    processArrayCreations(expressionExtractor.getArrayCreations(expression));
    processLiterals(expressionExtractor.getLiterals(expression));
}
 
Example #16
Source File: InstanceOfMethodInvocation.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
    return expression instanceof PsiMethodCallExpression;
}
 
Example #17
Source File: LombokVarValPostfixTemplate.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void expandForChooseExpression(@NotNull PsiElement expression, @NotNull Editor editor) {
  IntroduceVariableHandler handler = new IntroduceLombokVariableHandler(selectedTypeFQN);
  handler.invoke(expression.getProject(), editor, (PsiExpression) expression);
}
 
Example #18
Source File: IntroduceLombokVariableHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
UnitTestMockVariableSettings(PsiExpression expr) {
  this.expr = expr;
}
 
Example #19
Source File: InstanceOfPostfixExpression.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
    return expression instanceof PsiPostfixExpression;
}
 
Example #20
Source File: InstanceOfInfixExpression.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiBinaryExpression;
}
 
Example #21
Source File: ArrayInitializerExpressionTranslator.java    From java2typescript with Apache License 2.0 4 votes vote down vote up
public static void translate(PsiArrayInitializerExpression element, TranslationContext ctx) {
    boolean hasToBeClosed, isByteArray = false;
    if (ctx.NATIVE_ARRAY && element.getType() != null && element.getType().equalsToText("int[]")) {
        ctx.append("new Int32Array([");
        hasToBeClosed = true;
    } else if (ctx.NATIVE_ARRAY && element.getType() != null && element.getType().equalsToText("double[]")) {
        ctx.append("new Float64Array([");
        hasToBeClosed = true;
    } else if (ctx.NATIVE_ARRAY && element.getType() != null && element.getType().equalsToText("long[]")) {
        ctx.append("new Float64Array([");
        hasToBeClosed = true;
    } else if (ctx.NATIVE_ARRAY && element.getType() != null && element.getType().equalsToText("byte[]")) {
        ctx.append("new Int8Array([");
        hasToBeClosed = true;
    } else {
        ctx.append("[");
        hasToBeClosed = false;
    }
    PsiExpression[] initializers = element.getInitializers();
    if (element.getType() != null &&
            element.getType().getPresentableText().equals("byte[]")) {
        isByteArray = true;
    }
    if (initializers.length > 0) {
        for (int i = 0; i < initializers.length; i++) {
            ExpressionTranslator.translate(initializers[i], ctx);
            if (isByteArray &&
                    initializers[i].getType() != null &&
                    initializers[i].getType().getPresentableText().equals("char")) {
                ctx.append(".charCodeAt(0)");
            }
            if (i != initializers.length - 1) {
                ctx.append(", ");
            }
        }
    }
    ctx.append("]");
    if (hasToBeClosed) {
        ctx.append(")");
    }
}
 
Example #22
Source File: TextUtilsIsEmptyTemplate.java    From android-postfix-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean value(PsiElement element) {
    return InheritanceUtil.isInheritor(((PsiExpression) element).getType(), "java.lang.CharSequence") && !AndroidPostfixTemplatesUtils.isAnnotatedNullable(element);
}
 
Example #23
Source File: InstanceOfPrefixExpression.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
    return expression instanceof PsiPrefixExpression;
}
 
Example #24
Source File: InstanceOfSuperMethodInvocation.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiSuperExpression;
}
 
Example #25
Source File: InstanceOfCastExpression.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiTypeCastExpression;
}
 
Example #26
Source File: InstanceOfClassInstanceCreation.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiNewExpression;
}
 
Example #27
Source File: InstanceOfSuperFieldAccess.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiSuperExpression;
}
 
Example #28
Source File: InstanceOfAssignment.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiAssignmentExpression;
}
 
Example #29
Source File: InstanceOfVariable.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
    return (expression instanceof PsiReferenceExpression &&
            ((PsiReferenceExpression) expression).resolve() instanceof PsiVariable);
}
 
Example #30
Source File: InstanceOfArrayCreation.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(PsiExpression expression) {
	return expression instanceof PsiNewExpression;
}