private static PsiMethod convertMethodToLanguage(PsiMethod method, Language language) { if (method.getLanguage().equals(language)) { return method; } return JVMElementFactories.getFactory(language, method.getProject()) .createMethodFromText(method.getText(), null); }
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; }
@Nullable private static PsiMethodCallExpression checkMethodResolvable( PsiMethodCallExpression methodCall, PsiMethod targetMethod, PsiReferenceExpression context, PsiClass aClass) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(targetMethod.getProject()).getElementFactory(); final PsiElement resolved = methodCall.getMethodExpression().resolve(); if (resolved != targetMethod) { PsiClass containingClass; if (resolved instanceof PsiMethod) { containingClass = ((PsiMethod) resolved).getContainingClass(); } else if (resolved instanceof PsiClass) { containingClass = (PsiClass) resolved; } else { return null; } if (containingClass != null && containingClass.isInheritor(aClass, false)) { final PsiExpression newMethodExpression = factory.createExpressionFromText("super." + targetMethod.getName(), context); methodCall.getMethodExpression().replace(newMethodExpression); } else { methodCall = null; } } return methodCall; }
private static void removeUnusedParameterViaChangeSignature( final PsiMethod psiMethod, final Collection<PsiElement> parametersToDelete) { ArrayList<ParameterInfoImpl> newParameters = new ArrayList<ParameterInfoImpl>(); PsiParameter[] oldParameters = psiMethod.getParameterList().getParameters(); for (int i = 0; i < oldParameters.length; i++) { PsiParameter oldParameter = oldParameters[i]; if (!parametersToDelete.contains(oldParameter)) { newParameters.add( new ParameterInfoImpl(i, oldParameter.getName(), oldParameter.getType())); } } ParameterInfoImpl[] parameterInfos = newParameters.toArray(new ParameterInfoImpl[newParameters.size()]); ChangeSignatureProcessor csp = new ChangeSignatureProcessor( psiMethod.getProject(), psiMethod, false, null, psiMethod.getName(), psiMethod.getReturnType(), parameterInfos); csp.run(); }
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); }
@NotNull private List<PsiMethod> changeReturnType( final PsiMethod method, @NotNull final PsiType returnType) { final PsiMethod[] methods = getChangeRoots(method, returnType); if (methods == null) { // canceled return Collections.emptyList(); } final MethodSignatureChangeVisitor methodSignatureChangeVisitor = new MethodSignatureChangeVisitor(); for (PsiMethod targetMethod : methods) { methodSignatureChangeVisitor.addBase(targetMethod); ChangeSignatureProcessor processor = new UsagesAwareChangeSignatureProcessor( method.getProject(), targetMethod, false, null, myName, returnType, RemoveUnusedParameterFix.getNewParametersInfo(method, null), methodSignatureChangeVisitor); processor.run(); } return methodSignatureChangeVisitor.getAffectedMethods(); }
@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; } }); }
public IntroduceParameterObjectProcessor( String className, String packageName, MoveDestination moveDestination, PsiMethod method, VariableData[] parameters, boolean keepMethodAsDelegate, final boolean useExistingClass, final boolean createInnerClass, String newVisibility, boolean generateAccessors) { super(method.getProject()); myMoveDestination = moveDestination; this.method = method; this.className = className; this.packageName = packageName; this.keepMethodAsDelegate = keepMethodAsDelegate; myUseExistingClass = useExistingClass; myCreateInnerClass = createInnerClass; myNewVisibility = newVisibility; myGenerateAccessors = generateAccessors; this.parameters = new ArrayList<ParameterChunk>(); for (VariableData parameter : parameters) { this.parameters.add(new ParameterChunk(parameter)); } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] methodParams = parameterList.getParameters(); paramsToMerge = new int[parameters.length]; for (int p = 0; p < parameters.length; p++) { VariableData parameter = parameters[p]; for (int i = 0; i < methodParams.length; i++) { final PsiParameter methodParam = methodParams[i]; if (parameter.variable.equals(methodParam)) { paramsToMerge[p] = i; break; } } } final Set<PsiTypeParameter> typeParamSet = new HashSet<PsiTypeParameter>(); final PsiTypeVisitor<Object> typeParametersVisitor = new PsiTypeVisitor<Object>() { @Override public Object visitClassType(PsiClassType classType) { final PsiClass referent = classType.resolve(); if (referent instanceof PsiTypeParameter) { typeParamSet.add((PsiTypeParameter) referent); } return super.visitClassType(classType); } }; for (VariableData parameter : parameters) { parameter.type.accept(typeParametersVisitor); } typeParams = new ArrayList<PsiTypeParameter>(typeParamSet); final String qualifiedName = StringUtil.getQualifiedName(packageName, className); final GlobalSearchScope scope = GlobalSearchScope.allScope(myProject); existingClass = JavaPsiFacade.getInstance(myProject).findClass(qualifiedName, scope); }
private static boolean isMethodDeclarationInSource(@NotNull PsiMethod psiMethod) { if (psiMethod.getContainingFile() == null) return false; final VirtualFile virtualFile = psiMethod.getContainingFile().getVirtualFile(); if (virtualFile == null) return false; return ProjectRootManager.getInstance(psiMethod.getProject()) .getFileIndex() .isInSource(virtualFile); }
public MethodReturnTypeFix( @NotNull PsiMethod method, @NotNull PsiType returnType, boolean fixWholeHierarchy) { super(method); myReturnTypePointer = SmartTypePointerManager.getInstance(method.getProject()).createSmartTypePointer(returnType); myFixWholeHierarchy = fixWholeHierarchy; myName = method.getName(); myCanonicalText = returnType.getCanonicalText(); }
public static void checkMethodConflicts( @Nullable PsiClass aClass, PsiMethod refactoredMethod, PsiMethod prototype, final MultiMap<PsiElement, String> conflicts) { if (prototype == null) return; PsiMethod method = aClass != null ? aClass.findMethodBySignature(prototype, true) : null; if (method != null && method != refactoredMethod) { if (aClass.equals(method.getContainingClass())) { final String classDescr = aClass instanceof PsiAnonymousClass ? RefactoringBundle.message("current.class") : RefactoringUIUtil.getDescription(aClass, false); conflicts.putValue( method, RefactoringBundle.message( "method.0.is.already.defined.in.the.1", getMethodPrototypeString(prototype), classDescr)); } else { // method somewhere in base class if (JavaPsiFacade.getInstance(method.getProject()) .getResolveHelper() .isAccessible(method, aClass, null)) { String protoMethodInfo = getMethodPrototypeString(prototype); String className = CommonRefactoringUtil.htmlEmphasize( UsageViewUtil.getDescriptiveName(method.getContainingClass())); if (PsiUtil.getAccessLevel(prototype.getModifierList()) >= PsiUtil.getAccessLevel(method.getModifierList())) { boolean isMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); boolean isMyMethodAbstract = refactoredMethod != null && refactoredMethod.hasModifierProperty(PsiModifier.ABSTRACT); final String conflict = isMethodAbstract != isMyMethodAbstract ? RefactoringBundle.message( "method.0.will.implement.method.of.the.base.class", protoMethodInfo, className) : RefactoringBundle.message( "method.0.will.override.a.method.of.the.base.class", protoMethodInfo, className); conflicts.putValue(method, conflict); } else { // prototype is private, will be compile-error conflicts.putValue( method, RefactoringBundle.message( "method.0.will.hide.method.of.the.base.class", protoMethodInfo, className)); } } } } }
@Nullable private static DeclarationDescriptor findSuperFunction( @NotNull Collection<Pair<FunctionDescriptor, PsiMethod>> superFunctionCandidates, @NotNull PsiMethod superMethod) { PsiManager psiManager = PsiManager.getInstance(superMethod.getProject()); for (Pair<FunctionDescriptor, PsiMethod> candidate : superFunctionCandidates) { if (psiManager.areElementsEquivalent(candidate.second, superMethod)) { return candidate.first; } } return null; }
private static void fixPrimaryThrowsLists(PsiMethod method, PsiClassType[] newExceptions) throws IncorrectOperationException { PsiElementFactory elementFactory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); PsiJavaCodeReferenceElement[] refs = new PsiJavaCodeReferenceElement[newExceptions.length]; for (int i = 0; i < refs.length; i++) { refs[i] = elementFactory.createReferenceElementByType(newExceptions[i]); } PsiReferenceList throwsList = elementFactory.createReferenceList(refs); PsiReferenceList methodThrowsList = (PsiReferenceList) method.getThrowsList().replace(throwsList); methodThrowsList = (PsiReferenceList) JavaCodeStyleManager.getInstance(method.getProject()) .shortenClassReferences(methodThrowsList); CodeStyleManager.getInstance(method.getManager().getProject()) .reformatRange( method, method.getParameterList().getTextRange().getEndOffset(), methodThrowsList.getTextRange().getEndOffset()); }
private static void processCallerMethod( JavaChangeInfo changeInfo, PsiMethod caller, PsiMethod baseMethod, boolean toInsertParams, boolean toInsertThrows) throws IncorrectOperationException { LOG.assertTrue(toInsertParams || toInsertThrows); if (toInsertParams) { List<PsiParameter> newParameters = new ArrayList<PsiParameter>(); ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters()); final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters(); PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod); for (JavaParameterInfo info : primaryNewParms) { if (info.getOldIndex() < 0) newParameters.add(createNewParameter(changeInfo, info, substitutor)); } PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm); } if (toInsertThrows) { List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>(); final PsiReferenceList throwsList = caller.getThrowsList(); ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements()); final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions(); for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) { if (thrownExceptionInfo.getOldIndex() < 0) { final PsiClassType type = (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager()); final PsiJavaCodeReferenceElement ref = JavaPsiFacade.getInstance(caller.getProject()) .getElementFactory() .createReferenceElementByType(type); newThrowns.add(ref); } } PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); ChangeSignatureUtil.synchronizeList( throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm); } }
private void updateRefMethod( PsiElement psiResolved, RefElement refResolved, PsiElement refExpression, final PsiElement psiFrom, final RefElement refFrom) { PsiMethod psiMethod = (PsiMethod) psiResolved; RefMethodImpl refMethod = (RefMethodImpl) refResolved; PsiMethodCallExpression call = PsiTreeUtil.getParentOfType(refExpression, PsiMethodCallExpression.class); if (call != null) { PsiType returnType = psiMethod.getReturnType(); if (!psiMethod.isConstructor() && returnType != PsiType.VOID) { if (!(call.getParent() instanceof PsiExpressionStatement)) { refMethod.setReturnValueUsed(true); } addTypeReference(psiFrom, returnType, refFrom.getRefManager()); } PsiExpressionList argumentList = call.getArgumentList(); if (argumentList.getExpressions().length > 0) { refMethod.updateParameterValues(argumentList.getExpressions()); } final PsiExpression psiExpression = call.getMethodExpression().getQualifierExpression(); if (psiExpression != null) { final PsiType usedType = psiExpression.getType(); if (usedType != null) { final String fqName = psiMethod.getContainingClass().getQualifiedName(); if (fqName != null) { final PsiClassType methodOwnerType = JavaPsiFacade.getInstance(call.getProject()) .getElementFactory() .createTypeByFQClassName( fqName, GlobalSearchScope.allScope(psiMethod.getProject())); if (!usedType.equals(methodOwnerType)) { refMethod.setCalledOnSubClass(true); } } } } } }
private static boolean superConstructorHasParameters(PsiMethod method) { final PsiClass psiClass = method.getContainingClass(); if (psiClass == null) { return false; } final PsiClass superClass = psiClass.getSuperClass(); if (superClass != null) { for (final PsiMethod psiMethod : superClass.getConstructors()) { final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(method.getProject()).getResolveHelper(); if (resolveHelper.isAccessible(psiMethod, method, null) && psiMethod.getParameterList().getParameters().length > 0) { return true; } } } return false; }
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; }
@NotNull private static PsiSubstitutor calculateMethodSubstitutor( @NotNull PsiTypeParameter[] typeParameters, @NotNull PsiMethod method, @NotNull PsiSubstitutor siteSubstitutor, @NotNull PsiType[] types1, @NotNull PsiType[] types2, @NotNull LanguageLevel languageLevel) { PsiSubstitutor substitutor = PsiResolveHelper.SERVICE .getInstance(method.getProject()) .inferTypeArguments(typeParameters, types1, types2, languageLevel); for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(method)) { ProgressManager.checkCanceled(); LOG.assertTrue(typeParameter != null); if (!substitutor.getSubstitutionMap().containsKey(typeParameter)) { PsiType type = siteSubstitutor.substitute(typeParameter); if (type instanceof PsiClassType && typeParameter.getOwner() == method) { final PsiClass aClass = ((PsiClassType) type).resolve(); if (aClass instanceof PsiTypeParameter && ((PsiTypeParameter) aClass).getOwner() == method) { type = TypeConversionUtil.erasure(type, siteSubstitutor); } } substitutor = substitutor.put(typeParameter, type); } else { final PsiType type = substitutor.substitute(typeParameter); if (type instanceof PsiClassType) { final PsiClass aClass = ((PsiClassType) type).resolve(); if (aClass instanceof PsiTypeParameter) { substitutor = substitutor.put( typeParameter, JavaPsiFacade.getElementFactory(aClass.getProject()) .createType(aClass, siteSubstitutor)); } } } } return substitutor; }
public static void removeParameter(final PsiMethod method, final PsiParameter parameter) { final PsiParameter[] parameters = method.getParameterList().getParameters(); final List<ParameterInfoImpl> psiParameters = new ArrayList<ParameterInfoImpl>(); int paramIdx = 0; final String paramName = parameter.getName(); for (PsiParameter param : parameters) { if (!Comparing.strEqual(paramName, param.getName())) { psiParameters.add(new ParameterInfoImpl(paramIdx, param.getName(), param.getType())); } paramIdx++; } new ChangeSignatureProcessor( method.getProject(), method, false, null, method.getName(), method.getReturnType(), psiParameters.toArray(new ParameterInfoImpl[psiParameters.size()])) .run(); }
private static void addSuperCall( JavaChangeInfo changeInfo, PsiMethod constructor, PsiMethod callee, final UsageInfo[] usages) throws IncorrectOperationException { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(constructor.getProject()); PsiExpressionStatement superCall = (PsiExpressionStatement) factory.createStatementFromText("super();", constructor); PsiCodeBlock body = constructor.getBody(); assert body != null; PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]); } else { superCall = (PsiExpressionStatement) body.add(superCall); } PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression(); final PsiClass aClass = constructor.getContainingClass(); final PsiClass baseClass = changeInfo.getMethod().getContainingClass(); final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY); processMethodUsage( callExpression.getMethodExpression(), changeInfo, true, false, callee, substitutor, usages); }
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; }
private void addMethodConflicts(MultiMap<PsiElement, String> conflicts) { String newMethodName = myChangeInfo.getNewName(); if (!(myChangeInfo instanceof JavaChangeInfo)) { return; } try { PsiMethod prototype; final PsiMethod method = myChangeInfo.getMethod(); if (!StdLanguages.JAVA.equals(method.getLanguage())) return; PsiManager manager = method.getManager(); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final CanonicalTypes.Type returnType = myChangeInfo.getNewReturnType(); if (returnType != null) { prototype = factory.createMethod(newMethodName, returnType.getType(method, manager)); } else { prototype = factory.createConstructor(); prototype.setName(newMethodName); } JavaParameterInfo[] parameters = myChangeInfo.getNewParameters(); for (JavaParameterInfo info : parameters) { PsiType parameterType = info.createType(method, manager); if (parameterType == null) { parameterType = JavaPsiFacade.getElementFactory(method.getProject()) .createTypeFromText(CommonClassNames.JAVA_LANG_OBJECT, method); } PsiParameter param = factory.createParameter(info.getName(), parameterType); prototype.getParameterList().add(param); } ConflictsUtil.checkMethodConflicts( method.getContainingClass(), method, prototype, conflicts); } catch (IncorrectOperationException e) { LOG.error(e); } }
/** * Creates a new {@link MethodElement} object. * * @param method the PSI method object. * @return a new {@link MethodElement} object. * @since 2.15 */ public static MethodElement newMethodElement(PsiMethod method) { MethodElement me = new MethodElement(); PsiType type = method.getReturnType(); PsiModifierList modifiers = method.getModifierList(); // if something is wrong: // http://www.intellij.net/forums/thread.jsp?nav=false&forum=18&thread=88676&start=0&msRange=15 if (type == null) { log.warn( "This method does not have a valid return type: " + method.getName() + ", returnType=" + type); return me; } PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); setElementInfo(me, factory, type, modifiers); // names String fieldName = PsiAdapter.getGetterFieldName(method); me.setName(fieldName == null ? method.getName() : fieldName); me.setFieldName(fieldName); me.setMethodName(method.getName()); // getter me.setGetter(PsiAdapter.isGetterMethod(method)); // misc me.setDeprecated(method.isDeprecated()); me.setReturnTypeVoid(PsiAdapter.isTypeOfVoid(method.getReturnType())); // modifiers if (modifiers.hasModifierProperty(PsiModifier.ABSTRACT)) me.setModifierAbstract(true); if (modifiers.hasModifierProperty(PsiModifier.SYNCHRONIZED)) me.setModifierSynchronized(true); return me; }
public void checkPrimitiveVarargs( @NotNull List<CandidateInfo> conflicts, final int argumentsCount) { if (JavaVersionService.getInstance().isAtLeast(myArgumentsList, JavaSdkVersion.JDK_1_7)) return; CandidateInfo objectVararg = null; for (CandidateInfo conflict : conflicts) { ProgressManager.checkCanceled(); final PsiMethod method = (PsiMethod) conflict.getElement(); final int parametersCount = method.getParameterList().getParametersCount(); if (method.isVarArgs() && parametersCount - 1 == argumentsCount) { final PsiType type = method.getParameterList().getParameters()[parametersCount - 1].getType(); final PsiType componentType = ((PsiArrayType) type).getComponentType(); final PsiClassType classType = PsiType.getJavaLangObject( method.getManager(), GlobalSearchScope.allScope(method.getProject())); if (Comparing.equal(componentType, classType)) { objectVararg = conflict; } } } if (objectVararg != null) { for (CandidateInfo conflict : conflicts) { ProgressManager.checkCanceled(); PsiMethod method = (PsiMethod) conflict.getElement(); if (method != objectVararg && method.isVarArgs()) { final int paramsCount = method.getParameterList().getParametersCount(); final PsiType type = method.getParameterList().getParameters()[paramsCount - 1].getType(); final PsiType componentType = ((PsiArrayType) type).getComponentType(); if (argumentsCount == paramsCount - 1 && componentType instanceof PsiPrimitiveType) { conflicts.remove(objectVararg); break; } } } } }
private static void modifySuperCall( final PsiMethod subConstructor, final Set<PsiParameter> parametersToPassToSuper) { final PsiCodeBlock body = subConstructor.getBody(); if (body != null) { PsiMethodCallExpression superCall = null; final PsiStatement[] statements = body.getStatements(); if (statements.length > 0) { if (statements[0] instanceof PsiExpressionStatement) { final PsiExpression expression = ((PsiExpressionStatement) statements[0]).getExpression(); if (expression instanceof PsiMethodCallExpression) { final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression; if ("super".equals(methodCall.getMethodExpression().getText())) { superCall = methodCall; } } } } final PsiElementFactory factory = JavaPsiFacade.getInstance(subConstructor.getProject()).getElementFactory(); try { if (superCall == null) { PsiExpressionStatement statement = (PsiExpressionStatement) factory.createStatementFromText("super();", null); statement = (PsiExpressionStatement) body.addAfter(statement, null); superCall = (PsiMethodCallExpression) statement.getExpression(); } final PsiExpressionList argList = superCall.getArgumentList(); for (final PsiParameter parameter : parametersToPassToSuper) { argList.add(factory.createExpressionFromText(parameter.getName(), null)); } } catch (IncorrectOperationException e) { LOG.error(e); } } }
private static void completeAnnotationAttributeName( CompletionResultSet result, PsiElement insertedElement, CompletionParameters parameters) { PsiNameValuePair pair = PsiTreeUtil.getParentOfType(insertedElement, PsiNameValuePair.class); PsiAnnotationParameterList parameterList = (PsiAnnotationParameterList) pair.getParent(); PsiAnnotation anno = (PsiAnnotation) parameterList.getParent(); boolean showClasses = psiElement().afterLeaf("(").accepts(insertedElement); PsiClass annoClass = null; final PsiJavaCodeReferenceElement referenceElement = anno.getNameReferenceElement(); if (referenceElement != null) { final PsiElement element = referenceElement.resolve(); if (element instanceof PsiClass) { annoClass = (PsiClass) element; if (annoClass.findMethodsByName("value", false).length == 0) { showClasses = false; } } } if (showClasses && insertedElement.getParent() instanceof PsiReferenceExpression) { final Set<LookupElement> set = JavaCompletionUtil.processJavaReference( insertedElement, (PsiJavaReference) insertedElement.getParent(), new ElementExtractorFilter(createAnnotationFilter(insertedElement)), JavaCompletionProcessor.Options.DEFAULT_OPTIONS, result.getPrefixMatcher(), parameters); for (final LookupElement element : set) { result.addElement(element); } addAllClasses(parameters, result, new InheritorsHolder(insertedElement, result)); } if (annoClass != null) { final PsiNameValuePair[] existingPairs = parameterList.getAttributes(); methods: for (PsiMethod method : annoClass.getMethods()) { if (!(method instanceof PsiAnnotationMethod)) continue; final String attrName = method.getName(); for (PsiNameValuePair existingAttr : existingPairs) { if (PsiTreeUtil.isAncestor(existingAttr, insertedElement, false)) break; if (Comparing.equal(existingAttr.getName(), attrName) || PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(attrName) && existingAttr.getName() == null) continue methods; } LookupElementBuilder element = LookupElementBuilder.createWithIcon(method) .withInsertHandler( new InsertHandler<LookupElement>() { @Override public void handleInsert(InsertionContext context, LookupElement item) { final Editor editor = context.getEditor(); TailType.EQ.processTail(editor, editor.getCaretModel().getOffset()); context.setAddCompletionChar(false); context.commitDocument(); PsiAnnotationParameterList paramList = PsiTreeUtil.findElementOfClassAtOffset( context.getFile(), context.getStartOffset(), PsiAnnotationParameterList.class, false); if (paramList != null && paramList.getAttributes().length > 0 && paramList.getAttributes()[0].getName() == null) { int valueOffset = paramList.getAttributes()[0].getTextRange().getStartOffset(); context .getDocument() .insertString( valueOffset, PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME); TailType.EQ.processTail( editor, valueOffset + PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.length()); } } }); PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod) method).getDefaultValue(); if (defaultValue != null) { Object constant = JavaPsiFacade.getInstance(method.getProject()) .getConstantEvaluationHelper() .computeConstantExpression(defaultValue); if (constant != null) { element = element.withTailText( " default " + (constant instanceof String ? "\"" + constant + "\"" : constant), true); } } result.addElement(element); } } }
@Override public boolean reduce(InferenceSession session, List<ConstraintFormula> constraints) { if (!LambdaUtil.isFunctionalType(myT)) { return false; } final PsiType groundTargetType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(myT); final PsiClassType.ClassResolveResult classResolveResult = PsiUtil.resolveGenericsClassInType(groundTargetType); final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(classResolveResult); if (interfaceMethod == null) { return false; } final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, classResolveResult); final PsiParameter[] targetParameters = interfaceMethod.getParameterList().getParameters(); final PsiType interfaceMethodReturnType = interfaceMethod.getReturnType(); final PsiType returnType = substitutor.substitute(interfaceMethodReturnType); final PsiType[] typeParameters = myExpression.getTypeParameters(); final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(myExpression); if (!myExpression.isExact()) { for (PsiParameter parameter : targetParameters) { if (!session.isProperType(substitutor.substitute(parameter.getType()))) { return false; } } } else { final PsiMember applicableMember = myExpression.getPotentiallyApplicableMember(); LOG.assertTrue(applicableMember != null); final PsiClass applicableMemberContainingClass = applicableMember.getContainingClass(); final PsiClass containingClass = qualifierResolveResult.getContainingClass(); PsiSubstitutor psiSubstitutor = qualifierResolveResult.getSubstitutor(); psiSubstitutor = applicableMemberContainingClass == null || containingClass == null || myExpression.isConstructor() ? psiSubstitutor : TypeConversionUtil.getSuperClassSubstitutor( applicableMemberContainingClass, containingClass, psiSubstitutor); PsiType applicableMethodReturnType = applicableMember instanceof PsiMethod ? ((PsiMethod) applicableMember).getReturnType() : null; int idx = 0; for (PsiTypeParameter param : ((PsiTypeParameterListOwner) applicableMember).getTypeParameters()) { if (idx < typeParameters.length) { psiSubstitutor = psiSubstitutor.put(param, typeParameters[idx++]); } } final PsiParameter[] parameters = applicableMember instanceof PsiMethod ? ((PsiMethod) applicableMember).getParameterList().getParameters() : PsiParameter.EMPTY_ARRAY; if (targetParameters.length == parameters.length + 1) { specialCase(session, constraints, substitutor, targetParameters, true); for (int i = 1; i < targetParameters.length; i++) { constraints.add( new TypeCompatibilityConstraint( session.substituteWithInferenceVariables( psiSubstitutor.substitute(parameters[i - 1].getType())), substitutor.substitute(targetParameters[i].getType()))); } } else if (targetParameters.length == parameters.length) { for (int i = 0; i < targetParameters.length; i++) { constraints.add( new TypeCompatibilityConstraint( session.substituteWithInferenceVariables( psiSubstitutor.substitute(parameters[i].getType())), substitutor.substitute(targetParameters[i].getType()))); } } else { return false; } if (returnType != PsiType.VOID && returnType != null) { if (applicableMethodReturnType == PsiType.VOID) { return false; } if (applicableMethodReturnType != null) { constraints.add( new TypeCompatibilityConstraint( returnType, session.substituteWithInferenceVariables( psiSubstitutor.substitute(applicableMethodReturnType)))); } else if (applicableMember instanceof PsiClass || applicableMember instanceof PsiMethod && ((PsiMethod) applicableMember).isConstructor()) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(applicableMember.getProject()); if (containingClass != null) { final PsiType classType = session.substituteWithInferenceVariables( elementFactory.createType(containingClass, psiSubstitutor)); constraints.add(new TypeCompatibilityConstraint(returnType, classType)); } } } return true; } final Map<PsiElement, PsiType> map = LambdaUtil.getFunctionalTypeMap(); final PsiType added = map.put(myExpression, session.startWithFreshVars(groundTargetType)); final JavaResolveResult resolve; try { resolve = myExpression.advancedResolve(true); } finally { if (added == null) { map.remove(myExpression); } } final PsiElement element = resolve.getElement(); if (element == null) { return false; } if (PsiType.VOID.equals(returnType) || returnType == null) { return true; } if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod) element; final PsiType referencedMethodReturnType; final PsiClass containingClass = method.getContainingClass(); LOG.assertTrue(containingClass != null, method); PsiClass qContainingClass = qualifierResolveResult.getContainingClass(); PsiSubstitutor psiSubstitutor = qualifierResolveResult.getSubstitutor(); if (qContainingClass != null) { if (PsiUtil.isRawSubstitutor(qContainingClass, psiSubstitutor)) { psiSubstitutor = PsiSubstitutor.EMPTY; } if (qContainingClass.isInheritor(containingClass, true)) { psiSubstitutor = TypeConversionUtil.getClassSubstitutor( containingClass, qContainingClass, PsiSubstitutor.EMPTY); LOG.assertTrue(psiSubstitutor != null); } } if (method.isConstructor()) { referencedMethodReturnType = JavaPsiFacade.getElementFactory(method.getProject()) .createType(containingClass, PsiSubstitutor.EMPTY); } else { referencedMethodReturnType = method.getReturnType(); } LOG.assertTrue(referencedMethodReturnType != null, method); if (!PsiTreeUtil.isContextAncestor(containingClass, myExpression, false) || PsiUtil.getEnclosingStaticElement(myExpression, containingClass) != null) { session.initBounds(myExpression, containingClass.getTypeParameters()); } session.initBounds(myExpression, method.getTypeParameters()); // if i) the method reference elides NonWildTypeArguments, // ii) the compile-time declaration is a generic method, and // iii) the return type of the compile-time declaration mentions at least one of the method's // type parameters; if (typeParameters.length == 0 && method.getTypeParameters().length > 0) { final PsiClass interfaceClass = classResolveResult.getElement(); LOG.assertTrue(interfaceClass != null); if (PsiPolyExpressionUtil.mentionsTypeParameters( referencedMethodReturnType, ContainerUtil.newHashSet(method.getTypeParameters()))) { // the constraint reduces to the bound set B3 which would be used to determine the method // reference's invocation type // when targeting the return type of the function type, as defined in 18.5.2. session.collectApplicabilityConstraints( myExpression, ((MethodCandidateInfo) resolve), groundTargetType); session.registerReturnTypeConstraints(referencedMethodReturnType, returnType); return true; } } if (PsiType.VOID.equals(referencedMethodReturnType)) { return false; } int idx = 0; for (PsiTypeParameter param : method.getTypeParameters()) { if (idx < typeParameters.length) { psiSubstitutor = psiSubstitutor.put(param, typeParameters[idx++]); } } final PsiParameter[] parameters = method.getParameterList().getParameters(); if (targetParameters.length == parameters.length + 1 && !method.isVarArgs() && PsiPolyExpressionUtil.mentionsTypeParameters( referencedMethodReturnType, ContainerUtil.newHashSet( containingClass.getTypeParameters()))) { // todo specification bug? specialCase(session, constraints, substitutor, targetParameters, false); } constraints.add( new TypeCompatibilityConstraint( returnType, session.substituteWithInferenceVariables( psiSubstitutor.substitute(referencedMethodReturnType)))); } return true; }
@Override @Nullable protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project) { if (aClass instanceof PsiAnonymousClass) { Messages.showMessageDialog( project, CodeInsightBundle.message("error.attempt.to.generate.constructor.for.anonymous.class"), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return null; } myCopyJavadoc = false; PsiMethod[] baseConstructors = null; PsiClass baseClass = aClass.getSuperClass(); if (baseClass != null) { ArrayList<PsiMethod> array = new ArrayList<PsiMethod>(); for (PsiMethod method : baseClass.getConstructors()) { if (JavaPsiFacade.getInstance(method.getProject()) .getResolveHelper() .isAccessible(method, aClass, null)) { array.add(method); } } if (!array.isEmpty()) { if (array.size() == 1) { baseConstructors = new PsiMethod[] {array.get(0)}; } else { final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY); PsiMethodMember[] constructors = ContainerUtil.map2Array( array, PsiMethodMember.class, new Function<PsiMethod, PsiMethodMember>() { @Override public PsiMethodMember fun(final PsiMethod s) { return new PsiMethodMember(s, substitutor); } }); MemberChooser<PsiMethodMember> chooser = new MemberChooser<PsiMethodMember>(constructors, false, true, project); chooser.setTitle( CodeInsightBundle.message("generate.constructor.super.constructor.chooser.title")); chooser.show(); List<PsiMethodMember> elements = chooser.getSelectedElements(); if (elements == null || elements.isEmpty()) return null; baseConstructors = new PsiMethod[elements.size()]; for (int i = 0; i < elements.size(); i++) { final ClassMember member = elements.get(i); baseConstructors[i] = ((PsiMethodMember) member).getElement(); } myCopyJavadoc = chooser.isCopyJavadoc(); } } } ClassMember[] allMembers = getAllOriginalMembers(aClass); ClassMember[] members; if (allMembers.length == 0) { members = ClassMember.EMPTY_ARRAY; } else { members = chooseMembers(allMembers, true, false, project, null); if (members == null) return null; } if (baseConstructors != null) { ArrayList<ClassMember> array = new ArrayList<ClassMember>(); for (PsiMethod baseConstructor : baseConstructors) { array.add(new PsiMethodMember(baseConstructor)); } ContainerUtil.addAll(array, members); members = array.toArray(new ClassMember[array.size()]); } return members; }
public static PsiMethod generateConstructorPrototype( PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException { PsiManager manager = aClass.getManager(); JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject()); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject()); PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass); String modifier = PsiUtil.getMaximumModifierForMember(aClass, false); if (modifier != null) { PsiUtil.setModifierProperty(constructor, modifier, true); } if (baseConstructor != null) { PsiJavaCodeReferenceElement[] throwRefs = baseConstructor.getThrowsList().getReferenceElements(); for (PsiJavaCodeReferenceElement ref : throwRefs) { constructor.getThrowsList().add(ref); } if (copyJavaDoc) { final PsiDocComment docComment = ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment(); if (docComment != null) { constructor.addAfter(docComment, null); } } } boolean isNotEnum = false; if (baseConstructor != null) { PsiClass superClass = aClass.getSuperClass(); LOG.assertTrue(superClass != null); if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) { isNotEnum = true; if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names PsiClass dummyClass = JVMElementFactories.requireFactory( baseConstructor.getLanguage(), baseConstructor.getProject()) .createClass("Dummy"); baseConstructor = (PsiMethod) dummyClass.add(baseConstructor); } PsiParameter[] params = baseConstructor.getParameterList().getParameters(); for (PsiParameter param : params) { PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass); GenerateMembersUtil.copyOrReplaceModifierList(param, newParam); constructor.getParameterList().add(newParam); } } } JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject()); final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName()); dummyConstructor.getParameterList().replace(constructor.getParameterList().copy()); List<PsiParameter> fieldParams = new ArrayList<PsiParameter>(); for (PsiField field : fields) { String fieldName = field.getName(); String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD); String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER); parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true); PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass); final NullableNotNullManager nullableManager = NullableNotNullManager.getInstance(field.getProject()); final String notNull = nullableManager.getNotNull(field); if (notNull != null) { parm.getModifierList() .addAfter(factory.createAnnotationFromText("@" + notNull, field), null); } constructor.getParameterList().add(parm); dummyConstructor.getParameterList().add(parm.copy()); fieldParams.add(parm); } ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage()); if (generator != null) { @NonNls StringBuilder buffer = new StringBuilder(); generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY); if (isNotEnum) { generator.generateSuperCallIfNeeded( buffer, baseConstructor.getParameterList().getParameters()); } generator.generateFieldInitialization( buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()])); generator.finish(buffer); PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass); constructor.getBody().replace(stub.getBody()); } constructor = (PsiMethod) codeStyleManager.reformat(constructor); return constructor; }
private void doMoveMethod(PsiSubstitutor substitutor, MemberInfo info) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); PsiMethod method = (PsiMethod) info.getMember(); PsiMethod sibling = method; PsiMethod anchor = null; while (sibling != null) { sibling = PsiTreeUtil.getNextSiblingOfType(sibling, PsiMethod.class); if (sibling != null) { anchor = MethodSignatureUtil.findMethodInSuperClassBySignatureInDerived( method.getContainingClass(), myTargetSuperClass, sibling.getSignature(PsiSubstitutor.EMPTY), false); if (anchor != null) { break; } } } PsiMethod methodCopy = (PsiMethod) method.copy(); Language language = myTargetSuperClass.getLanguage(); final PsiMethod superClassMethod = myTargetSuperClass.findMethodBySignature(methodCopy, false); if (superClassMethod != null && superClassMethod.findDeepestSuperMethods().length == 0 || method.findSuperMethods(myTargetSuperClass).length == 0) { deleteOverrideAnnotationIfFound(methodCopy); } boolean isOriginalMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT) || method.hasModifierProperty(PsiModifier.DEFAULT); boolean isOriginalMethodPrototype = method instanceof HaxeFunctionPrototypeDeclarationWithAttributes; if (myIsTargetInterface || info.isToAbstract()) { ChangeContextUtil.clearContextInfo(method); if (!info.isToAbstract() && !method.hasModifierProperty(PsiModifier.ABSTRACT) && PsiUtil.isLanguageLevel8OrHigher(myTargetSuperClass)) { // pull as default RefactoringUtil.makeMethodDefault(methodCopy); isOriginalMethodAbstract = true; } else { RefactoringUtil.makeMethodAbstract(myTargetSuperClass, methodCopy); } RefactoringUtil.replaceMovedMemberTypeParameters( methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); myJavaDocPolicy.processCopiedJavaDoc( methodCopy.getDocComment(), method.getDocComment(), isOriginalMethodAbstract); final PsiMember movedElement; if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { movedElement = (PsiMember) superClassMethod.replace(convertMethodToLanguage(methodCopy, language)); } else { methodCopy = HaxeElementGenerator.createFunctionPrototypeDeclarationWithAttributes( myProject, methodCopy.getText().trim() + ";"); movedElement = anchor != null ? (PsiMember) myTargetSuperClass.addBefore(methodCopy, anchor) : (PsiMember) myTargetSuperClass.addBefore(methodCopy, myTargetSuperClass.getRBrace()); reformat(movedElement); } CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(method.getProject()); if (styleSettings.INSERT_OVERRIDE_ANNOTATION) { if (PsiUtil.isLanguageLevel5OrHigher(mySourceClass) && !myIsTargetInterface || PsiUtil.isLanguageLevel6OrHigher(mySourceClass)) { new AddAnnotationFix(Override.class.getName(), method) .invoke(method.getProject(), null, mySourceClass.getContainingFile()); } } if (!PsiUtil.isLanguageLevel6OrHigher(mySourceClass) && myIsTargetInterface) { if (isOriginalMethodAbstract) { for (PsiMethod oMethod : OverridingMethodsSearch.search(method)) { deleteOverrideAnnotationIfFound(oMethod); } } deleteOverrideAnnotationIfFound(method); } myMembersAfterMove.add(movedElement); // if (isOriginalMethodAbstract) { method.delete(); // } } else { if (isOriginalMethodAbstract) { PsiUtil.setModifierProperty(myTargetSuperClass, PsiModifier.ABSTRACT, true); } RefactoringUtil.replaceMovedMemberTypeParameters( methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory); fixReferencesToStatic(methodCopy); if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { superClassMethod.replace(convertMethodToLanguage(methodCopy, language)); } else { final PsiMember movedElement = anchor != null ? (PsiMember) myTargetSuperClass.addBefore( convertMethodToLanguage(methodCopy, language), anchor) : (PsiMember) myTargetSuperClass.addBefore( convertMethodToLanguage(methodCopy, language), myTargetSuperClass.getRBrace()); reformat(movedElement); myMembersAfterMove.add(movedElement); } method.delete(); } }