diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 6e0c412215d..8f6f1eee176 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,7 +1,7 @@ // For format details, see https://aka.ms/vscode-remote/devcontainer.json or this file's README at: { "name": "F#", - "image": "mcr.microsoft.com/dotnet/sdk:9.0.102", + "image": "mcr.microsoft.com/dotnet/sdk:9.0.200", "features": { "ghcr.io/devcontainers/features/common-utils:2.5.2": {}, "ghcr.io/devcontainers/features/git:1.3.2": {}, diff --git a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md index da9198c332c..1c78cff8fe9 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md +++ b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md @@ -11,6 +11,7 @@ * Cancellable: set token in more places ([PR #18283](https://github.com/dotnet/fsharp/pull/18283)) * Cancellable: fix leaking cancellation token ([PR #18295](https://github.com/dotnet/fsharp/pull/18295)) * Fix NRE when accessing nullable fields of types within their equals/hash/compare methods ([PR #18296](https://github.com/dotnet/fsharp/pull/18296)) +* Fix nullness warning for overrides of generic code with nullable type instance ([Issue #17988](https://github.com/dotnet/fsharp/issues/17988), [PR #18337](https://github.com/dotnet/fsharp/pull/18337)) ### Added * Added missing type constraints in FCS. ([PR #18241](https://github.com/dotnet/fsharp/pull/18241)) @@ -26,6 +27,8 @@ * Update `Obsolete` attribute checking to account for `DiagnosticId` and `UrlFormat` properties. ([PR #18224](https://github.com/dotnet/fsharp/pull/18224)) * Remove `Cancellable.UsingToken` from tests ([PR #18276](https://github.com/dotnet/fsharp/pull/18276)) * Added nullability annotations to `.Using` builder method for `async`, `task` and compiler-internal builders ([PR #18292](https://github.com/dotnet/fsharp/pull/18292)) +* Warn when `unit` is passed to an `obj`-typed argument ([PR #18330](https://github.com/dotnet/fsharp/pull/18330)) +* Warning for "useless null handling" works with piped syntax constructs now ([PR #18331](https://github.com/dotnet/fsharp/pull/18331)) ### Breaking Changes * Struct unions with overlapping fields now generate mappings needed for reading via reflection ([Issue #18121](https://github.com/dotnet/fsharp/issues/17797), [PR #18274](https://github.com/dotnet/fsharp/pull/17877)) diff --git a/docs/release-notes/.FSharp.Core/9.0.101.md b/docs/release-notes/.FSharp.Core/9.0.101.md new file mode 100644 index 00000000000..a130c5fa8cc --- /dev/null +++ b/docs/release-notes/.FSharp.Core/9.0.101.md @@ -0,0 +1,17 @@ +## FSharp.Core 9.0.101 did not change compared to version 9.0.100. Below are the changes for FSharp.Core 9.0.100 + +### Fixed +* Struct UnionCase doesn't seem to be a valid target for the DefaultAugmentationAttribute ([Issue #17499](https://github.com/dotnet/fsharp/issues/17499), [PR #17502](https://github.com/dotnet/fsharp/pull/17502)) + +### Added + +* Enable C# collection expression support for F# lists & sets. ([Language suggestion #1355](https://github.com/fsharp/fslang-suggestions/issues/1355), [RFC FS-1145 (PR#776)](https://github.com/fsharp/fslang-design/pull/776), [PR #17359](https://github.com/dotnet/fsharp/pull/17359)) +* Add module functions for converting between `'T option` and `'T voption`. ([PR #17436](https://github.com/dotnet/fsharp/pull/17436)) + +### Changed +* Change compiler default setting realsig+ when building assemblies ([Issue #17384](https://github.com/dotnet/fsharp/issues/17384), [PR #17378](https://github.com/dotnet/fsharp/pull/17385)) +* Change compiler default setting for compressedMetadata ([Issue #17379](https://github.com/dotnet/fsharp/issues/17379), [PR #17383](https://github.com/dotnet/fsharp/pull/17383)) +* Enable FSharp 9.0 Language Version ([Issue #17497](https://github.com/dotnet/fsharp/issues/17438)), [PR](https://github.com/dotnet/fsharp/pull/17500))) +* Struct UnionCase doesn't seem to be a valid target for the DefaultAugmentationAttribute ([Issue #17499](https://github.com/dotnet/fsharp/issues/17499), [PR #17502](https://github.com/dotnet/fsharp/pull/17502)) +### Breaking Changes + diff --git a/docs/release-notes/.Language/preview.md b/docs/release-notes/.Language/preview.md index d6ef41c3d57..905e086a163 100644 --- a/docs/release-notes/.Language/preview.md +++ b/docs/release-notes/.Language/preview.md @@ -4,6 +4,7 @@ * Deprecate places where `seq` can be omitted. ([Language suggestion #1033](https://github.com/fsharp/fslang-suggestions/issues/1033), [PR #17772](https://github.com/dotnet/fsharp/pull/17772)) * Added type conversions cache, only enabled for compiler runs ([PR#17668](https://github.com/dotnet/fsharp/pull/17668)) * Support ValueOption + Struct attribute as optional parameter for methods ([Language suggestion #1136](https://github.com/fsharp/fslang-suggestions/issues/1136), [PR #18098](https://github.com/dotnet/fsharp/pull/18098)) +* Warn when `unit` is passed to an `obj`-typed argument ([PR #18330](https://github.com/dotnet/fsharp/pull/18330)) ### Fixed diff --git a/eng/Versions.props b/eng/Versions.props index ce0f5f5ac23..bacdd4e3233 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -37,7 +37,7 @@ $(FSMajorVersion).$(FSMinorVersion).$(FSBuildVersion) - 9.0.101 + 9.0.201 $(FSCorePackageVersionValue)-$(PreReleaseVersionLabel).* diff --git a/global.json b/global.json index 34fb2765a67..598d8b7367b 100644 --- a/global.json +++ b/global.json @@ -1,10 +1,10 @@ { "sdk": { - "version": "9.0.103", + "version": "9.0.200", "allowPrerelease": true }, "tools": { - "dotnet": "9.0.103", + "dotnet": "9.0.200", "vs": { "version": "17.8", "components": [ diff --git a/src/Compiler/Checking/ConstraintSolver.fs b/src/Compiler/Checking/ConstraintSolver.fs index 2578107176d..a45bb37234f 100644 --- a/src/Compiler/Checking/ConstraintSolver.fs +++ b/src/Compiler/Checking/ConstraintSolver.fs @@ -3177,6 +3177,7 @@ and ArgsMustSubsumeOrConvert trackErrors { let g = csenv.g let m = callerArg.Range + let callerTy = callerArg.CallerArgumentType let calledArgTy, usesTDC, eqn = AdjustCalledArgType csenv.InfoReader ad isConstraint enforceNullableOptionalsKnownTypes calledArg callerArg match eqn with @@ -3188,8 +3189,10 @@ and ArgsMustSubsumeOrConvert match usesTDC with | TypeDirectedConversionUsed.Yes(warn, _, _) -> do! WarnD(warn csenv.DisplayEnv) | TypeDirectedConversionUsed.No -> () - do! SolveTypeSubsumesTypeWithReport csenv ndeep m trace cxsln (Some calledArg.CalledArgumentType) calledArgTy callerArg.CallerArgumentType - if calledArg.IsParamArray && isArray1DTy g calledArgTy && not (isArray1DTy g callerArg.CallerArgumentType) then + do! SolveTypeSubsumesTypeWithReport csenv ndeep m trace cxsln (Some calledArg.CalledArgumentType) calledArgTy callerTy + if g.langVersion.SupportsFeature(LanguageFeature.WarnWhenUnitPassedToObjArg) && isUnitTy g callerTy && isObjTyAnyNullness g calledArgTy then + do! WarnD(Error(FSComp.SR.tcUnitToObjSubsumption(), m)) + if calledArg.IsParamArray && isArray1DTy g calledArgTy && not (isArray1DTy g callerTy) then return! ErrorD(Error(FSComp.SR.csMethodExpectsParams(), m)) else return usesTDC diff --git a/src/Compiler/Checking/Expressions/CheckExpressions.fs b/src/Compiler/Checking/Expressions/CheckExpressions.fs index df64c4da62e..ee465013b6b 100644 --- a/src/Compiler/Checking/Expressions/CheckExpressions.fs +++ b/src/Compiler/Checking/Expressions/CheckExpressions.fs @@ -1890,7 +1890,11 @@ let FreshenAbstractSlot g amap m synTyparDecls absMethInfo = // Work out the required type of the member let argTysFromAbsSlot = argTys |> List.mapSquared (instType typarInstFromAbsSlot) - let retTyFromAbsSlot = retTy |> GetFSharpViewOfReturnType g |> instType typarInstFromAbsSlot + + let retTyFromAbsSlot = + retTy + |> GetFSharpViewOfReturnType g + |> instType typarInstFromAbsSlot typarsFromAbsSlotAreRigid, typarsFromAbsSlot, argTysFromAbsSlot, retTyFromAbsSlot let CheckRecdExprDuplicateFields (elems: Ident list) = @@ -8568,29 +8572,21 @@ and TcApplicationThen (cenv: cenv) (overallTy: OverallTy) env tpenv mExprAndArg | _ -> synArg - let (arg, tpenv), cenv = + let (arg, tpenv) = // treat left and right of '||' and '&&' as control flow, so for example // f expr1 && g expr2 // will have debug points on "f expr1" and "g expr2" - let env,cenv = + let env = match leftExpr with | ApplicableExpr(expr=Expr.Val (vref, _, _)) | ApplicableExpr(expr=Expr.App (Expr.Val (vref, _, _), _, _, [_], _)) when valRefEq g vref g.and_vref || valRefEq g vref g.and2_vref || valRefEq g vref g.or_vref - || valRefEq g vref g.or2_vref -> - { env with eIsControlFlow = true },cenv - | ApplicableExpr(expr=Expr.Val (valRef=vref)) - | ApplicableExpr(expr=Expr.App (funcExpr=Expr.Val (valRef=vref))) -> - match TryFindLocalizedFSharpStringAttribute g g.attrib_WarnOnWithoutNullArgumentAttribute vref.Attribs with - | Some _ as msg -> env,{ cenv with css.WarnWhenUsingWithoutNullOnAWithNullTarget = msg} - | None when cenv.css.WarnWhenUsingWithoutNullOnAWithNullTarget <> None -> - env, { cenv with css.WarnWhenUsingWithoutNullOnAWithNullTarget = None} - | None -> env,cenv - | _ -> env,cenv - - TcExprFlex2 cenv domainTy env false tpenv synArg, cenv + || valRefEq g vref g.or2_vref -> { env with eIsControlFlow = true } + | _ -> env + + TcExprFlex2 cenv domainTy env false tpenv synArg let exprAndArg, resultTy = buildApp cenv leftExpr resultTy arg mExprAndArg TcDelayed cenv overallTy env tpenv mExprAndArg exprAndArg resultTy atomicFlag delayed @@ -9289,6 +9285,7 @@ and TcValueItemThen cenv overallTy env vref tpenv mItem afterResolution delayed PropagateThenTcDelayed cenv overallTy env tpenv mExprAndTypeArgs vexpFlex vexpFlex.Type ExprAtomicFlag.Atomic otherDelayed // Value get + | _ -> let _, vExpr, isSpecial, _, _, tpenv = TcVal cenv env tpenv vref None (Some afterResolution) mItem @@ -9297,6 +9294,19 @@ and TcValueItemThen cenv overallTy env vref tpenv mItem afterResolution delayed | Expr.Const (Const.String value, _, _) -> TcConstStringExpr cenv overallTy env mItem tpenv value LiteralArgumentType.StaticField | _ -> vExpr, tpenv + let getCenvForVref cenv (vref:ValRef) = + match TryFindLocalizedFSharpStringAttribute g g.attrib_WarnOnWithoutNullArgumentAttribute vref.Attribs with + | Some _ as msg -> { cenv with css.WarnWhenUsingWithoutNullOnAWithNullTarget = msg} + | None when cenv.css.WarnWhenUsingWithoutNullOnAWithNullTarget <> None -> + // We need to reset the warning back to default once in a nested call, to prevent false warnings e.g. in `Option.ofObj (Path.GetDirectoryName "")` + { cenv with css.WarnWhenUsingWithoutNullOnAWithNullTarget = None} + | None -> cenv + + let cenv = + match vExpr with + | Expr.App (funcExpr=Expr.Val (valRef=vref)) -> getCenvForVref cenv vref + | _ -> cenv + let vexpFlex = if isSpecial then MakeApplicableExprNoFlex cenv vExpr else MakeApplicableExprWithFlex cenv env vExpr PropagateThenTcDelayed cenv overallTy env tpenv mItem vexpFlex vexpFlex.Type ExprAtomicFlag.Atomic delayed @@ -11768,6 +11778,15 @@ and ApplyAbstractSlotInference (cenv: cenv) (envinner: TcEnv) (_: Val option) (a match uniqueAbstractMethSigs with | uniqueAbstractMeth :: _ -> + // Overrides can narrow the retTy from nullable to not-null. + // By changing nullness to be variable we do not get in the way of eliminating nullness (=good). + // We only keep a WithNull nullness if it was part of an explicit type instantiation + let canChangeNullableRetTy = + match g.checkNullness, renaming with + | false, _ -> false + | true, [] -> true + | true, _ -> not(uniqueAbstractMeth.HasGenericRetTy()) + let uniqueAbstractMeth = uniqueAbstractMeth.Instantiate(cenv.amap, m, renaming) let typarsFromAbsSlotAreRigid, typarsFromAbsSlot, argTysFromAbsSlot, retTyFromAbsSlot = @@ -11775,9 +11794,10 @@ and ApplyAbstractSlotInference (cenv: cenv) (envinner: TcEnv) (_: Val option) (a let declaredTypars = (if typarsFromAbsSlotAreRigid then typarsFromAbsSlot else declaredTypars) - // Overrides can narrow the retTy from nullable to not-null. - // By changing nullness to be variable we do not get in the way of eliminating nullness (=good). - let retTyFromAbsSlot = retTyFromAbsSlot |> changeWithNullReqTyToVariable g + let retTyFromAbsSlot = + if canChangeNullableRetTy then + retTyFromAbsSlot |> changeWithNullReqTyToVariable g + else retTyFromAbsSlot let absSlotTy = mkMethodTy g argTysFromAbsSlot retTyFromAbsSlot diff --git a/src/Compiler/Checking/infos.fs b/src/Compiler/Checking/infos.fs index 3fe1ba2f7b1..8dcc5dc8ac1 100644 --- a/src/Compiler/Checking/infos.fs +++ b/src/Compiler/Checking/infos.fs @@ -1430,6 +1430,20 @@ type MethInfo = let (ParamAttribs(isParamArrayArg, isInArg, isOutArg, optArgInfo, callerInfo, reflArgInfo)) = info ParamData(isParamArrayArg, isInArg, isOutArg, optArgInfo, callerInfo, nmOpt, reflArgInfo, pty))) + member x.HasGenericRetTy() = + match x with + | ILMeth(_g, ilminfo, _) -> ilminfo.RawMetadata.Return.Type.IsTypeVar + | FSMeth(g, _, vref, _) -> + let _, _, _, retTy, _ = GetTypeOfMemberInMemberForm g vref + match retTy with + | Some retTy -> isTyparTy g retTy + | None -> false + | MethInfoWithModifiedReturnType(_,retTy) -> false + | DefaultStructCtor _ -> false +#if !NO_TYPEPROVIDERS + | ProvidedMeth(amap, mi, _, m) -> false +#endif + /// Get the ParamData objects for the parameters of a MethInfo member x.HasParamArrayArg(amap, m, minst) = x.GetParamDatas(amap, m, minst) |> List.existsSquared (fun (ParamData(isParamArrayArg, _, _, _, _, _, _, _)) -> isParamArrayArg) diff --git a/src/Compiler/Checking/infos.fsi b/src/Compiler/Checking/infos.fsi index 9ab99a8346b..e091834e271 100644 --- a/src/Compiler/Checking/infos.fsi +++ b/src/Compiler/Checking/infos.fsi @@ -538,6 +538,8 @@ type MethInfo = /// Get the signature of an abstract method slot. member GetSlotSig: amap: ImportMap * m: range -> SlotSig + member HasGenericRetTy: unit -> bool + /// Get the ParamData objects for the parameters of a MethInfo member HasParamArrayArg: amap: ImportMap * m: range * minst: TType list -> bool diff --git a/src/Compiler/FSComp.txt b/src/Compiler/FSComp.txt index ad95dc6556b..eedaecbb9be 100644 --- a/src/Compiler/FSComp.txt +++ b/src/Compiler/FSComp.txt @@ -1683,6 +1683,7 @@ forFormatInvalidForInterpolated4,"Interpolated strings used as type IFormattable 3394,parsNewExprMemberAccess,"This member access is ambiguous. Please use parentheses around the object creation, e.g. '(new SomeType(args)).MemberName'" 3395,tcImplicitConversionUsedForMethodArg,"This expression uses the implicit conversion '%s' to convert type '%s' to type '%s'." 3396,tcLiteralAttributeCannotUseActivePattern,"A [] declaration cannot use an active pattern for its identifier" +3397,tcUnitToObjSubsumption,"This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\"." 3401,ilxgenInvalidConstructInStateMachineDuringCodegen,"The resumable code construct '%s' may only be used in inlined code protected by 'if __useResumableCode then ...' and the overall composition must form valid resumable code." 3402,tcInvalidResumableConstruct,"The construct '%s' may only be used in valid resumable code." 3501,tcResumableCodeFunctionMustBeInline,"Invalid resumable code. Any method of function accepting or returning resumable code must be marked 'inline'" @@ -1794,3 +1795,4 @@ featureDontWarnOnUppercaseIdentifiersInBindingPatterns,"Don't warn on uppercase 3874,tcExpectedTypeParamMarkedWithUnitOfMeasureAttribute,"Expected unit-of-measure type parameter must be marked with the [] attribute." featureDeprecatePlacesWhereSeqCanBeOmitted,"Deprecate places where 'seq' can be omitted" featureSupportValueOptionsAsOptionalParameters,"Support ValueOption as valid type for optional member parameters" +featureSupportWarnWhenUnitPassedToObjArg,"Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`." diff --git a/src/Compiler/Facilities/LanguageFeatures.fs b/src/Compiler/Facilities/LanguageFeatures.fs index 5401ea26a1b..9ee90f98bb4 100644 --- a/src/Compiler/Facilities/LanguageFeatures.fs +++ b/src/Compiler/Facilities/LanguageFeatures.fs @@ -98,6 +98,7 @@ type LanguageFeature = | UseTypeSubsumptionCache | DeprecatePlacesWhereSeqCanBeOmitted | SupportValueOptionsAsOptionalParameters + | WarnWhenUnitPassedToObjArg /// LanguageVersion management type LanguageVersion(versionText) = @@ -227,6 +228,7 @@ type LanguageVersion(versionText) = LanguageFeature.DontWarnOnUppercaseIdentifiersInBindingPatterns, previewVersion LanguageFeature.DeprecatePlacesWhereSeqCanBeOmitted, previewVersion LanguageFeature.SupportValueOptionsAsOptionalParameters, previewVersion + LanguageFeature.WarnWhenUnitPassedToObjArg, previewVersion ] static let defaultLanguageVersion = LanguageVersion("default") @@ -388,6 +390,7 @@ type LanguageVersion(versionText) = | LanguageFeature.UseTypeSubsumptionCache -> FSComp.SR.featureUseTypeSubsumptionCache () | LanguageFeature.DeprecatePlacesWhereSeqCanBeOmitted -> FSComp.SR.featureDeprecatePlacesWhereSeqCanBeOmitted () | LanguageFeature.SupportValueOptionsAsOptionalParameters -> FSComp.SR.featureSupportValueOptionsAsOptionalParameters () + | LanguageFeature.WarnWhenUnitPassedToObjArg -> FSComp.SR.featureSupportWarnWhenUnitPassedToObjArg () /// Get a version string associated with the given feature. static member GetFeatureVersionString feature = diff --git a/src/Compiler/Facilities/LanguageFeatures.fsi b/src/Compiler/Facilities/LanguageFeatures.fsi index 90572888001..410a8b193c9 100644 --- a/src/Compiler/Facilities/LanguageFeatures.fsi +++ b/src/Compiler/Facilities/LanguageFeatures.fsi @@ -89,6 +89,7 @@ type LanguageFeature = | UseTypeSubsumptionCache | DeprecatePlacesWhereSeqCanBeOmitted | SupportValueOptionsAsOptionalParameters + | WarnWhenUnitPassedToObjArg /// LanguageVersion management type LanguageVersion = diff --git a/src/Compiler/Interactive/ControlledExecution.fs b/src/Compiler/Interactive/ControlledExecution.fs index 2d696344b58..2d18a8819b2 100644 --- a/src/Compiler/Interactive/ControlledExecution.fs +++ b/src/Compiler/Interactive/ControlledExecution.fs @@ -6,6 +6,8 @@ // because we continue to support older coreclrs and the windows desktop framework through netstandard2.0 // we access the features using reflection +#nowarn "3262" // The `Option.ofObj (Type.GetType..) construct warns in ns20, because Type.GetType is not annotated as nullable + namespace FSharp.Compiler.Interactive open System diff --git a/src/Compiler/xlf/FSComp.txt.cs.xlf b/src/Compiler/xlf/FSComp.txt.cs.xlf index 30a20d94b26..74894da5d02 100644 --- a/src/Compiler/xlf/FSComp.txt.cs.xlf +++ b/src/Compiler/xlf/FSComp.txt.cs.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Vlastnosti testu případu sjednocení @@ -1712,6 +1717,11 @@ Neočekávaný typ funkce v definici pole případu sjednocení. Pokud chcete, aby pole bylo funkcí, zvažte zabalení signatury funkce závorkami, např. | Případ a -> b na | případ (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' se obvykle používá jako omezení typu v obecném kódu, například \"T when ISomeInterface<'T>\" nebo \"let f (x: #ISomeInterface<_>)\". Pokyny najdete v https://aka.ms/fsharp-iwsams. Toto upozornění můžete zakázat pomocí #nowarn \"3536\" nebo '--nowarn:3536'. diff --git a/src/Compiler/xlf/FSComp.txt.de.xlf b/src/Compiler/xlf/FSComp.txt.de.xlf index 99eb6f814b6..77409615867 100644 --- a/src/Compiler/xlf/FSComp.txt.de.xlf +++ b/src/Compiler/xlf/FSComp.txt.de.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Eigenschaften von Union-Falltests @@ -1712,6 +1717,11 @@ Unerwarteter Funktionstyp in Felddefinition von Union-Fall (case). Wenn das Feld eine Funktion sein soll, sollten Sie die Funktionssignatur in Klammern einschließen, z. B. | Case of a -> b als | Case of (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. „{0}“ wird normalerweise als Typeinschränkung im generischen Code verwendet, z. B. \"'T when ISomeInterface<'T>\" oder \"let f (x: #ISomeInterface<_>)\". Anleitungen finden Sie unter https://aka.ms/fsharp-iwsams. Sie können diese Warnung deaktivieren, indem Sie „#nowarn \"3536\"“ or „--nowarn:3536“ verwenden. diff --git a/src/Compiler/xlf/FSComp.txt.es.xlf b/src/Compiler/xlf/FSComp.txt.es.xlf index 5a841603175..9f042384d39 100644 --- a/src/Compiler/xlf/FSComp.txt.es.xlf +++ b/src/Compiler/xlf/FSComp.txt.es.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Propiedades de prueba de caso de unión @@ -1712,6 +1717,11 @@ Tipo de función inesperado en la definición de campo de caso de unión. Si pretende que el campo sea una función, considere la posibilidad de encapsular la firma de función con paréntesis, por ejemplo, Case of a -> b en | Case of (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' se usa normalmente como restricción de tipo en código genérico; por ejemplo, \"'T when ISomeInterface<'T>\" o \"let f (x: #ISomeInterface<_>)\". Consulte https://aka.ms/fsharp-iwsams para obtener instrucciones. Puede deshabilitar esta advertencia con "#nowarn \"3536\"" o "--nowarn:3536". diff --git a/src/Compiler/xlf/FSComp.txt.fr.xlf b/src/Compiler/xlf/FSComp.txt.fr.xlf index 3e98a558168..621286a8e21 100644 --- a/src/Compiler/xlf/FSComp.txt.fr.xlf +++ b/src/Compiler/xlf/FSComp.txt.fr.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Propriétés du test de cas d’union @@ -1712,6 +1717,11 @@ Type de fonction inattendu dans la définition du champ de cas d'union. Si vous souhaitez que le champ soit une fonction, envisagez d'envelopper la signature de la fonction avec des parenthèses, par exemple. | Cas de a -> b dans | Cas de (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' est généralement utilisée comme contrainte de type dans le code générique, par exemple \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". Consultez https://aka.ms/fsharp-iwsams pour obtenir de l’aide. Vous pouvez désactiver cet avertissement à l’aide de '#nowarn \"3536\"' or '--nowarn:3536'. diff --git a/src/Compiler/xlf/FSComp.txt.it.xlf b/src/Compiler/xlf/FSComp.txt.it.xlf index b982714a140..1d7bdf56aa0 100644 --- a/src/Compiler/xlf/FSComp.txt.it.xlf +++ b/src/Compiler/xlf/FSComp.txt.it.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Proprietà test case di unione @@ -1712,6 +1717,11 @@ Tipo di funzione imprevisto nella definizione del campo del caso di unione. Se desideri che il campo sia una funzione, considera di eseguire il wrapping della firma della funzione con le parentesi, ad esempio | Case of a -> b into | Case of (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' viene in genere usato come vincolo di tipo nel codice generico, ad esempio \"'T when ISomeInterface<'T>\" o \"let f (x: #ISomeInterface<_>)\". Per indicazioni, vedere https://aka.ms/fsharp-iwsams. È possibile disabilitare questo avviso usando '#nowarn \"3536\"' o '--nowarn:3536'. diff --git a/src/Compiler/xlf/FSComp.txt.ja.xlf b/src/Compiler/xlf/FSComp.txt.ja.xlf index 3a23712a963..c928a51da3e 100644 --- a/src/Compiler/xlf/FSComp.txt.ja.xlf +++ b/src/Compiler/xlf/FSComp.txt.ja.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties ユニオン ケースのテスト プロパティ @@ -1712,6 +1717,11 @@ 共用体ケースのフィールド定義で予期しない関数型が発生しました。フィールドを関数にする場合は、関数シグネチャを parens でラップすることを検討してください、例えば、 | Case of a -> b into | Case of (a -> b)。 + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' は通常、ジェネリック コードの型制約として使用されます (例: \"'T when ISomeInterface<'T>\" または \"let f (x: #ISomeInterface<_>)\")。ガイダンスについては https://aka.ms/fsharp-iwsams を参照してください。この警告は、'#nowarn \"3536\"' または '--nowarn:3536' を使用して無効にできます。 diff --git a/src/Compiler/xlf/FSComp.txt.ko.xlf b/src/Compiler/xlf/FSComp.txt.ko.xlf index 41ad2ce40ab..aaff373fcda 100644 --- a/src/Compiler/xlf/FSComp.txt.ko.xlf +++ b/src/Compiler/xlf/FSComp.txt.ko.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties 공용 구조체 사례 테스트 속성 @@ -1712,6 +1717,11 @@ 공용 구조체 사례 필드 정의에 예기치 않은 함수 형식이 있습니다. 필드가 함수가 되도록 하려면 함수 시그니처를 구문 분석으로 래핑하는 것이 좋습니다(예: | Case of a -> b into | Case of (a -> b)) + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}'은(는) 일반적으로 제네릭 코드에서 형식 제약 조건으로 사용됩니다(예: \"'T when ISomeInterface<'T>\" 또는 \"let f (x: #ISomeInterface<_>)\"). 지침은 https://aka.ms/fsharp-iwsams를 참조하세요. '#nowarn \"3536\"' 또는 '--nowarn:3536'을 사용하여 이 경고를 비활성화할 수 있습니다. diff --git a/src/Compiler/xlf/FSComp.txt.pl.xlf b/src/Compiler/xlf/FSComp.txt.pl.xlf index f7cf199c4f5..f886e72e8f8 100644 --- a/src/Compiler/xlf/FSComp.txt.pl.xlf +++ b/src/Compiler/xlf/FSComp.txt.pl.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Właściwości testowe przypadku unii @@ -1712,6 +1717,11 @@ Nieoczekiwany typ funkcji w definicji pola przypadku unii. Jeśli zamierzasz, aby pole było funkcją, rozważ ujęcie podpisu funkcji w nawiasy, np. | Przypadek a -> b | Przypadek (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. Element „{0}” jest zwykle używany jako ograniczenie typu w kodzie ogólnym, np. \"" T, gdy ISomeInterface<' T>\" lub \"let f (x: #ISomeInterface<_>)\". Aby uzyskać wskazówki, zobacz https://aka.ms/fsharp-iwsams. To ostrzeżenie można wyłączyć, używając polecenia „nowarn \"3536\"" lub "--nowarn:3536”. diff --git a/src/Compiler/xlf/FSComp.txt.pt-BR.xlf b/src/Compiler/xlf/FSComp.txt.pt-BR.xlf index 4813c278467..69082574676 100644 --- a/src/Compiler/xlf/FSComp.txt.pt-BR.xlf +++ b/src/Compiler/xlf/FSComp.txt.pt-BR.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Propriedades de teste de caso de união @@ -1712,6 +1717,11 @@ Tipo de função inesperado na definição de campo de caso de união. Se você pretende que o campo seja uma função, considere encapsular a assinatura de função com parênteses, por exemplo, | Caso de a -> b em | Caso de (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' normalmente é usado como uma restrição de tipo em código genérico, por exemplo, \"'T when ISomeInterface<'T>\" ou \"let f (x: #ISomeInterface<_>)\". Confira https://aka.ms/fsharp-iwsams para obter as diretrizes. Você pode desabilitar este aviso usando '#nowarn \"3536\"' ou '--nowarn:3536'. diff --git a/src/Compiler/xlf/FSComp.txt.ru.xlf b/src/Compiler/xlf/FSComp.txt.ru.xlf index b1aad1198d9..df0d5f9770a 100644 --- a/src/Compiler/xlf/FSComp.txt.ru.xlf +++ b/src/Compiler/xlf/FSComp.txt.ru.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Свойства теста союзного случая @@ -1712,6 +1717,11 @@ Неожиданный тип функции в определении поля регистра объединения. Если предполагается, что поле будет представлять собой функцию, следует обернуть сигнатуру функции родительными падежами, например, | Case of a -> b в | Case of (a -> b). + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. "{0}" обычно используется в качестве ограничения типа в универсальном коде, например \"'T when ISomeInterface<"T>\" или \"let f (x: #ISomeInterface<_>)\". См. руководство на https://aka.ms/fsharp-iwsams. Это предупреждение можно отключить с помощью "#nowarn \"3536\"" или "--nowarn:3536". diff --git a/src/Compiler/xlf/FSComp.txt.tr.xlf b/src/Compiler/xlf/FSComp.txt.tr.xlf index 050ccf6ea95..77568593137 100644 --- a/src/Compiler/xlf/FSComp.txt.tr.xlf +++ b/src/Compiler/xlf/FSComp.txt.tr.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties Birleşim durumu test özellikleri @@ -1712,6 +1717,11 @@ Birleşim durumu alan tanımında beklenmeyen işlev türü. Alanın bir işlev olmasını amaçlıyorsanız işlev imzasını parens ile sarmalamayı göz önünde bulundurun. Ör. | (a -> b) durumunda | a -> b durumu. + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' normalde genel kodda tür kısıtlaması olarak kullanılır, ör. \"'T when ISomeInterface<'T>\" veya \"let f (x: #ISomeInterface<_>)\". Rehber için bkz. https://aka.ms/fsharp-iwsams. '#nowarn \"3536\"' veya '--nowarn:3536' kullanarak bu uyarıyı devre dışı bırakabilirsiniz. diff --git a/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf b/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf index 085668fbc09..59532dc06d8 100644 --- a/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf +++ b/src/Compiler/xlf/FSComp.txt.zh-Hans.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties 联合用例测试属性 @@ -1712,6 +1717,11 @@ 联合用例字段定义中出现意外的函数类型。如果打算将字段作为函数,请考虑使用括号括起函数签名,例如 | Case of a -> b into | Case of (a -> b)。 + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. "{0}" 通常用作泛型代码中的类型约束,例如 \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\"。有关指南,请参阅 https://aka.ms/fsharp-iwsams。可以使用 '#nowarn \"3536\"' 或 '--nowarn:3536' 禁用此警告。 diff --git a/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf b/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf index 48f36e86118..2274eb373c8 100644 --- a/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf +++ b/src/Compiler/xlf/FSComp.txt.zh-Hant.xlf @@ -627,6 +627,11 @@ Support ValueOption as valid type for optional member parameters + + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + Warn when unit is passed to a member accepting `obj` argument, e.g. `Method(o:obj)` will warn if called via `Method()`. + + Union case test properties 聯集案例測試屬性 @@ -1712,6 +1717,11 @@ 聯集案例欄位定義中有未預期的函式類型。如果您想要讓欄位成為函式,請考慮使用括弧括住函式簽章,例如將 | Case of a -> b 變更為 | Case of (a -> b)。 + + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn \"3397\". + + '{0}' is normally used as a type constraint in generic code, e.g. \"'T when ISomeInterface<'T>\" or \"let f (x: #ISomeInterface<_>)\". See https://aka.ms/fsharp-iwsams for guidance. You can disable this warning by using '#nowarn \"3536\"' or '--nowarn:3536'. '{0}' 通常做為一般程式碼中的類型限制式,例如 \"'T when ISomeInterface<'T>\" 或 \"let f (x: #ISomeInterface<_>)\"。請參閱 https://aka.ms/fsharp-iwsams 以尋求指引。您可以使用 '#nowarn \"3536\"' 或 '--nowarn:3536' 來停用此警告。 diff --git a/src/FSharp.Build/FSharpEmbedResourceText.fs b/src/FSharp.Build/FSharpEmbedResourceText.fs index 9af5eaf4d72..3e3c79f82ee 100644 --- a/src/FSharp.Build/FSharpEmbedResourceText.fs +++ b/src/FSharp.Build/FSharpEmbedResourceText.fs @@ -268,12 +268,13 @@ open Microsoft.FSharp.Core.Operators open Microsoft.FSharp.Text open Microsoft.FSharp.Collections open Printf + +#nowarn ""3262"" // The call to Option.ofObj below is applied in multiple compilation modes for GetString, sometimes the value is typed as a non-nullable string " let StringBoilerPlate fileName = @" // BEGIN BOILERPLATE - static let getCurrentAssembly () = System.Reflection.Assembly.GetExecutingAssembly() static let getTypeInfo (t: System.Type) = t diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/OptionalDefaultParamArgs.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/OptionalDefaultParamArgs.fs index ae25dc72198..8ba293dce2a 100644 --- a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/OptionalDefaultParamArgs.fs +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/OptionalDefaultParamArgs.fs @@ -73,12 +73,25 @@ module MemberDefinitions_OptionalDefaultParamArgs = [] let ``W_WrongDefaultType_fs`` compilation = compilation + |> withLangVersionPreview |> verifyCompile |> shouldFail - |> withDiagnostics [ - (Warning 3211, Line 10, Col 62, Line 10, Col 63, "The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'.") - ] - + |> withDiagnostics + [ Warning 3211, Line 10, Col 62, Line 10, Col 63, "The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'." + Error 1, Line 13, Col 25, Line 13, Col 27, "This expression was expected to have type + 'string' + but here has type + 'unit' "] + + [] + let ``W_WrongDefaultObjType_fs`` compilation = + compilation + |> withLangVersionPreview + |> verifyCompile + |> shouldFail + |> withDiagnostics + [ Warning 3211, Line 10, Col 62, Line 10, Col 67, "The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'." + Warning 3397, Line 12, Col 19, Line 12, Col 21, """This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. This warning may be disabled using '#nowarn "3397"."""] diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultObj.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultObj.fs new file mode 100644 index 00000000000..b0e95c0974a --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultObj.fs @@ -0,0 +1,13 @@ +// #Conformance #DeclarationElements #MemberDefinitions #OptionalDefaultParameterValueArguments + + +//The DefaultParameterValue attribute and any Optional attribute will be ignored. +//Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'. + +open System.Runtime.InteropServices + +type Class() = + static member WrongType([]b:obj) = printfn "%A" b + +do Class.WrongType() +do Class.WrongType("") \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultType.fs b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultType.fs index 89b002a9238..8844f1bc8b5 100644 --- a/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultType.fs +++ b/tests/FSharp.Compiler.ComponentTests/Conformance/BasicGrammarElements/MemberDefinitions/OptionalDefaultParamArgs/W_WrongDefaultType.fs @@ -10,5 +10,6 @@ type Class() = static member WrongType([]b:string) = b let r = Class.WrongType("123") +let r2 = Class.WrongType() do () \ No newline at end of file diff --git a/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableReferenceTypesTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableReferenceTypesTests.fs index 50467c12e0a..bb95ba7a6a1 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableReferenceTypesTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableReferenceTypesTests.fs @@ -1266,6 +1266,47 @@ let mappedMaybe = nonNull maybeNull |> shouldFail |> withDiagnostics [Error 3262, Line 4, Col 25, Line 4, Col 39, "Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion."] +[] +let ``Useless null check when used in piping`` () = + FSharp """module MyLibrary + +let foo = "test" +let bar = foo |> Option.ofObj // Should produce FS3262, but did not +""" + |> asLibrary + |> typeCheckWithStrictNullness + |> shouldFail + |> withDiagnostics [Error 3262, Line 4, Col 18, Line 4, Col 30, "Value known to be without null passed to a function meant for nullables: You can create 'Some value' directly instead of 'ofObj', or consider not using an option for this value."] + +[] +let ``Useless null check when used in multi piping`` () = + FSharp """module MyLibrary + +let myFunc whateverArg = + whateverArg |> string |> Option.ofObj +""" + |> asLibrary + |> typeCheckWithStrictNullness + |> shouldFail + |> withDiagnostics [Error 3262, Line 4, Col 30, Line 4, Col 42, "Value known to be without null passed to a function meant for nullables: You can create 'Some value' directly instead of 'ofObj', or consider not using an option for this value."] + +[] +let ``Useless null check when used in more exotic pipes`` () = + FSharp """module MyLibrary + +let functionComposition x = x |> (string >> Option.ofObj) +let doublePipe x = ("x","y") ||> (fun x _y -> Option.ofObj x) +let intToint x = x + 1 +let pointfree = intToint >> string >> Option.ofObj +""" + |> asLibrary + |> typeCheckWithStrictNullness + |> shouldFail + |> withDiagnostics + [ Error 3262, Line 3, Col 45, Line 3, Col 57, "Value known to be without null passed to a function meant for nullables: You can create 'Some value' directly instead of 'ofObj', or consider not using an option for this value." + Error 3262, Line 4, Col 60, Line 4, Col 61, "Value known to be without null passed to a function meant for nullables: You can create 'Some value' directly instead of 'ofObj', or consider not using an option for this value." + Error 3262, Line 6, Col 39, Line 6, Col 51, "Value known to be without null passed to a function meant for nullables: You can create 'Some value' directly instead of 'ofObj', or consider not using an option for this value."] + [] let ``Regression: Useless usage in nested calls`` () = FSharp """module MyLibrary @@ -1341,6 +1382,32 @@ dict["ok"] <- 42 |> shouldSucceed + +[] +[] +[] +[] +[] +[] +let ``Nullness in inheritance chain`` (returnExp:string) = + + FSharp $"""module MyLibrary + +[] +type Generator<'T>() = + abstract Values: unit -> 'T + +[] +type ListGenerator<'T>() = + inherit Generator | null>() + + override _.Values() = {returnExp} +""" + |> asLibrary + |> typeCheckWithStrictNullness + |> shouldSucceed + + [] let ``Notnull constraint and inline annotated value`` () = FSharp """module MyLibrary diff --git a/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableRegressionTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableRegressionTests.fs index 9bf4730e404..c549cc09aa2 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableRegressionTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/Nullness/NullableRegressionTests.fs @@ -42,7 +42,8 @@ let ``Signature conformance`` langVersion checknulls = |> compile |> shouldFail |> withDiagnostics - [(Warning 3261, Line 4, Col 5, Line 4, Col 10, "Nullness warning: Module 'M' contains + [Warning 3262, Line 18, Col 48, Line 18, Col 60, "Value known to be without null passed to a function meant for nullables: You can create 'Some value' directly instead of 'ofObj', or consider not using an option for this value." + (Warning 3261, Line 4, Col 5, Line 4, Col 10, "Nullness warning: Module 'M' contains val test2: x: string | null -> unit but its signature specifies val test2: string -> unit diff --git a/tests/FSharp.Compiler.ComponentTests/Language/Nullness/library-functions.fs.checknulls_on.err.bsl b/tests/FSharp.Compiler.ComponentTests/Language/Nullness/library-functions.fs.checknulls_on.err.bsl index 026cfabacff..64237a113c2 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/Nullness/library-functions.fs.checknulls_on.err.bsl +++ b/tests/FSharp.Compiler.ComponentTests/Language/Nullness/library-functions.fs.checknulls_on.err.bsl @@ -1,13 +1,9 @@ -library-functions.fs (6,27)-(6,29) typecheck error Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion. library-functions.fs (7,10)-(7,17) typecheck error Nullness warning: The type 'String | null' supports 'null' but a non-null type is expected. -library-functions.fs (7,33)-(7,35) typecheck error Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion. library-functions.fs (8,18)-(8,20) typecheck error Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion. -library-functions.fs (10,28)-(10,39) typecheck error Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion. library-functions.fs (11,18)-(11,26) typecheck error Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion. library-functions.fs (17,27)-(17,38) typecheck error Nullness warning: A non-nullable 'String' was expected but this expression is nullable. Consider either changing the target to also be nullable, or use pattern matching to safely handle the null case of this expression. library-functions.fs (18,28)-(18,39) typecheck error Nullness warning: A non-nullable 'String' was expected but this expression is nullable. Consider either changing the target to also be nullable, or use pattern matching to safely handle the null case of this expression. library-functions.fs (20,28)-(20,36) typecheck error Nullness warning: The type 'String | null' supports 'null' but a non-null type is expected. library-functions.fs (26,17)-(26,19) typecheck error Nullness warning: The type 'string' does not support 'null'. library-functions.fs (27,10)-(27,16) typecheck error Nullness warning: The type 'String' does not support 'null'. -library-functions.fs (37,17)-(37,21) typecheck error Nullness warning: A non-nullable 'String' was expected but this expression is nullable. Consider either changing the target to also be nullable, or use pattern matching to safely handle the null case of this expression. -library-functions.fs (41,26)-(41,28) typecheck error Value known to be without null passed to a function meant for nullables: You can remove this `nonNull` assertion. \ No newline at end of file +library-functions.fs (37,17)-(37,21) typecheck error Nullness warning: A non-nullable 'String' was expected but this expression is nullable. Consider either changing the target to also be nullable, or use pattern matching to safely handle the null case of this expression. \ No newline at end of file diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/AsyncModule.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/AsyncModule.fs index d5bf29374d0..b4e54ab6f4c 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/AsyncModule.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/AsyncModule.fs @@ -12,6 +12,9 @@ open FSharp.Core.UnitTests.LibraryTestFx open Xunit open FsCheck +#nowarn "3397" // This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. +// Why warned - the tests here are actually trying to assert that Async still works. + module Utils = let internal memoizeAsync f = let cache = System.Collections.Concurrent.ConcurrentDictionary<'a, System.Threading.Tasks.Task<'b>>() diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/LazyType.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/LazyType.fs index 30643db5499..9bc8ec3e7de 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/LazyType.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/LazyType.fs @@ -8,6 +8,9 @@ open Xunit open Microsoft.FSharp.Collections open FSharp.Core.UnitTests.LibraryTestFx +#nowarn "3397" // This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. +// Why warned - the tests here are actually trying to test that when this happens (unit passed), it indeed results in a null + type LazyType() = [] diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Reflection/FSharpReflection.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Reflection/FSharpReflection.fs index 56fd8a0a1b1..fabb8936201 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Reflection/FSharpReflection.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Reflection/FSharpReflection.fs @@ -12,6 +12,9 @@ open Xunit open Microsoft.FSharp.Reflection +#nowarn "3397" // This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. +// Why warned - the tests here are testing also how APIs react to unit being passed to it. + (* [Test Strategy] Make sure each method works on: diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule1.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule1.fs index 727ed166b86..ec620ebc220 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule1.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule1.fs @@ -13,6 +13,9 @@ open System open FSharp.Core.UnitTests.LibraryTestFx open Xunit +#nowarn "3397" // This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. +// Why warned - the tests here are actually trying to test that when this happens (unit passed), it indeed results in a null + type OperatorsModule1() = [] diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule2.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule2.fs index f2dc93d9ee9..3e0ea652746 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule2.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/OperatorsModule2.fs @@ -19,6 +19,8 @@ open FSharp.Core.UnitTests.LibraryTestFx open Xunit #nowarn "3370" +#nowarn "3397" // This expression uses 'unit' for an 'obj'-typed argument. This will lead to passing 'null' at runtime. +// Why warned - the tests here are actually trying to test that when this happens (unit passed), it indeed results in a null /// If this type compiles without error it is correct /// Wrong if you see: FS0670 This code is not sufficiently generic. The type variable ^T could not be generalized because it would escape its scope.