@Nullable public DfaVariableState withInstanceofValue(DfaTypeValue dfaType) { if (dfaType.getDfaType().getPsiType() instanceof PsiPrimitiveType) return this; if (checkInstanceofValue(dfaType.getDfaType())) { DfaVariableState result = dfaType.isNullable() ? withNullability(Nullness.NULLABLE) : this; List<DfaPsiType> moreGeneric = ContainerUtil.newArrayList(); for (DfaPsiType alreadyInstanceof : myInstanceofValues) { if (dfaType.getDfaType().isAssignableFrom(alreadyInstanceof)) { return result; } if (alreadyInstanceof.isAssignableFrom(dfaType.getDfaType())) { moreGeneric.add(alreadyInstanceof); } } HashSet<DfaPsiType> newInstanceof = ContainerUtil.newHashSet(myInstanceofValues); newInstanceof.removeAll(moreGeneric); newInstanceof.add(dfaType.getDfaType()); result = createCopy(newInstanceof, myNotInstanceofValues, result.myNullability); return result; } return null; }
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 visitArrayInitializerExpression( PsiArrayInitializerExpression expression) { super.visitArrayInitializerExpression(expression); final PsiType type = expression.getType(); if (type == null) { return; } final PsiType componentType = type.getDeepComponentType(); if (!(componentType instanceof PsiPrimitiveType)) { return; } final int numElements = calculateNumElements(expression); if (numElements <= m_limit) { return; } registerError(expression, Integer.valueOf(numElements)); }
@NotNull public static String getTypeString(@NotNull ExtractMethodInfoHelper helper, boolean forPresentation, @NotNull String modifier) { if (!helper.specifyType()) { return modifier.isEmpty() ? "def " : ""; } PsiType type = helper.getOutputType(); final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(type); if (unboxed != null) type = unboxed; final String returnType = StringUtil.notNullize(forPresentation ? type.getPresentableText() : type.getCanonicalText()); if (StringUtil.isEmptyOrSpaces(returnType) || "null".equals(returnType)) { return modifier.isEmpty() ? "def " : ""; } else { return returnType + " "; } }
/** * Returns false if <code>type</code> is a multiple levels of collections or arrays. Returns true * otherwise. * * @param type The PsiType been validated. * @param project The project that has the PsiElement associated with <code>type</code>. */ public boolean isValidArrayOrPrimitiveType(PsiType type, Project project) { if (type instanceof PsiArrayType) { PsiArrayType arrayType = (PsiArrayType) type; if (arrayType.getComponentType() instanceof PsiPrimitiveType) { return true; } else { return isValidInnerArrayType(arrayType.getComponentType(), project); } } // Check if type is a Collection PsiClassType collectionType = JavaPsiFacade.getElementFactory(project).createTypeByFQClassName("java.util.Collection"); if (collectionType.isAssignableFrom(type)) { assert (type instanceof PsiClassType); PsiClassType classType = (PsiClassType) type; PsiType[] typeParams = classType.getParameters(); assert (typeParams.length > 0); return isValidInnerArrayType(typeParams[0], project); } return true; }
public void annotate(final PsiElement element, final AnnotationHolder holder) { if (!VtlReferenceContributor.VTLVARIABLE_COMMENT.accepts(element)) { return; } final String text = element.getText(); final String[] nameAndType = VtlFile.findVariableNameAndTypeAndScopeFilePath(text); if (nameAndType == null) { return; } final VtlImplicitVariable variable = ((VtlFile) element.getContainingFile()).findImplicitVariable(nameAndType[0]); if (variable == null || variable.getPsiType() instanceof PsiPrimitiveType) { return; } for (PsiReference javaRef : VtlReferenceContributor.getReferencesToJavaTypes(element)) { if(javaRef.resolve() == null) { TextRange range = javaRef.getRangeInElement().shiftRight(element.getTextRange().getStartOffset()); holder.createErrorAnnotation(range, VelocityBundle.message("invalid.java.type")); } } }
@NotNull private static List<StandardMethodContract> postProcessContracts(@NotNull PsiMethodImpl method, MethodData data, List<PreContract> rawContracts) { List<StandardMethodContract> contracts = ContainerUtil.concat(rawContracts, c -> c.toContracts(method, data.methodBody(method))); if(contracts.isEmpty()) { return Collections.emptyList(); } final PsiType returnType = method.getReturnType(); if(returnType != null && !(returnType instanceof PsiPrimitiveType)) { contracts = boxReturnValues(contracts); } List<StandardMethodContract> compatible = ContainerUtil.filter(contracts, contract -> isContractCompatibleWithMethod(method, returnType, contract)); if(compatible.size() > MAX_CONTRACT_COUNT) { LOG.debug("Too many contracts for " + PsiUtil.getMemberQualifiedName(method) + ", shrinking the list"); return compatible.subList(0, MAX_CONTRACT_COUNT); } return compatible; }
public static Nullness inferNullity(PsiMethodImpl method) { if(!InferenceFromSourceUtil.shouldInferFromSource(method)) { return Nullness.UNKNOWN; } PsiType type = method.getReturnType(); if(type == null || type instanceof PsiPrimitiveType) { return Nullness.UNKNOWN; } return CachedValuesManager.getCachedValue(method, () -> { MethodData data = ContractInferenceIndexKt.getIndexedData(method); NullityInferenceResult result = data == null ? null : data.getNullity(); Nullness nullness = result == null ? null : RecursionManager.doPreventingRecursion(method, true, () -> result.getNullness(method, data.methodBody(method))); if(nullness == null) { nullness = Nullness.UNKNOWN; } return CachedValueProvider.Result.create(nullness, method, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT); }); }
static boolean isReturnTypeCompatible(@Nullable PsiType returnType, @NotNull MethodContract.ValueConstraint returnValue) { if(returnValue == MethodContract.ValueConstraint.ANY_VALUE || returnValue == MethodContract.ValueConstraint.THROW_EXCEPTION) { return true; } if(PsiType.VOID.equals(returnType)) { return false; } if(PsiType.BOOLEAN.equals(returnType)) { return returnValue == MethodContract.ValueConstraint.TRUE_VALUE || returnValue == MethodContract.ValueConstraint.FALSE_VALUE; } if(!(returnType instanceof PsiPrimitiveType)) { return returnValue == MethodContract.ValueConstraint.NULL_VALUE || returnValue == MethodContract.ValueConstraint.NOT_NULL_VALUE; } return false; }
@Override public boolean isAvailable(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if(!super.isAvailable(project, file, startElement, endElement)) { return false; } PsiModifierListOwner owner = getContainer(file, startElement.getTextRange().getStartOffset()); if(owner == null || AnnotationUtil.isAnnotated(owner, getAnnotationsToRemove()[0], false, false)) { return false; } if(owner instanceof PsiMethod) { PsiType returnType = ((PsiMethod) owner).getReturnType(); return returnType != null && !(returnType instanceof PsiPrimitiveType); } return true; }
@Nullable private static String getTypeShortName(@NotNull final PsiType type) { if(type instanceof PsiPrimitiveType) { return ((PsiPrimitiveType) type).getBoxedTypeName(); } if(type instanceof PsiClassType) { return ((PsiClassType) type).getClassName(); } if(type instanceof PsiArrayType) { return getTypeShortName(((PsiArrayType) type).getComponentType()) + "[]"; } return null; }
@Override protected int getNextStep(int step) { if(step + 1 == getNonNullStepCode()) { if(templateDependsOnFieldsNullability()) { for(MemberInfo classField : myClassFields) { if(classField.isChecked()) { PsiField field = (PsiField) classField.getMember(); if(!(field.getType() instanceof PsiPrimitiveType)) { return getNonNullStepCode(); } } } } return step; } return super.getNextStep(step); }
public static boolean isSubtypeable(PsiExpression expr) { final PsiType type = expr.getType(); if(type instanceof PsiPrimitiveType) { return false; } if(type instanceof PsiClassType) { final PsiClass psiClass = ((PsiClassType) type).resolve(); if(psiClass != null && psiClass.hasModifierProperty(PsiModifier.FINAL)) { return false; } } return true; }
private String getValueForType( PsiType type ) { if( type instanceof PsiPrimitiveType ) { if( type.getCanonicalText().equals( "boolean" ) ) { return "false"; } return "0"; } return "null"; }
@Override public void renderElement(LookupElementPresentation presentation) { final PsiClass psiClass = getPsiClass(); if (psiClass != null) { presentation.setIcon(presentation.isReal() ? psiClass.getIcon(Iconable.ICON_FLAG_VISIBILITY) : EMPTY_ICON); presentation.setTailText(" (" + PsiFormatUtil.getPackageDisplayName(psiClass) + ")", true); } final PsiType type = getPsiType(); presentation.setItemText(type.getPresentableText()); presentation.setItemTextBold(type instanceof PsiPrimitiveType); }
@Override public boolean checkNotNullable(DfaValue value) { if (value == myFactory.getConstFactory().getNull()) return false; if (value instanceof DfaTypeValue && ((DfaTypeValue)value).isNullable()) return false; if (value instanceof DfaVariableValue) { DfaVariableValue varValue = (DfaVariableValue)value; if (varValue.getVariableType() instanceof PsiPrimitiveType) return true; if (isNotNull(varValue)) return true; if (getVariableState(varValue).isNullable()) return false; } return true; }
public NullSmartCompletionContributor() { extend(CompletionType.SMART, and(JavaSmartCompletionContributor.INSIDE_EXPRESSION, not(psiElement().afterLeaf("."))), new ExpectedTypeBasedCompletionProvider() { @Override protected void addCompletions(final CompletionParameters parameters, final CompletionResultSet result, final Collection<ExpectedTypeInfo> infos) { if (!StringUtil.startsWithChar(result.getPrefixMatcher().getPrefix(), 'n')) { return; } LinkedHashSet<CompletionResult> results = result.runRemainingContributors(parameters, true); for (CompletionResult completionResult : results) { if (completionResult.isStartMatch()) { return; } } for (final ExpectedTypeInfo info : infos) { if (!(info.getType() instanceof PsiPrimitiveType)) { final LookupElement item = BasicExpressionCompletionContributor.createKeywordLookupItem(parameters.getPosition(), PsiKeyword.NULL); result.addElement(JavaSmartCompletionContributor.decorate(item, infos)); return; } } } }); }
public void testForcedFieldType() throws Exception { configureByFile("/refactoring/introduceField/beforeForcedFieldType.java"); new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false){ @Override protected PsiType getFieldType(PsiType type) { return PsiPrimitiveType.INT; } }.invoke(getProject(), myEditor, myFile, null); checkResultByFile("/refactoring/introduceField/afterForcedFieldType.java"); }
private static void fillPrimitivesNames(final PsiPrimitiveType type) { PRIMITIVES_NAMES.add(type.getBoxedTypeName()); PRIMITIVES_NAMES.add(type.getCanonicalText()); PRIMITIVES_SHORT_NAMES.add(StringUtilRt.getShortName(type.getBoxedTypeName())); PRIMITIVES_SHORT_NAMES.add(type.getCanonicalText()); }
public GrReplacePrimitiveTypeWithWrapperFix(GrTypeElement typeElement) { LOG.assertTrue(typeElement.isValid()); final PsiType type = typeElement.getType(); LOG.assertTrue(type instanceof PsiPrimitiveType); myBoxedName = ((PsiPrimitiveType)type).getBoxedType(typeElement).getClassName(); }
@Override public final PsiType getVariableType(GrVariable variable) { if (!(variable instanceof GrParameter)) { return null; } GrClosableBlock closure; int paramIndex; if (variable instanceof ClosureSyntheticParameter) { closure = ((ClosureSyntheticParameter)variable).getClosure(); paramIndex = 0; } else { PsiElement eParameterList = variable.getParent(); if (!(eParameterList instanceof GrParameterList)) return null; PsiElement eClosure = eParameterList.getParent(); if (!(eClosure instanceof GrClosableBlock)) return null; closure = (GrClosableBlock)eClosure; GrParameterList parameterList = (GrParameterList)eParameterList; paramIndex = parameterList.getParameterNumber((GrParameter)variable); } PsiType res = getClosureParameterType(closure, paramIndex); if (res instanceof PsiPrimitiveType) { return ((PsiPrimitiveType)res).getBoxedType(closure); } return res; }
public static GrMethod createMethod(ExtractMethodInfoHelper helper) { StringBuilder buffer = new StringBuilder(); //Add signature PsiType type = helper.getOutputType(); final PsiPrimitiveType outUnboxed = PsiPrimitiveType.getUnboxedType(type); if (outUnboxed != null) type = outUnboxed; String modifier = getModifierString(helper); String typeText = getTypeString(helper, false, modifier); buffer.append(modifier); buffer.append(typeText); appendName(buffer, helper.getName()); buffer.append("("); for (String param : getParameterString(helper, true)) { buffer.append(param); } buffer.append(") { \n"); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(helper.getProject()); generateBody(helper, type == PsiType.VOID, buffer, helper.isForceReturn()); buffer.append("\n}"); String methodText = buffer.toString(); return factory.createMethodFromText(methodText, helper.getContext()); }
public NullSmartCompletionContributor() { extend(CompletionType.SMART, and(JavaSmartCompletionContributor.INSIDE_EXPRESSION, not(psiElement().afterLeaf("."))), new ExpectedTypeBasedCompletionProvider() { @Override protected void addCompletions(final CompletionParameters parameters, final CompletionResultSet result, final Collection<ExpectedTypeInfo> infos) { if (!StringUtil.startsWithChar(result.getPrefixMatcher().getPrefix(), 'n')) { return; } LinkedHashSet<CompletionResult> results = result.runRemainingContributors(parameters, true); for (CompletionResult completionResult : results) { if (completionResult.isStartMatch()) { return; } } for (final ExpectedTypeInfo info : infos) { if (!(info.getType() instanceof PsiPrimitiveType)) { final LookupItem item = (LookupItem)BasicExpressionCompletionContributor.createKeywordLookupItem(parameters.getPosition(), PsiKeyword.NULL); item.setAttribute(LookupItem.TYPE, PsiType.NULL); result.addElement(JavaSmartCompletionContributor.decorate(item, infos)); return; } } } }); }
@Nullable public static PsiMethod getMethodWithMinNotPrimitiveParameters(final @NotNull PsiMethod[] methods, final Set<String> excludedParamsQNames) { PsiMethod minMethod = null; int minParametersCount = Integer.MAX_VALUE; for (final PsiMethod method : methods) { final PsiParameterList parameterList = method.getParameterList(); boolean doContinue = false; int parametersCount = parameterList.getParametersCount(); for (final PsiParameter p : parameterList.getParameters()) { if (!(p.getType() instanceof PsiPrimitiveType)) { if (excludedParamsQNames.contains(p.getType().getCanonicalText())) { doContinue = true; break; } parametersCount++; } } if (doContinue) { continue; } if (parametersCount < minParametersCount) { if (parametersCount == 0) { return method; } minParametersCount = parametersCount; minMethod = method; } } return minMethod; }
public static GrMethod createMethod(ExtractMethodInfoHelper helper) { StringBuilder buffer = new StringBuilder(); //Add signature PsiType type = helper.getOutputType(); final PsiPrimitiveType outUnboxed = PsiPrimitiveType.getUnboxedType(type); if (outUnboxed != null) type = outUnboxed; String modifier = getModifierString(helper); String typeText = getTypeString(helper, false, modifier); buffer.append(modifier); buffer.append(typeText); appendName(buffer, helper.getName()); buffer.append("("); for (String param : getParameterString(helper, true)) { buffer.append(param); } buffer.append(") { \n"); GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(helper.getProject()); generateBody(helper, type == PsiType.VOID, buffer, helper.isForceReturn()); buffer.append("\n}"); String methodText = buffer.toString(); GrMethod method = factory.createMethodFromText(methodText); LOG.assertTrue(method != null); return method; }
@NotNull public static String getReturnValueOfType(@Nullable PsiType type) { if (type instanceof PsiPrimitiveType) { if (PsiType.BOOLEAN.equals(type)) { return PsiKeyword.FALSE; } else { return "0"; } } else if (PsiType.VOID.equals(type)) { return ""; } else { return PsiKeyword.NULL; } }
@Override public boolean checkNotNullable(DfaValue value) { if(value == myFactory.getConstFactory().getNull()) { return false; } if(value instanceof DfaTypeValue && ((DfaTypeValue) value).isNullable()) { return false; } if(value instanceof DfaVariableValue) { DfaVariableValue varValue = (DfaVariableValue) value; if(varValue.getVariableType() instanceof PsiPrimitiveType) { return true; } if(isNotNull(varValue)) { return true; } if(getVariableState(varValue).getNullability() == Nullness.NULLABLE) { return false; } } return true; }
@NotNull static PsiParameter[] checkMethodParameters(PsiMethod method) { if(method.getBody() == null) { return PsiParameter.EMPTY_ARRAY; } final Collection<PsiParameter> nullableParameters = new SmartList<>(); final PsiParameter[] parameters = method.getParameterList().getParameters(); for(int index = 0; index < parameters.length; index++) { PsiParameter parameter = parameters[index]; if(!(parameter.getType() instanceof PsiPrimitiveType) && !NullableNotNullManager.isNotNull(parameter) && !NullableNotNullManager.isNullable(parameter) && JavaNullMethodArgumentUtil .hasNullArgument(method, index)) { nullableParameters.add(parameter); } } if(nullableParameters.isEmpty()) { return PsiParameter.EMPTY_ARRAY; } final NullParameterConstraintChecker checker = new NullParameterConstraintChecker(nullableParameters); checker.analyzeMethod(method.getBody(), new StandardInstructionVisitor()); return checker.myPossiblyViolatedParameters.stream().filter(checker.myUsedParameters::contains).toArray(PsiParameter[]::new); }
private boolean isNotNullCall(ExpressionRange delegate, PsiCodeBlock body) { PsiMethodCallExpression call = (PsiMethodCallExpression) delegate.restoreExpression(body); if(call.getType() instanceof PsiPrimitiveType) { return true; } PsiMethod target = call.resolveMethod(); return target != null && NullableNotNullManager.isNotNull(target); }
@Nullable DfaVariableState withInstanceofValue(@NotNull DfaTypeValue dfaType) { if(dfaType.getDfaType().getPsiType() instanceof PsiPrimitiveType) { return this; } if(checkInstanceofValue(dfaType.getDfaType())) { DfaVariableState result = dfaType.isNullable() ? withFact(DfaFactType.CAN_BE_NULL, true) : this; List<DfaPsiType> moreGeneric = ContainerUtil.newArrayList(); for(DfaPsiType alreadyInstanceof : myInstanceofValues) { if(dfaType.getDfaType().isAssignableFrom(alreadyInstanceof)) { return result; } if(alreadyInstanceof.isAssignableFrom(dfaType.getDfaType())) { moreGeneric.add(alreadyInstanceof); } } HashSet<DfaPsiType> newInstanceof = ContainerUtil.newHashSet(myInstanceofValues); newInstanceof.removeAll(moreGeneric); newInstanceof.add(dfaType.getDfaType()); result = createCopy(newInstanceof, myNotInstanceofValues, result.myFactMap); return result; } return null; }
@Override void iteration(CFGBuilder builder) { PsiType outType = StreamApiUtil.getStreamElementType(myCall.getType()); PsiPrimitiveType primitiveType = PsiPrimitiveType.getUnboxedType(outType); if(primitiveType != null) { builder.boxUnbox(myCall, primitiveType, outType).assignTo(builder.createTempVariable(outType)); } myNext.iteration(builder); }
/** * Creates a range for given type (for primitives and boxed: values range) * * @param type type to create a range for * @return a range or null if type is not supported */ @Nullable public static LongRangeSet fromType(PsiType type) { if(type == null) { return null; } type = PsiPrimitiveType.getOptionallyUnboxedType(type); if(type != null) { if(type.equals(PsiType.BYTE)) { return Range.BYTE_RANGE; } if(type.equals(PsiType.CHAR)) { return Range.CHAR_RANGE; } if(type.equals(PsiType.SHORT)) { return Range.SHORT_RANGE; } if(type.equals(PsiType.INT)) { return Range.INT_RANGE; } if(type.equals(PsiType.LONG)) { return all(); } } return null; }
@Override public boolean areTypesConvertible(PsiType exprType, PsiType parameterType, final PsiElement context) { if (exprType instanceof PsiClassType && parameterType instanceof PsiPrimitiveType) { parameterType = ((PsiPrimitiveType)parameterType).getBoxedType(context); //unboxing from type of cast expression will take place at runtime if (parameterType == null) return false; } return parameterType.isConvertibleFrom(exprType); }
public NullSmartCompletionContributor() { extend(CompletionType.SMART, and(JavaSmartCompletionContributor.INSIDE_EXPRESSION, not(psiElement().afterLeaf("."))), new ExpectedTypeBasedCompletionProvider() { @Override protected void addCompletions(final CompletionParameters parameters, final CompletionResultSet result, final Collection<ExpectedTypeInfo> infos) { if(!StringUtil.startsWithChar(result.getPrefixMatcher().getPrefix(), 'n')) { return; } LinkedHashSet<CompletionResult> results = result.runRemainingContributors(parameters, true); for(CompletionResult completionResult : results) { if(completionResult.isStartMatch()) { return; } } for(final ExpectedTypeInfo info : infos) { if(!(info.getType() instanceof PsiPrimitiveType)) { final LookupElement item = BasicExpressionCompletionContributor.createKeywordLookupItem(parameters.getPosition(), PsiKeyword.NULL); result.addElement(JavaSmartCompletionContributor.decorate(item, infos)); return; } } } }); }