private boolean checkMethodSignature(PsiMethod method) { // subscribe() calls that have no return type are custom Observers whose error handling we cannot check if (PsiType.VOID.equals(method.getReturnType())) { return false; } int argCount = method.getParameterList().getParametersCount(); // when more than one argument is given, there is usually one error callback included if (argCount > 1) { return false; } // no arguments, no error handling if (argCount == 0) { return true; } // if we have only one argument, check that it's not a BiConsumer PsiParameter parameter = method.getParameterList().getParameters()[0]; return !"io.reactivex.functions.BiConsumer".equals(parameter.getType().getCanonicalText()); }
private PsiElement findExtensionMethodNavigationElement( PsiClass extClass, PsiMethod plantedMethod ) { PsiMethod[] found = extClass.findMethodsByName( plantedMethod.getName(), false ); outer: for( PsiMethod m : found ) { PsiParameter[] extParams = m.getParameterList().getParameters(); PsiParameter[] plantedParams = plantedMethod.getParameterList().getParameters(); if( extParams.length - 1 == plantedParams.length ) { for( int i = 1; i < extParams.length; i++ ) { PsiParameter extParam = extParams[i]; PsiParameter plantedParam = plantedParams[i - 1]; PsiType extErased = TypeConversionUtil.erasure( extParam.getType() ); PsiType plantedErased = TypeConversionUtil.erasure( plantedParam.getType() ); if( !extErased.toString().equals( plantedErased.toString() ) ) { continue outer; } } return m.getNavigationElement(); } } return null; }
@Nullable public PsiType inferType( PsiTypeElement typeElement ) { PsiType psiType = null; final PsiElement parent = typeElement.getParent(); if( (parent instanceof PsiLocalVariable && isVar( (PsiLocalVariable)parent )) || (parent instanceof PsiParameter && isVarForEach( (PsiParameter)parent )) ) { if( parent instanceof PsiLocalVariable ) { psiType = processLocalVariableInitializer( ((PsiLocalVariable)parent).getInitializer() ); } else { psiType = processForeach( ((PsiParameter)parent).getDeclarationScope() ); } if( null == psiType ) { psiType = PsiType.getJavaLangObject( typeElement.getManager(), GlobalSearchScope.allScope( typeElement.getProject() ) ); } } return psiType; }
void check(@NonNull PsiMethod method) { if (mClass != null && !mClassFields.isEmpty()) { // メソッド引数に boolean のパラメータがある場合のみ対象とする Map<String, PsiParameter> parameters = new HashMap<>(); PsiParameter[] params = method.getParameterList().getParameters(); for (PsiParameter param : params) { if (param.getType() != PsiType.BOOLEAN) continue; parameters.put(param.getName(), param); } if (parameters.isEmpty()) return; mMethod = method; mFlagMethodParameters.clear(); mFlagMethodParameters.putAll(parameters); mFlagLogic = null; } }
private static void seekChildren(PsiElement element, PsiIdentifier target, Find find) { for (PsiElement child : element.getChildren()) { if (child instanceof PsiLocalVariable) { PsiLocalVariable localVariable = (PsiLocalVariable) child; if (isSameName(target, localVariable.getNameIdentifier())) { find.findLocalVariable = localVariable; return; } } if (child instanceof PsiParameter) { PsiParameter parameter = (PsiParameter) child; if (isSameName(target, parameter.getNameIdentifier())) { find.findParameter = parameter; return; } } seekChildren(child, target, find); if (!find.isEmpty()) return; } }
@Override public void generateFieldInitialization(@NotNull StringBuilder buffer, @NotNull PsiField[] fields, @NotNull PsiParameter[] parameters) { for (int i = 0, length = fields.length; i < length; i++) { String fieldName = fields[i].getName(); String paramName = parameters[i].getName(); if (fieldName.equals(paramName)) { buffer.append("this."); } buffer.append(fieldName); buffer.append("="); buffer.append(paramName); buffer.append(";\n"); } }
@Override public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException { if (psiElement instanceof PsiParameterList) { String text = psiElement.getText(); if (StringUtil.startsWithChar(text, '(') && !StringUtil.endsWithChar(text, ')')) { PsiParameter[] params = ((PsiParameterList)psiElement).getParameters(); int offset; if (params.length == 0) { offset = psiElement.getTextRange().getStartOffset() + 1; } else { offset = params[params.length - 1].getTextRange().getEndOffset(); } editor.getDocument().insertString(offset, ")"); } } }
private void appendAccessors(final Set<PsiParameter> params, boolean isGetter) { final PsiElement element = getElement(); if (element != null) { for (PsiParameter parameter : params) { final IntroduceParameterObjectProcessor.ParameterChunk parameterChunk = IntroduceParameterObjectProcessor.ParameterChunk.getChunkByParameter(parameter, parameters); LOGGER.assertTrue(parameterChunk != null); final PsiField field = parameterChunk.getField(); if (field != null) { element.add(isGetter ? GenerateMembersUtil.generateGetterPrototype(field) : GenerateMembersUtil.generateSetterPrototype(field)); } } } }
private void appendConflicts(StringBuffer buf, final Set<PsiParameter> paramsNeeding) { if (!paramsNeeding.isEmpty()) { buf.append(paramsNeeding == paramsNeedingGetters ? "Getters" : "Setters"); buf.append(" for the following fields are required:\n"); buf.append(StringUtil.join(paramsNeeding, new Function<PsiParameter, String>() { public String fun(PsiParameter psiParameter) { final IntroduceParameterObjectProcessor.ParameterChunk chunk = IntroduceParameterObjectProcessor.ParameterChunk.getChunkByParameter(psiParameter, parameters); if (chunk != null) { final PsiField field = chunk.getField(); if (field != null) { return field.getName(); } } return psiParameter.getName(); } }, ", ")); buf.append(".\n"); } }
public AutomaticParametersRenamer(PsiParameter param, String newParamName) { final PsiElement scope = param.getDeclarationScope(); if (scope instanceof PsiMethod) { final PsiMethod method = (PsiMethod)scope; final int parameterIndex = method.getParameterList().getParameterIndex(param); if (parameterIndex < 0) return; for (PsiMethod overrider : OverridingMethodsSearch.search(method)) { final PsiParameter[] parameters = overrider.getParameterList().getParameters(); if (parameterIndex >= parameters.length) continue; final PsiParameter inheritedParam = parameters[parameterIndex]; if (!Comparing.strEqual(inheritedParam.getName(), newParamName)) { myElements.add(inheritedParam); suggestAllNames(inheritedParam.getName(), newParamName); } } } }
public IntroduceParameterSettingsUI(PsiLocalVariable onLocalVariable, PsiExpression onExpression, PsiMethod methodToReplaceIn, TIntArrayList parametersToRemove) { myHasInitializer = onLocalVariable != null && onLocalVariable.getInitializer() != null; myIsInvokedOnDeclaration = onExpression == null; final PsiParameter[] parameters = methodToReplaceIn.getParameterList().getParameters(); myParametersToRemove = new PsiParameter[parameters.length]; myParametersToRemoveChecked = new boolean[parameters.length]; parametersToRemove.forEach(new TIntProcedure() { public boolean execute(final int paramNum) { myParametersToRemove[paramNum] = parameters[paramNum]; return true; } }); myIsLocalVariable = onLocalVariable != null; }
public MethodJavaDocHelper(PsiMethod method) { myMethod = method; myDocComment = myMethod.getDocComment(); if (myDocComment == null) { myDoCorrectJavaDoc = false; return; } final PsiParameter[] parameters = myMethod.getParameterList().getParameters(); if (parameters.length != 0) { final PsiDocTag[] paramTags = myDocComment.findTagsByName("param"); if (paramTags.length > 0) { myDoCorrectJavaDoc = true; } else { myDoCorrectJavaDoc = false; } } else { myDoCorrectJavaDoc = true; } }
public static String fillMethodParameters(final PsiMethod method, @Nullable final TIntObjectHashMap<SubLookupElement> replaceElements) { final TIntObjectHashMap<SubLookupElement> notNullReplaceElements = replaceElements == null ? new TIntObjectHashMap<SubLookupElement>(0) : replaceElements; final PsiParameter[] parameters = method.getParameterList().getParameters(); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < parameters.length; i++) { if (i != 0) { sb.append(", "); } final PsiParameter parameter = parameters[i]; final SubLookupElement replaceElement = notNullReplaceElements.get(i); if (replaceElement != null) { sb.append(replaceElement.getInsertString()); } else { sb.append(parameter.getName()); } } return sb.toString(); }
private static MatchResult matchParameters(final PsiMethod method, final ChainCompletionContext context, final Set<String> additionalExcludedNames) { int matched = 0; int unMatched = 0; boolean hasTarget = false; for (final PsiParameter parameter : method.getParameterList().getParameters()) { final PsiType type = parameter.getType(); final String canonicalText = type.getCanonicalText(); if (context.contains(canonicalText) || type instanceof PsiPrimitiveType) { matched++; } else { unMatched++; } if (context.getTarget().getClassQName().equals(canonicalText) || additionalExcludedNames.contains(canonicalText)) { hasTarget = true; } } return new MatchResult(matched, unMatched, hasTarget); }
@Override public void visitMethod(@NotNull PsiMethod method) { final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() == 0) { return; } final Query<MethodSignatureBackedByPsiMethod> query = SuperMethodsSearch.search( method, method.getContainingClass(), true, false); final MethodSignatureBackedByPsiMethod methodSignature = query.findFirst(); if (methodSignature == null) { return; } final PsiMethod superMethod = methodSignature.getMethod(); final PsiParameter[] parameters = parameterList.getParameters(); checkParameters(superMethod, parameters); }
@Override public void visitCatchSection(PsiCatchSection section) { super.visitCatchSection(section); final PsiParameter parameter = section.getParameter(); if (parameter == null) { return; } final PsiTypeElement typeElement = parameter.getTypeElement(); if (typeElement == null) { return; } final PsiTypeElement[] childTypeElements = PsiTreeUtil.getChildrenOfType(typeElement, PsiTypeElement.class); if (childTypeElements != null) { for (PsiTypeElement childTypeElement : childTypeElements) { checkTypeElement(childTypeElement); } } else { checkTypeElement(typeElement); } }
@Override protected void check(@NotNull GrControlFlowOwner owner, @NotNull ProblemsHolder problemsHolder) { Instruction[] flow = owner.getControlFlow(); ReadWriteVariableInstruction[] reads = ControlFlowBuilderUtil.getReadsWithoutPriorWrites(flow, true); for (ReadWriteVariableInstruction read : reads) { PsiElement element = read.getElement(); if (element instanceof GroovyPsiElement && !(element instanceof GrClosableBlock)) { String name = read.getVariableName(); GroovyPsiElement property = ResolveUtil.resolveProperty((GroovyPsiElement)element, name); if (property != null && !(property instanceof PsiParameter) && !(property instanceof PsiField) && PsiTreeUtil.isAncestor(owner, property, false) && !(myIgnoreBooleanExpressions && isBooleanCheck(element)) ) { problemsHolder.registerProblem(element, GroovyInspectionBundle.message("unassigned.access.tooltip", name)); } } } }
@Override public void generateFieldInitialization(@NotNull StringBuilder buffer, @NotNull PsiField[] fields, @NotNull PsiParameter[] parameters) { for (int i = 0, length = fields.length; i < length; i++) { String fieldName = fields[i].getName(); String paramName = parameters[i].getName(); if (fieldName.equals(paramName)) { buffer.append("this."); } buffer.append(fieldName); buffer.append("="); buffer.append(paramName); buffer.append("\n"); } }
public static Result searchForVarsToWrap(GroovyPsiElement root, Result analyzedVars, ExpressionContext context) { LocalVarAnalyzer visitor = new LocalVarAnalyzer(); root.accept(visitor); Map<PsiVariable, String> varToName = analyzedVars == null ? new HashMap<PsiVariable, String>() : analyzedVars.varToName; Set<PsiVariable> toWrap = analyzedVars == null ? new HashSet<PsiVariable>() : analyzedVars.toWrap; Set<PsiVariable> toMakeFinal = analyzedVars == null ? new HashSet<PsiVariable>() : analyzedVars.toMakeFinal; for (PsiVariable v : visitor.touched) { if (visitor.rewritten.contains(v)) { toWrap.add(v); if (v instanceof PsiParameter) { varToName.put(v, GenerationUtil.suggestVarName(v.getType(), root, context)); } else { varToName.put(v, v.getName()); } } else { toMakeFinal.add(v); varToName.put(v, v.getName()); } } return analyzedVars == null ? new Result(toMakeFinal, toWrap, varToName) : analyzedVars; }
private boolean hasParameterName(PsiParameter psiParameter) { PsiModifierList modifierList = psiParameter.getModifierList(); if (modifierList == null) { return false; } PsiAnnotation annotation = modifierList.findAnnotation("javax.inject.Named"); if (annotation != null) { return true; } annotation = modifierList.findAnnotation(GctConstants.APP_ENGINE_ANNOTATION_NAMED); if (annotation != null) { return true; } return false; }
private void initializePsiMethod(String methodName, String httpMethodValue, String pathValue) { PsiAnnotationMemberValue mockAnnotationMemberValue1 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue1.getText()).thenReturn(httpMethodValue); PsiAnnotationMemberValue mockAnnotationMemberValue2 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue2.getText()).thenReturn(pathValue); PsiAnnotation mockAnnotation = mock(PsiAnnotation.class); when(mockAnnotation.getQualifiedName()) .thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API_METHOD); when(mockAnnotation.findAttributeValue("httpMethod")).thenReturn(mockAnnotationMemberValue1); when(mockAnnotation.findAttributeValue("path")).thenReturn(mockAnnotationMemberValue2); PsiAnnotation[] mockAnnotationsArray = {mockAnnotation}; PsiModifierList mockModifierList = mock(PsiModifierList.class); when(mockModifierList.getAnnotations()).thenReturn(mockAnnotationsArray); mockPsiMethod = mock(PsiMethod.class); when(mockPsiMethod.getModifierList()).thenReturn(mockModifierList); when(mockPsiMethod.getName()).thenReturn(methodName); when(mockPsiMethod.getContainingClass()).thenReturn(mockPsiClass); PsiParameterList mockParameterList = mock(PsiParameterList.class); when(mockParameterList.getParameters()).thenReturn(new PsiParameter[0]); when(mockPsiMethod.getParameterList()).thenReturn(mockParameterList); }
/** * Tests that the NamedResourceInspection's quick fix flagged with {@link * NamedResourceError#MISSING_NAME} for an @Named annotation with a {@link PsiParameter} parent * updates the query name to to the name of the {@link PsiParameter}. */ public void testQuickFix_noQueryNameSpecifiedWithParameter() { Project myProject = myFixture.getProject(); PsiParameter parameter = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createParameterFromText("@javax.inject.Named() String foobar", null); PsiAnnotation[] annotationsList = parameter.getModifierList().getAnnotations(); assert (annotationsList.length == 1); NamedResourceInspection.MissingNameQuickFix myQuickFix = new NamedResourceInspection().new MissingNameQuickFix(); MockProblemDescriptor problemDescriptor = new MockProblemDescriptor(annotationsList[0], "", ProblemHighlightType.ERROR); myQuickFix.applyFix(myProject, problemDescriptor); assertEquals("@javax.inject.Named(\"foobar\")", annotationsList[0].getText()); }
@Override protected Collection<DfaMemoryState> createInitialStates(@NotNull PsiElement psiBlock, InstructionVisitor visitor) { final Collection<DfaMemoryState> initialStates = super.createInitialStates(psiBlock, visitor); if (initialStates == null) { return null; } final PsiElement parent = psiBlock.getParent(); if (parent instanceof PsiMethod) { PsiMethod method = (PsiMethod)parent; //todo move out from generic runner for (PsiParameter parameter : method.getParameterList().getParameters()) { if (NullableNotNullManager.isNotNull(parameter)) { final DfaVariableValue value = getFactory().getVarFactory().createVariableValue(parameter, false); for (final DfaMemoryState initialState : initialStates) { initialState.applyNotNull(value); } } } } return initialStates; }
public static boolean checkParametersForTypesQNames(final PsiMethod[] psiMethods, final Set<String> excludedTypesQNames) { if (psiMethods.length == 0) { return true; } for (final PsiMethod method : psiMethods) { boolean hasTargetInParams = false; for (final PsiParameter param : method.getParameterList().getParameters()) { final String paramType = param.getType().getCanonicalText(); if (excludedTypesQNames.contains(paramType)) { hasTargetInParams = true; break; } } if (!hasTargetInParams) { return true; } } return false; }
@Nullable @Override protected PsiParameter[] getParams(PsiElement element) { final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class); final PsiParameter[] parameters = method.getParameterList().getParameters(); final ParameterClassMember[] members = new ParameterClassMember[parameters.length]; for (int i = 0; i < members.length; i++) { members[i] = new ParameterClassMember(parameters[i]); } final MemberChooser<ParameterClassMember> chooser = new MemberChooser<ParameterClassMember>(members, false, true, element.getProject()); chooser.selectElements(members); chooser.setTitle("Choose " + (method.isConstructor() ? "Constructor" : "Method") + " Parameters"); chooser.show(); if (chooser.isOK()) { final List<ParameterClassMember> elements = chooser.getSelectedElements(); if (elements != null) { PsiParameter[] params = new PsiParameter[elements.size()]; for (int i = 0; i < params.length; i++) { params[i] = elements.get(i).getParameter(); } return params; } } return null; }
@Override public void visitParameter(@NotNull PsiParameter parameter) { super.visitParameter(parameter); if (parameter.getDeclarationScope() instanceof PsiCatchSection) { return; } final PsiTypeElement typeElement = parameter.getTypeElement(); if (typeElement == null) { return; } if (!ConcreteClassUtil.typeIsConcreteClass(typeElement, ignoreAbstractClasses)) { return; } final String variableName = parameter.getName(); registerError(typeElement, variableName); }
protected void check(GrControlFlowOwner owner, ProblemsHolder problemsHolder) { Instruction[] flow = owner.getControlFlow(); ReadWriteVariableInstruction[] reads = ControlFlowBuilderUtil.getReadsWithoutPriorWrites(flow, true); for (ReadWriteVariableInstruction read : reads) { PsiElement element = read.getElement(); if (element instanceof GroovyPsiElement) { String name = read.getVariableName(); GroovyPsiElement property = ResolveUtil.resolveProperty((GroovyPsiElement)element, name); if (property != null && !(property instanceof PsiParameter) && !(property instanceof PsiField) && PsiTreeUtil.isAncestor(owner, property, false) && !GppTypeConverter.hasTypedContext(element) && !(myIgnoreBooleanExpressions && isBooleanCheck(element)) ) { problemsHolder.registerProblem(element, GroovyInspectionBundle.message("unassigned.access.tooltip", name)); } } } }
/** * Finds and removes a given method * @param methodName * @param arguments */ private void findAndRemoveMethod(String methodName, String... arguments) { // Maybe there's an easier way to do this with mClass.findMethodBySignature(), but I'm not an expert on Psi* PsiMethod[] methods = psiClass.findMethodsByName(methodName, false); for (PsiMethod method : methods) { PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() == arguments.length) { boolean shouldDelete = true; PsiParameter[] parameters = parameterList.getParameters(); for (int i = 0; i < arguments.length; i++) { if (!parameters[i].getType().getCanonicalText().equals(arguments[i])) { shouldDelete = false; } } if (shouldDelete) { method.delete(); } } } }