@Override protected void updateTitle(@Nullable final PsiVariable variable, final String value) { final PsiElement declarationScope = variable != null ? ((PsiParameter) variable).getDeclarationScope() : null; if (declarationScope instanceof PsiMethod) { final PsiMethod psiMethod = (PsiMethod) declarationScope; final StringBuilder buf = new StringBuilder(); buf.append(psiMethod.getName()).append(" ("); boolean frst = true; final List<TextRange> ranges2Remove = new ArrayList<>(); TextRange addedRange = null; for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) { if (frst) { frst = false; } else { buf.append(", "); } int startOffset = buf.length(); if (myMustBeFinal || myPanel.isGenerateFinal()) { buf.append("final "); } buf.append(parameter.getType().getPresentableText()) .append(" ") .append(variable == parameter ? value : parameter.getName()); int endOffset = buf.length(); if (variable == parameter) { addedRange = new TextRange(startOffset, endOffset); } else if (myPanel.isParamToRemove(parameter)) { ranges2Remove.add(new TextRange(startOffset, endOffset)); } } buf.append(")"); setPreviewText(buf.toString()); final MarkupModel markupModel = DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true); markupModel.removeAllHighlighters(); for (TextRange textRange : ranges2Remove) { markupModel.addRangeHighlighter( textRange.getStartOffset(), textRange.getEndOffset(), 0, getTestAttributesForRemoval(), HighlighterTargetArea.EXACT_RANGE); } markupModel.addRangeHighlighter( addedRange.getStartOffset(), addedRange.getEndOffset(), 0, getTextAttributesForAdd(), HighlighterTargetArea.EXACT_RANGE); revalidate(); } }
public String[] getAdditionalIconNames() { ArrayList<String> result = new ArrayList<String>(); String[] sa = new String[0]; if (myEnd instanceof PsiMethod) { PsiMethod m = (PsiMethod) myEnd; if (m.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) { result.add("nodes/c_public"); } else if (m.getModifierList().hasModifierProperty(PsiModifier.PROTECTED)) { result.add("nodes/c_protected"); } else if (m.getModifierList().hasModifierProperty(PsiModifier.PRIVATE)) { result.add("nodes/c_private"); } else { result.add("nodes/c_plocal"); } if ((getModifiers() & ModifierConstants.IMPLEMENTING) != 0) { result.add("gutter/implementingMethod"); } if ((getModifiers() & ModifierConstants.IMPLEMENTED) != 0) { result.add("gutter/implementedMethod"); } if ((getModifiers() & ModifierConstants.OVERRIDING) != 0) { result.add("gutter/overridingMethod"); } if ((getModifiers() & ModifierConstants.OVERRIDDEN) != 0) { result.add("gutter/overridenMethod"); } } return result.toArray(sa); }
private void reportNullableReturns( DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors, @NotNull PsiElement block) { final PsiMethod method = getScopeMethod(block); if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return; boolean notNullRequired = NullableNotNullManager.isNotNull(method); if (!notNullRequired && !SUGGEST_NULLABLE_ANNOTATIONS) return; PsiType returnType = method.getReturnType(); // no warnings in void lambdas, where the expression is not returned anyway if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && returnType == PsiType.VOID) return; // no warnings for Void methods, where only null can be possibly returned if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return; for (PsiElement statement : visitor.getProblems(NullabilityProblem.nullableReturn)) { assert statement instanceof PsiExpression; final PsiExpression expr = (PsiExpression) statement; if (!reportedAnchors.add(expr)) continue; if (notNullRequired) { final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.return.null.from.notnull") : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull"); holder.registerProblem(expr, text); } else if (AnnotationUtil.isAnnotatingApplicable(statement)) { final NullableNotNullManager manager = NullableNotNullManager.getInstance(expr.getProject()); final String defaultNullable = manager.getDefaultNullable(); final String presentableNullable = StringUtil.getShortName(defaultNullable); final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message( "dataflow.message.return.null.from.notnullable", presentableNullable) : InspectionsBundle.message( "dataflow.message.return.nullable.from.notnullable", presentableNullable); final LocalQuickFix[] fixes = PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class) instanceof PsiLambdaExpression ? LocalQuickFix.EMPTY_ARRAY : new LocalQuickFix[] { new AnnotateMethodFix( defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls())) { @Override public int shouldAnnotateBaseMethod( PsiMethod method, PsiMethod superMethod, Project project) { return 1; } } }; holder.registerProblem(expr, text, fixes); } } }
private boolean isTrivial(PsiMethod method) { final PsiCodeBlock body = method.getBody(); if (body == null) { return true; } final PsiStatement[] statements = body.getStatements(); if (statements.length == 0) { return true; } final Project project = method.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiConstantEvaluationHelper evaluationHelper = psiFacade.getConstantEvaluationHelper(); for (PsiStatement statement : statements) { if (!(statement instanceof PsiIfStatement)) { return false; } final PsiIfStatement ifStatement = (PsiIfStatement) statement; final PsiExpression condition = ifStatement.getCondition(); final Object result = evaluationHelper.computeConstantExpression(condition); if (result == null || !result.equals(Boolean.FALSE)) { return false; } } return true; }
private void analyzeDfaWithNestedClosures( PsiElement scope, ProblemsHolder holder, StandardDataFlowRunner dfaRunner, Collection<DfaMemoryState> initialStates) { final DataFlowInstructionVisitor visitor = new DataFlowInstructionVisitor(dfaRunner); final RunnerResult rc = dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS, initialStates); if (rc == RunnerResult.OK) { createDescription(dfaRunner, holder, visitor); MultiMap<PsiElement, DfaMemoryState> nestedClosures = dfaRunner.getNestedClosures(); for (PsiElement closure : nestedClosures.keySet()) { analyzeDfaWithNestedClosures(closure, holder, dfaRunner, nestedClosures.get(closure)); } } else if (rc == RunnerResult.TOO_COMPLEX) { if (scope.getParent() instanceof PsiMethod) { PsiMethod method = (PsiMethod) scope.getParent(); final PsiIdentifier name = method.getNameIdentifier(); if (name != null) { // Might be null for synthetic methods like JSP page. holder.registerProblem( name, InspectionsBundle.message("dataflow.too.complex"), ProblemHighlightType.WEAK_WARNING); } } } }
@NotNull private static List<PsiMethod> findMethodsBySignature( @NotNull PsiClass aClass, @NotNull PsiMethod patternMethod, boolean checkBases, boolean stopOnFirst) { final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases); if (methodsByName.length == 0) return Collections.emptyList(); final List<PsiMethod> methods = new SmartList<PsiMethod>(); final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY); for (final PsiMethod method : methodsByName) { final PsiClass superClass = method.getContainingClass(); final PsiSubstitutor substitutor; if (checkBases && !aClass.equals(superClass)) { substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY); } else { substitutor = PsiSubstitutor.EMPTY; } final MethodSignature signature = method.getSignature(substitutor); if (signature.equals(patternSignature)) { methods.add(method); if (stopOnFirst) { break; } } } return methods; }
private static boolean isCollectCall(PsiStatement body, final PsiParameter parameter) { PsiIfStatement ifStatement = extractIfStatement(body); final PsiMethodCallExpression methodCallExpression = extractAddCall(body, ifStatement); if (methodCallExpression != null) { final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); PsiClass qualifierClass = null; if (qualifierExpression instanceof PsiReferenceExpression) { if (ReferencesSearch.search(parameter, new LocalSearchScope(qualifierExpression)) .findFirst() != null) { return false; } final PsiElement resolve = ((PsiReferenceExpression) qualifierExpression).resolve(); if (resolve instanceof PsiVariable) { if (ReferencesSearch.search( resolve, new LocalSearchScope(methodCallExpression.getArgumentList())) .findFirst() != null) { return false; } } qualifierClass = PsiUtil.resolveClassInType(qualifierExpression.getType()); } else if (qualifierExpression == null) { final PsiClass enclosingClass = PsiTreeUtil.getParentOfType(body, PsiClass.class); if (PsiUtil.getEnclosingStaticElement(body, enclosingClass) == null) { qualifierClass = enclosingClass; } } if (qualifierClass != null && InheritanceUtil.isInheritor( qualifierClass, false, CommonClassNames.JAVA_UTIL_COLLECTION)) { while (ifStatement != null && PsiTreeUtil.isAncestor(body, ifStatement, false)) { final PsiExpression condition = ifStatement.getCondition(); if (condition != null && isConditionDependsOnUpdatedCollections(condition, qualifierExpression)) return false; ifStatement = PsiTreeUtil.getParentOfType(ifStatement, PsiIfStatement.class); } final PsiElement resolve = methodExpression.resolve(); if (resolve instanceof PsiMethod && "add".equals(((PsiMethod) resolve).getName()) && ((PsiMethod) resolve).getParameterList().getParametersCount() == 1) { final PsiExpression[] args = methodCallExpression.getArgumentList().getExpressions(); if (args.length == 1) { if (args[0] instanceof PsiCallExpression) { final PsiMethod method = ((PsiCallExpression) args[0]).resolveMethod(); return method != null && !method.hasTypeParameters() && !isThrowsCompatible(method); } return true; } } } } return false; }
@Nullable private PsiParameter getParameter() { if (!myMethod.isValid()) return null; final PsiParameter[] parameters = myMethod.getParameterList().getParameters(); return parameters.length > myParameterIndex && myParameterIndex >= 0 ? parameters[myParameterIndex] : null; }
public String getTypeIconName() { if (myEnd instanceof PsiMethod) { PsiMethod m = (PsiMethod) myEnd; return (((PsiModifierList) m.getModifierList()).hasModifierProperty(PsiModifier.STATIC)) ? "nodes/staticMethod" : "nodes/method"; } return null; }
boolean hasPrivateConstructor(PsiClass aClass) { final PsiMethod[] constructors = aClass.getConstructors(); for (final PsiMethod constructor : constructors) { if (constructor.hasModifierProperty(PsiModifier.PRIVATE)) { return true; } } return false; }
static boolean hasNullArgConstructor(PsiClass aClass) { final PsiMethod[] constructors = aClass.getConstructors(); for (final PsiMethod constructor : constructors) { final PsiParameterList params = constructor.getParameterList(); if (params.getParametersCount() == 0) { return true; } } return false; }
@Override public void visitThrowStatement(PsiThrowStatement statement) { super.visitThrowStatement(statement); final PsiCatchSection catchSection = PsiTreeUtil.getParentOfType(statement, PsiCatchSection.class, true, PsiClass.class); if (catchSection == null) { return; } final PsiParameter parameter = catchSection.getParameter(); if (parameter == null) { return; } @NonNls final String parameterName = parameter.getName(); if (PsiUtil.isIgnoredName(parameterName)) { return; } final PsiExpression exception = statement.getException(); if (exception == null) { return; } if (ignoreCantWrap) { final PsiType thrownType = exception.getType(); if (thrownType instanceof PsiClassType) { final PsiClassType classType = (PsiClassType) thrownType; final PsiClass exceptionClass = classType.resolve(); if (exceptionClass != null) { final PsiMethod[] constructors = exceptionClass.getConstructors(); final PsiClassType throwableType = TypeUtils.getType(CommonClassNames.JAVA_LANG_THROWABLE, statement); boolean canWrap = false; outer: for (PsiMethod constructor : constructors) { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); for (PsiParameter constructorParameter : parameters) { final PsiType type = constructorParameter.getType(); if (throwableType.equals(type)) { canWrap = true; break outer; } } } if (!canWrap) { return; } } } } final ReferenceFinder visitor = new ReferenceFinder(parameter); exception.accept(visitor); if (visitor.usesParameter()) { return; } registerStatementError(statement); }
@Nullable private ProblemDescriptor createDescription( @NotNull PsiTypeCastExpression cast, @NotNull InspectionManager manager, boolean onTheFly) { PsiExpression operand = cast.getOperand(); PsiTypeElement castType = cast.getCastType(); if (operand == null || castType == null) return null; PsiElement parent = cast.getParent(); while (parent instanceof PsiParenthesizedExpression) { parent = parent.getParent(); } if (parent instanceof PsiReferenceExpression) { if (IGNORE_ANNOTATED_METHODS) { final PsiElement gParent = parent.getParent(); if (gParent instanceof PsiMethodCallExpression) { final PsiMethod psiMethod = ((PsiMethodCallExpression) gParent).resolveMethod(); if (psiMethod != null && NullableNotNullManager.isNotNull(psiMethod)) { final PsiClass superClass = PsiUtil.resolveClassInType(operand.getType()); final PsiClass containingClass = psiMethod.getContainingClass(); if (containingClass != null && superClass != null && containingClass.isInheritor(superClass, true)) { for (PsiMethod method : psiMethod.findSuperMethods(superClass)) { if (NullableNotNullManager.isNullable(method)) { return null; } } } } } } } else if (parent instanceof PsiExpressionList) { final PsiElement gParent = parent.getParent(); if (gParent instanceof PsiMethodCallExpression && IGNORE_SUSPICIOUS_METHOD_CALLS) { final String message = SuspiciousCollectionsMethodCallsInspection.getSuspiciousMethodCallMessage( (PsiMethodCallExpression) gParent, operand.getType(), true, new ArrayList<PsiMethod>(), new IntArrayList()); if (message != null) { return null; } } } String message = InspectionsBundle.message( "inspection.redundant.cast.problem.descriptor", "<code>" + operand.getText() + "</code>", "<code>#ref</code> #loc"); return manager.createProblemDescriptor( castType, message, myQuickFixAction, ProblemHighlightType.LIKE_UNUSED_SYMBOL, onTheFly); }
private static int getMethodOffsetInInterface(PsiMethod method) { final PsiMethod[] superMethods = method.findSuperMethods(); // final PsiMethod[] superMethods = PsiSuperMethodUtil.findSuperMethods(method); // todo // - for IDEA 5.0 if (superMethods.length == 0) return 0; PsiMethod m = superMethods[0]; PsiElement parent = m.getParent(); if (parent instanceof PsiClass && ((PsiClass) parent).isInterface()) { return m.getTextOffset(); } return getMethodOffsetInInterface(m); }
private static PsiSubstitutor checkRaw( boolean isRaw, @NotNull PsiElementFactory factory, @NotNull PsiMethod candidateMethod, @NotNull PsiSubstitutor substitutor) { if (isRaw && !candidateMethod.hasModifierProperty( PsiModifier.STATIC)) { // static methods are not erased due to raw overriding PsiTypeParameter[] methodTypeParameters = candidateMethod.getTypeParameters(); substitutor = factory.createRawSubstitutor(substitutor, methodTypeParameters); } return substitutor; }
private static TextRange calculateLimitRange( final PsiFile file, final Document doc, final int line) { final int offset = doc.getLineStartOffset(line); if (offset > 0) { PsiMethod method = PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiMethod.class, false); if (method != null) { final TextRange elemRange = method.getTextRange(); return new TextRange( doc.getLineNumber(elemRange.getStartOffset()), doc.getLineNumber(elemRange.getEndOffset())); } } return new TextRange(0, doc.getLineCount() - 1); }
@Override public void visitMethod(@NotNull PsiMethod method) { // note: no call to super; final String methodName = method.getName(); if (!HardcodedMethodConstants.FINALIZE.equals(methodName)) { return; } final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() != 0) { return; } if (ignoreTrivialFinalizers && isTrivial(method)) { return; } registerMethodError(method); }
private void doImport(final PsiMethod toImport) { CommandProcessor.getInstance() .executeCommand( toImport.getProject(), new Runnable() { @Override public void run() { ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { try { PsiMethodCallExpression element = myMethodCall.getElement(); if (element != null) { element .getMethodExpression() .bindToElementViaStaticImport(toImport.getContainingClass()); } } catch (IncorrectOperationException e) { LOG.error(e); } } }); } }, getText(), this); }
@Override protected PsiVariable createFieldToStartTemplateOn( final String[] names, final PsiType defaultType) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myMethod.getProject()); return ApplicationManager.getApplication() .runWriteAction( new Computable<PsiParameter>() { @Override public PsiParameter compute() { final PsiParameter anchor = JavaIntroduceParameterMethodUsagesProcessor.getAnchorParameter(myMethod); final PsiParameter psiParameter = (PsiParameter) myMethod .getParameterList() .addAfter( elementFactory.createParameter( chooseName(names, myMethod.getLanguage()), defaultType), anchor); PsiUtil.setModifierProperty( psiParameter, PsiModifier.FINAL, myPanel.hasFinalModifier()); myParameterIndex = myMethod.getParameterList().getParameterIndex(psiParameter); return psiParameter; } }); }
private static LookupElementBuilder createOverridingLookupElement( boolean implemented, final PsiMethod baseMethod, PsiClass baseClass, PsiSubstitutor substitutor) { RowIcon icon = new RowIcon( baseMethod.getIcon(0), implemented ? AllIcons.Gutter.ImplementingMethod : AllIcons.Gutter.OverridingMethod); return createGenerateMethodElement( baseMethod, substitutor, icon, baseClass.getName(), new InsertHandler<LookupElement>() { @Override public void handleInsert(InsertionContext context, LookupElement item) { removeLookupString(context); final PsiClass parent = PsiTreeUtil.findElementOfClassAtOffset( context.getFile(), context.getStartOffset(), PsiClass.class, false); if (parent == null) return; List<PsiMethod> prototypes = OverrideImplementUtil.overrideOrImplementMethod(parent, baseMethod, false); insertGenerationInfos( context, OverrideImplementUtil.convert2GenerationInfos(prototypes)); } }); }
/** * Called when getters and setters are to be kept together in pairs. Searches the list of entries * for any getter/setter methods that matches this getter method. Normally there is only one * setter per getter, but one could have a "getXXX", "isXXX" and "setXXX" trio which need to be * related. In this case, the first getter encountered finds the other getter and setter and the * three will be emitted in that order. * * @param possibleMethods entry list, possibly containing the corresponding setter for this * getter. * @param settings */ public void determineSetter( final List<ClassContentsEntry> possibleMethods, RearrangerSettings settings) { if (!isGetter()) // wasted assertion, already checked before calling { return; } final PsiMethod thisMethod = (PsiMethod) myEnd; String thisProperty = MethodUtil.getPropertyName(thisMethod); if (isGetter() && !myKeptWithProperty) { if (settings.isKeepGettersSettersWithProperty()) { hookGetterToProperty(possibleMethods); } } for (ClassContentsEntry o : possibleMethods) { if (o instanceof RelatableEntry) { MethodEntry me = (MethodEntry) o; // don't use a setter twice (could be two methods which both look like getters; assign the // setter // to only one of them.) Also, associate all getter/setter methods for the same property // with the // first one encountered. if ((me.isSetter() || me.isGetter()) && me.myCorrespondingGetterSetters.size() == 0 && me != this) { PsiMethod m = (PsiMethod) me.myEnd; String otherProperty = MethodUtil.getPropertyName(m); if (thisProperty.equals(otherProperty)) { LOG.debug( "method " + thisMethod.toString() + " is getter; its setter is " + m.toString()); // place getters ahead of setters if (me.isGetter()) { myCorrespondingGetterSetters.add(0, me); // clear the getter flag and set the setter flag; this causes the method to be emitted // under the first getter encountered. me.setGetter(false); me.setSetter(true); } else { myCorrespondingGetterSetters.add(me); } me.myCorrespondingGetterSetters.add(this); } } } } }
private static void addSuperSignatureElements( final PsiClass parent, boolean implemented, CompletionResultSet result, Set<MethodSignature> addedSignatures) { for (CandidateInfo candidate : OverrideImplementExploreUtil.getMethodsToOverrideImplement(parent, implemented)) { PsiMethod baseMethod = (PsiMethod) candidate.getElement(); PsiClass baseClass = baseMethod.getContainingClass(); PsiSubstitutor substitutor = candidate.getSubstitutor(); if (!baseMethod.isConstructor() && baseClass != null && addedSignatures.add(baseMethod.getSignature(substitutor))) { result.addElement( createOverridingLookupElement(implemented, baseMethod, baseClass, substitutor)); } } }
@Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement classNameIdentifier = descriptor.getPsiElement(); final PsiClass aClass = (PsiClass) classNameIdentifier.getParent(); if (aClass == null) { return; } final PsiManager psiManager = PsiManager.getInstance(project); final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); final PsiMethod constructor = factory.createConstructor(); final PsiModifierList modifierList = constructor.getModifierList(); modifierList.setModifierProperty(PsiModifier.PRIVATE, true); aClass.add(constructor); final CodeStyleManager styleManager = psiManager.getCodeStyleManager(); styleManager.reformat(constructor); }
@Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement classNameIdentifier = descriptor.getPsiElement(); final PsiClass aClass = (PsiClass) classNameIdentifier.getParent(); if (aClass == null) { return; } final PsiMethod[] constructurs = aClass.getConstructors(); for (final PsiMethod constructor : constructurs) { final PsiParameterList parameterList = constructor.getParameterList(); if (parameterList.getParametersCount() == 0) { final PsiModifierList modifiers = constructor.getModifierList(); modifiers.setModifierProperty(PsiModifier.PUBLIC, false); modifiers.setModifierProperty(PsiModifier.PROTECTED, false); modifiers.setModifierProperty(PsiModifier.PRIVATE, true); } } }
private boolean hasGoodToString(PsiClass aClass) { final PsiMethod[] methods = aClass.findMethodsByName(HardcodedMethodConstants.TO_STRING, true); for (PsiMethod method : methods) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { continue; } final String name = containingClass.getQualifiedName(); if (CommonClassNames.JAVA_LANG_OBJECT.equals(name)) { continue; } final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() == 0) { return true; } } return false; }
private static boolean isThrowsCompatible(PsiMethod method) { return ContainerUtil.find( method.getThrowsList().getReferencedTypes(), new Condition<PsiClassType>() { @Override public boolean value(PsiClassType type) { return !ExceptionUtil.isUncheckedException(type); } }) != null; }
public static boolean isMainOrPremainMethod(@NotNull PsiMethod method) { if (!PsiType.VOID.equals(method.getReturnType())) return false; String name = method.getName(); if (!("main".equals(name) || "premain".equals(name))) return false; PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); MethodSignature signature = method.getSignature(PsiSubstitutor.EMPTY); try { MethodSignature main = createSignatureFromText(factory, "void main(String[] args);"); if (MethodSignatureUtil.areSignaturesEqual(signature, main)) return true; MethodSignature premain = createSignatureFromText( factory, "void premain(String args, java.lang.instrument.Instrumentation i);"); if (MethodSignatureUtil.areSignaturesEqual(signature, premain)) return true; } catch (IncorrectOperationException e) { LOG.error(e); } return false; }
private static boolean canCallMethodsInConstructors(PsiClass aClass, boolean virtual) { for (PsiMethod constructor : aClass.getConstructors()) { if (!constructor.getLanguage().isKindOf(JavaLanguage.INSTANCE)) return true; PsiCodeBlock body = constructor.getBody(); if (body == null) continue; for (PsiMethodCallExpression call : SyntaxTraverser.psiTraverser().withRoot(body).filter(PsiMethodCallExpression.class)) { PsiReferenceExpression methodExpression = call.getMethodExpression(); if (methodExpression instanceof PsiThisExpression || methodExpression instanceof PsiSuperExpression) continue; if (!virtual) return true; PsiMethod target = call.resolveMethod(); if (target != null && PsiUtil.canBeOverriden(target)) return true; } } return false; }
@Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { if (!FileModificationService.getInstance() .preparePsiElementForWrite(descriptor.getPsiElement())) return; final PsiModifierListOwner element = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiModifierListOwner.class); if (element != null) { RefElement refElement = null; if (myManager != null) { refElement = myManager.getReference(element); } try { if (element instanceof PsiVariable) { ((PsiVariable) element).normalizeDeclaration(); } PsiModifierList list = element.getModifierList(); LOG.assertTrue(list != null); if (element instanceof PsiMethod) { PsiMethod psiMethod = (PsiMethod) element; PsiClass containingClass = psiMethod.getContainingClass(); if (containingClass != null && containingClass.getParent() instanceof PsiFile && myHint == PsiModifier.PRIVATE && list.hasModifierProperty(PsiModifier.FINAL)) { list.setModifierProperty(PsiModifier.FINAL, false); } } list.setModifierProperty(myHint, true); if (refElement instanceof RefJavaElement) { RefJavaUtil.getInstance().setAccessModifier((RefJavaElement) refElement, myHint); } } catch (IncorrectOperationException e) { LOG.error(e); } } }
private static String computeConstantSuperCtorCallParameter( PsiClass languagePsiClass, int index) { if (languagePsiClass instanceof PsiAnonymousClass) { return getStringConstantExpression( ((PsiAnonymousClass) languagePsiClass).getArgumentList(), index); } PsiMethod defaultConstructor = null; for (PsiMethod constructor : languagePsiClass.getConstructors()) { if (constructor.getParameterList().getParametersCount() == 0) { defaultConstructor = constructor; break; } } if (defaultConstructor == null) { return null; } final PsiCodeBlock body = defaultConstructor.getBody(); if (body == null) { return null; } final PsiStatement[] statements = body.getStatements(); if (statements.length < 1) { return null; } // super() must be first PsiStatement statement = statements[0]; if (!(statement instanceof PsiExpressionStatement)) { return null; } PsiExpression expression = ((PsiExpressionStatement) statement).getExpression(); if (!(expression instanceof PsiMethodCallExpression)) { return null; } PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression; PsiExpressionList expressionList = methodCallExpression.getArgumentList(); return getStringConstantExpression(expressionList, index); }