@Override public void visitNewExpression(PsiNewExpression expression) { super.visitNewExpression(expression); final PsiJavaCodeReferenceElement classReference = expression.getClassReference(); if (classReference == null) { return; } final String name = classReference.getReferenceName(); if (!"BigDecimal".equals(name)) { return; } final PsiMethod constructor = expression.resolveConstructor(); if (constructor == null) { return; } final PsiParameterList parameterList = constructor.getParameterList(); final int length = parameterList.getParametersCount(); if (length != 1 && length != 2) { return; } final PsiParameter[] parameters = parameterList.getParameters(); final PsiParameter firstParameter = parameters[0]; final PsiType type = firstParameter.getType(); if (type != PsiType.DOUBLE) { return; } registerNewExpressionError(expression); }
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); }
ParamUsageVisitor(PsiMethod method, int[] paramIndicesToMerge) { super(); final PsiParameterList paramList = method.getParameterList(); final PsiParameter[] parameters = paramList.getParameters(); for (int i : paramIndicesToMerge) { paramsToMerge.add(parameters[i]); } }
@Nullable public static PsiParameter getAnchorParameter(PsiParameterList parameterList, boolean isVarArgs) { final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (isVarArgs) { return length > 1 ? parameters[length - 2] : null; } else { return length > 0 ? parameters[length - 1] : null; } }
@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); }
public JLabel getPopupEntryText(RearrangerSettings settings) { StringBuffer name = new StringBuffer(80); PsiMethod m = (PsiMethod) myEnd; if (m.getReturnTypeElement() != null && !settings.isShowTypeAfterMethod()) { name.append(m.getReturnTypeElement().getText()); name.append(' '); } name.append(m.getName()); PsiParameterList plist = m.getParameterList(); if (settings.isShowParameterNames() || settings.isShowParameterTypes()) { if (plist != null) { name.append("("); for (int i = 0; i < plist.getParameters().length; i++) { if (i > 0) { name.append(", "); } if (settings.isShowParameterTypes()) { String modifiers = plist.getParameters()[i].getModifierList().getText(); if (modifiers.length() > 0) { name.append(modifiers); name.append(' '); } name.append(plist.getParameters()[i].getTypeElement().getText()); if (settings.isShowParameterNames()) { name.append(' '); } } if (settings.isShowParameterNames()) { name.append(plist.getParameters()[i].getName()); } } name.append(")"); } } if (m.getReturnTypeElement() != null && settings.isShowTypeAfterMethod()) { name.append(": "); name.append(m.getReturnTypeElement().getText()); } return new JLabel(name.toString()); }
@Nullable public static PsiParameter findParameterAtCursor(@NotNull PsiFile file, @NotNull Editor editor) { final int offset = editor.getCaretModel().getOffset(); final PsiParameterList parameterList = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiParameterList.class, false); if (parameterList == null) return null; final PsiParameter[] parameters = parameterList.getParameters(); for (PsiParameter parameter : parameters) { final TextRange range = parameter.getTextRange(); if (range.getStartOffset() <= offset && offset <= range.getEndOffset()) return parameter; } return null; }
@Nullable private static PsiMethod existingClassIsCompatible(PsiClass aClass, List<ParameterChunk> params) { if (params.size() == 1) { final ParameterChunk parameterChunk = params.get(0); final PsiType paramType = parameterChunk.parameter.type; if (TypeConversionUtil.isPrimitiveWrapper(aClass.getQualifiedName())) { parameterChunk.setField(aClass.findFieldByName("value", false)); parameterChunk.setGetter(paramType.getCanonicalText() + "Value"); for (PsiMethod constructor : aClass.getConstructors()) { if (constructorIsCompatible(constructor, params)) return constructor; } } } final PsiMethod[] constructors = aClass.getConstructors(); PsiMethod compatibleConstructor = null; for (PsiMethod constructor : constructors) { if (constructorIsCompatible(constructor, params)) { compatibleConstructor = constructor; break; } } if (compatibleConstructor == null) { return null; } final PsiParameterList parameterList = compatibleConstructor.getParameterList(); final PsiParameter[] constructorParams = parameterList.getParameters(); for (int i = 0; i < constructorParams.length; i++) { final PsiParameter param = constructorParams[i]; final ParameterChunk parameterChunk = params.get(i); final PsiField field = findFieldAssigned(param, compatibleConstructor); if (field == null) { return null; } parameterChunk.setField(field); final PsiMethod getterForField = PropertyUtil.findGetterForField(field); if (getterForField != null) { parameterChunk.setGetter(getterForField.getName()); } final PsiMethod setterForField = PropertyUtil.findSetterForField(field); if (setterForField != null) { parameterChunk.setSetter(setterForField.getName()); } } return compatibleConstructor; }
@Nullable private static PsiParameter getAnchorParameter(PsiMethod methodToReplaceIn) { PsiParameterList parameterList = methodToReplaceIn.getParameterList(); final PsiParameter anchorParameter; final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (!methodToReplaceIn.isVarArgs()) { anchorParameter = length > 0 ? parameters[length - 1] : null; } else { LOG.assertTrue(length > 0); LOG.assertTrue(parameters[length - 1].isVarArgs()); anchorParameter = length > 1 ? parameters[length - 2] : null; } return anchorParameter; }
private static boolean constructorIsCompatible( PsiMethod constructor, List<ParameterChunk> params) { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] constructorParams = parameterList.getParameters(); if (constructorParams.length != params.size()) { return false; } for (int i = 0; i < constructorParams.length; i++) { if (!TypeConversionUtil.isAssignable( constructorParams[i].getType(), params.get(i).parameter.type)) { return false; } } return true; }
public static boolean isDefaultInstantiable(PsiClass psiClass) { final PsiMethod[] constructors = psiClass.getConstructors(); if (constructors.length == 0) { return true; } for (PsiMethod psiMethod : constructors) { final PsiParameterList parameterList = psiMethod.getParameterList(); if (psiMethod.getModifierList().hasModifierProperty("public") && parameterList.getParameters().length == 0) { return true; } } return false; }
private static boolean usesDefaultClone(PsiClass aClass) { final Project project = aClass.getProject(); final PsiManager manager = aClass.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass cloneable = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Cloneable", scope); if (!InheritanceUtil.isInheritorOrSelf(aClass, cloneable, true)) { return false; } final PsiMethod[] methods = aClass.findMethodsByName("clone", false); for (PsiMethod method : methods) { final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length == 0) { return false; } } return true; }
private boolean hasOnlyMain(PsiClass aClass) { final PsiMethod[] methods = aClass.getMethods(); if (methods.length == 0) { return false; } for (PsiMethod method : methods) { if (method.isConstructor()) { continue; } if (!method.hasModifierProperty(PsiModifier.STATIC)) { return false; } if (method.hasModifierProperty(PsiModifier.PRIVATE)) { continue; } if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { return false; } final String name = method.getName(); if (!name.equals(HardcodedMethodConstants.MAIN)) { return false; } final PsiType returnType = method.getReturnType(); if (!PsiType.VOID.equals(returnType)) { return false; } final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() != 1) { return false; } final PsiParameter[] parameters = parameterList.getParameters(); final PsiParameter parameter = parameters[0]; final PsiType type = parameter.getType(); if (!type.equalsToText("java.lang.String[]")) { return false; } } return true; }
private static boolean isClassHasConstructorWithMap(PsiClass aClass) { PsiMethod[] constructors = aClass.getConstructors(); if (constructors.length == 0) return true; for (PsiMethod constructor : constructors) { PsiParameterList parameterList = constructor.getParameterList(); PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length == 0) return true; final PsiParameter first = parameters[0]; if (InheritanceUtil.isInheritor(first.getType(), CommonClassNames.JAVA_UTIL_MAP)) return true; if (first instanceof GrParameter && ((GrParameter) first).getTypeGroovy() == null) return true; // if constructor has only optional parameters it can be used as default constructor with map // args if (!PsiUtil.isConstructorHasRequiredParameters(constructor)) return true; } return false; }
private static boolean usesDefaultSerialization(PsiClass aClass) { final Project project = aClass.getProject(); final PsiManager manager = aClass.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass serializable = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.io.Serializable", scope); if (!InheritanceUtil.isInheritorOrSelf(aClass, serializable, true)) { return false; } final PsiMethod[] methods = aClass.findMethodsByName("writeObject", false); for (PsiMethod method : methods) { final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length == 1) { final PsiType type = parameters[0].getType(); final String text = type.getCanonicalText(); if ("java.io.DataOutputStream".equals(text)) { return false; } } } return true; }
private void addTypesByVariable( HashSet<PsiType> typesSet, PsiVariable var, PsiFile scopeFile, HashSet<PsiVariable> checkedVariables, int flags, TextRange rangeToIgnore) { if (!checkedVariables.add(var)) return; // System.out.println("analyzing usages of " + var + " in file " + scopeFile); SearchScope searchScope = new LocalSearchScope(scopeFile); if (BitUtil.isSet(flags, CHECK_USAGE) || BitUtil.isSet(flags, CHECK_DOWN)) { for (PsiReference varRef : ReferencesSearch.search(var, searchScope, false)) { PsiElement ref = varRef.getElement(); if (BitUtil.isSet(flags, CHECK_USAGE)) { PsiType type = guessElementTypeFromReference(myMethodPatternMap, ref, rangeToIgnore); if (type != null && !(type instanceof PsiPrimitiveType)) { typesSet.add(type); } } if (BitUtil.isSet(flags, CHECK_DOWN)) { if (ref.getParent() instanceof PsiExpressionList && ref.getParent().getParent() instanceof PsiMethodCallExpression) { // TODO : new PsiExpressionList list = (PsiExpressionList) ref.getParent(); PsiExpression[] args = list.getExpressions(); int argIndex = -1; for (int j = 0; j < args.length; j++) { PsiExpression arg = args[j]; if (arg.equals(ref)) { argIndex = j; break; } } PsiMethodCallExpression methodCall = (PsiMethodCallExpression) list.getParent(); PsiMethod method = (PsiMethod) methodCall.getMethodExpression().resolve(); if (method != null) { PsiParameter[] parameters = method.getParameterList().getParameters(); if (argIndex < parameters.length) { addTypesByVariable( typesSet, parameters[argIndex], method.getContainingFile(), checkedVariables, flags | CHECK_USAGE, rangeToIgnore); } } } } } } if (BitUtil.isSet(flags, CHECK_UP)) { if (var instanceof PsiParameter && var.getParent() instanceof PsiParameterList && var.getParent().getParent() instanceof PsiMethod) { PsiParameterList list = (PsiParameterList) var.getParent(); PsiParameter[] parameters = list.getParameters(); int argIndex = -1; for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; if (parameter.equals(var)) { argIndex = i; break; } } PsiMethod method = (PsiMethod) var.getParent().getParent(); // System.out.println("analyzing usages of " + method + " in file " + scopeFile); for (PsiReference methodRef : ReferencesSearch.search(method, searchScope, false)) { PsiElement ref = methodRef.getElement(); if (ref.getParent() instanceof PsiMethodCallExpression) { PsiMethodCallExpression methodCall = (PsiMethodCallExpression) ref.getParent(); PsiExpression[] args = methodCall.getArgumentList().getExpressions(); if (args.length <= argIndex) continue; PsiExpression arg = args[argIndex]; if (arg instanceof PsiReferenceExpression) { PsiElement refElement = ((PsiReferenceExpression) arg).resolve(); if (refElement instanceof PsiVariable) { addTypesByVariable( typesSet, (PsiVariable) refElement, scopeFile, checkedVariables, flags | CHECK_USAGE, rangeToIgnore); } } // TODO : constructor } } } } }
private void prepareBehaviourForReturningParameter() { given(psiClass.getConstructors()).willReturn(constructors); given(constructor.getParameterList()).willReturn(parameterList); given(parameterList.getParameters()).willReturn(parameters); }
private static boolean addParameterToConstructor( final Project project, final PsiFile file, final Editor editor, final PsiMethod constructor, final PsiField[] fields) throws IncorrectOperationException { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); ParameterInfoImpl[] newParamInfos = new ParameterInfoImpl[parameters.length + fields.length]; final List<PsiVariable> params = new ArrayList<PsiVariable>(Arrays.asList(parameters)); Collections.addAll(params, fields); Collections.sort(params, new FieldParameterComparator(parameterList)); int i = 0; final HashMap<PsiField, String> usedFields = new HashMap<PsiField, String>(); for (PsiVariable param : params) { final PsiType paramType = param.getType(); if (param instanceof PsiParameter) { newParamInfos[i++] = new ParameterInfoImpl( parameterList.getParameterIndex((PsiParameter) param), param.getName(), paramType, param.getName()); } else { final String uniqueParameterName = getUniqueParameterName(parameters, param, usedFields); usedFields.put((PsiField) param, uniqueParameterName); newParamInfos[i++] = new ParameterInfoImpl(-1, uniqueParameterName, paramType, uniqueParameterName); } } final SmartPointerManager manager = SmartPointerManager.getInstance(project); final SmartPsiElementPointer constructorPointer = manager.createSmartPsiElementPointer(constructor); final PsiMethod fromText = JavaPsiFacade.getElementFactory(project) .createMethodFromText(createDummyMethod(constructor, newParamInfos), constructor); final PsiClass containingClass = constructor.getContainingClass(); if (containingClass == null) return false; final int minUsagesNumber = containingClass.findMethodsBySignature(fromText, false).length > 0 ? 0 : 1; final List<ParameterInfoImpl> parameterInfos = ChangeMethodSignatureFromUsageFix.performChange( project, editor, file, constructor, minUsagesNumber, newParamInfos, true, true); final ParameterInfoImpl[] resultParams = parameterInfos != null ? parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()]) : newParamInfos; return ApplicationManager.getApplication() .runWriteAction( new Computable<Boolean>() { @Override public Boolean compute() { return doCreate( project, editor, parameters, constructorPointer, resultParams, usedFields); } }); }
public List<PsiParameter> getChildren(PsiParameterList psiParameterList) { return Arrays.asList(psiParameterList.getParameters()); }
private static void processPrimaryMethod( JavaChangeInfo changeInfo, PsiMethod method, PsiMethod baseMethod, boolean isOriginal) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); if (changeInfo.isVisibilityChanged()) { PsiModifierList modifierList = method.getModifierList(); final String highestVisibility = isOriginal ? changeInfo.getNewVisibility() : VisibilityUtil.getHighestVisibility( changeInfo.getNewVisibility(), VisibilityUtil.getVisibilityModifier(modifierList)); VisibilityUtil.setVisibility(modifierList, highestVisibility); } if (changeInfo.isNameChanged()) { String newName = baseMethod == null ? changeInfo.getNewName() : RefactoringUtil.suggestNewOverriderName( method.getName(), baseMethod.getName(), changeInfo.getNewName()); if (newName != null && !newName.equals(method.getName())) { final PsiIdentifier nameId = method.getNameIdentifier(); assert nameId != null; nameId.replace( JavaPsiFacade.getInstance(method.getProject()) .getElementFactory() .createIdentifier(newName)); } } final PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : ChangeSignatureProcessor.calculateSubstitutor(method, baseMethod); if (changeInfo.isReturnTypeChanged()) { PsiType newTypeElement = changeInfo .getNewReturnType() .getType(changeInfo.getMethod().getParameterList(), method.getManager()); final PsiType returnType = substitutor.substitute(newTypeElement); // don't modify return type for non-Java overriders (EJB) if (method.getName().equals(changeInfo.getNewName())) { final PsiTypeElement typeElement = method.getReturnTypeElement(); if (typeElement != null) { typeElement.replace(factory.createTypeElement(returnType)); } } } PsiParameterList list = method.getParameterList(); PsiParameter[] parameters = list.getParameters(); final JavaParameterInfo[] parameterInfos = changeInfo.getNewParameters(); final int delta = baseMethod != null ? baseMethod.getParameterList().getParametersCount() - method.getParameterList().getParametersCount() : 0; PsiParameter[] newParms = new PsiParameter[Math.max(parameterInfos.length - delta, 0)]; final String[] oldParameterNames = changeInfo.getOldParameterNames(); final String[] oldParameterTypes = changeInfo.getOldParameterTypes(); for (int i = 0; i < newParms.length; i++) { JavaParameterInfo info = parameterInfos[i]; int index = info.getOldIndex(); if (index >= 0) { PsiParameter parameter = parameters[index]; newParms[i] = parameter; String oldName = oldParameterNames[index]; if (!oldName.equals(info.getName()) && oldName.equals(parameter.getName())) { PsiIdentifier newIdentifier = factory.createIdentifier(info.getName()); parameter.getNameIdentifier().replace(newIdentifier); } String oldType = oldParameterTypes[index]; if (!oldType.equals(info.getTypeText())) { parameter.normalizeDeclaration(); PsiType newType = substitutor.substitute( info.createType(changeInfo.getMethod().getParameterList(), method.getManager())); parameter.getTypeElement().replace(factory.createTypeElement(newType)); } } else { newParms[i] = createNewParameter(changeInfo, info, substitutor); } } resolveParameterVsFieldsConflicts(newParms, method, list, changeInfo.toRemoveParm()); fixJavadocsForChangedMethod(method, changeInfo, newParms.length); if (changeInfo.isExceptionSetOrOrderChanged()) { final PsiClassType[] newExceptions = getPrimaryChangedExceptionInfo(changeInfo); fixPrimaryThrowsLists(method, newExceptions); } }
public static int getParameterIndex( @NotNull PsiParameter parameter, @NotNull PsiParameterList parameterList) { PsiParameter[] parameters = parameterList.getParameters(); for (int i = 0; i < parameters.length; i++) { PsiParameter paramInList = parameters[i]; if (parameter.equals(paramInList)) return i; } String name = parameter.getName(); PsiParameter suspect = null; int i; for (i = parameters.length - 1; i >= 0; i--) { PsiParameter paramInList = parameters[i]; if (name.equals(paramInList.getName())) { suspect = paramInList; break; } } String message = parameter + ":" + parameter.getClass() + " not found among parameters: " + Arrays.asList(parameters) + "." + " parameterList' parent: " + parameterList.getParent() + ";" + " parameter.getParent()==paramList: " + (parameter.getParent() == parameterList) + "; " + parameterList.getClass() + ";" + " parameter.isValid()=" + parameter.isValid() + ";" + " parameterList.isValid()= " + parameterList.isValid() + ";" + " parameterList stub: " + (parameterList instanceof StubBasedPsiElement ? ((StubBasedPsiElement) parameterList).getStub() : "---") + "; " + " parameter stub: " + (parameter instanceof StubBasedPsiElement ? ((StubBasedPsiElement) parameter).getStub() : "---") + ";" + " suspect: " + suspect + " (index=" + i + "); " + (suspect == null ? null : suspect.getClass()) + " suspect stub: " + (suspect instanceof StubBasedPsiElement ? ((StubBasedPsiElement) suspect).getStub() : suspect == null ? "-null-" : "---" + suspect.getClass()) + ";" + " parameter.equals(suspect) = " + parameter.equals(suspect) + "; " + " parameter.getNode() == suspect.getNode(): " + (parameter.getNode() == (suspect == null ? null : suspect.getNode())) + "; " + "."; LOG.error(message); return i; }