private boolean isStructuralType( PsiTypeElement typeElem ) { if( typeElem != null ) { PsiClass psiClass = PsiUtil.resolveClassInType( typeElem.getType() ); if( psiClass == null ) { return false; } PsiAnnotation structuralAnno = psiClass.getModifierList() == null ? null : psiClass.getModifierList().findAnnotation( "manifold.ext.api.Structural" ); if( structuralAnno != null ) { return true; } } return false; }
@Override public void visitAssertStatement(PsiAssertStatement statement) { super.visitAssertStatement(statement); final PsiExpression assertCondition = statement.getAssertCondition(); final PsiExpression expression = ParenthesesUtils.stripParentheses(assertCondition); if (expression == null) { return; } if (BoolUtils.isFalse(expression)) { return; } if (!PsiUtil.isConstantExpression(expression)) { return; } registerError(expression); }
@Nullable private static String getBoxedPropertyType(PsiElement declaration) { PsiType attrType = null; if (declaration instanceof PsiField) { attrType = JavaFxPsiUtil.getWrappedPropertyType((PsiField)declaration, declaration.getProject(), JavaFxCommonClassNames.ourWritableMap); } else if (declaration instanceof PsiMethod) { final PsiParameter[] parameters = ((PsiMethod)declaration).getParameterList().getParameters(); final boolean isStatic = ((PsiMethod)declaration).hasModifierProperty(PsiModifier.STATIC); if (isStatic && parameters.length == 2 || !isStatic && parameters.length == 1) { attrType = parameters[parameters.length - 1].getType(); } } String boxedQName = null; if (attrType instanceof PsiPrimitiveType) { boxedQName = ((PsiPrimitiveType)attrType).getBoxedTypeName(); } else if (PsiPrimitiveType.getUnboxedType(attrType) != null) { final PsiClass attrClass = PsiUtil.resolveClassInType(attrType); boxedQName = attrClass != null ? attrClass.getQualifiedName() : null; } return boxedQName; }
private static PsiType getIteratedType(PsiElement parent, PsiType collection) { if (parent instanceof GrReferenceExpression) { final GrExpression qualifier = ((GrReferenceExpression)parent).getQualifier(); if (qualifier != null) { return ClosureParameterEnhancer.findTypeForIteration(qualifier, parent); } } final PsiType iterable = PsiUtil.extractIterableTypeParameter(collection, true); if (iterable != null && parent instanceof GrExpression) { return PsiImplUtil.normalizeWildcardTypeByPosition(iterable, (GrExpression)parent); } else { return iterable; } }
@NotNull public static PsiVariable[] getVariablesVisibleAt(@Nullable final PsiElement place, String prefix) { if (place == null) { return new PsiVariable[0]; } final Set<String> usedNames = ContainerUtil.newHashSet(); final List<PsiVariable> list = new ArrayList<PsiVariable>(); VariablesProcessor varproc = new VariablesProcessor(prefix, true, list) { @Override public boolean execute(@NotNull PsiElement pe, @NotNull ResolveState state) { if (pe instanceof PsiVariable) { if (!usedNames.add(((PsiVariable)pe).getName())) { return false; } //exclude variables that are initialized in 'place' final PsiExpression initializer = ((PsiVariable)pe).getInitializer(); if (initializer != null && PsiTreeUtil.isAncestor(initializer, place, false)) return true; } return pe instanceof PsiField && !PsiUtil.isAccessible((PsiField)pe, place, null) || super.execute(pe, state); } }; PsiScopesUtil.treeWalkUp(varproc, place, null); return varproc.getResultsAsArray(); }
private PsiType inferIteratorType(GroovyResolveResult iteratorMethodResult, GrExpression tupleInitializer) { PsiElement method = iteratorMethodResult.getElement(); if (method instanceof PsiMethod) { return iteratorMethodResult.getSubstitutor().substitute(((PsiMethod)method).getReturnType()); } else { PsiType initializerType = tupleInitializer.getType(); PsiType iterableParam = PsiUtil.extractIterableTypeParameter(initializerType, false); JavaPsiFacade facade = JavaPsiFacade.getInstance(context.project); PsiClass iterableClass = facade.findClass(CommonClassNames.JAVA_UTIL_ITERATOR, tupleInitializer.getResolveScope()); if (iterableClass != null && iterableParam != null) { return facade.getElementFactory().createType(iterableClass, iterableParam); } else { return facade.getElementFactory().createTypeFromText(CommonClassNames.JAVA_UTIL_ITERATOR, tupleInitializer); } } }
private static boolean hasStaticInitializer(PsiField field) { if (field.hasModifierProperty(PsiModifier.STATIC)) { final PsiExpression initializer = field.getInitializer(); if (initializer == null) { return false; } final PsiType fieldType = field.getType(); final PsiType stringType = TypeUtils.getStringType(field); if (field.hasModifierProperty(PsiModifier.FINAL) && (fieldType instanceof PsiPrimitiveType || fieldType.equals(stringType))) { return !PsiUtil.isConstantExpression(initializer); } else { return true; } } return false; }
@Override public void visitConditionalExpression(PsiConditionalExpression expression) { super.visitConditionalExpression(expression); final PsiExpression condition = PsiUtil.skipParenthesizedExprDown(expression.getCondition()); if (!(condition instanceof PsiBinaryExpression)) { return; } final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)condition; final PsiReferenceExpression referenceExpression = extractVariableReference(binaryExpression); if (referenceExpression == null) { return; } final IElementType tokenType = binaryExpression.getOperationTokenType(); if (tokenType == JavaTokenType.EQEQ) { if (checkVariableUsage(referenceExpression, expression.getThenExpression(), expression.getElseExpression())) { registerError(referenceExpression, Boolean.FALSE); } } else if (tokenType == JavaTokenType.NE) { if (checkVariableUsage(referenceExpression, expression.getElseExpression(), expression.getThenExpression())) { registerError(referenceExpression, Boolean.FALSE); } } }
boolean isReferencedForWrite(@NotNull PsiVariable variable) { Collection<PsiReference> array; synchronized (myLocalRefsMap) { array = myLocalRefsMap.get(variable); } if (array.isEmpty()) return false; for (PsiReference ref : array) { final PsiElement refElement = ref.getElement(); if (!(refElement instanceof PsiExpression)) { // possible with incomplete code return true; } if (PsiUtil.isAccessedForWriting((PsiExpression)refElement)) { return true; } } return false; }
private void addExprTypesByDerivedClasses(LinkedHashSet<PsiType> set, PsiExpression expr) { PsiType type = expr.getType(); if (!(type instanceof PsiClassType)) return; PsiClass refClass = PsiUtil.resolveClassInType(type); if (refClass == null) return; PsiManager manager = PsiManager.getInstance(myProject); PsiElementProcessor.CollectElementsWithLimit<PsiClass> processor = new PsiElementProcessor.CollectElementsWithLimit<PsiClass>(5); ClassInheritorsSearch.search(refClass, true).forEach(new PsiElementProcessorAdapter<PsiClass>(processor)); if (processor.isOverflow()) return; for (PsiClass derivedClass : processor.getCollection()) { if (derivedClass instanceof PsiAnonymousClass) continue; PsiType derivedType = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createType(derivedClass); set.add(derivedType); } }
private static void registerSwapFixes(final PsiExpression[] expressions, final PsiCall callExpression, final List<PsiCall> permutations, MethodCandidateInfo candidate, final int incompatibilitiesCount, final int minIncompatibleIndex, final int maxIncompatibleIndex) throws IncorrectOperationException { PsiMethod method = candidate.getElement(); PsiSubstitutor substitutor = candidate.getSubstitutor(); if (incompatibilitiesCount >= 3) return; // no way we can fix it by swapping for (int i = minIncompatibleIndex; i < maxIncompatibleIndex; i++) { for (int j = i+1; j <= maxIncompatibleIndex; j++) { ArrayUtil.swap(expressions, i, j); if (PsiUtil.isApplicable(method, substitutor, expressions)) { PsiCall copy = (PsiCall)callExpression.copy(); PsiExpression[] copyExpressions = copy.getArgumentList().getExpressions(); copyExpressions[i].replace(expressions[i]); copyExpressions[j].replace(expressions[j]); JavaResolveResult result = copy.resolveMethodGenerics(); if (result.getElement() != null && result.isValidResult()) { permutations.add(copy); if (permutations.size() > 1) return; } } ArrayUtil.swap(expressions, i, j); } } }
private void checkExpression(PsiExpression expression) { expression = PsiUtil.deparenthesizeExpression(expression); if (negate) { if (expression instanceof PsiPrefixExpression) { final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression; final IElementType tokenType = prefixExpression.getOperationTokenType(); if (tokenType != JavaTokenType.EXCL) { return; } expression = PsiUtil.deparenthesizeExpression( prefixExpression.getOperand()); checkInstanceOfExpression(expression); } } else { checkInstanceOfExpression(expression); } if (expression instanceof PsiPolyadicExpression) { final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)expression; visitPolyadicExpression(binaryExpression); } }
@Nullable private Collection<DfaMemoryState> createInitialStates(@NotNull PsiElement psiBlock, InstructionVisitor visitor) { PsiClass containingClass = PsiTreeUtil.getParentOfType(psiBlock, PsiClass.class); if (containingClass != null && PsiUtil.isLocalOrAnonymousClass(containingClass)) { final PsiElement parent = containingClass.getParent(); final PsiCodeBlock block = DfaPsiUtil.getTopmostBlockInSameClass(parent); if ((parent instanceof PsiNewExpression || parent instanceof PsiDeclarationStatement) && block != null) { final RunnerResult result = analyzeMethod(block, visitor); if (result == RunnerResult.OK) { final Collection<DfaMemoryState> closureStates = myNestedClosures.get(DfaPsiUtil.getTopmostBlockInSameClass(psiBlock)); if (!closureStates.isEmpty()) { return closureStates; } } return null; } } return Collections.singletonList(createMemoryState()); }
public boolean addBound(PsiType classType, InferenceBound inferenceBound) { if (inferenceBound == InferenceBound.EQ && PsiUtil.resolveClassInClassTypeOnly(classType) == this) { return false; } List<PsiType> list = myBounds.get(inferenceBound); if (list == null) { list = new ArrayList<PsiType>(); myBounds.put(inferenceBound, list); } final int idx = list.indexOf(classType); if (idx < 0) { list.add(classType); return true; } return false; }
protected static void chooseAndImplement(PsiClass psiClass, Project project, @NotNull PsiClass targetClass, Editor editor) { boolean hasNonTrivialConstructor = false; final PsiMethod[] constructors = psiClass.getConstructors(); for (PsiMethod constructor : constructors) { if (constructor.getParameterList().getParametersCount() > 0) { hasNonTrivialConstructor = true; break; } } if (hasNonTrivialConstructor) { final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(psiClass, targetClass, PsiSubstitutor.EMPTY); final List<PsiMethodMember> baseConstructors = new ArrayList<PsiMethodMember>(); for (PsiMethod baseConstr : constructors) { if (PsiUtil.isAccessible(project, baseConstr, targetClass, targetClass)) { baseConstructors.add(new PsiMethodMember(baseConstr, substitutor)); } } final int offset = editor.getCaretModel().getOffset(); CreateConstructorMatchingSuperFix.chooseConstructor2Delegate(project, editor, substitutor, baseConstructors, constructors, targetClass); editor.getCaretModel().moveToOffset(offset); } OverrideImplementUtil.chooseAndImplementMethods(project, editor, targetClass); }
public static String createTempVar(PsiExpression expr, PsiElement context, boolean declareFinal) throws IncorrectOperationException { PsiElement anchorStatement = getParentStatement(context, true); LOG.assertTrue(anchorStatement != null && anchorStatement.getParent() != null); Project project = expr.getProject(); String[] suggestedNames = JavaCodeStyleManager.getInstance(project).suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expr, null).names; final String prefix = suggestedNames.length > 0 ? suggestedNames[0] : "var"; final String id = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName(prefix, context, true); PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory(); if (expr instanceof PsiParenthesizedExpression) { PsiExpression expr1 = ((PsiParenthesizedExpression)expr).getExpression(); if (expr1 != null) { expr = expr1; } } PsiDeclarationStatement decl = factory.createVariableDeclarationStatement(id, expr.getType(), expr); if (declareFinal) { PsiUtil.setModifierProperty(((PsiLocalVariable)decl.getDeclaredElements()[0]), PsiModifier.FINAL, true); } anchorStatement.getParent().addBefore(decl, anchorStatement); return id; }
@Nullable private static Map<PsiTypeParameter, PsiTypeParameter> calculateReplacementMap(final PsiSubstitutor substitutor, final PsiClass targetClass, final PsiElement containingElement) { final HashMap<PsiTypeParameter, PsiTypeParameter> result = new HashMap<PsiTypeParameter, PsiTypeParameter>(); for (PsiTypeParameter classTypeParameter : PsiUtil.typeParametersIterable(targetClass)) { final PsiType substitution = substitutor.substitute(classTypeParameter); if (!(substitution instanceof PsiClassType)) return null; final PsiClass aClass = ((PsiClassType)substitution).resolve(); if (!(aClass instanceof PsiTypeParameter)) return null; final PsiTypeParameter methodTypeParameter = (PsiTypeParameter)aClass; if (methodTypeParameter.getOwner() != containingElement) return null; if (result.keySet().contains(methodTypeParameter)) return null; result.put(methodTypeParameter, classTypeParameter); } return result; }
private void getExpectedArgumentsTypesForNewExpression(@NotNull final PsiNewExpression newExpr, @NotNull final PsiExpressionList list) { PsiType newType = newExpr.getType(); if (newType instanceof PsiClassType) { JavaResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(newType); PsiClass newClass = (PsiClass)resolveResult.getElement(); final PsiSubstitutor substitutor; if (newClass instanceof PsiAnonymousClass) { final PsiAnonymousClass anonymous = (PsiAnonymousClass)newClass; newClass = anonymous.getBaseClassType().resolve(); if (newClass == null) return; substitutor = TypeConversionUtil.getSuperClassSubstitutor(newClass, anonymous, PsiSubstitutor.EMPTY); } else if (newClass != null) { substitutor = resolveResult.getSubstitutor(); } else { return; } getExpectedTypesForConstructorCall(newClass, list, substitutor); } }
@Nullable private static PsiSubstitutor unify(@NotNull PsiSubstitutor substitutor, @NotNull PsiSubstitutor parentSubstitutor, @NotNull Project project) { Map<PsiTypeParameter,PsiType> newMap = new THashMap<PsiTypeParameter, PsiType>(substitutor.getSubstitutionMap()); for (Map.Entry<PsiTypeParameter, PsiType> entry : substitutor.getSubstitutionMap().entrySet()) { PsiTypeParameter typeParameter = entry.getKey(); PsiType type = entry.getValue(); PsiClass resolved = PsiUtil.resolveClassInType(type); if (!parentSubstitutor.getSubstitutionMap().containsKey(typeParameter)) continue; PsiType parentType = parentSubstitutor.substitute(parentSubstitutor.substitute(typeParameter)); if (resolved instanceof PsiTypeParameter) { PsiTypeParameter res = (PsiTypeParameter)resolved; newMap.put(res, parentType); } else if (!Comparing.equal(type, parentType)) { return null; // cannot unify } } return JavaPsiFacade.getElementFactory(project).createSubstitutor(newMap); }
@Override public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { final PsiVariable refVariable = findPreviousVariable(); if (refVariable == null) return; if (!CodeInsightUtil.preparePsiElementsForWrite(myVariable, refVariable)) return; final PsiExpression initializer = myVariable.getInitializer(); if (initializer == null) { myVariable.delete(); return; } PsiUtil.setModifierProperty(refVariable, PsiModifier.FINAL, false); final PsiElementFactory factory = JavaPsiFacade.getInstance(myVariable.getProject()).getElementFactory(); final PsiElement statement = factory.createStatementFromText(myVariable.getName() + " = " + initializer.getText() + ";", null); myVariable.getParent().replace(statement); }
@Nullable @Override public ResolvedClass getSuperClass() { if (myClass != null) { PsiClass superClass = myClass.getSuperClass(); // When you make an anonymous inner class from an interface like this, // we want to treat the interface itself as the "super class" // public View.OnClickListener onSave = new View.OnClickListener() { // @Override // public void onClick(View v) { // .. if (PsiUtil.isLocalOrAnonymousClass(myClass)) { PsiClass[] interfaces = myClass.getInterfaces(); if (interfaces.length > 0) { return new ResolvedPsiClass(interfaces[0]); } } if (superClass != null) { return new ResolvedPsiClass(superClass); } } return null; }
@Nullable public static PsiAnnotationMemberValue findAttributeValue(@NotNull PsiAnnotation annotation, @Nullable @NonNls String attributeName) { final PsiAnnotationMemberValue value = findDeclaredAttributeValue(annotation, attributeName); if (value != null) return value; if (attributeName == null) attributeName = "value"; final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement(); if (referenceElement != null) { PsiElement resolved = referenceElement.resolve(); if (resolved != null) { PsiMethod[] methods = ((PsiClass)resolved).findMethodsByName(attributeName, false); for (PsiMethod method : methods) { if (PsiUtil.isAnnotationMethod(method)) { return ((PsiAnnotationMethod)method).getDefaultValue(); } } } } return null; }
public static PsiType normalizeWildcardTypeByPosition(@NotNull PsiType type, @NotNull PsiExpression expression) { PsiUtilCore.ensureValid(expression); PsiUtil.ensureValidType(type); PsiExpression topLevel = expression; while (topLevel.getParent() instanceof PsiArrayAccessExpression && ((PsiArrayAccessExpression)topLevel.getParent()).getArrayExpression() == topLevel) { topLevel = (PsiExpression)topLevel.getParent(); } if (topLevel instanceof PsiArrayAccessExpression && !PsiUtil.isAccessedForWriting(topLevel)) { return PsiUtil.captureToplevelWildcards(type, expression); } final PsiType normalized = doNormalizeWildcardByPosition(type, expression, topLevel); LOG.assertTrue(normalized.isValid(), type); if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(topLevel)) { return PsiUtil.captureToplevelWildcards(normalized, expression); } return normalized; }
@Override public boolean ignoreInference(@NotNull PsiModifierListOwner owner, @Nullable String annotationFQN) { if (owner instanceof PsiMethod && PsiUtil.canBeOverriden((PsiMethod)owner)) { return true; } if (ORG_JETBRAINS_ANNOTATIONS_CONTRACT.equals(annotationFQN) && HardcodedContracts.hasHardcodedContracts(owner)) { return true; } if (AnnotationUtil.NOT_NULL.equals(annotationFQN) && owner instanceof PsiParameter && owner.getParent() != null) { if (AnnotationUtil.isAnnotated(owner, NullableNotNullManager.getInstance(owner.getProject()).getNullables(), false, false)) { return true; } if (HardcodedContracts.hasHardcodedContracts(owner)) { return true; } } return false; }
@Override public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { final PsiElement element = PsiUtilBase.getElementAtCaret(editor); final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (psiClass == null) return; final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); String annotation = ""; if (PsiUtil.getLanguageLevel(file).isAtLeast(LanguageLevel.JDK_1_5)) { annotation = "@SuppressWarnings({\"MethodOverridesStaticMethodOfSuperclass\", \"UnusedDeclaration\"})"; } final PsiMethod createUI = factory.createMethodFromText(annotation + "\npublic static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent c) {" + "\n return new " + psiClass.getName() + "();\n}", psiClass); final PsiMethod newMethod = (PsiMethod)psiClass.add(CodeStyleManager.getInstance(project).reformat(createUI)); JavaCodeStyleManager.getInstance(project).shortenClassReferences(newMethod); final PsiReturnStatement returnStatement = PsiTreeUtil.findChildOfType(newMethod, PsiReturnStatement.class); if (returnStatement != null) { final int offset = returnStatement.getTextRange().getEndOffset(); editor.getCaretModel().moveToOffset(offset - 2); } }
@Contract("_, null -> null") public static PsiMethod setVisibility(PsiMember member, PsiMethod prototype) { if (prototype == null) return null; String visibility = CodeStyleSettingsManager.getSettings(member.getProject()).VISIBILITY; @PsiModifier.ModifierConstant String newVisibility; if (VisibilityUtil.ESCALATE_VISIBILITY.equals(visibility)) { PsiClass aClass = member instanceof PsiClass ? (PsiClass)member : member.getContainingClass(); newVisibility = PsiUtil.getMaximumModifierForMember(aClass, false); } else { //noinspection MagicConstant newVisibility = visibility; } VisibilityUtil.setVisibility(prototype.getModifierList(), newVisibility); return prototype; }
public boolean satisfiedBy(@NotNull PsiElement element) { if (!(element instanceof PsiParameterList)) { return false; } if (!PsiUtil.isLanguageLevel5OrHigher(element)) { return false; } final PsiParameterList parameterList = (PsiParameterList)element; if (!(element.getParent() instanceof PsiMethod)) { return false; } if (parameterList.getParametersCount() == 0) { return false; } final PsiParameter[] parameters = parameterList.getParameters(); final PsiParameter lastParameter = parameters[parameters.length - 1]; if (lastParameter.isVarArgs()) { return false; } final PsiType type = lastParameter.getType(); return type instanceof PsiArrayType; }
@Override public boolean execute(@NotNull final ReferencesSearch.SearchParameters p, @NotNull final Processor<PsiReference> consumer) { final PsiElement refElement = p.getElementToSearch(); boolean isAnnotation = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { @Override public Boolean compute() { return PsiUtil.isAnnotationMethod(refElement); } }); if (isAnnotation) { final PsiMethod method = (PsiMethod)refElement; PsiClass containingClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() { @Override public PsiClass compute() { boolean isValueMethod = PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(method.getName()) && method.getParameterList().getParametersCount() == 0; return isValueMethod ? method.getContainingClass() : null; } }); if (containingClass != null) { SearchScope scope = ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() { @Override public SearchScope compute() { return p.getEffectiveSearchScope(); } }); final Query<PsiReference> query = ReferencesSearch.search(containingClass, scope, p.isIgnoreAccessScope()); return query.forEach(createImplicitDefaultAnnotationMethodConsumer(consumer)); } } return true; }
private boolean canInlineParmOrThisVariable(PsiLocalVariable variable) { boolean isAccessedForWriting = false; for (PsiReference ref : ReferencesSearch.search(variable)) { PsiElement refElement = ref.getElement(); if (refElement instanceof PsiExpression) { if (PsiUtil.isAccessedForWriting((PsiExpression)refElement)) { isAccessedForWriting = true; } } } PsiExpression initializer = variable.getInitializer(); boolean shouldBeFinal = variable.hasModifierProperty(PsiModifier.FINAL) && false; return canInlineParmOrThisVariable(initializer, shouldBeFinal, false, ReferencesSearch.search(variable).findAll().size(), isAccessedForWriting); }
@Override public void visitBinaryExpression(GrBinaryExpression expression) { super.visitBinaryExpression(expression); if (expression.getOperationTokenType() != GroovyTokenTypes.kIN) return; GrExpression leftOperand = expression.getLeftOperand(); GrExpression rightOperand = expression.getRightOperand(); if (rightOperand == null) return; PsiType ltype = leftOperand.getType(); PsiType rtype = rightOperand.getType(); if (ltype == null || rtype == null) return; PsiType component; if (rtype instanceof PsiArrayType) { component = ((PsiArrayType)rtype).getComponentType(); } else if (InheritanceUtil.isInheritor(rtype, CommonClassNames.JAVA_UTIL_COLLECTION)) { component = PsiUtil.substituteTypeParameter(rtype, CommonClassNames.JAVA_UTIL_COLLECTION, 0, false); } else { checkSimpleClasses(ltype, rtype, expression); return; } if (component == null) return; if (TypesUtil.isAssignableWithoutConversions(component, ltype, expression)) return; registerError(expression, ltype, rtype); }
public boolean processChangeMethodSignature(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException { if (!(usage.getElement() instanceof PsiMethod) || !isJavaUsage(usage)) return true; PsiMethod method = (PsiMethod)usage.getElement(); final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(data.getParameterName(), method.getBody()); final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(method); PsiElementFactory factory = JavaPsiFacade.getInstance(data.getProject()).getElementFactory(); PsiParameter parameter = factory.createParameter(data.getParameterName(), data.getForcedType()); PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, data.isDeclareFinal()); final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); data.getParametersToRemove().forEachDescending(new TIntProcedure() { public boolean execute(final int paramNum) { try { PsiParameter param = parameters[paramNum]; PsiDocTag tag = javaDocHelper.getTagForParameter(param); if (tag != null) { tag.delete(); } param.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } return true; } }); final PsiParameter anchorParameter = getAnchorParameter(method); parameter = (PsiParameter)parameterList.addAfter(parameter, anchorParameter); JavaCodeStyleManager.getInstance(data.getProject()).shortenClassReferences(parameter); final PsiDocTag tagForAnchorParameter = javaDocHelper.getTagForParameter(anchorParameter); javaDocHelper.addParameterAfter(data.getParameterName(), tagForAnchorParameter); fieldConflictsResolver.fix(); return false; }
public MethodResolverProcessor(PsiClass classConstr, @NotNull PsiExpressionList argumentList, @NotNull PsiElement place, @NotNull PsiFile placeFile) { super(place, placeFile, new PsiConflictResolver[]{new JavaMethodsConflictResolver(argumentList, PsiUtil.getLanguageLevel(placeFile))}, new SmartList<CandidateInfo>()); setIsConstructor(true); setAccessClass(classConstr); setArgumentList(argumentList); }
public static void processTypeDeclarations(PsiType type, PsiElement place, PsiScopeProcessor processor) { if (type instanceof PsiArrayType) { LanguageLevel languageLevel = PsiUtil.getLanguageLevel(place); final PsiClass arrayClass = JavaPsiFacade.getInstance(place.getProject()).getElementFactory().getArrayClass(languageLevel); final PsiTypeParameter[] arrayTypeParameters = arrayClass.getTypeParameters(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; if (arrayTypeParameters.length > 0) { substitutor = substitutor.put(arrayTypeParameters[0], ((PsiArrayType)type).getComponentType()); } arrayClass.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, substitutor), arrayClass, place); } else if (type instanceof PsiIntersectionType) { for (PsiType psiType : ((PsiIntersectionType)type).getConjuncts()) { processTypeDeclarations(psiType, place, processor); } } else if (type instanceof PsiDisjunctionType) { final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound(); processTypeDeclarations(lub, place, processor); } else { final JavaResolveResult result = PsiUtil.resolveGenericsClassInType(type); final PsiClass clazz = (PsiClass)result.getElement(); if (clazz != null) { clazz.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, result.getSubstitutor()), clazz, place); } } }
@Override public PsiClass moveClass(@NotNull PsiClass aClass, @NotNull PsiClass targetClass) { if (!(aClass instanceof GrTypeDefinition)) return null; GroovyChangeContextUtil.encodeContextInfo(aClass); PsiDocComment doc = aClass.getDocComment(); PsiElement brace = targetClass.getRBrace(); PsiClass newClass = (PsiClass)targetClass.addBefore(aClass, brace); PsiElement sibling = newClass.getPrevSibling(); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(targetClass.getProject()); if (!org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isNewLine(sibling)) { targetClass.addBefore(factory.createLineTerminator("\n "), newClass); } else if (doc != null) { LOG.assertTrue(sibling != null); sibling.replace(factory.createLineTerminator(sibling.getText() + " ")); } if (doc != null) { targetClass.addBefore(doc, newClass); targetClass.addBefore(factory.createLineTerminator("\n"), newClass); } if (targetClass.isInterface()) { PsiUtil.setModifierProperty(newClass, PsiModifier.PUBLIC, true); } else { PsiUtil.setModifierProperty(newClass, PsiModifier.STATIC, true); } GroovyChangeContextUtil.decodeContextInfo(newClass, null, null); return newClass; }
@Override public boolean isAvailable() { PsiExpression expression = getSubExpression(); return super.isAvailable() && expression != null && expression.isValid() && expression.getManager().isInProject(expression) && !PsiUtil.isAccessedForWriting(expression); }
@Nullable private LocalQuickFix[] createNPEFixes(PsiExpression qualifier, PsiExpression expression, boolean onTheFly) { if (qualifier == null || expression == null) return null; if (qualifier instanceof PsiMethodCallExpression) return null; try { final List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>(); if (isVolatileFieldReference(qualifier)) { ContainerUtil.addIfNotNull(fixes, createIntroduceVariableFix(qualifier)); } else if (!(qualifier instanceof PsiLiteralExpression && ((PsiLiteralExpression)qualifier).getValue() == null)) { if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) { final Project project = qualifier.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiBinaryExpression binary = (PsiBinaryExpression)elementFactory.createExpressionFromText("a != null", null); binary.getLOperand().replace(qualifier); ContainerUtil.addIfNotNull(fixes, createAssertFix(binary, expression)); } addSurroundWithIfFix(qualifier, fixes, onTheFly); if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) { fixes.add(new ReplaceWithTernaryOperatorFix(qualifier)); } } ContainerUtil.addIfNotNull(fixes, DfaOptionalSupport.registerReplaceOptionalOfWithOfNullableFix(qualifier)); return fixes.isEmpty() ? null : fixes.toArray(new LocalQuickFix[fixes.size()]); } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
private static boolean isEqualsConstant(PsiExpression expression, PsiVariable variable) { if (!(expression instanceof PsiMethodCallExpression)) { return false; } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final String methodName = methodExpression.getReferenceName(); if (!HardcodedMethodConstants.EQUALS.equals(methodName) && !HardcodedMethodConstants.EQUALS_IGNORE_CASE.equals(methodName)) { return false; } final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (!(qualifier instanceof PsiReferenceExpression)) { return false; } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifier; final PsiElement target = referenceExpression.resolve(); if (!variable.equals(target)) { return false; } final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return false; } final PsiExpression argument = arguments[0]; return PsiUtil.isConstantExpression(argument); }
private static String toPrimitive(String replaceByArg, PsiType from, PsiElement context) { return PsiUtil.isLanguageLevel5OrHigher(context) ? replaceByArg : from instanceof PsiPrimitiveType ? "((" + ((PsiPrimitiveType)from).getBoxedTypeName() + ")" + replaceByArg + ")." + from.getCanonicalText() + "Value()" : "((" + from.getCanonicalText() + ")" + replaceByArg + ")"; }
@NotNull public static Set<PsiType> calculateExceptionsThrown(@Nullable PsiElement element, @NotNull Set<PsiType> out) { if (element == null) return out; if (element instanceof PsiResourceList) { final PsiResourceList resourceList = (PsiResourceList)element; for (PsiResourceListElement resource : resourceList) { final PsiMethod method = PsiUtil.getResourceCloserMethod(resource); collectExceptionsThrown(method, out); } } final ExceptionsThrownVisitor visitor = new ExceptionsThrownVisitor(out); element.accept(visitor); return out; }
@Override public boolean isMemberEnabled(MemberInfo member) { if(myTargetClass != null && myTargetClass.isInterface() && !PsiUtil.isLanguageLevel8OrHigher(myTargetClass)) { return !(member.getMember() instanceof PsiMethod); } return super.isMemberEnabled(member); }