public PsiReturnStatement addReturnForMethod(final PsiFile file, final PsiMethod method) { final PsiModifierList modifiers = method.getModifierList(); if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT) || method.getBody() == null) { return null; } try { final ConvertReturnStatementsVisitor visitor = new ConvertReturnStatementsVisitor(factory, method, myTargetType); ControlFlow controlFlow; try { controlFlow = HighlightControlFlowUtil.getControlFlowNoConstantEvaluate(method.getBody()); } catch (AnalysisCanceledException e) { return null; // must be an error } PsiReturnStatement returnStatement; if (controlFlow != null && ControlFlowUtil.processReturns(controlFlow, visitor)) { // extra return statement not needed // get latest modified return statement and select... returnStatement = visitor.getLatestReturn(); } else { returnStatement = visitor.createReturnInLastStatement(); } if (method.getContainingFile() != file) { UndoUtil.markPsiFileForUndo(file); } return returnStatement; } catch (IncorrectOperationException e) { LOG.error(e); } return null; }
private static PsiStatement addInitializationToConstructors( PsiLocalVariable local, PsiField field, PsiMethod enclosingConstructor, PsiElementFactory factory) throws IncorrectOperationException { PsiClass aClass = field.getContainingClass(); PsiMethod[] constructors = aClass.getConstructors(); PsiStatement assignment = createAssignment(local, field.getName(), factory); boolean added = false; for (PsiMethod constructor : constructors) { if (constructor == enclosingConstructor) continue; PsiCodeBlock body = constructor.getBody(); if (body == null) continue; PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { PsiStatement first = statements[0]; if (first instanceof PsiExpressionStatement) { PsiExpression expression = ((PsiExpressionStatement) first).getExpression(); if (expression instanceof PsiMethodCallExpression) { @NonNls String text = ((PsiMethodCallExpression) expression).getMethodExpression().getText(); if ("this".equals(text)) { continue; } if ("super".equals(text) && enclosingConstructor == null && PsiTreeUtil.isAncestor(constructor, local, false)) { local.delete(); return (PsiStatement) body.addAfter(assignment, first); } } } if (enclosingConstructor == null && PsiTreeUtil.isAncestor(constructor, local, false)) { local.delete(); return (PsiStatement) body.addBefore(assignment, first); } } assignment = (PsiStatement) body.add(assignment); added = true; } if (!added && enclosingConstructor == null) { if (aClass instanceof PsiAnonymousClass) { final PsiClassInitializer classInitializer = (PsiClassInitializer) aClass.addAfter(factory.createClassInitializer(), field); assignment = (PsiStatement) classInitializer.getBody().add(assignment); } else { PsiMethod constructor = (PsiMethod) aClass.add(factory.createConstructor()); assignment = (PsiStatement) constructor.getBody().add(assignment); } } if (enclosingConstructor == null) local.delete(); return assignment; }
/** Add the initView() after onCreate() */ private void addInitViewAfterOnCreate() { String initViewStatement = "initView();"; PsiMethod createMethod = mClass.findMethodsByName("onCreate", false)[0]; for (PsiStatement statement : createMethod.getBody().getStatements()) { if (statement.getText().equals(initViewStatement)) { return; } } createMethod.getBody().add(mFactory.createStatementFromText(initViewStatement, mClass)); }
protected void performRefactoring(UsageInfo[] usages) { if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return; PsiMethod patternMethod = createMethodToAdd(); final List<PsiReference> docRefs = new ArrayList<PsiReference>(); for (UsageInfo usage : usages) { if (usage instanceof InheritorUsageInfo) { final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor(); addMethodToClass(inheritor, patternMethod, true); } else if (usage instanceof MethodCallUsageInfo && !((MethodCallUsageInfo) usage).isInternal()) { correctMethodCall(((MethodCallUsageInfo) usage).getMethodCallExpression(), false); } else if (usage instanceof JavadocUsageInfo) { docRefs.add(usage.getElement().getReference()); } } try { if (myTargetClass.isInterface()) patternMethod.getBody().delete(); final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false); myMethod.delete(); for (PsiReference reference : docRefs) { reference.bindToElement(method); } VisibilityUtil.fixVisibility(usages, method, myNewVisibility); } catch (IncorrectOperationException e) { LOG.error(e); } }
@Override public boolean isMethodOnlyCallsSuper(PsiMethod method) { boolean hasStatements = false; PsiCodeBlock body = method.getBody(); if (body != null) { PsiStatement[] statements = body.getStatements(); for (PsiStatement statement : statements) { boolean isCallToSameSuper = false; if (statement instanceof PsiExpressionStatement) { isCallToSameSuper = isCallToSuperMethod(((PsiExpressionStatement) statement).getExpression(), method); } else if (statement instanceof PsiReturnStatement) { PsiExpression expression = ((PsiReturnStatement) statement).getReturnValue(); isCallToSameSuper = expression == null || isCallToSuperMethod(expression, method); } hasStatements = true; if (isCallToSameSuper) continue; return false; } } if (hasStatements) { final PsiMethod[] superMethods = method.findSuperMethods(); for (PsiMethod superMethod : superMethods) { if (VisibilityUtil.compare( VisibilityUtil.getVisibilityModifier(superMethod.getModifierList()), VisibilityUtil.getVisibilityModifier(method.getModifierList())) > 0) return false; } } return hasStatements; }
List<MethodContract> inferContracts() { PsiCodeBlock body = myMethod.getBody(); PsiStatement[] statements = body == null ? PsiStatement.EMPTY_ARRAY : body.getStatements(); if (statements.length == 0) return Collections.emptyList(); if (statements.length == 1) { if (statements[0] instanceof PsiReturnStatement) { List<MethodContract> result = handleDelegation(((PsiReturnStatement) statements[0]).getReturnValue(), false); if (result != null) return result; } else if (statements[0] instanceof PsiExpressionStatement && ((PsiExpressionStatement) statements[0]).getExpression() instanceof PsiMethodCallExpression) { List<MethodContract> result = handleDelegation(((PsiExpressionStatement) statements[0]).getExpression(), false); if (result != null) return ContainerUtil.findAll( result, new Condition<MethodContract>() { @Override public boolean value(MethodContract contract) { return contract.returnValue == THROW_EXCEPTION || !textMatches(myMethod.getReturnTypeElement(), PsiKeyword.VOID); } }); } } ValueConstraint[] emptyState = MethodContract.createConstraintArray(myMethod.getParameterList().getParametersCount()); return visitStatements(Collections.singletonList(emptyState), statements); }
@Override protected PsiMethod findOrCreateSetUpMethod(PsiClass clazz) throws IncorrectOperationException { LOG.assertTrue(clazz.getLanguage() == GroovyFileType.GROOVY_LANGUAGE); final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(clazz.getProject()); final PsiMethod patternMethod = createSetUpPatternMethod(factory); final PsiClass baseClass = clazz.getSuperClass(); if (baseClass != null) { final PsiMethod baseMethod = baseClass.findMethodBySignature(patternMethod, false); if (baseMethod != null && baseMethod.hasModifierProperty(PsiModifier.PUBLIC)) { PsiUtil.setModifierProperty(patternMethod, PsiModifier.PROTECTED, false); PsiUtil.setModifierProperty(patternMethod, PsiModifier.PUBLIC, true); } } PsiMethod inClass = clazz.findMethodBySignature(patternMethod, false); if (inClass == null) { PsiMethod testMethod = JUnitUtil.findFirstTestMethod(clazz); if (testMethod != null) { return (PsiMethod) clazz.addBefore(patternMethod, testMethod); } return (PsiMethod) clazz.add(patternMethod); } else if (inClass.getBody() == null) { return (PsiMethod) inClass.replace(patternMethod); } return inClass; }
@Override public void visitMethod(@NotNull PsiMethod method) { super.visitMethod(method); final PsiCodeBlock body = method.getBody(); if (body == null) { return; } if (method.getNameIdentifier() == null) { return; } final PsiMethod leastConcreteSuperMethod = getLeastConcreteSuperMethod(method); if (leastConcreteSuperMethod == null) { return; } final PsiClass objectClass = ClassUtils.findObjectClass(method); final PsiMethod[] superMethods = method.findSuperMethods(objectClass); if (superMethods.length > 0) { return; } if (ignoreEmptySuperMethods) { final PsiMethod superMethod = (PsiMethod) leastConcreteSuperMethod.getNavigationElement(); if (MethodUtils.isTrivial(superMethod, true)) { return; } } if (onlyReportWhenAnnotated) { if (!AnnotationUtil.isAnnotated(leastConcreteSuperMethod, annotations)) { return; } } if (containsSuperCall(body, leastConcreteSuperMethod)) { return; } registerMethodError(method); }
@Override public void visitMethod(PsiMethod method) { ArrangementSettingsToken type = method.isConstructor() ? CONSTRUCTOR : METHOD; JavaElementArrangementEntry entry = createNewEntry(method, method.getTextRange(), type, method.getName(), true); if (entry == null) { return; } processEntry(entry, method, method.getBody()); parseProperties(method, entry); myInfo.onMethodEntryCreated(method, entry); MethodSignatureBackedByPsiMethod overridden = SuperMethodsSearch.search(method, null, true, false).findFirst(); if (overridden != null) { myInfo.onOverriddenMethod(overridden.getMethod(), method); } boolean reset = myMethodBodyProcessor.setBaseMethod(method); try { method.accept(myMethodBodyProcessor); } finally { if (reset) { myMethodBodyProcessor.setBaseMethod(null); } } }
private void collectUncaughtExceptions(@NotNull PsiMethod method) { if (isExternalOverride()) return; if (getRefManager().isOfflineView()) return; @NonNls final String name = method.getName(); if (getOwnerClass().isTestCase() && name.startsWith("test")) return; if (getSuperMethods().isEmpty()) { PsiClassType[] throwsList = method.getThrowsList().getReferencedTypes(); if (throwsList.length > 0) { myUnThrownExceptions = throwsList.length == 1 ? new SmartList<String>() : new ArrayList<String>(throwsList.length); for (final PsiClassType type : throwsList) { PsiClass aClass = type.resolve(); String fqn = aClass == null ? null : aClass.getQualifiedName(); if (fqn != null) { myUnThrownExceptions.add(fqn); } } } } final PsiCodeBlock body = method.getBody(); if (body == null) return; final Collection<PsiClassType> exceptionTypes = ExceptionUtil.collectUnhandledExceptions(body, method, false); for (final PsiClassType exceptionType : exceptionTypes) { updateThrowsList(exceptionType); } }
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; }
@Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return myMethod != null && myMethod.isValid() && myMethod.getBody() == null && myMethod.getContainingClass() != null && myMethod.getManager().isInProject(myMethod); }
public static boolean isFieldInitializedAfterObjectConstruction(@NotNull PsiField field) { if (field.hasInitializer()) return true; final boolean isFieldStatic = field.hasModifierProperty(PsiModifier.STATIC); final PsiClass aClass = field.getContainingClass(); if (aClass != null) { // field might be assigned in the other field initializers if (isFieldInitializedInOtherFieldInitializer(aClass, field, isFieldStatic)) return true; } final PsiClassInitializer[] initializers; if (aClass != null) { initializers = aClass.getInitializers(); } else { return false; } for (PsiClassInitializer initializer : initializers) { if (initializer.hasModifierProperty(PsiModifier.STATIC) == isFieldStatic && variableDefinitelyAssignedIn(field, initializer.getBody())) { return true; } } if (isFieldStatic) { return false; } else { // instance field should be initialized at the end of the each constructor final PsiMethod[] constructors = aClass.getConstructors(); if (constructors.length == 0) return false; nextConstructor: for (PsiMethod constructor : constructors) { PsiCodeBlock ctrBody = constructor.getBody(); if (ctrBody == null) return false; final List<PsiMethod> redirectedConstructors = JavaHighlightUtil.getChainedConstructors(constructor); for (int j = 0; redirectedConstructors != null && j < redirectedConstructors.size(); j++) { PsiMethod redirectedConstructor = redirectedConstructors.get(j); final PsiCodeBlock body = redirectedConstructor.getBody(); if (body != null && variableDefinitelyAssignedIn(field, body)) continue nextConstructor; } if (!ctrBody.isValid() || variableDefinitelyAssignedIn(field, ctrBody)) { continue; } return false; } return true; } }
@Override public ProblemDescriptor[] checkMethod( @NotNull PsiMethod psiMethod, @NotNull InspectionManager manager, boolean isOnTheFly) { final PsiCodeBlock body = psiMethod.getBody(); if (body != null) { return getDescriptions(body, manager, isOnTheFly); } return null; }
public static PsiMethod generateSetterPrototype( PsiField field, final PsiClass containingClass, boolean returnSelf) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); String name = field.getName(); boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); VariableKind kind = codeStyleManager.getVariableKind(field); String propertyName = codeStyleManager.variableNameToPropertyName(name, kind); String setName = suggestSetterName(project, field); try { PsiMethod setMethod = factory.createMethod( setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiParameter param = factory.createParameter(parameterName, field.getType()); annotateWithNullableStuff(field, factory, param); setMethod.getParameterList().add(param); PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic); @NonNls StringBuffer buffer = new StringBuffer(); buffer.append("{\n"); if (name.equals(parameterName)) { if (!isStatic) { buffer.append("this."); } else { String className = containingClass.getName(); if (className != null) { buffer.append(className); buffer.append("."); } } } buffer.append(name); buffer.append("="); buffer.append(parameterName); buffer.append(";\n"); if (returnSelf) { buffer.append("return this;\n"); } buffer.append("}"); PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null); setMethod.getBody().replace(body); setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod); return setMethod; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
public void applyFix(final Project project, final PsiFile file, final Editor editor) { if (!CodeInsightUtilBase.prepareFileForWrite(myClass.getContainingFile())) return; PsiCodeBlock body; if (myClass.isInterface() && (body = myMethod.getBody()) != null) body.delete(); for (String exception : myExceptions) { PsiUtil.addException(myMethod, exception); } PsiMethod method = (PsiMethod) myClass.add(myMethod); method = (PsiMethod) method.replace(reformat(project, method)); if (editor != null) { GenerateMembersUtil.positionCaret(editor, method, true); } }
private void calculateInitializersConflicts(MultiMap<PsiElement, String> conflicts) { final PsiClassInitializer[] initializers = sourceClass.getInitializers(); for (PsiClassInitializer initializer : initializers) { if (initializerDependsOnMoved(initializer)) { conflicts.putValue(initializer, "Class initializer requires moved members"); } } for (PsiMethod constructor : sourceClass.getConstructors()) { if (initializerDependsOnMoved(constructor.getBody())) { conflicts.putValue(constructor, "Constructor requires moved members"); } } }
@NotNull protected UsageInfo[] findUsages() { final PsiManager manager = myMethod.getManager(); final GlobalSearchScope searchScope = GlobalSearchScope.allScope(manager.getProject()); final List<UsageInfo> usages = new ArrayList<UsageInfo>(); for (PsiReference ref : ReferencesSearch.search(myMethod, searchScope, false)) { final PsiElement element = ref.getElement(); if (element instanceof PsiReferenceExpression) { boolean isInternal = PsiTreeUtil.isAncestor(myMethod, element, true); usages.add(new MethodCallUsageInfo((PsiReferenceExpression) element, isInternal)); } else if (element instanceof PsiDocTagValue) { usages.add(new JavadocUsageInfo(((PsiDocTagValue) element))); } else { throw new UnknownReferenceTypeException(element.getLanguage()); } } if (myTargetClass.isInterface()) { addInheritorUsages(myTargetClass, searchScope, usages); } final PsiCodeBlock body = myMethod.getBody(); if (body != null) { body.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitNewExpression(PsiNewExpression expression) { if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) { usages.add(new InternalUsageInfo(expression)); } super.visitNewExpression(expression); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) { usages.add(new InternalUsageInfo(expression)); } else if (!expression.isQualified()) { final PsiElement resolved = expression.resolve(); if (myTargetVariable.equals(resolved)) { usages.add(new InternalUsageInfo(expression)); } } super.visitReferenceExpression(expression); } }); } return usages.toArray(new UsageInfo[usages.size()]); }
@NotNull private ParameterList createFunctionParameters(@NotNull PsiMethod method) { List<Parameter> result = new LinkedList<Parameter>(); for (PsiParameter parameter : method.getParameterList().getParameters()) { result.add( new Parameter( new IdentifierImpl(parameter.getName()), typeToType( parameter.getType(), ConverterUtil.isAnnotatedAsNotNull(parameter.getModifierList())), ConverterUtil.isReadOnly(parameter, method.getBody()))); } return new ParameterList(result); }
private void registerNestedClosures(DfaInstructionState instructionState, PsiClass nestedClass) { DfaMemoryStateImpl closureState = createClosureState(instructionState.getMemoryState()); for (PsiMethod method : nestedClass.getMethods()) { PsiCodeBlock body = method.getBody(); if (body != null) { myNestedClosures.putValue(body, closureState); } } for (PsiClassInitializer initializer : nestedClass.getInitializers()) { myNestedClosures.putValue(initializer.getBody(), closureState); } for (PsiField field : nestedClass.getFields()) { myNestedClosures.putValue(field, closureState); } }
private static void resolveParameterVsFieldsConflicts( final PsiParameter[] newParms, final PsiMethod method, final PsiParameterList list, boolean[] toRemoveParm) throws IncorrectOperationException { List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>(); for (PsiParameter parameter : newParms) { conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody())); } ChangeSignatureUtil.synchronizeList( list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm); JavaCodeStyleManager.getInstance(list.getProject()).shortenClassReferences(list); for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) { fieldConflictsResolver.fix(); } }
@NotNull private Function methodToFunction(@NotNull PsiMethod method, boolean notEmpty) { if (isOverrideObjectDirect(method)) { dispatcher.setExpressionVisitor(new ExpressionVisitorForDirectObjectInheritors(this)); } else { dispatcher.setExpressionVisitor(new ExpressionVisitor(this)); } methodReturnType = method.getReturnType(); IdentifierImpl identifier = new IdentifierImpl(method.getName()); Type returnType = typeToType( method.getReturnType(), ConverterUtil.isAnnotatedAsNotNull(method.getModifierList())); Block body = hasFlag(J2KConverterFlags.SKIP_BODIES) ? Block.EMPTY_BLOCK : blockToBlock(method.getBody(), notEmpty); // #TODO Element params = createFunctionParameters(method); List<Element> typeParameters = elementsToElementList(method.getTypeParameters()); Set<String> modifiers = modifiersListToModifiersSet(method.getModifierList()); if (isOverrideAnyMethodExceptMethodsFromObject(method)) { modifiers.add(Modifier.OVERRIDE); } if (method.getParent() instanceof PsiClass && ((PsiClass) method.getParent()).isInterface()) { modifiers.remove(Modifier.ABSTRACT); } if (isNotOpenMethod(method)) { modifiers.add(Modifier.NOT_OPEN); } if (method.isConstructor()) { // TODO: simplify boolean isPrimary = isConstructorPrimary(method); return new Constructor( identifier, modifiers, returnType, typeParameters, params, new Block(removeEmpty(body.getStatements()), false), isPrimary); } return new Function(identifier, modifiers, returnType, typeParameters, params, body); }
protected void performRefactoring(UsageInfo[] usages) { if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return; PsiMethod patternMethod = createMethodToAdd(); final List<PsiReference> docRefs = new ArrayList<PsiReference>(); for (UsageInfo usage : usages) { if (usage instanceof InheritorUsageInfo) { final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor(); addMethodToClass(inheritor, patternMethod, true); } else if (usage instanceof MethodCallUsageInfo && !((MethodCallUsageInfo) usage).isInternal()) { final PsiElement expression = ((MethodCallUsageInfo) usage).getMethodCallExpression(); if (expression instanceof PsiMethodCallExpression) { correctMethodCall((PsiMethodCallExpression) expression, false); } else if (expression instanceof PsiMethodReferenceExpression) { PsiExpression newQualifier = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createExpressionFromText(myTargetVariable.getType().getCanonicalText(), null); ((PsiMethodReferenceExpression) expression).setQualifierExpression(newQualifier); } } else if (usage instanceof JavadocUsageInfo) { docRefs.add(usage.getElement().getReference()); } } try { if (myTargetClass.isInterface()) patternMethod.getBody().delete(); final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false); myMethod.delete(); for (PsiReference reference : docRefs) { reference.bindToElement(method); } VisibilityUtil.fixVisibility(UsageViewUtil.toElements(usages), method, myNewVisibility); if (myOpenInEditor) { EditorHelper.openInEditor(method); } } catch (IncorrectOperationException e) { LOG.error(e); } }
private static PsiStatement addInitializationToSetUp( final PsiLocalVariable local, final PsiField field, final PsiElementFactory factory) throws IncorrectOperationException { PsiMethod inClass = TestFrameworks.getInstance().findOrCreateSetUpMethod(field.getContainingClass()); assert inClass != null; PsiStatement assignment = createAssignment(local, field.getName(), factory); final PsiCodeBlock body = inClass.getBody(); assert body != null; if (PsiTreeUtil.isAncestor(body, local, false)) { assignment = (PsiStatement) body.addBefore(assignment, PsiTreeUtil.getParentOfType(local, PsiStatement.class)); } else { assignment = (PsiStatement) body.add(assignment); } local.delete(); return assignment; }
@Override public void visitField(@NotNull PsiField field) { if (field.hasModifierProperty(PsiModifier.STATIC)) { return; } if (field.getInitializer() != null) { return; } final PsiAnnotation annotation = AnnotationUtil.findAnnotation(field, annotationNames); if (annotation != null) { return; } if (m_ignorePrimitives) { final PsiType fieldType = field.getType(); if (ClassUtils.isPrimitive(fieldType)) { return; } } final PsiClass aClass = field.getContainingClass(); if (aClass == null) { return; } for (ImplicitUsageProvider provider : Extensions.getExtensions(ImplicitUsageProvider.EP_NAME)) { if (provider.isImplicitWrite(field)) { return; } } final UninitializedReadCollector uninitializedReadsCollector = new UninitializedReadCollector(); if (!isInitializedInInitializer(field, uninitializedReadsCollector)) { final PsiMethod[] constructors = aClass.getConstructors(); for (final PsiMethod constructor : constructors) { final PsiCodeBlock body = constructor.getBody(); uninitializedReadsCollector.blockAssignsVariable(body, field); } } final PsiExpression[] badReads = uninitializedReadsCollector.getUninitializedReads(); for (PsiExpression expression : badReads) { registerError(expression); } }
@Override public void invoke( @NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { final PsiClass myClass = (PsiClass) startElement; if (!CodeInsightUtilBase.prepareFileForWrite(myClass.getContainingFile())) return; PsiCodeBlock body; if (myClass.isInterface() && (body = myMethodPrototype.getBody()) != null) body.delete(); for (String exception : myExceptions) { PsiUtil.addException(myMethodPrototype, exception); } PsiMethod method = (PsiMethod) myClass.add(myMethodPrototype); method = (PsiMethod) method.replace(reformat(project, method)); if (editor != null) { GenerateMembersUtil.positionCaret(editor, method, true); } }
@Nullable public static PsiField findPropertyFieldByMember(final PsiMember psiMember) { if (psiMember instanceof PsiField) { return (PsiField) psiMember; } else if (psiMember instanceof PsiMethod) { final PsiMethod psiMethod = (PsiMethod) psiMember; final PsiType returnType = psiMethod.getReturnType(); if (returnType == null) return null; final PsiCodeBlock body = psiMethod.getBody(); final PsiStatement[] statements = body == null ? null : body.getStatements(); final PsiStatement statement = statements == null || statements.length != 1 ? null : statements[0]; final PsiElement target; if (PsiType.VOID.equals(returnType)) { final PsiExpression expression = statement instanceof PsiExpressionStatement ? ((PsiExpressionStatement) statement).getExpression() : null; target = expression instanceof PsiAssignmentExpression ? ((PsiAssignmentExpression) expression).getLExpression() : null; } else { target = statement instanceof PsiReturnStatement ? ((PsiReturnStatement) statement).getReturnValue() : null; } final PsiElement resolved = target instanceof PsiReferenceExpression ? ((PsiReferenceExpression) target).resolve() : null; if (resolved instanceof PsiField) { final PsiField field = (PsiField) resolved; if (psiMember.getContainingClass() == field.getContainingClass() || psiMember.getContainingClass().isInheritor(field.getContainingClass(), true)) return field; } } return null; }
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; }
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); }
private PsiMethod generateMethodBodyFor( PsiMethod method, String propertyName, String parameterName, PsiElementFactory elementFactory) { StringBuilder methodBodyBuilder = new StringBuilder() .append("{\n") .append("this.") .append(propertyName) .append("=") .append(parameterName) .append(";\n") .append("return this;\n") .append("}\n"); PsiCodeBlock methodBody = elementFactory.createCodeBlockFromText(methodBodyBuilder.toString(), null); method.getBody().replace(methodBody); method = (PsiMethod) CodeStyleManager.getInstance(method.getProject()).reformat(method); return method; }