@Nullable Resolution getResolutionFrom(PsiField field) { PsiAnnotation annotation = scenarioStateProvider.getJGivenAnnotationOn(field); if (annotation == null) { return null; } PsiExpression annotationValue = annotationValueProvider.getAnnotationValue(annotation, FIELD_RESOLUTION); return Optional.ofNullable(annotationValue) .map(PsiElement::getText) .map(t -> { for (Resolution resolution : Resolution.values()) { if (resolution != Resolution.AUTO && t.contains(resolution.name())) { return resolution; } } return getResolutionForFieldType(field); }).orElse(getResolutionForFieldType(field)); }
private int findArgPos( PsiMethodCallExpression methodCall, PsiElement firstElem ) { PsiExpression[] args = methodCall.getArgumentList().getExpressions(); for( int i = 0; i < args.length; i++ ) { PsiExpression arg = args[i]; PsiElement csr = firstElem; while( csr != null && csr != firstElem ) { csr = csr.getParent(); } if( csr == firstElem ) { return i; } } throw new IllegalStateException(); }
public boolean satisfiedBy(PsiElement element) { if (!(element instanceof PsiJavaToken)) { return false; } final PsiElement parent = element.getParent(); if (!(parent instanceof PsiPolyadicExpression)) { return false; } final PsiPolyadicExpression expression = (PsiPolyadicExpression)parent; final PsiExpression[] operands = expression.getOperands(); if (operands.length < 2) { return false; } PsiExpression prevOperand = null; for (PsiExpression operand : operands) { final PsiJavaToken token = expression.getTokenBeforeOperand(operand); if (element == token) { if (prevOperand == null || operand.getText().equals(prevOperand.getText())) { return false; } break; } prevOperand = operand; } return !ComparisonUtils.isComparison(expression); }
@Override public void visitSynchronizedStatement( @NotNull PsiSynchronizedStatement statement) { super.visitSynchronizedStatement(statement); final PsiExpression lockExpression = statement.getLockExpression(); if (lockExpression == null) { return; } final String type = TypeUtils.expressionHasTypeOrSubtype( lockExpression, "java.util.concurrent.locks.Lock", "java.util.concurrent.locks.ReadWriteLock"); if (type == null) { return; } registerError(lockExpression, type); }
@Override public void visitArrayInitializerExpression( PsiArrayInitializerExpression expression) { super.visitArrayInitializerExpression(expression); final PsiExpression[] initializers = expression.getInitializers(); if (initializers.length > 0) { return; } if (expression.getParent() instanceof PsiNewExpression) { return; } if (ExpressionUtils.isDeclaredConstant(expression)) { return; } registerError(expression); }
@Override public void processIntention(@NotNull PsiElement element) { final PsiJavaToken token = (PsiJavaToken)element; final PsiElement parent = token.getParent(); if (!(parent instanceof PsiPolyadicExpression)) { return; } final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent; final PsiExpression[] operands = polyadicExpression.getOperands(); final StringBuilder newExpression = new StringBuilder(); String prevOperand = null; final String tokenText = token.getText() + ' '; // 2- -1 without the space is not legal for (PsiExpression operand : operands) { final PsiJavaToken token1 = polyadicExpression.getTokenBeforeOperand(operand); if (token == token1) { newExpression.append(operand.getText()).append(tokenText); continue; } if (prevOperand != null) { newExpression.append(prevOperand).append(tokenText); } prevOperand = operand.getText(); } newExpression.append(prevOperand); PsiReplacementUtil.replaceExpression(polyadicExpression, newExpression.toString()); }
@Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final String name = methodExpression.getReferenceName(); if (!"setScale".equals(name) && !"divide".equals(name)) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); if (PsiUtilCore.hasErrorElementChild(argumentList)) { return; } final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return; } if (!TypeUtils.expressionHasTypeOrSubtype(expression, "java.math.BigDecimal")) { return; } registerMethodCallError(expression); }
@Override public void doFix(final Project project, ProblemDescriptor descriptor) { final PsiExpression expression = (PsiExpression)descriptor.getPsiElement(); final JavaRefactoringActionHandlerFactory factory = JavaRefactoringActionHandlerFactory.getInstance(); final RefactoringActionHandler extractHandler = factory.createExtractMethodHandler(); final DataManager dataManager = DataManager.getInstance(); final DataContext dataContext = dataManager.getDataContext(); final Runnable runnable = new Runnable() { @Override public void run() { extractHandler.invoke(project, new PsiElement[]{expression}, dataContext); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { ApplicationManager.getApplication().invokeLater(runnable); } }
public IntroduceVariableDialog(Project project, PsiExpression expression, int occurrencesCount, boolean anyLValueOccurences, boolean declareFinalIfAll, TypeSelectorManager typeSelectorManager, IntroduceVariableHandler.Validator validator) { super(project, true); myProject = project; myExpression = expression; myOccurrencesCount = occurrencesCount; myAnyLValueOccurences = anyLValueOccurences; myDeclareFinalIfAll = declareFinalIfAll; myTypeSelectorManager = typeSelectorManager; myValidator = validator; setTitle(REFACTORING_NAME); init(); }
@Override public void visitNewExpression(@NotNull PsiNewExpression expression) { super.visitNewExpression(expression); if (!ExpressionUtils.hasType(expression, "java.text.SimpleDateFormat")) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList == null) { return; } final PsiExpression[] arguments = argumentList.getExpressions(); for (PsiExpression argument : arguments) { if (ExpressionUtils.hasType(argument, "java.util.Locale")) { return; } } registerNewExpressionError(expression); }
public static boolean isPowerOfTwo(PsiExpression rhs) { if (!(rhs instanceof PsiLiteralExpression)) { return false; } final PsiLiteralExpression literal = (PsiLiteralExpression)rhs; final Object value = literal.getValue(); if (!(value instanceof Number)) { return false; } if (value instanceof Double || value instanceof Float) { return false; } int intValue = ((Number)value).intValue(); if (intValue <= 0) { return false; } while (intValue % 2 == 0) { intValue >>= 1; } return intValue == 1; }
@Override public PsiType getType() { final Template template = getTemplate(); String text = template.getTemplateText(); StringBuilder resultingText = new StringBuilder(text); int segmentsCount = template.getSegmentsCount(); for (int j = segmentsCount - 1; j >= 0; j--) { if (template.getSegmentName(j).equals(TemplateImpl.END)) { continue; } resultingText.insert(template.getSegmentOffset(j), "xxx"); } try { final PsiExpression templateExpression = JavaPsiFacade.getElementFactory(myContext.getProject()).createExpressionFromText(resultingText.toString(), myContext); return templateExpression.getType(); } catch (IncorrectOperationException e) { // can happen when text of the template does not form an expression return null; } }
@Nullable @Override public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) { if (params.length == 1) { Result result = params[0].calculateResult(context); if (result != null) { PsiExpression expression = MacroUtil.resultToPsiExpression(result, context); if (expression != null) { PsiType type = expression.getType(); if (type != null) { return new PsiTypeResult(type, context.getProject()); } } } } return null; }
@Override public void visitExpressionStatement(@NotNull PsiExpressionStatement statement) { super.visitExpressionStatement(statement); final PsiExpression expression = statement.getExpression(); if (!(expression instanceof PsiNewExpression)) { return; } final PsiNewExpression newExpression = (PsiNewExpression)expression; final PsiExpression[] arrayDimensions = newExpression.getArrayDimensions(); if (arrayDimensions.length != 0) { return; } if (newExpression.getArrayInitializer() != null) { return; } registerNewExpressionError(newExpression); }
public void testSiblingInnerClassType() { doTest(new MockIntroduceVariableHandler("vari", true, false, false, "A.B") { @Override public IntroduceVariableSettings getSettings(Project project, Editor editor, PsiExpression expr, PsiExpression[] occurrences, TypeSelectorManagerImpl typeSelectorManager, boolean declareFinalIfAll, boolean anyAssignmentLHS, InputValidator validator, PsiElement anchor, final OccurrencesChooser.ReplaceChoice replaceChoice) { final PsiType type = typeSelectorManager.getDefaultType(); assertTrue(type.getPresentableText(), type.getPresentableText().equals("B")); return super.getSettings(project, editor, expr, occurrences, typeSelectorManager, declareFinalIfAll, anyAssignmentLHS, validator, anchor, replaceChoice); } }); }
@Override protected void processIntention(@NotNull final PsiElement element) throws IncorrectOperationException { final PsiExpression expression = (PsiExpression)element; final Number value = (Number)ExpressionUtils.computeConstantExpression(expression); if (value == null) return; final PsiType type = expression.getType(); final boolean negated = ExpressionUtils.isNegative(expression); final String resultString = convertValue(value, type, negated); if (resultString == null) return; if (negated) { PsiReplacementUtil.replaceExpression((PsiExpression)expression.getParent(), resultString); } else { PsiReplacementUtil.replaceExpression(expression, resultString); } }
private static boolean isR2Expression(PsiElement node) { if (node.getParent() == null) { return false; } String text = node.getText(); PsiElement parent = LintUtils.skipParentheses(node.getParent()); return (text.equals(R2) || text.contains(".R2")) && parent instanceof PsiExpression && endsWithAny(parent.getText(), SUPPORTED_TYPES); }
@Nullable PsiExpression getAnnotationValue(PsiAnnotation annotation, String annotationKey) { PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes(); return Arrays.stream(attributes) .filter(a -> annotationKey.equalsIgnoreCase(a.getName())) .map(PsiNameValuePair::getValue) .filter(v -> v instanceof PsiExpression) .map(v -> (PsiExpression) v) .findFirst().orElse(null); }
private boolean hasExpressionElement(PsiElement[] psiElements) { for (PsiElement psiElement : psiElements) { if ((psiElement instanceof PsiExpression)) { return true; } } return false; }
private PsiType findInitializerType( PsiElement firstElem ) { PsiElement csr = firstElem; while( csr != null && !(csr instanceof PsiLocalVariableImpl) ) { csr = csr.getParent(); } if( csr instanceof PsiLocalVariableImpl ) { PsiExpression initializer = ((PsiLocalVariableImpl)csr).getInitializer(); return initializer == null ? null : initializer.getType(); } return null; }
private PsiType processForeach( PsiElement parentDeclarationScope ) { PsiType result = null; if( parentDeclarationScope instanceof PsiForeachStatement ) { final PsiForeachStatement foreachStatement = (PsiForeachStatement)parentDeclarationScope; final PsiExpression iteratedValue = foreachStatement.getIteratedValue(); if( iteratedValue != null ) { result = JavaGenericsUtil.getCollectionItemType( iteratedValue ); } } return result; }
private static void extractExpressions(@NonNull PsiElement element, List<PsiExpression> expressions) { for (PsiElement child : element.getChildren()) { if (child instanceof PsiExpression) { expressions.add((PsiExpression) child); continue; } extractExpressions(child, expressions); } }
public static void debugVariable(PsiLocalVariable variable) { if (variable != null) { PsiIdentifier id = variable.getNameIdentifier(); PsiTypeElement type = variable.getTypeElement(); PsiExpression init = variable.getInitializer(); System.out.println("variable -> " + variable.getText() + ", id=" + (id != null ? id.getText() : "null") + ", type=" + (type != null ? type.getText() : "null") + ", init=" + (init != null ? init.getText() : "null")); } }
public static void debugExpressions(String tag, PsiElement root, List<PsiExpression> expressions) { System.out.println(tag + " :root=>>>>\n" + root.getText() + "\n<<<"); for (PsiExpression expr : expressions) { System.out.println("expression -> " + expr.getText()); } System.out.println(); }
public static void debugParameters(String tag, PsiElement root, List<PsiParameter> parameters) { System.out.println(tag + " :root=>>>>\n" + root.getText() + "\n<<<"); for (PsiParameter param : parameters) { PsiIdentifier id = param.getNameIdentifier(); PsiTypeElement type = param.getTypeElement(); PsiExpression init = param.getInitializer(); System.out.println("parameter -> " + param.getText() + ", id=" + (id != null ? id.getText() : "null") + ", type=" + (type != null ? type.getText() : "null")); } System.out.println(); }
@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 = StringUtils.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; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final String newJBColor = String.format("new %s(%s, new java.awt.Color())", JBColor.class.getName(), element.getText()); final PsiExpression expression = factory.createExpressionFromText(newJBColor, element.getContext()); final PsiElement newElement = element.replace(expression); final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); final int offset = el.getTextOffset() + el.getText().length() - 2; final Editor editor = PsiUtilBase.findEditor(el); if (editor != null) { editor.getCaretModel().moveToOffset(offset); } }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); final String jbColorConstant = String.format("%s.%s", JBColor.class.getName(), myConstantName); final PsiExpression expression = factory.createExpressionFromText(jbColorConstant, element.getContext()); final PsiElement newElement = element.replace(expression); JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); if (!(element instanceof PsiBinaryExpression)) { return; } final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)element; final PsiExpression lhs = ParenthesesUtils.stripParentheses(binaryExpression.getLOperand()); final PsiExpression rhs = ParenthesesUtils.stripParentheses(binaryExpression.getROperand()); if (!(lhs instanceof PsiBinaryExpression) || !(rhs instanceof PsiBinaryExpression)) { return; } final PsiBinaryExpression lBinaryExpression = (PsiBinaryExpression)lhs; final PsiBinaryExpression rBinaryExpression = (PsiBinaryExpression)rhs; final PsiExpression llhs = ParenthesesUtils.stripParentheses(lBinaryExpression.getLOperand()); final PsiExpression lrhs = ParenthesesUtils.stripParentheses(rBinaryExpression.getLOperand()); if (llhs == null || lrhs == null) { return; } final PsiExpression thenExpression = ParenthesesUtils.stripParentheses(lBinaryExpression.getROperand()); final PsiExpression elseExpression = ParenthesesUtils.stripParentheses(rBinaryExpression.getROperand()); if (thenExpression == null || elseExpression == null) { return; } if (BoolUtils.isNegation(llhs) ) { PsiReplacementUtil.replaceExpression(binaryExpression, getText(lrhs) + '?' + getText(elseExpression) + ':' + getText(thenExpression)); } else { PsiReplacementUtil.replaceExpression(binaryExpression, getText(llhs) + '?' + getText(thenExpression) + ':' + getText(elseExpression)); } }
@Override public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) { super.visitBinaryExpression(expression); if (!ComparisonUtils.isComparison(expression)) { return; } final PsiExpression lhs = expression.getLOperand(); final PsiExpression rhs = expression.getROperand(); if (!isConstantExpression(rhs) || isConstantExpression(lhs)) { return; } registerError(expression); }
public void doTest(String expressionText, String messageFormatText, String... foundExpressionTexts) { final PsiExpression expression = JavaPsiFacade.getElementFactory(getProject()).createExpressionFromText(expressionText, null); final StringBuilder result = new StringBuilder(); final ArrayList<PsiExpression> args = new ArrayList<PsiExpression>(); PsiConcatenationUtil.buildFormatString(expression, result, args, false); assertEquals(messageFormatText, result.toString()); assertEquals(foundExpressionTexts.length, args.size()); for (int i = 0; i < foundExpressionTexts.length; i++) { final String foundExpressionText = foundExpressionTexts[i]; assertEquals(foundExpressionText, args.get(i).getText()); } }
public static boolean isEqualityComparison(@NotNull PsiExpression expression) { if (!(expression instanceof PsiPolyadicExpression)) { return false; } final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression; final IElementType tokenType = polyadicExpression.getOperationTokenType(); return tokenType.equals(JavaTokenType.EQEQ) || tokenType.equals(JavaTokenType.NE); }
public PsiTypeCastExpressionPattern withOperand(final ElementPattern<? extends PsiExpression> operand) { return with(new PatternCondition<PsiTypeCastExpression>("withOperand") { @Override public boolean accepts(@NotNull PsiTypeCastExpression psiTypeCastExpression, ProcessingContext context) { return operand.accepts(psiTypeCastExpression.getOperand(), context); } }); }
public PsiMethodCallPattern withQualifier(final ElementPattern<? extends PsiExpression> qualifier) { return with(new PatternCondition<PsiMethodCallExpression>("withQualifier") { @Override public boolean accepts(@NotNull PsiMethodCallExpression psiMethodCallExpression, ProcessingContext context) { return qualifier.accepts(psiMethodCallExpression.getMethodExpression().getQualifierExpression(), context); } }); }
public PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException { PsiElementFactory elementFactory = JavaPsiFacade.getInstance(context.getProject()).getElementFactory(); try { return elementFactory.createExpressionFromText("this[" + myIndex + "]", null); } catch (IncorrectOperationException e) { throw new EvaluateException(e.getMessage(), e); } }
public PsiExpression getDescriptorEvaluation(DebuggerContext context) throws EvaluateException { PsiElementFactory elementFactory = JavaPsiFacade.getInstance(context.getProject()).getElementFactory(); try { return elementFactory.createExpressionFromText(getName(), PositionUtil.getContextElement(context)); } catch (IncorrectOperationException e) { throw new EvaluateException(DebuggerBundle.message("error.invalid.local.variable.name", getName()), e); } }
@Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiExpression literal = (PsiExpression)descriptor.getPsiElement(); final String text = literal.getText(); final String newText = text.replace('l', 'L'); PsiReplacementUtil.replaceExpression(literal, newText); }
public boolean isOK(IntroduceVariableSettings settings) { String name = settings.getEnteredName(); final PsiElement anchor; final boolean replaceAllOccurrences = settings.isReplaceAllOccurrences(); if (replaceAllOccurrences) { anchor = myAnchorStatementIfAll; } else { anchor = myAnchorStatement; } final PsiElement scope = anchor.getParent(); if(scope == null) return true; final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); final HashSet<PsiVariable> reportedVariables = new HashSet<PsiVariable>(); JavaUnresolvableLocalCollisionDetector.CollidingVariableVisitor visitor = new JavaUnresolvableLocalCollisionDetector.CollidingVariableVisitor() { public void visitCollidingElement(PsiVariable collidingVariable) { if (!reportedVariables.contains(collidingVariable)) { reportedVariables.add(collidingVariable); String message = RefactoringBundle.message("introduced.variable.will.conflict.with.0", RefactoringUIUtil.getDescription(collidingVariable, true)); conflicts.putValue(collidingVariable, message); } } }; JavaUnresolvableLocalCollisionDetector.visitLocalsCollisions(anchor, name, scope, anchor, visitor); if (replaceAllOccurrences) { final PsiExpression[] occurences = myOccurenceManager.getOccurrences(); for (PsiExpression occurence : occurences) { IntroduceVariableBase.checkInLoopCondition(occurence, conflicts); } } else { IntroduceVariableBase.checkInLoopCondition(myOccurenceManager.getMainOccurence(), conflicts); } if (conflicts.size() > 0) { return myIntroduceVariableBase.reportConflicts(conflicts, myProject, settings); } else { return true; } }
@Override public void doFix(Project project, ProblemDescriptor descriptor) { final PsiExpression literalExpression = (PsiExpression)descriptor.getPsiElement(); final String text = literalExpression.getText(); final String newText = getCanonicalForm(text); PsiReplacementUtil.replaceExpression(literalExpression, newText); }
public boolean satisfiedBy(@NotNull PsiElement element) { if (!(element instanceof PsiExpression)) { return false; } final PsiExpression expression = (PsiExpression)element; final PsiElement parent = element.getParent(); return !UnclearBinaryExpressionInspection.mightBeConfusingExpression(parent) && UnclearBinaryExpressionInspection.isUnclearExpression(expression, parent); }