diff --git a/.gitignore b/.gitignore index 3c609f19391..ec2166b3fc3 100644 --- a/.gitignore +++ b/.gitignore @@ -100,7 +100,9 @@ ossreadme*.txt *.log *.jrs *.chk -*.bak +*.bak +*.vserr +*.err *.orig *.mdf *.ldf diff --git a/DEVGUIDE.md b/DEVGUIDE.md index b17fed89880..5c6f51c3c8e 100644 --- a/DEVGUIDE.md +++ b/DEVGUIDE.md @@ -53,7 +53,17 @@ After you build the first time you can open and use this solution in Visual Stud If you don't have everything installed yet, you'll get prompted by Visual Studio to install a few more things. This is because we use a `.vsconfig` file that specifies all our dependencies. -## Developing on Windows - No Visual Studio +If you are just developing the core compiler and library then building ``FSharp.sln`` will be enough. + +### Developing the F# Compiler (Linux/macOS) + +For Linux/Mac: + + ./build.sh + +Running tests: + + ./build.sh --test We recommend installing the latest released Visual Studio and using that if you are on Windows. However, if you prefer not to do that, you will need to install the following: diff --git a/FSharp.Profiles.props b/FSharp.Profiles.props index bc6988d0bac..c9e761c997a 100644 --- a/FSharp.Profiles.props +++ b/FSharp.Profiles.props @@ -11,35 +11,18 @@ $(DefineConstants);NETSTANDARD $(DefineConstants);FX_NO_APP_DOMAINS - $(DefineConstants);FX_NO_ARRAY_LONG_LENGTH - $(DefineConstants);FX_NO_BEGINEND_READWRITE - $(DefineConstants);FX_NO_BINARY_SERIALIZATION - $(DefineConstants);FX_NO_CONVERTER - $(DefineConstants);FX_NO_DEFAULT_DEPENDENCY_TYPE $(DefineConstants);FX_NO_CORHOST_SIGNER $(DefineConstants);FX_NO_EVENTWAITHANDLE_IDISPOSABLE $(DefineConstants);FX_NO_EXIT_CONTEXT_FLAGS $(DefineConstants);FX_NO_PARAMETERIZED_THREAD_START $(DefineConstants);FX_NO_PDB_READER $(DefineConstants);FX_NO_PDB_WRITER - $(DefineConstants);FX_NO_REFLECTION_MODULE_HANDLES - $(DefineConstants);FX_NO_REFLECTION_ONLY - $(DefineConstants);FX_NO_RUNTIMEENVIRONMENT - $(DefineConstants);FX_NO_SECURITY_PERMISSIONS - $(DefineConstants);FX_NO_SERVERCODEPAGES $(DefineConstants);FX_NO_SYMBOLSTORE $(DefineConstants);FX_NO_SYSTEM_CONFIGURATION - $(DefineConstants);FX_NO_THREAD - $(DefineConstants);FX_NO_THREADABORT - $(DefineConstants);FX_NO_WAITONE_MILLISECONDS - $(DefineConstants);FX_NO_WEB_CLIENT $(DefineConstants);FX_NO_WIN_REGISTRY $(DefineConstants);FX_NO_WINFORMS $(DefineConstants);FX_NO_INDENTED_TEXT_WRITER - $(DefineConstants);FX_REDUCED_EXCEPTIONS $(DefineConstants);FX_RESHAPED_REFEMIT - $(DefineConstants);FX_RESHAPED_GLOBALIZATION - $(DefineConstants);FX_RESHAPED_REFLECTION $(DefineConstants);FX_RESHAPED_MSBUILD $(OtherFlags) --simpleresolution diff --git a/FSharpBuild.Directory.Build.props b/FSharpBuild.Directory.Build.props index 6687fb40888..95fa8fcd020 100644 --- a/FSharpBuild.Directory.Build.props +++ b/FSharpBuild.Directory.Build.props @@ -94,6 +94,10 @@ true + + $(DefineConstants);TESTING_ON_LINUX + + $(ProtoOutputPath)\fsc\Microsoft.FSharp.Targets diff --git a/FSharpTests.Directory.Build.targets b/FSharpTests.Directory.Build.targets index fe916bf2df2..8ae8c562556 100644 --- a/FSharpTests.Directory.Build.targets +++ b/FSharpTests.Directory.Build.targets @@ -13,6 +13,7 @@ DisabledWarnings="$(NoWarn)" DotnetFsiCompilerPath="$(DotnetFsiCompilerPath)" FsiExec="@(FsiExec)" + LangVersion="$(LangVersion)" LCID="$(LCID)" LoadSources="@(LoadSource)" NoFramework="false" diff --git a/Makefile b/Makefile index 10de364b677..a002620f232 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,7 @@ restore: build: proto restore $(DotNetExe) build-server shutdown - $(DotNetExe) build -c $(Configuration) -f netstandard1.6 src/fsharp/FSharp.Core/FSharp.Core.fsproj + $(DotNetExe) build -c $(Configuration) -f netstandard2.0 src/fsharp/FSharp.Core/FSharp.Core.fsproj $(DotNetExe) build -c $(Configuration) -f netstandard2.0 src/fsharp/FSharp.Build/FSharp.Build.fsproj $(DotNetExe) build -c $(Configuration) -f netstandard2.0 src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj $(DotNetExe) build -c $(Configuration) -f netcoreapp2.1 src/fsharp/fsc/fsc.fsproj diff --git a/eng/Build.ps1 b/eng/Build.ps1 index 1d64fc8460d..4d503dbedaa 100644 --- a/eng/Build.ps1 +++ b/eng/Build.ps1 @@ -195,6 +195,7 @@ function BuildSolution() { /p:QuietRestore=$quietRestore ` /p:QuietRestoreBinaryLog=$binaryLog ` /p:TestTargetFrameworks=$testTargetFrameworks ` + /v:$verbosity ` $suppressExtensionDeployment ` @properties } diff --git a/eng/Versions.props b/eng/Versions.props index 3556edc478f..8efcedaa538 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -12,25 +12,25 @@ beta - 4.6 + 4.7 $(FSLanguageVersion) - $(FSCoreMajorVersion).3 + $(FSCoreMajorVersion).1 $(FSCoreMajorVersion).0 $(FSCoreVersionPrefix).0 - 4.6.2 + 4.7.0 $(FSCorePackageVersion)-$(PreReleaseVersionLabel).* - 10.5 + 10.6 $(FSPackageMajorVersion).0 $(FSPackageVersion) $(FSPackageVersion).0 16 - 2 + 3 $(VSMajorVersion).0 $(VSMajorVersion).$(VSMinorVersion).0 $(VSAssemblyVersionPrefix).0 @@ -55,7 +55,6 @@ https://dotnet.myget.org/F/roslyn-tools/api/v3/index.json; https://api.nuget.org/v3/index.json; https://dotnet.myget.org/F/roslyn/api/v3/index.json; - https://dotnet.myget.org/F/roslyn-analyzers/api/v3/index.json; https://dotnet.myget.org/F/symreader-converter/api/v3/index.json; https://dotnet.myget.org/F/interactive-window/api/v3/index.json; https://myget.org/F/vs-devcore/api/v3/index.json; diff --git a/eng/build.sh b/eng/build.sh index e7627f2bd48..cda4795f873 100755 --- a/eng/build.sh +++ b/eng/build.sh @@ -246,6 +246,7 @@ function BuildSolution { # do real build MSBuild $toolset_build_proj \ $bl \ + /v:$verbosity \ /p:Configuration=$configuration \ /p:Projects="$projects" \ /p:RepoRoot="$repo_root" \ @@ -278,3 +279,4 @@ if [[ "$test_core_clr" == true ]]; then fi ExitWithExitCode 0 + diff --git a/eng/common/templates/job/publish-build-assets.yml b/eng/common/templates/job/publish-build-assets.yml index b722975f9c2..5dca87c5db2 100644 --- a/eng/common/templates/job/publish-build-assets.yml +++ b/eng/common/templates/job/publish-build-assets.yml @@ -61,6 +61,7 @@ jobs: /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} /p:Configuration=$(_BuildConfig) + /v:detailed condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} diff --git a/eng/common/tools.sh b/eng/common/tools.sh index 757d5b9ea46..cdba97ac8b8 100755 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -379,6 +379,8 @@ function MSBuild-Core { } } +. "$scriptroot/pipeline-logging-functions.sh" + ResolvePath "${BASH_SOURCE[0]}" _script_dir=`dirname "$_ResolvePath"` diff --git a/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj b/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj index c3125e32d13..d6c71b55456 100644 --- a/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj +++ b/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj @@ -12,13 +12,9 @@ true - $(DefineConstants);FX_NO_RUNTIMEENVIRONMENT $(DefineConstants);NO_PROJECTCRACKER - - ReshapedReflection.fs - FsUnit.fs diff --git a/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj b/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj index 1c258ad3087..04389899a26 100644 --- a/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj +++ b/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj @@ -33,7 +33,6 @@ $(DefineConstants);FX_NO_PDB_WRITER $(DefineConstants);FX_NO_SYMBOLSTORE $(DefineConstants);FX_NO_APP_DOMAINS - $(DefineConstants);FX_NO_RUNTIMEENVIRONMENT $(DefineConstants);FX_NO_WIN_REGISTRY $(DefineConstants);FX_NO_SYSTEM_CONFIGURATION $(DefineConstants);FX_RESHAPED_REFEMIT @@ -66,9 +65,6 @@ Logger.fs - - Reshaped/reshapedreflection.fs - ErrorText/sformat.fsi @@ -81,6 +77,12 @@ ErrorText/sr.fs + + Driver\LanguageFeatures.fsi + + + Driver\LanguageFeatures.fs + LexYaccRuntime/prim-lexing.fsi @@ -156,6 +158,9 @@ Utilities/bytes.fs + + Utilities\XmlAdapters.fs + Utilities/lib.fs @@ -269,6 +274,9 @@ AbsIL/ilreflect.fs + + ReferenceResolution/reshapedmsbuild.fs + ReferenceResolution/ReferenceResolver.fs @@ -593,9 +601,6 @@ Service/ServiceUntypedParse.fs - - Service/reshapedmsbuild.fs - Service/ServiceDeclarationLists.fsi diff --git a/src/absil/illib.fs b/src/absil/illib.fs index fea0fd92a97..68b7c8d40a8 100644 --- a/src/absil/illib.fs +++ b/src/absil/illib.fs @@ -12,10 +12,6 @@ open System.Reflection open System.Threading open System.Runtime.CompilerServices -#if FX_RESHAPED_REFLECTION -open Microsoft.FSharp.Core.ReflectionAdapters -#endif - // Logical shift right treating int32 as unsigned integer. // Code that uses this should probably be adjusted to use unsigned integer types. let (>>>&) (x: int32) (n: int32) = int32 (uint32 x >>> n) @@ -258,12 +254,6 @@ module Option = module List = - //let item n xs = List.nth xs n -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif - let sortWithOrder (c: IComparer<'T>) elements = List.sortWith (Order.toFunction c) elements let splitAfter n l = @@ -1272,11 +1262,6 @@ type LayeredMultiMap<'Key, 'Value when 'Key : equality and 'Key : comparison>(co [] module Shim = -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif - type IFileSystem = /// A shim over File.ReadAllBytes diff --git a/src/absil/ilreflect.fs b/src/absil/ilreflect.fs index 152b2bf54d5..cf43af269e6 100644 --- a/src/absil/ilreflect.fs +++ b/src/absil/ilreflect.fs @@ -24,10 +24,6 @@ open FSharp.Compiler.ErrorLogger open FSharp.Compiler.Range open FSharp.Core.Printf -#if FX_RESHAPED_REFLECTION -open Microsoft.FSharp.Core.ReflectionAdapters -#endif - let codeLabelOrder = ComparisonIdentity.Structural // Convert the output of convCustomAttr @@ -314,10 +310,8 @@ let convAssemblyRef (aref: ILAssemblyRef) = asmName.Version <- System.Version (int32 version.Major, int32 version.Minor, int32 version.Build, int32 version.Revision) Option.iter setVersion aref.Version // asmName.ProcessorArchitecture <- System.Reflection.ProcessorArchitecture.MSIL -#if !FX_RESHAPED_GLOBALIZATION //Option.iter (fun name -> asmName.CultureInfo <- System.Globalization.CultureInfo.CreateSpecificCulture name) aref.Locale asmName.CultureInfo <- System.Globalization.CultureInfo.InvariantCulture -#endif asmName /// The global environment. @@ -665,9 +659,6 @@ let TypeBuilderInstantiationT = ty let typeIsNotQueryable (ty: Type) = -#if FX_RESHAPED_REFLECTION - let ty = ty.GetTypeInfo() -#endif (ty :? TypeBuilder) || ((ty.GetType()).Equals(TypeBuilderInstantiationT)) //---------------------------------------------------------------------------- // convFieldSpec @@ -796,11 +787,7 @@ let queryableTypeGetMethod cenv emEnv parentT (mref: ILMethodRef) = parentT.GetMethod(mref.Name, cconv ||| BindingFlags.Public ||| BindingFlags.NonPublic, null, argTs, -#if FX_RESHAPED_REFLECTION - (null: obj[])) -#else (null: ParameterModifier[])) -#endif // This can fail if there is an ambiguity w.r.t. return type with _ -> null if (isNonNull methInfo && equalTypes resT methInfo.ReturnType) then @@ -1436,11 +1423,7 @@ let buildGenParamsPass1 _emEnv defineGenericParameters (gps: ILGenericParameterD let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParameterDefs) = -#if FX_RESHAPED_REFLECTION - let genpBs = genArgs |> Array.map (fun x -> (x.GetTypeInfo() :?> GenericTypeParameterBuilder)) -#else let genpBs = genArgs |> Array.map (fun x -> (x :?> GenericTypeParameterBuilder)) -#endif gps |> List.iteri (fun i (gp: ILGenericParameterDef) -> let gpB = genpBs.[i] // the Constraints are either the parent (base) type or interfaces. diff --git a/src/absil/ilwrite.fs b/src/absil/ilwrite.fs index f46b33176c7..dbd8a288755 100644 --- a/src/absil/ilwrite.fs +++ b/src/absil/ilwrite.fs @@ -3037,9 +3037,6 @@ module FileSystemUtilites = open System open System.Reflection open System.Globalization -#if FX_RESHAPED_REFLECTION - open Microsoft.FSharp.Core.ReflectionAdapters -#endif let progress = try System.Environment.GetEnvironmentVariable("FSharp_DebugSetFilePermissions") <> null with _ -> false let setExecutablePermission (filename: string) = diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 0f39af500bc..624a27f92d9 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -29,6 +29,7 @@ open FSharp.Compiler.AttributeChecking open FSharp.Compiler.ConstraintSolver open FSharp.Compiler.DiagnosticMessage open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Import open FSharp.Compiler.Infos open FSharp.Compiler.Lexhelp @@ -1740,7 +1741,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt let os = System.Text.StringBuilder() OutputPhasedDiagnostic os err flattenErrors canSuggestNames errors.Add( Diagnostic.Short(isError, os.ToString()) ) - + relatedErrors |> List.iter OutputRelatedError match err with @@ -1790,7 +1791,7 @@ let OutputDiagnosticContext prefix fileLineFn os err = let (++) x s = x @ [s] -//---------------------------------------------------------------------------- +//-------------------------------------------------------------------------- // General file name resolver //-------------------------------------------------------------------------- @@ -1975,7 +1976,7 @@ type ICompilationThread = /// Enqueue work to be done on a compilation thread. abstract EnqueueWork: (CompilationThreadToken -> unit) -> unit -type ImportedBinary = +type ImportedBinary = { FileName: string RawMetadata: IRawFSharpAssemblyData #if !NO_EXTENSIONTYPING @@ -1986,7 +1987,7 @@ type ImportedBinary = ILAssemblyRefs: ILAssemblyRef list ILScopeRef: ILScopeRef } -type ImportedAssembly = +type ImportedAssembly = { ILScopeRef: ILScopeRef FSharpViewOfMetadata: CcuThunk AssemblyAutoOpenAttributes: string list @@ -2001,7 +2002,7 @@ type AvailableImportedAssembly = | ResolvedImportedAssembly of ImportedAssembly | UnresolvedImportedAssembly of string -type CcuLoadFailureAction = +type CcuLoadFailureAction = | RaiseError | ReturnNone @@ -2161,8 +2162,10 @@ type TcConfigBuilder = mutable internalTestSpanStackReferring: bool mutable noConditionalErasure: bool - + mutable pathMap: PathMap + + mutable langVersion: LanguageVersion } static member Initial = @@ -2205,7 +2208,7 @@ type TcConfigBuilder = debuginfo = false testFlagEmitFeeFeeAs100001 = false dumpDebugInfo = false - debugSymbolFile = None + debugSymbolFile = None (* Backend configuration *) typeCheckOnly = false @@ -2300,6 +2303,7 @@ type TcConfigBuilder = internalTestSpanStackReferring = false noConditionalErasure = false pathMap = PathMap.empty + langVersion = LanguageVersion("default") } static member CreateNew(legacyReferenceResolver, defaultFSharpBinariesDir, reduceMemoryUsage, implicitIncludeDir, @@ -2720,6 +2724,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.emitTailcalls = data.emitTailcalls member x.deterministic = data.deterministic member x.pathMap = data.pathMap + member x.langVersion = data.langVersion member x.preferredUiLang = data.preferredUiLang member x.lcid = data.lcid member x.optsOn = data.optsOn @@ -3097,7 +3102,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member tcConfig.PrimaryAssemblyDllReference() = primaryAssemblyReference member tcConfig.CoreLibraryDllReference() = fslibReference - + let ReportWarning options err = warningOn err (options.WarnLevel) (options.WarnOn) && not (List.contains (GetDiagnosticNumber err) (options.WarnOff)) @@ -3448,8 +3453,8 @@ let ParseOneInputFile (tcConfig: TcConfig, lexResourceManager, conditionalCompil if List.exists (Filename.checkSuffix lower) (FSharpSigFileSuffixes@FSharpImplFileSuffixes) then if not(FileSystem.SafeExists filename) then error(Error(FSComp.SR.buildCouldNotFindSourceFile filename, rangeStartup)) - // bug 3155: if the file name is indirect, use a full path - let lexbuf = UnicodeLexing.UnicodeFileAsLexbuf(filename, tcConfig.inputCodePage, retryLocked) + let isFeatureSupported featureId = tcConfig.langVersion.SupportsFeature featureId + let lexbuf = UnicodeLexing.UnicodeFileAsLexbuf(isFeatureSupported, filename, tcConfig.inputCodePage, retryLocked) ParseOneInputLexbuf(tcConfig, lexResourceManager, conditionalCompilationDefines, lexbuf, filename, isLastCompiland, errorLogger) else error(Error(FSComp.SR.buildInvalidSourceFileExtension(SanitizeFileName filename tcConfig.implicitIncludeDir), rangeStartup)) with e -> (* errorR(Failure("parse failed")); *) errorRecovery e rangeStartup; None @@ -4693,7 +4698,7 @@ and [] TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAsse let tcGlobals = TcGlobals(tcConfig.compilingFslib, ilGlobals, fslibCcu, tcConfig.implicitIncludeDir, tcConfig.mlCompatibility, tcConfig.isInteractive, tryFindSysTypeCcu, tcConfig.emitDebugInfoInQuotations, - tcConfig.noDebugData, tcConfig.pathMap) + tcConfig.noDebugData, tcConfig.pathMap, tcConfig.langVersion) #if DEBUG // the global_g reference cell is used only for debug printing @@ -4978,11 +4983,13 @@ module private ScriptPreprocessClosure = | CodeContext.CompilationAndEvaluation -> ["INTERACTIVE"] | CodeContext.Compilation -> ["COMPILED"] | CodeContext.Editing -> "EDITING" :: (if IsScript filename then ["INTERACTIVE"] else ["COMPILED"]) - let lexbuf = UnicodeLexing.SourceTextAsLexbuf(sourceText) - + + let isFeatureSupported featureId = tcConfig.langVersion.SupportsFeature featureId + let lexbuf = UnicodeLexing.SourceTextAsLexbuf(isFeatureSupported, sourceText) + let isLastCompiland = (IsScript filename), tcConfig.target.IsExe // The root compiland is last in the list of compilands. ParseOneInputLexbuf (tcConfig, lexResourceManager, defines, lexbuf, filename, isLastCompiland, errorLogger) - + /// Create a TcConfig for load closure starting from a single .fsx file let CreateScriptTextTcConfig (legacyReferenceResolver, defaultFSharpBinariesDir, @@ -5194,7 +5201,7 @@ module private ScriptPreprocessClosure = useSimpleResolution, useFsiAuxLib, useSdkRefs, lexResourceManager: Lexhelp.LexResourceManager, applyCommmandLineArgs, assumeDotNetFramework, - tryGetMetadataSnapshot, reduceMemoryUsage) = + tryGetMetadataSnapshot, reduceMemoryUsage) = // Resolve the basic references such as FSharp.Core.dll first, before processing any #I directives in the script // @@ -5292,11 +5299,8 @@ let CheckSimulateException(tcConfig: TcConfig) = | Some("tc-oom") -> raise(System.OutOfMemoryException()) | Some("tc-an") -> raise(System.ArgumentNullException("simulated")) | Some("tc-invop") -> raise(System.InvalidOperationException()) -#if FX_REDUCED_EXCEPTIONS -#else | Some("tc-av") -> raise(System.AccessViolationException()) | Some("tc-nfn") -> raise(System.NotFiniteNumberException()) -#endif | Some("tc-aor") -> raise(System.ArgumentOutOfRangeException()) | Some("tc-dv0") -> raise(System.DivideByZeroException()) | Some("tc-oe") -> raise(System.OverflowException()) diff --git a/src/fsharp/CompileOps.fsi b/src/fsharp/CompileOps.fsi index 8a017c1e327..34e25a21f17 100644 --- a/src/fsharp/CompileOps.fsi +++ b/src/fsharp/CompileOps.fsi @@ -17,6 +17,7 @@ open FSharp.Compiler.TypeChecker open FSharp.Compiler.Range open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Tast open FSharp.Compiler.TcGlobals open FSharp.Compiler.Text @@ -383,6 +384,8 @@ type TcConfigBuilder = mutable noConditionalErasure: bool mutable pathMap : PathMap + + mutable langVersion : LanguageVersion } static member Initial: TcConfigBuilder @@ -543,6 +546,7 @@ type TcConfig = member copyFSharpCore: CopyFSharpCoreFlag member shadowCopyReferences: bool member useSdkRefs: bool + member langVersion: LanguageVersion static member Create: TcConfigBuilder * validate: bool -> TcConfig diff --git a/src/fsharp/CompileOptions.fs b/src/fsharp/CompileOptions.fs index a3c0f5c3279..c4595d2dc24 100644 --- a/src/fsharp/CompileOptions.fs +++ b/src/fsharp/CompileOptions.fs @@ -18,6 +18,7 @@ open FSharp.Compiler.TcGlobals open FSharp.Compiler.Tast open FSharp.Compiler.Tastops open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Lib open FSharp.Compiler.Range open FSharp.Compiler.IlxGen @@ -527,6 +528,7 @@ let tagAlgorithm = "{SHA1|SHA256}" let tagInt = "" let tagPathMap = "" let tagNone = "" +let tagLangVersionValues = "{?|version|latest|preview}" // PrintOptionInfo //---------------- @@ -814,28 +816,41 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = //---------------------- let defineSymbol tcConfigB s = tcConfigB.conditionalCompilationDefines <- s :: tcConfigB.conditionalCompilationDefines - + let mlCompatibilityFlag (tcConfigB: TcConfigBuilder) = CompilerOption ("mlcompatibility", tagNone, OptionUnit (fun () -> tcConfigB.mlCompatibility<-true; tcConfigB.TurnWarningOff(rangeCmdArgs, "62")), None, Some (FSComp.SR.optsMlcompatibility())) +/// LanguageVersion management +let setLanguageVersion (specifiedVersion) = + + let languageVersion = new LanguageVersion(specifiedVersion) + let dumpAllowedValues () = + printfn "%s" (FSComp.SR.optsSupportedLangVersions()) + for v in languageVersion.ValidOptions do printfn "%s" v + for v in languageVersion.ValidVersions do printfn "%s" v + exit 0 + + if specifiedVersion = "?" then dumpAllowedValues () + if not (languageVersion.ContainsVersion specifiedVersion) then error(Error(FSComp.SR.optsUnrecognizedLanguageVersion specifiedVersion, rangeCmdArgs)) + languageVersion + let languageFlags tcConfigB = [ - CompilerOption - ("checked", tagNone, - OptionSwitch (fun switch -> tcConfigB.checkOverflow <- (switch = OptionSwitch.On)), None, - Some (FSComp.SR.optsChecked())) - - CompilerOption - ("define", tagString, - OptionString (defineSymbol tcConfigB), None, - Some (FSComp.SR.optsDefine())) - + // -langversion:? Display the allowed values for language version + // -langversion: Specify language version such as + // 'default' (latest major version), or + // 'latest' (latest version, including minor versions), + // 'preview' (features for preview) + // or specific versions like '4.7' + CompilerOption("langversion", tagLangVersionValues, OptionString (fun switch -> tcConfigB.langVersion <- setLanguageVersion(switch)), None, Some (FSComp.SR.optsLangVersion())) + + CompilerOption("checked", tagNone, OptionSwitch (fun switch -> tcConfigB.checkOverflow <- (switch = OptionSwitch.On)), None, Some (FSComp.SR.optsChecked())) + CompilerOption("define", tagString, OptionString (defineSymbol tcConfigB), None, Some (FSComp.SR.optsDefine())) mlCompatibilityFlag tcConfigB ] - // OptionBlock: Advanced user options //----------------------------------- @@ -1606,16 +1621,10 @@ let ReportTime (tcConfig:TcConfig) descr = | Some("fsc-oom") -> raise(System.OutOfMemoryException()) | Some("fsc-an") -> raise(System.ArgumentNullException("simulated")) | Some("fsc-invop") -> raise(System.InvalidOperationException()) -#if FX_REDUCED_EXCEPTIONS -#else | Some("fsc-av") -> raise(System.AccessViolationException()) -#endif | Some("fsc-aor") -> raise(System.ArgumentOutOfRangeException()) | Some("fsc-dv0") -> raise(System.DivideByZeroException()) -#if FX_REDUCED_EXCEPTIONS -#else | Some("fsc-nfn") -> raise(System.NotFiniteNumberException()) -#endif | Some("fsc-oe") -> raise(System.OverflowException()) | Some("fsc-atmm") -> raise(System.ArrayTypeMismatchException()) | Some("fsc-bif") -> raise(System.BadImageFormatException()) diff --git a/src/fsharp/ConstraintSolver.fs b/src/fsharp/ConstraintSolver.fs index 188eba19cb2..1e59e05b526 100644 --- a/src/fsharp/ConstraintSolver.fs +++ b/src/fsharp/ConstraintSolver.fs @@ -2730,9 +2730,26 @@ let UndoIfFailed f = ReportWarnings warns true +let UndoIfFailedOrWarnings f = + let trace = Trace.New() + let res = + try + f trace + |> CheckNoErrorsAndGetWarnings + with e -> None + match res with + | Some [] -> + true + | _ -> + trace.Undo() + false + let AddCxTypeEqualsTypeUndoIfFailed denv css m ty1 ty2 = UndoIfFailed (fun trace -> SolveTypeEqualsTypeKeepAbbrevs (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m (WithTrace trace) ty1 ty2) +let AddCxTypeEqualsTypeUndoIfFailedOrWarnings denv css m ty1 ty2 = + UndoIfFailedOrWarnings (fun trace -> SolveTypeEqualsTypeKeepAbbrevs (MakeConstraintSolverEnv ContextInfo.NoContext css m denv) 0 m (WithTrace trace) ty1 ty2) + let AddCxTypeEqualsTypeMatchingOnlyUndoIfFailed denv css m ty1 ty2 = let csenv = { MakeConstraintSolverEnv ContextInfo.NoContext css m denv with MatchingOnly = true } UndoIfFailed (fun trace -> SolveTypeEqualsTypeKeepAbbrevs csenv 0 m (WithTrace trace) ty1 ty2) diff --git a/src/fsharp/ConstraintSolver.fsi b/src/fsharp/ConstraintSolver.fsi index 59c271b126b..1fce009f616 100644 --- a/src/fsharp/ConstraintSolver.fsi +++ b/src/fsharp/ConstraintSolver.fsi @@ -126,6 +126,7 @@ val CheckDeclaredTypars : DisplayEnv -> ConstraintSolverSt val AddConstraint : ConstraintSolverEnv -> int -> Range.range -> OptionalTrace -> Typar -> TyparConstraint -> OperationResult val AddCxTypeEqualsType : ContextInfo -> DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> unit val AddCxTypeEqualsTypeUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool +val AddCxTypeEqualsTypeUndoIfFailedOrWarnings : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool val AddCxTypeEqualsTypeMatchingOnlyUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool val AddCxTypeMustSubsumeType : ContextInfo -> DisplayEnv -> ConstraintSolverState -> range -> OptionalTrace -> TType -> TType -> unit val AddCxTypeMustSubsumeTypeUndoIfFailed : DisplayEnv -> ConstraintSolverState -> range -> TType -> TType -> bool diff --git a/src/fsharp/ErrorLogger.fs b/src/fsharp/ErrorLogger.fs index 2f9c07173b5..5760aef8a2a 100755 --- a/src/fsharp/ErrorLogger.fs +++ b/src/fsharp/ErrorLogger.fs @@ -351,10 +351,6 @@ module ErrorLoggerExtensions = /// Reraise an exception if it is one we want to report to Watson. let ReraiseIfWatsonable(exn:exn) = -#if FX_REDUCED_EXCEPTIONS - ignore exn - () -#else match exn with // These few SystemExceptions which we don't report to Watson are because we handle these in some way in Build.fs | :? System.Reflection.TargetInvocationException -> () @@ -366,7 +362,6 @@ module ErrorLoggerExtensions = PreserveStackTrace exn raise exn | _ -> () -#endif type ErrorLogger with @@ -404,10 +399,7 @@ module ErrorLoggerExtensions = // Throws StopProcessing and exceptions raised by the DiagnosticSink(exn) handler. match exn with (* Don't send ThreadAbortException down the error channel *) -#if FX_REDUCED_EXCEPTIONS -#else | :? System.Threading.ThreadAbortException | WrappedError((:? System.Threading.ThreadAbortException), _) -> () -#endif | ReportedError _ | WrappedError(ReportedError _, _) -> () | StopProcessing | WrappedError(StopProcessing, _) -> PreserveStackTrace exn @@ -679,7 +671,7 @@ type public FSharpErrorSeverityOptions = // See https://github.com/Microsoft/visualfsharp/issues/6417, if a compile of the FSharp.Compiler.Services.dll or other compiler -// binary produces exactly 65536 methods then older versions of the compiler raise a bug. If you hit this bug again then try removing -// this. -let dummyMethodFOrBug6417A() = () -let dummyMethodFOrBug6417B() = () +// binary produces exactly 65536 methods then older versions of the compiler raise a bug. If you hit this bug again then try adding +// this back in. +// let dummyMethodFOrBug6417A() = () +// let dummyMethodFOrBug6417B() = () diff --git a/src/fsharp/ExtensionTyping.fs b/src/fsharp/ExtensionTyping.fs index 0513bcf2eea..c075e0dbe96 100755 --- a/src/fsharp/ExtensionTyping.fs +++ b/src/fsharp/ExtensionTyping.fs @@ -140,9 +140,7 @@ module internal ExtensionTyping = let StripException (e: exn) = match e with -#if !FX_REDUCED_EXCEPTIONS | :? System.Reflection.TargetInvocationException as e -> e.InnerException -#endif | :? TypeInitializationException as e -> e.InnerException | _ -> e @@ -417,6 +415,7 @@ module internal ExtensionTyping = member __.IsEnum = x.IsEnum member __.IsClass = x.IsClass member __.IsSealed = x.IsSealed + member __.IsAbstract = x.IsAbstract member __.IsInterface = x.IsInterface member __.GetArrayRank() = x.GetArrayRank() member __.GenericParameterPosition = x.GenericParameterPosition diff --git a/src/fsharp/ExtensionTyping.fsi b/src/fsharp/ExtensionTyping.fsi index 5049fffa778..5c679fe69e1 100755 --- a/src/fsharp/ExtensionTyping.fsi +++ b/src/fsharp/ExtensionTyping.fsi @@ -120,6 +120,7 @@ module internal ExtensionTyping = member IsInterface : bool member IsClass : bool member IsSealed : bool + member IsAbstract : bool member IsPublic : bool member IsNestedPublic : bool member GenericParameterPosition : int diff --git a/src/fsharp/FSComp.txt b/src/fsharp/FSComp.txt index 65cdd47d5be..096da0a7cc7 100644 --- a/src/fsharp/FSComp.txt +++ b/src/fsharp/FSComp.txt @@ -73,6 +73,7 @@ buildProductNameCommunity,"F# Compiler for F# %s" pickleErrorReadingWritingMetadata,"Error reading/writing metadata for the F# compiled DLL '%s'. Was the DLL compiled with an earlier version of the F# compiler? (error: '%s')." 245,tastTypeOrModuleNotConcrete,"The type/module '%s' is not a concrete module or type" tastTypeHasAssemblyCodeRepresentation,"The type '%s' has an inline assembly code representation" +246,optsUnrecognizedLanguageVersion,"Unrecognized value '%s' for --langversion use --langversion:? for complete list" 247,tastNamespaceAndModuleWithSameNameInAssembly,"A namespace and a module named '%s' both occur in two parts of this assembly" 248,tastTwoModulesWithSameNameInAssembly,"Two modules named '%s' occur in two parts of this assembly" 249,tastDuplicateTypeDefinitionInAssembly,"Two type definitions named '%s' occur in namespace '%s' in two parts of this assembly" @@ -420,6 +421,7 @@ parsAttributesMustComeBeforeVal,"Attributes should be placed before 'val'" 568,parsAllEnumFieldsRequireValues,"All enum fields must be given values" 569,parsInlineAssemblyCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on inline assembly code types" 571,parsUnexpectedIdentifier,"Unexpected identifier: '%s'" +10,parsUnexpectedSymbolDot,"Unexpected symbol '.' in member definition. Expected 'with', '=' or other token." 572,parsUnionCasesCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation." 573,parsEnumFieldsCannotHaveVisibilityDeclarations,"Accessibility modifiers are not permitted on enumeration fields" parsConsiderUsingSeparateRecordType,"Consider using a separate record type instead" @@ -1462,9 +1464,13 @@ notAFunctionButMaybeDeclaration,"This value is not a function and cannot be appl 3244,parsInvalidAnonRecdType,"Invalid anonymous record type" 3245,tcCopyAndUpdateNeedsRecordType,"The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record" 3246,tcAugmentationsCannotHaveAttributes,"Attributes cannot be applied to type extensions." +3250,expressionHasNoName,"Expression does not have a name." +3251,chkNoFirstClassNameOf,"Using the 'nameof' operator as a first-class function value is not permitted." 3300,chkInvalidFunctionParameterType,"The parameter '%s' has an invalid type '%s'. This is not permitted by the rules of Common IL." 3301,chkInvalidFunctionReturnType,"The function or method has an invalid return type '%s'. This is not permitted by the rules of Common IL." useSdkRefs,"Use reference assemblies for .NET framework references when available (Enabled by default)." fSharpBannerVersion,"%s for F# %s" nativeResourceFormatError,"Stream does not begin with a null resource and is not in '.RES' format." -nativeResourceHeaderMalformed,"Resource header beginning at offset %s is malformed." \ No newline at end of file +nativeResourceHeaderMalformed,"Resource header beginning at offset %s is malformed." +optsLangVersion,"Display the allowed values for language version, specify language version such as 'latest' or 'preview'" +optsSupportedLangVersions,"Supported language versions:" diff --git a/src/fsharp/FSharp.Build/FSharp.Build.fsproj b/src/fsharp/FSharp.Build/FSharp.Build.fsproj index e22c8797018..76b9c7043e9 100644 --- a/src/fsharp/FSharp.Build/FSharp.Build.fsproj +++ b/src/fsharp/FSharp.Build/FSharp.Build.fsproj @@ -19,7 +19,6 @@ - diff --git a/src/fsharp/FSharp.Build/Fsc.fs b/src/fsharp/FSharp.Build/Fsc.fs index 8080637fcdf..25bdfa38d3a 100644 --- a/src/fsharp/FSharp.Build/Fsc.fs +++ b/src/fsharp/FSharp.Build/Fsc.fs @@ -40,6 +40,7 @@ type public Fsc () as this = let mutable generateInterfaceFile : string = null let mutable highEntropyVA : bool = false let mutable keyFile : string = null + let mutable langVersion : string = null let mutable noFramework = false let mutable optimize : bool = true let mutable otherFlags : string = null @@ -103,15 +104,15 @@ type public Fsc () as this = | "EMBEDDED" -> "embedded" | "FULL" -> "full" | _ -> null) - if embedAllSources then - builder.AppendSwitch("--embed+") + if embedAllSources then builder.AppendSwitch("--embed+") if embeddedFiles <> null then for item in embeddedFiles do builder.AppendSwitchIfNotNull("--embed:", item.ItemSpec) builder.AppendSwitchIfNotNull("--sourcelink:", sourceLink) + builder.AppendSwitchIfNotNull("--langversion:", langVersion) // NoFramework - if noFramework then - builder.AppendSwitch("--noframework") + if noFramework then + builder.AppendSwitch("--noframework") // BaseAddress builder.AppendSwitchIfNotNull("--baseaddress:", baseAddress) // DefineConstants @@ -120,7 +121,6 @@ type public Fsc () as this = builder.AppendSwitchIfNotNull("--define:", item.ItemSpec) // DocumentationFile builder.AppendSwitchIfNotNull("--doc:", documentationFile) - // GenerateInterfaceFile builder.AppendSwitchIfNotNull("--sig:", generateInterfaceFile) // KeyFile @@ -343,6 +343,10 @@ type public Fsc () as this = with get() = keyFile and set(s) = keyFile <- s + member fsc.LangVersion + with get() = langVersion + and set(s) = langVersion <- s + member fsc.LCID with get() = vslcid and set(p) = vslcid <- p @@ -376,7 +380,7 @@ type public Fsc () as this = member fsc.PathMap with get() = pathMap and set(s) = pathMap <- s - + // --pdb : // Name the debug output file member fsc.PdbFile diff --git a/src/fsharp/FSharp.Build/Fsi.fs b/src/fsharp/FSharp.Build/Fsi.fs index 93d8fc66590..ed1aae5e132 100644 --- a/src/fsharp/FSharp.Build/Fsi.fs +++ b/src/fsharp/FSharp.Build/Fsi.fs @@ -29,6 +29,7 @@ type public Fsi () as this = let mutable disabledWarnings : string = null let mutable dotnetFsiCompilerPath : string = null let mutable fsiExec = false + let mutable langVersion : string = null let mutable noFramework = false let mutable optimize = true let mutable otherFlags : string = null @@ -67,6 +68,7 @@ type public Fsi () as this = builder.AppendSwitchIfNotNull("--codepage:", codePage) + builder.AppendSwitchIfNotNull("--langversion:", langVersion) if noFramework then builder.AppendSwitch("--noframework") if defineConstants <> null then @@ -167,6 +169,10 @@ type public Fsi () as this = with get() = vslcid and set(p) = vslcid <- p + member fsc.LangVersion + with get() = langVersion + and set(s) = langVersion <- s + // --noframework member fsi.NoFramework with get() = noFramework diff --git a/src/fsharp/FSharp.Build/Microsoft.FSharp.Targets b/src/fsharp/FSharp.Build/Microsoft.FSharp.Targets index a5d036b885a..8421c8ea504 100644 --- a/src/fsharp/FSharp.Build/Microsoft.FSharp.Targets +++ b/src/fsharp/FSharp.Build/Microsoft.FSharp.Targets @@ -273,8 +273,8 @@ this file. - - + + Win32ResourceFile="$(Win32Resource)"> diff --git a/src/fsharp/FSharp.Build/xlf/FSBuild.txt.ja.xlf b/src/fsharp/FSharp.Build/xlf/FSBuild.txt.ja.xlf index 2cbcdb1927b..558d9a4705d 100644 --- a/src/fsharp/FSharp.Build/xlf/FSBuild.txt.ja.xlf +++ b/src/fsharp/FSharp.Build/xlf/FSBuild.txt.ja.xlf @@ -4,7 +4,7 @@ {0} for F# {1} - F# {1} の {0} + F# {1} のための {0} diff --git a/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj b/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj index 70c01bec4f0..75af428f4f1 100644 --- a/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj +++ b/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj @@ -21,7 +21,6 @@ - diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index 1b8ddb24d37..d8f5341a8a2 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -63,12 +63,6 @@ Logger.fs - - Reflection\reshapedreflection.fs - - - Reflection\reshapedmsbuild.fs - ErrorText\sformat.fsi @@ -81,6 +75,12 @@ ErrorText\sr.fs + + Driver\LanguageFeatures.fsi + + + Driver\LanguageFeatures.fs + LexYaccRuntime\prim-lexing.fsi @@ -147,6 +147,9 @@ Utilities\bytes.fs + + Utilities\XmlAdapters.fs + Utilities\InternalCollections.fsi @@ -272,7 +275,9 @@ ReferenceResolution\ReferenceResolver.fs - + + ReferenceResolution/reshapedmsbuild.fs + ReferenceResolution/LegacyMSBuildReferenceResolver.fsi @@ -636,9 +641,6 @@ Service/ServiceXmlDocParser.fs - - Service/reshapedmsbuild.fs - Service/ExternalSymbol.fsi diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.netcore.nuspec b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.netcore.nuspec index 2133f3bcf14..e8af5ff0e4a 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.netcore.nuspec +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.netcore.nuspec @@ -4,7 +4,7 @@ FSharp.Compiler.Private.netcore .NET Core compatible version of the fsharp compiler service dll - Supported Platforms: - .NET Core (netstandard1.6) + Supported Platforms: - .NET Core (netstandard2.0) en-US true @@ -15,7 +15,7 @@ $tags$ - + diff --git a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec index a82fbb1ac3e..dd9293cd88c 100644 --- a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec +++ b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec @@ -45,7 +45,7 @@ - + - + true - net45;netstandard1.6 + net45;netstandard2.0 FSharp.Core FSharp.Core.nuspec true diff --git a/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuspec b/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuspec index ee7a88b29d6..e94b3a547c3 100644 --- a/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuspec +++ b/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuspec @@ -5,50 +5,23 @@ https://fsharp.org/img/logo.png en-US - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - - - + + + + - - - - + + + + - + diff --git a/src/fsharp/FSharp.Core/FSCore.resx b/src/fsharp/FSharp.Core/FSCore.resx index 8b74b1d039c..b90b5442f20 100644 --- a/src/fsharp/FSharp.Core/FSCore.resx +++ b/src/fsharp/FSharp.Core/FSCore.resx @@ -540,4 +540,7 @@ This is not a valid query expression. The construct '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. + + maxDegreeOfParallelism must be positive, was {0} + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/FSharp.Core.fsproj b/src/fsharp/FSharp.Core/FSharp.Core.fsproj index 03a83fca87e..ef68a28e6d6 100644 --- a/src/fsharp/FSharp.Core/FSharp.Core.fsproj +++ b/src/fsharp/FSharp.Core/FSharp.Core.fsproj @@ -4,8 +4,8 @@ Library - net45;netstandard1.6 - netstandard1.6 + net45;netstandard2.0 + netstandard2.0 $(NoWarn);45;55;62;75;1204 true $(DefineConstants);FSHARP_CORE @@ -113,9 +113,6 @@ Collections/set.fs - - Reflection/reshapedreflection.fs - Reflection/reflect.fsi @@ -217,11 +214,6 @@ - - - - - diff --git a/src/fsharp/FSharp.Core/Linq.fs b/src/fsharp/FSharp.Core/Linq.fs index e4deedbf077..fb9432075c4 100644 --- a/src/fsharp/FSharp.Core/Linq.fs +++ b/src/fsharp/FSharp.Core/Linq.fs @@ -162,11 +162,6 @@ open Microsoft.FSharp.Quotations open Microsoft.FSharp.Quotations.Patterns open Microsoft.FSharp.Quotations.DerivedPatterns -#if FX_RESHAPED_REFLECTION -open PrimReflectionAdapters -open ReflectionAdapters -#endif - module LeafExpressionConverter = // The following is recognized as a LINQ 'member initialization pattern' in a quotation. @@ -219,11 +214,7 @@ module LeafExpressionConverter = SubstHelperRaw(q, x, y) |> Expr.Cast let showAll = -#if FX_RESHAPED_REFLECTION - true -#else BindingFlags.Public ||| BindingFlags.NonPublic -#endif let NullableConstructor = typedefof>.GetConstructors().[0] diff --git a/src/fsharp/FSharp.Core/Query.fs b/src/fsharp/FSharp.Core/Query.fs index cd681e77936..92ee2451844 100644 --- a/src/fsharp/FSharp.Core/Query.fs +++ b/src/fsharp/FSharp.Core/Query.fs @@ -302,11 +302,6 @@ open Microsoft.FSharp.Quotations.DerivedPatterns open Microsoft.FSharp.Linq.QueryRunExtensions -#if FX_RESHAPED_REFLECTION -open PrimReflectionAdapters -open ReflectionAdapters -#endif - [] module Query = diff --git a/src/fsharp/FSharp.Core/QueryExtensions.fs b/src/fsharp/FSharp.Core/QueryExtensions.fs index 4885899fe89..bfddf7e57ef 100644 --- a/src/fsharp/FSharp.Core/QueryExtensions.fs +++ b/src/fsharp/FSharp.Core/QueryExtensions.fs @@ -15,11 +15,6 @@ open System.Collections.Generic open System.Linq open System.Linq.Expressions -#if FX_RESHAPED_REFLECTION -open PrimReflectionAdapters -open ReflectionAdapters -#endif - // ---------------------------------------------------------------------------- /// A type used to reconstruct a grouping after applying a mutable->immutable mapping transformation @@ -171,11 +166,7 @@ module internal Adapters = let (|RecordFieldGetSimplification|_|) (expr:Expr) = match expr with | Patterns.PropertyGet(Some (Patterns.NewRecord(typ,els)),propInfo,[]) -> -#if FX_RESHAPED_REFLECTION - let fields = Microsoft.FSharp.Reflection.FSharpType.GetRecordFields(typ, true) -#else let fields = Microsoft.FSharp.Reflection.FSharpType.GetRecordFields(typ,System.Reflection.BindingFlags.Public|||System.Reflection.BindingFlags.NonPublic) -#endif match fields |> Array.tryFindIndex (fun p -> p = propInfo) with | None -> None | Some i -> if i < els.Length then Some els.[i] else None diff --git a/src/fsharp/FSharp.Core/array.fs b/src/fsharp/FSharp.Core/array.fs index 8d7ce38869d..0ac47bd39a6 100644 --- a/src/fsharp/FSharp.Core/array.fs +++ b/src/fsharp/FSharp.Core/array.fs @@ -10,9 +10,6 @@ namespace Microsoft.FSharp.Collections open Microsoft.FSharp.Core.Operators open Microsoft.FSharp.Core.CompilerServices open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators -#if FX_RESHAPED_REFLECTION - open System.Reflection -#endif /// Basic operations on arrays [] @@ -191,11 +188,7 @@ namespace Microsoft.FSharp.Collections [] let countBy (projection: 'T->'Key) (array: 'T[]) = checkNonNull "array" array -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then countByValueType projection array else countByRefType projection array @@ -445,11 +438,7 @@ namespace Microsoft.FSharp.Collections [] let groupBy (projection: 'T->'Key) (array: 'T[]) = checkNonNull "array" array -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then groupByValueType projection array else groupByRefType projection array diff --git a/src/fsharp/FSharp.Core/async.fs b/src/fsharp/FSharp.Core/async.fs index 1f20f7c8110..1d4eb37ecc3 100644 --- a/src/fsharp/FSharp.Core/async.fs +++ b/src/fsharp/FSharp.Core/async.fs @@ -17,10 +17,6 @@ namespace Microsoft.FSharp.Control open Microsoft.FSharp.Control open Microsoft.FSharp.Collections -#if FX_RESHAPED_REFLECTION - open ReflectionAdapters -#endif - type LinkedSubSource(cancellationToken: CancellationToken) = let failureCTS = new CancellationTokenSource() @@ -168,13 +164,11 @@ namespace Microsoft.FSharp.Control let f = unbox<(unit -> AsyncReturn)> o this.ExecuteWithTrampoline f |> unfake) -#if !FX_NO_PARAMETERIZED_THREAD_START // Preallocate this delegate and keep it in the trampoline holder. let threadStartCallbackForStartThreadWithTrampoline = ParameterizedThreadStart (fun o -> let f = unbox<(unit -> AsyncReturn)> o this.ExecuteWithTrampoline f |> unfake) -#endif /// Execute an async computation after installing a trampoline on its synchronous stack. [] @@ -196,22 +190,10 @@ namespace Microsoft.FSharp.Control | null -> this.QueueWorkItemWithTrampoline f | _ -> this.PostWithTrampoline syncCtxt f -#if FX_NO_PARAMETERIZED_THREAD_START - // This should be the only call to Thread.Start in this library. We must always install a trampoline. - member this.StartThreadWithTrampoline (f: unit -> AsyncReturn) = -#if FX_NO_THREAD - this.QueueWorkItemWithTrampoline f -#else - (new Thread((fun _ -> this.Execute f |> unfake), IsBackground=true)).Start() - fake() -#endif - -#else // This should be the only call to Thread.Start in this library. We must always install a trampoline. member __.StartThreadWithTrampoline (f: unit -> AsyncReturn) = (new Thread(threadStartCallbackForStartThreadWithTrampoline, IsBackground=true)).Start(f|>box) fake() -#endif /// Save the exception continuation during propagation of an exception, or prior to raising an exception member inline __.OnExceptionRaised econt = @@ -731,12 +713,7 @@ namespace Microsoft.FSharp.Control match resEvent with | null -> () | ev -> -#if FX_NO_EVENTWAITHANDLE_IDISPOSABLE - ev.Dispose() - System.GC.SuppressFinalize ev -#else ev.Close() -#endif resEvent <- null) interface IDisposable with @@ -824,15 +801,7 @@ namespace Microsoft.FSharp.Control | None -> // OK, let's really wait for the Set signal. This may block. let timeout = defaultArg timeout Threading.Timeout.Infinite -#if FX_NO_EXIT_CONTEXT_FLAGS -#if FX_NO_WAITONE_MILLISECONDS - let ok = resHandle.WaitOne(TimeSpan(int64 timeout*10000L)) -#else - let ok = resHandle.WaitOne(millisecondsTimeout= timeout) -#endif -#else let ok = resHandle.WaitOne(millisecondsTimeout= timeout, exitContext=true) -#endif if ok then // Now the result really must be available result @@ -1196,7 +1165,13 @@ namespace Microsoft.FSharp.Control async { let! cancellationToken = cancellationTokenAsync return AsyncPrimitives.StartAsTask cancellationToken computation taskCreationOptions } - static member Parallel (computations: seq>) = + static member Parallel (computations: seq>) = Async.Parallel(computations, ?maxDegreeOfParallelism=None) + + static member Parallel (computations: seq>, ?maxDegreeOfParallelism: int) = + match maxDegreeOfParallelism with + | Some x when x < 1 -> raise(System.ArgumentException(String.Format(SR.GetString(SR.maxDegreeOfParallelismNotPositive), x), "maxDegreeOfParallelism")) + | _ -> () + MakeAsync (fun ctxt -> let tasks, result = try @@ -1251,19 +1226,61 @@ namespace Microsoft.FSharp.Control | _ -> () finishTask(Interlocked.Decrement &count) - tasks |> Array.iteri (fun i p -> - QueueAsync + // If maxDegreeOfParallelism is set but is higher then the number of tasks we have we set it back to None to fall into the simple + // queue all items branch + let maxDegreeOfParallelism = + match maxDegreeOfParallelism with + | None -> None + | Some maxDegreeOfParallelism -> if maxDegreeOfParallelism >= tasks.Length then None else Some maxDegreeOfParallelism + + // Simple case (no maxDegreeOfParallelism) just queue all the work, if we have maxDegreeOfParallelism set we start that many workers + // which will make progress on the actual computations + match maxDegreeOfParallelism with + | None -> + tasks |> Array.iteri (fun i p -> + QueueAsync + innerCTS.Token + // on success, record the result + (fun res -> recordSuccess i res) + // on exception... + (fun edi -> recordFailure (Choice1Of2 edi)) + // on cancellation... + (fun cexn -> recordFailure (Choice2Of2 cexn)) + p + |> unfake) + | Some maxDegreeOfParallelism -> + let mutable i = -1 + let worker = MakeAsync (fun _ -> + while i < tasks.Length do + let j = Interlocked.Increment &i + if j < tasks.Length then + let trampolineHolder = new TrampolineHolder() + trampolineHolder.ExecuteWithTrampoline (fun () -> + let ctxt = + AsyncActivation.Create + innerCTS.Token + trampolineHolder + (fun res -> recordSuccess j res) + (fun edi -> recordFailure (Choice1Of2 edi)) + (fun cexn -> recordFailure (Choice2Of2 cexn)) + tasks.[j].Invoke ctxt + ) + |> unfake + fake() + ) + for x = 1 to maxDegreeOfParallelism do + QueueAsync innerCTS.Token - // on success, record the result - (fun res -> recordSuccess i res) - // on exception... + (fun _ -> fake()) (fun edi -> recordFailure (Choice1Of2 edi)) - // on cancellation... (fun cexn -> recordFailure (Choice2Of2 cexn)) - p - |> unfake) + worker + |> unfake + fake())) + static member Sequential (computations: seq>) = Async.Parallel(computations, maxDegreeOfParallelism=1) + static member Choice(computations: Async<'T option> seq) : Async<'T option> = MakeAsync (fun ctxt -> let result = @@ -1385,15 +1402,7 @@ namespace Microsoft.FSharp.Control let millisecondsTimeout = defaultArg millisecondsTimeout Threading.Timeout.Infinite if millisecondsTimeout = 0 then async.Delay(fun () -> -#if FX_NO_EXIT_CONTEXT_FLAGS -#if FX_NO_WAITONE_MILLISECONDS - let ok = waitHandle.WaitOne(TimeSpan 0L) -#else - let ok = waitHandle.WaitOne 0 -#endif -#else let ok = waitHandle.WaitOne(0, exitContext=false) -#endif async.Return ok) else CreateDelimitedUserCodeAsync(fun ctxt -> @@ -1683,12 +1692,7 @@ namespace Microsoft.FSharp.Control member stream.AsyncRead(buffer: byte[], ?offset, ?count) = let offset = defaultArg offset 0 let count = defaultArg count buffer.Length -#if FX_NO_BEGINEND_READWRITE - // use combo CreateDelimitedUserCodeAsync + taskContinueWith instead of AwaitTask so we can pass cancellation token to the ReadAsync task - CreateDelimitedUserCodeAsync (fun ctxt -> taskContinueWith (stream.ReadAsync(buffer, offset, count, ctxt.aux.token)) ctxt false) -#else Async.FromBeginEnd (buffer, offset, count, stream.BeginRead, stream.EndRead) -#endif [] // give the extension member a 'nice', unmangled compiled name, unique within this module member stream.AsyncRead count = @@ -1705,12 +1709,7 @@ namespace Microsoft.FSharp.Control member stream.AsyncWrite(buffer:byte[], ?offset:int, ?count:int) = let offset = defaultArg offset 0 let count = defaultArg count buffer.Length -#if FX_NO_BEGINEND_READWRITE - // use combo CreateDelimitedUserCodeAsync + taskContinueWithUnit instead of AwaitTask so we can pass cancellation token to the WriteAsync task - CreateDelimitedUserCodeAsync (fun ctxt -> taskContinueWithUnit (stream.WriteAsync(buffer, offset, count, ctxt.aux.token)) ctxt false) -#else Async.FromBeginEnd (buffer, offset, count, stream.BeginWrite, stream.EndWrite) -#endif type IObservable<'Args> with @@ -1746,8 +1745,6 @@ namespace Microsoft.FSharp.Control | _ -> None) -#if !FX_NO_WEB_CLIENT - type System.Net.WebClient with member inline private this.Download(event: IEvent<'T, _>, handler: _ -> 'T, start, result) = let downloadAsync = @@ -1799,5 +1796,3 @@ namespace Microsoft.FSharp.Control start = (fun userToken -> this.DownloadFileAsync(address, fileName, userToken)), result = (fun _ -> ()) ) -#endif - diff --git a/src/fsharp/FSharp.Core/async.fsi b/src/fsharp/FSharp.Core/async.fsi index ae2cc882a51..fe4da64debd 100644 --- a/src/fsharp/FSharp.Core/async.fsi +++ b/src/fsharp/FSharp.Core/async.fsi @@ -161,6 +161,35 @@ namespace Microsoft.FSharp.Control /// A computation that returns an array of values from the sequence of input computations. static member Parallel : computations:seq> -> Async<'T[]> + /// Creates an asynchronous computation that executes all the given asynchronous computations, + /// initially queueing each as work items and using a fork/join pattern. + /// + /// If all child computations succeed, an array of results is passed to the success continuation. + /// + /// If any child computation raises an exception, then the overall computation will trigger an + /// exception, and cancel the others. + /// + /// The overall computation will respond to cancellation while executing the child computations. + /// If cancelled, the computation will cancel any remaining child computations but will still wait + /// for the other child computations to complete. + /// A sequence of distinct computations to be parallelized. + /// A computation that returns an array of values from the sequence of input computations. + static member Parallel : computations:seq> * ?maxDegreeOfParallelism : int -> Async<'T[]> + + /// Creates an asynchronous computation that executes all the given asynchronous computations sequentially. + /// + /// If all child computations succeed, an array of results is passed to the success continuation. + /// + /// If any child computation raises an exception, then the overall computation will trigger an + /// exception, and cancel the others. + /// + /// The overall computation will respond to cancellation while executing the child computations. + /// If cancelled, the computation will cancel any remaining child computations but will still wait + /// for the other child computations to complete. + /// A sequence of distinct computations to be run in sequence. + /// A computation that returns an array of values from the sequence of input computations. + static member Sequential : computations:seq> -> Async<'T[]> + /// Creates an asynchronous computation that executes all given asynchronous computations in parallel, /// returning the result of the first succeeding computation (one whose result is 'Some x'). /// If all child computations complete with None, the parent computation also returns None. @@ -739,8 +768,7 @@ namespace Microsoft.FSharp.Control /// An asynchronous computation that waits for response to the WebRequest. [] // give the extension member a nice, unmangled compiled name, unique within this module member AsyncGetResponse : unit -> Async - -#if !FX_NO_WEB_CLIENT + type System.Net.WebClient with /// Returns an asynchronous computation that, when run, will wait for the download of the given URI. @@ -761,7 +789,6 @@ namespace Microsoft.FSharp.Control /// An asynchronous computation that will wait for the download of the URI to specified file. [] // give the extension member a nice, unmangled compiled name, unique within this module member AsyncDownloadFile : address:System.Uri * fileName: string -> Async -#endif // Internals used by MailboxProcessor module internal AsyncBuilderImpl = diff --git a/src/fsharp/FSharp.Core/event.fs b/src/fsharp/FSharp.Core/event.fs index 4489c325d5a..8643b669c3e 100644 --- a/src/fsharp/FSharp.Core/event.fs +++ b/src/fsharp/FSharp.Core/event.fs @@ -11,10 +11,6 @@ namespace Microsoft.FSharp.Control open System.Reflection open System.Diagnostics -#if FX_RESHAPED_REFLECTION - open ReflectionAdapters -#endif - [] type DelegateEvent<'Delegate when 'Delegate :> System.Delegate>() = let mutable multicast : System.Delegate = null diff --git a/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs b/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs index 0d6c3772c1b..b3fa821511a 100644 --- a/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs +++ b/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs @@ -166,21 +166,13 @@ module ExtraTopLevelOperators = [] let dict (keyValuePairs:seq<'Key*'T>) : IDictionary<'Key,'T> = -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then dictValueType keyValuePairs :> _ else dictRefType keyValuePairs :> _ [] let readOnlyDict (keyValuePairs:seq<'Key*'T>) : IReadOnlyDictionary<'Key,'T> = -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then dictValueType keyValuePairs :> _ else dictRefType keyValuePairs :> _ diff --git a/src/fsharp/FSharp.Core/list.fs b/src/fsharp/FSharp.Core/list.fs index 653c557a455..e7fd17ee52d 100644 --- a/src/fsharp/FSharp.Core/list.fs +++ b/src/fsharp/FSharp.Core/list.fs @@ -9,9 +9,6 @@ namespace Microsoft.FSharp.Collections open Microsoft.FSharp.Collections open Microsoft.FSharp.Core.CompilerServices open System.Collections.Generic -#if FX_RESHAPED_REFLECTION - open System.Reflection -#endif [] [] @@ -71,11 +68,7 @@ namespace Microsoft.FSharp.Collections [] let countBy (projection:'T->'Key) (list:'T list) = -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then countByValueType projection list else countByRefType projection list @@ -446,11 +439,7 @@ namespace Microsoft.FSharp.Collections [] let groupBy (projection:'T->'Key) (list:'T list) = -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then groupByValueType projection list else groupByRefType projection list diff --git a/src/fsharp/FSharp.Core/map.fs b/src/fsharp/FSharp.Core/map.fs index d701fb87cfa..d0fccda1fdb 100644 --- a/src/fsharp/FSharp.Core/map.fs +++ b/src/fsharp/FSharp.Core/map.fs @@ -446,21 +446,19 @@ module MapTree = [] type Map<[]'Key, []'Value when 'Key : comparison >(comparer: IComparer<'Key>, tree: MapTree<'Key, 'Value>) = -#if !FX_NO_BINARY_SERIALIZATION [] - // This type is logically immutable. This field is only mutated during deserialization. - let mutable comparer = comparer + // This type is logically immutable. This field is only mutated during deserialization. + let mutable comparer = comparer [] - // This type is logically immutable. This field is only mutated during deserialization. - let mutable tree = tree + // This type is logically immutable. This field is only mutated during deserialization. + let mutable tree = tree - // This type is logically immutable. This field is only mutated during serialization and deserialization. + // This type is logically immutable. This field is only mutated during serialization and deserialization. // - // WARNING: The compiled name of this field may never be changed because it is part of the logical + // WARNING: The compiled name of this field may never be changed because it is part of the logical // WARNING: permanent serialization format for this type. - let mutable serializedData = null -#endif + let mutable serializedData = null // We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty // set (it is just a lookup into a .NET table of type-instantiation-indexed static fields). @@ -468,7 +466,6 @@ type Map<[]'Key, [ new Map<'Key, 'Value>(comparer, MapTree<_, _>.MapEmpty) -#if !FX_NO_BINARY_SERIALIZATION [] member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) = ignore context @@ -483,9 +480,8 @@ type Map<[]'Key, [ - tree <- serializedData |> Array.map (fun (KeyValue(k, v)) -> (k, v)) |> MapTree.ofArray comparer + tree <- serializedData |> Array.map (fun (KeyValue(k, v)) -> (k, v)) |> MapTree.ofArray comparer serializedData <- null -#endif static member Empty : Map<'Key, 'Value> = empty diff --git a/src/fsharp/FSharp.Core/prim-types.fs b/src/fsharp/FSharp.Core/prim-types.fs index 5c053e8ba95..542852e5da9 100644 --- a/src/fsharp/FSharp.Core/prim-types.fs +++ b/src/fsharp/FSharp.Core/prim-types.fs @@ -374,29 +374,6 @@ namespace Microsoft.FSharp.Core /// Represents a out-argument managed pointer in F# code. This type should only be used with F# 4.5+. type outref<'T> = byref<'T, ByRefKinds.Out> -#if FX_RESHAPED_REFLECTION - module PrimReflectionAdapters = - - open System.Reflection - open System.Linq - // copied from BasicInlinedOperations - let inline box (x:'T) = (# "box !0" type ('T) x : obj #) - let inline unboxPrim<'T>(x:obj) = (# "unbox.any !0" type ('T) x : 'T #) - type System.Type with - member inline this.IsGenericType = this.GetTypeInfo().IsGenericType - member inline this.IsValueType = this.GetTypeInfo().IsValueType - member inline this.IsSealed = this.GetTypeInfo().IsSealed - member inline this.IsAssignableFrom(otherType: Type) = this.GetTypeInfo().IsAssignableFrom(otherType.GetTypeInfo()) - member inline this.GetGenericArguments() = this.GetTypeInfo().GenericTypeArguments - member inline this.GetProperty(name) = this.GetRuntimeProperty(name) - member inline this.GetMethod(name, parameterTypes) = this.GetRuntimeMethod(name, parameterTypes) - member inline this.GetCustomAttributes(attributeType: Type, inherits: bool) : obj[] = - unboxPrim<_> (box (CustomAttributeExtensions.GetCustomAttributes(this.GetTypeInfo(), attributeType, inherits).ToArray())) - - open PrimReflectionAdapters - -#endif - module internal BasicInlinedOperations = let inline unboxPrim<'T>(x:obj) = (# "unbox.any !0" type ('T) x : 'T #) let inline box (x:'T) = (# "box !0" type ('T) x : obj #) @@ -548,12 +525,8 @@ namespace Microsoft.FSharp.Core ignore obj // pretend the variable is used let e = new System.ArgumentException(ErrorStrings.AddressOpNotFirstClassString) (# "throw" (e :> System.Exception) : nativeptr<'T> #) - - + open IntrinsicOperators -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters -#endif [] // nested module OK module IntrinsicFunctions = @@ -881,78 +854,6 @@ namespace Microsoft.FSharp.Core /// specialcase: Core implementation of structural comparison on arbitrary arrays. and GenericComparisonArbArrayWithComparer (comp:GenericComparer) (x:System.Array) (y:System.Array) : int = -#if FX_NO_ARRAY_LONG_LENGTH - if x.Rank = 1 && y.Rank = 1 then - let lenx = x.Length - let leny = y.Length - let c = intOrder lenx leny - if c <> 0 then c else - let basex = (x.GetLowerBound(0)) - let basey = (y.GetLowerBound(0)) - let c = intOrder basex basey - if c <> 0 then c else - let rec check i = - if i >= lenx then 0 else - let c = GenericCompare comp ((x.GetValue(i + basex)),(y.GetValue(i + basey))) - if c <> 0 then c else check (i + 1) - check 0 - elif x.Rank = 2 && y.Rank = 2 then - let lenx0 = x.GetLength(0) - let leny0 = y.GetLength(0) - let c = intOrder lenx0 leny0 - if c <> 0 then c else - let lenx1 = x.GetLength(1) - let leny1 = y.GetLength(1) - let c = intOrder lenx1 leny1 - if c <> 0 then c else - let basex0 = (x.GetLowerBound(0)) - let basex1 = (x.GetLowerBound(1)) - let basey0 = (y.GetLowerBound(0)) - let basey1 = (y.GetLowerBound(1)) - let c = intOrder basex0 basey0 - if c <> 0 then c else - let c = intOrder basex1 basey1 - if c <> 0 then c else - let rec check0 i = - let rec check1 j = - if j >= lenx1 then 0 else - let c = GenericCompare comp ((x.GetValue(i + basex0,j + basex1)), (y.GetValue(i + basey0,j + basey1))) - if c <> 0 then c else check1 (j + 1) - if i >= lenx0 then 0 else - let c = check1 0 - if c <> 0 then c else - check0 (i + 1) - check0 0 - else - let c = intOrder x.Rank y.Rank - if c <> 0 then c else - let ndims = x.Rank - // check lengths - let rec precheck k = - if k >= ndims then 0 else - let c = intOrder (x.GetLength(k)) (y.GetLength(k)) - if c <> 0 then c else - let c = intOrder (x.GetLowerBound(k)) (y.GetLowerBound(k)) - if c <> 0 then c else - precheck (k+1) - let c = precheck 0 - if c <> 0 then c else - let idxs : int[] = zeroCreate ndims - let rec checkN k baseIdx i lim = - if i >= lim then 0 else - set idxs k (baseIdx + i) - let c = - if k = ndims - 1 - then GenericCompare comp ((x.GetValue(idxs)), (y.GetValue(idxs))) - else check (k+1) - if c <> 0 then c else - checkN k baseIdx (i + 1) lim - and check k = - if k >= ndims then 0 else - let baseIdx = x.GetLowerBound(k) - checkN k baseIdx 0 (x.GetLength(k)) - check 0 -#else if x.Rank = 1 && y.Rank = 1 then let lenx = x.LongLength let leny = y.LongLength @@ -985,11 +886,11 @@ namespace Microsoft.FSharp.Core let c = int64Order basex1 basey1 if c <> 0 then c else let rec check0 i = - let rec check1 j = + let rec check1 j = if j >=. lenx1 then 0 else let c = GenericCompare comp ((x.GetValue(i +. basex0,j +. basex1)), (y.GetValue(i +. basey0,j +. basey1))) if c <> 0 then c else check1 (j +. 1L) - if i >=. lenx0 then 0 else + if i >=. lenx0 then 0 else let c = check1 0L if c <> 0 then c else check0 (i +. 1L) @@ -998,8 +899,8 @@ namespace Microsoft.FSharp.Core let c = intOrder x.Rank y.Rank if c <> 0 then c else let ndims = x.Rank - // check lengths - let rec precheck k = + // check lengths + let rec precheck k = if k >= ndims then 0 else let c = int64Order (x.GetLongLength(k)) (y.GetLongLength(k)) if c <> 0 then c else @@ -1023,10 +924,9 @@ namespace Microsoft.FSharp.Core let baseIdx = x.GetLowerBound(k) checkN k (int64 baseIdx) 0L (x.GetLongLength(k)) check 0 -#endif - + /// optimized case: Core implementation of structural comparison on object arrays. - and GenericComparisonObjArrayWithComparer (comp:GenericComparer) (x:obj[]) (y:obj[]) : int = + and GenericComparisonObjArrayWithComparer (comp:GenericComparer) (x:obj[]) (y:obj[]) : int = let lenx = x.Length let leny = y.Length let c = intOrder lenx leny @@ -1035,8 +935,8 @@ namespace Microsoft.FSharp.Core let mutable i = 0 let mutable res = 0 while i < lenx do - let c = GenericCompare comp ((get x i), (get y i)) - if c <> 0 then (res <- c; i <- lenx) + let c = GenericCompare comp ((get x i), (get y i)) + if c <> 0 then (res <- c; i <- lenx) else i <- i + 1 res @@ -1058,7 +958,7 @@ namespace Microsoft.FSharp.Core type GenericComparer with interface System.Collections.IComparer with override c.Compare(x:obj,y:obj) = GenericCompare c (x,y) - + /// The unique object for comparing values in PER mode (where local exceptions are thrown when NaNs are compared) let fsComparerPER = GenericComparer(true) @@ -1403,63 +1303,6 @@ namespace Microsoft.FSharp.Core /// specialcase: Core implementation of structural equality on arbitrary arrays. and GenericEqualityArbArray er (iec:System.Collections.IEqualityComparer) (x:System.Array) (y:System.Array) : bool = -#if FX_NO_ARRAY_LONG_LENGTH - if x.Rank = 1 && y.Rank = 1 then - // check lengths - let lenx = x.Length - let leny = y.Length - (int32Eq lenx leny) && - // check contents - let basex = x.GetLowerBound(0) - let basey = y.GetLowerBound(0) - (int32Eq basex basey) && - let rec check i = (i >= lenx) || (GenericEqualityObj er iec ((x.GetValue(basex + i)),(y.GetValue(basey + i))) && check (i + 1)) - check 0 - elif x.Rank = 2 && y.Rank = 2 then - // check lengths - let lenx0 = x.GetLength(0) - let leny0 = y.GetLength(0) - (int32Eq lenx0 leny0) && - let lenx1 = x.GetLength(1) - let leny1 = y.GetLength(1) - (int32Eq lenx1 leny1) && - let basex0 = x.GetLowerBound(0) - let basex1 = x.GetLowerBound(1) - let basey0 = y.GetLowerBound(0) - let basey1 = y.GetLowerBound(1) - (int32Eq basex0 basey0) && - (int32Eq basex1 basey1) && - // check contents - let rec check0 i = - let rec check1 j = (j >= lenx1) || (GenericEqualityObj er iec ((x.GetValue(basex0 + i,basex1 + j)), (y.GetValue(basey0 + i,basey1 + j))) && check1 (j + 1)) - (i >= lenx0) || (check1 0 && check0 (i + 1)) - check0 0 - else - (x.Rank = y.Rank) && - let ndims = x.Rank - // check lengths - let rec precheck k = - (k >= ndims) || - (int32Eq (x.GetLength(k)) (y.GetLength(k)) && - int32Eq (x.GetLowerBound(k)) (y.GetLowerBound(k)) && - precheck (k+1)) - precheck 0 && - let idxs : int32[] = zeroCreate ndims - // check contents - let rec checkN k baseIdx i lim = - (i >= lim) || - (set idxs k (baseIdx + i); - (if k = ndims - 1 - then GenericEqualityObj er iec ((x.GetValue(idxs)),(y.GetValue(idxs))) - else check (k+1)) && - checkN k baseIdx (i + 1) lim) - and check k = - (k >= ndims) || - (let baseIdx = x.GetLowerBound(k) - checkN k baseIdx 0 (x.GetLength(k))) - - check 0 -#else if x.Rank = 1 && y.Rank = 1 then // check lengths let lenx = x.LongLength @@ -1468,9 +1311,9 @@ namespace Microsoft.FSharp.Core // check contents let basex = int64 (x.GetLowerBound(0)) let basey = int64 (y.GetLowerBound(0)) - (int64Eq basex basey) && + (int64Eq basex basey) && let rec check i = (i >=. lenx) || (GenericEqualityObj er iec ((x.GetValue(basex +. i)),(y.GetValue(basey +. i))) && check (i +. 1L)) - check 0L + check 0L elif x.Rank = 2 && y.Rank = 2 then // check lengths let lenx0 = x.GetLongLength(0) @@ -1491,16 +1334,16 @@ namespace Microsoft.FSharp.Core (i >=. lenx0) || (check1 0L && check0 (i +. 1L)) check0 0L else - (x.Rank = y.Rank) && + (x.Rank = y.Rank) && let ndims = x.Rank - // check lengths - let rec precheck k = - (k >= ndims) || - (int64Eq (x.GetLongLength(k)) (y.GetLongLength(k)) && - int32Eq (x.GetLowerBound(k)) (y.GetLowerBound(k)) && + // check lengths + let rec precheck k = + (k >= ndims) || + (int64Eq (x.GetLongLength(k)) (y.GetLongLength(k)) && + int32Eq (x.GetLowerBound(k)) (y.GetLowerBound(k)) && precheck (k+1)) precheck 0 && - let idxs : int64[] = zeroCreate ndims + let idxs : int64[] = zeroCreate ndims // check contents let rec checkN k baseIdx i lim = (i >=. lim) || @@ -1513,10 +1356,8 @@ namespace Microsoft.FSharp.Core (k >= ndims) || (let baseIdx = x.GetLowerBound(k) checkN k (int64 baseIdx) 0L (x.GetLongLength(k))) - check 0 -#endif - + /// optimized case: Core implementation of structural equality on object arrays. and GenericEqualityObjArray er iec (x:obj[]) (y:obj[]) : bool = let lenx = x.Length @@ -2958,7 +2799,6 @@ namespace Microsoft.FSharp.Core [] static member op_Implicit(func : ('T -> 'Res) ) = new System.Func<'T,'Res>(func) -#if !FX_NO_CONVERTER [] static member op_Implicit(f : System.Converter<_,_>) : ('T -> 'Res) = (fun t -> f.Invoke(t)) @@ -2968,7 +2808,6 @@ namespace Microsoft.FSharp.Core static member FromConverter (converter: System.Converter<_,_>) : ('T -> 'Res) = (fun t -> converter.Invoke(t)) static member ToConverter (func: ('T -> 'Res) ) = new System.Converter<'T,'Res>(func) -#endif static member InvokeFast (func:FSharpFunc<_,_>, arg1: 'T, arg2: 'Res) = OptimizedClosures.invokeFast2(func, arg1, arg2) @@ -2984,9 +2823,7 @@ namespace Microsoft.FSharp.Core static member inline ToFSharpFunc (action: Action<_>) = (fun t -> action.Invoke(t)) -#if !FX_NO_CONVERTER static member inline ToFSharpFunc (converter : Converter<_,_>) = (fun t -> converter.Invoke(t)) -#endif // Note: this is not made public in the signature, because of conflicts with the Converter overload. // The method remains in case someone is calling it via reflection. @@ -4266,26 +4103,12 @@ namespace Microsoft.FSharp.Core module Attributes = open System.Runtime.CompilerServices -#if !FX_NO_DEFAULT_DEPENDENCY_TYPE - [] -#endif - -#if !FX_NO_COMVISIBLE [] -#endif [] - -#if BE_SECURITY_TRANSPARENT [] // assembly is fully transparent #if CROSS_PLATFORM_COMPILER #else [] // v4 transparency; soon to be the default, but not yet -#endif -#else -#if !FX_NO_SECURITY_PERMISSIONS - // REVIEW: Need to choose a specific permission for the action to be applied to - [] -#endif #endif do () @@ -4317,6 +4140,9 @@ namespace Microsoft.FSharp.Core [] let inline typeof<'T> = BasicInlinedOperations.typeof<'T> + [] + let inline nameof (_: 'T) : string = raise (Exception "may not call directly, should always be optimized away") + [] let methodhandleof (_call: ('T -> 'TResult)) : System.RuntimeMethodHandle = raise (Exception "may not call directly, should always be optimized away") @@ -4649,13 +4475,10 @@ namespace Microsoft.FSharp.Core when ^T : unativeint = (# "conv.ovf.i.un" value : nativeint #) when ^T : byte = (# "conv.ovf.i.un" value : nativeint #) - module OperatorIntrinsics = - + module OperatorIntrinsics = + open System.Collections -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters -#endif - + let notStarted() = raise (new System.InvalidOperationException(SR.GetString(SR.enumerationNotStarted))) let alreadyFinished() = raise (new System.InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished))) diff --git a/src/fsharp/FSharp.Core/prim-types.fsi b/src/fsharp/FSharp.Core/prim-types.fsi index 6d345a2cfda..7ba3b3ae4d4 100644 --- a/src/fsharp/FSharp.Core/prim-types.fsi +++ b/src/fsharp/FSharp.Core/prim-types.fsi @@ -1342,20 +1342,6 @@ namespace Microsoft.FSharp.Core [] val inline FastCompareTuple5 : comparer:System.Collections.IComparer -> tuple1:('T1 * 'T2 * 'T3 * 'T4 * 'T5) -> tuple2:('T1 * 'T2 * 'T3 * 'T4 * 'T5) -> int -#if FX_RESHAPED_REFLECTION - module internal PrimReflectionAdapters = - - open System.Reflection - - type System.Type with - member inline IsGenericType : bool - member inline IsValueType : bool - member inline GetMethod : string * parameterTypes : Type[] -> MethodInfo - member inline GetProperty : string -> PropertyInfo - member inline IsAssignableFrom : otherType : Type -> bool - member inline GetCustomAttributes : attributeType : Type * inherits: bool -> obj[] -#endif - //------------------------------------------------------------------------- // F# Choice Types @@ -1503,8 +1489,6 @@ namespace Microsoft.FSharp.Core /// 'U abstract member Invoke : func:'T -> 'U -#if !FX_NO_CONVERTER - /// Convert an F# first class function value to a value of type System.Converter /// The input function. /// A System.Converter of the function type. @@ -1524,7 +1508,6 @@ namespace Microsoft.FSharp.Core /// The input System.Converter. /// An F# function of the same type. static member FromConverter : converter:System.Converter<'T,'U> -> ('T -> 'U) -#endif /// Invoke an F# first class function value with five curried arguments. In some cases this /// will result in a more efficient application than applying the arguments successively. @@ -1575,12 +1558,10 @@ namespace Microsoft.FSharp.Core /// The F# function. static member inline ToFSharpFunc : action:Action<'T> -> ('T -> unit) -#if !FX_NO_CONVERTER /// Convert the given Converter delegate object to an F# function value /// The input Converter delegate. /// The F# function. static member inline ToFSharpFunc : converter:Converter<'T,'U> -> ('T -> 'U) -#endif /// Convert the given Action delegate object to an F# function value /// The input Action delegate. @@ -2418,6 +2399,10 @@ namespace Microsoft.FSharp.Core [] val inline typeof<'T> : System.Type + /// Returns the name of the given symbol. + [] + val inline nameof : 'T -> string + /// An internal, library-only compiler intrinsic for compile-time /// generation of a RuntimeMethodHandle. [] diff --git a/src/fsharp/FSharp.Core/printf.fs b/src/fsharp/FSharp.Core/printf.fs index 3913eeeba5a..26276c5fd63 100644 --- a/src/fsharp/FSharp.Core/printf.fs +++ b/src/fsharp/FSharp.Core/printf.fs @@ -47,11 +47,6 @@ module internal PrintfImpl = open Microsoft.FSharp.Collections open LanguagePrimitives.IntrinsicOperators -#if FX_RESHAPED_REFLECTION - open Microsoft.FSharp.Core.PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif - open System.IO [] @@ -1070,12 +1065,8 @@ module internal PrintfImpl = static member GenericToString<'T>(spec: FormatSpecifier) = let bindingFlags = -#if FX_RESHAPED_REFLECTION - isPlusForPositives spec.Flags // true - show non-public -#else if isPlusForPositives spec.Flags then BindingFlags.Public ||| BindingFlags.NonPublic else BindingFlags.Public -#endif let useZeroWidth = isPadWithZeros spec.Flags let opts = diff --git a/src/fsharp/FSharp.Core/quotations.fs b/src/fsharp/FSharp.Core/quotations.fs index efd9763e1c5..974e32c7678 100644 --- a/src/fsharp/FSharp.Core/quotations.fs +++ b/src/fsharp/FSharp.Core/quotations.fs @@ -20,11 +20,6 @@ open Microsoft.FSharp.Text.StructuredPrintfImpl.TaggedTextOps #nowarn "52" // The value has been copied to ensure the original is not mutated by this operation -#if FX_RESHAPED_REFLECTION -open PrimReflectionAdapters -open ReflectionAdapters -#endif - //-------------------------------------------------------------------------- // RAW quotations - basic data types //-------------------------------------------------------------------------- @@ -56,11 +51,7 @@ module Helpers = let staticBindingFlags = BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.DeclaredOnly let staticOrInstanceBindingFlags = BindingFlags.Instance ||| BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.DeclaredOnly let instanceBindingFlags = BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.DeclaredOnly -#if FX_RESHAPED_REFLECTION - let publicOrPrivateBindingFlags = true -#else let publicOrPrivateBindingFlags = BindingFlags.Public ||| BindingFlags.NonPublic -#endif let isDelegateType (typ:Type) = if typ.IsSubclassOf(typeof) then @@ -989,11 +980,7 @@ module Patterns = let resT = instFormal tyargTs rty let methInfo = try -#if FX_RESHAPED_REFLECTION - match parentT.GetMethod(nm, argTs) with -#else match parentT.GetMethod(nm, staticOrInstanceBindingFlags, null, argTs, null) with -#endif | null -> None | res -> Some res with :? AmbiguousMatchException -> None @@ -1021,11 +1008,7 @@ module Patterns = let tyArgs = List.toArray tyArgs let methInfo = try -#if FX_RESHAPED_REFLECTION - match ty.GetMethod(nm, argTypes) with -#else match ty.GetMethod(nm, staticOrInstanceBindingFlags, null, argTypes, null) with -#endif | null -> None | res -> Some res with :? AmbiguousMatchException -> None @@ -1138,21 +1121,13 @@ module Patterns = | _ -> null | ctor -> ctor - let bindProp (tc, propName, retType, argTypes, tyargs) = // We search in the instantiated type, rather than searching the generic type. let typ = mkNamedType (tc, tyargs) let argtyps : Type list = argTypes |> inst tyargs let retType : Type = retType |> inst tyargs |> removeVoid -#if FX_RESHAPED_REFLECTION - try - typ.GetProperty(propName, staticOrInstanceBindingFlags) - with :? AmbiguousMatchException -> null // more than one property found with the specified name and matching binding constraints - return null to initiate manual search - |> bindPropBySearchIfCandidateIsNull typ propName retType (Array.ofList argtyps) - |> checkNonNullResult ("propName", String.Format(SR.GetString(SR.QfailedToBindProperty), propName)) // fxcop may not see "propName" as an arg -#else typ.GetProperty(propName, staticOrInstanceBindingFlags, null, retType, Array.ofList argtyps, null) |> checkNonNullResult ("propName", String.Format(SR.GetString(SR.QfailedToBindProperty), propName)) // fxcop may not see "propName" as an arg -#endif + let bindField (tc, fldName, tyargs) = let typ = mkNamedType (tc, tyargs) typ.GetField(fldName, staticOrInstanceBindingFlags) |> checkNonNullResult ("fldName", String.Format(SR.GetString(SR.QfailedToBindField), fldName)) // fxcop may not see "fldName" as an arg @@ -1163,26 +1138,12 @@ module Patterns = let bindGenericCtor (tc:Type, argTypes:Instantiable) = let argtyps = instFormal (getGenericArguments tc) argTypes -#if FX_RESHAPED_REFLECTION - let argTypes = Array.ofList argtyps - tc.GetConstructor argTypes - |> bindCtorBySearchIfCandidateIsNull tc argTypes - |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) -#else tc.GetConstructor(instanceBindingFlags, null, Array.ofList argtyps, null) |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) -#endif let bindCtor (tc, argTypes:Instantiable, tyargs) = let typ = mkNamedType (tc, tyargs) let argtyps = argTypes |> inst tyargs -#if FX_RESHAPED_REFLECTION - let argTypes = Array.ofList argtyps - typ.GetConstructor argTypes - |> bindCtorBySearchIfCandidateIsNull typ argTypes - |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) -#else typ.GetConstructor(instanceBindingFlags, null, Array.ofList argtyps, null) |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) -#endif let chop n xs = if n < 0 then invalidArg "n" (SR.GetString(SR.inputMustBeNonNegative)) @@ -1358,11 +1319,7 @@ module Patterns = if a = "" then mscorlib elif a = "." then st.localAssembly else -#if FX_RESHAPED_REFLECTION - match System.Reflection.Assembly.Load(AssemblyName a) with -#else match System.Reflection.Assembly.Load a with -#endif | null -> raise <| System.InvalidOperationException(String.Format(SR.GetString(SR.QfailedToBindAssembly), a.ToString())) | assembly -> assembly @@ -1684,14 +1641,6 @@ module Patterns = let decodedTopResources = new Dictionary(10, HashIdentity.Structural) -#if FX_NO_REFLECTION_MODULE_HANDLES // not available on Silverlight - [] - type ModuleHandle = ModuleHandle of string * string - type System.Reflection.Module with - member x.ModuleHandle = ModuleHandle(x.Assembly.FullName, x.Name) -#else - type ModuleHandle = System.ModuleHandle -#endif [] type ReflectedDefinitionTableKey = @@ -1735,11 +1684,7 @@ module Patterns = not (decodedTopResources.ContainsKey((assem, resourceName))) then let cmaAttribForResource = -#if FX_RESHAPED_REFLECTION - CustomAttributeExtensions.GetCustomAttributes(assem, typeof) |> Seq.toArray -#else assem.GetCustomAttributes(typeof, false) -#endif |> (function null -> [| |] | x -> x) |> Array.tryPick (fun ca -> match ca with diff --git a/src/fsharp/FSharp.Core/reflect.fs b/src/fsharp/FSharp.Core/reflect.fs index 2024be205bf..f9e0a9daa8e 100644 --- a/src/fsharp/FSharp.Core/reflect.fs +++ b/src/fsharp/FSharp.Core/reflect.fs @@ -27,11 +27,6 @@ module internal ReflectionUtils = [] module internal Impl = -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open ReflectionAdapters -#endif - let getBindingFlags allowAccess = ReflectionUtils.toBindingFlags (defaultArg allowAccess false) let inline checkNonNull argName (v: 'T) = @@ -56,31 +51,18 @@ module internal Impl = //----------------------------------------------------------------- // GENERAL UTILITIES -#if FX_RESHAPED_REFLECTION - let instanceFieldFlags = BindingFlags.Instance - let instancePropertyFlags = BindingFlags.Instance - let staticPropertyFlags = BindingFlags.Static - let staticFieldFlags = BindingFlags.Static - let staticMethodFlags = BindingFlags.Static -#else let instanceFieldFlags = BindingFlags.GetField ||| BindingFlags.Instance let instancePropertyFlags = BindingFlags.GetProperty ||| BindingFlags.Instance let staticPropertyFlags = BindingFlags.GetProperty ||| BindingFlags.Static let staticFieldFlags = BindingFlags.GetField ||| BindingFlags.Static let staticMethodFlags = BindingFlags.Static -#endif - let getInstancePropertyInfo (typ: Type, propName, bindingFlags) = typ.GetProperty(propName, instancePropertyFlags ||| bindingFlags) let getInstancePropertyInfos (typ, names, bindingFlags) = names |> Array.map (fun nm -> getInstancePropertyInfo (typ, nm, bindingFlags)) - let getInstancePropertyReader (typ: Type, propName, bindingFlags) = match getInstancePropertyInfo(typ, propName, bindingFlags) with | null -> None -#if FX_RESHAPED_REFLECTION - | prop -> Some(fun (obj: obj) -> prop.GetValue (obj, null)) -#else | prop -> Some(fun (obj: obj) -> prop.GetValue (obj, instancePropertyFlags ||| bindingFlags, null, null, null)) -#endif + //----------------------------------------------------------------- // ATTRIBUTE DECOMPILATION @@ -95,7 +77,6 @@ module internal Impl = | None -> failwith "no compilation mapping attribute" | Some a -> a -#if !FX_NO_REFLECTION_ONLY let cmaName = typeof.FullName let assemblyName = typeof.Assembly.GetName().Name let _ = assert (assemblyName = "FSharp.Core") @@ -121,33 +102,26 @@ module internal Impl = match tryFindCompilationMappingAttributeFromData attrs with | None -> failwith "no compilation mapping attribute" | Some a -> a -#endif let tryFindCompilationMappingAttributeFromType (typ: Type) = -#if !FX_NO_REFLECTION_ONLY let assem = typ.Assembly if (not (isNull assem)) && assem.ReflectionOnly then tryFindCompilationMappingAttributeFromData ( typ.GetCustomAttributesData()) else -#endif tryFindCompilationMappingAttribute ( typ.GetCustomAttributes (typeof, false)) let tryFindCompilationMappingAttributeFromMemberInfo (info: MemberInfo) = -#if !FX_NO_REFLECTION_ONLY let assem = info.DeclaringType.Assembly if (not (isNull assem)) && assem.ReflectionOnly then tryFindCompilationMappingAttributeFromData (info.GetCustomAttributesData()) else -#endif tryFindCompilationMappingAttribute (info.GetCustomAttributes (typeof, false)) let findCompilationMappingAttributeFromMemberInfo (info: MemberInfo) = -#if !FX_NO_REFLECTION_ONLY let assem = info.DeclaringType.Assembly if (not (isNull assem)) && assem.ReflectionOnly then findCompilationMappingAttributeFromData (info.GetCustomAttributesData()) else -#endif findCompilationMappingAttribute (info.GetCustomAttributes (typeof, false)) let sequenceNumberOfMember (x: MemberInfo) = let (_, n, _) = findCompilationMappingAttributeFromMemberInfo x in n @@ -285,11 +259,8 @@ module internal Impl = let getUnionCaseRecordReader (typ: Type, tag: int, bindingFlags) = let props = fieldsPropsOfUnionCase (typ, tag, bindingFlags) -#if FX_RESHAPED_REFLECTION - (fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, null))) -#else (fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, bindingFlags, null, null, null))) -#endif + let getUnionTagReader (typ: Type, bindingFlags) : (obj -> int) = if isOptionType typ then (fun (obj: obj) -> match obj with null -> 0 | _ -> 1) @@ -302,20 +273,12 @@ module internal Impl = | Some reader -> (fun (obj: obj) -> reader obj :?> int) | None -> (fun (obj: obj) -> -#if FX_RESHAPED_REFLECTION - let m2b = typ.GetMethod("GetTag", [| typ |]) -#else let m2b = typ.GetMethod("GetTag", BindingFlags.Static ||| bindingFlags, null, [| typ |], null) -#endif m2b.Invoke(null, [|obj|]) :?> int) let getUnionTagMemberInfo (typ: Type, bindingFlags) = match getInstancePropertyInfo (typ, "Tag", bindingFlags) with -#if FX_RESHAPED_REFLECTION - | null -> (typ.GetMethod("GetTag") :> MemberInfo) -#else | null -> (typ.GetMethod("GetTag", BindingFlags.Static ||| bindingFlags) :> MemberInfo) -#endif | info -> (info :> MemberInfo) let isUnionCaseNullary (typ: Type, tag: int, bindingFlags) = @@ -335,11 +298,8 @@ module internal Impl = let getUnionCaseConstructor (typ: Type, tag: int, bindingFlags) = let meth = getUnionCaseConstructorMethod (typ, tag, bindingFlags) (fun args -> -#if FX_RESHAPED_REFLECTION - meth.Invoke(null, args)) -#else meth.Invoke(null, BindingFlags.Static ||| BindingFlags.InvokeMethod ||| bindingFlags, null, args, null)) -#endif + let checkUnionType (unionType, bindingFlags) = checkNonNull "unionType" unionType if not (isUnionType (unionType, bindingFlags)) then @@ -513,18 +473,10 @@ module internal Impl = let ctor = if typ.IsValueType then let fields = typ.GetFields (instanceFieldFlags ||| BindingFlags.Public) |> orderTupleFields -#if FX_RESHAPED_REFLECTION - typ.GetConstructor(fields |> Array.map (fun fi -> fi.FieldType)) -#else typ.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance, null, fields |> Array.map (fun fi -> fi.FieldType), null) -#endif else let props = typ.GetProperties() |> orderTupleProperties -#if FX_RESHAPED_REFLECTION - typ.GetConstructor(props |> Array.map (fun p -> p.PropertyType)) -#else typ.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance, null, props |> Array.map (fun p -> p.PropertyType), null) -#endif match ctor with | null -> raise (ArgumentException (String.Format (SR.GetString (SR.invalidTupleTypeConstructorNotDefined), typ.FullName))) | _ -> () @@ -533,11 +485,7 @@ module internal Impl = let getTupleCtor(typ: Type) = let ctor = getTupleConstructorMethod typ (fun (args: obj[]) -> -#if FX_RESHAPED_REFLECTION - ctor.Invoke args) -#else ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| BindingFlags.Public, null, args, null)) -#endif let rec getTupleReader (typ: Type) = let etys = typ.GetGenericArguments() @@ -639,11 +587,7 @@ module internal Impl = let getRecordConstructorMethod(typ: Type, bindingFlags) = let props = fieldPropsOfRecordType(typ, bindingFlags) -#if FX_RESHAPED_REFLECTION - let ctor = typ.GetConstructor(props |> Array.map (fun p -> p.PropertyType)) -#else let ctor = typ.GetConstructor(BindingFlags.Instance ||| bindingFlags, null, props |> Array.map (fun p -> p.PropertyType), null) -#endif match ctor with | null -> raise <| ArgumentException (String.Format (SR.GetString (SR.invalidRecordTypeConstructorNotDefined), typ.FullName)) | _ -> () @@ -652,11 +596,7 @@ module internal Impl = let getRecordConstructor(typ: Type, bindingFlags) = let ctor = getRecordConstructorMethod(typ, bindingFlags) (fun (args: obj[]) -> -#if FX_RESHAPED_REFLECTION - ctor.Invoke args) -#else ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| bindingFlags, null, args, null)) -#endif /// EXCEPTION DECOMPILATION // Check the base type - if it is also an F# type then @@ -703,10 +643,6 @@ module internal Impl = if not (isTupleType tupleType) then invalidArg argName (String.Format (SR.GetString (SR.notATupleType), tupleType.FullName)) -#if FX_RESHAPED_REFLECTION -open ReflectionAdapters -#endif - [] type UnionCaseInfo(typ: System.Type, tag: int) = diff --git a/src/fsharp/FSharp.Core/seq.fs b/src/fsharp/FSharp.Core/seq.fs index ab48146b631..97326e7315a 100644 --- a/src/fsharp/FSharp.Core/seq.fs +++ b/src/fsharp/FSharp.Core/seq.fs @@ -1071,11 +1071,7 @@ namespace Microsoft.FSharp.Collections [] let groupBy (projection:'T->'Key) (source:seq<'T>) = -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then mkDelayedSeq (fun () -> groupByValueType projection source) else mkDelayedSeq (fun () -> groupByRefType projection source) @@ -1164,11 +1160,7 @@ namespace Microsoft.FSharp.Collections let countBy (projection:'T->'Key) (source:seq<'T>) = checkNonNull "source" source -#if FX_RESHAPED_REFLECTION - if (typeof<'Key>).GetTypeInfo().IsValueType -#else if typeof<'Key>.IsValueType -#endif then mkDelayedSeq (fun () -> countByValueType projection source) else mkDelayedSeq (fun () -> countByRefType projection source) diff --git a/src/fsharp/FSharp.Core/set.fs b/src/fsharp/FSharp.Core/set.fs index f0c88dcf581..5da5152f296 100644 --- a/src/fsharp/FSharp.Core/set.fs +++ b/src/fsharp/FSharp.Core/set.fs @@ -512,23 +512,20 @@ module internal SetTree = [>)>] [] [] -type Set<[]'T when 'T: comparison >(comparer:IComparer<'T>, tree: SetTree<'T>) = +type Set<[]'T when 'T: comparison >(comparer:IComparer<'T>, tree: SetTree<'T>) = -#if !FX_NO_BINARY_SERIALIZATION [] - // NOTE: This type is logically immutable. This field is only mutated during deserialization. - let mutable comparer = comparer + // NOTE: This type is logically immutable. This field is only mutated during deserialization. + let mutable comparer = comparer [] - // NOTE: This type is logically immutable. This field is only mutated during deserialization. - let mutable tree = tree + // NOTE: This type is logically immutable. This field is only mutated during deserialization. + let mutable tree = tree - // NOTE: This type is logically immutable. This field is only mutated during serialization and deserialization. - // - // WARNING: The compiled name of this field may never be changed because it is part of the logical + // NOTE: This type is logically immutable. This field is only mutated during serialization and deserialization. + // WARNING: The compiled name of this field may never be changed because it is part of the logical // WARNING: permanent serialization format for this type. - let mutable serializedData = null -#endif + let mutable serializedData = null // We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty // set (it is just a lookup into a .NET table of type-instantiation-indexed static fields). @@ -537,7 +534,6 @@ type Set<[]'T when 'T: comparison >(comparer:IComparer<'T let comparer = LanguagePrimitives.FastGenericComparer<'T> Set<'T>(comparer, SetEmpty) -#if !FX_NO_BINARY_SERIALIZATION [] member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) = ignore context @@ -554,7 +550,6 @@ type Set<[]'T when 'T: comparison >(comparer:IComparer<'T comparer <- LanguagePrimitives.FastGenericComparer<'T> tree <- SetTree.ofArray comparer serializedData serializedData <- null -#endif [] member internal set.Comparer = comparer diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.cs.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.cs.xlf index 7c8e97d6501..c1837555d36 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.cs.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.cs.xlf @@ -707,6 +707,11 @@ Toto není platný výraz dotazu. V dotazu byla použita konstrukce {0}, která není rozpoznána překladačem dotazu z jazyka F# do jazyka LINQ. Prostudujte si specifikace povolených dotazů a zvažte přesunutí některých operací mimo výraz dotazu. + + maxDegreeOfParallelism must be positive, was {0} + Hodnota maxDegreeOfParallelism musí být kladná, ale vyskytla se hodnota {0}. + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.de.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.de.xlf index cfcd71290fa..bb113a5dd44 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.de.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.de.xlf @@ -707,6 +707,11 @@ Dies ist kein gültiger Abfrageausdruck. Das Konstrukt "{0}" wurde in einer Abfrage verwendet, wird jedoch vom F#-to-LINQ-Abfragekonvertierungsprogramm nicht erkannt. Überprüfen Sie die Spezifikation zulässiger Abfragen, und entfernen Sie unter Umständen einige Operationen aus dem Abfrageausdruck. + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism muss positiv sein, lautete jedoch "{0}". + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.es.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.es.xlf index 46a617777f6..da7f8919363 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.es.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.es.xlf @@ -707,6 +707,11 @@ Esta no es una expresión de consulta válida. La construcción '{0}' se usó en una consulta, pero el traductor de consultas F#-to-LINQ no la reconoce. Compruebe la especificación de consultas permitidas y considere mover algunas de las operaciones fuera de la expresión de consulta. + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism debe ser positivo, era {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.fr.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.fr.xlf index 09dfb48a62c..7dc0ce7839d 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.fr.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.fr.xlf @@ -707,6 +707,11 @@ Cette expression de requête n'est pas valide. La construction '{0}' a été utilisée dans une requête, mais n'est pas reconnue par le traducteur de requête F#-to-LINQ. Vérifiez la spécification des requêtes autorisées et envisagez de retirer certaines opérations de l'expression de requête. + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism doit être positif, était {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.it.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.it.xlf index 5598638a5f4..170e1e51a8c 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.it.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.it.xlf @@ -707,6 +707,11 @@ Espressione di query non valida. Il costrutto '{0}' è stato utilizzato in una query ma non è stato riconosciuto dal traduttore di query da F# a LINQ. Verificare le specifiche delle query consentite e provare a spostare alcune operazioni all'esterno dell'espressione di query. + + maxDegreeOfParallelism must be positive, was {0} + Il valore di maxDegreeOfParallelism deve essere positivo. È {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.ja.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.ja.xlf index d33e013cb6a..23b3da2999c 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.ja.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.ja.xlf @@ -707,6 +707,11 @@ これは有効なクエリ式ではありません。クエリで構造 '{0}' が使用されていますが、F# から LINQ へのクエリ トランスレーターに認識されません。許可されたクエリの仕様を確認し、一部の操作をクエリ式の外に移動することを検討してください。 + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism には正の値を指定する必要がありますが、{0} が指定されました + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.ko.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.ko.xlf index ed24759baaa..0b5c94149ab 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.ko.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.ko.xlf @@ -707,6 +707,11 @@ 올바른 쿼리 식이 아닙니다. '{0}' 구문이 쿼리에 사용되었지만 F#-to-LINQ 쿼리 변환기에서 인식할 수 없습니다. 허용되는 쿼리의 사양을 확인하고 일부 연산을 쿼리 식 외부로 이동하세요. + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism은 양수여야 하는데 {0}였습니다. + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.pl.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.pl.xlf index 3d869bc263b..2fdde8861c9 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.pl.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.pl.xlf @@ -707,6 +707,11 @@ To nie jest prawidłowe wyrażenie zapytania. Konstrukcja „{0}” została użyta w zapytaniu, ale nie rozpoznaje jej translator zapytań z języka F# na język LINQ. Sprawdź specyfikacje dozwolonych zapytań i rozważ przeniesienie niektórych operacji poza wyrażenie zapytania. + + maxDegreeOfParallelism must be positive, was {0} + Wartość maxDegreeOfParallelism musi być dodatnia, a była równa {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.pt-BR.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.pt-BR.xlf index 48c0450f629..78d9107a472 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.pt-BR.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.pt-BR.xlf @@ -707,6 +707,11 @@ Expressão de consulta inválida. A construção '{0}' foi usada em uma consulta, mas não é reconhecida pelo conversor de consultas F#-to-LINQ. Verifique a especificação de consultas permitidas e considere remover algumas das operações da expressão de consulta. + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism deve ser positivo, foi {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.ru.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.ru.xlf index cb488ded3eb..c45569be955 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.ru.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.ru.xlf @@ -707,6 +707,11 @@ Недопустимое выражение запроса. Конструкция "{0}" использовалась запросе, но не была распознана транслятором запросов из F# в LINQ. Проверьте спецификацию разрешенных запросов и попробуйте вынести часть операций за пределы выражения запроса. + + maxDegreeOfParallelism must be positive, was {0} + Параметр maxDegreeOfParallelism должен иметь положительное значение, указано значение {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.tr.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.tr.xlf index 2baf7f4b07b..f168225ae6f 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.tr.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.tr.xlf @@ -707,6 +707,11 @@ Bu geçerli bir sorgu ifadesi değil. '{0}' yapısı sorguda kullanıldı, ancak F#-to-LINQ çevirmeni tarafından tanınmıyor. İzin verilen soruların belirtimini denetleyin ve işlemlerden bazılarını sorgu ifadesinin dışına taşımayı düşünün. + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism pozitif olmalıdır, değeri: {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hans.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hans.xlf index 9bac5ce1a8b..4995ea34088 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hans.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hans.xlf @@ -707,6 +707,11 @@ 这不是有效的查询表达式。查询中使用了构造“{0}”,但 F#-LINQ 查询转换器无法识别该构造。请查看有效查询的规范,考虑是否将部分运算移到查询表达式之外。 + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism 必须是正数,它之前是 {0} + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hant.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hant.xlf index e75ede8758c..e89c723874d 100644 --- a/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hant.xlf +++ b/src/fsharp/FSharp.Core/xlf/FSCore.zh-Hant.xlf @@ -564,7 +564,7 @@ Bad integer supplied to dynamic formatter - 提供給動態格式子的整數錯誤 + 提供給動態格式器的整數錯誤 @@ -707,6 +707,11 @@ 這不是有效的查詢運算式。查詢中使用了建構 '{0}',但 F#-to-LINQ 查詢翻譯工具無法加以辨認。請檢查所允許之查詢的規格,並考慮將一些運算移出查詢運算式。 + + maxDegreeOfParallelism must be positive, was {0} + maxDegreeOfParallelism 必須為正數,原先為 {0} + + \ No newline at end of file diff --git a/src/fsharp/IlxGen.fs b/src/fsharp/IlxGen.fs index 5e61742fd9a..62300df6766 100644 --- a/src/fsharp/IlxGen.fs +++ b/src/fsharp/IlxGen.fs @@ -7444,13 +7444,10 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = mkLdarg 2us mkNormalCall (mkILCtorMethSpecForTy (g.iltyp_Exception, [serializationInfoType; streamingContextType])) ], None)) - -//#if BE_SECURITY_TRANSPARENT + [ilCtorDefForSerialziation] -//#else (* let getObjectDataMethodForSerialization = - let ilMethodDef = mkILNonGenericVirtualMethod ("GetObjectData", ILMemberAccess.Public, @@ -7478,7 +7475,7 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = | _ -> [] let ilTypeName = tref.Name - + let interfaces = exnc.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv.amap m eenv.tyenv) let tdef = mkILGenericClass diff --git a/src/fsharp/LanguageFeatures.fs b/src/fsharp/LanguageFeatures.fs new file mode 100644 index 00000000000..4f553253118 --- /dev/null +++ b/src/fsharp/LanguageFeatures.fs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Coordinating compiler operations - configuration, loading initial context, reporting errors etc. +module internal FSharp.Compiler.Features + +open System + +//------------------------------------------------------------------------------------------------------------------ +// Language version command line switch +//------------------------------------------------------------------------------------------------------------------ +// Add your features to this List - in code use languageVersion.SupportsFeature(LanguageFeatures.yourFeature) +// a return value of false means your feature is not supported by the user's language selection +// All new language features added from now on must be protected by this. +// Note: +// * The fslang design process will require a decision about feature name and whether it is required. +// * When a feature is assigned a release language, we will scrub the code of feature references and apply +// the Release Language version. + +/// LanguageFeature enumeration +[] +type LanguageFeature = + | PreviewVersion = 0 + | LanguageVersion46 = 1 + | LanguageVersion47 = 2 + | SingleUnderscorePattern = 3 + | WildCardInForLoop = 4 + | RelaxWhitespace = 5 + | NameOf = 6 + | ImplicitYield = 7 + | OpenStaticClasses = 8 + + +/// LanguageVersion management +type LanguageVersion (specifiedVersion) = + + // When we increment language versions here preview is higher than current RTM version + static let languageVersion46 = 4.6m + static let languageVersion47 = 4.7m + static let previewVersion = 9999m // Language version when preview specified + static let defaultVersion = languageVersion47 // Language version when default specified + static let latestVersion = defaultVersion // Language version when latest specified + static let latestMajorVersion = languageVersion46 // Language version when latestmajor specified + + static let validOptions = [| "preview"; "default"; "latest"; "latestmajor" |] + static let languageVersions = set [| languageVersion46; languageVersion47 |] + + static let features = dict [| + // Add new LanguageVersions here ... + LanguageFeature.LanguageVersion46, languageVersion46 + LanguageFeature.LanguageVersion47, languageVersion47 + LanguageFeature.PreviewVersion, previewVersion + LanguageFeature.SingleUnderscorePattern, languageVersion47 + LanguageFeature.WildCardInForLoop, languageVersion47 + LanguageFeature.RelaxWhitespace, languageVersion47 + LanguageFeature.NameOf, previewVersion + LanguageFeature.ImplicitYield, languageVersion47 + LanguageFeature.OpenStaticClasses, previewVersion + |] + + let specified = + match specifiedVersion with + | "?" -> 0m + | "preview" -> previewVersion + | "default" -> latestVersion + | "latest" -> latestVersion + | "latestmajor" -> latestMajorVersion + | _ -> + match Decimal.TryParse(specifiedVersion) with + | true, v -> v + | _ -> 0m + + /// Check if this feature is supported by the selected langversion + member __.SupportsFeature featureId = + match features.TryGetValue featureId with + | true, v -> v <= specified + | false, _ -> false + + /// Does the languageVersion support this version string + member __.ContainsVersion version = + match version with + | "?" | "preview" | "default" | "latest" | "latestmajor" -> true + | _ -> + match Decimal.TryParse(specifiedVersion) with + | true, v -> languageVersions.Contains v + | _ -> false + + /// Get a list of valid strings for help text + member __.ValidOptions = validOptions + + /// Get a list of valid versions for help text + member __.ValidVersions = [| + for v in languageVersions |> Seq.sort do + let label = if v = defaultVersion then " (Default)" else "" + yield sprintf "%M%s" v label + |] + + /// Get the specified LanguageVersion + member __.SpecifiedVerson = specified diff --git a/src/fsharp/LanguageFeatures.fsi b/src/fsharp/LanguageFeatures.fsi new file mode 100644 index 00000000000..d1d190d3f96 --- /dev/null +++ b/src/fsharp/LanguageFeatures.fsi @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +/// Coordinating compiler operations - configuration, loading initial context, reporting errors etc. +module internal FSharp.Compiler.Features + +/// LanguageFeature enumeration +[] +type LanguageFeature = + | PreviewVersion = 0 + | LanguageVersion46 = 1 + | LanguageVersion47 = 2 + | SingleUnderscorePattern = 3 + | WildCardInForLoop = 4 + | RelaxWhitespace = 5 + | NameOf = 6 + | ImplicitYield = 7 + | OpenStaticClasses = 8 + + +/// LanguageVersion management +type LanguageVersion = + + /// Create a LanguageVersion management object + new: string -> LanguageVersion + + /// Get the list of valid versions + member ContainsVersion: string -> bool + + /// Does the specified LanguageVersion support the specified feature + member SupportsFeature: LanguageFeature -> bool + + /// Get the list of valid versions + member ValidVersions: string array + + /// Get the list of valid options + member ValidOptions: string array + + /// Get the specified LanguageVersion + member SpecifiedVerson: decimal diff --git a/src/fsharp/LexFilter.fs b/src/fsharp/LexFilter.fs index 7cfdbcf494a..e37b0c35b1b 100755 --- a/src/fsharp/LexFilter.fs +++ b/src/fsharp/LexFilter.fs @@ -12,9 +12,9 @@ open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Parser open FSharp.Compiler.Lexhelp - let debug = false let stringOfPos (p: Position) = sprintf "(%d:%d)" p.OriginalLine p.Column @@ -764,8 +764,17 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // 'type C = class ... ' limited by 'type' // 'type C = interface ... ' limited by 'type' // 'type C = struct ... ' limited by 'type' - | _, (CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _) - -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) + | _, (CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _) + -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) + + // 'type C(' limited by 'type' + | _, (CtxtSeqBlock _ :: CtxtParen(LPAREN, _) :: (CtxtTypeDefns _ as limitCtxt) :: _ ) + // 'static member C(' limited by 'static', likewise others + | _, (CtxtSeqBlock _ :: CtxtParen(LPAREN, _) :: (CtxtMemberHead _ as limitCtxt) :: _ ) + // 'static member P with get() = ' limited by 'static', likewise others + | _, (CtxtWithAsLet _ :: (CtxtMemberHead _ as limitCtxt) :: _ ) + when lexbuf.SupportsFeature LanguageFeature.RelaxWhitespace + -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) // REVIEW: document these | _, (CtxtSeqBlock _ :: CtxtParen((BEGIN | LPAREN | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _) @@ -780,6 +789,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // else expr | (CtxtIf _ | CtxtElse _ | CtxtThen _), (CtxtIf _ as limitCtxt) :: _rest -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) + // Permitted inner-construct precise block alignment: // while ... // do expr diff --git a/src/fsharp/MethodCalls.fs b/src/fsharp/MethodCalls.fs index 895f2d1f729..cf590b69ee3 100644 --- a/src/fsharp/MethodCalls.fs +++ b/src/fsharp/MethodCalls.fs @@ -938,6 +938,19 @@ let TakeObjAddrForMethodCall g amap (minfo: MethInfo) isMutable m objArgs f = let hasCallInfo = ccallInfo.IsSome let mustTakeAddress = hasCallInfo || minfo.ObjArgNeedsAddress(amap, m) let objArgTy = tyOfExpr g objArgExpr + + let isMutable = + match isMutable with + | DefinitelyMutates + | NeverMutates + | AddressOfOp -> isMutable + | PossiblyMutates -> + // Check to see if the method is read-only. Perf optimization. + // If there is an extension member whose first arg is an inref, we must return NeverMutates. + if mustTakeAddress && (minfo.IsReadOnly || minfo.IsReadOnlyExtensionMember (amap, m)) then + NeverMutates + else + isMutable let wrap, objArgExprAddr, isReadOnly, _isWriteOnly = mkExprAddrOfExpr g mustTakeAddress hasCallInfo isMutable objArgExpr None m diff --git a/src/fsharp/NameResolution.fs b/src/fsharp/NameResolution.fs index 57b81f0ff4f..9715905d3c8 100644 --- a/src/fsharp/NameResolution.fs +++ b/src/fsharp/NameResolution.fs @@ -24,6 +24,7 @@ open FSharp.Compiler.AttributeChecking open FSharp.Compiler.InfoReader open FSharp.Compiler.PrettyNaming open FSharp.Compiler.Text +open FSharp.Compiler.Features open System.Collections.Generic #if !NO_EXTENSIONTYPING @@ -35,6 +36,7 @@ type NameResolver(g: TcGlobals, amap: Import.ImportMap, infoReader: InfoReader, instantiationGenerator: (range -> Typars -> TypeInst)) = + /// Used to transform typars into new inference typars // instantiationGenerator is a function to help us create the // type parameters by copying them from type parameter specifications read @@ -49,6 +51,7 @@ type NameResolver(g: TcGlobals, member nr.g = g member nr.amap = amap member nr.InfoReader = infoReader + member nr.languageSupportsNameOf = g.langVersion.SupportsFeature LanguageFeature.NameOf //------------------------------------------------------------------------- // Helpers for unionconstrs and recdfields @@ -78,7 +81,6 @@ let ActivePatternElemsOfValRef vref = | Some apinfo -> apinfo.ActiveTags |> List.mapi (fun i _ -> APElemRef(apinfo, vref, i)) | None -> [] - /// Try to make a reference to a value in a module. // // mkNestedValRef may fail if the assembly load set is @@ -314,6 +316,7 @@ type FullyQualifiedFlag = | OpenQualified +type UnqualifiedItems = LayeredMap [] /// The environment of information used to resolve names @@ -321,8 +324,8 @@ type NameResolutionEnv = { /// Display environment information for output eDisplayEnv: DisplayEnv - /// Values and Data Tags available by unqualified name - eUnqualifiedItems: LayeredMap + /// Values, functions, methods and other items available by unqualified name + eUnqualifiedItems: UnqualifiedItems /// Data Tags and Active Pattern Tags available by unqualified name ePatItems: NameMap @@ -417,6 +420,12 @@ type NameResolutionEnv = // Helpers to do with extension members //------------------------------------------------------------------------- +/// Indicates if we only need one result or all possible results from a resolution. +[] +type ResultCollectionSettings = + | AllResults + | AtMostOneResult + /// Allocate the next extension method priority. This is an incrementing sequence of integers /// during type checking. let NextExtensionMethodPriority() = uint64 (newStamp()) @@ -488,6 +497,125 @@ let private GetCSharpStyleIndexedExtensionMembersForTyconRef (amap: Import.Impor [] +/// Query the declared properties of a type (including inherited properties) +let IntrinsicPropInfosOfTypeInScope (infoReader: InfoReader) optFilter ad findFlag m ty = + let g = infoReader.g + let amap = infoReader.amap + let pinfos = GetIntrinsicPropInfoSetsOfType infoReader optFilter ad AllowMultiIntfInstantiations.Yes findFlag m ty + let pinfos = pinfos |> ExcludeHiddenOfPropInfos g amap m + pinfos + +/// Select from a list of extension properties +let SelectPropInfosFromExtMembers (infoReader: InfoReader) ad optFilter declaringTy m extMemInfos = + let g = infoReader.g + let amap = infoReader.amap + // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers, hence use a set. + let seen = HashSet(ExtensionMember.Comparer g) + let propCollector = new PropertyCollector(g, amap, m, declaringTy, optFilter, ad) + for emem in extMemInfos do + if seen.Add emem then + match emem with + | FSExtMem (vref, _pri) -> + match vref.MemberInfo with + | None -> () + | Some membInfo -> propCollector.Collect(membInfo, vref) + | ILExtMem _ -> + // No extension properties coming from .NET + () + propCollector.Close() + +/// Query the available extension properties of a type (including extension properties for inherited types) +let ExtensionPropInfosOfTypeInScope collectionSettings (infoReader:InfoReader) (nenv: NameResolutionEnv) optFilter ad m ty = + let g = infoReader.g + + let extMemsDangling = SelectPropInfosFromExtMembers infoReader ad optFilter ty m nenv.eUnindexedExtensionMembers + + if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil extMemsDangling) then + extMemsDangling + else + let extMemsFromHierarchy = + infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) + |> List.collect (fun ty -> + if isAppTy g ty then + let tcref = tcrefOfAppTy g ty + let extMemInfos = nenv.eIndexedExtensionMembers.Find tcref + SelectPropInfosFromExtMembers infoReader ad optFilter ty m extMemInfos + else []) + + extMemsDangling @ extMemsFromHierarchy + +/// Get all the available properties of a type (both intrinsic and extension) +let AllPropInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad findFlag m ty = + IntrinsicPropInfosOfTypeInScope infoReader optFilter ad findFlag m ty + @ ExtensionPropInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad m ty + +/// Get the available methods of a type (both declared and inherited) +let IntrinsicMethInfosOfType (infoReader:InfoReader) optFilter ad allowMultiIntfInst findFlag m ty = + let g = infoReader.g + let amap = infoReader.amap + let minfos = GetIntrinsicMethInfoSetsOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty + let minfos = minfos |> ExcludeHiddenOfMethInfos g amap m + minfos + +/// Select from a list of extension methods +let SelectMethInfosFromExtMembers (infoReader:InfoReader) optFilter apparentTy m extMemInfos = + let g = infoReader.g + // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers + let seen = HashSet(ExtensionMember.Comparer g) + [ + for emem in extMemInfos do + if seen.Add emem then + match emem with + | FSExtMem (vref, pri) -> + match vref.MemberInfo with + | None -> () + | Some membInfo -> + match TrySelectMemberVal g optFilter apparentTy (Some pri) membInfo vref with + | Some m -> yield m + | _ -> () + | ILExtMem (actualParent, minfo, pri) when (match optFilter with None -> true | Some nm -> nm = minfo.LogicalName) -> + // Make a reference to the type containing the extension members + match minfo with + | ILMeth(_, ilminfo, _) -> + yield (MethInfo.CreateILExtensionMeth (infoReader.amap, m, apparentTy, actualParent, Some pri, ilminfo.RawMetadata)) + // F#-defined IL-style extension methods are not seen as extension methods in F# code + | FSMeth(g, _, vref, _) -> + yield (FSMeth(g, apparentTy, vref, Some pri)) +#if !NO_EXTENSIONTYPING + // // Provided extension methods are not yet supported + | ProvidedMeth(amap, providedMeth, _, m) -> + yield (ProvidedMeth(amap, providedMeth, Some pri, m)) +#endif + | DefaultStructCtor _ -> + () + | _ -> () + ] + +/// Query the available extension properties of a methods (including extension methods for inherited types) +let ExtensionMethInfosOfTypeInScope (collectionSettings:ResultCollectionSettings) (infoReader:InfoReader) (nenv: NameResolutionEnv) optFilter m ty = + let extMemsDangling = SelectMethInfosFromExtMembers infoReader optFilter ty m nenv.eUnindexedExtensionMembers + if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil extMemsDangling) then + extMemsDangling + else + let extMemsFromHierarchy = + infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) + |> List.collect (fun ty -> + let g = infoReader.g + if isAppTy g ty then + let tcref = tcrefOfAppTy g ty + let extValRefs = nenv.eIndexedExtensionMembers.Find tcref + SelectMethInfosFromExtMembers infoReader optFilter ty m extValRefs + else []) + extMemsDangling @ extMemsFromHierarchy + +/// Get all the available methods of a type (both intrinsic and extension) +let AllMethInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad findFlag m ty = + let intrinsic = IntrinsicMethInfosOfType infoReader optFilter ad AllowMultiIntfInstantiations.Yes findFlag m ty + if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil intrinsic) then + intrinsic + else + intrinsic @ ExtensionMethInfosOfTypeInScope collectionSettings infoReader nenv optFilter m ty + //------------------------------------------------------------------------- // Helpers to do with building environments //------------------------------------------------------------------------- @@ -504,7 +632,7 @@ type BulkAdd = Yes | No /// bulkAddMode: true when adding the values from the 'open' of a namespace /// or module, when we collapse the value table down to a dictionary. -let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: LayeredMap<_, _>) (vrefs: ValRef[]) = +let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: UnqualifiedItems) (vrefs: ValRef[]) = // Object model members are not added to the unqualified name resolution environment let vrefs = vrefs |> Array.filter (fun vref -> not vref.IsMember) @@ -616,7 +744,7 @@ let AddUnionCases1 (tab: Map<_, _>) (ucrefs: UnionCaseRef list) = acc.Add (ucref.CaseName, item)) /// Add a set of union cases to the corresponding sub-table of the environment -let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs: UnionCaseRef list) = +let AddUnionCases2 bulkAddMode (eUnqualifiedItems: UnqualifiedItems) (ucrefs: UnionCaseRef list) = match bulkAddMode with | BulkAdd.Yes -> let items = @@ -630,8 +758,46 @@ let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs: Un let item = Item.UnionCase(GeneralizeUnionCaseRef ucref, false) acc.Add (ucref.CaseName, item)) +let AddStaticContentOfTyconRefToNameEnv (g:TcGlobals) (amap: Import.ImportMap) ad m (nenv: NameResolutionEnv) (tcref:TyconRef) = + // If OpenStaticClasses is not enabled then don't do this + if amap.g.langVersion.SupportsFeature LanguageFeature.OpenStaticClasses then + let ty = generalizedTyconRef tcref + let infoReader = InfoReader(g,amap) + let items = + [| let methGroups = + AllMethInfosOfTypeInScope ResultCollectionSettings.AllResults infoReader nenv None ad PreferOverrides m ty + |> List.groupBy (fun m -> m.LogicalName) + + for (methName, methGroup) in methGroups do + let methGroup = methGroup |> List.filter (fun m -> not m.IsInstance && not m.IsClassConstructor) + if not methGroup.IsEmpty then + yield KeyValuePair(methName, Item.MethodGroup(methName, methGroup, None)) + + let propInfos = + AllPropInfosOfTypeInScope ResultCollectionSettings.AllResults infoReader nenv None ad PreferOverrides m ty + |> List.groupBy (fun m -> m.PropertyName) + + for (propName, propInfos) in propInfos do + let propInfos = propInfos |> List.filter (fun m -> m.IsStatic) + for propInfo in propInfos do + yield KeyValuePair(propName , Item.Property(propName,[propInfo])) + + let fields = + infoReader.GetILFieldInfosOfType(None, ad, m, ty) + |> List.groupBy (fun f -> f.FieldName) + + for (fieldName, fieldInfos) in fields do + let fieldInfos = fieldInfos |> List.filter (fun fi -> fi.IsStatic) + for fieldInfo in fieldInfos do + yield KeyValuePair(fieldName, Item.ILField(fieldInfo)) + |] + + { nenv with eUnqualifiedItems = nenv.eUnqualifiedItems.AddAndMarkAsCollapsible items } + else + nenv + /// Add any implied contents of a type definition to the environment. -let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) amap m nenv (tcref: TyconRef) = +let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) amap ad m nenv (tcref: TyconRef) = let isIL = tcref.IsILTycon let ucrefs = if isIL then [] else tcref.UnionCasesAsList |> List.map tcref.MakeNestedUnionCaseRef @@ -679,10 +845,14 @@ let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) | _ -> Item.UnqualifiedType [tcref])) else tab - if isILOrRequiredQualifiedAccess || List.isEmpty ucrefs then - tab - else - AddUnionCases2 bulkAddMode tab ucrefs + + let tab = + if isILOrRequiredQualifiedAccess || List.isEmpty ucrefs then + tab + else + AddUnionCases2 bulkAddMode tab ucrefs + + tab let ePatItems = if isILOrRequiredQualifiedAccess || List.isEmpty ucrefs then @@ -690,17 +860,26 @@ let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) else AddUnionCases1 nenv.ePatItems ucrefs - { nenv with - eFieldLabels = eFieldLabels - eUnqualifiedItems = eUnqualifiedItems - ePatItems = ePatItems - eIndexedExtensionMembers = eIndexedExtensionMembers - eUnindexedExtensionMembers = eUnindexedExtensionMembers } + let nenv = + { nenv with + eFieldLabels = eFieldLabels + eUnqualifiedItems = eUnqualifiedItems + ePatItems = ePatItems + eIndexedExtensionMembers = eIndexedExtensionMembers + eUnindexedExtensionMembers = eUnindexedExtensionMembers } + + let nenv = + if TryFindFSharpBoolAttribute g g.attrib_AutoOpenAttribute tcref.Attribs = Some true && isStaticClass g tcref then + AddStaticContentOfTyconRefToNameEnv g amap ad m nenv tcref + else + nenv + + nenv /// Add a set of type definitions to the name resolution environment -let AddTyconRefsToNameEnv bulkAddMode ownDefinition g amap m root nenv tcrefs = +let AddTyconRefsToNameEnv bulkAddMode ownDefinition g amap ad m root nenv tcrefs = if isNil tcrefs then nenv else - let env = List.fold (AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition g amap m) nenv tcrefs + let env = List.fold (AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition g amap ad m) nenv tcrefs // Add most of the contents of the tycons en-masse, then flatten the tables if we're opening a module or namespace let tcrefs = Array.ofList tcrefs { env with @@ -799,7 +978,7 @@ and AddModuleOrNamespaceContentsToNameEnv (g: TcGlobals) amap (ad: AccessorDomai let tcref = modref.NestedTyconRef tycon if IsEntityAccessible amap m ad tcref then Some tcref else None) - let nenv = (nenv, tcrefs) ||> AddTyconRefsToNameEnv BulkAdd.Yes false g amap m false + let nenv = (nenv, tcrefs) ||> AddTyconRefsToNameEnv BulkAdd.Yes false g amap ad m false let vrefs = mty.AllValsAndMembers.ToList() |> List.choose (fun x -> if IsAccessible ad x.Accessibility then TryMkValRefInModRef modref x else None) @@ -817,8 +996,14 @@ and AddModuleOrNamespaceContentsToNameEnv (g: TcGlobals) amap (ad: AccessorDomai // open M1 // // The list contains [M1b; M1a] -and AddModulesAndNamespacesContentsToNameEnv g amap ad m root nenv modrefs = - (modrefs, nenv) ||> List.foldBack (fun modref acc -> AddModuleOrNamespaceContentsToNameEnv g amap ad m root acc modref) +and AddEntitiesContentsToNameEnv g amap ad m root nenv modrefs = + (modrefs, nenv) ||> List.foldBack (fun modref acc -> AddEntityContentsToNameEnv g amap ad m root acc modref) + +and AddEntityContentsToNameEnv g amap ad m root nenv (modref: EntityRef) = + if modref.IsModuleOrNamespace then + AddModuleOrNamespaceContentsToNameEnv g amap ad m root nenv modref + else + AddStaticContentOfTyconRefToNameEnv g amap ad m nenv modref /// Add a single modules or namespace to the name resolution environment let AddModuleOrNamespaceRefToNameEnv g amap m root ad nenv (modref: EntityRef) = @@ -910,18 +1095,13 @@ let AddResults res1 res2 = let NoResultsOrUsefulErrors = Result [] -/// Indicates if we only need one result or all possible results from a resolution. -[] -type ResultCollectionSettings = -| AllResults -| AtMostOneResult - let rec CollectResults f = function | [] -> NoResultsOrUsefulErrors | [h] -> OneResult (f h) | h :: t -> AddResults (OneResult (f h)) (CollectResults f t) -let rec CollectAtMostOneResult f = function +let rec CollectAtMostOneResult f inputs = + match inputs with | [] -> NoResultsOrUsefulErrors | [h] -> OneResult (f h) | h :: t -> @@ -1257,7 +1437,7 @@ type FormatStringCheckContext = type ITypecheckResultsSink = abstract NotifyEnvWithScope: range * NameResolutionEnv * AccessorDomain -> unit abstract NotifyExprHasType: pos * TType * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range -> unit - abstract NotifyNameResolution: pos * Item * Item * TyparInst * ItemOccurence * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range * bool -> unit + abstract NotifyNameResolution: pos * item: Item * itemMethodGroup: Item * TyparInst * ItemOccurence * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range * replace: bool -> unit abstract NotifyFormatSpecifierLocation: range * int -> unit abstract NotifyOpenDeclaration: OpenDeclaration -> unit abstract CurrentSourceText: ISourceText option @@ -1828,13 +2008,16 @@ let CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities //------------------------------------------------------------------------- /// Perform name resolution for an identifier which must resolve to be a namespace or module. -let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQualified (nenv: NameResolutionEnv) ad (id: Ident) (rest: Ident list) isOpenDecl = +let rec ResolveLongIndentAsModuleOrNamespaceOrStaticClass sink (atMostOne: ResultCollectionSettings) (amap: Import.ImportMap) m allowStaticClasses first fullyQualified (nenv: NameResolutionEnv) ad (id:Ident) (rest: Ident list) isOpenDecl = + + // If the selected language version doesn't support open static classes then turn them off. + let allowStaticClasses = allowStaticClasses && amap.g.langVersion.SupportsFeature LanguageFeature.OpenStaticClasses if first && id.idText = MangledGlobalName then match rest with | [] -> error (Error(FSComp.SR.nrGlobalUsedOnlyAsFirstName(), id.idRange)) | id2 :: rest2 -> - ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m false FullyQualified nenv ad id2 rest2 isOpenDecl + ResolveLongIndentAsModuleOrNamespaceOrStaticClass sink atMostOne amap m allowStaticClasses false FullyQualified nenv ad id2 rest2 isOpenDecl else let moduleOrNamespaces = nenv.ModulesAndNamespaces fullyQualified let namespaceNotFound = lazy( @@ -1847,6 +2030,8 @@ let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQu UndefinedName(0, FSComp.SR.undefinedNameNamespaceOrModule, id, suggestModulesAndNamespaces)) + // Avoid generating the same error and name suggestion thunk twice It's not clear this is necessary + // since it's just saving an allocation. let mutable moduleNotFoundErrorCache = None let moduleNotFound (modref: ModuleOrNamespaceRef) (mty: ModuleOrNamespaceType) (id: Ident) depth = match moduleNotFoundErrorCache with @@ -1867,36 +2052,69 @@ let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQu let occurence = if isOpenDecl then ItemOccurence.Open else ItemOccurence.Use CallNameResolutionSink sink (m, nenv, item, item, emptyTyparInst, occurence, nenv.DisplayEnv, ad) - match moduleOrNamespaces.TryGetValue id.idText with - | true, modrefs -> + let erefs = + let modrefs = + match moduleOrNamespaces.TryGetValue id.idText with + | true, modrefs -> modrefs + | _ -> [] + + let tcrefs = + if allowStaticClasses then + LookupTypeNameInEnvNoArity fullyQualified id.idText nenv |> List.filter (isStaticClass amap.g) + else [] + + modrefs @ tcrefs + + if not erefs.IsEmpty then /// Look through the sub-namespaces and/or modules - let rec look depth (modref: ModuleOrNamespaceRef) (mty: ModuleOrNamespaceType) (lid: Ident list) = + let rec look depth allowStaticClasses (modref: ModuleOrNamespaceRef) (lid: Ident list) = + let mty = modref.ModuleOrNamespaceType match lid with - | [] -> success (depth, modref, mty) - | id :: rest -> - match mty.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with - | true, mspec -> - let subref = modref.NestedTyconRef mspec - if IsEntityAccessible amap m ad subref then - notifyNameResolution subref id.idRange - look (depth+1) subref mspec.ModuleOrNamespaceType rest - else - moduleNotFound modref mty id depth - | _ -> moduleNotFound modref mty id depth - + | [] -> + success [ (depth, modref, mty) ] - modrefs |> CollectResults2 atMostOne (fun modref -> - if IsEntityAccessible amap m ad modref then - notifyNameResolution modref id.idRange - look 1 modref modref.ModuleOrNamespaceType rest + | id :: rest -> + let especs = + let mspecs = + match mty.ModulesAndNamespacesByDemangledName.TryGetValue id.idText with + | true, res -> [res] + | _ -> [] + let tspecs = + if allowStaticClasses then + LookupTypeNameInEntityNoArity id.idRange id.idText mty + |> List.filter (modref.NestedTyconRef >> isStaticClass amap.g) + else [] + mspecs @ tspecs + + if not especs.IsEmpty then + especs + |> List.map (fun espec -> + let subref = modref.NestedTyconRef espec + if IsEntityAccessible amap m ad subref then + notifyNameResolution subref id.idRange + let allowStaticClasses = allowStaticClasses && (subref.IsModuleOrNamespace || isStaticClass amap.g subref) + look (depth+1) allowStaticClasses subref rest + else + moduleNotFound modref mty id depth) + |> List.reduce AddResults + else + moduleNotFound modref mty id depth + + erefs + |> List.map (fun eref -> + if IsEntityAccessible amap m ad eref then + notifyNameResolution eref id.idRange + let allowStaticClasses = allowStaticClasses && (eref.IsModuleOrNamespace || isStaticClass amap.g eref) + look 1 allowStaticClasses eref rest else raze (namespaceNotFound.Force())) - | _ -> raze (namespaceNotFound.Force()) - + |> List.reduce AddResults + else + raze (namespaceNotFound.Force()) // Note - 'rest' is annotated due to a bug currently in Unity (see: https://github.com/dotnet/fsharp/pull/7427) let ResolveLongIndentAsModuleOrNamespaceThen sink atMostOne amap m fullyQualified (nenv: NameResolutionEnv) ad id (rest: Ident list) isOpenDecl f = - match ResolveLongIndentAsModuleOrNamespace sink ResultCollectionSettings.AllResults amap m true fullyQualified nenv ad id [] isOpenDecl with + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass sink ResultCollectionSettings.AllResults amap m false true fullyQualified nenv ad id [] isOpenDecl with | Result modrefs -> match rest with | [] -> error(Error(FSComp.SR.nrUnexpectedEmptyLongId(), id.idRange)) @@ -1944,126 +2162,6 @@ let ResolveObjectConstructor (ncenv: NameResolver) edenv m ad ty = // Bind the "." notation (member lookup or lookup in a type) //------------------------------------------------------------------------- -/// Query the declared properties of a type (including inherited properties) -let IntrinsicPropInfosOfTypeInScope (infoReader:InfoReader) optFilter ad findFlag m ty = - let g = infoReader.g - let amap = infoReader.amap - let pinfos = GetIntrinsicPropInfoSetsOfType infoReader optFilter ad AllowMultiIntfInstantiations.Yes findFlag m ty - let pinfos = pinfos |> ExcludeHiddenOfPropInfos g amap m - pinfos - -/// Select from a list of extension properties -let SelectPropInfosFromExtMembers (infoReader:InfoReader) ad optFilter declaringTy m extMemInfos = - let g = infoReader.g - let amap = infoReader.amap - // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers, hence setify. - let seen = HashSet(ExtensionMember.Comparer g) - let propCollector = new PropertyCollector(g, amap, m, declaringTy, optFilter, ad) - for emem in extMemInfos do - if seen.Add emem then - match emem with - | FSExtMem (vref, _pri) -> - match vref.MemberInfo with - | None -> () - | Some membInfo -> propCollector.Collect(membInfo, vref) - | ILExtMem _ -> - // No extension properties coming from .NET - () - propCollector.Close() - -/// Query the available extension properties of a type (including extension properties for inherited types) -let ExtensionPropInfosOfTypeInScope collectionSettings (infoReader:InfoReader) (nenv: NameResolutionEnv) optFilter ad m ty = - let g = infoReader.g - - let extMemsDangling = SelectPropInfosFromExtMembers infoReader ad optFilter ty m nenv.eUnindexedExtensionMembers - - if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil extMemsDangling) then - extMemsDangling - else - let extMemsFromHierarchy = - infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes,m,ty) - |> List.collect (fun ty -> - if isAppTy g ty then - let tcref = tcrefOfAppTy g ty - let extMemInfos = nenv.eIndexedExtensionMembers.Find tcref - SelectPropInfosFromExtMembers infoReader ad optFilter ty m extMemInfos - else []) - - extMemsDangling @ extMemsFromHierarchy - -/// Get all the available properties of a type (both intrinsic and extension) -let AllPropInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad findFlag m ty = - IntrinsicPropInfosOfTypeInScope infoReader optFilter ad findFlag m ty - @ ExtensionPropInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad m ty - -/// Get the available methods of a type (both declared and inherited) -let IntrinsicMethInfosOfType (infoReader:InfoReader) optFilter ad allowMultiIntfInst findFlag m ty = - let g = infoReader.g - let amap = infoReader.amap - let minfos = GetIntrinsicMethInfoSetsOfType infoReader optFilter ad allowMultiIntfInst findFlag m ty - let minfos = minfos |> ExcludeHiddenOfMethInfos g amap m - minfos - -/// Select from a list of extension methods -let SelectMethInfosFromExtMembers (infoReader: InfoReader) optFilter apparentTy m extMemInfos = - let g = infoReader.g - // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers - let seen = HashSet(ExtensionMember.Comparer g) - [ - for emem in extMemInfos do - if seen.Add emem then - match emem with - | FSExtMem (vref, pri) -> - match vref.MemberInfo with - | None -> () - | Some membInfo -> - match TrySelectMemberVal g optFilter apparentTy (Some pri) membInfo vref with - | Some m -> yield m - | _ -> () - | ILExtMem (actualParent, minfo, pri) when (match optFilter with None -> true | Some nm -> nm = minfo.LogicalName) -> - // Make a reference to the type containing the extension members - match minfo with - | ILMeth(_, ilminfo, _) -> - yield (MethInfo.CreateILExtensionMeth (infoReader.amap, m, apparentTy, actualParent, Some pri, ilminfo.RawMetadata)) - // F#-defined IL-style extension methods are not seen as extension methods in F# code - | FSMeth(g, _, vref, _) -> - yield (FSMeth(g, apparentTy, vref, Some pri)) -#if !NO_EXTENSIONTYPING - // // Provided extension methods are not yet supported - | ProvidedMeth(amap, providedMeth, _, m) -> - yield (ProvidedMeth(amap, providedMeth, Some pri, m)) -#endif - | DefaultStructCtor _ -> - () - | _ -> () - ] - -/// Query the available extension properties of a methods (including extension methods for inherited types) -let ExtensionMethInfosOfTypeInScope (collectionSettings:ResultCollectionSettings) (infoReader:InfoReader) (nenv: NameResolutionEnv) optFilter m ty = - let extMemsDangling = SelectMethInfosFromExtMembers infoReader optFilter ty m nenv.eUnindexedExtensionMembers - if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil extMemsDangling) then - extMemsDangling - else - let extMemsFromHierarchy = - infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes,m,ty) - |> List.collect (fun ty -> - let g = infoReader.g - if isAppTy g ty then - let tcref = tcrefOfAppTy g ty - let extValRefs = nenv.eIndexedExtensionMembers.Find tcref - SelectMethInfosFromExtMembers infoReader optFilter ty m extValRefs - else []) - extMemsDangling @ extMemsFromHierarchy - -/// Get all the available methods of a type (both intrinsic and extension) -let AllMethInfosOfTypeInScope collectionSettings infoReader nenv optFilter ad findFlag m ty = - let intrinsic = IntrinsicMethInfosOfType infoReader optFilter ad AllowMultiIntfInstantiations.Yes findFlag m ty - if collectionSettings = ResultCollectionSettings.AtMostOneResult && not (isNil intrinsic) then - intrinsic - else - intrinsic @ ExtensionMethInfosOfTypeInScope collectionSettings infoReader nenv optFilter m ty - - /// Used to report an error condition where name resolution failed due to an indeterminate type exception IndeterminateType of range @@ -2411,6 +2509,15 @@ let ChooseTyconRefInExpr (ncenv: NameResolver, m, ad, nenv, id: Ident, typeNameR /// that may represent further actions, e.g. further lookups. let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified m ad nenv (typeNameResInfo: TypeNameResolutionInfo) (id: Ident) (rest: Ident list) isOpenDecl = let resInfo = ResolutionInfo.Empty + let canSuggestThisItem (item:Item) = + // All items can be suggested except nameof when it comes from FSharp.Core.dll and the nameof feature is not enabled + match item with + | Item.Value v -> + let isNameOfOperator = valRefEq ncenv.g ncenv.g.nameof_vref v + if isNameOfOperator && not (ncenv.g.langVersion.SupportsFeature LanguageFeature.NameOf) then false + else true + | _ -> true + if first && id.idText = MangledGlobalName then match rest with | [] -> @@ -2445,7 +2552,16 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified | Exception e -> typeError := Some e; None | true, res -> - Some (FreshenUnqualifiedItem ncenv m res, []) + let fresh = FreshenUnqualifiedItem ncenv m res + match fresh with + | Item.Value value -> + let isNameOfOperator = valRefEq ncenv.g ncenv.g.nameof_vref value + if isNameOfOperator && not (ncenv.languageSupportsNameOf) then + // Do not resolve `nameof` if the feature is unsupported, even if it is FSharp.Core + None + else + Some (fresh, []) + | _ -> Some (fresh, []) | _ -> None @@ -2476,7 +2592,8 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified | _ -> let suggestNamesAndTypes (addToBuffer: string -> unit) = for e in nenv.eUnqualifiedItems do - addToBuffer e.Value.DisplayName + if canSuggestThisItem e.Value then + addToBuffer e.Value.DisplayName for e in nenv.TyconsByDemangledNameAndArity fullyQualified do if IsEntityAccessible ncenv.amap m ad e.Value then @@ -2572,7 +2689,8 @@ let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified addToBuffer e.Value.DisplayName for e in nenv.eUnqualifiedItems do - addToBuffer e.Value.DisplayName + if canSuggestThisItem e.Value then + addToBuffer e.Value.DisplayName match innerSearch with | Exception (UndefinedName(0, _, id1, suggestionsF)) when Range.equals id.idRange id1.idRange -> @@ -3971,6 +4089,7 @@ let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionE ResolvePartialLongIdentInModuleOrNamespace ncenv nenv isApplicableMeth m ad modref rest allowObsolete else []) + // Look for values called 'id' that accept the dot-notation let values, isItemVal = (match nenv.eUnqualifiedItems.TryGetValue id with @@ -4131,6 +4250,7 @@ and ResolvePartialLongIdentToClassOrRecdFieldsImpl (ncenv: NameResolver) (nenv: ResolvePartialLongIdentInModuleOrNamespaceForRecordFields ncenv nenv m ad modref rest allowObsolete else []) + let qualifiedFields = match rest with | [] -> diff --git a/src/fsharp/NameResolution.fsi b/src/fsharp/NameResolution.fsi index 8ec9caedc76..a1567ed43bf 100755 --- a/src/fsharp/NameResolution.fsi +++ b/src/fsharp/NameResolution.fsi @@ -22,6 +22,7 @@ type NameResolver = member InfoReader : InfoReader member amap : ImportMap member g : TcGlobals + member languageSupportsNameOf : bool /// Get the active pattern elements defined in a module, if any. Cache in the slot in the module type. val ActivePatternElemsOfModuleOrNamespace : ModuleOrNamespaceRef -> NameMap @@ -186,7 +187,7 @@ val internal AddValRefToNameEnv : NameResolutionEnv -> ValRef val internal AddActivePatternResultTagsToNameEnv : ActivePatternInfo -> NameResolutionEnv -> TType -> range -> NameResolutionEnv /// Add a list of type definitions to the name resolution environment -val internal AddTyconRefsToNameEnv : BulkAdd -> bool -> TcGlobals -> ImportMap -> range -> bool -> NameResolutionEnv -> TyconRef list -> NameResolutionEnv +val internal AddTyconRefsToNameEnv : BulkAdd -> bool -> TcGlobals -> ImportMap -> AccessorDomain -> range -> bool -> NameResolutionEnv -> TyconRef list -> NameResolutionEnv /// Add an F# exception definition to the name resolution environment val internal AddExceptionDeclsToNameEnv : BulkAdd -> NameResolutionEnv -> TyconRef -> NameResolutionEnv @@ -201,7 +202,7 @@ val internal AddModuleOrNamespaceRefsToNameEnv : TcGlobals -> val internal AddModuleOrNamespaceRefToNameEnv : TcGlobals -> ImportMap -> range -> bool -> AccessorDomain -> NameResolutionEnv -> ModuleOrNamespaceRef -> NameResolutionEnv /// Add a list of modules or namespaces to the name resolution environment -val internal AddModulesAndNamespacesContentsToNameEnv : TcGlobals -> ImportMap -> AccessorDomain -> range -> bool -> NameResolutionEnv -> ModuleOrNamespaceRef list -> NameResolutionEnv +val internal AddEntitiesContentsToNameEnv : TcGlobals -> ImportMap -> AccessorDomain -> range -> bool -> NameResolutionEnv -> ModuleOrNamespaceRef list -> NameResolutionEnv /// A flag which indicates if it is an error to have two declared type parameters with identical names /// in the name resolution environment. @@ -468,8 +469,8 @@ type PermitDirectReferenceToGeneratedType = | Yes | No -/// Resolve a long identifier to a namespace or module. -val internal ResolveLongIndentAsModuleOrNamespace : TcResultsSink -> ResultCollectionSettings -> Import.ImportMap -> range -> bool -> FullyQualifiedFlag -> NameResolutionEnv -> AccessorDomain -> Ident -> Ident list -> isOpenDecl: bool -> ResultOrException<(int * ModuleOrNamespaceRef * ModuleOrNamespaceType) list > +/// Resolve a long identifier to a namespace, module or static class. +val internal ResolveLongIndentAsModuleOrNamespaceOrStaticClass : TcResultsSink -> ResultCollectionSettings -> Import.ImportMap -> range -> allowStaticClasses: bool -> first: bool -> FullyQualifiedFlag -> NameResolutionEnv -> AccessorDomain -> Ident -> Ident list -> isOpenDecl: bool -> ResultOrException<(int * ModuleOrNamespaceRef * ModuleOrNamespaceType) list > /// Resolve a long identifier to an object constructor. val internal ResolveObjectConstructor : NameResolver -> DisplayEnv -> range -> AccessorDomain -> TType -> ResultOrException diff --git a/src/fsharp/PostInferenceChecks.fs b/src/fsharp/PostInferenceChecks.fs index d6ad0cdf64e..4d8f05b5a01 100644 --- a/src/fsharp/PostInferenceChecks.fs +++ b/src/fsharp/PostInferenceChecks.fs @@ -282,7 +282,8 @@ let GetLimitValByRef cenv env m v = { scope = scope; flags = flags } let LimitVal cenv (v: Val) limit = - cenv.limitVals.[v.Stamp] <- limit + if not v.IgnoresByrefScope then + cenv.limitVals.[v.Stamp] <- limit let BindVal cenv env (v: Val) = //printfn "binding %s..." v.DisplayName @@ -697,6 +698,7 @@ and CheckValRef (cenv: cenv) (env: env) v m (context: PermitByRefExpr) = if isSpliceOperator cenv.g v then errorR(Error(FSComp.SR.chkNoFirstClassSplicing(), m)) if valRefEq cenv.g v cenv.g.addrof_vref then errorR(Error(FSComp.SR.chkNoFirstClassAddressOf(), m)) if valRefEq cenv.g v cenv.g.reraise_vref then errorR(Error(FSComp.SR.chkNoFirstClassRethrow(), m)) + if valRefEq cenv.g v cenv.g.nameof_vref then errorR(Error(FSComp.SR.chkNoFirstClassNameOf(), m)) // ByRefLike-typed values can only occur in permitting contexts if context.Disallow && isByrefLikeTy cenv.g m v.Type then diff --git a/src/fsharp/TastOps.fs b/src/fsharp/TastOps.fs index c638d9a864e..91a63819dab 100644 --- a/src/fsharp/TastOps.fs +++ b/src/fsharp/TastOps.fs @@ -22,6 +22,7 @@ open FSharp.Compiler.TcGlobals open FSharp.Compiler.Layout open FSharp.Compiler.Layout.TaggedTextOps open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Features #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping #endif @@ -3003,8 +3004,8 @@ let isByrefTyconRef (g: TcGlobals) (tcref: TyconRef) = let isByrefLikeTyconRef (g: TcGlobals) m (tcref: TyconRef) = tcref.CanDeref && match tcref.TryIsByRefLike with - | Some res -> res - | None -> + | ValueSome res -> res + | _ -> let res = isByrefTyconRef g tcref || (isStructTyconRef tcref && TyconRefHasAttribute g m g.attrib_IsByRefLikeAttribute tcref) @@ -3221,6 +3222,11 @@ let isSizeOfValRef g vref = // There is an internal version of typeof defined in prim-types.fs that needs to be detected || (g.compilingFslib && vref.LogicalName = "sizeof") +let isNameOfValRef g vref = + valRefEq g vref g.nameof_vref + // There is an internal version of nameof defined in prim-types.fs that needs to be detected + || (g.compilingFslib && vref.LogicalName = "nameof") + let isTypeDefOfValRef g vref = valRefEq g vref g.typedefof_vref // There is an internal version of typedefof defined in prim-types.fs that needs to be detected @@ -3246,6 +3252,16 @@ let (|TypeDefOfExpr|_|) g expr = | Expr.App (Expr.Val (vref, _, _), _, [ty], [], _) when isTypeDefOfValRef g vref -> Some ty | _ -> None +let (|NameOfExpr|_|) g expr = + match expr with + | Expr.App(Expr.Val(vref,_,_),_,[ty],[],_) when isNameOfValRef g vref -> Some ty + | _ -> None + +let (|SeqExpr|_|) g expr = + match expr with + | Expr.App(Expr.Val(vref,_,_),_,_,_,_) when valRefEq g vref g.seq_vref -> Some() + | _ -> None + //-------------------------------------------------------------------------- // DEBUG layout //--------------------------------------------------------------------------- @@ -5925,34 +5941,56 @@ let mkAndSimplifyMatch spBind exprm matchm ty tree targets = //------------------------------------------------------------------------- type Mutates = AddressOfOp | DefinitelyMutates | PossiblyMutates | NeverMutates -exception DefensiveCopyWarning of string * range +exception DefensiveCopyWarning of string * range let isRecdOrStructTyconRefAssumedImmutable (g: TcGlobals) (tcref: TyconRef) = tcref.CanDeref && not (isRecdOrUnionOrStructTyconRefDefinitelyMutable tcref) || - tyconRefEq g tcref g.decimal_tcr || + tyconRefEq g tcref g.decimal_tcr || tyconRefEq g tcref g.date_tcr -let isRecdOrStructTyconRefReadOnly (g: TcGlobals) m (tcref: TyconRef) = +let isTyconRefReadOnly g m (tcref: TyconRef) = tcref.CanDeref && - match tcref.TryIsReadOnly with - | Some res -> res - | None -> - let isImmutable = isRecdOrStructTyconRefAssumedImmutable g tcref - let hasAttrib = TyconRefHasAttribute g m g.attrib_IsReadOnlyAttribute tcref - let res = isImmutable || hasAttrib - tcref.SetIsReadOnly res + if + match tcref.TryIsReadOnly with + | ValueSome res -> res + | _ -> + let res = TyconRefHasAttribute g m g.attrib_IsReadOnlyAttribute tcref + tcref.SetIsReadOnly res + res + then true + else tcref.IsEnumTycon + +let isTyconRefAssumedReadOnly g (tcref: TyconRef) = + tcref.CanDeref && + match tcref.TryIsAssumedReadOnly with + | ValueSome res -> res + | _ -> + let res = isRecdOrStructTyconRefAssumedImmutable g tcref + tcref.SetIsAssumedReadOnly res res -let isRecdOrStructTyReadOnly (g: TcGlobals) m ty = +let isRecdOrStructTyconRefReadOnlyAux g m isInref (tcref: TyconRef) = + if isInref && tcref.IsILStructOrEnumTycon then + isTyconRefReadOnly g m tcref + else + isTyconRefReadOnly g m tcref || isTyconRefAssumedReadOnly g tcref + +let isRecdOrStructTyconRefReadOnly g m tcref = + isRecdOrStructTyconRefReadOnlyAux g m false tcref + +let isRecdOrStructTyReadOnlyAux (g: TcGlobals) m isInref ty = match tryDestAppTy g ty with | ValueNone -> false - | ValueSome tcref -> isRecdOrStructTyconRefReadOnly g m tcref + | ValueSome tcref -> isRecdOrStructTyconRefReadOnlyAux g m isInref tcref + +let isRecdOrStructTyReadOnly g m ty = + isRecdOrStructTyReadOnlyAux g m false ty -let CanTakeAddressOf g m ty mut = +let CanTakeAddressOf g m isInref ty mut = match mut with | NeverMutates -> true - | PossiblyMutates -> isRecdOrStructTyReadOnly g m ty + | PossiblyMutates -> isRecdOrStructTyReadOnlyAux g m isInref ty | DefinitelyMutates -> false | AddressOfOp -> true // you can take the address but you might get a (readonly) inref as a result @@ -5980,7 +6018,7 @@ let CanTakeAddressOfImmutableVal (g: TcGlobals) m (vref: ValRef) mut = // || valRefInThisAssembly g.compilingFslib vref // This is because we don't actually guarantee to generate static backing fields for all values like these, e.g. simple constants "let x = 1". // We always generate a static property but there is no field to take an address of - CanTakeAddressOf g m vref.Type mut + CanTakeAddressOf g m false vref.Type mut let MustTakeAddressOfVal (g: TcGlobals) (vref: ValRef) = vref.IsMutable && @@ -5992,7 +6030,7 @@ let MustTakeAddressOfByrefGet (g: TcGlobals) (vref: ValRef) = let CanTakeAddressOfByrefGet (g: TcGlobals) (vref: ValRef) mut = isInByrefTy g vref.Type && - CanTakeAddressOf g vref.Range (destByrefTy g vref.Type) mut + CanTakeAddressOf g vref.Range true (destByrefTy g vref.Type) mut let MustTakeAddressOfRecdField (rfref: RecdField) = // Static mutable fields must be private, hence we don't have to take their address @@ -6005,14 +6043,18 @@ let CanTakeAddressOfRecdFieldRef (g: TcGlobals) m (rfref: RecdFieldRef) tinst mu // We only do this if the field is defined in this assembly because we can't take addresses across assemblies for immutable fields entityRefInThisAssembly g.compilingFslib rfref.TyconRef && not rfref.RecdField.IsMutable && - CanTakeAddressOf g m (actualTyOfRecdFieldRef rfref tinst) mut + CanTakeAddressOf g m false (actualTyOfRecdFieldRef rfref tinst) mut let CanTakeAddressOfUnionFieldRef (g: TcGlobals) m (uref: UnionCaseRef) cidx tinst mut = // We only do this if the field is defined in this assembly because we can't take addresses across assemblies for immutable fields entityRefInThisAssembly g.compilingFslib uref.TyconRef && let rfref = uref.FieldByIndex cidx not rfref.IsMutable && - CanTakeAddressOf g m (actualTyOfUnionFieldRef uref cidx tinst) mut + CanTakeAddressOf g m false (actualTyOfUnionFieldRef uref cidx tinst) mut + +let mkDerefAddrExpr mAddrGet expr mExpr exprTy = + let v, _ = mkCompGenLocal mAddrGet "byrefReturn" exprTy + mkCompGenLet mExpr v expr (mkAddrGet mAddrGet (mkLocalValRef v)) /// Make the address-of expression and return a wrapper that adds any allocated locals at an appropriate scope. /// Also return a flag that indicates if the resulting pointer is a not a pointer where writing is allowed and will @@ -6150,8 +6192,12 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress // Take a defensive copy let tmp, _ = match mut with - | NeverMutates -> mkCompGenLocal m "copyOfStruct" ty + | NeverMutates -> mkCompGenLocal m "copyOfStruct" ty | _ -> mkMutableCompGenLocal m "copyOfStruct" ty + + // This local is special in that it ignore byref scoping rules. + tmp.SetIgnoresByrefScope() + let readonly = true let writeonly = false Some (tmp, expr), (mkValAddr m readonly (mkLocalValRef tmp)), readonly, writeonly @@ -8569,6 +8615,7 @@ let IsSimpleSyntacticConstantExpr g inputExpr = | UncheckedDefaultOfExpr g _ | SizeOfExpr g _ | TypeOfExpr g _ -> true + | NameOfExpr g _ when g.langVersion.SupportsFeature LanguageFeature.NameOf -> true // All others are not simple constant expressions | _ -> false @@ -8939,3 +8986,19 @@ let isThreadOrContextStatic g attrs = let mkUnitDelayLambda (g: TcGlobals) m e = let uv, _ = mkCompGenLocal m "unitVar" g.unit_ty mkLambda m uv (e, tyOfExpr g e) + + +let isStaticClass (g:TcGlobals) (x: EntityRef) = + not x.IsModuleOrNamespace && + x.TyparsNoRange.IsEmpty && + ((x.IsILTycon && + x.ILTyconRawMetadata.IsSealed && + x.ILTyconRawMetadata.IsAbstract) +#if !NO_EXTENSIONTYPING + || (x.IsProvided && + match x.TypeReprInfo with + | TProvidedTypeExtensionPoint info -> info.IsSealed && info.IsAbstract + | _ -> false) +#endif + || (not x.IsILTycon && not x.IsProvided && HasFSharpAttribute g g.attrib_AbstractClassAttribute x.Attribs)) && + not (HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute x.Attribs) diff --git a/src/fsharp/TastOps.fsi b/src/fsharp/TastOps.fsi index b0743de8536..6119007d52c 100755 --- a/src/fsharp/TastOps.fsi +++ b/src/fsharp/TastOps.fsi @@ -369,6 +369,9 @@ exception DefensiveCopyWarning of string * range type Mutates = AddressOfOp | DefinitelyMutates | PossiblyMutates | NeverMutates +/// Helper to create an expression that dereferences an address. +val mkDerefAddrExpr: mAddrGet: range -> expr: Expr -> mExpr: range -> exprTy: TType -> Expr + /// Helper to take the address of an expression val mkExprAddrOfExprAux : TcGlobals -> bool -> bool -> Mutates -> Expr -> ValRef option -> range -> (Val * Expr) option * Expr * bool * bool @@ -2240,6 +2243,8 @@ val (|EnumExpr|_|) : TcGlobals -> Expr -> Expr option val (|TypeOfExpr|_|) : TcGlobals -> Expr -> TType option val (|TypeDefOfExpr|_|) : TcGlobals -> Expr -> TType option +val (|NameOfExpr|_|) : TcGlobals -> Expr -> TType option +val (|SeqExpr|_|) : TcGlobals -> Expr -> unit option val EvalLiteralExprOrAttribArg: TcGlobals -> Expr -> Expr @@ -2302,3 +2307,4 @@ val isThreadOrContextStatic: TcGlobals -> Attrib list -> bool val mkUnitDelayLambda: TcGlobals -> range -> Expr -> Expr +val isStaticClass: g: TcGlobals -> tcref: TyconRef -> bool \ No newline at end of file diff --git a/src/fsharp/TcGlobals.fs b/src/fsharp/TcGlobals.fs index 1aa14c5794d..38b1e7d1d6d 100755 --- a/src/fsharp/TcGlobals.fs +++ b/src/fsharp/TcGlobals.fs @@ -22,6 +22,7 @@ open FSharp.Compiler.Range open FSharp.Compiler.Ast open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming +open FSharp.Compiler.Features open Internal.Utilities @@ -180,8 +181,8 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d // The helper to find system types amongst referenced DLLs tryFindSysTypeCcu, emitDebugInfoInQuotations: bool, noDebugData: bool, - pathMap: PathMap) = - + pathMap: PathMap, langVersion: LanguageVersion) = + let vara = NewRigidTypar "a" envRange let varb = NewRigidTypar "b" envRange let varc = NewRigidTypar "c" envRange @@ -239,7 +240,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d // Search for a type. If it is not found, leave a dangling CCU reference with some useful diagnostic information should // the type actually be dereferenced let findSysTypeCcu path typeName = - match tryFindSysTypeCcu path typeName with + match tryFindSysTypeCcu path typeName with | None -> CcuThunk.CreateDelayed(dummyAssemblyNameCarryingUsefulErrorInformation path typeName) | Some ccu -> ccu @@ -664,6 +665,8 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d let v_typeof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "typeof" , None , Some "TypeOf" , [vara], ([], v_system_Type_ty)) let v_methodhandleof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "methodhandleof" , None , Some "MethodHandleOf", [vara;varb], ([[varaTy --> varbTy]], v_system_RuntimeMethodHandle_ty)) let v_sizeof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "sizeof" , None , Some "SizeOf" , [vara], ([], v_int_ty)) + let v_nameof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "nameof" , None , Some "NameOf" , [vara], ([[varaTy]], v_string_ty)) + let v_unchecked_defaultof_info = makeIntrinsicValRef(fslib_MFOperatorsUnchecked_nleref, "defaultof" , None , Some "DefaultOf", [vara], ([], varaTy)) let v_typedefof_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "typedefof" , None , Some "TypeDefOf", [vara], ([], v_system_Type_ty)) let v_range_op_info = makeIntrinsicValRef(fslib_MFOperators_nleref, "op_Range" , None , None , [vara], ([[varaTy];[varaTy]], mkSeqTy varaTy)) @@ -902,6 +905,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member __.emitDebugInfoInQuotations = emitDebugInfoInQuotations member __.directoryToResolveRelativePaths= directoryToResolveRelativePaths member __.pathMap = pathMap + member __.langVersion = langVersion member __.unionCaseRefEq x y = primUnionCaseRefEq compilingFslib fslibCcu x y member __.valRefEq x y = primValRefEq compilingFslib fslibCcu x y member __.fslibCcu = fslibCcu @@ -1331,6 +1335,7 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member val methodhandleof_vref = ValRefForIntrinsic v_methodhandleof_info member val typeof_vref = ValRefForIntrinsic v_typeof_info member val sizeof_vref = ValRefForIntrinsic v_sizeof_info + member val nameof_vref = ValRefForIntrinsic v_nameof_info member val typedefof_vref = ValRefForIntrinsic v_typedefof_info member val enum_vref = ValRefForIntrinsic v_enum_operator_info member val enumOfValue_vref = ValRefForIntrinsic v_enumOfValue_info @@ -1358,15 +1363,15 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d member val unbox_fast_vref = ValRefForIntrinsic v_unbox_fast_info member val istype_vref = ValRefForIntrinsic v_istype_info member val istype_fast_vref = ValRefForIntrinsic v_istype_fast_info - member val query_source_vref = ValRefForIntrinsic v_query_source_info - member val query_value_vref = ValRefForIntrinsic v_query_value_info - member val query_run_value_vref = ValRefForIntrinsic v_query_run_value_info - member val query_run_enumerable_vref = ValRefForIntrinsic v_query_run_enumerable_info - member val query_for_vref = ValRefForIntrinsic v_query_for_value_info - member val query_yield_vref = ValRefForIntrinsic v_query_yield_value_info - member val query_yield_from_vref = ValRefForIntrinsic v_query_yield_from_value_info - member val query_select_vref = ValRefForIntrinsic v_query_select_value_info - member val query_where_vref = ValRefForIntrinsic v_query_where_value_info + member val query_source_vref = ValRefForIntrinsic v_query_source_info + member val query_value_vref = ValRefForIntrinsic v_query_value_info + member val query_run_value_vref = ValRefForIntrinsic v_query_run_value_info + member val query_run_enumerable_vref = ValRefForIntrinsic v_query_run_enumerable_info + member val query_for_vref = ValRefForIntrinsic v_query_for_value_info + member val query_yield_vref = ValRefForIntrinsic v_query_yield_value_info + member val query_yield_from_vref = ValRefForIntrinsic v_query_yield_from_value_info + member val query_select_vref = ValRefForIntrinsic v_query_select_value_info + member val query_where_vref = ValRefForIntrinsic v_query_where_value_info member val query_zero_vref = ValRefForIntrinsic v_query_zero_value_info member __.seq_collect_info = v_seq_collect_info diff --git a/src/fsharp/TypeChecker.fs b/src/fsharp/TypeChecker.fs index 091b2f68738..5cc848e5ab1 100644 --- a/src/fsharp/TypeChecker.fs +++ b/src/fsharp/TypeChecker.fs @@ -36,6 +36,7 @@ open FSharp.Compiler.ConstraintSolver open FSharp.Compiler.NameResolution open FSharp.Compiler.PrettyNaming open FSharp.Compiler.InfoReader +open FSharp.Compiler.Features #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping @@ -357,7 +358,7 @@ let AddLocalExnDefnAndReport tcSink scopem env (exnc: Tycon) = /// Add a list of type definitions to TcEnv let AddLocalTyconRefs ownDefinition g amap m tcrefs env = if isNil tcrefs then env else - { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.No ownDefinition g amap m false env.eNameResEnv tcrefs } + { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.No ownDefinition g amap env.eAccessRights m false env.eNameResEnv tcrefs } /// Add a list of type definitions to TcEnv let AddLocalTycons g amap m (tycons: Tycon list) env = @@ -370,11 +371,11 @@ let AddLocalTyconsAndReport tcSink scopem g amap m tycons env = CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) env -/// Adjust the TcEnv to account for opening the set of modules and namespaces implied by an `open` declaration -let OpenModulesOrNamespaces tcSink g amap scopem root env mvvs openDeclaration = +/// Adjust the TcEnv to account for opening the set of modules, namespaces or static classes implied by an `open` declaration +let OpenEntities tcSink g amap scopem root env mvvs openDeclaration = let env = if isNil mvvs then env else - { env with eNameResEnv = AddModulesAndNamespacesContentsToNameEnv g amap env.eAccessRights scopem root env.eNameResEnv mvvs } + { env with eNameResEnv = AddEntitiesContentsToNameEnv g amap env.eAccessRights scopem root env.eNameResEnv mvvs } CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) CallOpenDeclarationSink tcSink openDeclaration env @@ -406,7 +407,7 @@ let AddNonLocalCcu g amap scopem env assemblyName (ccu: CcuThunk, internalsVisib let env = AddRootModuleOrNamespaceRefs g amap scopem env modrefs let env = if isNil tcrefs then env else - { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.Yes false g amap scopem true env.eNameResEnv tcrefs } + { env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.Yes false g amap env.eAccessRights scopem true env.eNameResEnv tcrefs } env /// Adjust the TcEnv to account for a fully processed "namespace" declaration in thie file @@ -417,7 +418,7 @@ let AddLocalRootModuleOrNamespace tcSink g amap scopem env (mtyp: ModuleOrNamesp let tcrefs = mtyp.TypeAndExceptionDefinitions |> List.map mkLocalTyconRef let env = AddRootModuleOrNamespaceRefs g amap scopem env modrefs let env = { env with - eNameResEnv = if isNil tcrefs then env.eNameResEnv else AddTyconRefsToNameEnv BulkAdd.No false g amap scopem true env.eNameResEnv tcrefs + eNameResEnv = if isNil tcrefs then env.eNameResEnv else AddTyconRefsToNameEnv BulkAdd.No false g amap env.eAccessRights scopem true env.eNameResEnv tcrefs eUngeneralizableItems = addFreeItemOfModuleTy mtyp env.eUngeneralizableItems } CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) env @@ -644,11 +645,11 @@ let ImplicitlyOpenOwnNamespace tcSink g amap scopem enclosingNamespacePath env = match enclosingNamespacePathToOpen with | id :: rest -> let ad = env.eAccessRights - match ResolveLongIndentAsModuleOrNamespace tcSink ResultCollectionSettings.AllResults amap scopem true OpenQualified env.eNameResEnv ad id rest true with + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass tcSink ResultCollectionSettings.AllResults amap scopem true true OpenQualified env.eNameResEnv ad id rest true with | Result modrefs -> let modrefs = List.map p23 modrefs let openDecl = OpenDeclaration.Create (enclosingNamespacePathToOpen, modrefs, scopem, true) - OpenModulesOrNamespaces tcSink g amap scopem false env modrefs openDecl + OpenEntities tcSink g amap scopem false env modrefs openDecl | Exception _ -> env | _ -> env @@ -846,6 +847,10 @@ let UnifyUnitType cenv (env: TcEnv) m ty expr = false +let TryUnifyUnitTypeWithoutWarning cenv (env:TcEnv) m ty = + let denv = env.DisplayEnv + AddCxTypeEqualsTypeUndoIfFailedOrWarnings denv cenv.css m ty cenv.g.unit_ty + // Logically extends System.AttributeTargets module AttributeTargets = let FieldDecl = AttributeTargets.Field ||| AttributeTargets.Property @@ -3389,8 +3394,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr let currentExpr, enumElemTy = // Implicitly dereference byref for expr 'for x in ...' if isByrefTy cenv.g enumElemTy then - let v, _ = mkCompGenLocal m "byrefReturn" enumElemTy - let expr = mkCompGenLet currentExpr.Range v currentExpr (mkAddrGet m (mkLocalValRef v)) + let expr = mkDerefAddrExpr m currentExpr currentExpr.Range enumElemTy expr, destByrefTy cenv.g enumElemTy else currentExpr, enumElemTy @@ -3513,35 +3517,84 @@ let (|ExprAsPat|_|) (f: SynExpr) = None | _ -> None +/// Check if a computation or sequence expression is syntactically free of 'yield' (though not yield!) +let YieldFree cenv expr = + if cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield then + + // Implement yield free logic for F# Language including the LanguageFeature.ImplicitYield + let rec YieldFree expr = + match expr with + | SynExpr.Sequential (_, _, e1, e2, _) -> + YieldFree e1 && YieldFree e2 + + | SynExpr.IfThenElse (_, e2, e3opt, _, _, _, _) -> + YieldFree e2 && Option.forall YieldFree e3opt + + | SynExpr.TryWith (e1, _, clauses, _, _, _, _) -> + YieldFree e1 && clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | (SynExpr.Match (_, _, clauses, _) | SynExpr.MatchBang (_, _, clauses, _)) -> + clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | SynExpr.For (_, _, _, _, _, body, _) + | SynExpr.TryFinally (body, _, _, _, _) + | SynExpr.LetOrUse (_, _, _, body, _) + | SynExpr.While (_, _, body, _) + | SynExpr.ForEach (_, _, _, _, _, body, _) -> + YieldFree body + + | SynExpr.LetOrUseBang(_, _, _, _, _, body, _) -> + YieldFree body + + | SynExpr.YieldOrReturn((true, _), _, _) -> false + + | _ -> true + + YieldFree expr + else + // Implement yield free logic for F# Language without the LanguageFeature.ImplicitYield + let rec YieldFree expr = + match expr with + | SynExpr.Sequential (_, _, e1, e2, _) -> + YieldFree e1 && YieldFree e2 + + | SynExpr.IfThenElse (_, e2, e3opt, _, _, _, _) -> + YieldFree e2 && Option.forall YieldFree e3opt + + | SynExpr.TryWith (e1, _, clauses, _, _, _, _) -> + YieldFree e1 && clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | (SynExpr.Match (_, _, clauses, _) | SynExpr.MatchBang (_, _, clauses, _)) -> + clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) + + | SynExpr.For (_, _, _, _, _, body, _) + | SynExpr.TryFinally (body, _, _, _, _) + | SynExpr.LetOrUse (_, _, _, body, _) + | SynExpr.While (_, _, body, _) + | SynExpr.ForEach (_, _, _, _, _, body, _) -> + YieldFree body + + | SynExpr.LetOrUseBang _ + | SynExpr.YieldOrReturnFrom _ + | SynExpr.YieldOrReturn _ + | SynExpr.ImplicitZero _ + | SynExpr.Do _ -> false + + | _ -> true + + YieldFree expr + + /// Determine if a syntactic expression inside 'seq { ... }' or '[...]' counts as a "simple sequence /// of semicolon separated values". For example [1;2;3]. /// 'acceptDeprecated' is true for the '[ ... ]' case, where we allow the syntax '[ if g then t else e ]' but ask it to be parenthesized /// -let (|SimpleSemicolonSequence|_|) acceptDeprecated c = - - let rec YieldFree expr = - match expr with - | SynExpr.Sequential (_, _, e1, e2, _) -> YieldFree e1 && YieldFree e2 - | SynExpr.IfThenElse (_, e2, e3opt, _, _, _, _) -> YieldFree e2 && Option.forall YieldFree e3opt - | SynExpr.TryWith (e1, _, clauses, _, _, _, _) -> YieldFree e1 && clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) - | (SynExpr.Match (_, _, clauses, _) | SynExpr.MatchBang (_, _, clauses, _)) -> - clauses |> List.forall (fun (Clause(_, _, e, _, _)) -> YieldFree e) - | SynExpr.For (_, _, _, _, _, body, _) - | SynExpr.TryFinally (body, _, _, _, _) - | SynExpr.LetOrUse (_, _, _, body, _) - | SynExpr.While (_, _, body, _) - | SynExpr.ForEach (_, _, _, _, _, body, _) -> YieldFree body - | SynExpr.YieldOrReturnFrom _ - | SynExpr.YieldOrReturn _ - | SynExpr.LetOrUseBang _ - | SynExpr.ImplicitZero _ - | SynExpr.Do _ -> false - | _ -> true +let (|SimpleSemicolonSequence|_|) cenv acceptDeprecated cexpr = - let rec IsSimpleSemicolonSequenceElement expr = - match expr with - | SynExpr.IfThenElse _ when acceptDeprecated && YieldFree expr -> true - | SynExpr.IfThenElse _ + let IsSimpleSemicolonSequenceElement expr = + match expr with + | SynExpr.IfThenElse _ when acceptDeprecated && YieldFree cenv expr -> true + | SynExpr.IfThenElse _ | SynExpr.TryWith _ | SynExpr.Match _ | SynExpr.For _ @@ -3553,15 +3606,14 @@ let (|SimpleSemicolonSequence|_|) acceptDeprecated c = | SynExpr.Do _ | SynExpr.MatchBang _ | SynExpr.LetOrUseBang _ - | SynExpr.ImplicitZero _ | SynExpr.While _ -> false | _ -> true - let rec GetSimpleSemicolonSequenceOfComprehension expr acc = + let rec TryGetSimpleSemicolonSequenceOfComprehension expr acc = match expr with | SynExpr.Sequential (_, true, e1, e2, _) -> if IsSimpleSemicolonSequenceElement e1 then - GetSimpleSemicolonSequenceOfComprehension e2 (e1 :: acc) + TryGetSimpleSemicolonSequenceOfComprehension e2 (e1 :: acc) else None | e -> @@ -3570,10 +3622,7 @@ let (|SimpleSemicolonSequence|_|) acceptDeprecated c = else None - if YieldFree c then - GetSimpleSemicolonSequenceOfComprehension c [] - else - None + TryGetSimpleSemicolonSequenceOfComprehension cexpr [] //------------------------------------------------------------------------- // Mutually recursive shapes @@ -4089,9 +4138,8 @@ let buildApp cenv expr resultTy arg m = | _ when isByrefTy g resultTy -> // Handle byref returns, byref-typed returns get implicitly dereferenced - let v, _ = mkCompGenLocal m "byrefReturn" resultTy let expr = expr.SupplyArgument (arg, m) - let expr = mkCompGenLet m v expr.Expr (mkAddrGet m (mkLocalValRef v)) + let expr = mkDerefAddrExpr m expr.Expr m resultTy let resultTy = destByrefTy g resultTy MakeApplicableExprNoFlex cenv expr, resultTy @@ -5680,6 +5728,12 @@ and TcStmt cenv env tpenv synExpr = else mkCompGenSequential m expr (mkUnit cenv.g m), tpenv +and TryTcStmt cenv env tpenv synExpr = + let expr, ty, tpenv = TcExprOfUnknownType cenv env tpenv synExpr + let m = synExpr.Range + let hasTypeUnit = TryUnifyUnitTypeWithoutWarning cenv env m ty + hasTypeUnit, expr, tpenv + /// During checking of expressions of the form (x(y)).z(w1, w2) /// keep a stack of things on the right. This lets us recognize /// method applications and other item-based syntax. @@ -5748,6 +5802,13 @@ and TcExprUndelayedNoType cenv env tpenv synExpr: Expr * TType * _ = expr, overallTy, tpenv and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = + + // LanguageFeatures.ImplicitYield do not require this validation + let implicitYieldEnabled = cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + let validateObjectSequenceOrRecordExpression = not implicitYieldEnabled + let validateExpressionWithIfRequiresParenethesis = not implicitYieldEnabled + let acceptDeprecatedIfThenExpression = not implicitYieldEnabled + match synExpr with | SynExpr.Paren (expr2, _, _, mWholeExprIncludingParentheses) -> // We invoke CallExprHasTypeSink for every construct which is atomic in the syntax, i.e. where a '.' immediately following the @@ -5946,25 +6007,23 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = match comp with | SynExpr.New _ -> errorR(Error(FSComp.SR.tcInvalidObjectExpressionSyntaxForm(), m)) - | SimpleSemicolonSequence false _ -> + | SimpleSemicolonSequence cenv false _ when validateObjectSequenceOrRecordExpression -> errorR(Error(FSComp.SR.tcInvalidObjectSequenceOrRecordExpression(), m)) | _ -> () if not !isNotNakedRefCell && not cenv.g.compilingFslib then error(Error(FSComp.SR.tcInvalidSequenceExpressionSyntaxForm(), m)) - TcComputationOrSequenceExpression cenv env overallTy m None tpenv comp + TcSequenceExpression cenv env tpenv comp overallTy m | SynExpr.ArrayOrListOfSeqExpr (isArray, comp, m) -> CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) - match comp with - | SynExpr.CompExpr (_, _, (SimpleSemicolonSequence true elems as body), _) -> - match body with - | SimpleSemicolonSequence false _ -> - () - | _ -> - errorR(Deprecated(FSComp.SR.tcExpressionWithIfRequiresParenthesis(), m)) + | SynExpr.CompExpr (_, _, (SimpleSemicolonSequence cenv acceptDeprecatedIfThenExpression elems as body), _) -> + match body with + | SimpleSemicolonSequence cenv false _ -> () + | _ when validateExpressionWithIfRequiresParenethesis -> errorR(Deprecated(FSComp.SR.tcExpressionWithIfRequiresParenthesis(), m)) + | _ -> () let replacementExpr = if isArray then @@ -6063,6 +6122,19 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let expr2, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv synExpr2 Expr.Sequential (expr1, expr2, ThenDoSeq, sp, m), tpenv + // Used to implement the type-directed 'implicit yield' rule for computation expressions + | SynExpr.SequentialOrImplicitYield (sp, synExpr1, synExpr2, otherExpr, m) -> + let isStmt, expr1, tpenv = TryTcStmt cenv env tpenv synExpr1 + if isStmt then + let env = ShrinkContext env m synExpr2.Range + let expr2, tpenv = TcExprThatCanBeCtorBody cenv overallTy env tpenv synExpr2 + Expr.Sequential(expr1, expr2, NormalSeq, sp, m), tpenv + else + // The first expression wasn't unit-typed, so proceed to the alternative interpretation + // Note a copy of the first expression is embedded in 'otherExpr' and thus + // this will type-check the first expression over again. + TcExpr cenv overallTy env tpenv otherExpr + | SynExpr.Do (synInnerExpr, m) -> UnifyTypes cenv env m overallTy cenv.g.unit_ty TcStmtThatCantBeCtorBody cenv env tpenv synInnerExpr @@ -6892,7 +6964,7 @@ and TcConstExpr cenv overallTy env m tpenv c = let expr = let modName = "NumericLiteral" + suffix let ad = env.eAccessRights - match ResolveLongIndentAsModuleOrNamespace cenv.tcSink ResultCollectionSettings.AtMostOneResult cenv.amap m true OpenQualified env.eNameResEnv ad (ident (modName, m)) [] false with + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AtMostOneResult cenv.amap m true true OpenQualified env.eNameResEnv ad (ident (modName, m)) [] false with | Result [] | Exception _ -> error(Error(FSComp.SR.tcNumericLiteralRequiresModule modName, m)) | Result ((_, mref, _) :: _) -> @@ -7336,24 +7408,13 @@ and TcQuotationExpr cenv overallTy env tpenv (_oper, raw, ast, isFromQueryExpres // We serialize the quoted expression to bytes in IlxGen after type inference etc. is complete. expr, tpenv -//------------------------------------------------------------------------- -// TcComputationOrSequenceExpression -//------------------------------------------------------------------------- - -and TcComputationOrSequenceExpression cenv (env: TcEnv) overallTy m interpValOpt tpenv comp = - match interpValOpt with - | Some (interpExpr: Expr, builderTy) -> - TcComputationExpression cenv env overallTy m interpExpr builderTy tpenv comp - | None -> - TcSequenceExpression cenv env tpenv comp overallTy m - /// Ignores an attribute and IgnoreAttribute _ = None -// Used for all computation expressions except sequence expressions -and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv comp = +/// Used for all computation expressions except sequence expressions +and TcComputationExpression cenv env overallTy mWhole (interpExpr: Expr) builderTy tpenv (comp: SynExpr) = - //dprintfn "TcComputationOrSequenceExpression, comp = \n%A\n-------------------\n" comp + //dprintfn "TcComputationExpression, comp = \n%A\n-------------------\n" comp let ad = env.eAccessRights let mkSynDelay2 (e: SynExpr) = mkSynDelay (e.Range.MakeSynthetic()) e @@ -7382,19 +7443,18 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let builderVal = mkSynIdGet m builderValName mkSynApp1 (SynExpr.DotGet (builderVal, range0, LongIdentWithDots([mkSynId m nm], []), m)) args m - let sourceMethInfo = TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Source" builderTy + let hasMethInfo nm = TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad nm builderTy |> isNil |> not + + let sourceMethInfo = TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Source" builderTy + // Optionally wrap sources of "let!", "yield!", "use!" in "query.Source" let mkSourceExpr callExpr = match sourceMethInfo with | [] -> callExpr | _ -> mkSynCall "Source" callExpr.Range [callExpr] - /// Decide if the builder is an auto-quote builder - let isAutoQuote = - match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Quote" builderTy with - | [] -> false - | _ -> true + let isAutoQuote = hasMethInfo "Quote" let customOperationMethods = AllMethInfosOfTypeInScope ResultCollectionSettings.AllResults cenv.infoReader env.NameEnv None ad IgnoreOverrides mBuilderVal builderTy @@ -7552,7 +7612,6 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let (_, argInfo) = List.item i argInfos HasFSharpAttribute cenv.g cenv.g.attrib_ProjectionParameterAttribute argInfo.Attribs - let (|ForEachThen|_|) e = match e with | SynExpr.ForEach (_spBind, SeqExprOnly false, isFromSource, pat1, expr1, SynExpr.Sequential (_, true, clause, rest, _), _) -> Some (isFromSource, pat1, expr1, clause, rest) @@ -7705,7 +7764,6 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> None - let (|StripApps|) e = let rec strip e = match e with @@ -7764,6 +7822,20 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | SynExpr.Sequential (_sp, true, dataComp1, dataComp2, _) -> (dataComp1, Some dataComp2) | _ -> (e, None) + // "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1) + // This is not pretty - we have to decide which range markers we use for the calls to Combine and Delay + // NOTE: we should probably suppress these sequence points altogether + let rangeForCombine innerComp1 = + match innerComp1 with + | SynExpr.IfThenElse (_, _, _, _, _, mIfToThen, _m) -> mIfToThen + | SynExpr.Match (SequencePointAtBinding mMatch, _, _, _) -> mMatch + | SynExpr.TryWith (_, _, _, _, _, SequencePointAtTry mTry, _) -> mTry + | SynExpr.TryFinally (_, _, _, SequencePointAtTry mTry, _) -> mTry + | SynExpr.For (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind + | SynExpr.ForEach (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind + | SynExpr.While (SequencePointAtWhileLoop mWhile, _, _, _) -> mWhile + | _ -> innerComp1.Range + // Check for 'where x > y', 'select x, y' and other mis-applications of infix operators, give a good error message, and return a flag let checkForBinaryApp comp = match comp with @@ -7794,6 +7866,13 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let emptyVarSpace = LazyWithContext.NotLazy ([], env) + // If there are no 'yield' in the computation expression, and the builder supports 'Yield', + // then allow the type-directed rule interpreting non-unit-typed expressions in statement + // positions as 'yield'. 'yield!' may be present in the computation expression. + let enableImplicitYield = + cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + && (hasMethInfo "Yield" && hasMethInfo "Combine" && hasMethInfo "Delay" && YieldFree cenv comp) + // q - a flag indicating if custom operators are allowed. They are not allowed inside try/with, try/finally, if/then/else etc. // varSpace - a lazy data structure indicating the variables bound so far in the overall computation // comp - the computation expression being analyzed @@ -8160,16 +8239,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1) // This is not pretty - we have to decide which range markers we use for the calls to Combine and Delay // NOTE: we should probably suppress these sequence points altogether - let m1 = - match innerComp1 with - | SynExpr.IfThenElse (_, _, _, _, _, mIfToThen, _m) -> mIfToThen - | SynExpr.Match (SequencePointAtBinding mMatch, _, _, _) -> mMatch - | SynExpr.TryWith (_, _, _, _, _, SequencePointAtTry mTry, _) -> mTry - | SynExpr.TryFinally (_, _, _, SequencePointAtTry mTry, _) -> mTry - | SynExpr.For (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind - | SynExpr.ForEach (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind - | SynExpr.While (SequencePointAtWhileLoop mWhile, _, _, _) -> mWhile - | _ -> innerComp1.Range + let m1 = rangeForCombine innerComp1 if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Combine" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Combine"), m)) if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Delay" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), m)) Some (translatedCtxt (mkSynCall "Combine" m1 [c; mkSynCall "Delay" m1 [mkSynDelay innerComp2.Range (transNoQueryOps innerComp2)]])) @@ -8185,7 +8255,20 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some(trans true q varSpace (SynExpr.LetOrUseBang (sp, false, true, SynPat.Const(SynConst.Unit, rhsExpr.Range), rhsExpr, innerComp2, m)) translatedCtxt) // "expr; cexpr" is treated as sequential execution | _ -> - Some (trans true q varSpace innerComp2 (fun holeFill -> translatedCtxt (SynExpr.Sequential (sp, true, innerComp1, holeFill, m)))) + Some (trans true q varSpace innerComp2 (fun holeFill -> + let fillExpr = + if enableImplicitYield then + // When implicit yields are enabled, then if the 'innerComp1' checks as type + // 'unit' we interpret the expression as a sequential, and when it doesn't + // have type 'unit' we interpret it as a 'Yield + Combine'. + let combineExpr = + let m1 = rangeForCombine innerComp1 + let implicitYieldExpr = mkSynCall "Yield" comp.Range [innerComp1] + mkSynCall "Combine" m1 [implicitYieldExpr; mkSynCall "Delay" m1 [mkSynDelay holeFill.Range holeFill]] + SynExpr.SequentialOrImplicitYield(sp, innerComp1, holeFill, combineExpr, m) + else + SynExpr.Sequential(sp, true, innerComp1, holeFill, m) + translatedCtxt fillExpr)) | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, isRecovery, mIfToThen, mIfToEndOfElseBranch) -> match elseCompOpt with @@ -8314,7 +8397,6 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some (translatedCtxt yieldExpr) else Some (translatedCtxt (mkSynCall "ReturnFrom" m [yieldExpr])) - | SynExpr.YieldOrReturn ((isYield, _), yieldExpr, m) -> let methName = (if isYield then "Yield" else "Return") @@ -8324,7 +8406,9 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> None - and transNoQueryOps comp = trans true false emptyVarSpace comp id + and transNoQueryOps comp = + trans true false emptyVarSpace comp id + and trans firstTry q varSpace comp translatedCtxt = match tryTrans firstTry q varSpace comp translatedCtxt with | Some e -> e @@ -8340,8 +8424,9 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv if isNil (TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env m ad "Return" builderTy) then SynExpr.ImplicitZero m else - SynExpr.YieldOrReturn ((false, true), SynExpr.Const (SynConst.Unit, m), m) - trans true q varSpace (SynExpr.LetOrUseBang (NoSequencePointAtDoBinding, false, false, SynPat.Const(SynConst.Unit, mUnit), rhsExpr, bodyExpr, m)) translatedCtxt + SynExpr.YieldOrReturn((false, true), SynExpr.Const (SynConst.Unit, m), m) + trans true q varSpace (SynExpr.LetOrUseBang(NoSequencePointAtDoBinding, false, false, SynPat.Const(SynConst.Unit, mUnit), rhsExpr, bodyExpr, m)) translatedCtxt + // "expr;" in final position is treated as { expr; zero } // Suppress the sequence point on the "zero" | _ -> @@ -8353,21 +8438,27 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv match comp with | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential | _ -> errorR(Error(FSComp.SR.tcUnrecognizedQueryOperator(), comp.RangeOfFirstPortion)) - trans true q varSpace (SynExpr.ImplicitZero comp.Range) (fun holeFill -> translatedCtxt (SynExpr.Sequential (SuppressSequencePointOnStmtOfSequential, true, comp, holeFill, comp.Range))) + trans true q varSpace (SynExpr.ImplicitZero comp.Range) (fun holeFill -> + let fillExpr = + if enableImplicitYield then + let implicitYieldExpr = mkSynCall "Yield" comp.Range [comp] + SynExpr.SequentialOrImplicitYield(SuppressSequencePointOnStmtOfSequential, comp, holeFill, implicitYieldExpr, comp.Range) + else + SynExpr.Sequential(SuppressSequencePointOnStmtOfSequential, true, comp, holeFill, comp.Range) + translatedCtxt fillExpr) - let basicSynExpr = trans true (hasCustomOperations ()) (LazyWithContext.NotLazy ([], env)) comp (fun holeFill -> holeFill) + let basicSynExpr = + trans true (hasCustomOperations ()) (LazyWithContext.NotLazy ([], env)) comp (fun holeFill -> holeFill) let delayedExpr = match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Delay" builderTy with | [] -> basicSynExpr | _ -> mkSynCall "Delay" mBuilderVal [(mkSynDelay2 basicSynExpr)] - let quotedSynExpr = if isAutoQuote then SynExpr.Quote (mkSynIdGet (mBuilderVal.MakeSynthetic()) (CompileOpName "<@ @>"), (*isRaw=*)false, delayedExpr, (*isFromQueryExpression=*)true, mWhole) else delayedExpr - let runExpr = match TryFindIntrinsicOrExtensionMethInfo ResultCollectionSettings.AtMostOneResult cenv env mBuilderVal ad "Run" builderTy with @@ -8405,6 +8496,13 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = // Allow subsumption at 'yield' if the element type is nominal prior to the analysis of the body of the sequence expression let flex = not (isTyparTy cenv.g genEnumElemTy) + // If there are no 'yield' in the computation expression then allow the type-directed rule + // interpreting non-unit-typed expressions in statement positions as 'yield'. 'yield!' may be + // present in the computation expression. + let enableImplicitYield = + cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield + && (YieldFree cenv comp) + let mkDelayedExpr (coreExpr: Expr) = let m = coreExpr.Range let overallTy = tyOfExpr cenv.g coreExpr @@ -8464,7 +8562,8 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = let innerExprMark = innerExpr.Range Some(mkSeqFinally cenv env innerExprMark genOuterTy innerExpr unwindExpr, tpenv) - | SynExpr.Paren (_, _, _, m) -> + + | SynExpr.Paren (_, _, _, m) when not (cenv.g.langVersion.SupportsFeature LanguageFeature.ImplicitYield)-> error(Error(FSComp.SR.tcConstructIsAmbiguousInSequenceExpression(), m)) | SynExpr.ImplicitZero m -> @@ -8476,17 +8575,15 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = | SynExpr.Sequential (sp, true, innerComp1, innerComp2, m) -> // "expr; cexpr" is treated as sequential execution // "cexpr; cexpr" is treated as append - match tryTcSequenceExprBody env genOuterTy tpenv innerComp1 with - | None -> - let innerExpr1, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv innerComp1 - let innerExpr2, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp2 - - Some(Expr.Sequential (innerExpr1, innerExpr2, NormalSeq, sp, m), tpenv) - - | Some (innerExpr1, tpenv) -> + let res, tpenv = tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv innerComp1 + match res with + | Choice1Of2 innerExpr1 -> let innerExpr2, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp2 let innerExpr2 = mkDelayedExpr innerExpr2 Some(mkSeqAppend cenv env innerComp1.Range genOuterTy innerExpr1 innerExpr2, tpenv) + | Choice2Of2 stmt1 -> + let innerExpr2, tpenv = tcSequenceExprBody env genOuterTy tpenv innerComp2 + Some(Expr.Sequential(stmt1, innerExpr2, NormalSeq, sp, m), tpenv) | SynExpr.IfThenElse (guardExpr, thenComp, elseCompOpt, spIfToThen, _isRecovery, mIfToThen, mIfToEndOfElseBranch) -> let guardExpr', tpenv = TcExpr cenv cenv.g.bool_ty env tpenv guardExpr @@ -8560,15 +8657,34 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = | _ -> None and tcSequenceExprBody env genOuterTy tpenv comp = + let res, tpenv = tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv comp + match res with + | Choice1Of2 expr -> + expr, tpenv + | Choice2Of2 stmt -> + let m = comp.Range + let resExpr = Expr.Sequential(stmt, mkSeqEmpty cenv env m genOuterTy, NormalSeq, SuppressSequencePointOnStmtOfSequential, m) + resExpr, tpenv + + and tcSequenceExprBodyAsSequenceOrStatement env genOuterTy tpenv comp = match tryTcSequenceExprBody env genOuterTy tpenv comp with - | Some e -> e + | Some (expr, tpenv) -> Choice1Of2 expr, tpenv | None -> - // seq { ...; expr } is treated as 'seq { ... ; expr; yield! Seq.empty }' - // Note this means seq { ...; () } is treated as 'seq { ... ; (); yield! Seq.empty }' - let m = comp.Range let env = { env with eContextInfo = ContextInfo.SequenceExpression genOuterTy } - let expr, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv comp - Expr.Sequential (expr, mkSeqEmpty cenv env m genOuterTy, NormalSeq, SuppressSequencePointOnStmtOfSequential, m), tpenv + if enableImplicitYield then + let hasTypeUnit, expr, tpenv = TryTcStmt cenv env tpenv comp + if hasTypeUnit then + Choice2Of2 expr, tpenv + else + let genResultTy = NewInferenceType () + UnifyTypes cenv env m genOuterTy (mkSeqTy cenv.g genResultTy) + let exprTy = tyOfExpr cenv.g expr + AddCxTypeMustSubsumeType env.eContextInfo env.DisplayEnv cenv.css m NoTrace genResultTy exprTy + let resExpr = mkCallSeqSingleton cenv.g m genResultTy (mkCoerceExpr(expr, genResultTy, m, exprTy)) + Choice1Of2 resExpr, tpenv + else + let stmt, tpenv = TcStmtThatCantBeCtorBody cenv env tpenv comp + Choice2Of2 stmt, tpenv let coreExpr, tpenv = tcSequenceExprBody env overallTy tpenv comp let delayedExpr = mkDelayedExpr coreExpr @@ -8704,41 +8820,91 @@ and delayRest rest mPrior delayed = let mPriorAndLongId = unionRanges mPrior (rangeOfLid longId) DelayedDotLookup (rest, mPriorAndLongId) :: delayed +/// Typecheck "nameof" expressions +and TcNameOfExpr cenv env tpenv (synArg: SynExpr) = + let rec stripParens expr = + match expr with + | SynExpr.Paren(expr, _, _, _) -> stripParens expr + | _ -> expr + + let cleanSynArg = stripParens synArg + let m = cleanSynArg.Range + let rec check overallTyOpt expr (delayed: DelayedItem list) = + match expr with + | LongOrSingleIdent (false, (LongIdentWithDots(longId, _) as lidd), _, _) when longId.Length > 0 -> + let ad = env.eAccessRights + let id, rest = List.headAndTail longId + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m false true OpenQualified env.eNameResEnv ad id rest true with + | Result modref when delayed.IsEmpty && modref |> List.exists (p23 >> IsEntityAccessible cenv.amap m ad) -> + () // resolved to a module or namespace, done with checks + | _ -> + let (TypeNameResolutionInfo(_, staticArgsInfo)) = GetLongIdentTypeNameInfo delayed + match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad longId staticArgsInfo PermitDirectReferenceToGeneratedType.No with + | Result tcref when IsEntityAccessible cenv.amap m ad tcref -> + () // resolved to a type name, done with checks + | _ -> + let overallTy = match overallTyOpt with None -> NewInferenceType() | Some t -> t + let _, _ = TcLongIdentThen cenv overallTy env tpenv lidd delayed + () // checked as an expression, done with checks + List.last longId + + | SynExpr.TypeApp (hd, _, types, _, _, _, m) -> + check overallTyOpt hd (DelayedTypeApp(types, m, m) :: delayed) + + | SynExpr.Paren(expr, _, _, _) when overallTyOpt.IsNone && delayed.IsEmpty -> + check overallTyOpt expr [] + + | SynExpr.Typed (synBodyExpr, synType, _m) when delayed.IsEmpty && overallTyOpt.IsNone -> + let tgtTy, _tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synType + check (Some tgtTy) synBodyExpr [] + + | _ -> + error (Error(FSComp.SR.expressionHasNoName(), m)) + + let lastIdent = check None cleanSynArg [] + let constRange = mkRange m.FileName m.Start (mkPos m.StartLine (m.StartColumn + lastIdent.idText.Length + 2)) // `2` are for quotes + Expr.Const(Const.String(lastIdent.idText), constRange, cenv.g.string_ty) + //------------------------------------------------------------------------- // TcFunctionApplicationThen: Typecheck "expr x" + projections //------------------------------------------------------------------------- and TcFunctionApplicationThen cenv overallTy env tpenv mExprAndArg expr exprty (synArg: SynExpr) atomicFlag delayed = - let denv = env.DisplayEnv let mArg = synArg.Range let mFunExpr = expr.Range + // If the type of 'synArg' unifies as a function type, then this is a function application, otherwise // it is an error or a computation expression match UnifyFunctionTypeUndoIfFailed cenv denv mFunExpr exprty with - | ValueSome (domainTy, resultTy) -> - - // Notice the special case 'seq { ... }'. In this case 'seq' is actually a function in the F# library. - // Set a flag in the syntax tree to say we noticed a leading 'seq' - match synArg with - | SynExpr.CompExpr (false, isNotNakedRefCell, _comp, _m) -> - isNotNakedRefCell := - !isNotNakedRefCell - || - (match expr with - | ApplicableExpr(_, Expr.Op (TOp.Coerce, _, [Expr.App (Expr.Val (vf, _, _), _, _, _, _)], _), _) when valRefEq cenv.g vf cenv.g.seq_vref -> true - | _ -> false) - | _ -> () - - let arg, tpenv = TcExpr cenv domainTy env tpenv synArg - let exprAndArg, resultTy = buildApp cenv expr resultTy arg mExprAndArg - TcDelayed cenv overallTy env tpenv mExprAndArg exprAndArg resultTy atomicFlag delayed - | _ -> + | ValueSome (domainTy, resultTy) -> + match expr with + | ApplicableExpr(_, NameOfExpr cenv.g _, _) when cenv.g.langVersion.SupportsFeature LanguageFeature.NameOf -> + let replacementExpr = TcNameOfExpr cenv env tpenv synArg + TcDelayed cenv overallTy env tpenv mExprAndArg (ApplicableExpr(cenv, replacementExpr, true)) cenv.g.string_ty ExprAtomicFlag.Atomic delayed + | _ -> + // Notice the special case 'seq { ... }'. In this case 'seq' is actually a function in the F# library. + // Set a flag in the syntax tree to say we noticed a leading 'seq' + match synArg with + | SynExpr.CompExpr (false, isNotNakedRefCell, _comp, _m) -> + isNotNakedRefCell := + !isNotNakedRefCell + || + (match expr with + | ApplicableExpr(_, Expr.Op(TOp.Coerce, _, [SeqExpr cenv.g], _), _) -> true + | _ -> false) + | _ -> () + + let arg, tpenv = TcExpr cenv domainTy env tpenv synArg + let exprAndArg, resultTy = buildApp cenv expr resultTy arg mExprAndArg + TcDelayed cenv overallTy env tpenv mExprAndArg exprAndArg resultTy atomicFlag delayed + + | ValueNone -> // OK, 'expr' doesn't have function type, but perhaps 'expr' is a computation expression builder, and 'arg' is '{ ... }' match synArg with | SynExpr.CompExpr (false, _isNotNakedRefCell, comp, _m) -> - let bodyOfCompExpr, tpenv = TcComputationOrSequenceExpression cenv env overallTy mFunExpr (Some(expr.Expr, exprty)) tpenv comp + let bodyOfCompExpr, tpenv = TcComputationExpression cenv env overallTy mFunExpr expr.Expr exprty tpenv comp TcDelayed cenv overallTy env tpenv mExprAndArg (MakeApplicableExprNoFlex cenv bodyOfCompExpr) (tyOfExpr cenv.g bodyOfCompExpr) ExprAtomicFlag.NonAtomic delayed | _ -> error (NotAFunction(denv, overallTy, mFunExpr, mArg)) @@ -8747,25 +8913,26 @@ and TcFunctionApplicationThen cenv overallTy env tpenv mExprAndArg expr exprty ( // TcLongIdentThen: Typecheck "A.B.C.E.F ... " constructs //------------------------------------------------------------------------- -and TcLongIdentThen cenv overallTy env tpenv (LongIdentWithDots(longId, _)) delayed = +and GetLongIdentTypeNameInfo delayed = + // Given 'MyOverloadedType.MySubType...' use the number of given type arguments to help + // resolve type name lookup of 'MyOverloadedType' + // Also determine if type names should resolve to Item.Types or Item.CtorGroup + match delayed with + | DelayedTypeApp (tyargs, _, _) :: (DelayedDot | DelayedDotLookup _) :: _ -> + // cases like 'MyType.Sth' + TypeNameResolutionInfo(ResolveTypeNamesToTypeRefs, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) - let ad = env.eAccessRights - let typeNameResInfo = - // Given 'MyOverloadedType.MySubType...' use arity of #given type arguments to help - // resolve type name lookup of 'MyOverloadedType' - // Also determine if type names should resolve to Item.Types or Item.CtorGroup - match delayed with - | DelayedTypeApp (tyargs, _, _) :: (DelayedDot | DelayedDotLookup _) :: _ -> - // cases like 'MyType.Sth' - TypeNameResolutionInfo(ResolveTypeNamesToTypeRefs, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) + | DelayedTypeApp (tyargs, _, _) :: _ -> + // Note, this also covers the case 'MyType.' (without LValue_get), which is needed for VS (when typing) + TypeNameResolutionInfo(ResolveTypeNamesToCtors, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) - | DelayedTypeApp (tyargs, _, _) :: _ -> - // Note, this also covers the case 'MyType.' (without LValue_get), which is needed for VS (when typing) - TypeNameResolutionInfo(ResolveTypeNamesToCtors, TypeNameResolutionStaticArgsInfo.FromTyArgs tyargs.Length) + | _ -> + TypeNameResolutionInfo.Default - | _ -> - TypeNameResolutionInfo.Default +and TcLongIdentThen cenv overallTy env tpenv (LongIdentWithDots(longId, _)) delayed = + let ad = env.eAccessRights + let typeNameResInfo = GetLongIdentTypeNameInfo delayed let nameResolutionResult = ResolveLongIdentAsExprAndComputeRange cenv.tcSink cenv.nameResolver (rangeOfLid longId) ad env.eNameResEnv typeNameResInfo longId TcItemThen cenv overallTy env tpenv nameResolutionResult delayed @@ -9121,6 +9288,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | SynExpr.TryFinally _ | SynExpr.Lazy _ | SynExpr.Sequential _ + | SynExpr.SequentialOrImplicitYield _ | SynExpr.LetOrUse _ | SynExpr.DotSet _ | SynExpr.DotIndexedSet _ @@ -10044,8 +10212,7 @@ and TcMethodApplication // byref-typed returns get implicitly dereferenced let vty = tyOfExpr cenv.g callExpr0 if isByrefTy cenv.g vty then - let v, _ = mkCompGenLocal mMethExpr "byrefReturn" vty - mkCompGenLet mMethExpr v callExpr0 (mkAddrGet mMethExpr (mkLocalValRef v)) + mkDerefAddrExpr mMethExpr callExpr0 mMethExpr vty else callExpr0 @@ -12288,19 +12455,19 @@ let TcTyconMemberSpecs cenv env containerInfo declKind tpenv (augSpfn: SynMember // Bind 'open' declarations //------------------------------------------------------------------------- -let TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap (longId: Ident list) = +let TcOpenLidAndPermitAutoResolve tcSink env amap (longId : Ident list) = let ad = env.eAccessRights match longId with | [] -> [] | id :: rest -> let m = longId |> List.map (fun id -> id.idRange) |> List.reduce unionRanges - match ResolveLongIndentAsModuleOrNamespace tcSink ResultCollectionSettings.AllResults amap m true OpenQualified env.eNameResEnv ad id rest true with + match ResolveLongIndentAsModuleOrNamespaceOrStaticClass tcSink ResultCollectionSettings.AllResults amap m true true OpenQualified env.eNameResEnv ad id rest true with | Result res -> res | Exception err -> errorR(err); [] let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = - match TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap longId with + match TcOpenLidAndPermitAutoResolve tcSink env amap longId with | [] -> env | modrefs -> @@ -12352,7 +12519,7 @@ let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = modrefs |> List.iter (fun modref -> CheckEntityAttributes g modref m |> CommitOperationResult) let openDecl = OpenDeclaration.Create (longId, modrefs, scopem, false) - let env = OpenModulesOrNamespaces tcSink g amap scopem false env modrefs openDecl + let env = OpenEntities tcSink g amap scopem false env modrefs openDecl env @@ -13827,7 +13994,7 @@ module MutRecBindingChecking = let resolved = match p with | [] -> Result [] - | id :: rest -> ResolveLongIndentAsModuleOrNamespace cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m true OpenQualified env.eNameResEnv ad id rest false + | id :: rest -> ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m false true OpenQualified env.eNameResEnv ad id rest false let mvvs = ForceRaise resolved if isNil mvvs then env else let modrefs = mvvs |> List.map p23 @@ -16659,7 +16826,7 @@ let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synS let resolved = match p with | [] -> Result [] - | id :: rest -> ResolveLongIndentAsModuleOrNamespace cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m true OpenQualified env.eNameResEnv ad id rest false + | id :: rest -> ResolveLongIndentAsModuleOrNamespaceOrStaticClass cenv.tcSink ResultCollectionSettings.AllResults cenv.amap m false true OpenQualified env.eNameResEnv ad id rest false let mvvs = ForceRaise resolved let scopem = unionRanges m endm let unfilteredModrefs = mvvs |> List.map p23 @@ -17213,7 +17380,7 @@ let ApplyAssemblyLevelAutoOpenAttributeToTcEnv g amap (ccu: CcuThunk) scopem env | ValueNone -> warn() | ValueSome _ -> let openDecl = OpenDeclaration.Create ([], [modref], scopem, false) - OpenModulesOrNamespaces TcResultsSink.NoSink g amap scopem root env [modref] openDecl + OpenEntities TcResultsSink.NoSink g amap scopem root env [modref] openDecl // Add the CCU and apply the "AutoOpen" attributes let AddCcuToTcEnv(g, amap, scopem, env, assemblyName, ccu, autoOpens, internalsVisible) = diff --git a/src/fsharp/UnicodeLexing.fs b/src/fsharp/UnicodeLexing.fs index bb1c26dabf2..d34092940e2 100644 --- a/src/fsharp/UnicodeLexing.fs +++ b/src/fsharp/UnicodeLexing.fs @@ -7,22 +7,23 @@ module internal FSharp.Compiler.UnicodeLexing // open FSharp.Compiler.AbstractIL.Internal.Library +open FSharp.Compiler.Features open Internal.Utilities -open System.IO +open System.IO open Internal.Utilities.Text.Lexing type Lexbuf = LexBuffer -let StringAsLexbuf (s:string) : Lexbuf = - LexBuffer<_>.FromChars (s.ToCharArray()) - -let FunctionAsLexbuf (bufferFiller: char[] * int * int -> int) : Lexbuf = - LexBuffer<_>.FromFunction bufferFiller +let StringAsLexbuf (supportsFeature: Features.LanguageFeature -> bool, s:string) : Lexbuf = + LexBuffer<_>.FromChars (supportsFeature, s.ToCharArray()) + +let FunctionAsLexbuf (supportsFeature: Features.LanguageFeature -> bool, bufferFiller: char[] * int * int -> int) : Lexbuf = + LexBuffer<_>.FromFunction(supportsFeature, bufferFiller) + +let SourceTextAsLexbuf (supportsFeature: Features.LanguageFeature -> bool, sourceText) = + LexBuffer.FromSourceText(supportsFeature, sourceText) -let SourceTextAsLexbuf sourceText = - LexBuffer.FromSourceText(sourceText) - // The choice of 60 retries times 50 ms is not arbitrary. The NTFS FILETIME structure // uses 2 second resolution for LastWriteTime. We retry long enough to surpass this threshold // plus 1 second. Once past the threshold the incremental builder will be able to retry asynchronously based @@ -41,7 +42,7 @@ let numRetries = 60 /// we can't just return the LexBuffer object, since the file it wraps wouldn't /// get closed when we're finished with the LexBuffer. Hence we return the stream, /// the reader and the LexBuffer. The caller should dispose the first two when done. -let UnicodeFileAsLexbuf (filename,codePage : int option, retryLocked:bool) : Lexbuf = +let UnicodeFileAsLexbuf (supportsFeature: Features.LanguageFeature -> bool, filename, codePage: int option, retryLocked: bool): Lexbuf = // Retry multiple times since other processes may be writing to this file. let rec getSource retryNumber = try @@ -68,5 +69,5 @@ let UnicodeFileAsLexbuf (filename,codePage : int option, retryLocked:bool) : Le else reraise() let source = getSource 0 - let lexbuf = LexBuffer<_>.FromChars(source.ToCharArray()) + let lexbuf = LexBuffer<_>.FromChars(supportsFeature, source.ToCharArray()) lexbuf diff --git a/src/fsharp/UnicodeLexing.fsi b/src/fsharp/UnicodeLexing.fsi index 7c0f0fb68d5..2478c7f857b 100644 --- a/src/fsharp/UnicodeLexing.fsi +++ b/src/fsharp/UnicodeLexing.fsi @@ -2,12 +2,13 @@ module internal FSharp.Compiler.UnicodeLexing +open FSharp.Compiler.Features open FSharp.Compiler.Text open Microsoft.FSharp.Text open Internal.Utilities.Text.Lexing type Lexbuf = LexBuffer -val internal StringAsLexbuf : string -> Lexbuf -val public FunctionAsLexbuf : (char [] * int * int -> int) -> Lexbuf -val public UnicodeFileAsLexbuf :string * int option * (*retryLocked*) bool -> Lexbuf -val public SourceTextAsLexbuf : ISourceText -> Lexbuf +val internal StringAsLexbuf: (Features.LanguageFeature -> bool) * string -> Lexbuf +val public FunctionAsLexbuf: (Features.LanguageFeature -> bool) * (char [] * int * int -> int) -> Lexbuf +val public UnicodeFileAsLexbuf: (Features.LanguageFeature -> bool) * string * int option * (*retryLocked*) bool -> Lexbuf +val public SourceTextAsLexbuf: (Features.LanguageFeature -> bool) * ISourceText -> Lexbuf diff --git a/src/fsharp/XmlAdapters.fs b/src/fsharp/XmlAdapters.fs new file mode 100644 index 00000000000..4f48955945a --- /dev/null +++ b/src/fsharp/XmlAdapters.fs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace Microsoft.FSharp.Core +open System.Reflection + +//Replacement for: System.Security.SecurityElement.Escape(line) All platforms +module internal XmlAdapters = + open System.Text + open Microsoft.FSharp.Collections + + let s_escapeChars = [| '<'; '>'; '\"'; '\''; '&' |] + + let getEscapeSequence c = + match c with + | '<' -> "<" + | '>' -> ">" + | '\"' -> """ + | '\'' -> "'" + | '&' -> "&" + | _ as ch -> ch.ToString() + + let escape str = String.collect getEscapeSequence str + diff --git a/src/fsharp/ast.fs b/src/fsharp/ast.fs index 46bb6b1420e..59e93205ce1 100644 --- a/src/fsharp/ast.fs +++ b/src/fsharp/ast.fs @@ -12,6 +12,7 @@ open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler open FSharp.Compiler.UnicodeLexing open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.PrettyNaming open FSharp.Compiler.Range @@ -671,7 +672,7 @@ and /// F# syntax: lazy expr | Lazy of SynExpr * range: range - /// Seq(seqPoint, isTrueSeq, e1, e2, m) + /// Sequential(seqPoint, isTrueSeq, e1, e2, m) /// isTrueSeq: false indicates "let v = a in b; v" /// /// F# syntax: expr; expr @@ -749,10 +750,12 @@ and /// Computation expressions only, based on JOIN_IN token from lex filter | JoinIn of SynExpr * range * SynExpr * range: range - /// F# syntax: - /// Computation expressions only, implied by final "do" or "do!" + /// Used internally during type checking for translating computation expressions. | ImplicitZero of range: range + /// Used internally during type checking for translating computation expressions. + | SequentialOrImplicitYield of seqPoint:SequencePointInfoForSeq * expr1:SynExpr * expr2:SynExpr * ifNotStmt:SynExpr * range:range + /// F# syntax: yield expr /// F# syntax: return expr /// Computation expressions only @@ -833,6 +836,7 @@ and | SynExpr.TryWith (range=m) | SynExpr.TryFinally (range=m) | SynExpr.Sequential (range=m) + | SynExpr.SequentialOrImplicitYield (range=m) | SynExpr.ArbitraryAfterError (range=m) | SynExpr.FromParseError (range=m) | SynExpr.DiscardAfterMissingQualificationAfterDot (range=m) @@ -872,138 +876,25 @@ and /// range ignoring any (parse error) extra trailing dots member e.RangeSansAnyExtraDot = match e with - | SynExpr.Paren (range=m) - | SynExpr.Quote (range=m) - | SynExpr.Const (range=m) - | SynExpr.Typed (range=m) - | SynExpr.Tuple (range=m) - | SynExpr.ArrayOrList (range=m) - | SynExpr.AnonRecd (range=m) - | SynExpr.Record (range=m) - | SynExpr.New (range=m) - | SynExpr.ObjExpr (range=m) - | SynExpr.While (range=m) - | SynExpr.For (range=m) - | SynExpr.ForEach (range=m) - | SynExpr.CompExpr (range=m) - | SynExpr.ArrayOrListOfSeqExpr (range=m) - | SynExpr.Lambda (range=m) - | SynExpr.Match (range=m) - | SynExpr.MatchLambda (range=m) - | SynExpr.Do (range=m) - | SynExpr.Assert (range=m) - | SynExpr.App (range=m) - | SynExpr.TypeApp (range=m) - | SynExpr.LetOrUse (range=m) - | SynExpr.TryWith (range=m) - | SynExpr.TryFinally (range=m) - | SynExpr.Sequential (range=m) - | SynExpr.ArbitraryAfterError (range=m) - | SynExpr.FromParseError (range=m) - | SynExpr.IfThenElse (range=m) - | SynExpr.LongIdentSet (range=m) - | SynExpr.NamedIndexedPropertySet (range=m) - | SynExpr.DotIndexedGet (range=m) - | SynExpr.DotIndexedSet (range=m) - | SynExpr.DotSet (range=m) - | SynExpr.Set (range=m) - | SynExpr.DotNamedIndexedPropertySet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) - | SynExpr.LibraryOnlyILAssembly (range=m) - | SynExpr.LibraryOnlyStaticOptimization (range=m) - | SynExpr.TypeTest (range=m) - | SynExpr.Upcast (range=m) - | SynExpr.AddressOf (range=m) - | SynExpr.Downcast (range=m) - | SynExpr.JoinIn (range=m) - | SynExpr.InferredUpcast (range=m) - | SynExpr.InferredDowncast (range=m) - | SynExpr.Null (range=m) - | SynExpr.Lazy (range=m) - | SynExpr.TraitCall (range=m) - | SynExpr.ImplicitZero (range=m) - | SynExpr.YieldOrReturn (range=m) - | SynExpr.YieldOrReturnFrom (range=m) - | SynExpr.LetOrUseBang (range=m) - | SynExpr.MatchBang (range=m) - | SynExpr.DoBang (range=m) -> m | SynExpr.DotGet (expr, _, lidwd, m) -> if lidwd.ThereIsAnExtraDotAtTheEnd then unionRanges expr.Range lidwd.RangeSansAnyExtraDot else m | SynExpr.LongIdent (_, lidwd, _, _) -> lidwd.RangeSansAnyExtraDot | SynExpr.DiscardAfterMissingQualificationAfterDot (expr, _) -> expr.Range - | SynExpr.Fixed (_, m) -> m - | SynExpr.Ident id -> id.idRange + | _ -> e.Range /// Attempt to get the range of the first token or initial portion only - this is extremely ad-hoc, just a cheap way to improve a certain 'query custom operation' error range member e.RangeOfFirstPortion = match e with - // haven't bothered making these cases better than just .Range - | SynExpr.Quote (range=m) - | SynExpr.Const (range=m) - | SynExpr.Typed (range=m) - | SynExpr.Tuple (range=m) - | SynExpr.ArrayOrList (range=m) - | SynExpr.AnonRecd (range=m) - | SynExpr.Record (range=m) - | SynExpr.New (range=m) - | SynExpr.ObjExpr (range=m) - | SynExpr.While (range=m) - | SynExpr.For (range=m) - | SynExpr.CompExpr (range=m) - | SynExpr.ArrayOrListOfSeqExpr (range=m) - | SynExpr.Lambda (range=m) - | SynExpr.Match (range=m) - | SynExpr.MatchLambda (range=m) - | SynExpr.Do (range=m) - | SynExpr.Assert (range=m) - | SynExpr.TypeApp (range=m) - | SynExpr.LetOrUse (range=m) - | SynExpr.TryWith (range=m) - | SynExpr.TryFinally (range=m) - | SynExpr.ArbitraryAfterError (range=m) - | SynExpr.FromParseError (range=m) - | SynExpr.DiscardAfterMissingQualificationAfterDot (range=m) - | SynExpr.IfThenElse (range=m) - | SynExpr.LongIdent (range=m) - | SynExpr.LongIdentSet (range=m) - | SynExpr.NamedIndexedPropertySet (range=m) - | SynExpr.DotIndexedGet (range=m) - | SynExpr.DotIndexedSet (range=m) - | SynExpr.DotGet (range=m) - | SynExpr.DotSet (range=m) - | SynExpr.Set (range=m) - | SynExpr.DotNamedIndexedPropertySet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldGet (range=m) - | SynExpr.LibraryOnlyUnionCaseFieldSet (range=m) - | SynExpr.LibraryOnlyILAssembly (range=m) - | SynExpr.LibraryOnlyStaticOptimization (range=m) - | SynExpr.TypeTest (range=m) - | SynExpr.Upcast (range=m) - | SynExpr.AddressOf (range=m) - | SynExpr.Downcast (range=m) - | SynExpr.JoinIn (range=m) - | SynExpr.InferredUpcast (range=m) - | SynExpr.InferredDowncast (range=m) - | SynExpr.Null (range=m) - | SynExpr.Lazy (range=m) - | SynExpr.TraitCall (range=m) - | SynExpr.ImplicitZero (range=m) - | SynExpr.YieldOrReturn (range=m) - | SynExpr.YieldOrReturnFrom (range=m) - | SynExpr.LetOrUseBang (range=m) - | SynExpr.MatchBang (range=m) - | SynExpr.DoBang (range=m) -> m // these are better than just .Range, and also commonly applicable inside queries | SynExpr.Paren (_, m, _, _) -> m | SynExpr.Sequential (_, _, e1, _, _) + | SynExpr.SequentialOrImplicitYield (_, e1, _, _, _) | SynExpr.App (_, _, e1, _, _) -> e1.RangeOfFirstPortion | SynExpr.ForEach (_, _, _, pat, _, _, r) -> let start = r.Start let e = (pat.Range: range).Start mkRange r.FileName start e - | SynExpr.Ident id -> id.idRange - | SynExpr.Fixed (_, m) -> m + | _ -> e.Range and [] @@ -1972,36 +1863,51 @@ let PushCurriedPatternsToExpr synArgNameGenerator wholem isMember pats rhs = expr spatsl, expr -/// Helper for parsing the inline IL fragments. +let internal internalParseAssemblyCodeInstructions s isFeatureSupported m = #if NO_INLINE_IL_PARSER -let ParseAssemblyCodeInstructions _s m = + ignore s + ignore isFeatureSupported + errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) [| |] #else -let ParseAssemblyCodeInstructions s m = - try FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilInstrs + try + FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilInstrs FSharp.Compiler.AbstractIL.Internal.AsciiLexer.token - (UnicodeLexing.StringAsLexbuf s) + (UnicodeLexing.StringAsLexbuf(isFeatureSupported, s)) with _ -> - errorR(Error(FSComp.SR.astParseEmbeddedILError(), m)); [| |] + errorR(Error(FSComp.SR.astParseEmbeddedILError(), m)); [||] #endif +let ParseAssemblyCodeInstructions s m = + // Public API can not answer the isFeatureSupported questions, so here we support everything + let isFeatureSupported (_featureId:LanguageFeature) = true + internalParseAssemblyCodeInstructions s isFeatureSupported m + +let internal internalParseAssemblyCodeType s isFeatureSupported m = + ignore s + ignore isFeatureSupported -/// Helper for parsing the inline IL fragments. #if NO_INLINE_IL_PARSER -let ParseAssemblyCodeType _s m = errorR(Error((193, "Inline IL not valid in a hosted environment"), m)) IL.EcmaMscorlibILGlobals.typ_Object #else -let ParseAssemblyCodeType s m = - try FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilType + let isFeatureSupported (_featureId:LanguageFeature) = true + try + FSharp.Compiler.AbstractIL.Internal.AsciiParser.ilType FSharp.Compiler.AbstractIL.Internal.AsciiLexer.token - (UnicodeLexing.StringAsLexbuf s) + (UnicodeLexing.StringAsLexbuf(isFeatureSupported, s)) with RecoverableParseError -> errorR(Error(FSComp.SR.astParseEmbeddedILTypeError(), m)); IL.EcmaMscorlibILGlobals.typ_Object #endif +/// Helper for parsing the inline IL fragments. +let ParseAssemblyCodeType s m = + // Public API can not answer the isFeatureSupported questions, so here we support everything + let isFeatureSupported (_featureId:LanguageFeature) = true + internalParseAssemblyCodeType s isFeatureSupported m + //------------------------------------------------------------------------ // AST constructors //------------------------------------------------------------------------ @@ -2564,6 +2470,8 @@ let rec synExprContainsError inpExpr = walkExpr e1 || walkExpr e2 | SynExpr.Sequential (_, _, e1, e2, _) -> walkExpr e1 || walkExpr e2 + | SynExpr.SequentialOrImplicitYield (_, e1, e2, _, _) -> + walkExpr e1 || walkExpr e2 | SynExpr.IfThenElse (e1, e2, e3opt, _, _, _, _) -> walkExpr e1 || walkExpr e2 || walkExprOpt e3opt | SynExpr.DotIndexedGet (e1, es, _, _) -> diff --git a/src/fsharp/fsc.fs b/src/fsharp/fsc.fs index e3177acd7fb..dc5777cdc39 100644 --- a/src/fsharp/fsc.fs +++ b/src/fsharp/fsc.fs @@ -1063,13 +1063,10 @@ module MainModuleBuilder = elif not(tcConfig.target.IsExe) || not(tcConfig.includewin32manifest) || not(tcConfig.win32res = "") || runningOnMono then "" // otherwise, include the default manifest else -#if FX_NO_RUNTIMEENVIRONMENT - // On coreclr default manifest is alongside the compiler - Path.Combine(System.AppContext.BaseDirectory, @"default.win32manifest") -#else - // On the desktop default manifest is alongside the clr - Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), @"default.win32manifest") -#endif + let path = Path.Combine(System.AppContext.BaseDirectory, @"default.win32manifest") + if File.Exists(path) then path + else Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), @"default.win32manifest") + let nativeResources = [ for av in assemblyVersionResources findAttribute assemblyVersion do yield ILNativeResource.Out av @@ -1723,11 +1720,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, let directoryBuildingFrom = Directory.GetCurrentDirectory() let setProcessThreadLocals tcConfigB = match tcConfigB.preferredUiLang with -#if FX_RESHAPED_GLOBALIZATION - | Some s -> CultureInfo.CurrentUICulture <- new CultureInfo(s) -#else | Some s -> Thread.CurrentThread.CurrentUICulture <- new CultureInfo(s) -#endif | None -> () if tcConfigB.utf8output then Console.OutputEncoding <- Encoding.UTF8 diff --git a/src/fsharp/fsi/console.fs b/src/fsharp/fsi/console.fs index 1ac792abc16..04147be7696 100644 --- a/src/fsharp/fsi/console.fs +++ b/src/fsharp/fsi/console.fs @@ -13,8 +13,6 @@ open System.Collections.Generic module internal ConsoleOptions = let readKeyFixup (c:char) = -#if FX_NO_SERVERCODEPAGES -#else // Assumes the c:char is actually a byte in the System.Console.InputEncoding. // Convert it to a Unicode char through the encoding. if 0 <= int c && int c <= 255 then @@ -26,7 +24,6 @@ module internal ConsoleOptions = c // no fix up else assert("readKeyFixHook: given char is outside the 0..255 byte range" = "") -#endif c type internal Style = Prompt | Out | Error diff --git a/src/fsharp/fsi/fsi.fs b/src/fsharp/fsi/fsi.fs index bce19588be0..99bffe0b73c 100644 --- a/src/fsharp/fsi/fsi.fs +++ b/src/fsharp/fsi/fsi.fs @@ -27,13 +27,14 @@ open FSharp.Compiler.AbstractIL.ILBinaryReader open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library open FSharp.Compiler.AbstractIL.Extensions.ILX -open FSharp.Compiler.AbstractIL.ILRuntimeWriter +open FSharp.Compiler.AbstractIL.ILRuntimeWriter open FSharp.Compiler.Lib open FSharp.Compiler.AccessibilityLogic open FSharp.Compiler.Ast open FSharp.Compiler.CompileOptions open FSharp.Compiler.CompileOps open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Infos open FSharp.Compiler.InfoReader open FSharp.Compiler.NameResolution @@ -389,9 +390,7 @@ type internal FsiValuePrinter(fsi: FsiEvaluationSessionHostConfig, g: TcGlobals, | PrintExpr -> anyToLayoutCall.AnyToLayout(opts, x, ty) with -#if !FX_REDUCED_EXCEPTIONS | :? ThreadAbortException -> Layout.wordL (TaggedTextOps.tagText "") -#endif | e -> #if DEBUG printf "\n\nPrintValue: x = %+A and ty=%s\n" x (ty.FullName) @@ -803,7 +802,6 @@ let internal InstallErrorLoggingOnThisThread errorLogger = SetThreadErrorLoggerNoUnwind(errorLogger) SetThreadBuildPhaseNoUnwind(BuildPhase.Interactive) -#if !FX_NO_SERVERCODEPAGES /// Set the input/output encoding. The use of a thread is due to a known bug on /// on Vista where calls to Console.InputEncoding can block the process. let internal SetServerCodePages(fsiOptions: FsiCommandLineOptions) = @@ -833,7 +831,6 @@ let internal SetServerCodePages(fsiOptions: FsiCommandLineOptions) = if not !successful then System.Windows.Forms.MessageBox.Show(FSIstrings.SR.fsiConsoleProblem()) |> ignore #endif -#endif //---------------------------------------------------------------------------- // Prompt printing @@ -1618,9 +1615,11 @@ type internal FsiStdinLexerProvider let initialLightSyntaxStatus = tcConfigB.light <> Some false LightSyntaxStatus (initialLightSyntaxStatus, false (* no warnings *)) + let isFeatureSupported featureId = tcConfigB.langVersion.SupportsFeature featureId + let LexbufFromLineReader (fsiStdinSyphon: FsiStdinSyphon) readf = - UnicodeLexing.FunctionAsLexbuf - (fun (buf: char[], start, len) -> + UnicodeLexing.FunctionAsLexbuf + (isFeatureSupported, (fun (buf: char[], start, len) -> //fprintf fsiConsoleOutput.Out "Calling ReadLine\n" let inputOption = try Some(readf()) with :? EndOfStreamException -> None inputOption |> Option.iter (fun t -> fsiStdinSyphon.Add (t + "\n")) @@ -1636,7 +1635,7 @@ type internal FsiStdinLexerProvider for i = 0 to ntrimmed-1 do buf.[i+start] <- input.[i] ntrimmed - ) + )) //---------------------------------------------------------------------------- // Reading stdin as a lex stream @@ -1657,6 +1656,7 @@ type internal FsiStdinLexerProvider let tokenizer = LexFilter.LexFilter(interactiveInputLightSyntaxStatus, tcConfigB.compilingFslib, Lexer.token lexargs skip, lexbuf) tokenizer + let isFeatureSupported featureId = tcConfigB.langVersion.SupportsFeature featureId // Create a new lexer to read stdin member __.CreateStdinLexer (errorLogger) = @@ -1675,12 +1675,12 @@ type internal FsiStdinLexerProvider // Create a new lexer to read an "included" script file member __.CreateIncludedScriptLexer (sourceFileName, errorLogger) = - let lexbuf = UnicodeLexing.UnicodeFileAsLexbuf(sourceFileName,tcConfigB.inputCodePage,(*retryLocked*)false) + let lexbuf = UnicodeLexing.UnicodeFileAsLexbuf(isFeatureSupported, sourceFileName, tcConfigB.inputCodePage, (*retryLocked*)false) CreateLexerForLexBuffer (sourceFileName, lexbuf, errorLogger) // Create a new lexer to read a string member this.CreateStringLexer (sourceFileName, source, errorLogger) = - let lexbuf = UnicodeLexing.StringAsLexbuf(source) + let lexbuf = UnicodeLexing.StringAsLexbuf(isFeatureSupported, source) CreateLexerForLexBuffer (sourceFileName, lexbuf, errorLogger) member __.ConsoleInput = fsiConsoleInput @@ -1738,6 +1738,7 @@ type internal FsiInteractionProcessor stopProcessingRecovery e range0 istate,CompletedWithReportedError e + let isFeatureSupported featureId = tcConfigB.langVersion.SupportsFeature featureId let rangeStdin = rangeN Lexhelp.stdinMockFilename 0 @@ -1944,13 +1945,11 @@ type internal FsiInteractionProcessor fsiInterruptController.InterruptAllowed <- InterruptIgnored; res with -#if !FX_REDUCED_EXCEPTIONS | :? ThreadAbortException -> fsiInterruptController.ClearInterruptRequest() fsiInterruptController.InterruptAllowed <- InterruptIgnored; (try Thread.ResetAbort() with _ -> ()); (istate,CtrlC) -#endif | e -> fsiInterruptController.ClearInterruptRequest() fsiInterruptController.InterruptAllowed <- InterruptIgnored; @@ -1964,11 +1963,7 @@ type internal FsiInteractionProcessor let parseExpression (tokenizer:LexFilter.LexFilter) = reusingLexbufForParsing tokenizer.LexBuffer (fun () -> Parser.typedSeqExprEOF tokenizer.Lexer tokenizer.LexBuffer) - -// let parseType (tokenizer:LexFilter.LexFilter) = -// reusingLexbufForParsing tokenizer.LexBuffer (fun () -> -// Parser.typEOF tokenizer.Lexer tokenizer.LexBuffer) - + let mainThreadProcessParsedExpression ctok errorLogger (expr, istate) = istate |> InteractiveCatch errorLogger (fun istate -> istate |> mainThreadProcessAction ctok (fun ctok _tcConfig istate -> @@ -2096,7 +2091,7 @@ type internal FsiInteractionProcessor use _unwind1 = ErrorLogger.PushThreadBuildPhaseUntilUnwind(ErrorLogger.BuildPhase.Interactive) use _unwind2 = ErrorLogger.PushErrorLoggerPhaseUntilUnwind(fun _ -> errorLogger) use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID - let lexbuf = UnicodeLexing.StringAsLexbuf(sourceText) + let lexbuf = UnicodeLexing.StringAsLexbuf(isFeatureSupported, sourceText) let tokenizer = fsiStdinLexerProvider.CreateBufferLexer(scriptFileName, lexbuf, errorLogger) currState |> InteractiveCatch errorLogger (fun istate -> @@ -2113,7 +2108,7 @@ type internal FsiInteractionProcessor use _unwind1 = ErrorLogger.PushThreadBuildPhaseUntilUnwind(ErrorLogger.BuildPhase.Interactive) use _unwind2 = ErrorLogger.PushErrorLoggerPhaseUntilUnwind(fun _ -> errorLogger) use _scope = SetCurrentUICultureForThread fsiOptions.FsiLCID - let lexbuf = UnicodeLexing.StringAsLexbuf(sourceText) + let lexbuf = UnicodeLexing.StringAsLexbuf(isFeatureSupported, sourceText) let tokenizer = fsiStdinLexerProvider.CreateBufferLexer(scriptFileName, lexbuf, errorLogger) currState |> InteractiveCatch errorLogger (fun istate -> @@ -2263,7 +2258,6 @@ let internal DriveFsiEventLoop (fsi: FsiEvaluationSessionHostConfig, fsiConsoleO if !progress then fprintfn fsiConsoleOutput.Out "MAIN: entering event loop..."; fsi.EventLoopRun() with -#if !FX_REDUCED_EXCEPTIONS | :? ThreadAbortException -> // If this TAE handler kicks it's almost certainly too late to save the // state of the process - the state of the message loop may have been corrupted @@ -2271,7 +2265,6 @@ let internal DriveFsiEventLoop (fsi: FsiEvaluationSessionHostConfig, fsiConsoleO (try Thread.ResetAbort() with _ -> ()); true // Try again, just case we can restart -#endif | e -> stopProcessingRecovery e range0; true @@ -2368,20 +2361,14 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i do match tcConfigB.preferredUiLang with -#if FX_RESHAPED_GLOBALIZATION - | Some s -> System.Globalization.CultureInfo.CurrentUICulture <- new System.Globalization.CultureInfo(s) -#else | Some s -> Thread.CurrentThread.CurrentUICulture <- new System.Globalization.CultureInfo(s) -#endif | None -> () -#if !FX_NO_SERVERCODEPAGES - do - try - SetServerCodePages fsiOptions - with e -> + do + try + SetServerCodePages fsiOptions + with e -> warning(e) -#endif do updateBannerText() // resetting banner text after parsing options @@ -2572,8 +2559,8 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i member x.FormatValue(obj:obj, objTy) = fsiDynamicCompiler.FormatValue(obj, objTy) - member x.EvalExpression(sourceText) = - + member x.EvalExpression(sourceText) = + // Explanation: When the user of the FsiInteractiveSession object calls this method, the // code is parsed, checked and evaluated on the calling thread. This means EvalExpression // is not safe to call concurrently. @@ -2582,7 +2569,7 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i fsiInteractionProcessor.EvalExpression(ctok, sourceText, dummyScriptFileName, errorLogger) |> commitResult - member x.EvalExpressionNonThrowing(sourceText) = + member x.EvalExpressionNonThrowing(sourceText) = // Explanation: When the user of the FsiInteractiveSession object calls this method, the // code is parsed, checked and evaluated on the calling thread. This means EvalExpression // is not safe to call concurrently. diff --git a/src/fsharp/fsi/fsi.fsproj b/src/fsharp/fsi/fsi.fsproj index 96293d2d77c..5b4978679b2 100644 --- a/src/fsharp/fsi/fsi.fsproj +++ b/src/fsharp/fsi/fsi.fsproj @@ -34,9 +34,6 @@ - - - diff --git a/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf b/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf index 404171af9a3..0e7145c703e 100644 --- a/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf +++ b/src/fsharp/fsi/xlf/FSIstrings.txt.de.xlf @@ -14,27 +14,27 @@ - INPUT FILES - - - EINGABEDATEIEN - + – EINGABEDATEIEN – - CODE GENERATION - - - CODEGENERIERUNG - + – CODEGENERIERUNG – - ERRORS AND WARNINGS - - - FEHLER UND WARNUNGEN - + – FEHLER UND WARNUNGEN – - LANGUAGE - - - SPRACHE - + – SPRACHE – - MISCELLANEOUS - - - VERSCHIEDENES - + – VERSCHIEDENES – @@ -199,7 +199,7 @@ - Aborting main thread... - - Hauptthread wird abgebrochen... + – Hauptthread wird abgebrochen... diff --git a/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf b/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf index 0751b4601e4..c70b2e1dd3c 100644 --- a/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf +++ b/src/fsharp/fsi/xlf/FSIstrings.txt.ja.xlf @@ -129,7 +129,7 @@ gen - gen + 全般 diff --git a/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf b/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf index 295ea674957..4ba5fc71b71 100644 --- a/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf +++ b/src/fsharp/fsi/xlf/FSIstrings.txt.zh-Hant.xlf @@ -74,7 +74,7 @@ Execute interactions on a Windows Forms event loop (on by default) - 在 Windows Form 事件迴圈上執行互動 (預設為開啟) + 在 Windows Forms 事件迴圈上執行互動 (預設為開啟) @@ -99,7 +99,7 @@ A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - 啟動 F# Interactive 處理序時發生問題。這可能是因為背景處理序主控台對於支援某些 Windows 系統上具備 Unicode 支援功能之應用程式的已知問題所造成。請嘗試選取 [工具]5D; -> [選項]5D; -> [F# Interactive for Visual Studio]5D;,然後輸入 '--fsi-server-no-unicode'。 + 啟動 F# 互動處理序時發生問題。這可能是因為背景處理序主控台對於支援某些 Windows 系統上具備 Unicode 支援功能之應用程式的已知問題所造成。請嘗試選取 [工具] -> [選項] -> [F# Interactive for Visual Studio],然後輸入 '--fsi-server-no-unicode'。 @@ -139,7 +139,7 @@ F# Interactive directives: - F# Interactive 指示詞: + F# 互動指示詞: @@ -174,7 +174,7 @@ F# Interactive command line options: - F# Interactive 命令列選項: + F# 互動命令列選項: @@ -214,7 +214,7 @@ --> Referenced '{0}' (file may be locked by F# Interactive process) - --> 參考的 '{0}' (檔案可能已被 F# Interactive 處理序鎖定) + --> 參考的 '{0}' (檔案可能已被 F# 互動處理序鎖定) @@ -264,7 +264,7 @@ Prevents references from being locked by the F# Interactive process - 避免參考遭 F# 互動式處理序封鎖 + 避免參考遭 F# 互動處理序封鎖 diff --git a/src/fsharp/infos.fs b/src/fsharp/infos.fs index dd6f8b0e3f3..4ca16f77cdd 100755 --- a/src/fsharp/infos.fs +++ b/src/fsharp/infos.fs @@ -835,7 +835,15 @@ type ILMethInfo = member x.IsDllImport (g: TcGlobals) = match g.attrib_DllImportAttribute with | None -> false - | Some (AttribInfo(tref, _)) ->x.RawMetadata.CustomAttrs |> TryDecodeILAttribute g tref |> Option.isSome + | Some attr -> + x.RawMetadata.CustomAttrs + |> TryFindILAttribute attr + + /// Indicates if the method is marked with the [] attribute. This is done by looking at the IL custom attributes on + /// the method. + member x.IsReadOnly (g: TcGlobals) = + x.RawMetadata.CustomAttrs + |> TryFindILAttribute g.attrib_IsReadOnlyAttribute /// Get the (zero or one) 'self'/'this'/'object' arguments associated with an IL method. /// An instance extension method returns one object argument. @@ -1238,6 +1246,25 @@ type MethInfo = member x.IsStruct = isStructTy x.TcGlobals x.ApparentEnclosingType + /// Indicates if this method is read-only; usually by the [] attribute. + /// Must be an instance method. + /// Receiver must be a struct type. + member x.IsReadOnly = + // Perf Review: Is there a way we can cache this result? + x.IsInstance && + x.IsStruct && + match x with + | ILMeth (g, ilMethInfo, _) -> ilMethInfo.IsReadOnly g + | FSMeth _ -> false // F# defined methods not supported yet. Must be a language feature. + | _ -> false + + /// Indicates if this method is an extension member that is read-only. + /// An extension member is considered read-only if the first argument is a read-only byref (inref) type. + member x.IsReadOnlyExtensionMember (amap: Import.ImportMap, m) = + x.IsExtensionMember && + x.TryObjArgByrefType(amap, m, x.FormalMethodInst) + |> Option.exists (isInByrefTy amap.g) + /// Build IL method infos. static member CreateILMeth (amap: Import.ImportMap, m, ty: TType, md: ILMethodDef) = let tinfo = ILTypeInfo.FromType amap.g ty diff --git a/src/fsharp/lex.fsl b/src/fsharp/lex.fsl index a0d3f449c0e..a3a0003f57e 100644 --- a/src/fsharp/lex.fsl +++ b/src/fsharp/lex.fsl @@ -23,6 +23,7 @@ open FSharp.Compiler open FSharp.Compiler.Range open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Parser open FSharp.Compiler.Lexhelp open FSharp.Compiler.Lib @@ -83,11 +84,7 @@ let parseInt32 (s:string) = let mutable p = 0 let sign = getSign32 s &p l let specifier = get0OXB s &p l -#if FX_RESHAPED_GLOBALIZATION - match CultureInfo.InvariantCulture.TextInfo.ToLower(specifier) with -#else match Char.ToLower(specifier,CultureInfo.InvariantCulture) with -#endif | 'x' -> sign * (int32 (Convert.ToUInt32(UInt64.Parse(s.Substring(p), NumberStyles.AllowHexSpecifier,CultureInfo.InvariantCulture)))) | 'b' -> sign * (int32 (Convert.ToUInt32(parseBinaryUInt64 (s.Substring(p))))) | 'o' -> sign * (int32 (Convert.ToUInt32(parseOctalUInt64 (s.Substring(p))))) @@ -144,19 +141,17 @@ let tryAppendXmlDoc (buff:option) (s:string) = let shouldStartLine args lexbuf (m:range) err tok = if (m.StartColumn <> 0) then fail args lexbuf err tok else tok - + let shouldStartFile args lexbuf (m:range) err tok = if (m.StartColumn <> 0 || m.StartLine <> 1) then fail args lexbuf err tok else tok - -let evalIfDefExpression startPos args (lookup:string->bool) (lexed:string) = - let lexbuf = LexBuffer.FromChars (lexed.ToCharArray ()) + +let evalIfDefExpression startPos isFeatureSupported args (lookup:string->bool) (lexed:string) = + let lexbuf = LexBuffer.FromChars (isFeatureSupported, lexed.ToCharArray ()) lexbuf.StartPos <- startPos lexbuf.EndPos <- startPos let tokenStream = FSharp.Compiler.PPLexer.tokenstream args - let expr = FSharp.Compiler.PPParser.start tokenStream lexbuf - LexerIfdefEval lookup expr } @@ -614,7 +609,7 @@ rule token args skip = parse { let m = lexbuf.LexemeRange let lookup id = List.contains id args.defines let lexed = lexeme lexbuf - let isTrue = evalIfDefExpression lexbuf.StartPos args lookup lexed + let isTrue = evalIfDefExpression lexbuf.StartPos lexbuf.SupportsFeature args lookup lexed args.ifdefStack := (IfDefIf,m) :: !(args.ifdefStack) // Get the token; make sure it starts at zero position & return diff --git a/src/fsharp/lib.fs b/src/fsharp/lib.fs index dfcbddc2da3..6c4599f8a1c 100755 --- a/src/fsharp/lib.fs +++ b/src/fsharp/lib.fs @@ -513,9 +513,7 @@ module UnmanagedProcessExecutionOptions = extern UInt32 private GetLastError() // Translation of C# from http://swikb/v1/DisplayOnlineDoc.aspx?entryID=826 and copy in bug://5018 -#if !FX_NO_SECURITY_PERMISSIONS [] -#endif let EnableHeapTerminationOnCorruption() = if (System.Environment.OSVersion.Version.Major >= 6 && // If OS is Vista or higher System.Environment.Version.Major < 3) then // and CLR not 3.0 or higher diff --git a/src/fsharp/pars.fsy b/src/fsharp/pars.fsy index 66d72782e3a..cb2b0a7020b 100644 --- a/src/fsharp/pars.fsy +++ b/src/fsharp/pars.fsy @@ -18,6 +18,7 @@ open FSharp.Compiler.Ast open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features #if DEBUG let debugPrint(s) = @@ -129,9 +130,11 @@ let mkDefnBindings (mWhole,BindingSetPreAttrs(_,isRec,isUse,declsPreAttrs,_bindi let attrDecls = if not (isNil freeAttrs) then [ SynModuleDecl.Attributes (freeAttrs,attrsm) ] else [] attrDecls @ letDecls -let idOfPat m p = - match p with - | SynPat.Named (SynPat.Wild _,id,false,_,_) -> id +let idOfPat (parseState:IParseState) m p = + match p with + | SynPat.Wild r when parseState.LexBuffer.SupportsFeature LanguageFeature.WildCardInForLoop -> + mkSynId r "_" + | SynPat.Named (SynPat.Wild _,id,false,_,_) -> id | SynPat.LongIdent(LongIdentWithDots([id],_),_,None, SynConstructorArgs.Pats [], None,_) -> id | _ -> raiseParseErrorAt m (FSComp.SR.parsIntegerForLoopRequiresSimpleIdentifier()) @@ -1913,8 +1916,12 @@ opt_typ: | /* EMPTY */ { None } | COLON typ { Some $2 } - atomicPatternLongIdent: + | UNDERSCORE DOT pathOp { + if not (parseState.LexBuffer.SupportsFeature LanguageFeature.SingleUnderscorePattern) then + raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnexpectedSymbolDot()) + let (LongIdentWithDots(lid,dotms)) = $3 in (None,LongIdentWithDots(ident("_",rhs parseState 1)::lid, rhs parseState 2::dotms)) + } | GLOBAL DOT pathOp { let (LongIdentWithDots(lid,dotms)) = $3 in (None,LongIdentWithDots(ident(MangledGlobalName,rhs parseState 1) :: lid, rhs parseState 2 :: dotms)) } | pathOp { (None,$1) } | access pathOp { (Some($1), $2) } @@ -2106,7 +2113,7 @@ inlineAssemblyTyconRepr: | HASH stringOrKeywordString HASH { libraryOnlyError (lhs parseState) let lhsm = lhs parseState - SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (ParseAssemblyCodeType $2 (rhs parseState 2),lhsm) } + SynTypeDefnSimpleRepr.LibraryOnlyILAssembly (internalParseAssemblyCodeType $2 parseState.LexBuffer.SupportsFeature (rhs parseState 2),lhsm) } classOrInterfaceOrStruct: | CLASS { TyconClass } @@ -4002,7 +4009,7 @@ forLoopBinder: forLoopRange: | parenPattern EQUALS declExpr forLoopDirection declExpr - { idOfPat (rhs parseState 1) $1,$3,$4,$5 } + { idOfPat parseState (rhs parseState 1) $1,$3,$4,$5 } | parenPattern EQUALS rangeSequenceExpr { raiseParseErrorAt (rhs parseState 2) (FSComp.SR.parsUnexpectedSymbolEqualsInsteadOfIn()) } @@ -4015,11 +4022,11 @@ inlineAssemblyExpr: | HASH stringOrKeywordString opt_inlineAssemblyTypeArg opt_curriedArgExprs opt_inlineAssemblyReturnTypes HASH { libraryOnlyWarning (lhs parseState) let s,sm = $2,rhs parseState 2 - (fun m -> SynExpr.LibraryOnlyILAssembly (ParseAssemblyCodeInstructions s sm,$3,List.rev $4,$5,m)) } - -opt_curriedArgExprs: - | opt_curriedArgExprs argExpr %prec expr_args - { $2 :: $1 } + (fun m -> SynExpr.LibraryOnlyILAssembly (internalParseAssemblyCodeInstructions s parseState.LexBuffer.SupportsFeature sm, $3, List.rev $4, $5, m)) } + +opt_curriedArgExprs: + | opt_curriedArgExprs argExpr %prec expr_args + { $2 :: $1 } | { [] } diff --git a/src/fsharp/service/FSharpCheckerResults.fs b/src/fsharp/service/FSharpCheckerResults.fs index d8cfe81430a..6b493ca332c 100644 --- a/src/fsharp/service/FSharpCheckerResults.fs +++ b/src/fsharp/service/FSharpCheckerResults.fs @@ -21,6 +21,7 @@ open FSharp.Compiler.Ast open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Lib open FSharp.Compiler.PrettyNaming open FSharp.Compiler.Parser @@ -849,7 +850,12 @@ type internal TypeCheckInfo | Some(CompletionContext.OpenDeclaration) -> GetDeclaredItems (parseResultsOpt, lineStr, origLongIdentOpt, colAtEndOfNamesAndResidue, residueOpt, lastDotPos, line, loc, filterCtors, resolveOverloads, hasTextChangedSinceLastTypecheck, false, getAllSymbols) |> Option.map (fun (items, denv, m) -> - items |> List.filter (fun x -> match x.Item with Item.ModuleOrNamespaces _ -> true | _ -> false), denv, m) + items + |> List.filter (fun x -> + match x.Item with + | Item.ModuleOrNamespaces _ -> true + | Item.Types (_, tcrefs) when tcrefs |> List.exists (fun ty -> isAppTy g ty && isStaticClass g (tcrefOfAppTy g ty)) -> true + | _ -> false), denv, m) // Completion at '(x: ...)" | Some (CompletionContext.PatternType) -> @@ -1276,9 +1282,8 @@ type internal TypeCheckInfo valRefEq g g.reraise_vref vref || valRefEq g g.typeof_vref vref || valRefEq g g.typedefof_vref vref || - valRefEq g g.sizeof_vref vref - // TODO uncomment this after `nameof` operator is implemented - // || valRefEq g g.nameof_vref vref + valRefEq g g.sizeof_vref vref || + valRefEq g g.nameof_vref vref then Some() else None @@ -1525,8 +1530,12 @@ module internal ParseAndCheckFile = let tokenizer = LexFilter.LexFilter(lightSyntaxStatus, options.CompilingFsLib, Lexer.token lexargs true, lexbuf) tokenizer.Lexer - let createLexbuf sourceText = - UnicodeLexing.SourceTextAsLexbuf(sourceText) + // Public callers are unable to answer LanguageVersion feature support questions. + // External Tools including the VS IDE will enable the default LanguageVersion + let isFeatureSupported (_featureId:LanguageFeature) = true + + let createLexbuf sourceText isFeatureSupported = + UnicodeLexing.SourceTextAsLexbuf(isFeatureSupported, sourceText) let matchBraces(sourceText: ISourceText, fileName, options: FSharpParsingOptions, userOpName: string, suggestNamesForErrors: bool) = let delayedLogger = CapturingErrorLogger("matchBraces") @@ -1541,7 +1550,7 @@ module internal ParseAndCheckFile = use _unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse let matchingBraces = new ResizeArray<_>() - Lexhelp.usingLexbufForParsing(createLexbuf sourceText, fileName) (fun lexbuf -> + Lexhelp.usingLexbufForParsing(createLexbuf sourceText isFeatureSupported, fileName) (fun lexbuf -> let errHandler = ErrorHandler(false, fileName, options.ErrorSeverityOptions, sourceText, suggestNamesForErrors) let lexfun = createLexerFunction fileName options lexbuf errHandler let parenTokensBalance t1 t2 = @@ -1577,7 +1586,7 @@ module internal ParseAndCheckFile = use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse let parseResult = - Lexhelp.usingLexbufForParsing(createLexbuf sourceText, fileName) (fun lexbuf -> + Lexhelp.usingLexbufForParsing(createLexbuf sourceText isFeatureSupported, fileName) (fun lexbuf -> let lexfun = createLexerFunction fileName options lexbuf errHandler let isLastCompiland = fileName.Equals(options.LastFileName, StringComparison.CurrentCultureIgnoreCase) || diff --git a/src/fsharp/service/IncrementalBuild.fs b/src/fsharp/service/IncrementalBuild.fs index 4099b59c803..96e81e32147 100755 --- a/src/fsharp/service/IncrementalBuild.fs +++ b/src/fsharp/service/IncrementalBuild.fs @@ -1052,7 +1052,7 @@ type TypeCheckAccumulator = /// Global service state -type FrameworkImportsCacheKey = (*resolvedpath*)string list * string * (*TargetFrameworkDirectories*)string list* (*fsharpBinaries*)string +type FrameworkImportsCacheKey = (*resolvedpath*)string list * string * (*TargetFrameworkDirectories*)string list * (*fsharpBinaries*)string * (*langVersion*)decimal /// Represents a cache of 'framework' references that can be shared betweeen multiple incremental builds type FrameworkImportsCache(keepStrongly) = @@ -1083,12 +1083,13 @@ type FrameworkImportsCache(keepStrongly) = // The data elements in this key are very important. There should be nothing else in the TcConfig that logically affects // the import of a set of framework DLLs into F# CCUs. That is, the F# CCUs that result from a set of DLLs (including // FSharp.Core.dll and mscorlib.dll) must be logically invariant of all the other compiler configuration parameters. - let key = (frameworkDLLsKey, - tcConfig.primaryAssembly.Name, - tcConfig.GetTargetFrameworkDirectories(), - tcConfig.fsharpBinariesDir) + let key = (frameworkDLLsKey, + tcConfig.primaryAssembly.Name, + tcConfig.GetTargetFrameworkDirectories(), + tcConfig.fsharpBinariesDir, + tcConfig.langVersion.SpecifiedVerson) - match frameworkTcImportsCache.TryGet (ctok, key) with + match frameworkTcImportsCache.TryGet (ctok, key) with | Some res -> return res | None -> let tcConfigP = TcConfigProvider.Constant tcConfig diff --git a/src/fsharp/service/Reactor.fs b/src/fsharp/service/Reactor.fs index cc2a6af8449..f879e5133f9 100755 --- a/src/fsharp/service/Reactor.fs +++ b/src/fsharp/service/Reactor.fs @@ -64,11 +64,7 @@ type Reactor() = Trace.TraceInformation("Reactor: {0:n3} pausing {1} milliseconds", DateTime.Now.TimeOfDay.TotalSeconds, pauseBeforeBackgroundWork) pauseBeforeBackgroundWork return! inbox.TryReceive(timeout) } -#if FX_RESHAPED_GLOBALIZATION - CultureInfo.CurrentUICulture <- culture -#else Thread.CurrentThread.CurrentUICulture <- culture -#endif match msg with | Some (SetBackgroundOp bgOpOpt) -> //Trace.TraceInformation("Reactor: --> set background op, remaining {0}", inbox.CurrentQueueLength) diff --git a/src/fsharp/service/ServiceLexing.fs b/src/fsharp/service/ServiceLexing.fs index b59dad3586a..2deb0073598 100644 --- a/src/fsharp/service/ServiceLexing.fs +++ b/src/fsharp/service/ServiceLexing.fs @@ -15,6 +15,7 @@ open FSharp.Compiler.Parser open FSharp.Compiler.Range open FSharp.Compiler.Ast open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Lexhelp open FSharp.Compiler.Lib open Internal.Utilities @@ -767,18 +768,22 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, [] type FSharpSourceTokenizer(defineConstants: string list, filename: string option) = + + // Public callers are unable to answer LanguageVersion feature support questions. + // External Tools including the VS IDE will enable the default LanguageVersion + let isFeatureSupported (_featureId:LanguageFeature) = true + let lexResourceManager = new Lexhelp.LexResourceManager() let lexArgsLightOn = mkLexargs(filename, defineConstants, LightSyntaxStatus(true, false), lexResourceManager, ref [], DiscardErrorsLogger, PathMap.empty) let lexArgsLightOff = mkLexargs(filename, defineConstants, LightSyntaxStatus(false, false), lexResourceManager, ref [], DiscardErrorsLogger, PathMap.empty) member this.CreateLineTokenizer(lineText: string) = - let lexbuf = UnicodeLexing.StringAsLexbuf lineText + let lexbuf = UnicodeLexing.StringAsLexbuf(isFeatureSupported, lineText) FSharpLineTokenizer(lexbuf, Some lineText.Length, filename, lexArgsLightOn, lexArgsLightOff) - member this.CreateBufferTokenizer bufferFiller = - let lexbuf = UnicodeLexing.FunctionAsLexbuf bufferFiller + let lexbuf = UnicodeLexing.FunctionAsLexbuf(isFeatureSupported, bufferFiller) FSharpLineTokenizer(lexbuf, None, filename, lexArgsLightOn, lexArgsLightOff) module Keywords = diff --git a/src/fsharp/service/ServiceParseTreeWalk.fs b/src/fsharp/service/ServiceParseTreeWalk.fs index abd3472a680..eeab436524f 100755 --- a/src/fsharp/service/ServiceParseTreeWalk.fs +++ b/src/fsharp/service/ServiceParseTreeWalk.fs @@ -412,6 +412,7 @@ module public AstTraversal = dive synExpr2 synExpr2.Range traverseSynExpr] |> pick expr | SynExpr.Lazy (synExpr, _range) -> traverseSynExpr synExpr + | SynExpr.SequentialOrImplicitYield (_sequencePointInfoForSeq, synExpr, synExpr2, _, _range) | SynExpr.Sequential (_sequencePointInfoForSeq, _, synExpr, synExpr2, _range) -> [dive synExpr synExpr.Range traverseSynExpr dive synExpr2 synExpr2.Range traverseSynExpr] diff --git a/src/fsharp/service/ServiceUntypedParse.fs b/src/fsharp/service/ServiceUntypedParse.fs index f98fae2f720..84c8947d13d 100755 --- a/src/fsharp/service/ServiceUntypedParse.fs +++ b/src/fsharp/service/ServiceUntypedParse.fs @@ -299,6 +299,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op yield! walkTrySeqPt spTry yield! walkFinallySeqPt spFinally + | SynExpr.SequentialOrImplicitYield (spSeq, e1, e2, _, _) | SynExpr.Sequential (spSeq, _, e1, e2, _) -> yield! walkExpr (match spSeq with SuppressSequencePointOnStmtOfSequential -> false | _ -> true) e1 yield! walkExpr (match spSeq with SuppressSequencePointOnExprOfSequential -> false | _ -> true) e2 diff --git a/src/fsharp/service/service.fs b/src/fsharp/service/service.fs index 6250c87a929..7eac7390c29 100644 --- a/src/fsharp/service/service.fs +++ b/src/fsharp/service/service.fs @@ -19,6 +19,7 @@ open FSharp.Compiler.CompileOps open FSharp.Compiler.CompileOptions open FSharp.Compiler.Driver open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Lib open FSharp.Compiler.Range open FSharp.Compiler.TcGlobals diff --git a/src/fsharp/symbols/SymbolHelpers.fs b/src/fsharp/symbols/SymbolHelpers.fs index 1440eef5a4c..b1c46d9bd72 100644 --- a/src/fsharp/symbols/SymbolHelpers.fs +++ b/src/fsharp/symbols/SymbolHelpers.fs @@ -69,8 +69,8 @@ type FSharpErrorInfo(fileName, s: pos, e: pos, severity: FSharpErrorSeverity, me /// Decompose a warning or error into parts: position, severity, message, error number static member CreateFromExceptionAndAdjustEof(exn, isError, fallbackRange: range, (linesCount: int, lastLength: int), suggestNames: bool) = let r = FSharpErrorInfo.CreateFromException(exn, isError, fallbackRange, suggestNames) - - // Adjust to make sure that errors reported at Eof are shown at the linesCount + + // Adjust to make sure that errors reported at Eof are shown at the linesCount let startline, schange = min (r.StartLineAlternate, false) (linesCount, true) let endline, echange = min (r.EndLineAlternate, false) (linesCount, true) diff --git a/src/fsharp/tast.fs b/src/fsharp/tast.fs index dd8f0506f70..6e063cd8314 100644 --- a/src/fsharp/tast.fs +++ b/src/fsharp/tast.fs @@ -116,133 +116,137 @@ type ValFlags(flags: int64) = new (recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) = let flags = (match baseOrThis with - | BaseVal -> 0b0000000000000000000L - | CtorThisVal -> 0b0000000000000000010L - | NormalVal -> 0b0000000000000000100L - | MemberThisVal -> 0b0000000000000000110L) ||| - (if isCompGen then 0b0000000000000001000L - else 0b00000000000000000000L) ||| + | BaseVal -> 0b00000000000000000000L + | CtorThisVal -> 0b00000000000000000010L + | NormalVal -> 0b00000000000000000100L + | MemberThisVal -> 0b00000000000000000110L) ||| + (if isCompGen then 0b00000000000000001000L + else 0b000000000000000000000L) ||| (match inlineInfo with - | ValInline.PseudoVal -> 0b0000000000000000000L - | ValInline.Always -> 0b0000000000000010000L - | ValInline.Optional -> 0b0000000000000100000L - | ValInline.Never -> 0b0000000000000110000L) ||| + | ValInline.PseudoVal -> 0b00000000000000000000L + | ValInline.Always -> 0b00000000000000010000L + | ValInline.Optional -> 0b00000000000000100000L + | ValInline.Never -> 0b00000000000000110000L) ||| (match isMutable with - | Immutable -> 0b0000000000000000000L - | Mutable -> 0b0000000000001000000L) ||| + | Immutable -> 0b00000000000000000000L + | Mutable -> 0b00000000000001000000L) ||| (match isModuleOrMemberBinding with - | false -> 0b0000000000000000000L - | true -> 0b0000000000010000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000000010000000L) ||| (match isExtensionMember with - | false -> 0b0000000000000000000L - | true -> 0b0000000000100000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000000100000000L) ||| (match isIncrClassSpecialMember with - | false -> 0b0000000000000000000L - | true -> 0b0000000001000000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000001000000000L) ||| (match isTyFunc with - | false -> 0b0000000000000000000L - | true -> 0b0000000010000000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000000010000000000L) ||| (match recValInfo with - | ValNotInRecScope -> 0b0000000000000000000L - | ValInRecScope true -> 0b0000000100000000000L - | ValInRecScope false -> 0b0000001000000000000L) ||| + | ValNotInRecScope -> 0b00000000000000000000L + | ValInRecScope true -> 0b00000000100000000000L + | ValInRecScope false -> 0b00000001000000000000L) ||| (match allowTypeInst with - | false -> 0b0000000000000000000L - | true -> 0b0000100000000000000L) ||| + | false -> 0b00000000000000000000L + | true -> 0b00000100000000000000L) ||| (match isGeneratedEventVal with - | false -> 0b0000000000000000000L - | true -> 0b0100000000000000000L) + | false -> 0b00000000000000000000L + | true -> 0b00100000000000000000L) ValFlags flags member x.BaseOrThisInfo = - match (flags &&& 0b0000000000000000110L) with - | 0b0000000000000000000L -> BaseVal - | 0b0000000000000000010L -> CtorThisVal - | 0b0000000000000000100L -> NormalVal - | 0b0000000000000000110L -> MemberThisVal + match (flags &&& 0b00000000000000000110L) with + | 0b00000000000000000000L -> BaseVal + | 0b00000000000000000010L -> CtorThisVal + | 0b00000000000000000100L -> NormalVal + | 0b00000000000000000110L -> MemberThisVal | _ -> failwith "unreachable" - member x.IsCompilerGenerated = (flags &&& 0b0000000000000001000L) <> 0x0L + member x.IsCompilerGenerated = (flags &&& 0b00000000000000001000L) <> 0x0L member x.SetIsCompilerGenerated isCompGen = - let flags = (flags &&& ~~~0b0000000000000001000L) ||| + let flags = (flags &&& ~~~0b00000000000000001000L) ||| (match isCompGen with - | false -> 0b0000000000000000000L - | true -> 0b0000000000000001000L) + | false -> 0b00000000000000000000L + | true -> 0b00000000000000001000L) ValFlags flags member x.InlineInfo = - match (flags &&& 0b0000000000000110000L) with - | 0b0000000000000000000L -> ValInline.PseudoVal - | 0b0000000000000010000L -> ValInline.Always - | 0b0000000000000100000L -> ValInline.Optional - | 0b0000000000000110000L -> ValInline.Never + match (flags &&& 0b00000000000000110000L) with + | 0b00000000000000000000L -> ValInline.PseudoVal + | 0b00000000000000010000L -> ValInline.Always + | 0b00000000000000100000L -> ValInline.Optional + | 0b00000000000000110000L -> ValInline.Never | _ -> failwith "unreachable" member x.MutabilityInfo = - match (flags &&& 0b0000000000001000000L) with - | 0b0000000000000000000L -> Immutable - | 0b0000000000001000000L -> Mutable + match (flags &&& 0b00000000000001000000L) with + | 0b00000000000000000000L -> Immutable + | 0b00000000000001000000L -> Mutable | _ -> failwith "unreachable" member x.IsMemberOrModuleBinding = - match (flags &&& 0b0000000000010000000L) with - | 0b0000000000000000000L -> false - | 0b0000000000010000000L -> true + match (flags &&& 0b00000000000010000000L) with + | 0b00000000000000000000L -> false + | 0b00000000000010000000L -> true | _ -> failwith "unreachable" - member x.WithIsMemberOrModuleBinding = ValFlags(flags ||| 0b0000000000010000000L) + member x.WithIsMemberOrModuleBinding = ValFlags(flags ||| 0b00000000000010000000L) - member x.IsExtensionMember = (flags &&& 0b0000000000100000000L) <> 0L + member x.IsExtensionMember = (flags &&& 0b00000000000100000000L) <> 0L - member x.IsIncrClassSpecialMember = (flags &&& 0b0000000001000000000L) <> 0L + member x.IsIncrClassSpecialMember = (flags &&& 0b00000000001000000000L) <> 0L - member x.IsTypeFunction = (flags &&& 0b0000000010000000000L) <> 0L + member x.IsTypeFunction = (flags &&& 0b00000000010000000000L) <> 0L - member x.RecursiveValInfo = match (flags &&& 0b0000001100000000000L) with - | 0b0000000000000000000L -> ValNotInRecScope - | 0b0000000100000000000L -> ValInRecScope true - | 0b0000001000000000000L -> ValInRecScope false + member x.RecursiveValInfo = match (flags &&& 0b00000001100000000000L) with + | 0b00000000000000000000L -> ValNotInRecScope + | 0b00000000100000000000L -> ValInRecScope true + | 0b00000001000000000000L -> ValInRecScope false | _ -> failwith "unreachable" member x.WithRecursiveValInfo recValInfo = let flags = - (flags &&& ~~~0b0000001100000000000L) ||| + (flags &&& ~~~0b00000001100000000000L) ||| (match recValInfo with - | ValNotInRecScope -> 0b0000000000000000000L - | ValInRecScope true -> 0b0000000100000000000L - | ValInRecScope false -> 0b0000001000000000000L) + | ValNotInRecScope -> 0b00000000000000000000L + | ValInRecScope true -> 0b00000000100000000000L + | ValInRecScope false -> 0b00000001000000000000L) ValFlags flags - member x.MakesNoCriticalTailcalls = (flags &&& 0b0000010000000000000L) <> 0L + member x.MakesNoCriticalTailcalls = (flags &&& 0b00000010000000000000L) <> 0L - member x.WithMakesNoCriticalTailcalls = ValFlags(flags ||| 0b0000010000000000000L) + member x.WithMakesNoCriticalTailcalls = ValFlags(flags ||| 0b00000010000000000000L) - member x.PermitsExplicitTypeInstantiation = (flags &&& 0b0000100000000000000L) <> 0L + member x.PermitsExplicitTypeInstantiation = (flags &&& 0b00000100000000000000L) <> 0L - member x.HasBeenReferenced = (flags &&& 0b0001000000000000000L) <> 0L + member x.HasBeenReferenced = (flags &&& 0b00001000000000000000L) <> 0L - member x.WithHasBeenReferenced = ValFlags(flags ||| 0b0001000000000000000L) + member x.WithHasBeenReferenced = ValFlags(flags ||| 0b00001000000000000000L) - member x.IsCompiledAsStaticPropertyWithoutField = (flags &&& 0b0010000000000000000L) <> 0L + member x.IsCompiledAsStaticPropertyWithoutField = (flags &&& 0b00010000000000000000L) <> 0L - member x.WithIsCompiledAsStaticPropertyWithoutField = ValFlags(flags ||| 0b0010000000000000000L) + member x.WithIsCompiledAsStaticPropertyWithoutField = ValFlags(flags ||| 0b00010000000000000000L) - member x.IsGeneratedEventVal = (flags &&& 0b0100000000000000000L) <> 0L + member x.IsGeneratedEventVal = (flags &&& 0b00100000000000000000L) <> 0L - member x.IsFixed = (flags &&& 0b1000000000000000000L) <> 0L + member x.IsFixed = (flags &&& 0b01000000000000000000L) <> 0L - member x.WithIsFixed = ValFlags(flags ||| 0b1000000000000000000L) + member x.WithIsFixed = ValFlags(flags ||| 0b01000000000000000000L) + + member x.IgnoresByrefScope = (flags &&& 0b10000000000000000000L) <> 0L + + member x.WithIgnoresByrefScope = ValFlags(flags ||| 0b10000000000000000000L) /// Get the flags as included in the F# binary metadata member x.PickledBits = @@ -250,7 +254,7 @@ type ValFlags(flags: int64) = // Clear the IsCompiledAsStaticPropertyWithoutField, only used to determine whether to use a true field for a value, and to eliminate the optimization info for observable bindings // Clear the HasBeenReferenced, only used to report "unreferenced variable" warnings and to help collect 'it' values in FSI.EXE // Clear the IsGeneratedEventVal, since there's no use in propagating specialname information for generated add/remove event vals - (flags &&& ~~~0b0011001100000000000L) + (flags &&& ~~~0b10011001100000000000L) /// Represents the kind of a type parameter [] @@ -423,9 +427,9 @@ type EntityFlags(flags: int64) = /// These two bits represents the on-demand analysis about whether the entity has the IsByRefLike attribute member x.TryIsByRefLike = (flags &&& 0b000000011000000L) |> function - | 0b000000011000000L -> Some true - | 0b000000010000000L -> Some false - | _ -> None + | 0b000000011000000L -> ValueSome true + | 0b000000010000000L -> ValueSome false + | _ -> ValueNone /// Adjust the on-demand analysis about whether the entity has the IsByRefLike attribute member x.WithIsByRefLike flag = @@ -436,14 +440,14 @@ type EntityFlags(flags: int64) = | false -> 0b000000010000000L) EntityFlags flags - /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute member x.TryIsReadOnly = (flags &&& 0b000001100000000L) |> function - | 0b000001100000000L -> Some true - | 0b000001000000000L -> Some false - | _ -> None + | 0b000001100000000L -> ValueSome true + | 0b000001000000000L -> ValueSome false + | _ -> ValueNone - /// Adjust the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// Adjust the on-demand analysis about whether the entity has the IsReadOnly attribute member x.WithIsReadOnly flag = let flags = (flags &&& ~~~0b000001100000000L) ||| @@ -452,8 +456,24 @@ type EntityFlags(flags: int64) = | false -> 0b000001000000000L) EntityFlags flags + /// These two bits represents the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.TryIsAssumedReadOnly = (flags &&& 0b000110000000000L) + |> function + | 0b000110000000000L -> ValueSome true + | 0b000100000000000L -> ValueSome false + | _ -> ValueNone + + /// Adjust the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.WithIsAssumedReadOnly flag = + let flags = + (flags &&& ~~~0b000110000000000L) ||| + (match flag with + | true -> 0b000110000000000L + | false -> 0b000100000000000L) + EntityFlags flags + /// Get the flags as included in the F# binary metadata - member x.PickledBits = (flags &&& ~~~0b000001111000100L) + member x.PickledBits = (flags &&& ~~~0b000111111000100L) #if DEBUG @@ -1065,12 +1085,18 @@ and /// Represents a type definition, exception definition, module definition or /// Set the on-demand analysis about whether the entity has the IsByRefLike attribute member x.SetIsByRefLike b = x.entity_flags <- x.entity_flags.WithIsByRefLike b - /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute member x.TryIsReadOnly = x.entity_flags.TryIsReadOnly - /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute member x.SetIsReadOnly b = x.entity_flags <- x.entity_flags.WithIsReadOnly b + /// These two bits represents the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.TryIsAssumedReadOnly = x.entity_flags.TryIsAssumedReadOnly + + /// Set the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.SetIsAssumedReadOnly b = x.entity_flags <- x.entity_flags.WithIsAssumedReadOnly b + /// Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition member x.IsFSharpObjectModelTycon = match x.TypeReprInfo with | TFSharpObjectRepr _ -> true | _ -> false @@ -1446,7 +1472,10 @@ and IsSealed: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. - IsInterface: bool + IsAbstract: bool + + /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. + IsInterface: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. IsStructOrEnum: bool @@ -2009,6 +2038,7 @@ and Construct = IsStructOrEnum = st.PUntaint((fun st -> st.IsValueType || st.IsEnum), m) IsInterface = st.PUntaint((fun st -> st.IsInterface), m) IsSealed = st.PUntaint((fun st -> st.IsSealed), m) + IsAbstract = st.PUntaint((fun st -> st.IsAbstract), m) IsClass = st.PUntaint((fun st -> st.IsClass), m) IsErased = isErased IsSuppressRelocate = isSuppressRelocate } @@ -2721,6 +2751,9 @@ and [] /// Indicates if the value is pinned/fixed member x.IsFixed = x.val_flags.IsFixed + /// Indicates if the value will ignore byref scoping rules + member x.IgnoresByrefScope = x.val_flags.IgnoresByrefScope + /// Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, /// or does it have a signature?) member x.PermitsExplicitTypeInstantiation = x.val_flags.PermitsExplicitTypeInstantiation @@ -2944,6 +2977,8 @@ and [] member x.SetIsFixed() = x.val_flags <- x.val_flags.WithIsFixed + member x.SetIgnoresByrefScope() = x.val_flags <- x.val_flags.WithIgnoresByrefScope + member x.SetValReprInfo info = match x.val_opt_data with | Some optData -> optData.val_repr_info <- info @@ -3547,12 +3582,18 @@ and /// Set the on-demand analysis about whether the entity has the IsByRefLike attribute member x.SetIsByRefLike b = x.Deref.SetIsByRefLike b - /// The on-demand analysis about whether the entity has the IsByRefLike attribute + /// The on-demand analysis about whether the entity has the IsReadOnly attribute member x.TryIsReadOnly = x.Deref.TryIsReadOnly - /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct + /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute member x.SetIsReadOnly b = x.Deref.SetIsReadOnly b + /// The on-demand analysis about whether the entity is assumed to be a readonly struct + member x.TryIsAssumedReadOnly = x.Deref.TryIsAssumedReadOnly + + /// Set the on-demand analysis about whether the entity is assumed to be a readonly struct + member x.SetIsAssumedReadOnly b = x.Deref.SetIsAssumedReadOnly b + /// Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, /// which in F# is called a 'unknown representation' type). member x.IsHiddenReprTycon = x.Deref.IsHiddenReprTycon diff --git a/src/fsharp/xlf/FSComp.txt.cs.xlf b/src/fsharp/xlf/FSComp.txt.cs.xlf index 665567318f1..996f007de8d 100644 --- a/src/fsharp/xlf/FSComp.txt.cs.xlf +++ b/src/fsharp/xlf/FSComp.txt.cs.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Zobrazte si povolené hodnoty verze jazyka a pak zadejte požadovanou verzi, například latest nebo preview. + + + + Supported language versions: + Podporované jazykové verze: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Nerozpoznaná hodnota {0} pro parametr --langversion; seznam možností zobrazíte zadáním --langversion:? + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Neočekávaný symbol . v definici členu. Očekávalo se with, = nebo jiný token. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Zadejte algoritmus pro výpočet kontrolního součtu zdrojového souboru uloženého v PDB. Podporované hodnoty jsou: SHA1 nebo SHA256 (výchozí). Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + Algoritmus {0} není podporovaný. @@ -2029,7 +2049,7 @@ Type annotations on property getters and setters must be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...' - Poznámky typu u metod getter nebo setter vlastnosti se musí předávat až po get() nebo set(v). Příklad: with get() : string = + Poznámky typu u metod getter nebo setter vlastnosti se musí předávat až po get() nebo set(v). Příklad: with get() : string = ... @@ -7187,6 +7207,16 @@ Následující členy nemají žádnou implementaci (některé výsledky jsou vynechané): {0} Všechny členy rozhraní je potřeba implementovat a uvést pod příslušnou deklarací interface, třeba takto: interface ... with member ... + + Expression does not have a name. + Výraz není pojmenovaný. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + Použití operátoru nameof jako hodnoty funkce první třídy není povolené. + + Maps physical paths to source path names output by the compiler Mapuje fyzické cesty na názvy zdrojových cest z výstupu kompilátoru. diff --git a/src/fsharp/xlf/FSComp.txt.de.xlf b/src/fsharp/xlf/FSComp.txt.de.xlf index 93ec9cbaff4..44db98820d9 100644 --- a/src/fsharp/xlf/FSComp.txt.de.xlf +++ b/src/fsharp/xlf/FSComp.txt.de.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Zeigen Sie die zulässigen Werte für die Sprachversion an. Geben Sie die Sprachversion als "latest" oder "preview" an. + + + + Supported language versions: + Unterstützte Sprachversionen: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Unbekannter Wert "{0}" für "--langversion". Verwenden Sie "--langversion:?", um die vollständige Liste anzuzeigen. + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Unerwartetes Symbol "." in der Memberdefinition. Erwartet wurde "with", "=" oder ein anderes Token. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Geben Sie einen Algorithmus für die Berechnung der Quelldateiprüfsumme an, welcher in PDB gespeichert ist. Unterstützte Werte sind: SHA1 oder SHA256 (Standard) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + Algorithmus "{0}" wird nicht unterstützt @@ -334,7 +354,7 @@ Invalid directive. Expected '#time', '#time \"on\"' or '#time \"off\"'. - Ungültige Direktive. Erwartet wurde "#time", "#time \"on\"" oder '#time \"off\"". + Ungültige Direktive. Erwartet wurde "#time", '#time \"on\"' oder '#time \"off\"'. @@ -3959,7 +3979,7 @@ This definition may only be used in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - Diese Definition kann nur in einem Typ mit einem primären Konstruktor verwendet werden. Ziehen Sie in Betracht, Argumente zur Typdefinition hinzuzufügen, z. B. "type X(args) = ...". + Diese Definition kann nur in einem Typ mit einem primären Konstruktor verwendet werden. Ziehen Sie in Betracht, Argumente zur Typdefinition hinzuzufügen, z.B. "type X(args) = ...". @@ -4414,7 +4434,7 @@ - INPUT FILES - - - EINGABEDATEIEN - + – EINGABEDATEIEN – @@ -4424,7 +4444,7 @@ - CODE GENERATION - - - CODEGENERIERUNG - + - CODE GENERATION - @@ -4434,17 +4454,17 @@ - MISCELLANEOUS - - - VERSCHIEDENES - + – VERSCHIEDENES – - LANGUAGE - - - SPRACHE - + – SPRACHE – - ERRORS AND WARNINGS - - - FEHLER UND WARNUNGEN - + – FEHLER UND WARNUNGEN – @@ -4969,7 +4989,7 @@ This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - Dies ist kein gültiges numerisches Literal. Die folgenden numerischen Literale sind z. B. gültig: 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). + Dies ist kein gültiges numerisches Literal. Die folgenden numerischen Literale sind z.B. gültig: 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). @@ -5154,12 +5174,12 @@ Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - Entfernen Sie die Leerzeichen zwischen dem Typnamen und dem Typparameter, z. B. "\"type C<'T>\"", statt "type \"C <'T>\"". Typparameter müssen direkt an den Typnamen angeschlossen werden. + Entfernen Sie die Leerzeichen zwischen dem Typnamen und dem Typparameter, z.B. "\"type C<'T>\"", statt "type \"C <'T>\"". Typparameter müssen direkt an den Typnamen angeschlossen werden. Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - Entfernen Sie die Leerzeichen zwischen dem Typnamen und Typparameter, z. B. "\"C<'T>\"" statt "\"C <'T>\"". Typparameter müssen direkt an den Typnamen angeschlossen werden. + Entfernen Sie die Leerzeichen zwischen dem Typnamen und Typparameter, z.B. "\"C<'T>\"" statt "\"C <'T>\"". Typparameter müssen direkt an den Typnamen angeschlossen werden. @@ -5564,7 +5584,7 @@ Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly). - Statische Verknüpfungen dürfen beim Generieren einer Assembly mit Verweis auf System.Runtime (z. B. eine .NET Core- oder eine portierbare Assembly) nicht für eine Assembly verwendet werden, die auf mscorlib verweist (z. B. eine .NET Framework-Assembly). + Statische Verknüpfungen dürfen beim Generieren einer Assembly mit Verweis auf System.Runtime (z.B. eine .NET Core- oder eine portierbare Assembly) nicht für eine Assembly verwendet werden, die auf mscorlib verweist (z.B. eine .NET Framework-Assembly). @@ -5574,7 +5594,7 @@ Deterministic builds only support portable PDBs (--debug:portable or --debug:embedded) - Deterministische Builds unterstützen nur portable PDB-Dateien (--debug:portable oder --debug:embedded) + Deterministische Builds unterstützen nur portierbare PDBs ("--debug:portable" oder "--debug:embedded"). @@ -6149,7 +6169,7 @@ 'member val' definitions are only permitted in types with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - 'member val'-Definitionen sind nur in Typen mit einem primären Konstruktor zulässig. Möglicherweise sollten Sie Ihrer Typdefinition Argumente hinzufügen, z. B. 'type X(args) = ...'. + 'member val'-Definitionen sind nur in Typen mit einem primären Konstruktor zulässig. Möglicherweise sollten Sie Ihrer Typdefinition Argumente hinzufügen, z.B. 'type X(args) = ...'. @@ -6204,7 +6224,7 @@ This is not a known query operator. Query operators are identifiers such as 'select', 'where', 'sortBy', 'thenBy', 'groupBy', 'groupValBy', 'join', 'groupJoin', 'sumBy' and 'averageBy', defined using corresponding methods on the 'QueryBuilder' type. - Dies ist kein bekannter Abfrageoperator. Abfrageoperatoren sind Bezeichner wie z. B. 'select', 'where', 'sortBy', 'thenBy', 'groupBy', 'groupValBy', 'join', 'groupJoin', 'sumBy' und 'averageBy', die mithilfe der entsprechenden Methoden für den Typ 'QueryBuilder' definiert werden. + Dies ist kein bekannter Abfrageoperator. Abfrageoperatoren sind Bezeichner wie z.B. 'select', 'where', 'sortBy', 'thenBy', 'groupBy', 'groupValBy', 'join', 'groupJoin', 'sumBy' und 'averageBy', die mithilfe der entsprechenden Methoden für den Typ 'QueryBuilder' definiert werden. @@ -6244,7 +6264,7 @@ Arguments to query operators may require parentheses, e.g. 'where (x > y)' or 'groupBy (x.Length / 10)' - Argumente für Abfrageoperatoren erfordern möglicherweise Klammern, z. B. "where (x > y)" oder "groupBy (x.Length / 10)". + Argumente für Abfrageoperatoren erfordern möglicherweise Klammern, z.B. "where (x > y)" oder "groupBy (x.Length / 10)". @@ -6829,7 +6849,7 @@ Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in appropriate context. - Wird in Abfrageausdrücken verwendet, um festzulegen, welche Felder oder Spalten extrahiert werden. Dies ist kontextabhängiges Schlüsselwort, d. h. es ist kein reserviertes Wort und funktioniert nur im entsprechenden Kontext als Schlüsselwort. + Wird in Abfrageausdrücken verwendet, um festzulegen, welche Felder oder Spalten extrahiert werden. Dies ist kontextabhängiges Schlüsselwort, d. h. es ist kein reserviertes Wort und funktioniert nur im entsprechenden Kontext als Schlüsselwort. @@ -7049,7 +7069,7 @@ A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...' - Ein in einem Modul definierter Wert muss änderbar sein, um die Adresse anzunehmen, z. B. "let mutable x = ...". + Ein in einem Modul definierter Wert muss änderbar sein, um die Adresse anzunehmen, z.B. "let mutable x = ...". @@ -7187,6 +7207,16 @@ Für folgende Member wurde keine Implementierung angegeben (einige Ergebnisse ausgelassen): {0} Beachten Sie, dass alle Schnittstellenmember implementiert und in einer entsprechenden interface-Deklaration aufgeführt werden müssen, z.B. "interface ... with member ...". + + Expression does not have a name. + Ausdruck hat keinen Namen. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + Die Verwendung des Operators "nameof" als erstklassiger Funktionswert ist nicht zulässig. + + Maps physical paths to source path names output by the compiler Ordnet der Ausgabe von Quellpfadnamen des Compilers physische Pfade zu diff --git a/src/fsharp/xlf/FSComp.txt.es.xlf b/src/fsharp/xlf/FSComp.txt.es.xlf index 9969b04da4b..f67f43053ce 100644 --- a/src/fsharp/xlf/FSComp.txt.es.xlf +++ b/src/fsharp/xlf/FSComp.txt.es.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Mostrar los valores permitidos para la versión de idioma, especificar la versión de idioma como "latest" "preview" + + + + Supported language versions: + Versiones de lenguaje admitidas: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Valor no reconocido "{0}" para --langversion, use --langversion:? para una lista completa + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Símbolo inesperado "." en la definición de miembro. Se esperaba "with", "=" u otro token. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Especifique el algoritmo para calcular la suma de comprobación del archivo de origen almacenada en PDB. Los valores admitidos son SHA1 o SHA256 (predeterminado) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + No se admite el algoritmo '{0}' @@ -4954,7 +4974,7 @@ Invalid floating point number - número de punto flotante no válido. + Número de punto flotante no válido. @@ -5189,7 +5209,7 @@ The parameter '{0}' was inferred to have byref type. Parameters of byref type must be given an explicit type annotation, e.g. 'x1: byref<int>'. When used, a byref parameter is implicitly dereferenced. - Se infirió que el parámetro "{0}" tiene un tipo byref. Los parámetros de tipo byref deben recibir una anotación de tipo explícita, por ejemplo,"'x1: byref<int>". Cuando se usa, la referencia de un parámetro byref se elimina de forma implícita. + Se infirió que el parámetro "{0}" tiene un tipo byref. Los parámetros de tipo byref deben recibir una anotación de tipo explícita, por ejemplo,"x1: byref<int>". Cuando se usa, la referencia de un parámetro byref se elimina de forma implícita. @@ -7187,6 +7207,16 @@ No se ofreció ninguna implementación para esos miembros (se omitieron algunos resultados): {0} Tenga en cuenta que todos los miembros de la interfaz deben implementarse y enumerarse bajo una declaración de "interface" apropiada; por ejemplo, "interface ... with member ...". + + Expression does not have a name. + La expresión no tiene un nombre. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + No se permite el uso del operador "nameof" como un valor de función de primera clase. + + Maps physical paths to source path names output by the compiler Asigna rutas físicas de acceso a nombres de ruta de origen resultantes del compilador diff --git a/src/fsharp/xlf/FSComp.txt.fr.xlf b/src/fsharp/xlf/FSComp.txt.fr.xlf index c50670d8efa..e16fb76681e 100644 --- a/src/fsharp/xlf/FSComp.txt.fr.xlf +++ b/src/fsharp/xlf/FSComp.txt.fr.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Afficher les valeurs autorisées pour la version du langage, spécifier la version du langage comme 'dernière' ou 'préversion' + + + + Supported language versions: + Versions linguistiques prises en charge : + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Valeur non reconnue '{0}' pour --langversion use --langversion:? pour la liste complète + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Symbole '.' inattendu dans la définition du membre. 'with','=' ou autre jeton attendu. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Spécifiez l'algorithme pour calculer la somme de contrôle du fichier source stocké au format PDB. Les valeurs prises en charge sont : SHA1 ou SHA256 (par défaut) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + Algorithme '{0}' non pris en charge @@ -2249,7 +2269,7 @@ Invalid literal in type - littéral non valide dans le type + Littéral non valide dans le type @@ -7187,6 +7207,16 @@ Aucune implémentation pour ces membres (certains résultats sont omis) : {0} Notez que tous les membres d'interface doivent être implémentés et listés sous une déclaration 'interface' appropriée, par ex., 'interface ... with member ... '. + + Expression does not have a name. + L'expression n'a pas de nom. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + L'utilisation de l'opérateur 'nameof' comme valeur de fonction de première classe n'est pas autorisée. + + Maps physical paths to source path names output by the compiler Mappe les chemins physiques aux noms de chemin source générés par le compilateur diff --git a/src/fsharp/xlf/FSComp.txt.it.xlf b/src/fsharp/xlf/FSComp.txt.it.xlf index ad15c555b5e..2ef271b33ed 100644 --- a/src/fsharp/xlf/FSComp.txt.it.xlf +++ b/src/fsharp/xlf/FSComp.txt.it.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Visualizza i valori consentiti per la versione del linguaggio. Specificare la versione del linguaggio, ad esempio 'latest' o 'preview' + + + + Supported language versions: + Versioni del linguaggio supportate: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Valore '{0}' non riconosciuto per --langversion. Per l'elenco completo usare --langversion:? + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Simbolo '.' imprevisto nella definizione di membro. È previsto 'with', '=' o un altro token. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Consente di specificare l'algoritmo per calcolare il checksum del file di origine archiviato nel file PDB. I valori supportati sono SHA1 e SHA256 (predefinito). Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + L'algoritmo '{0}' non è supportato @@ -1979,7 +1999,7 @@ Syntax error - errore di sintassi + Errore di sintassi @@ -2294,12 +2314,12 @@ The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end' - La sintassi 'module ... = struct .. end' non è utilizzata nel codice F#. Provare a utilizzare 'module ... = begin .. end' + La sintassi 'module ... = struct .. end' non è usata nel codice F#. Provare a usare 'module ... = begin .. end' The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end' - La sintassi 'module ... : sig .. end' non è utilizzata nel codice F#. Provare a utilizzare 'module ... = begin .. end' + La sintassi 'module ... : sig .. end' non è usata nel codice F#. Provare a usare 'module ... = begin .. end' @@ -2669,7 +2689,7 @@ This property has an invalid type. Properties taking multiple indexer arguments should have types of the form 'ty1 * ty2 -> ty3'. Properties returning functions should have types of the form '(ty1 -> ty2)'. - La proprietà contiene un tipo non valido. Le proprietà che usano più argomenti di indicizzatore devono avere tipi nel formato 'ty1 * ty2 -> ty3'.. Le proprietà che restituiscono funzioni devono avere tipi nel formato '(ti1 -> ti2)'. + La proprietà contiene un tipo non valido. Le proprietà che usano più argomenti di indicizzatore devono avere tipi nel formato 'ty1 * ty2 -> ty3'. Le proprietà che restituiscono funzioni devono avere tipi nel formato '(ti1 -> ti2)'. @@ -2814,7 +2834,7 @@ This is not a valid pattern - Criterio non valido + Questo non è un criterio valido @@ -3289,7 +3309,7 @@ This is not a valid name for an active pattern - Il nome non è valido per un criterio attivo + Questo non è un nome valido per un criterio attivo @@ -7187,6 +7207,16 @@ Non è stata specificata alcuna implementazione per tali membri (alcuni risultati sono stati omessi): {0}. Si noti che tutti i membri dell'interfaccia devono essere implementati ed elencati in una dichiarazione 'interface' appropriata, ad esempio 'interface ... with member ...'. + + Expression does not have a name. + L'espressione non ha un nome. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + L'operatore 'nameof' non è consentito come valore di funzione di prima classe. + + Maps physical paths to source path names output by the compiler Esegue il mapping dei percorsi fisici ai nomi di percorso di origine restituiti dal compilatore diff --git a/src/fsharp/xlf/FSComp.txt.ja.xlf b/src/fsharp/xlf/FSComp.txt.ja.xlf index 2a65a01a763..d64338297fa 100644 --- a/src/fsharp/xlf/FSComp.txt.ja.xlf +++ b/src/fsharp/xlf/FSComp.txt.ja.xlf @@ -4,7 +4,27 @@ {0} for F# {1} - F# {1} の {0} + F# {1} のための {0} + + + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + 言語バージョンで許可された値を表示し、'最新' や 'プレビュー' などの言語バージョンを指定する + + + + Supported language versions: + サポートされる言語バージョン: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + --langversion の値 '{0}' が認識されません。完全なリストについては、--langversion:? を使用してください + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + メンバー定義に予期しない記号 '.' があります。'with'、'=' またはその他のトークンが必要です。 @@ -19,12 +39,12 @@ Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + PDB に格納されているソース ファイル チェックサムを計算するためのアルゴリズムを指定します。サポートされる値は次のとおりです: SHA1 または SHA256 (既定) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + アルゴリズム '{0}' はサポートされていません @@ -244,7 +264,7 @@ Unrecognized privacy setting '{0}' for managed resource, valid options are 'public' and 'private' - マネージ リソースの認識されないプライバシー設定 '{0}'。有効なオプションは 'public' および 'private' です。 + マネージド リソースの認識されないプライバシー設定 '{0}'。有効なオプションは 'public' および 'private' です。 @@ -269,7 +289,7 @@ Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'. Only the last source file of an application may omit such a declaration. - ライブラリまたは複数ファイル アプリケーション内のファイルは、名前空間またはモジュールの宣言から開始する必要があります (例: 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'。アプリケーションの最後のソース ファイルのみ、このような宣言を省略できます。 + ライブラリまたは複数ファイル アプリケーション内のファイルは、名前空間またはモジュールの宣言から開始する必要があります (例: 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule')。アプリケーションの最後のソース ファイルのみ、このような宣言を省略できます。 @@ -2294,7 +2314,7 @@ The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end' - F# コードでは 'module ... = struct .. end' という構文は使用されません。'module ... = begin .. end' を使用してください。 + F# コードでは ... 'module ... = struct .. end' という構文は使用されません。'module ... = begin .. end' を使用してください。 @@ -3549,8 +3569,7 @@ Uninitialized 'val' fields must be mutable and marked with the '[<DefaultValue>]' attribute. Consider using a 'let' binding instead of a 'val' field. - 初期化されていない 'val' フィールドは変更可能で、'[<DefaultValue>]' 属性によってマークされている必要があります。'val' フィールドの代わりに 'let' -バインディングの使用を検討してください。 + 初期化されていない 'val' フィールドは変更可能で、'[<DefaultValue>]' 属性によってマークされている必要があります。'val' フィールドの代わりに 'let' バインディングの使用を検討してください。 @@ -5155,13 +5174,12 @@ Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - 型名と型パラメーター間のスペースを削除します。たとえば、\"C <'T>\" ではなく \"type C<'T>\" と入力します。型パラメーターは型名に隣接していなければなりません。 + 型名と型パラメーターの間のスペースを削除します。たとえば、\"C <'T>\" ではなく \"C<'T>\" とします。型パラメーターは型名に隣接して配置する必要があります。 Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - 型名と型パラメーターの間のスペースを削除します。たとえば、 -\"C <'T>\" ではなく \"C<'T>\" とします。型パラメーターは型名に隣接して配置する必要があります。 + 型名と型パラメーターの間のスペースを削除します。たとえば、\"C <'T>\" ではなく \"C<'T>\" とします。型パラメーターは型名に隣接して配置する必要があります。 @@ -7189,6 +7207,16 @@ これらのメンバーに実装が指定されていません (一部の結果が省略されました): {0} すべてのインターフェイス メンバーは実装され、適切な 'interface' 宣言でリストされている必要があります。例: 'interface ... with member ...'。 + + Expression does not have a name. + 式に名前がありません。 + + + + Using the 'nameof' operator as a first-class function value is not permitted. + 'nameof' 演算子をファーストクラスの関数値として使用することは許可されていません。 + + Maps physical paths to source path names output by the compiler 物理パスをコンパイラ出力のソース パス名にマップします diff --git a/src/fsharp/xlf/FSComp.txt.ko.xlf b/src/fsharp/xlf/FSComp.txt.ko.xlf index 15a78d31778..03880250e9f 100644 --- a/src/fsharp/xlf/FSComp.txt.ko.xlf +++ b/src/fsharp/xlf/FSComp.txt.ko.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + 언어 버전의 허용된 값을 표시하고 '최신' 또는 '미리 보기'와 같은 언어 버전을 지정합니다. + + + + Supported language versions: + 지원되는 언어 버전: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + 전체 목록에 대한 --langversion use --langversion:?의 인식할 수 없는 값 '{0}'입니다. + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + 멤버 정의의 예기치 않은 기호 '.'입니다. 'with', '=' 또는 기타 토큰이 필요합니다. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + PDB에 저장된 소스 파일 체크섬을 계산하기 위한 알고리즘을 지정합니다. 지원되는 값은 SHA1 또는 SHA256(기본값)입니다. Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + {0}' 알고리즘은 지원되지 않습니다. @@ -7187,6 +7207,16 @@ 멤버 {0}에 지정된 구현이 없습니다(일부 결과는 생략됨). 모든 인터페이스 멤버가 구현되어 적절한 'interface' 선언에 나열되어야 합니다(예: 'interface ... with member ...'). + + Expression does not have a name. + 식에 이름이 없습니다. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + 'nameof' 연산자는 첫 번째 클래스 함수 값으로 사용할 수 없습니다. + + Maps physical paths to source path names output by the compiler 컴파일러에서 실제 경로를 소스 경로 이름 출력에 매핑합니다. diff --git a/src/fsharp/xlf/FSComp.txt.pl.xlf b/src/fsharp/xlf/FSComp.txt.pl.xlf index c169bb55bfc..98461fea0af 100644 --- a/src/fsharp/xlf/FSComp.txt.pl.xlf +++ b/src/fsharp/xlf/FSComp.txt.pl.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Wyświetl dozwolone wartości dla wersji językowej; określ wersję językową, np. „latest” lub „preview” + + + + Supported language versions: + Obsługiwane wersje językowe: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Nierozpoznana wartość „{0}” dla parametru –langversion; podaj parametr –langversion:?, aby uzyskać pełną listę + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Nieoczekiwany symbol „.” w definicji składowej. Oczekiwano ciągu „with”, znaku „=” lub innego tokenu. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Określ algorytm obliczania sumy kontrolnej pliku źródłowego przechowywanej w pliku PDB. Obsługiwane wartości to SHA1 lub SHA256 (domyślnie) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + Algorytm „{0}” nie jest obsługiwany @@ -7187,6 +7207,16 @@ Nie podano implementacji dla tych składowych (niektóre wyniki zostały pominięte): {0}Pamiętaj, że wszystkie składowe interfejsów muszą być zaimplementowane i wymienione w ramach odpowiedniej deklaracji „interface” np. „interface ... with member ...”. + + Expression does not have a name. + Wyrażenie nie ma nazwy. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + Używanie operatora „nameof” jako pierwszoklasowej wartości funkcji nie jest dozwolone. + + Maps physical paths to source path names output by the compiler Mapuje ścieżki fizyczne na wyjściowe nazwy ścieżek źródłowych z kompilatora diff --git a/src/fsharp/xlf/FSComp.txt.pt-BR.xlf b/src/fsharp/xlf/FSComp.txt.pt-BR.xlf index 6fc94fde878..bf05ba3e776 100644 --- a/src/fsharp/xlf/FSComp.txt.pt-BR.xlf +++ b/src/fsharp/xlf/FSComp.txt.pt-BR.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Exibe os valores permitidos para a versão do idioma, especifica a versão do idioma, como 'mais recente ' ou 'prévia' + + + + Supported language versions: + Versões de linguagens com suporte: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Valor não reconhecido '{0}' para --langversion use --langversion:? para a lista completa + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Símbolo inesperado '.' na definição de membro. Esperado 'com', '=' ou outro token. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Especifique o algoritmo para calcular a soma de verificação do arquivo de origem armazenada no PDB. Os valores suportados são: SHA1 ou SHA256 (padrão) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + Algoritmo '{0}' sem suporte @@ -1979,7 +1999,7 @@ Syntax error - erro de sintaxe + Erro de sintaxe @@ -7187,6 +7207,16 @@ Implementação não concedida para os membros (alguns resultados omitidos): {0} Todos os membros de interface devem ser implementados e listados em uma declaração de 'interface' apropriada, por exemplo, 'interface ... com o membro...'. + + Expression does not have a name. + A expressão não tem um nome. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + O uso do operador ' nameof ' como um valor de função de primeira classe não é permitido. + + Maps physical paths to source path names output by the compiler Mapeia caminhos físicos para nomes de caminho de origem gerados pelo compilador diff --git a/src/fsharp/xlf/FSComp.txt.ru.xlf b/src/fsharp/xlf/FSComp.txt.ru.xlf index 157b49fa5c9..16272ba0dc8 100644 --- a/src/fsharp/xlf/FSComp.txt.ru.xlf +++ b/src/fsharp/xlf/FSComp.txt.ru.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Отображение допустимых значений для версии языка. Укажите версию языка, например, "latest" или "preview". + + + + Supported language versions: + Поддерживаемые языковые версии: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + Не удалось распознать значение "{0}" для параметра --langversion. Для получения полного списка допустимых значений выполните команду use --langversion:? + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Неожиданный символ "." в определении члена. Ожидаемые инструкции: "with", "=" или другие токены. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + Укажите алгоритм для вычисления контрольной суммы исходного файла, хранящейся в файле PDB. Поддерживаемые значения: SHA1 или SHA256 (по умолчанию) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + Алгоритм "{0}" не поддерживается @@ -7187,6 +7207,16 @@ Реализация для этих членов отсутствует (некоторые результаты опущены): {0}Обратите внимание, что каждый член интерфейса должен быть реализован и указан в соответствующем объявлении "interface", например, "интерфейс ... с членом ...". + + Expression does not have a name. + Выражение не имеет имени. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + Использование оператора "nameof" в качестве значения функции первого класса не допускается. + + Maps physical paths to source path names output by the compiler Сопоставляет физические пути с исходными путями в выходных данных компилятора diff --git a/src/fsharp/xlf/FSComp.txt.tr.xlf b/src/fsharp/xlf/FSComp.txt.tr.xlf index 48e2433f2cf..85f8ee2f025 100644 --- a/src/fsharp/xlf/FSComp.txt.tr.xlf +++ b/src/fsharp/xlf/FSComp.txt.tr.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + Dil sürümü için izin verilen değerleri görüntüleyin, dil sürümünü 'en son' veya 'önizleme' örneklerindeki gibi belirtin + + + + Supported language versions: + Desteklenen dil sürümleri: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + --langversion için '{0}' değeri tanınmıyor. Tam liste için --langversion:? kullanın + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + Üye tanımında '.' sembolü beklenmiyordu. 'with', '=' veya başka bir belirteç bekleniyordu. + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + PDB içinde depolanan kaynak dosyası sağlama toplamını hesaplama algoritmasını belirtin. Desteklenen değerler: SHA1 veya SHA256 (varsayılan) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + {0}' algoritması desteklenmiyor @@ -7187,6 +7207,16 @@ Bu üyelere uygulama verilmedi (bazı sonuçlar atlandı): {0}Tüm arabirim üyelerinin uygulanması ve uygun bir "arabirim" bildirimi (ör. "arabirim ... ile üye ..." kapsamında listelenmesi gerektiğini unutmayın. + + Expression does not have a name. + İfade bir ada sahip değil. + + + + Using the 'nameof' operator as a first-class function value is not permitted. + 'Nameof' işlecinin birinci sınıf işlev değeri olarak kullanılmasına izin verilmez. + + Maps physical paths to source path names output by the compiler Fiziksel yolları derleyiciye göre kaynak yol adları çıkışıyla eşler diff --git a/src/fsharp/xlf/FSComp.txt.zh-Hans.xlf b/src/fsharp/xlf/FSComp.txt.zh-Hans.xlf index 46b4fc7896c..c0dbdcb1876 100644 --- a/src/fsharp/xlf/FSComp.txt.zh-Hans.xlf +++ b/src/fsharp/xlf/FSComp.txt.zh-Hans.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + 显示语言版本的允许值,指定语言版本,如“最新”或“预览” + + + + Supported language versions: + 支持的语言版本: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + --langversion 的值“{0}”无法识别,使用 --langversion:? 获取完整列表。 + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + 成员定义中有意外的符号 "."。预期 "with"、"+" 或其他标记。 + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + 指定用于计算存储在 PDB 中的源文件校验的算法。支持的值是:SHA1 或 SHA256(默认) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + 不支持算法“{0}” @@ -7187,6 +7207,16 @@ 没有为这些成员提供实现 (省略了一些结果): {0}请注意,必须实现所有接口成员,并在适当的 "interface" 声明下列出,例如 "interface ... with member ..."。 + + Expression does not have a name. + 表达式不具有名称。 + + + + Using the 'nameof' operator as a first-class function value is not permitted. + 不允许使用 "nameof" 运算符作为第一类函数的值。 + + Maps physical paths to source path names output by the compiler 将物理路径映射到编译器输出的源路径名 diff --git a/src/fsharp/xlf/FSComp.txt.zh-Hant.xlf b/src/fsharp/xlf/FSComp.txt.zh-Hant.xlf index d0329540271..90be2ee0817 100644 --- a/src/fsharp/xlf/FSComp.txt.zh-Hant.xlf +++ b/src/fsharp/xlf/FSComp.txt.zh-Hant.xlf @@ -17,14 +17,34 @@ Resource header beginning at offset {0} is malformed. + + Display the allowed values for language version, specify language version such as 'latest' or 'preview' + 顯示語言版本允許的值,指定 'latest' 或 'preview' 等語言版本 + + + + Supported language versions: + 支援的語言版本: + + + + Unrecognized value '{0}' for --langversion use --langversion:? for complete list + 對 --langversion 為無法識別的值 '{0}',對完整清單使用 --langversion:? + + + + Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + 成員定義中的非預期符號 '.'。預期為 'with'、'=' 或其他語彙基元。 + + Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) - Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default) + 請指定用來計算 PDB 中所儲存來源檔案總和檢查碼的演算法。支援的值為: SHA1 或 SHA256 (預設) Algorithm '{0}' is not supported - Algorithm '{0}' is not supported + 不支援演算法 '{0}' @@ -7187,6 +7207,16 @@ 未提供任何實作給這些成員 (部分結果已省略): {0}請注意,所有介面成員都必須經過實作,並列於適當的 'interface' 宣告下,例如 'interface ... with member ...'。 + + Expression does not have a name. + 運算式沒有名稱。 + + + + Using the 'nameof' operator as a first-class function value is not permitted. + 不允許使用"nameof" 運算子作為第一類函式值。 + + Maps physical paths to source path names output by the compiler 將實體路徑對應至來源路徑名稱,由編譯器輸出 diff --git a/src/fsharp/xlf/FSStrings.de.xlf b/src/fsharp/xlf/FSStrings.de.xlf index 60734cae522..7e373ec5342 100644 --- a/src/fsharp/xlf/FSStrings.de.xlf +++ b/src/fsharp/xlf/FSStrings.de.xlf @@ -74,7 +74,7 @@ Possible overload: '{0}'. {1}. - Mögliche Überladung: '{0}'. {1}. + Mögliche Überladung: "{0}". {1}. @@ -284,7 +284,7 @@ symbol ':?>' - Symbol ':?>' + Symbol ":?>" @@ -634,7 +634,7 @@ keyword 'const' - Schlüsselwort 'const' + Schlüsselwort "const" @@ -1434,7 +1434,7 @@ This value is not mutable. Consider using the mutable keyword, e.g. 'let mutable {0} = expression'. - Dieser Wert ist nicht änderbar. Verwenden Sie ggf. ein änderbares Schlüsselwort, z. B. "let mutable {0} = Ausdruck". + Dieser Wert ist nicht änderbar. Verwenden Sie ggf. ein änderbares Schlüsselwort, z.B. "let mutable {0} = Ausdruck". @@ -1549,17 +1549,17 @@ #I directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file, add a '-I' compiler option for this reference or delimit the directive with delimit it with '#if INTERACTIVE'/'#endif'. - #I-Direktiven dürfen nur in F#-Skriptdateien (Dateierweiterungen .fsx oder .fsscript) verwendet werden. Verschieben Sie entweder diesen Code in eine Skriptdatei, fügen Sie die Compileroption "-I" für diesen Verweis hinzu, oder trennen Sie die Direktive mit "#if INTERACTIVE'/'#endif" ab. + #I-Direktiven dürfen nur in F#-Skriptdateien (Dateierweiterungen .fsx oder .fsscript) verwendet werden. Verschieben Sie entweder diesen Code in eine Skriptdatei, fügen Sie die Compileroption "-I" für diesen Verweis hinzu, oder trennen Sie die Direktive mit "#if INTERACTIVE"/"#endif" ab. #r directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file or replace this reference with the '-r' compiler option. If this directive is being executed as user input, you may delimit it with '#if INTERACTIVE'/'#endif'. - #r-Anweisungen dürfen nur in F#-Skriptdateien (Dateierweiterungen .fsx oder .fsscript) verwendet werden. Verschieben Sie entweder diesen Code in eine Skriptdatei, oder ersetzen Sie diesen Verweis durch die Compileroption "-r". Wenn diese Anweisung als Benutzereingabe ausgeführt wird, trennen Sie sie mit "#if INTERACTIVE'/'#endif" ab. + #r-Anweisungen dürfen nur in F#-Skriptdateien (Dateierweiterungen .fsx oder .fsscript) verwendet werden. Verschieben Sie entweder diesen Code in eine Skriptdatei, oder ersetzen Sie diesen Verweis durch die Compileroption "-r". Wenn diese Anweisung als Benutzereingabe ausgeführt wird, trennen Sie sie mit "#if INTERACTIVE"/"#endif" ab. This directive may only be used in F# script files (extensions .fsx or .fsscript). Either remove the directive, move this code to a script file or delimit the directive with '#if INTERACTIVE'/'#endif'. - Diese Direktive darf nur in F#-Skriptdateien (Dateierweiterungen .fsx oder .fsscript) verwendet werden. Entfernen Sie entweder die Direktive, verschieben Sie diesen Code in eine Skriptdatei, oder trennen Sie die Direktive mit "#if INTERACTIVE'/'#endif" ab. + Diese Direktive darf nur in F#-Skriptdateien (Dateierweiterungen .fsx oder .fsscript) verwendet werden. Entfernen Sie entweder die Direktive, verschieben Sie diesen Code in eine Skriptdatei, oder trennen Sie die Direktive mit "#if INTERACTIVE"/"#endif" ab. diff --git a/src/fsharp/xlf/FSStrings.es.xlf b/src/fsharp/xlf/FSStrings.es.xlf index 238c6db5034..6ccd80493d7 100644 --- a/src/fsharp/xlf/FSStrings.es.xlf +++ b/src/fsharp/xlf/FSStrings.es.xlf @@ -954,7 +954,7 @@ comment - Comentario + comentario diff --git a/src/fsharp/xlf/FSStrings.it.xlf b/src/fsharp/xlf/FSStrings.it.xlf index 6ec47804c8c..c8f96cadaeb 100644 --- a/src/fsharp/xlf/FSStrings.it.xlf +++ b/src/fsharp/xlf/FSStrings.it.xlf @@ -954,7 +954,7 @@ comment - Commento + commento diff --git a/src/utils/CompilerLocationUtils.fs b/src/utils/CompilerLocationUtils.fs index df0c7123b4d..95aa5c5a31e 100644 --- a/src/utils/CompilerLocationUtils.fs +++ b/src/utils/CompilerLocationUtils.fs @@ -23,20 +23,7 @@ module internal FSharpEnvironment = #endif let versionOf<'t> = -#if FX_RESHAPED_REFLECTION - let aq = (typeof<'t>).AssemblyQualifiedName - let version = - if aq <> null then - let x = aq.Split(',', ' ') |> Seq.filter(fun x -> x.StartsWith("Version=", StringComparison.OrdinalIgnoreCase)) |> Seq.tryHead - match x with - | Some(x) -> x.Substring(8) - | _ -> null - else - null - version -#else typeof<'t>.Assembly.GetName().Version.ToString() -#endif let FSharpCoreLibRunningVersion = try match versionOf with @@ -200,7 +187,7 @@ module internal FSharpEnvironment = #else // Check for an app.config setting to redirect the default compiler location // Like fsharp-compiler-location - try + try // FSharp.Compiler support setting an appkey for compiler location. I've never seen this used. let result = tryAppConfig "fsharp-compiler-location" match result with diff --git a/src/utils/prim-lexing.fs b/src/utils/prim-lexing.fs index c397257b46c..1f772d6e87e 100644 --- a/src/utils/prim-lexing.fs +++ b/src/utils/prim-lexing.fs @@ -50,12 +50,12 @@ type StringText(str: string) = lazy getLines str member __.String = str - + override __.GetHashCode() = str.GetHashCode() override __.Equals(obj: obj) = str.Equals(obj) interface ISourceText with - + member __.Item with get index = str.[index] member __.GetLastCharacterPosition() = @@ -106,6 +106,7 @@ namespace Internal.Utilities.Text.Lexing open FSharp.Compiler.Text open Microsoft.FSharp.Core open Microsoft.FSharp.Collections + open FSharp.Compiler.Features open System.Collections.Generic [] @@ -168,11 +169,11 @@ namespace Internal.Utilities.Text.Lexing 0, 0) - type internal LexBufferFiller<'Char> = (LexBuffer<'Char> -> unit) - + type internal LexBufferFiller<'Char> = (LexBuffer<'Char> -> unit) + and [] - internal LexBuffer<'Char>(filler: LexBufferFiller<'Char>) = - let context = new Dictionary(1) + internal LexBuffer<'Char>(filler: LexBufferFiller<'Char>, supportsFeature:LanguageFeature -> bool) = + let context = new Dictionary(1) let mutable buffer = [||] /// number of valid characters beyond bufferScanStart. let mutable bufferMaxScanLength = 0 @@ -195,8 +196,7 @@ namespace Internal.Utilities.Text.Lexing Array.blit keep 0 buffer 0 nkeep bufferScanStart <- 0 bufferMaxScanLength <- nkeep - - + member lexbuf.EndOfScan () : int = //Printf.eprintf "endOfScan, lexBuffer.lexemeLength = %d\n" lexBuffer.lexemeLength; if bufferAcceptAction < 0 then @@ -211,13 +211,12 @@ namespace Internal.Utilities.Text.Lexing member lexbuf.StartPos with get() = startPos and set b = startPos <- b - + member lexbuf.EndPos with get() = endPos and set b = endPos <- b member lexbuf.Lexeme = Array.sub buffer bufferScanStart lexemeLength - member lexbuf.BufferLocalStore = (context :> IDictionary<_,_>) member lexbuf.LexemeLength with get() : int = lexemeLength and set v = lexemeLength <- v member lexbuf.Buffer with get() : 'Char[] = buffer and set v = buffer <- v @@ -238,45 +237,46 @@ namespace Internal.Utilities.Text.Lexing member x.BufferScanPos = bufferScanStart + bufferScanLength member lexbuf.EnsureBufferSize n = - if lexbuf.BufferScanPos + n >= buffer.Length then - let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) + if lexbuf.BufferScanPos + n >= buffer.Length then + let repl = Array.zeroCreate (lexbuf.BufferScanPos + n) Array.blit buffer bufferScanStart repl bufferScanStart bufferScanLength buffer <- repl + member __.SupportsFeature featureId = supportsFeature featureId - static member FromFunction (f : 'Char[] * int * int -> int) : LexBuffer<'Char> = + static member FromFunction (supportsFeature:LanguageFeature -> bool, f : 'Char[] * int * int -> int) : LexBuffer<'Char> = let extension= Array.zeroCreate 4096 let filler (lexBuffer: LexBuffer<'Char>) = let n = f (extension,0,extension.Length) lexBuffer.EnsureBufferSize n Array.blit extension 0 lexBuffer.Buffer lexBuffer.BufferScanPos n lexBuffer.BufferMaxScanLength <- lexBuffer.BufferScanLength + n - new LexBuffer<'Char>(filler) - + new LexBuffer<'Char>(filler, supportsFeature) + // Important: This method takes ownership of the array - static member FromArrayNoCopy (buffer: 'Char[]) : LexBuffer<'Char> = - let lexBuffer = new LexBuffer<'Char>(fun _ -> ()) + static member FromArrayNoCopy (supportsFeature:LanguageFeature -> bool, buffer: 'Char[]) : LexBuffer<'Char> = + let lexBuffer = new LexBuffer<'Char>((fun _ -> ()), supportsFeature) lexBuffer.Buffer <- buffer lexBuffer.BufferMaxScanLength <- buffer.Length lexBuffer // Important: this method does copy the array - static member FromArray (s: 'Char[]) : LexBuffer<'Char> = + static member FromArray (supportsFeature: LanguageFeature -> bool, s: 'Char[]) : LexBuffer<'Char> = let buffer = Array.copy s - LexBuffer<'Char>.FromArrayNoCopy buffer + LexBuffer<'Char>.FromArrayNoCopy(supportsFeature, buffer) // Important: This method takes ownership of the array - static member FromChars (arr:char[]) = LexBuffer.FromArrayNoCopy arr - - static member FromSourceText (sourceText: ISourceText) = + static member FromChars (supportsFeature:LanguageFeature -> bool, arr:char[]) = LexBuffer.FromArrayNoCopy (supportsFeature, arr) + + static member FromSourceText (supportsFeature: LanguageFeature -> bool, sourceText: ISourceText) = let mutable currentSourceIndex = 0 - LexBuffer.FromFunction(fun (chars, start, length) -> + LexBuffer.FromFunction(supportsFeature, fun (chars, start, length) -> let lengthToCopy = if currentSourceIndex + length <= sourceText.Length then length else sourceText.Length - currentSourceIndex - + if lengthToCopy <= 0 then 0 else sourceText.CopyTo(currentSourceIndex, chars, start, lengthToCopy) @@ -312,7 +312,6 @@ namespace Internal.Utilities.Text.Lexing open GenericImplFragments - [] type internal UnicodeTables(trans: uint16[] array, accept: uint16[]) = let sentinel = 255 * 256 + 255 @@ -334,11 +333,7 @@ namespace Internal.Utilities.Text.Lexing // ways let baseForUnicodeCategories = numLowUnicodeChars+numSpecificUnicodeChars*2 let unicodeCategory = -#if FX_RESHAPED_GLOBALIZATION - System.Globalization.CharUnicodeInfo.GetUnicodeCategory(inp) -#else System.Char.GetUnicodeCategory(inp) -#endif //System.Console.WriteLine("inp = {0}, unicodeCategory = {1}", [| box inp; box unicodeCategory |]); int trans.[state].[baseForUnicodeCategories + int32 unicodeCategory] else @@ -349,10 +344,9 @@ namespace Internal.Utilities.Text.Lexing if c = inp then int trans.[state].[baseForSpecificUnicodeChars+i*2+1] else loop(i+1) - loop 0 let eofPos = numLowUnicodeChars + 2*numSpecificUnicodeChars + numUnicodeCategories - + let rec scanUntilSentinel lexBuffer state = // Return an endOfScan after consuming the input let a = int accept.[state] diff --git a/src/utils/prim-lexing.fsi b/src/utils/prim-lexing.fsi index 4b4fd587171..bf9eb3171c1 100644 --- a/src/utils/prim-lexing.fsi +++ b/src/utils/prim-lexing.fsi @@ -39,6 +39,7 @@ open System.Collections.Generic open FSharp.Compiler.Text open Microsoft.FSharp.Core open Microsoft.FSharp.Control +open FSharp.Compiler.Features /// Position information stored for lexing tokens [] @@ -78,12 +79,12 @@ type internal Position = /// Apply a #line directive. member ApplyLineDirective : fileIdx:int * line:int -> Position - + /// Get an arbitrary position, with the empty string as filename. static member Empty : Position - + static member FirstLine : fileIdx:int -> Position - + [] /// Input buffers consumed by lexers generated by fslex.exe. /// The type must be generic to match the code generated by FsLex and FsYacc (if you would like to @@ -97,24 +98,28 @@ type internal LexBuffer<'Char> = /// The matched string. member Lexeme: 'Char [] - + /// Fast helper to turn the matched characters into a string, avoiding an intermediate array. static member LexemeString : LexBuffer -> string - + /// Dynamically typed, non-lexically scoped parameter table. member BufferLocalStore : IDictionary - + /// True if the refill of the buffer ever failed , or if explicitly set to True. member IsPastEndOfStream: bool with get,set + /// True if the refill of the buffer ever failed , or if explicitly set to True. + member SupportsFeature:LanguageFeature -> bool + /// Create a lex buffer suitable for Unicode lexing that reads characters from the given array. /// Important: does take ownership of the array. - static member FromChars: char[] -> LexBuffer + static member FromChars: (LanguageFeature -> bool) * char[] -> LexBuffer /// Create a lex buffer that reads character or byte inputs by using the given function. - static member FromFunction: ('Char[] * int * int -> int) -> LexBuffer<'Char> + static member FromFunction: (LanguageFeature -> bool) * ('Char[] * int * int -> int) -> LexBuffer<'Char> + /// Create a lex buffer backed by source text. - static member FromSourceText : ISourceText -> LexBuffer + static member FromSourceText : (LanguageFeature -> bool) * ISourceText -> LexBuffer /// The type of tables for an unicode lexer generated by fslex.exe. [] diff --git a/src/utils/reshapedmsbuild.fs b/src/utils/reshapedmsbuild.fs index 75859f44765..20b5cd6f961 100644 --- a/src/utils/reshapedmsbuild.fs +++ b/src/utils/reshapedmsbuild.fs @@ -21,41 +21,45 @@ type ITaskItem = abstract member CopyMetadataTo : ITaskItem -> unit abstract member CloneCustomMetadata : IDictionary -namespace Microsoft.Build.Utilities -open Microsoft.Build.Framework -open Microsoft.FSharp.Core.ReflectionAdapters -open System -open System.Collections -open System.Reflection - -type TaskItem (itemSpec:string) = - let assembly = Assembly.Load(new AssemblyName("Microsoft.Build.Utilities.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")) - let buildUtilitiesTaskType = assembly.GetType("Microsoft.Build.Utilities.Task") - let instance = Activator.CreateInstance(buildUtilitiesTaskType, [|itemSpec|]) - - interface ITaskItem with - member this.ItemSpec - with get () :string = (instance.GetPropertyValue("ItemSpec") :?> string) - and set (value:string) = (instance.SetPropertyValue("ItemSpec", value)); () - member this.MetadataNames - with get () :ICollection = (instance.GetPropertyValue("MetadataNames") :?> ICollection) - member this.MetadataCount - with get () :int = (instance.GetPropertyValue("MetadataCount") :?> int) - member this.CopyMetadataTo(iTaskItem) = - let m = buildUtilitiesTaskType.GetMethod("CopyMetadataTo", [| typeof |]) - m.Invoke(instance, [|iTaskItem :>obj|]) |> ignore - member this.CloneCustomMetadata = - let m = buildUtilitiesTaskType.GetMethod("CloneCustomMetadata", [||]) - (m.Invoke(instance,[||])) :?>IDictionary - member this.GetMetadata(metadataName) = - let m = buildUtilitiesTaskType.GetMethod("GetMetadata", [|typeof|]) - (m.Invoke(instance,[|metadataName|])) :?>string - member this.RemoveMetadata(metadataName) = - let m = buildUtilitiesTaskType.GetMethod("RemoveMetadata", [|typeof|]) - (m.Invoke(instance,[|metadataName|])) :?>string |>ignore - member this.SetMetadata(metadataName, metadataValue) = - let m = buildUtilitiesTaskType.GetMethod("SetMetadata", [|typeof;typeof|]) - (m.Invoke(instance,[|metadataName; metadataValue|])) |>ignore +module Utilities = + open Microsoft.Build.Framework + open System + open System.Collections + open System.Reflection + + type System.Object with + member this.GetPropertyValue(propName) = this.GetType().GetProperty(propName, BindingFlags.Public).GetValue(this, null) + member this.SetPropertyValue(propName, propValue) = this.GetType().GetProperty(propName, BindingFlags.Public).SetValue(this, propValue, null) + member this.GetMethod(methodName, argTypes) = this.GetType().GetMethod(methodName, argTypes, [||]) + + type TaskItem (itemSpec:string) = + let assembly = Assembly.Load(new AssemblyName("Microsoft.Build.Utilities.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")) + let buildUtilitiesTaskType = assembly.GetType("Microsoft.Build.Utilities.Task") + let instance = Activator.CreateInstance(buildUtilitiesTaskType, [|itemSpec|]) + + interface ITaskItem with + member this.ItemSpec + with get () :string = (instance.GetPropertyValue("ItemSpec") :?> string) + and set (value:string) = (instance.SetPropertyValue("ItemSpec", value)); () + member this.MetadataNames + with get () :ICollection = (instance.GetPropertyValue("MetadataNames") :?> ICollection) + member this.MetadataCount + with get () :int = (instance.GetPropertyValue("MetadataCount") :?> int) + member this.CopyMetadataTo(iTaskItem) = + let m = buildUtilitiesTaskType.GetMethod("CopyMetadataTo", [| typeof |]) + m.Invoke(instance, [|iTaskItem :>obj|]) |> ignore + member this.CloneCustomMetadata = + let m = buildUtilitiesTaskType.GetMethod("CloneCustomMetadata", [||]) + (m.Invoke(instance,[||])) :?>IDictionary + member this.GetMetadata(metadataName) = + let m = buildUtilitiesTaskType.GetMethod("GetMetadata", [|typeof|]) + (m.Invoke(instance,[|metadataName|])) :?>string + member this.RemoveMetadata(metadataName) = + let m = buildUtilitiesTaskType.GetMethod("RemoveMetadata", [|typeof|]) + (m.Invoke(instance,[|metadataName|])) :?>string |>ignore + member this.SetMetadata(metadataName, metadataValue) = + let m = buildUtilitiesTaskType.GetMethod("SetMetadata", [|typeof;typeof|]) + (m.Invoke(instance,[|metadataName; metadataValue|])) |>ignore namespace FSharp.Compiler open System @@ -66,11 +70,10 @@ open System.Linq open System.Runtime.Versioning open FSComp open Microsoft.Win32 +open Microsoft.Build.Framework.Utilities module internal MsBuildAdapters = - open Microsoft.FSharp.Core.ReflectionAdapters - /// /// Used to specify the targeted version of the .NET Framework for some methods of ToolLocationHelper. This is meant to mimic /// the official version here: https://source.dot.net/#q=TargetDotNetFrameworkVersion. @@ -102,7 +105,6 @@ module internal MsBuildAdapters = module internal ToolLocationHelper = open Microsoft.Build.Framework - open Microsoft.FSharp.Core.ReflectionAdapters open System.Linq open System.Reflection open MsBuildAdapters diff --git a/src/utils/reshapedreflection.fs b/src/utils/reshapedreflection.fs deleted file mode 100644 index 0b143951dda..00000000000 --- a/src/utils/reshapedreflection.fs +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -namespace Microsoft.FSharp.Core -open System.Reflection - -//Replacement for: System.Security.SecurityElement.Escape(line) All platforms -module internal XmlAdapters = - open System.Text - open Microsoft.FSharp.Collections - - let s_escapeChars = [| '<'; '>'; '\"'; '\''; '&' |] - - let getEscapeSequence c = - match c with - | '<' -> "<" - | '>' -> ">" - | '\"' -> """ - | '\'' -> "'" - | '&' -> "&" - | _ as ch -> ch.ToString() - - let escape str = String.collect getEscapeSequence str - -#if FX_RESHAPED_REFLECTION -module internal ReflectionAdapters = - open System - open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators - open Microsoft.FSharp.Collections - open PrimReflectionAdapters - - let inline hasFlag (flag : BindingFlags) f = (f &&& flag) = flag - let isDeclaredFlag f = hasFlag BindingFlags.DeclaredOnly f - let isPublicFlag f = hasFlag BindingFlags.Public f - let isStaticFlag f = hasFlag BindingFlags.Static f - let isInstanceFlag f = hasFlag BindingFlags.Instance f - let isNonPublicFlag f = hasFlag BindingFlags.NonPublic f - - let isAcceptable bindingFlags isStatic isPublic = - // 1. check if member kind (static\instance) was specified in flags - ((isStaticFlag bindingFlags && isStatic) || (isInstanceFlag bindingFlags && not isStatic)) && - // 2. check if member accessibility was specified in flags - ((isPublicFlag bindingFlags && isPublic) || (isNonPublicFlag bindingFlags && not isPublic)) - - let publicFlags = BindingFlags.Public ||| BindingFlags.Instance ||| BindingFlags.Static - - let commit (results : _[]) = - match results with - | [||] -> null - | [| m |] -> m - | _ -> raise (AmbiguousMatchException()) - - let canUseAccessor (accessor : MethodInfo) nonPublic = - (not (isNull (box accessor))) && (accessor.IsPublic || nonPublic) - - type System.Type with - member this.GetTypeInfo() = IntrospectionExtensions.GetTypeInfo(this) - member this.GetRuntimeProperties() = RuntimeReflectionExtensions.GetRuntimeProperties(this) - member this.GetRuntimeEvents() = RuntimeReflectionExtensions.GetRuntimeEvents(this) - member this.Attributes = this.GetTypeInfo().Attributes - member this.GetCustomAttributes(attrTy, inherits) : obj[] = downcast box(CustomAttributeExtensions.GetCustomAttributes(this.GetTypeInfo(), attrTy, inherits) |> Seq.toArray) - member this.GetNestedType (name, bindingFlags) = - // MSDN: http://msdn.microsoft.com/en-us/library/0dcb3ad5.aspx - // The following BindingFlags filter flags can be used to define which nested types to include in the search: - // You must specify either BindingFlags.Public or BindingFlags.NonPublic to get a return. - // Specify BindingFlags.Public to include public nested types in the search. - // Specify BindingFlags.NonPublic to include non-public nested types (that is, private, internal, and protected nested types) in the search. - // This method returns only the nested types of the current type. It does not search the base classes of the current type. - // To find types that are nested in base classes, you must walk the inheritance hierarchy, calling GetNestedType at each level. - let nestedTyOpt = - this.GetTypeInfo().DeclaredNestedTypes - |> Seq.tryFind (fun nestedTy -> - nestedTy.Name = name && ( - (isPublicFlag bindingFlags && nestedTy.IsNestedPublic) || - (isNonPublicFlag bindingFlags && (nestedTy.IsNestedPrivate || nestedTy.IsNestedFamily || nestedTy.IsNestedAssembly || nestedTy.IsNestedFamORAssem || nestedTy.IsNestedFamANDAssem)) - ) - ) - |> Option.map (fun ti -> ti.AsType()) - defaultArg nestedTyOpt null - // use different sources based on Declared flag - member this.GetMethods(bindingFlags) = - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredMethods else this.GetRuntimeMethods()) - |> Seq.filter (fun m -> isAcceptable bindingFlags m.IsStatic m.IsPublic) - |> Seq.toArray - - // use different sources based on Declared flag - member this.GetFields(bindingFlags) = - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredFields else this.GetRuntimeFields()) - |> Seq.filter (fun f -> isAcceptable bindingFlags f.IsStatic f.IsPublic) - |> Seq.toArray - - // use different sources based on Declared flag - member this.GetProperties(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredProperties else this.GetRuntimeProperties()) - |> Seq.filter (fun pi-> - let mi = match pi.GetMethod with | null -> pi.SetMethod | _ -> pi.GetMethod - if mi = null then false - else isAcceptable bindingFlags mi.IsStatic mi.IsPublic - ) - |> Seq.toArray - - member this.GetEvents(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - (if isDeclaredFlag bindingFlags then this.GetTypeInfo().DeclaredEvents else this.GetRuntimeEvents()) - |> Seq.filter (fun ei-> - let m = ei.GetAddMethod(true) - if m = null then false - else isAcceptable bindingFlags m.IsStatic m.IsPublic - ) - |> Seq.toArray - - member this.GetEvent(name, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - this.GetEvents(bindingFlags) - |> Array.filter (fun ei -> ei.Name = name) - |> commit - - member this.GetConstructor(bindingFlags, _binder, argsT:Type[], _parameterModifiers) = - this.GetConstructor(bindingFlags,argsT) - - member this.GetMethod(name, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - this.GetMethods(bindingFlags) - |> Array.filter(fun m -> m.Name = name) - |> commit - - member this.GetMethod(name, _bindingFlags, _binder, argsT:Type[], _parameterModifiers) = - this.GetMethod(name, argsT) - - // use different sources based on Declared flag - member this.GetProperty(name, bindingFlags) = - this.GetProperties(bindingFlags) - |> Array.filter (fun pi -> pi.Name = name) - |> commit - - member this.GetMethod(methodName, args:Type[], ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - let compareSequences parms args = - Seq.compareWith (fun parm arg -> if parm <> arg then 1 else 0) parms args - this.GetMethods(bindingFlags) - |> Array.filter(fun m -> m.Name = methodName && (compareSequences (m.GetParameters() |> Seq.map(fun x -> x.ParameterType)) args) = 0) - |> commit - - member this.GetNestedTypes(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags publicFlags - this.GetTypeInfo().DeclaredNestedTypes - |> Seq.filter (fun nestedTy-> - (isPublicFlag bindingFlags && nestedTy.IsNestedPublic) || - (isNonPublicFlag bindingFlags && (nestedTy.IsNestedPrivate || nestedTy.IsNestedFamily || nestedTy.IsNestedAssembly || nestedTy.IsNestedFamORAssem || nestedTy.IsNestedFamANDAssem))) - |> Seq.map (fun ti -> ti.AsType()) - |> Seq.toArray - - member this.GetEnumUnderlyingType() = - Enum.GetUnderlyingType(this) - - member this.InvokeMember(memberName, bindingFlags, _binder, target:obj, arguments:obj[], _cultureInfo) = - let m = this.GetMethod(memberName, (arguments |> Seq.map(fun x -> x.GetType()) |> Seq.toArray), bindingFlags) - match m with - | null -> raise <| System.MissingMethodException(String.Format("Method '{0}.{1}' not found.", this.FullName, memberName)) - | _ -> m.Invoke(target, arguments) - - member this.IsGenericType = this.GetTypeInfo().IsGenericType - - member this.IsGenericTypeDefinition = this.GetTypeInfo().IsGenericTypeDefinition - - member this.GetGenericArguments() = - if this.IsGenericTypeDefinition then this.GetTypeInfo().GenericTypeParameters - elif this.IsGenericType then this.GenericTypeArguments - else [||] - - member this.IsInterface = this.GetTypeInfo().IsInterface - - member this.IsPublic = this.GetTypeInfo().IsPublic - - member this.IsNestedPublic = this.GetTypeInfo().IsNestedPublic - - member this.IsClass = this.GetTypeInfo().IsClass - - member this.IsValueType = this.GetTypeInfo().IsValueType - - member this.IsSealed = this.GetTypeInfo().IsSealed - - member this.BaseType = this.GetTypeInfo().BaseType - - member this.GetConstructor(bindingFlags, parameterTypes : Type[]) = - this.GetTypeInfo().DeclaredConstructors - |> Seq.filter (fun ci -> isAcceptable bindingFlags ci.IsStatic ci.IsPublic) - |> Seq.filter (fun ci -> - ( - let parameters = ci.GetParameters() - (parameters.Length = parameterTypes.Length) && - (parameterTypes, parameters) ||> Array.forall2 (fun ty pi -> pi.ParameterType.Equals ty) - ) - ) - |> Seq.toArray - |> commit - - member this.GetConstructor(parameterTypes : Type[]) = - this.GetConstructor(BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance, parameterTypes) - - member this.GetConstructors(?bindingFlags) = - let bindingFlags = defaultArg bindingFlags (BindingFlags.Public ||| BindingFlags.Instance) - // type initializer will also be included in resultset - this.GetTypeInfo().DeclaredConstructors - |> Seq.filter (fun ci -> isAcceptable bindingFlags ci.IsStatic ci.IsPublic) - |> Seq.toArray - - // MSDN: returns an array of Type objects representing all the interfaces implemented or inherited by the current Type. - member this.GetInterfaces() = this.GetTypeInfo().ImplementedInterfaces |> Seq.toArray - - member this.GetMethods() = this.GetMethods(publicFlags) - - member this.Assembly = this.GetTypeInfo().Assembly - - member this.IsSubclassOf(otherTy : Type) = this.GetTypeInfo().IsSubclassOf(otherTy) - - member this.IsEnum = this.GetTypeInfo().IsEnum; - - member this.GetField(name, bindingFlags) = - this.GetFields(bindingFlags) - |> Array.filter (fun fi -> fi.Name = name) - |> commit - - member this.GetField(name) = RuntimeReflectionExtensions.GetRuntimeField(this, name) - - member this.GetProperty(name, propertyType, parameterTypes : Type[]) = - this.GetProperties() - |> Array.filter (fun pi -> - pi.Name = name && - pi.PropertyType = propertyType && - ( - let parameters = pi.GetIndexParameters() - (parameters.Length = parameterTypes.Length) && - (parameterTypes, parameters) ||> Array.forall2 (fun ty pi -> pi.ParameterType.Equals ty) - ) - ) - |> commit - - static member GetTypeCode(ty : Type) = - if typeof.Equals ty then TypeCode.Int32 - elif typeof.Equals ty then TypeCode.Int64 - elif typeof.Equals ty then TypeCode.Byte - elif ty = typeof then TypeCode.SByte - elif ty = typeof then TypeCode.Int16 - elif ty = typeof then TypeCode.UInt16 - elif ty = typeof then TypeCode.UInt32 - elif ty = typeof then TypeCode.UInt64 - elif ty = typeof then TypeCode.Single - elif ty = typeof then TypeCode.Double - elif ty = typeof then TypeCode.Decimal - else TypeCode.Object - - member this.Module = - this.GetTypeInfo().Module - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0}", this.ToString()) - s.GetHashCode() - - type System.Reflection.EventInfo with - - member this.GetAddMethod() = - this.AddMethod - - member this.GetRemoveMethod() = - this.RemoveMethod - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.FieldInfo with - member this.GetRawConstantValue() = - this.GetValue(null) - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.MemberInfo with - member this.GetCustomAttributes(attrTy, inherits) : obj[] = downcast box(CustomAttributeExtensions.GetCustomAttributes(this, attrTy, inherits) |> Seq.toArray) - - // TODO: is this an adequate replacement for MetadataToken - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.MethodInfo with - - member this.GetCustomAttributes(inherits : bool) : obj[] = downcast box(CustomAttributeExtensions.GetCustomAttributes(this, inherits) |> Seq.toArray) - - member this.Invoke(obj, _bindingFlags, _binder, args, _ci) = - this.Invoke(obj, args) - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = String.Format("{0},{0}", this.DeclaringType.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.ParameterInfo with - - member this.RawDefaultValue = this.DefaultValue - - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - // I really do not understand why: sprintf "%s,%s" (this.ReflectedType.ToString()) (this.ToString()) did not work - let s = String.Format("{0},{0},{0}", this.Member.DeclaringType.ToString(),this.Member.ToString(), this.ToString()) - s.GetHashCode() - - type System.Reflection.PropertyInfo with - - member this.GetGetMethod(nonPublic) = - let mi = this.GetMethod - if canUseAccessor mi nonPublic then mi - else null - - member this.GetSetMethod(nonPublic) = - let mi = this.SetMethod - if canUseAccessor mi nonPublic then mi - else null - - member this.GetGetMethod() = this.GetMethod - - member this.GetSetMethod() = this.SetMethod - - type System.Reflection.Assembly with - - member this.GetTypes() = - this.DefinedTypes - |> Seq.map (fun ti -> ti.AsType()) - |> Seq.toArray - - member this.GetExportedTypes() = - this.DefinedTypes - |> Seq.filter(fun ti -> ti.IsPublic) - |> Seq.map (fun ti -> ti.AsType()) - |> Seq.toArray - - member this.Location = - this.ManifestModule.FullyQualifiedName - - type System.Delegate with - - static member CreateDelegate(delegateType, methodInfo : MethodInfo) = methodInfo.CreateDelegate(delegateType) - - static member CreateDelegate(delegateType, obj : obj, methodInfo : MethodInfo) = methodInfo.CreateDelegate(delegateType, obj) - - type System.Object with - member this.GetPropertyValue(propName) = - this.GetType().GetProperty(propName, BindingFlags.Public).GetValue(this, null) - - member this.SetPropertyValue(propName, propValue) = - this.GetType().GetProperty(propName, BindingFlags.Public).SetValue(this, propValue, null) - - member this.GetMethod(methodName, argTypes) = - this.GetType().GetMethod(methodName, argTypes, BindingFlags.Public) - - type System.Char with - static member GetUnicodeCategory(c: char) = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c) - - type System.Reflection.Module with - member this.MetadataToken = - // TODO: is this an adequate replacement for MetadataToken - let s = this.FullyQualifiedName - s.GetHashCode() - -#if COMPILER // This part includes global state in globalLoadContext. Only include this support "once", i.e. when compiling FSharp.Compiler.Private.dll, FSharp.Compiler.Service.dll, fsc-proto.exe - - type CustomAssemblyResolver() = - inherit System.Runtime.Loader.AssemblyLoadContext() - override this.Load (assemblyName:AssemblyName):Assembly = - this.LoadFromAssemblyName(assemblyName) - - let globalLoadContext = - // This is an unfortunate temporary fix!!!! - // ======================================== - // We need to run fsi tests on a very old version of the corclr because of an unfortunate test framework - // This hack detects that, and uses the old code. - // On slightly newer code AssemblyLoadContext.Default is the way to go. - match Seq.tryHead (typeof.GetTypeInfo().Assembly.GetCustomAttributes()) with - | Some a when a.Version = "4.6.24410.01" -> new CustomAssemblyResolver() :> System.Runtime.Loader.AssemblyLoadContext - | _ -> System.Runtime.Loader.AssemblyLoadContext.Default - - type System.Reflection.Assembly with - static member LoadFrom(filename:string) = - globalLoadContext.LoadFromAssemblyPath(filename) - - static member UnsafeLoadFrom(filename:string) = - globalLoadContext.LoadFromAssemblyPath(filename) - - type System.Reflection.AssemblyName with - static member GetAssemblyName(path) = - System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(path) - -#endif - -#endif diff --git a/src/utils/sformat.fs b/src/utils/sformat.fs index 228f4aba399..42cb18fa8d0 100644 --- a/src/utils/sformat.fs +++ b/src/utils/sformat.fs @@ -38,11 +38,6 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl open Microsoft.FSharp.Collections open Microsoft.FSharp.Primitives.Basics -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open ReflectionAdapters -#endif - [] type LayoutTag = | ActivePatternCase @@ -321,11 +316,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl StringLimit : int; #endif FormatProvider: System.IFormatProvider; -#if FX_RESHAPED_REFLECTION - ShowNonPublic : bool -#else BindingFlags: System.Reflection.BindingFlags -#endif PrintWidth : int; PrintDepth : int; PrintLength : int; @@ -339,11 +330,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl StringLimit = System.Int32.MaxValue; #endif AttributeProcessor= (fun _ _ _ -> ()); -#if FX_RESHAPED_REFLECTION - ShowNonPublic = false -#else BindingFlags = System.Reflection.BindingFlags.Public; -#endif FloatingPointFormat = "g10"; PrintWidth = 80 ; PrintDepth = 100 ; @@ -358,11 +345,6 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl open System open System.Reflection -#if FX_RESHAPED_REFLECTION - open PrimReflectionAdapters - open Microsoft.FSharp.Core.ReflectionAdapters -#endif - [] type TypeInfo = | TupleType of Type list @@ -404,10 +386,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // Analyze an object to see if it the representation // of an F# value. - let GetValueInfoOfObject (bindingFlags:BindingFlags) (obj : obj) = -#if FX_RESHAPED_REFLECTION - let showNonPublic = isNonPublicFlag bindingFlags -#endif + let GetValueInfoOfObject (bindingFlags:BindingFlags) (obj : obj) = match obj with | null -> ObjectValue(obj) | _ -> @@ -429,34 +408,18 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // the type are the actual fields of the type. Again, // we should be reading attributes here that indicate the // true structure of the type, e.g. the order of the fields. -#if FX_RESHAPED_REFLECTION - elif FSharpType.IsUnion(reprty, showNonPublic) then - let tag,vals = FSharpValue.GetUnionFields (obj,reprty, showNonPublic) -#else elif FSharpType.IsUnion(reprty,bindingFlags) then let tag,vals = FSharpValue.GetUnionFields (obj,reprty,bindingFlags) -#endif let props = tag.GetFields() let pvals = (props,vals) ||> Array.map2 (fun prop v -> prop.Name,(v, prop.PropertyType)) ConstructorValue(tag.Name, Array.toList pvals) -#if FX_RESHAPED_REFLECTION - elif FSharpType.IsExceptionRepresentation(reprty, showNonPublic) then - let props = FSharpType.GetExceptionFields(reprty, showNonPublic) - let vals = FSharpValue.GetExceptionFields(obj, showNonPublic) -#else elif FSharpType.IsExceptionRepresentation(reprty,bindingFlags) then let props = FSharpType.GetExceptionFields(reprty,bindingFlags) let vals = FSharpValue.GetExceptionFields(obj,bindingFlags) -#endif let pvals = (props,vals) ||> Array.map2 (fun prop v -> prop.Name,(v, prop.PropertyType)) ExceptionValue(reprty, pvals |> Array.toList) -#if FX_RESHAPED_REFLECTION - elif FSharpType.IsRecord(reprty, showNonPublic) then - let props = FSharpType.GetRecordFields(reprty, showNonPublic) -#else elif FSharpType.IsRecord(reprty,bindingFlags) then let props = FSharpType.GetRecordFields(reprty,bindingFlags) -#endif RecordValue(props |> Array.map (fun prop -> prop.Name, prop.GetValue(obj,null), prop.PropertyType) |> Array.toList) else ObjectValue(obj) @@ -491,12 +454,8 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let string_of_int (i:int) = i.ToString() let typeUsesSystemObjectToString (ty:System.Type) = - try -#if FX_RESHAPED_REFLECTION - let methInfo = ty.GetRuntimeMethod("ToString",[| |]) -#else + try let methInfo = ty.GetMethod("ToString",BindingFlags.Public ||| BindingFlags.Instance,null,[| |],null) -#endif methInfo.DeclaringType = typeof with e -> false /// If "str" ends with "ending" then remove it from "str", otherwise no change. @@ -796,16 +755,8 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // -------------------------------------------------------------------- let getProperty (ty: Type) (obj: obj) name = -#if FX_RESHAPED_REFLECTION - let prop = ty.GetProperty(name, (BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic)) - if not (isNull prop) then prop.GetValue(obj,[||]) - // Others raise MissingMethodException - else - let msg = System.String.Concat([| "Method '"; ty.FullName; "."; name; "' not found." |]) - raise (System.MissingMethodException(msg)) -#else ty.InvokeMember(name, (BindingFlags.GetProperty ||| BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic), null, obj, [| |],CultureInfo.InvariantCulture) -#endif + let getField obj (fieldInfo: FieldInfo) = fieldInfo.GetValue(obj) @@ -1173,11 +1124,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // If the leafFormatter was directly here, then layout leaves could store strings. match obj with | _ when opts.ShowProperties -> -#if FX_RESHAPED_REFLECTION - let props = ty.GetProperties(BindingFlags.Instance ||| BindingFlags.Public) -#else let props = ty.GetProperties(BindingFlags.GetField ||| BindingFlags.Instance ||| BindingFlags.Public) -#endif let fields = ty.GetFields(BindingFlags.Instance ||| BindingFlags.Public) |> Array.map (fun i -> i :> MemberInfo) let propsAndFields = props |> Array.map (fun i -> i :> MemberInfo) @@ -1193,10 +1140,10 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl // massively reign in deep printing of properties let nDepth = depthLim/10 #if NETSTANDARD - Array.Sort((propsAndFields),{ new IComparer with member this.Compare(p1,p2) = compare (p1.Name) (p2.Name) } ); -#else - Array.Sort((propsAndFields :> Array),{ new System.Collections.IComparer with member this.Compare(p1,p2) = compare ((p1 :?> MemberInfo).Name) ((p2 :?> MemberInfo).Name) } ); -#endif + Array.Sort((propsAndFields),{ new IComparer with member this.Compare(p1,p2) = compare (p1.Name) (p2.Name) } ) +#else + Array.Sort((propsAndFields :> Array),{ new System.Collections.IComparer with member this.Compare(p1,p2) = compare ((p1 :?> MemberInfo).Name) ((p2 :?> MemberInfo).Name) } ) +#endif if propsAndFields.Length = 0 || (nDepth <= 0) then basicL else basicL --- @@ -1307,12 +1254,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl let fsi_any_to_layout opts x = anyL ShowTopLevelBinding BindingFlags.Public opts x #else // FSharp.Core -#if FX_RESHAPED_REFLECTION - let internal anyToStringForPrintf options (showNonPublicMembers : bool) x = - let bindingFlags = ReflectionUtils.toBindingFlags showNonPublicMembers -#else let internal anyToStringForPrintf options (bindingFlags:BindingFlags) x = -#endif x |> anyL ShowAll bindingFlags options |> layout_to_string options #endif diff --git a/src/utils/sformat.fsi b/src/utils/sformat.fsi index f7c053e51fc..e6ff9762bb5 100644 --- a/src/utils/sformat.fsi +++ b/src/utils/sformat.fsi @@ -302,11 +302,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl StringLimit: int; #endif FormatProvider: System.IFormatProvider -#if FX_RESHAPED_REFLECTION - ShowNonPublic : bool -#else BindingFlags: System.Reflection.BindingFlags -#endif PrintWidth : int PrintDepth : int PrintLength : int @@ -341,11 +337,7 @@ namespace Microsoft.FSharp.Text.StructuredPrintfImpl #if FSHARP_CORE // FSharp.Core.dll: Most functions aren't needed in FSharp.Core.dll, but we add one entry for printf -#if FX_RESHAPED_REFLECTION - val anyToStringForPrintf: options:FormatOptions -> showNonPublicMembers : bool -> value:'T * Type -> string -#else val anyToStringForPrintf: options:FormatOptions -> bindingFlags:System.Reflection.BindingFlags -> value:'T * Type -> string -#endif #else val asTaggedTextWriter: writer: TextWriter -> TaggedTextWriter val any_to_layout : options:FormatOptions -> value:'T * Type -> Layout diff --git a/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs b/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs index f6395b91c49..be1521a56ac 100644 --- a/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs +++ b/tests/EndToEndBuildTests/ProvidedTypes/ProvidedTypes.fs @@ -4026,7 +4026,7 @@ namespace ProviderImplementation.ProvidedTypes.AssemblyReader // Emit compressed untagged integer member buf.EmitZUntaggedIndex big idx = if big then buf.EmitInt32 idx - elif idx > 0xffff then failwith "EmitZUntaggedIndex: too big for small address or simple index" + elif idx > 0xffff then failwithf "EmitZUntaggedIndex: too big for small address or simple index, idx = %d, big = %A, stack = %s" idx big ((new System.Diagnostics.StackTrace()).ToString()) else buf.EmitInt32AsUInt16 idx // Emit compressed tagged integer diff --git a/tests/FSharp.Compiler.UnitTests/HashIfExpression.fs b/tests/FSharp.Compiler.UnitTests/HashIfExpression.fs index 91d7bfcb8d6..21667c727d5 100644 --- a/tests/FSharp.Compiler.UnitTests/HashIfExpression.fs +++ b/tests/FSharp.Compiler.UnitTests/HashIfExpression.fs @@ -12,7 +12,7 @@ open FSharp.Compiler open FSharp.Compiler.Lexer open FSharp.Compiler.Lexhelp open FSharp.Compiler.ErrorLogger -open FSharp.Compiler.ErrorLogger +open FSharp.Compiler.Features open FSharp.Compiler.Ast open Internal.Utilities @@ -69,7 +69,8 @@ type HashIfExpression() = CompileThreadStatic.ErrorLogger <- errorLogger let parser (s : string) = - let lexbuf = LexBuffer.FromChars (s.ToCharArray ()) + let isFeatureSupported (_featureId:LanguageFeature) = true + let lexbuf = LexBuffer.FromChars (isFeatureSupported, s.ToCharArray ()) lexbuf.StartPos <- startPos lexbuf.EndPos <- startPos let tokenStream = PPLexer.tokenstream args diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj index aaf0065bfc3..3ead53af374 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj @@ -32,6 +32,7 @@ + @@ -95,9 +96,9 @@ - - - + + + diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/DiscrimantedUnionType.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/DiscrimantedUnionType.fs index 90d30f40a6c..e5a48ad3007 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/DiscrimantedUnionType.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/DiscrimantedUnionType.fs @@ -10,17 +10,6 @@ open NUnit.Framework open FsCheck open FsCheck.PropOperators -#if FX_RESHAPED_REFLECTION -open FSharp.Reflection.FSharpReflectionExtensions - -[] -module PrimReflectionAdapters = - - type System.Type with - member this.IsValueType = this.GetTypeInfo().IsValueType -#endif - - type EnumUnion = | A | B 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 3e33f34bd5b..b525469322b 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 @@ -168,8 +168,8 @@ type AsyncModule() = let dispose(d : #IDisposable) = d.Dispose() - let testErrorAndCancelRace computation = - for _ in 1..20 do + let testErrorAndCancelRace testCaseName computation = + for i in 1..20 do let cts = new System.Threading.CancellationTokenSource() use barrier = new System.Threading.ManualResetEvent(false) async { cts.Cancel() } @@ -180,7 +180,7 @@ type AsyncModule() = Async.StartWithContinuations( computation, - (fun _ -> failwith "success not expected"), + (fun _ -> failwith (sprintf "Testcase: %s --- success not expected iterations 1 .. 20 - failed on iteration %d" testCaseName i)), (fun _ -> incr()), (fun _ -> incr()), cts.Token @@ -427,12 +427,11 @@ type AsyncModule() = member this.``RaceBetweenCancellationAndError.AwaitWaitHandle``() = let disposedEvent = new System.Threading.ManualResetEvent(false) dispose disposedEvent - - testErrorAndCancelRace(Async.AwaitWaitHandle disposedEvent) + testErrorAndCancelRace "RaceBetweenCancellationAndError.AwaitWaitHandle" (Async.AwaitWaitHandle disposedEvent) [] member this.``RaceBetweenCancellationAndError.Sleep``() = - testErrorAndCancelRace (Async.Sleep (-5)) + testErrorAndCancelRace "RaceBetweenCancellationAndError.Sleep" (Async.Sleep (-5)) #if EXPENSIVE #if NET46 @@ -626,3 +625,67 @@ type AsyncModule() = } |> Async.RunSynchronously Console.WriteLine "Checking result...." Assert.AreEqual(1, !x) + + [] + member this.``Parallel with maxDegreeOfParallelism`` () = + let mutable i = 1 + let action j = async { + Assert.AreEqual(j, i) + i <- i + 1 + } + let computation = + [| for i in 1 .. 1000 -> action i |] + |> fun cs -> Async.Parallel(cs, 1) + Async.RunSynchronously(computation) |> ignore + + [] + member this.``maxDegreeOfParallelism can not be 0`` () = + try + [| for i in 1 .. 10 -> async { return i } |] + |> fun cs -> Async.Parallel(cs, 0) + |> ignore + Assert.Fail("Unexpected success") + with + | :? System.ArgumentException as exc -> + Assert.AreEqual("maxDegreeOfParallelism", exc.ParamName) + Assert.True(exc.Message.Contains("maxDegreeOfParallelism must be positive, was 0")) + + [] + member this.``maxDegreeOfParallelism can not be negative`` () = + try + [| for i in 1 .. 10 -> async { return i } |] + |> fun cs -> Async.Parallel(cs, -1) + |> ignore + Assert.Fail("Unexpected success") + with + | :? System.ArgumentException as exc -> + Assert.AreEqual("maxDegreeOfParallelism", exc.ParamName) + Assert.True(exc.Message.Contains("maxDegreeOfParallelism must be positive, was -1")) + +// This has been failing very regularly on LINUX --- issue : https://github.com/dotnet/fsharp/issues/7112 +#if !TESTING_ON_LINUX + [] + member this.``RaceBetweenCancellationAndError.Parallel``() = + [| for i in 1 .. 1000 -> async { return i } |] + |> fun cs -> Async.Parallel(cs, 1) + |> testErrorAndCancelRace "RaceBetweenCancellationAndError.Parallel" +#endif + + [] + member this.``error on one workflow should cancel all others with maxDegreeOfParallelism``() = + let counter = + async { + let counter = ref 0 + let job i = async { + if i = 55 then failwith "boom" + else + do! Async.Sleep 1000 + incr counter + } + + let! _ = Async.Parallel ([ for i in 1 .. 100 -> job i ], 2) |> Async.Catch + do! Async.Sleep 5000 + return !counter + } |> Async.RunSynchronously + + Assert.AreEqual(0, counter) \ No newline at end of file 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 7e1dec5a2ff..21df908745d 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 @@ -26,30 +26,6 @@ Make sure each method works on: * Struct versions of the above *) -#if FX_RESHAPED_REFLECTION -module PrimReflectionAdapters = - open System.Linq - - type System.Type with - member this.Assembly = this.GetTypeInfo().Assembly - member this.IsGenericType = this.GetTypeInfo().IsGenericType - member this.IsValueType = this.GetTypeInfo().IsValueType - member this.IsAssignableFrom(otherTy : Type) = this.GetTypeInfo().IsAssignableFrom(otherTy.GetTypeInfo()) - member this.GetProperty(name) = this.GetRuntimeProperty(name) - member this.GetProperties() = this.GetRuntimeProperties() |> Array.ofSeq - member this.GetMethod(name, parameterTypes) = this.GetRuntimeMethod(name, parameterTypes) - member this.GetCustomAttributes(attrTy : Type, inherits : bool) : obj[] = - unbox (box (CustomAttributeExtensions.GetCustomAttributes(this.GetTypeInfo(), attrTy, inherits).ToArray())) - - type System.Reflection.MemberInfo with - member this.ReflectedType = this.DeclaringType - - type System.Reflection.Assembly with - member this.GetTypes() = this.DefinedTypes |> Seq.map (fun ti -> ti.AsType()) |> Array.ofSeq - -open PrimReflectionAdapters -#endif - module IsModule = type IsModuleType () = member __.M = 1 @@ -1056,22 +1032,14 @@ type FSharpTypeTests() = // Regression for 5588, Reflection: unit is still treated as a record type, but only if you pass BindingFlags.NonPublic [] - member __.``IsRecord.Regression5588``() = - + member __.``IsRecord.Regression5588``() = // negative Assert.IsFalse(FSharpType.IsRecord(typeof)) - -#if FX_RESHAPED_REFLECTION - Assert.IsFalse( FSharpType.IsRecord(typeof, true) ) -#else Assert.IsFalse( FSharpType.IsRecord(typeof, System.Reflection.BindingFlags.NonPublic) ) -#endif () - [] - member __.IsTuple() = - + member __.IsTuple() = // positive Assert.IsTrue(FSharpType.IsTuple(typeof>)) Assert.IsTrue(FSharpType.IsTuple(typeof>)) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/RecordTypes.fs b/tests/FSharp.Core.UnitTests/FSharp.Core/RecordTypes.fs index 112c3509b1b..e131a9274dd 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/RecordTypes.fs +++ b/tests/FSharp.Core.UnitTests/FSharp.Core/RecordTypes.fs @@ -11,16 +11,6 @@ open NUnit.Framework open FsCheck open FsCheck.PropOperators -#if FX_RESHAPED_REFLECTION -open FSharp.Reflection.FSharpReflectionExtensions - -[] -module PrimReflectionAdapters = - - type System.Type with - member this.IsValueType = this.GetTypeInfo().IsValueType -#endif - type Record = { A: int B: int diff --git a/tests/FSharp.Core.UnitTests/LibraryTestFx.fs b/tests/FSharp.Core.UnitTests/LibraryTestFx.fs index 637cc41d2e3..224ab11c500 100644 --- a/tests/FSharp.Core.UnitTests/LibraryTestFx.fs +++ b/tests/FSharp.Core.UnitTests/LibraryTestFx.fs @@ -54,12 +54,8 @@ let CheckThrowsFormatException f = CheckThrowsExn let VerifySeqsEqual (seq1 : seq<'T>) (seq2 : seq<'T>) = CollectionAssert.AreEqual(seq1, seq2) -let sleep(n : int32) = -#if FX_NO_THREAD - async { do! Async.Sleep(n) } |> Async.RunSynchronously -#else +let sleep(n : int32) = System.Threading.Thread.Sleep(n) -#endif module SurfaceArea = open System.Reflection @@ -70,13 +66,12 @@ module SurfaceArea = let private getActual () = // get current FSharp.Core - let asm = typeof.GetTypeInfo().Assembly + let asm = typeof.Assembly let fsCoreFullName = asm.FullName // public types only let types = asm.ExportedTypes |> Seq.filter (fun ty -> let ti = ty.GetTypeInfo() in ti.IsPublic || ti.IsNestedPublic) |> Array.ofSeq - let typenames = new System.Collections.Generic.List() // extract canonical string form for every public member of every type let getTypeMemberStrings (t : Type) = // for System.Runtime-based profiles, need to do lots of manual work @@ -128,36 +123,38 @@ module SurfaceArea = // If both sets are empty, the surface areas match so allow the test to pass. if Set.isEmpty unexpectedlyMissing && Set.isEmpty unexpectedlyPresent then - Assert.Pass () - - let logFile = - let workDir = TestContext.CurrentContext.WorkDirectory - sprintf "%s\\FSharp.Core.SurfaceArea.%s.txt" workDir platform - System.IO.File.WriteAllText(logFile, String.Join("\r\n", actual)) - - // The surface areas don't match; prepare an easily-readable output message. - let msg = - let inline newLine (sb : System.Text.StringBuilder) = sb.AppendLine () |> ignore - let sb = System.Text.StringBuilder () - Printf.bprintf sb "Assembly: %A" asm - newLine sb - sb.AppendLine "Expected and actual surface area don't match. To see the delta, run:" |> ignore - Printf.bprintf sb " windiff %s %s" fileName logFile - newLine sb - newLine sb - sb.Append "Unexpectedly missing (expected, not actual):" |> ignore - for s in unexpectedlyMissing do + // pass + () + else + + let logFile = + let workDir = TestContext.CurrentContext.WorkDirectory + sprintf "%s\\FSharp.Core.SurfaceArea.%s.txt" workDir platform + System.IO.File.WriteAllText(logFile, String.Join("\r\n", actual)) + + // The surface areas don't match; prepare an easily-readable output message. + let msg = + let inline newLine (sb : System.Text.StringBuilder) = sb.AppendLine () |> ignore + let sb = System.Text.StringBuilder () + Printf.bprintf sb "Assembly: %A" asm newLine sb - sb.Append " " |> ignore - sb.Append s |> ignore - newLine sb - newLine sb - sb.Append "Unexpectedly present (actual, not expected):" |> ignore - for s in unexpectedlyPresent do + sb.AppendLine "Expected and actual surface area don't match. To see the delta, run:" |> ignore + Printf.bprintf sb " windiff %s %s" fileName logFile newLine sb - sb.Append " " |> ignore - sb.Append s |> ignore - newLine sb - sb.ToString () + newLine sb + sb.Append "Unexpectedly missing (expected, not actual):" |> ignore + for s in unexpectedlyMissing do + newLine sb + sb.Append " " |> ignore + sb.Append s |> ignore + newLine sb + newLine sb + sb.Append "Unexpectedly present (actual, not expected):" |> ignore + for s in unexpectedlyPresent do + newLine sb + sb.Append " " |> ignore + sb.Append s |> ignore + newLine sb + sb.ToString () - Assert.Fail msg + failwith msg diff --git a/tests/FSharp.Core.UnitTests/SurfaceArea.coreclr.fs b/tests/FSharp.Core.UnitTests/SurfaceArea.coreclr.fs index eba09d2de44..561871089f0 100644 --- a/tests/FSharp.Core.UnitTests/SurfaceArea.coreclr.fs +++ b/tests/FSharp.Core.UnitTests/SurfaceArea.coreclr.fs @@ -5,7 +5,6 @@ namespace FSharp.Core.UnitTests.Portable.SurfaceArea open NUnit.Framework open FSharp.Core.UnitTests.LibraryTestFx - type SurfaceAreaTest() = [] member this.VerifyArea(): unit = @@ -548,6 +547,8 @@ Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[Sys Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[System.Threading.CancellationToken] get_CancellationToken() Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[System.Threading.Tasks.Task`1[T]] StartChildAsTask[T](Microsoft.FSharp.Control.FSharpAsync`1[T], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.Tasks.TaskCreationOptions]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T[]] Parallel[T](System.Collections.Generic.IEnumerable`1[Microsoft.FSharp.Control.FSharpAsync`1[T]]) +Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T[]] Parallel[T](System.Collections.Generic.IEnumerable`1[Microsoft.FSharp.Control.FSharpAsync`1[T]], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) +Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T[]] Sequential[T](System.Collections.Generic.IEnumerable`1[Microsoft.FSharp.Control.FSharpAsync`1[T]]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T] AwaitEvent[TDel,T](Microsoft.FSharp.Control.IEvent`2[TDel,T], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Core.Unit]]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T] AwaitTask[T](System.Threading.Tasks.Task`1[T]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T] FromBeginEnd[TArg1,TArg2,TArg3,T](TArg1, TArg2, TArg3, Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`5[TArg1,TArg2,TArg3,System.AsyncCallback,System.Object],System.IAsyncResult], Microsoft.FSharp.Core.FSharpFunc`2[System.IAsyncResult,T], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Core.Unit]]) @@ -629,7 +630,10 @@ Microsoft.FSharp.Control.ObservableModule: System.IObservable`1[T] Merge[T](Syst Microsoft.FSharp.Control.ObservableModule: System.Tuple`2[System.IObservable`1[TResult1],System.IObservable`1[TResult2]] Split[T,TResult1,TResult2](Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.FSharpChoice`2[TResult1,TResult2]], System.IObservable`1[T]) Microsoft.FSharp.Control.ObservableModule: System.Tuple`2[System.IObservable`1[T],System.IObservable`1[T]] Partition[T](Microsoft.FSharp.Core.FSharpFunc`2[T,System.Boolean], System.IObservable`1[T]) Microsoft.FSharp.Control.ObservableModule: Void Add[T](Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.Unit], System.IObservable`1[T]) +Microsoft.FSharp.Control.WebExtensions: Microsoft.FSharp.Control.FSharpAsync`1[Microsoft.FSharp.Core.Unit] AsyncDownloadFile(System.Net.WebClient, System.Uri, System.String) +Microsoft.FSharp.Control.WebExtensions: Microsoft.FSharp.Control.FSharpAsync`1[System.Byte[]] AsyncDownloadData(System.Net.WebClient, System.Uri) Microsoft.FSharp.Control.WebExtensions: Microsoft.FSharp.Control.FSharpAsync`1[System.Net.WebResponse] AsyncGetResponse(System.Net.WebRequest) +Microsoft.FSharp.Control.WebExtensions: Microsoft.FSharp.Control.FSharpAsync`1[System.String] AsyncDownloadString(System.Net.WebClient, System.Uri) Microsoft.FSharp.Core.AbstractClassAttribute: Void .ctor() Microsoft.FSharp.Core.AllowNullLiteralAttribute: Boolean Value Microsoft.FSharp.Core.AllowNullLiteralAttribute: Boolean get_Value() @@ -1633,6 +1637,10 @@ Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7]: Microsoft.FSharp.Cor Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7]: Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7] NewChoice5Of7(T5) Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7]: Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7] NewChoice6Of7(T6) Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7]: Microsoft.FSharp.Core.FSharpChoice`7[T1,T2,T3,T4,T5,T6,T7] NewChoice7Of7(T7) +Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] FromConverter(System.Converter`2[T,TResult]) +Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] op_Implicit(System.Converter`2[T,TResult]) +Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: System.Converter`2[T,TResult] ToConverter(Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]) +Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: System.Converter`2[T,TResult] op_Implicit(Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]) Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: TResult Invoke(T) Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: V InvokeFast[V](Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.FSharpFunc`2[TResult,V]], T, TResult) Microsoft.FSharp.Core.FSharpFunc`2[T,TResult]: Void .ctor() @@ -1748,6 +1756,7 @@ Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[Microsoft. Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.Unit] FromAction[T](System.Action`1[T]) Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T,Microsoft.FSharp.Core.Unit] ToFSharpFunc[T](System.Action`1[T]) Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] FromFunc[T,TResult](System.Func`2[T,TResult]) +Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] ToFSharpFunc[T,TResult](System.Converter`2[T,TResult]) Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T1,Microsoft.FSharp.Core.FSharpFunc`2[T2,Microsoft.FSharp.Core.FSharpFunc`2[T3,Microsoft.FSharp.Core.FSharpFunc`2[T4,Microsoft.FSharp.Core.FSharpFunc`2[T5,Microsoft.FSharp.Core.Unit]]]]] FromAction[T1,T2,T3,T4,T5](System.Action`5[T1,T2,T3,T4,T5]) Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T1,Microsoft.FSharp.Core.FSharpFunc`2[T2,Microsoft.FSharp.Core.FSharpFunc`2[T3,Microsoft.FSharp.Core.FSharpFunc`2[T4,Microsoft.FSharp.Core.FSharpFunc`2[T5,TResult]]]]] FromFunc[T1,T2,T3,T4,T5,TResult](System.Func`6[T1,T2,T3,T4,T5,TResult]) Microsoft.FSharp.Core.FuncConvert: Microsoft.FSharp.Core.FSharpFunc`2[T1,Microsoft.FSharp.Core.FSharpFunc`2[T2,Microsoft.FSharp.Core.FSharpFunc`2[T3,Microsoft.FSharp.Core.FSharpFunc`2[T4,Microsoft.FSharp.Core.FSharpFunc`2[T5,TResult]]]]] FuncFromTupled[T1,T2,T3,T4,T5,TResult](Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`5[T1,T2,T3,T4,T5],TResult]) @@ -2049,6 +2058,7 @@ Microsoft.FSharp.Core.Operators: System.IO.TextReader ConsoleIn[T]() Microsoft.FSharp.Core.Operators: System.IO.TextWriter ConsoleError[T]() Microsoft.FSharp.Core.Operators: System.IO.TextWriter ConsoleOut[T]() Microsoft.FSharp.Core.Operators: System.Object Box[T](T) +Microsoft.FSharp.Core.Operators: System.String NameOf[T](T) Microsoft.FSharp.Core.Operators: System.String ToString[T](T) Microsoft.FSharp.Core.Operators: System.String op_Concatenate(System.String, System.String) Microsoft.FSharp.Core.Operators: System.Tuple`2[TKey,TValue] KeyValuePattern[TKey,TValue](System.Collections.Generic.KeyValuePair`2[TKey,TValue]) diff --git a/tests/FSharp.Core.UnitTests/SurfaceArea.net40.fs b/tests/FSharp.Core.UnitTests/SurfaceArea.net40.fs index 31a266a41db..7a6f7f9d334 100644 --- a/tests/FSharp.Core.UnitTests/SurfaceArea.net40.fs +++ b/tests/FSharp.Core.UnitTests/SurfaceArea.net40.fs @@ -547,6 +547,8 @@ Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[Sys Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[System.Threading.CancellationToken] get_CancellationToken() Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[System.Threading.Tasks.Task`1[T]] StartChildAsTask[T](Microsoft.FSharp.Control.FSharpAsync`1[T], Microsoft.FSharp.Core.FSharpOption`1[System.Threading.Tasks.TaskCreationOptions]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T[]] Parallel[T](System.Collections.Generic.IEnumerable`1[Microsoft.FSharp.Control.FSharpAsync`1[T]]) +Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T[]] Parallel[T](System.Collections.Generic.IEnumerable`1[Microsoft.FSharp.Control.FSharpAsync`1[T]], Microsoft.FSharp.Core.FSharpOption`1[System.Int32]) +Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T[]] Sequential[T](System.Collections.Generic.IEnumerable`1[Microsoft.FSharp.Control.FSharpAsync`1[T]]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T] AwaitEvent[TDel,T](Microsoft.FSharp.Control.IEvent`2[TDel,T], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Core.Unit]]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T] AwaitTask[T](System.Threading.Tasks.Task`1[T]) Microsoft.FSharp.Control.FSharpAsync: Microsoft.FSharp.Control.FSharpAsync`1[T] FromBeginEnd[TArg1,TArg2,TArg3,T](TArg1, TArg2, TArg3, Microsoft.FSharp.Core.FSharpFunc`2[System.Tuple`5[TArg1,TArg2,TArg3,System.AsyncCallback,System.Object],System.IAsyncResult], Microsoft.FSharp.Core.FSharpFunc`2[System.IAsyncResult,T], Microsoft.FSharp.Core.FSharpOption`1[Microsoft.FSharp.Core.FSharpFunc`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Core.Unit]]) @@ -2056,6 +2058,7 @@ Microsoft.FSharp.Core.Operators: System.IO.TextReader ConsoleIn[T]() Microsoft.FSharp.Core.Operators: System.IO.TextWriter ConsoleError[T]() Microsoft.FSharp.Core.Operators: System.IO.TextWriter ConsoleOut[T]() Microsoft.FSharp.Core.Operators: System.Object Box[T](T) +Microsoft.FSharp.Core.Operators: System.String NameOf[T](T) Microsoft.FSharp.Core.Operators: System.String ToString[T](T) Microsoft.FSharp.Core.Operators: System.String op_Concatenate(System.String, System.String) Microsoft.FSharp.Core.Operators: System.Tuple`2[TKey,TValue] KeyValuePattern[TKey,TValue](System.Collections.Generic.KeyValuePair`2[TKey,TValue]) @@ -2701,5 +2704,4 @@ Microsoft.FSharp.Reflection.UnionCaseInfo: System.Type get_DeclaringType()" () #else SurfaceArea.verify expected "net40" (System.IO.Path.Combine(__SOURCE_DIRECTORY__,__SOURCE_FILE__)) - () #endif diff --git a/tests/fsharp/Compiler/CompilerAssert.fs b/tests/fsharp/Compiler/CompilerAssert.fs index 2402de3a0ac..50102ab21c4 100644 --- a/tests/fsharp/Compiler/CompilerAssert.fs +++ b/tests/fsharp/Compiler/CompilerAssert.fs @@ -3,6 +3,7 @@ namespace FSharp.Compiler.UnitTests open System +open System.Diagnostics open System.IO open System.Text open System.Diagnostics @@ -142,11 +143,11 @@ let main argv = 0""" ProjectId = None SourceFiles = [|"test.fs"|] #if !NETCOREAPP - OtherOptions = [|"--preferreduilang:en-US"|] + OtherOptions = [|"--preferreduilang:en-US";"--warn:5"|] #else OtherOptions = let assemblies = getNetCoreAppReferences |> Array.map (fun x -> sprintf "-r:%s" x) - Array.append [|"--preferreduilang:en-US"; "--targetprofile:netcore"; "--noframework"|] assemblies + Array.append [|"--preferreduilang:en-US"; "--targetprofile:netcore"; "--noframework";"--warn:5"|] assemblies #endif ReferencedProjects = [||] IsIncompleteTypeCheckEnvironment = false @@ -314,10 +315,3 @@ let main argv = 0""" Assert.AreEqual(expectedErrorRange, (info.StartLineAlternate, info.StartColumn + 1, info.EndLineAlternate, info.EndColumn + 1), "expectedErrorRange") Assert.AreEqual(expectedErrorMsg, info.Message, "expectedErrorMsg") ) - - [] - let ``hello world``() = - CompileExeAndRun - """ -(printfn "Hello, world.") - """ \ No newline at end of file diff --git a/tests/fsharp/Compiler/ErrorMessages/WarnExpressionTests.fs b/tests/fsharp/Compiler/ErrorMessages/WarnExpressionTests.fs index 4ed147e916e..8929183b83e 100644 --- a/tests/fsharp/Compiler/ErrorMessages/WarnExpressionTests.fs +++ b/tests/fsharp/Compiler/ErrorMessages/WarnExpressionTests.fs @@ -107,7 +107,8 @@ let changeX() = [] let ``Warn If Discarded In List``() = - CompilerAssert.TypeCheckSingleError + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] """ let div _ _ = 1 let subView _ _ = [1; 2] @@ -119,14 +120,17 @@ let view model dispatch = div [] [] ] """ - FSharpErrorSeverity.Warning - 3221 - (9, 8, 9, 17) - "This expression returns a value of type 'int' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'." + [| + FSharpErrorSeverity.Warning, + 3221, + (9, 8, 9, 17), + "This expression returns a value of type 'int' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'." + |] [] let ``Warn If Discarded In List 2``() = - CompilerAssert.TypeCheckSingleError + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] """ // stupid things to make the sample compile let div _ _ = 1 @@ -143,14 +147,17 @@ let view model dispatch = ] ] """ - FSharpErrorSeverity.Warning - 3222 - (13, 19, 13, 41) - "This expression returns a value of type 'int list' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'." + [| + FSharpErrorSeverity.Warning, + 3222, + (13, 19, 13, 41), + "This expression returns a value of type 'int list' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'." + |] [] let ``Warn If Discarded In List 3``() = - CompilerAssert.TypeCheckSingleError + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] """ // stupid things to make the sample compile let div _ _ = 1 @@ -167,10 +174,12 @@ let view model dispatch = ] ] """ - FSharpErrorSeverity.Warning - 20 - (13, 19, 13, 41) - "The result of this expression has type 'bool' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'." + [| + FSharpErrorSeverity.Warning, + 20, + (13, 19, 13, 41), + "The result of this expression has type 'bool' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'." + |] [] let ``Warn Only On Last Expression``() = diff --git a/tests/fsharp/Compiler/Language/ByrefTests.fs b/tests/fsharp/Compiler/Language/ByrefTests.fs new file mode 100644 index 00000000000..2797125d791 --- /dev/null +++ b/tests/fsharp/Compiler/Language/ByrefTests.fs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.UnitTests + +open NUnit.Framework +open FSharp.Compiler.SourceCodeServices + +[] +module ByrefTests = + + [] + let ``No defensive copy on .NET struct`` () = + CompilerAssert.Pass + """ +open System +open System.Runtime.CompilerServices + +let f (x: DateTime) = x.ToLocalTime() +let f2 () = + let x = DateTime.Now + x.ToLocalTime() + +[] +type Extensions = + + [] + static member Test(x: inref) = &x + + [] + static member Test2(x: byref) = &x + +let test (x: inref) = + x.Test() + +let test2 (x: byref) = + x.Test2() + +let test3 (x: byref) = + x.Test() + +let test4 () = + DateTime.Now.Test() + +let test5 (x: inref) = + &x.Test() + +let test6 () = + DateTime.Now.Test().Test().Test() + """ + + [] + let ``Extension method scope errors`` () = + CompilerAssert.TypeCheckWithErrors + """ +open System +open System.Runtime.CompilerServices + +[] +type Extensions = + + [] + static member Test(x: inref) = &x + +let f1 () = + &DateTime.Now.Test() + +let f2 () = + let result = + let dt = DateTime.Now + &dt.Test() + result + +let f3 () = + Extensions.Test(let dt = DateTime.Now in &dt) + +let f4 () = + let dt = DateTime.Now + &Extensions.Test(&dt) + +let f5 () = + &Extensions.Test(let dt = DateTime.Now in &dt) + """ + [| + ( + FSharpErrorSeverity.Error, + 3228, + (12, 6, 12, 25), + "The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." + ) + ( + FSharpErrorSeverity.Error, + 3228, + (17, 10, 17, 19), + "The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." + ) + ( + FSharpErrorSeverity.Error, + 3228, + (21, 5, 21, 50), + "The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." + ) + ( + FSharpErrorSeverity.Error, + 3228, + (25, 6, 25, 26), + "The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." + ) + ( + FSharpErrorSeverity.Error, + 3228, + (28, 6, 28, 51), + "The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope." + ) + |] + +// TODO: A better way to test the ones below are to use a custom struct in C# code that contains explicit use of their "readonly" keyword. +#if NETCOREAPP + // NETCORE makes DateTime a readonly struct; therefore, it should not error. + [] + let ``No defensive copy on .NET struct - netcore`` () = + CompilerAssert.Pass + """ +open System +let f (x: inref) = x.ToLocalTime() +let f2 () = + let x = DateTime.Now + let y = &x + y.ToLocalTime() +let f3 (x: inref) = &x +let f4 (x: inref) = + (f3 &x).ToLocalTime() + +open System.Runtime.CompilerServices +[] +type Extensions = + + [] + static member Test(x: inref) = &x + +let test1 () = + DateTime.Now.Test().Date + +let test2 () = + DateTime.Now.Test().Test().Date.Test().Test().Date.Test() + """ +#else + // Note: Currently this is assuming NET472. That may change which might break these tests. Consider using custom C# code. + [] + let ``Defensive copy on .NET struct for inref`` () = + CompilerAssert.TypeCheckWithErrors + """ +open System +let f (x: inref) = x.ToLocalTime() +let f2 () = + let x = DateTime.Now + let y = &x + y.ToLocalTime() +let f3 (x: inref) = &x +let f4 (x: inref) = + (f3 &x).ToLocalTime() + +open System.Runtime.CompilerServices +[] +type Extensions = + + [] + static member Test(x: inref) = &x + +let test1 () = + DateTime.Now.Test().Date + """ + [| + ( + FSharpErrorSeverity.Warning, + 52, + (3, 30, 3, 45), + "The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed" + ) + ( + FSharpErrorSeverity.Warning, + 52, + (7, 5, 7, 20), + "The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed" + ) + ( + FSharpErrorSeverity.Warning, + 52, + (10, 5, 10, 26), + "The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed" + ) + ( + FSharpErrorSeverity.Warning, + 52, + (20, 5, 20, 29), + "The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed" + ) + |] +#endif \ No newline at end of file diff --git a/tests/fsharp/Compiler/Language/OpenStaticClasses.fs b/tests/fsharp/Compiler/Language/OpenStaticClasses.fs new file mode 100644 index 00000000000..f4f955b0d5f --- /dev/null +++ b/tests/fsharp/Compiler/Language/OpenStaticClasses.fs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +namespace FSharp.Compiler.UnitTests + +open FSharp.Compiler.SourceCodeServices +open NUnit.Framework + + +(* + Tests in this file evaluate whether the language supports accessing functions on static classes using open + The feature was added in preview, the test cases ensure that the original errors are reproduced when the langversion:4.6 is specified +*) + +[] +module OpenStaticClassesTests = + + let baseModule = """ +module Core_OpenStaticClasses + +[] +type MyMath() = + static member Min(a: double, b: double) = System.Math.Min(a, b) + static member Min(a: int, b: int) = System.Math.Min(a, b) + +[] +type AutoOpenMyMath() = + static member AutoMin(a: double, b: double) = System.Math.Min(a, b) + static member AutoMin(a: int, b: int) = System.Math.Min(a, b) + +[] +type NotAllowedToOpen() = + static member QualifiedMin(a: double, b: double) = System.Math.Min(a, b) + static member QualifiedMin(a: int, b: int) = System.Math.Min(a, b) + +""" + + [] + let ``OpenStaticClassesTests - OpenSystemMathOnce - langversion:v4.6`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] + (baseModule + """ +module OpenSystemMathOnce = + + open System.Math + let x = Min(1.0, 2.0)""") + [| + (FSharpErrorSeverity.Error, 39, (22,28,22,32), "The namespace 'Math' is not defined."); + (FSharpErrorSeverity.Error, 39, (23,24,23,27), "The value or constructor 'Min' is not defined. Maybe you want one of the following:\r\n min\r\n sin") + |] + + [] + let ``OpenStaticClassesTests - OpenSystemMathOnce - langversion:preview`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:preview" |] + (baseModule + """ +module OpenSystemMathOnce = + + open System.Math + let x = Min(1.0, 2.0)""") + [| |] + + [] + let ``OpenStaticClassesTests - OpenSystemMathTwice - langversion:v4.6`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] + (baseModule + """ +module OpenSystemMathTwice = + + open System.Math + let x = Min(1.0, 2.0) + + open System.Math + let x2 = Min(2.0, 1.0)""") + [| + (FSharpErrorSeverity.Error, 39, (22,17,22,21), "The namespace 'Math' is not defined."); + (FSharpErrorSeverity.Error, 39, (23,13,23,16), "The value or constructor 'Min' is not defined. Maybe you want one of the following:\r\n min\r\n sin") + (FSharpErrorSeverity.Error, 39, (25,17,25,21), "The namespace 'Math' is not defined."); + (FSharpErrorSeverity.Error, 39, (26,14,26,17), "The value or constructor 'Min' is not defined. Maybe you want one of the following:\r\n min\r\n sin") + |] + + [] + let ``OpenStaticClassesTests - OpenSystemMathTwice - langversion:preview`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:preview" |] + (baseModule + """ +module OpenSystemMathOnce = + + open System.Math + let x = Min(1.0, 2.0)""") + [| |] + + [] + let ``OpenStaticClassesTests - OpenMyMathOnce - langversion:v4.6`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] + (baseModule + """ +module OpenMyMathOnce = + + open MyMath + let x = Min(1.0, 2.0) + let x2 = Min(1, 2)""") + [| + (FSharpErrorSeverity.Error, 39, (22,10,22,16), "The namespace or module 'MyMath' is not defined. Maybe you want one of the following:\r\n Math"); + (FSharpErrorSeverity.Error, 39, (23,13,23,16), "The value or constructor 'Min' is not defined. Maybe you want one of the following:\r\n min\r\n sin") + (FSharpErrorSeverity.Error, 39, (24,14,24,17), "The value or constructor 'Min' is not defined. Maybe you want one of the following:\r\n min\r\n sin") + |] + + [] + let ``OpenStaticClassesTests - OpenMyMathOnce - langversion:preview`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:preview" |] + (baseModule + """ +module OpenMyMathOnce = + + open MyMath + let x = Min(1.0, 2.0) + let x2 = Min(1, 2)""") + [| |] + + [] + let ``OpenStaticClassesTests - DontOpenAutoMath - langversion:v4.6`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] + (baseModule + """ +module DontOpenAutoMath = + + let x = AutoMin(1.0, 2.0) + let x2 = AutoMin(1, 2)""") + [| + (FSharpErrorSeverity.Error, 39, (22,13,22,20), "The value or constructor 'AutoMin' is not defined."); + (FSharpErrorSeverity.Error, 39, (23,14,23,21), "The value or constructor 'AutoMin' is not defined.") + |] + + [] + let ``OpenStaticClassesTests - DontOpenAutoMath - langversion:preview`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:preview" |] + (baseModule + """ +module DontOpenAutoMath = + + let x = AutoMin(1.0, 2.0) + let x2 = AutoMin(1, 2)""") + [| |] + + [] + let ``OpenStaticClassesTests - OpenAutoMath - langversion:v4.6`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:4.6" |] + (baseModule + """ +module OpenAutoMath = + open AutoOpenMyMath + //open NotAllowedToOpen + + let x = AutoMin(1.0, 2.0) + let x2 = AutoMin(1, 2)""") + [| + (FSharpErrorSeverity.Error, 39, (21,10,21,24), "The namespace or module 'AutoOpenMyMath' is not defined."); + (FSharpErrorSeverity.Error, 39, (24,13,24,20), "The value or constructor 'AutoMin' is not defined.") + (FSharpErrorSeverity.Error, 39, (25,14,25,21), "The value or constructor 'AutoMin' is not defined.") + |] + + [] + let ``OpenStaticClassesTests - OpenAutoMath - langversion:preview`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:preview" |] + (baseModule + """ +module OpenAutoMath = + open AutoOpenMyMath + //open NotAllowedToOpen + + let x = AutoMin(1.0, 2.0) + let x2 = AutoMin(1, 2)""") + [| |] + + [] + let ``OpenStaticClassesTests - OpenAccessibleFields - langversion:preview`` () = + CompilerAssert.TypeCheckWithErrorsAndOptions + [| "--langversion:preview" |] + (baseModule + """ +module OpenAFieldFromMath = + open System.Math + + let pi = PI""") + [||] + + // TODO - wait for Will's integration of testing changes that makes this easlier + // [] + // let ``OpenStaticClassesTests - InternalsVisibleWhenHavingAnIVT - langversion:preview``() = ... \ No newline at end of file diff --git a/tests/fsharp/FSharpSuite.Tests.fsproj b/tests/fsharp/FSharpSuite.Tests.fsproj index fc1e8d0e4b3..66d44a523a3 100644 --- a/tests/fsharp/FSharpSuite.Tests.fsproj +++ b/tests/fsharp/FSharpSuite.Tests.fsproj @@ -27,6 +27,7 @@ NunitHelpers.fs + @@ -56,10 +57,13 @@ + + + diff --git a/tests/fsharp/HandleExpects.fs b/tests/fsharp/HandleExpects.fs new file mode 100644 index 00000000000..76c5267bacf --- /dev/null +++ b/tests/fsharp/HandleExpects.fs @@ -0,0 +1,196 @@ +module HandleExpects + +open System +open System.IO +open System.Text.RegularExpressions +open System.Xml + +type Expects = { status:string; id:string; span:string; pattern:string; mutable matched:bool; line:string } +type ErrorMessage = { source:string; status:string; id:string; span:string; text:string; mutable matched:bool; line:string } +type Span = { startrow:int; startcol:int; endrow:int; endcol:int } + +let tryParseSpan (span:string) = + let s = span.Trim([| '('; ')' |]).Split(',') + match s.Length with + | 2 -> { startrow=Int32.Parse(s.[0]); startcol=Int32.Parse(s.[1]); endrow=Int32.MaxValue; endcol=Int32.MaxValue } + | 4 -> { startrow=Int32.Parse(s.[0]); startcol=Int32.Parse(s.[1]); endrow=Int32.Parse(s.[2]); endcol=Int32.Parse(s.[3]) } + | _ -> raise (InvalidDataException(sprintf "The span : '%s' is invalid" span)); + +let isStringEmpty s = String.IsNullOrWhiteSpace(s) +let isStringNotEmpty s = not (isStringEmpty s) +let stringToLower s = if isStringNotEmpty s then s.ToLower() else s +let areStringsEqual s1 s2 = String.Compare(s1, s2, StringComparison.OrdinalIgnoreCase) = 0 +let areSpansEqual s1 s2 = + let span1 = tryParseSpan s1 + let span2 = tryParseSpan s2 + if span1.startrow <> span2.startrow then false + elif span1.startcol <> span2.startcol then false + elif span1.endrow <> span2.endrow then false + elif span1.endcol <> span2.endcol then false + else true + +let stripFromFileExpectations source = + let readExpect expect = + let pattern = "(?]*>{1})(?.*)(?)" //"().)*-->|<\w*((?!\/<).)*\/>|<(?\w+)[^>]*>(?>[^<]|(?R))*<\/\k\s*>)" + let rx = new Regex(pattern) + let matched = rx.Match(expect) + if matched.Success then + // The content of the Expects group contains a lot of invalid Xml and the Xml reader fails when it sees it. + // So we just save it away, remove it from the xml, then read the xml and put it back + // Save away the contents of the element and strip it out of expect pattern + let content = (matched.Groups.[2]).ToString() + let nocontentxpect = + if isStringEmpty content then expect + else expect.Replace(content, "") + + let rdr = XmlReader.Create(new StringReader(nocontentxpect)) + let mutable element = { status="success"; id = ""; span = ""; pattern = content; matched = false; line=expect } + let mutable insideExpects = false + let mutable foundOne = false + try + let rec loop () = + if rdr.Read() then + match rdr.NodeType with + | XmlNodeType.Element when String.Compare(rdr.Name, "Expects", StringComparison.OrdinalIgnoreCase) = 0 -> + insideExpects <- true + if rdr.AttributeCount > 0 then + let status = stringToLower (rdr.GetAttribute("status")) + let span = rdr.GetAttribute("span") + let id = stringToLower (rdr.GetAttribute("id")) + element <- {element with status=status; id=id; span=span } + foundOne <- true + | XmlNodeType.EndElement when String.Compare(rdr.Name, "Expects", StringComparison.OrdinalIgnoreCase) = 0 -> + insideExpects <- false + | _ -> () + loop () + else () + loop () + if foundOne then Some element + else None + with | e -> printfn "Oops !!! %A" e; reraise() + else None + + File.ReadAllLines(source) + |> Array.filter(fun line -> line.Trim().StartsWith(@"//")) + |> Array.map(fun line -> line.Trim().Substring(2).Trim()) + |> Array.filter(fun line -> line.StartsWith(@" Array.map(fun expect -> readExpect expect) + |> Array.filter(fun expect -> expect.IsSome) + |> Array.map(fun expect -> expect.Value) + +let readErrorMessagesFromOutput output = + //Formats of error messages + // Syntax error in code: + // 1. filename(row,col): (sometext perhaps typecheck) error|warning ErrorNo: ErrorText + // e.g: Program.fs(5,9): error ErrorNo: ErrorText + // 2. Program.fs(5,3,5,20): (sometext perhaps typecheck) error FS0039: ErrorText + // e.g: + // Program.fs(5,3,5,20): (sometext perhaps typecheck) error FS0039: PicturePoint ... + // 3. error ErrorNo: ErrorText + // e.g: error FS0207: No inputs specified + let getErrorMessage line pattern = + let rx = new Regex(pattern) + let matched = rx.Match(line) + let getMatchForName (name:string) = matched.Groups.[name].ToString() + + if matched.Success then Some { + source = (getMatchForName "tagSourceFileName") + status = stringToLower (getMatchForName "tagStatus") + id = stringToLower (getMatchForName "tagErrorNo") + span = (getMatchForName "tagSpan") + text = (getMatchForName "tagText") + matched = false + line = line + } + else None + + let rgxTagSourceFileName = "(?[^(]{1,})(?:[(]{1})" + let rgxTagSpan = "(?[^):]{1,})(?:[)]{1})(?:[(\s:]*)" + let rgxTagStatus = "(?(error|typecheck error|warning|success|notin))" + let rgxColonWhiteSpace = "(?:[\s:]*)" + let rgxWhiteSpace = "(?:[\s]*)" + let rgxTagErrorNo = "(?\s*[^:\s]*)" + let rgxTagText = "(?.*)" + let rgxTagTail = "(?\s\[.*\]$)" + + // E.g: Q:\version46\test.fs(25,13): error FS0010: Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. [Q:\Temp\FSharp.Cambridge\vaw2t1vp.cai\f0bi0hny.wwx.fsproj] + let rgxFull = rgxTagSourceFileName + rgxTagSpan + rgxColonWhiteSpace + rgxTagStatus + rgxWhiteSpace + rgxTagErrorNo + rgxColonWhiteSpace + rgxTagText + rgxWhiteSpace + rgxTagTail + + // E.g: FSC : error FS0010: Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. [Q:\Temp\FSharp.Cambridge\vaw2t1vp.cai\f0bi0hny.wwx.fsproj] + let rgxShort = rgxTagStatus + rgxTagErrorNo + rgxColonWhiteSpace + rgxTagText + rgxWhiteSpace + rgxTagTail + [| + for line in output do + let errorMessage = + getErrorMessage line rgxFull + |> Option.orElse (getErrorMessage line rgxShort) + match errorMessage with + | Some e -> yield e + | _ -> () + |] + +let compareResults output (expectations:Expects array) (errorMessages:ErrorMessage array) = + for expect in expectations do + match expect.status with + | "error" + | "typecheck error" + | "warning" -> + // Check for this error/warning in found errors list + for msg in errorMessages do + let matched = + if isStringNotEmpty expect.id && not (areStringsEqual expect.id msg.id) then false + elif isStringNotEmpty expect.status && not (areStringsEqual expect.status msg.status) then false + elif isStringNotEmpty expect.span && not (areSpansEqual expect.span msg.span) then false + elif isStringNotEmpty expect.pattern then + let regex = new Regex(expect.pattern) + let matched = regex.Match(msg.text) + matched.Success + else true + if matched then + expect.matched <- true + msg.matched <- true + | "success" -> + // In this case search for text in the page + let regex = new Regex(expect.pattern) + for line in output do + let matched = regex.Match(line) + if matched.Success then expect.matched <- true + | "notin" -> + // In this case search for text not appearing in the page + let regex = new Regex(expect.pattern) + let mutable found = false + for line in output do + let matched = regex.Match(line) + if matched.Success then found <- true + if not found then expect.matched <- true + | _ -> () + +let verifyResults source outputPath = + let output = File.ReadAllLines(outputPath) + let expectations = stripFromFileExpectations source + if expectations.Length > 0 then + // There must be at least one to do this testing + let errorMessages = readErrorMessagesFromOutput output + compareResults output expectations errorMessages + + // Print out discovered expects + let verifiedexpectations = + expectations + |> Seq.fold(fun result expects -> + if not (expects.matched) then + printfn "Failed to match expected result '%s'" expects.line + false + else result + ) true + let verifiederrormessages = + errorMessages + |> Seq.fold(fun result msg -> + if not (msg.matched) then + printfn "Failed to match produced error message: '%s'" msg.line + false + else result + ) true + + if not (verifiedexpectations && verifiederrormessages) then + failwith (sprintf "Failed validating error codes") + +//HandleExpects.verifyResults @"C:\Users\kevinr\AppData\Local\Temp\FSharp.Cambridge\bcnyzkvb.ict\test.fs" @"C:\Users\kevinr\AppData\Local\Temp\FSharp.Cambridge\bcnyzkvb.ict\buildoutput.txt" \ No newline at end of file diff --git a/tests/fsharp/core/forexpression/test.fsx b/tests/fsharp/core/forexpression/test.fsx index 6384d113693..0fada85b01b 100644 --- a/tests/fsharp/core/forexpression/test.fsx +++ b/tests/fsharp/core/forexpression/test.fsx @@ -19,6 +19,7 @@ let testData = let expectedArraySum = 167167000 // Find an expression for this sum from count let expectedRangeSum = ((count + 1) * count) / 2 let expectedStringSum = 30 +let expectedWildCard = count + 1 let getTestData (inner : int [] -> #seq) (outer : #seq [] -> #seq<'U>) = (testData |> Array.map inner) |> outer @@ -109,11 +110,7 @@ let sumOverRange () = let sumOverString () = let mutable sum = 0 for i in testString do -#if NETCOREAPP - sum <- sum + ((int (i :?> char)) - (int '0')) -#else sum <- sum + ((int i) - (int '0')) -#endif sum let arraySum = sumOverArray () diff --git a/tests/fsharp/core/forexpression/version46/test.fs b/tests/fsharp/core/forexpression/version46/test.fs new file mode 100644 index 00000000000..c2042a9f0c1 --- /dev/null +++ b/tests/fsharp/core/forexpression/version46/test.fs @@ -0,0 +1,41 @@ +//An integer for loop must use a simple identifier +module Global + +let failures = ref [] + +let report_failure (s : string) = + stderr.Write" NO: " + stderr.WriteLine s + failures := !failures @ [s] + +let test (s : string) b = + stderr.Write(s) + if b then stderr.WriteLine " OK" + else report_failure (s) + +let check s b1 b2 = test s (b1 = b2) + +// usingWildcard counts using a wildcard in a for loop +let usingWildcard () = + let mutable sum = 0 + for _ = 0 to count do + sum <- sum + 1 + + printfn "usingWildcards expected to produce sum of 4 : sum='%d'"sum + +do test "wildCard" (4 = usingWildcard () ) + +#if TESTS_AS_APP +let RUN() = !failures +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif + diff --git a/tests/fsharp/core/forexpression/version47/test.fs b/tests/fsharp/core/forexpression/version47/test.fs new file mode 100644 index 00000000000..868a4757ce2 --- /dev/null +++ b/tests/fsharp/core/forexpression/version47/test.fs @@ -0,0 +1,43 @@ +//usingWildcards expected to produce sum of 4 : sum='4' +#if TESTS_AS_APP +module Core_forexpression_47 +#endif + +let failures = ref [] + +let report_failure (s : string) = + stderr.Write" NO: " + stderr.WriteLine s + failures := !failures @ [s] + +let test (s : string) b = + stderr.Write(s) + if b then stderr.WriteLine " OK" + else report_failure (s) + +let check s b1 b2 = test s (b1 = b2) + +// usingWildcard counts using a wildcard in a for loop +let usingWildcard () = + let mutable sum = 0 + for _ = 0 to count do + sum <- sum + 1 + + printfn "usingWildcards expected to produce sum of 4 : sum='%d'"sum + +do test "wildCard" (4 = usingWildcard () ) + +#if TESTS_AS_APP +let RUN() = !failures +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif + diff --git a/tests/fsharp/core/fsfromfsviacs/lib2.cs b/tests/fsharp/core/fsfromfsviacs/lib2.cs index eb6d6acc141..449f926d7f4 100644 --- a/tests/fsharp/core/fsfromfsviacs/lib2.cs +++ b/tests/fsharp/core/fsfromfsviacs/lib2.cs @@ -124,4 +124,17 @@ public class ApiWrapper public static Func f4 = new Func((int arg1, string arg2, byte arg3, sbyte arg4) => arg1 + arg2.Length + 1 + arg3 + arg4); public static Func f5 = new Func((int arg1, string arg2, byte arg3, sbyte arg4, Int16 arg5) => arg1 + arg2.Length + 1 + arg3 + arg4 + arg5); } +} + +namespace StructTests +{ + public struct NonReadOnlyStruct + { + public int X { get; set; } + + public void M(int x) + { + X = x; + } + } } \ No newline at end of file diff --git a/tests/fsharp/core/fsfromfsviacs/test.fsx b/tests/fsharp/core/fsfromfsviacs/test.fsx index 072a896c1eb..47e2e359769 100644 --- a/tests/fsharp/core/fsfromfsviacs/test.fsx +++ b/tests/fsharp/core/fsfromfsviacs/test.fsx @@ -210,6 +210,75 @@ let ToFSharpFunc() = test "vkejhwew904" (FuncConvert.FromFunc(FSharpFuncTests.ApiWrapper.f4)(3)("a")(6uy)(7y) = FSharpFuncTests.ApiWrapper.f4.Invoke(3, "a", 6uy, 7y)) test "vkejhwew905" (FuncConvert.FromFunc(FSharpFuncTests.ApiWrapper.f5)(3)("a")(6uy)(7y)(7s) = FSharpFuncTests.ApiWrapper.f5.Invoke(3, "a", 6uy, 7y, 7s)) +module TestStructs = + open StructTests + + let someFunc (s: NonReadOnlyStruct) = + s.M(456) + s.X + + let someByrefFunc (s: byref) = + s.M(456) + s.X + + let someInrefFunc (s: inref) = + s.M(456) + s.X + + let someFuncReturn (s: NonReadOnlyStruct) = + s.X + + let someInrefFuncReturn (s: inref) = + s.X + + let test1 () = + let s = NonReadOnlyStruct() + check "hdlcjiklhen1" s.X 0 + s.M(123) + check "hdlcjiklhen2" s.X 123 + check "hdlcjiklhen3" (someFunc s) 456 + check "hdlcjiklhen4" s.X 123 + + + let test2 () = + let mutable s = NonReadOnlyStruct() + check "hdlcjiklhen5" s.X 0 + s.M(123) + check "hdlcjiklhen6" s.X 123 + check "hdlcjiklhen7" (someByrefFunc &s) 456 + check "hdlcjiklhen8" s.X 456 + + + let test3 () = + let s = NonReadOnlyStruct() + check "hdlcjiklhen9" s.X 0 + s.M(123) + check "hdlcjiklhen10" s.X 123 + check "hdlcjiklhen11" (someInrefFunc &s) 123 + check "hdlcjiklhen12" s.X 123 + + let test4 () = + let s = NonReadOnlyStruct() + check "hdlcjiklhen13" s.X 0 + s.M(123) + check "hdlcjiklhen14" s.X 123 + check "hdlcjiklhen15" (someFuncReturn s) 0 // Technically a bug today, but test is to verify current behavior. + check "hdlcjiklhen16" s.X 123 + + let test5 () = + let s = NonReadOnlyStruct() + check "hdlcjiklhen17" s.X 0 + s.M(123) + check "hdlcjiklhen18" s.X 123 + check "hdlcjiklhen19" (someInrefFuncReturn &s) 123 + check "hdlcjiklhen20" s.X 123 + +TestStructs.test1 () +TestStructs.test2 () +TestStructs.test3 () +TestStructs.test4 () +TestStructs.test5 () + #endif #if TESTS_AS_APP diff --git a/tests/fsharp/core/indent/version46/test.fsx b/tests/fsharp/core/indent/version46/test.fsx new file mode 100644 index 00000000000..7afc6f1dd51 --- /dev/null +++ b/tests/fsharp/core/indent/version46/test.fsx @@ -0,0 +1,121 @@ +//Possible incorrect indentation: this token is offside of context started at position \(59:19\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(59:19\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(63:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(63:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(69:23\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(69:23\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(77:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(77:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(83:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(83:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(88:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(88:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(91:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(91:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(95:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(95:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(100:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(100:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(104:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(104:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(59:19\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(59:19\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(63:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(63:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(69:23\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(69:23\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(77:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(77:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(83:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(83:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(88:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(88:25\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(91:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(91:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(95:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(95:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(100:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(100:20\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(104:21\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(104:21\). Try indenting this token further or using standard formatting conventions. + + +module Global + +let failures = ref [] + +let report_failure (s : string) = + stderr.Write" NO: " + stderr.WriteLine s + failures := !failures @ [s] + +let test (s : string) b = + stderr.Write(s) + if b then stderr.WriteLine " OK" + else report_failure (s) + +let check s b1 b2 = test s (b1 = b2) + +type OffsideCheck(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = 1 + +module M = + type OffsideCheck(a:int, + b:int, c:int, // 4.6 warning: 4.7 warning + d:int, e:int, + f:int) = + class end + +module M2 = + type OffsideCheck() = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 warning + d:int, e:int, + f:int) = 1 + +type C() = + static member P with get() = + 1 // 4.6 warning: 4.7 no warning + +module M3 = + type C() = + static member P with get() = + 1 // warning + +type OffsideCheck2(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = 1 + +type OffsideCheck3(a:int, + b:int, c:int, // no warning + d:int, e:int, + f:int) = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = 1 + +#if TESTS_AS_APP +let RUN() = !failures +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif diff --git a/tests/fsharp/core/indent/version47/test.fsx b/tests/fsharp/core/indent/version47/test.fsx new file mode 100644 index 00000000000..97b226e9e52 --- /dev/null +++ b/tests/fsharp/core/indent/version47/test.fsx @@ -0,0 +1,93 @@ +//Possible incorrect indentation: this token is offside of context started at position \(41:5\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(41:5\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(49:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(49:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(60:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(60:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(41:5\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(41:5\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(49:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(49:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(60:9\). Try indenting this token further or using standard formatting conventions. +//Possible incorrect indentation: this token is offside of context started at position \(60:9\). Try indenting this token further or using standard formatting conventions. + + +module Global + +let failures = ref [] + +let report_failure (s : string) = + stderr.Write" NO: " + stderr.WriteLine s + failures := !failures @ [s] + +let test (s : string) b = + stderr.Write(s) + if b then stderr.WriteLine " OK" + else report_failure (s) + +let check s b1 b2 = test s (b1 = b2) + +type OffsideCheck(a:int, + b:int, c:int, // no warning + d:int, e:int, + f:int) = + static member M(a:int, + b:int, c:int, // no warning + d:int, e:int, + f:int) = 1 + +module M = + type OffsideCheck(a:int, + b:int, c:int, // 4.6 warning: 4.7 warning + d:int, e:int, + f:int) = + class end + +module M2 = + type OffsideCheck() = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 warning + d:int, e:int, + f:int) = 1 + +type C() = + static member P with get() = + 1 // 4.6 warning: 4.7 no warning + +module M3 = + type C() = + static member P with get() = + 1 // warning + +type OffsideCheck2(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = 1 + +type OffsideCheck3(a:int, + b:int, c:int, // no warning + d:int, e:int, + f:int) = + static member M(a:int, + b:int, c:int, // 4.6 warning: 4.7 no warning + d:int, e:int, + f:int) = 1 + +#if TESTS_AS_APP +let RUN() = !failures +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif diff --git a/tests/fsharp/core/members/self-identifier/version46/test.fs b/tests/fsharp/core/members/self-identifier/version46/test.fs new file mode 100644 index 00000000000..5a53a84a4cb --- /dev/null +++ b/tests/fsharp/core/members/self-identifier/version46/test.fs @@ -0,0 +1,62 @@ +//Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. +//Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. +//Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. +//Unexpected symbol '.' in member definition. Expected 'with', '=' or other token. + +module Global + +let failures = ref [] + +let report_failure (s : string) = + stderr.Write" NO: " + stderr.WriteLine s + failures := !failures @ [s] + +let test (s : string) b = + stderr.Write(s) + if b then stderr.WriteLine " OK" + else report_failure (s) + +let check s b1 b2 = test s (b1 = b2) + +//-------------------------------------------------------------- +// Test using "_" as the self identifier introduced in F# 4.7 +type MyTypeWithUnderscoreIdentifier () = + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + +[] +type MyStructWithUnderscoreIdentifier = + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + +type MyClassWithUnderscoreIdentifier () = + class + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + end + +type MyStructTypeWithUnderscoreIdentifier = + struct + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + end + + +#if TESTS_AS_APP +let RUN() = !failures +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif diff --git a/tests/fsharp/core/members/self-identifier/version47/test.fs b/tests/fsharp/core/members/self-identifier/version47/test.fs new file mode 100644 index 00000000000..99629250b65 --- /dev/null +++ b/tests/fsharp/core/members/self-identifier/version47/test.fs @@ -0,0 +1,58 @@ +module Global + +let failures = ref [] + +let report_failure (s : string) = + stderr.Write" NO: " + stderr.WriteLine s + failures := !failures @ [s] + +let test (s : string) b = + stderr.Write(s) + if b then stderr.WriteLine " OK" + else report_failure (s) + +let check s b1 b2 = test s (b1 = b2) + +//-------------------------------------------------------------- +// Test using "_" as the self identifier introduced in F# 4.7 +type MyTypeWithUnderscoreIdentifier () = + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + +[] +type MyStructWithUnderscoreIdentifier = + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + +type MyClassWithUnderscoreIdentifier () = + class + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + end + +type MyStructTypeWithUnderscoreIdentifier = + struct + member _.MethodWithUnderscoreSelf() = true + member __.MethodWithDoubleUnderscoreSelf() = true + member _E.MethodWithUnderscoreESelf() = true + end + + +#if TESTS_AS_APP +let RUN() = !failures +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif + diff --git a/tests/fsharp/core/nameof/preview/test.fsx b/tests/fsharp/core/nameof/preview/test.fsx new file mode 100644 index 00000000000..bbad8d142ad --- /dev/null +++ b/tests/fsharp/core/nameof/preview/test.fsx @@ -0,0 +1,353 @@ +// +#if TESTS_AS_APP +module TestSuite_FSharpCore_nameof_47 +#endif + +#nowarn "44" + +open System + +exception ABC + +type Assert = + static member AreEqual (a, b) = a=b + static member Fail = raise (Exception("Fail")) + +let failures = ref [] + +let report_failure (s : string) = + failures := !failures @ [s] + +let test (s : string) b = + if b then stderr.Write " Success " + else + stderr.Write " Failed " + report_failure (s) + stderr.WriteLine(s) + +let check s b1 b2 = test s (b1 = b2) + +type BasicNameOfTests() = + + static let staticConstant = 23 + let localConstant = 23 + + member this.MemberMethod() = 0 + member this.MemberProperty = this.MemberMethod() + + member this.``member method``() = 0 + member this.``member property`` = this.``member method``() + + static member StaticMethod() = 0 + static member StaticProperty = BasicNameOfTests.StaticMethod() + + static member ``static method``() = 0 + static member ``static property`` = BasicNameOfTests.``static method``() + + static member ``local variable name lookup`` () = + let a = 0 + let b = nameof a + let result = Assert.AreEqual("a", b) + let c = nameof b + result || Assert.AreEqual("b", c) + + static member ``local int function name`` () = + let myFunction x = 0 * x + let result = nameof myFunction + Assert.AreEqual("myFunction", result) + + static member ``local curried function name`` () = + let curriedFunction x y = x * y + let result = nameof curriedFunction + Assert.AreEqual("curriedFunction", result) + + static member ``local tupled function name`` () = + let tupledFunction(x,y) = x * y + let result = nameof tupledFunction + Assert.AreEqual("tupledFunction", result) + + static member ``local unit function name`` () = + let myFunction() = 1 + let result = nameof(myFunction) + Assert.AreEqual("myFunction", result) + + static member ``local function parameter name`` () = + let myFunction parameter1 = nameof parameter1 + let result = myFunction "x" + Assert.AreEqual("parameter1", result) + + static member ``can get name from inside a local function (needs to be let rec)`` () = + let rec myLocalFunction x = + let z = 2 * x + nameof myLocalFunction + " " + z.ToString() + + let a = myLocalFunction 23 + let result = Assert.AreEqual("myLocalFunction 46", a) + + let b = myLocalFunction 25 + result || Assert.AreEqual("myLocalFunction 50", b) + + static member ``can get name from inside static member`` () = + let b = nameof(BasicNameOfTests.``can get name from inside static member``) + Assert.AreEqual("can get name from inside static member", b) + + member this.``can get name from inside instance member`` () = + let b = nameof(this.``can get name from inside instance member``) + Assert.AreEqual("can get name from inside instance member", b) + + static member ``can get name of static member`` () = + let b = nameof(BasicNameOfTests.``can get name of static member``) + Assert.AreEqual("can get name of static member", b) + + member this.``can get name of instance member`` () = + let b = nameof(this.MemberMethod) + Assert.AreEqual("MemberMethod", b) + + static member ``namespace name`` () = + let b = nameof(FSharp.Core) + Assert.AreEqual("Core",b) + + static member ``module name`` () = + let b = nameof(FSharp.Core.Operators) + Assert.AreEqual("Operators",b) + + static member ``exception name`` () = + let b = nameof(ABC) + Assert.AreEqual("ABC",b) + + static member ``nested type name 1`` () = + let b = nameof(System.Collections.Generic.List.Enumerator<_>) + Assert.AreEqual("Enumerator",b) + + static member ``type name 2`` () = + let b = nameof(System.Action<_>) + Assert.AreEqual("Action",b) + + static member ``member function which is defined below`` () = + let x = BasicNameOfTests() + let b = nameof(x.MemberMethodDefinedBelow) + Assert.AreEqual("MemberMethodDefinedBelow",b) + + member this.MemberMethodDefinedBelow(x,y) = x * y + + static member ``static member function name`` () = + let b = nameof(BasicNameOfTests.StaticMethod) + Assert.AreEqual("StaticMethod",b) + + member this.``class member lookup`` () = + let b = nameof(localConstant) + Assert.AreEqual("localConstant",b) + + static member ``static property name`` () = + let b = nameof(BasicNameOfTests.StaticProperty) + Assert.AreEqual("StaticProperty",b) + + member this.get_XYZ() = 1 + + static member ``member method starting with get_`` () = + let x = BasicNameOfTests() + let b = nameof(x.get_XYZ) + Assert.AreEqual("get_XYZ",b) + + static member get_SXYZ() = 1 + + static member ``static method starting with get_`` () = + let b = nameof(BasicNameOfTests.get_SXYZ) + Assert.AreEqual("get_SXYZ",b) + + static member ``nameof local property with encapsulated name`` () = + let ``local property with encapsulated name and %.f`` = 0 + let b = nameof(``local property with encapsulated name and %.f``) + Assert.AreEqual("local property with encapsulated name and %.f",b) + +type MethodGroupNameOfTests() = + member this.MethodGroup() = () + member this.MethodGroup(i:int) = () + + member this.MethodGroup1(i:int, f:float, s:string) = 0 + member this.MethodGroup1(f:float, l:int64) = "foo" + member this.MethodGroup1(u:unit -> unit -> int, h: unit) : unit = () + + member this.``single argument method group name lookup`` () = + let b = nameof(this.MethodGroup) + Assert.AreEqual("MethodGroup",b) + + member this.``multiple argument method group name lookup`` () = + let b = nameof(this.MethodGroup1 : (float * int64 -> _)) + Assert.AreEqual("MethodGroup1",b) + +type FrameworkMethodTests() = + member this.``library function name`` () = + let b = nameof(List.map) + Assert.AreEqual("map",b) + + member this.``static class function name`` () = + let b = nameof(System.Tuple.Create) + Assert.AreEqual("Create",b) + +type CustomUnionType = + | OptionA + | OptionB of int * string + +type CustomRecordType = + { X: int; Y: int } + +[] type Milliquacks + +type UnionAndRecordNameOfTests() = + + member this.``measure 1`` () = + let b = nameof(Milliquacks) + Assert.AreEqual("Milliquacks",b) + + member this.``record case 1`` () = + let sample = Unchecked.defaultof + let b = nameof(sample.X) + let result = Assert.AreEqual("X",b) + let b = nameof(sample.Y) + result || Assert.AreEqual("Y",b) + + member this.``union case 1`` () = + let b = nameof(OptionA) + Assert.AreEqual("OptionA",b) + + member this.``union case 2`` () = + let b = nameof(OptionB) + Assert.AreEqual("OptionB",b) + +type AttributeNameOfTests() = + + [] + member this.``ok in attribute`` () = + let t = typeof.GetMethod("ok in attribute") + let attrs = t.GetCustomAttributes(typeof, false) + let attr = attrs.[0] :?> ObsoleteAttribute + Assert.AreEqual(attr.Message, "test string") + +type OperatorNameOfTests() = + + member this.``lookup name of typeof operator`` () = + let b = nameof(typeof) + Assert.AreEqual("typeof",b) + + member this.``lookup name of + operator`` () = + let b = nameof(+) + Assert.AreEqual("op_Addition",b) + + member this.``lookup name of |> operator`` () = + let a = nameof(|>) + let result = Assert.AreEqual("op_PipeRight",a) + let b = nameof(op_PipeRight) + result || Assert.AreEqual("op_PipeRight",b) + + member this.``lookup name of nameof operator`` () = + let b = nameof(nameof) + Assert.AreEqual("nameof",b) + +type PatternMatchingOfOperatorNameTests() = + member this.Method1(i:int) = () + + member this.``use it as a match case guard`` () = + match "Method1" with + | x when x = nameof(this.Method1) -> true + | _ -> false + +type NameOfOperatorInQuotations() = + member this.``use it in a quotation`` () = + let q = + <@ + let f(x:int) = nameof x + f 20 + @> + true + +type NameOfOperatorForGenerics() = + member this.``use it in a generic function`` () = + let fullyGeneric x = x + let b = nameof(fullyGeneric) + Assert.AreEqual("fullyGeneric",b) + + member this.``lookup name of a generic class`` () = + let b = nameof System.Collections.Generic.List + Assert.AreEqual("List",b) + +type UserDefinedNameOfTests() = + static member ``user defined nameof should shadow the operator`` () = + let nameof x = "test" + x.ToString() + let y = nameof 1 + Assert.AreEqual("test1",y) + +type Person = + { Name : string + Age : int } + member __.Update(fld : string, value : obj) = + match fld with + | x when x = nameof __.Name -> { __ with Name = string value } + | x when x = nameof __.Age -> { __ with Age = value :?> int } + | _ -> __ + +do test "local variable name lookup" (BasicNameOfTests.``local variable name lookup`` ()) +do test "local int function name" (BasicNameOfTests.``local int function name`` ()) +do test "local curried function name" (BasicNameOfTests.``local curried function name`` ()) +do test "local tupled function name" (BasicNameOfTests.``local tupled function name`` ()) +do test "local unit function name" (BasicNameOfTests.``local unit function name`` ()) +do test "local function parameter name" (BasicNameOfTests.``local function parameter name`` ()) +do test "can get name from inside a local function (needs to be let rec)" + (BasicNameOfTests.``can get name from inside a local function (needs to be let rec)`` ()) +do test "can get name from inside static member" (BasicNameOfTests.``can get name from inside static member`` ()) +do test "can get name from inside instance member" ((BasicNameOfTests()).``can get name from inside instance member`` ()) +do test "can get name of instance member" ((BasicNameOfTests()).``can get name of instance member`` ()) +do test "namespace name" (BasicNameOfTests.``namespace name`` ()) +do test "module name" (BasicNameOfTests.``module name`` ()) +do test "exception name" (BasicNameOfTests.``exception name`` ()) +do test "nested type name 1" (BasicNameOfTests.``nested type name 1`` ()) +do test "type name 2" (BasicNameOfTests.``type name 2`` ()) +do test "member function which is defined below" (BasicNameOfTests.``member function which is defined below`` ()) +do test "class member lookup" ((BasicNameOfTests()).``class member lookup`` ()) +do test "static member function name" (BasicNameOfTests.``static member function name`` ()) +do test "static property name" (BasicNameOfTests.``static property name`` ()) +do test "member method starting with get_" (BasicNameOfTests.``member method starting with get_`` ()) +do test "static method starting with get_" (BasicNameOfTests.``static method starting with get_`` ()) +do test "nameof local property with encapsulated name" (BasicNameOfTests.``nameof local property with encapsulated name`` ()) + +do test "single argument method group name lookup" ((MethodGroupNameOfTests()).``single argument method group name lookup`` ()) +do test "multiple argument method group name lookup" ((MethodGroupNameOfTests()).``multiple argument method group name lookup`` ()) + +do test "measure 1" ((UnionAndRecordNameOfTests()).``measure 1`` ()) +do test "record case 1" ((UnionAndRecordNameOfTests()).``record case 1`` ()) +do test "union case 1" ((UnionAndRecordNameOfTests()).``union case 1`` ()) +do test "union case 2" ((UnionAndRecordNameOfTests()).``union case 2`` ()) + +do test "ok in attribute" ((AttributeNameOfTests()).``ok in attribute`` ()) + +do test "lookup name of typeof operator" ((OperatorNameOfTests()).``lookup name of typeof operator`` ()) +do test "lookup name of + operator" ((OperatorNameOfTests()).``lookup name of + operator`` ()) +do test "lookup name of |> operator" ((OperatorNameOfTests()).``lookup name of |> operator`` ()) +do test "lookup name of nameof operator" ((OperatorNameOfTests()).``lookup name of nameof operator`` ()) + +do test "use it as a match case guard" ((PatternMatchingOfOperatorNameTests()).``use it as a match case guard`` ()) + +do test "se it in a quotation" ((NameOfOperatorInQuotations()).``use it in a quotation`` ()) + +do test "use it in a generic function" ((NameOfOperatorForGenerics()).``use it in a generic function`` ()) +do test "lookup name of a generic class" ((NameOfOperatorForGenerics()).``lookup name of a generic class`` ()) + +do test "user defined nameof should shadow the operator"(UserDefinedNameOfTests.``user defined nameof should shadow the operator`` ()) + +#if TESTS_AS_APP +let RUN() = + match !failures with + | [] -> stdout.WriteLine "Test Passed" + | _ -> stdout.WriteLine "Test Failed" +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif + diff --git a/tests/fsharp/core/nameof/version46/test.fsx b/tests/fsharp/core/nameof/version46/test.fsx new file mode 100644 index 00000000000..111ac45dc6c --- /dev/null +++ b/tests/fsharp/core/nameof/version46/test.fsx @@ -0,0 +1,408 @@ +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//This is not a valid constant expression or custom attribute value +//This is not a valid constant expression or custom attribute value +//The value or constructor 'nameof' is not defined. +//This is not a valid constant expression or custom attribute value +//This is not a valid constant expression or custom attribute value +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'nameof' is not defined. +//The value or constructor 'name' is not defined. Maybe you want one of the following: + + + +#if TESTS_AS_APP +module TestSuite_FSharpCore_nameof_46 +#endif +#nowarn "44" + +open System + +exception ABC + +type Assert = + static member AreEqual (a, b) = a=b + static member Fail = raise (Exception("Fail")) + +let failures = ref [] + +let report_failure (s : string) = + failures := !failures @ [s] + +let test (s : string) b = + if b then stderr.Write " Success " + else + stderr.Write " Failed " + report_failure (s) + stderr.WriteLine(s) + +let check s b1 b2 = test s (b1 = b2) + +type BasicNameOfTests() = + + static let staticConstant = 23 + let localConstant = 23 + + member this.MemberMethod() = 0 + member this.MemberProperty = this.MemberMethod() + + member this.``member method``() = 0 + member this.``member property`` = this.``member method``() + + static member StaticMethod() = 0 + static member StaticProperty = BasicNameOfTests.StaticMethod() + + static member ``static method``() = 0 + static member ``static property`` = BasicNameOfTests.``static method``() + + static member ``local variable name lookup`` () = + let a = 0 + let b = nameof a + let result = Assert.AreEqual("a", b) + let c = nameof b + result || Assert.AreEqual("b", c) + + static member ``local int function name`` () = + let myFunction x = 0 * x + let result = nameof myFunction + Assert.AreEqual("myFunction", result) + + static member ``local curried function name`` () = + let curriedFunction x y = x * y + let result = nameof curriedFunction + Assert.AreEqual("curriedFunction", result) + + static member ``local tupled function name`` () = + let tupledFunction(x,y) = x * y + let result = nameof tupledFunction + Assert.AreEqual("tupledFunction", result) + + static member ``local unit function name`` () = + let myFunction() = 1 + let result = nameof(myFunction) + Assert.AreEqual("myFunction", result) + + static member ``local function parameter name`` () = + let myFunction parameter1 = nameof parameter1 + let result = myFunction "x" + Assert.AreEqual("parameter1", result) + + static member ``can get name from inside a local function (needs to be let rec)`` () = + let rec myLocalFunction x = + let z = 2 * x + nameof myLocalFunction + " " + z.ToString() + + let a = myLocalFunction 23 + let result = Assert.AreEqual("myLocalFunction 46", a) + + let b = myLocalFunction 25 + result || Assert.AreEqual("myLocalFunction 50", b) + + static member ``can get name from inside static member`` () = + let b = nameof(BasicNameOfTests.``can get name from inside static member``) + Assert.AreEqual("can get name from inside static member", b) + + member this.``can get name from inside instance member`` () = + let b = nameof(this.``can get name from inside instance member``) + Assert.AreEqual("can get name from inside instance member", b) + + static member ``can get name of static member`` () = + let b = nameof(BasicNameOfTests.``can get name of static member``) + Assert.AreEqual("can get name of static member", b) + + member this.``can get name of instance member`` () = + let b = nameof(this.MemberMethod) + Assert.AreEqual("MemberMethod", b) + + static member ``namespace name`` () = + let b = nameof(FSharp.Core) + Assert.AreEqual("Core",b) + + static member ``module name`` () = + let b = nameof(FSharp.Core.Operators) + Assert.AreEqual("Operators",b) + + static member ``exception name`` () = + let b = nameof(ABC) + Assert.AreEqual("ABC",b) + + static member ``nested type name 1`` () = + let b = nameof(System.Collections.Generic.List.Enumerator<_>) + Assert.AreEqual("Enumerator",b) + + static member ``type name 2`` () = + let b = nameof(System.Action<_>) + Assert.AreEqual("Action",b) + + static member ``member function which is defined below`` () = + let x = BasicNameOfTests() + let b = nameof(x.MemberMethodDefinedBelow) + Assert.AreEqual("MemberMethodDefinedBelow",b) + + member this.MemberMethodDefinedBelow(x,y) = x * y + + static member ``static member function name`` () = + let b = nameof(BasicNameOfTests.StaticMethod) + Assert.AreEqual("StaticMethod",b) + + member this.``class member lookup`` () = + let b = nameof(localConstant) + Assert.AreEqual("localConstant",b) + + static member ``static property name`` () = + let b = nameof(BasicNameOfTests.StaticProperty) + Assert.AreEqual("StaticProperty",b) + + member this.get_XYZ() = 1 + + static member ``member method starting with get_`` () = + let x = BasicNameOfTests() + let b = nameof(x.get_XYZ) + Assert.AreEqual("get_XYZ",b) + + static member get_SXYZ() = 1 + + static member ``static method starting with get_`` () = + let b = nameof(BasicNameOfTests.get_SXYZ) + Assert.AreEqual("get_SXYZ",b) + + static member ``nameof local property with encapsulated name`` () = + let ``local property with encapsulated name and %.f`` = 0 + let b = nameof(``local property with encapsulated name and %.f``) + Assert.AreEqual("local property with encapsulated name and %.f",b) + +type MethodGroupNameOfTests() = + member this.MethodGroup() = () + member this.MethodGroup(i:int) = () + + member this.MethodGroup1(i:int, f:float, s:string) = 0 + member this.MethodGroup1(f:float, l:int64) = "foo" + member this.MethodGroup1(u:unit -> unit -> int, h: unit) : unit = () + + member this.``single argument method group name lookup`` () = + let b = nameof(this.MethodGroup) + Assert.AreEqual("MethodGroup",b) + + member this.``multiple argument method group name lookup`` () = + let b = nameof(this.MethodGroup1 : (float * int64 -> _)) + Assert.AreEqual("MethodGroup1",b) + +type FrameworkMethodTests() = + member this.``library function name`` () = + let b = nameof(List.map) + Assert.AreEqual("map",b) + + member this.``static class function name`` () = + let b = nameof(System.Tuple.Create) + Assert.AreEqual("Create",b) + +type CustomUnionType = + | OptionA + | OptionB of int * string + +type CustomRecordType = + { X: int; Y: int } + +[] type Milliquacks + +type UnionAndRecordNameOfTests() = + + member this.``measure 1`` () = + let b = nameof(Milliquacks) + Assert.AreEqual("Milliquacks",b) + + member this.``record case 1`` () = + let sample = Unchecked.defaultof + let b = nameof(sample.X) + let result = Assert.AreEqual("X",b) + let b = nameof(sample.Y) + result || Assert.AreEqual("Y",b) + + member this.``union case 1`` () = + let b = nameof(OptionA) + Assert.AreEqual("OptionA",b) + + member this.``union case 2`` () = + let b = nameof(OptionB) + Assert.AreEqual("OptionB",b) + +type AttributeNameOfTests() = + + [] + member this.``ok in attribute`` () = + let t = typeof.GetMethod("ok in attribute") + let attrs = t.GetCustomAttributes(typeof, false) + let attr = attrs.[0] :?> ObsoleteAttribute + Assert.AreEqual(attr.Message, "test string") + +type OperatorNameOfTests() = + + member this.``lookup name of typeof operator`` () = + let b = nameof(typeof) + Assert.AreEqual("typeof",b) + + member this.``lookup name of + operator`` () = + let b = nameof(+) + Assert.AreEqual("op_Addition",b) + + member this.``lookup name of |> operator`` () = + let a = nameof(|>) + let result = Assert.AreEqual("op_PipeRight",a) + let b = nameof(op_PipeRight) + result || Assert.AreEqual("op_PipeRight",b) + + member this.``lookup name of nameof operator`` () = + let b = nameof(nameof) + Assert.AreEqual("nameof",b) + +type PatternMatchingOfOperatorNameTests() = + member this.Method1(i:int) = () + + member this.``use it as a match case guard`` () = + match "Method1" with + | x when x = nameof(this.Method1) -> true + | _ -> false + +type NameOfOperatorInQuotations() = + member this.``use it in a quotation`` () = + let q = + <@ + let f(x:int) = nameof x + f 20 + @> + true + +type NameOfOperatorForGenerics() = + member this.``use it in a generic function`` () = + let fullyGeneric x = x + let b = nameof(fullyGeneric) + Assert.AreEqual("fullyGeneric",b) + + member this.``lookup name of a generic class`` () = + let b = nameof System.Collections.Generic.List + Assert.AreEqual("List",b) + +type UserDefinedNameOfTests() = + static member ``user defined nameof should shadow the operator`` () = + let nameof x = "test" + x.ToString() + let y = nameof 1 + Assert.AreEqual("test1",y) + +type Person = + { Name : string + Age : int } + member __.Update(fld : string, value : obj) = + match fld with + | x when x = nameof __.Name -> { __ with Name = string value } + | x when x = nameof __.Age -> { __ with Age = value :?> int } + | _ -> __ + +module Foo = + let nameof = () + let x = name () + +do test "local variable name lookup" (BasicNameOfTests.``local variable name lookup`` ()) +do test "local int function name" (BasicNameOfTests.``local int function name`` ()) +do test "local curried function name" (BasicNameOfTests.``local curried function name`` ()) +do test "local tupled function name" (BasicNameOfTests.``local tupled function name`` ()) +do test "local unit function name" (BasicNameOfTests.``local unit function name`` ()) +do test "local function parameter name" (BasicNameOfTests.``local function parameter name`` ()) +do test "can get name from inside a local function (needs to be let rec)" + (BasicNameOfTests.``can get name from inside a local function (needs to be let rec)`` ()) +do test "can get name from inside static member" (BasicNameOfTests.``can get name from inside static member`` ()) +do test "can get name from inside instance member" ((BasicNameOfTests()).``can get name from inside instance member`` ()) +do test "can get name of instance member" ((BasicNameOfTests()).``can get name of instance member`` ()) +do test "namespace name" (BasicNameOfTests.``namespace name`` ()) +do test "module name" (BasicNameOfTests.``module name`` ()) +do test "exception name" (BasicNameOfTests.``exception name`` ()) +do test "nested type name 1" (BasicNameOfTests.``nested type name 1`` ()) +do test "type name 2" (BasicNameOfTests.``type name 2`` ()) +do test "member function which is defined below" (BasicNameOfTests.``member function which is defined below`` ()) +do test "class member lookup" ((BasicNameOfTests()).``class member lookup`` ()) +do test "static member function name" (BasicNameOfTests.``static member function name`` ()) +do test "static property name" (BasicNameOfTests.``static property name`` ()) +do test "member method starting with get_" (BasicNameOfTests.``member method starting with get_`` ()) +do test "static method starting with get_" (BasicNameOfTests.``static method starting with get_`` ()) +do test "nameof local property with encapsulated name" (BasicNameOfTests.``nameof local property with encapsulated name`` ()) + +do test "single argument method group name lookup" ((MethodGroupNameOfTests()).``single argument method group name lookup`` ()) +do test "multiple argument method group name lookup" ((MethodGroupNameOfTests()).``multiple argument method group name lookup`` ()) + +do test "measure 1" ((UnionAndRecordNameOfTests()).``measure 1`` ()) +do test "record case 1" ((UnionAndRecordNameOfTests()).``record case 1`` ()) +do test "union case 1" ((UnionAndRecordNameOfTests()).``union case 1`` ()) +do test "union case 2" ((UnionAndRecordNameOfTests()).``union case 2`` ()) + +do test "ok in attribute" ((AttributeNameOfTests()).``ok in attribute`` ()) + +do test "lookup name of typeof operator" ((OperatorNameOfTests()).``lookup name of typeof operator`` ()) +do test "lookup name of + operator" ((OperatorNameOfTests()).``lookup name of + operator`` ()) +do test "lookup name of |> operator" ((OperatorNameOfTests()).``lookup name of |> operator`` ()) +do test "lookup name of nameof operator" ((OperatorNameOfTests()).``lookup name of nameof operator`` ()) + +do test "use it as a match case guard" ((PatternMatchingOfOperatorNameTests()).``use it as a match case guard`` ()) + +do test "se it in a quotation" ((NameOfOperatorInQuotations()).``use it in a quotation`` ()) + +do test "use it in a generic function" ((NameOfOperatorForGenerics()).``use it in a generic function`` ()) +do test "lookup name of a generic class" ((NameOfOperatorForGenerics()).``lookup name of a generic class`` ()) + +do test "user defined nameof should shadow the operator"(UserDefinedNameOfTests.``user defined nameof should shadow the operator`` ()) + +#if TESTS_AS_APP +let RUN() = + match !failures with + | [] -> stdout.WriteLine "Test Passed" + | _ -> stdout.WriteLine "Test Failed" +#else +let aa = + match !failures with + | [] -> + stdout.WriteLine "Test Passed" + System.IO.File.WriteAllText("test.ok","ok") + exit 0 + | _ -> + stdout.WriteLine "Test Failed" + exit 1 +#endif + diff --git a/tests/fsharp/core/quotes/test.fsx b/tests/fsharp/core/quotes/test.fsx index 289988569de..8be5e210971 100644 --- a/tests/fsharp/core/quotes/test.fsx +++ b/tests/fsharp/core/quotes/test.fsx @@ -2007,7 +2007,6 @@ module TestQuotationOfCOnstructors = | _ -> false) -#if !FX_RESHAPED_REFLECTION // Also test getting the reflected definition for private members implied by "let f() = ..." bindings let fMethod = (typeof.GetMethod("f", Reflection.BindingFlags.Instance ||| Reflection.BindingFlags.Public ||| Reflection.BindingFlags.NonPublic)) @@ -2020,9 +2019,7 @@ module TestQuotationOfCOnstructors = -> unitVar.Type = typeof | _ -> false) - Expr.TryGetReflectedDefinition fMethod |> printfn "%A" -#endif test "vkjnkvrw0" (match Expr.TryGetReflectedDefinition (typeof.GetConstructors().[0]) with @@ -2312,29 +2309,17 @@ module ReflectedDefinitionOnTypesWithImplicitCodeGen = // This type has an implicit IComparable implementation, it is not accessible as a reflected definition type U = A of int | B of string | C of System.DateTime -#if FX_RESHAPED_REFLECTION - for m in typeof.GetMethods() do -#else for m in typeof.GetMethods(System.Reflection.BindingFlags.DeclaredOnly) do -#endif check "celnwer33" (Quotations.Expr.TryGetReflectedDefinition(m).IsNone) true // This type has some implicit codegen exception X of string * int -#if FX_RESHAPED_REFLECTION - for m in typeof.GetMethods() do -#else for m in typeof.GetMethods(System.Reflection.BindingFlags.DeclaredOnly) do -#endif check "celnwer34" (Quotations.Expr.TryGetReflectedDefinition(m).IsNone) true // This type has an implicit IComparable implementation, it is not accessible as a reflected definition [] type SR = { x:int; y:string; z:System.DateTime } -#if FX_RESHAPED_REFLECTION - for m in typeof.GetMethods() do -#else for m in typeof.GetMethods(System.Reflection.BindingFlags.DeclaredOnly) do -#endif check "celnwer35" (Quotations.Expr.TryGetReflectedDefinition(m).IsNone) true #if !NETCOREAPP @@ -3175,13 +3160,10 @@ module TestMatchBang = | expr -> Error "Delay is incorrect") (Ok ()) - testSimpleMatchBang() - + testSimpleMatchBang() -#if !FX_RESHAPED_REFLECTION module TestAssemblyAttributes = let attributes = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(false) -#endif #if TESTS_AS_APP let RUN() = !failures diff --git a/tests/fsharp/core/samename/tempet.fsproj b/tests/fsharp/core/samename/tempet.fsproj index d6ac10eab9b..20f63eb9cc1 100644 --- a/tests/fsharp/core/samename/tempet.fsproj +++ b/tests/fsharp/core/samename/tempet.fsproj @@ -1,7 +1,7 @@  - netstandard1.6 + netstandard2.0 diff --git a/tests/fsharp/core/subtype/test.fsx b/tests/fsharp/core/subtype/test.fsx index 381e5b9a658..9751d03e6e3 100644 --- a/tests/fsharp/core/subtype/test.fsx +++ b/tests/fsharp/core/subtype/test.fsx @@ -1386,12 +1386,10 @@ module CoercivePipingTest = check "clwcweki" (f8 3) (box 3) check "clwcweki" (f9 3) (box 3) -#if !FX_RESHAPED_REFLECTION // this was the actual repro let f (info: System.Reflection.MethodInfo) = System.Attribute.GetCustomAttribute(info, typeof) :?> ReflectedDefinitionAttribute -#endif module Test_Dev10_Bug_917383 = @@ -1728,7 +1726,6 @@ module InliningOnSubTypes1 = do check "clkewlijwlkw" (f()) (13, 17) -#if !FX_RESHAPED_REFLECTION module StructUnionSingleCase = [] type S = S @@ -1756,7 +1753,6 @@ module StructUnionSingleCase = do check "wekew0ewek5" (typeof.IsValueType) true do check "wekew0ewek5b" (typeof.BaseType) typeof -#endif // See https://github.com/Microsoft/visualfsharp/issues/238 module GenericPropertyConstraintSolvedByRecord = diff --git a/tests/fsharp/single-test.fs b/tests/fsharp/single-test.fs index c89a6f5c2ea..236ef364371 100644 --- a/tests/fsharp/single-test.fs +++ b/tests/fsharp/single-test.fs @@ -5,15 +5,17 @@ open System.IO open System.Diagnostics open NUnit.Framework open TestFramework - +open HandleExpects type Permutation = | FSC_CORECLR + | FSC_CORECLR_BUILDONLY | FSI_CORECLR #if !FSHARP_SUITE_DRIVES_CORECLR_TESTS | FSI_FILE | FSI_STDIN | GENERATED_SIGNATURE + | FSC_BUILDONLY | FSC_OPT_MINUS_DEBUG | FSC_OPT_PLUS_DEBUG | AS_DLL @@ -59,7 +61,6 @@ type ProjectConfiguration = { Optimize:bool } - let replaceTokens tag (replacement:string) (template:string) = template.Replace(tag, replacement) let generateProps testCompilerVersion configuration = @@ -97,7 +98,7 @@ let generateOverrides = // optimize = true or false // configuration = "Release" or "Debug" // -let generateProjectArtifacts (pc:ProjectConfiguration) outputType (targetFramework:string) configuration = +let generateProjectArtifacts (pc:ProjectConfiguration) outputType (targetFramework:string) configuration languageVersion= let fsharpCoreLocation = let compiler = if outputType = OutputType.Script then @@ -106,12 +107,11 @@ let generateProjectArtifacts (pc:ProjectConfiguration) outputType (targetFramewo "FSharp.Core" let targetCore = if targetFramework.StartsWith("netstandard", StringComparison.InvariantCultureIgnoreCase) || targetFramework.StartsWith("netcoreapp", StringComparison.InvariantCultureIgnoreCase) then - "netstandard1.6" + "netstandard2.0" else "net45" (Path.GetFullPath(__SOURCE_DIRECTORY__) + "/../../artifacts/bin/" + compiler + "/" + configuration + "/" + targetCore + "/FSharp.Core.dll") - let computeSourceItems addDirectory addCondition (compileItem:CompileItem) sources = let computeInclude src = let fileName = if addDirectory then Path.Combine(pc.SourceDirectory, src) else src @@ -148,9 +148,9 @@ let generateProjectArtifacts (pc:ProjectConfiguration) outputType (targetFramewo false $(DEBUG) portable + $(LANGUAGEVERSION) $(OPTIMIZE) false - FX_RESHAPED_REFLECTION NETCOREAPP false $(RestoreFromArtifactsPath) @@ -202,12 +202,12 @@ let generateProjectArtifacts (pc:ProjectConfiguration) outputType (targetFramewo |> replaceTokens "$(OPTIMIZE)" optimize |> replaceTokens "$(DEBUG)" debug |> replaceTokens "$(TARGETFRAMEWORK)" targetFramework + |> replaceTokens "$(LANGUAGEVERSION)" languageVersion |> replaceTokens "$(RestoreFromArtifactsPath)" (Path.GetFullPath(__SOURCE_DIRECTORY__) + "/../../artifacts/packages/" + configuration) - generateProjBody let lockObj = obj() -let singleTestBuildAndRunCore cfg copyFiles p = +let singleTestBuildAndRunCore cfg copyFiles p languageVersion = let sources = [] let loadSources = [] let useSources = [] @@ -221,7 +221,7 @@ let singleTestBuildAndRunCore cfg copyFiles p = // compilerType = "coreclr" or "net40" // targetFramework optimize = "net472" OR NETCOREAPP3.0 etc ... // optimize = true or false - let executeSingleTestBuildAndRun outputType compilerType targetFramework optimize = + let executeSingleTestBuildAndRun outputType compilerType targetFramework optimize buildOnly = let mutable result = false let directory = let mutable result = "" @@ -249,6 +249,13 @@ let singleTestBuildAndRunCore cfg copyFiles p = Optimize = optimize } + let findFirstSourceFile (pc:ProjectConfiguration) = + let sources = List.append pc.SourceItems pc.ExtraSourceItems + let found = sources |> List.tryFind(fun source -> File.Exists(Path.Combine(directory, source))) + match found with + | Some p -> Path.Combine(directory, p) + | None -> failwith "Missing SourceFile in test case" + let targetsBody = generateTargets let overridesBody = generateOverrides let targetsFileName = Path.Combine(directory, "Directory.Build.targets") @@ -262,43 +269,51 @@ let singleTestBuildAndRunCore cfg copyFiles p = try File.Delete(Path.Combine(directory, "FSharp.Core.dll")) with _ -> () emitFile targetsFileName targetsBody emitFile overridesFileName overridesBody + let buildOutputFile = Path.Combine(directory, "buildoutput.txt") if outputType = OutputType.Exe then let executeFsc testCompilerVersion targetFramework = let propsBody = generateProps testCompilerVersion cfg.BUILD_CONFIG emitFile propsFileName propsBody - let projectBody = generateProjectArtifacts pc outputType targetFramework cfg.BUILD_CONFIG + let projectBody = generateProjectArtifacts pc outputType targetFramework cfg.BUILD_CONFIG languageVersion emitFile projectFileName projectBody use testOkFile = new FileGuard(Path.Combine(directory, "test.ok")) - exec { cfg with Directory = directory } cfg.DotNetExe (sprintf "run -f %s" targetFramework) - testOkFile.CheckExists() + let cfg = { cfg with Directory = directory } + let result = execBothToOutNoCheck cfg directory buildOutputFile cfg.DotNetExe (sprintf "run -f %s" targetFramework) + if not (buildOnly) then + result |> checkResult + testOkFile.CheckExists() executeFsc compilerType targetFramework + if buildOnly then verifyResults (findFirstSourceFile pc) buildOutputFile else let executeFsi testCompilerVersion targetFramework = let propsBody = generateProps testCompilerVersion cfg.BUILD_CONFIG emitFile propsFileName propsBody - let projectBody = generateProjectArtifacts pc outputType targetFramework cfg.BUILD_CONFIG + let projectBody = generateProjectArtifacts pc outputType targetFramework cfg.BUILD_CONFIG languageVersion emitFile projectFileName projectBody use testOkFile = new FileGuard(Path.Combine(directory, "test.ok")) - exec { cfg with Directory = directory } cfg.DotNetExe "build /t:RunFSharpScript" + let cfg = { cfg with Directory = directory } + execBothToOut cfg directory buildOutputFile cfg.DotNetExe "build /t:RunFSharpScript" testOkFile.CheckExists() executeFsi compilerType targetFramework - result <- true + result <- true finally if result <> false then - Directory.Delete(directory, true) + try Directory.Delete(directory, true) with _ -> () else printfn "Configuration: %s" cfg.Directory printfn "Directory: %s" directory printfn "Filename: %s" projectFileName match p with - | FSC_CORECLR -> executeSingleTestBuildAndRun OutputType.Exe "coreclr" "netcoreapp3.0" true - | FSI_CORECLR -> executeSingleTestBuildAndRun OutputType.Script "coreclr" "netcoreapp3.0" true + | FSC_CORECLR -> executeSingleTestBuildAndRun OutputType.Exe "coreclr" "netcoreapp3.0" true false + | FSC_CORECLR_BUILDONLY -> executeSingleTestBuildAndRun OutputType.Exe "coreclr" "netcoreapp3.0" true true + | FSI_CORECLR -> executeSingleTestBuildAndRun OutputType.Script "coreclr" "netcoreapp3.0" true false #if !FSHARP_SUITE_DRIVES_CORECLR_TESTS - | FSC_OPT_PLUS_DEBUG -> executeSingleTestBuildAndRun OutputType.Exe "net40" "net472" true - | FSC_OPT_MINUS_DEBUG -> executeSingleTestBuildAndRun OutputType.Exe "net40" "net472" false - | FSI_FILE -> executeSingleTestBuildAndRun OutputType.Script "net40" "net472" true + | FSC_BUILDONLY -> executeSingleTestBuildAndRun OutputType.Exe "net40" "net472" false true + | FSC_OPT_PLUS_DEBUG -> executeSingleTestBuildAndRun OutputType.Exe "net40" "net472" true false + | FSC_OPT_MINUS_DEBUG -> executeSingleTestBuildAndRun OutputType.Exe "net40" "net472" false false + | FSI_FILE -> executeSingleTestBuildAndRun OutputType.Script "net40" "net472" true false | FSI_STDIN -> use cleanup = (cleanUpFSharpCore cfg) @@ -339,8 +354,8 @@ let singleTestBuildAndRunCore cfg copyFiles p = let sources = extraSources |> List.filter (fileExists cfg) - fsc cfg "%s --optimize -a -o:test--optimize-lib.dll -g" cfg.fsc_flags sources - fsc cfg "%s --optimize -r:test--optimize-lib.dll -o:test--optimize-client-of-lib.exe -g" cfg.fsc_flags sources + fsc cfg "%s --optimize -a -o:test--optimize-lib.dll -g --langversion:preview " cfg.fsc_flags sources + fsc cfg "%s --optimize -r:test--optimize-lib.dll -o:test--optimize-client-of-lib.exe -g --langversion:preview " cfg.fsc_flags sources peverify cfg "test--optimize-lib.dll" peverify cfg "test--optimize-client-of-lib.exe" @@ -349,21 +364,28 @@ let singleTestBuildAndRunCore cfg copyFiles p = testOkFile.CheckExists() #endif - + let singleTestBuildAndRunAux cfg p = - singleTestBuildAndRunCore cfg "" p + singleTestBuildAndRunCore cfg "" p "latest" let singleTestBuildAndRunWithCopyDlls cfg copyFiles p = - singleTestBuildAndRunCore cfg copyFiles p + singleTestBuildAndRunCore cfg copyFiles p "latest" let singleTestBuildAndRun dir p = let cfg = testConfig dir singleTestBuildAndRunAux cfg p +let singleTestBuildAndRunVersion dir p version = + let cfg = testConfig dir + singleTestBuildAndRunCore cfg "" p version -let singleNegTest (cfg: TestConfig) testname = +let singleVersionedNegTest (cfg: TestConfig) version testname = - let cfg = { cfg with fsc_flags = sprintf "%s --define:NEGATIVE" cfg.fsc_flags } + let cfg = { + cfg with + fsc_flags = sprintf "%s %s --define:NEGATIVE" cfg.fsc_flags (if not (String.IsNullOrEmpty(version)) then "--langversion:" + version else "") + fsi_flags = sprintf "%s %s" cfg.fsi_flags (if not (String.IsNullOrEmpty(version)) then "--langversion:" + version else "") + } // REM == Set baseline (fsc vs vs, in case the vs baseline exists) let VSBSLFILE = @@ -377,7 +399,7 @@ let singleNegTest (cfg: TestConfig) testname = testname + "b.mli"; testname + "b.fsi"; testname + "b.ml"; testname + "b.fs"; ] yield! src |> List.filter (fileExists cfg) - + if fileExists cfg "helloWorldProvider.dll" then yield "-r:helloWorldProvider.dll" @@ -387,7 +409,8 @@ let singleNegTest (cfg: TestConfig) testname = ] if fileExists cfg (testname + "-pre.fs") - then fsc cfg "%s -a -o:%s-pre.dll" cfg.fsc_flags testname [testname + "-pre.fs"] + then + fsc cfg "%s -a -o:%s-pre.dll" cfg.fsc_flags testname [testname + "-pre.fs"] else () if fileExists cfg (testname + "-pre.fsx") then @@ -426,3 +449,5 @@ let singleNegTest (cfg: TestConfig) testname = log "***** %s.err %s.bsl differed: a bug or baseline may need updating" testname testname log "***** %s.vserr %s differed: a bug or baseline may need updating" testname VSBSLFILE failwithf "%s.err %s.bsl differ; %A; %s.vserr %s differ; %A" testname testname l1 testname VSBSLFILE l2 + +let singleNegTest (cfg: TestConfig) testname = singleVersionedNegTest (cfg: TestConfig) "" testname diff --git a/tests/fsharp/test-framework.fs b/tests/fsharp/test-framework.fs index c76d9082897..cb2418f04c6 100644 --- a/tests/fsharp/test-framework.fs +++ b/tests/fsharp/test-framework.fs @@ -170,7 +170,7 @@ let config configurationName envVars = #else let fscArchitecture = "netcoreapp2.1" let fsiArchitecture = "netcoreapp2.1" - let fsharpCoreArchitecture = "netstandard1.6" + let fsharpCoreArchitecture = "netstandard2.0" let fsharpBuildArchitecture = "netcoreapp2.1" let fsharpCompilerInteractiveSettingsArchitecture = "netstandard2.0" #endif @@ -443,7 +443,8 @@ let execAppendIgnoreExitCode cfg stdoutPath stderrPath p = Command.exec cfg.Dire let exec cfg p = Command.exec cfg.Directory cfg.EnvironmentVariables execArgs p >> checkResult let execExpectFail cfg p = Command.exec cfg.Directory cfg.EnvironmentVariables execArgs p >> checkErrorLevel1 let execIn cfg workDir p = Command.exec workDir cfg.EnvironmentVariables execArgs p >> checkResult -let execBothToOut cfg workDir outFile p = Command.exec workDir cfg.EnvironmentVariables { execArgs with Output = OutputAndErrorToSameFile(Overwrite(outFile)) } p >> checkResult +let execBothToOutNoCheck cfg workDir outFile p = Command.exec workDir cfg.EnvironmentVariables { execArgs with Output = OutputAndErrorToSameFile(Overwrite(outFile)) } p +let execBothToOut cfg workDir outFile p = execBothToOutNoCheck cfg workDir outFile p >> checkResult let execAppendOutIgnoreExitCode cfg workDir outFile p = Command.exec workDir cfg.EnvironmentVariables { execArgs with Output = Output(Append(outFile)) } p >> alwaysSuccess let execAppendErrExpectFail cfg errPath p = Command.exec cfg.Directory cfg.EnvironmentVariables { execArgs with Output = Error(Overwrite(errPath)) } p >> checkErrorLevel1 let execStdin cfg l p = Command.exec cfg.Directory cfg.EnvironmentVariables { Output = Inherit; Input = Some(RedirectInput(l)) } p >> checkResult diff --git a/tests/fsharp/tests.fs b/tests/fsharp/tests.fs index c73726a3a8a..da940132179 100644 --- a/tests/fsharp/tests.fs +++ b/tests/fsharp/tests.fs @@ -16,10 +16,12 @@ open NUnit.Framework open TestFramework open Scripting open SingleTest +open HandleExpects #if FSHARP_SUITE_DRIVES_CORECLR_TESTS // Use these lines if you want to test CoreCLR let FSC_BASIC = FSC_CORECLR +let FSC_BUILDONLY = FSC_CORECLR_BUILDONLY let FSI_BASIC = FSI_CORECLR #else let FSC_BASIC = FSC_OPT_PLUS_DEBUG @@ -27,7 +29,7 @@ let FSI_BASIC = FSI_FILE #endif // ^^^^^^^^^^^^ To run these tests in F# Interactive , 'build net40', then send this chunk, then evaluate body of a test ^^^^^^^^^^^^ -module CoreTests = +module CoreTests = // These tests are enabled for .NET Framework and .NET Core [] let ``access-FSC_BASIC``() = singleTestBuildAndRun "core/access" FSC_BASIC @@ -1678,7 +1680,7 @@ module CoreTests = csc cfg """/nologo /r:"%s" /r:lib--optimize.dll /out:test--optimize.exe""" cfg.FSCOREDLLPATH ["test.cs"] - let dicases = ["flag_deterministic_init1.fs"; "lib_deterministic_init1.fs"; "flag_deterministic_init2.fs"; "lib_deterministic_init2.fs"; "flag_deterministic_init3.fs"; "lib_deterministic_init3.fs"; "flag_deterministic_init4.fs"; "lib_deterministic_init4.fs"; "flag_deterministic_init5.fs"; "lib_deterministic_init5.fs"; "flag_deterministic_init6.fs"; "lib_deterministic_init6.fs"; "flag_deterministic_init7.fs"; "lib_deterministic_init7.fs"; "flag_deterministic_init8.fs"; "lib_deterministic_init8.fs"; "flag_deterministic_init9.fs"; "lib_deterministic_init9.fs"; "flag_deterministic_init10.fs"; "lib_deterministic_init10.fs"; "flag_deterministic_init11.fs"; "lib_deterministic_init11.fs"; "flag_deterministic_init12.fs"; "lib_deterministic_init12.fs"; "flag_deterministic_init13.fs"; "lib_deterministic_init13.fs"; "flag_deterministic_init14.fs"; "lib_deterministic_init14.fs"; "flag_deterministic_init15.fs"; "lib_deterministic_init15.fs"; "flag_deterministic_init16.fs"; "lib_deterministic_init16.fs"; "flag_deterministic_init17.fs"; "lib_deterministic_init17.fs"; "flag_deterministic_init18.fs"; "lib_deterministic_init18.fs"; "flag_deterministic_init19.fs"; "lib_deterministic_init19.fs"; "flag_deterministic_init20.fs"; "lib_deterministic_init20.fs"; "flag_deterministic_init21.fs"; "lib_deterministic_init21.fs"; "flag_deterministic_init22.fs"; "lib_deterministic_init22.fs"; "flag_deterministic_init23.fs"; "lib_deterministic_init23.fs"; "flag_deterministic_init24.fs"; "lib_deterministic_init24.fs"; "flag_deterministic_init25.fs"; "lib_deterministic_init25.fs"; "flag_deterministic_init26.fs"; "lib_deterministic_init26.fs"; "flag_deterministic_init27.fs"; "lib_deterministic_init27.fs"; "flag_deterministic_init28.fs"; "lib_deterministic_init28.fs"; "flag_deterministic_init29.fs"; "lib_deterministic_init29.fs"; "flag_deterministic_init30.fs"; "lib_deterministic_init30.fs"; "flag_deterministic_init31.fs"; "lib_deterministic_init31.fs"; "flag_deterministic_init32.fs"; "lib_deterministic_init32.fs"; "flag_deterministic_init33.fs"; "lib_deterministic_init33.fs"; "flag_deterministic_init34.fs"; "lib_deterministic_init34.fs"; "flag_deterministic_init35.fs"; "lib_deterministic_init35.fs"; "flag_deterministic_init36.fs"; "lib_deterministic_init36.fs"; "flag_deterministic_init37.fs"; "lib_deterministic_init37.fs"; "flag_deterministic_init38.fs"; "lib_deterministic_init38.fs"; "flag_deterministic_init39.fs"; "lib_deterministic_init39.fs"; "flag_deterministic_init40.fs"; "lib_deterministic_init40.fs"; "flag_deterministic_init41.fs"; "lib_deterministic_init41.fs"; "flag_deterministic_init42.fs"; "lib_deterministic_init42.fs"; "flag_deterministic_init43.fs"; "lib_deterministic_init43.fs"; "flag_deterministic_init44.fs"; "lib_deterministic_init44.fs"; "flag_deterministic_init45.fs"; "lib_deterministic_init45.fs"; "flag_deterministic_init46.fs"; "lib_deterministic_init46.fs"; "flag_deterministic_init47.fs"; "lib_deterministic_init47.fs"; "flag_deterministic_init48.fs"; "lib_deterministic_init48.fs"; "flag_deterministic_init49.fs"; "lib_deterministic_init49.fs"; "flag_deterministic_init50.fs"; "lib_deterministic_init50.fs"; "flag_deterministic_init51.fs"; "lib_deterministic_init51.fs"; "flag_deterministic_init52.fs"; "lib_deterministic_init52.fs"; "flag_deterministic_init53.fs"; "lib_deterministic_init53.fs"; "flag_deterministic_init54.fs"; "lib_deterministic_init54.fs"; "flag_deterministic_init55.fs"; "lib_deterministic_init55.fs"; "flag_deterministic_init56.fs"; "lib_deterministic_init56.fs"; "flag_deterministic_init57.fs"; "lib_deterministic_init57.fs"; "flag_deterministic_init58.fs"; "lib_deterministic_init58.fs"; "flag_deterministic_init59.fs"; "lib_deterministic_init59.fs"; "flag_deterministic_init60.fs"; "lib_deterministic_init60.fs"; "flag_deterministic_init61.fs"; "lib_deterministic_init61.fs"; "flag_deterministic_init62.fs"; "lib_deterministic_init62.fs"; "flag_deterministic_init63.fs"; "lib_deterministic_init63.fs"; "flag_deterministic_init64.fs"; "lib_deterministic_init64.fs"; "flag_deterministic_init65.fs"; "lib_deterministic_init65.fs"; "flag_deterministic_init66.fs"; "lib_deterministic_init66.fs"; "flag_deterministic_init67.fs"; "lib_deterministic_init67.fs"; "flag_deterministic_init68.fs"; "lib_deterministic_init68.fs"; "flag_deterministic_init69.fs"; "lib_deterministic_init69.fs"; "flag_deterministic_init70.fs"; "lib_deterministic_init70.fs"; "flag_deterministic_init71.fs"; "lib_deterministic_init71.fs"; "flag_deterministic_init72.fs"; "lib_deterministic_init72.fs"; "flag_deterministic_init73.fs"; "lib_deterministic_init73.fs"; "flag_deterministic_init74.fs"; "lib_deterministic_init74.fs"; "flag_deterministic_init75.fs"; "lib_deterministic_init75.fs"; "flag_deterministic_init76.fs"; "lib_deterministic_init76.fs"; "flag_deterministic_init77.fs"; "lib_deterministic_init77.fs"; "flag_deterministic_init78.fs"; "lib_deterministic_init78.fs"; "flag_deterministic_init79.fs"; "lib_deterministic_init79.fs"; "flag_deterministic_init80.fs"; "lib_deterministic_init80.fs"; "flag_deterministic_init81.fs"; "lib_deterministic_init81.fs"; "flag_deterministic_init82.fs"; "lib_deterministic_init82.fs"; "flag_deterministic_init83.fs"; "lib_deterministic_init83.fs"; "flag_deterministic_init84.fs"; "lib_deterministic_init84.fs"; "flag_deterministic_init85.fs"; "lib_deterministic_init85.fs"] + let dicases = ["flag_deterministic_init1.fs"; "lib_deterministic_init1.fs"; "flag_deterministic_init2.fs"; "lib_deterministic_init2.fs"; "flag_deterministic_init3.fs"; "lib_deterministic_init3.fs"; "flag_deterministic_init4.fs"; "lib_deterministic_init4.fs"; "flag_deterministic_init5.fs"; "lib_deterministic_init5.fs"; "flag_deterministic_init6.fs"; "lib_deterministic_init6.fs"; "flag_deterministic_init7.fs"; "lib_deterministic_init7.fs"; "flag_deterministic_init8.fs"; "lib_deterministic_init8.fs"; "flag_deterministic_init9.fs"; "lib_deterministic_init9.fs"; "flag_deterministic_init10.fs"; "lib_deterministic_init10.fs"; "flag_deterministic_init11.fs"; "lib_deterministic_init11.fs"; "flag_deterministic_init12.fs"; "lib_deterministic_init12.fs"; "flag_deterministic_init13.fs"; "lib_deterministic_init13.fs"; "flag_deterministic_init14.fs"; "lib_deterministic_init14.fs"; "flag_deterministic_init15.fs"; "lib_deterministic_init15.fs"; "flag_deterministic_init16.fs"; "lib_deterministic_init16.fs"; "flag_deterministic_init17.fs"; "lib_deterministic_init17.fs"; "flag_deterministic_init18.fs"; "lib_deterministic_init18.fs"; "flag_deterministic_init19.fs"; "lib_deterministic_init19.fs"; "flag_deterministic_init20.fs"; "lib_deterministic_init20.fs"; "flag_deterministic_init21.fs"; "lib_deterministic_init21.fs"; "flag_deterministic_init22.fs"; "lib_deterministic_init22.fs"; "flag_deterministic_init23.fs"; "lib_deterministic_init23.fs"; "flag_deterministic_init24.fs"; "lib_deterministic_init24.fs"; "flag_deterministic_init25.fs"; "lib_deterministic_init25.fs"; "flag_deterministic_init26.fs"; "lib_deterministic_init26.fs"; "flag_deterministic_init27.fs"; "lib_deterministic_init27.fs"; "flag_deterministic_init28.fs"; "lib_deterministic_init28.fs"; "flag_deterministic_init29.fs"; "lib_deterministic_init29.fs"; "flag_deterministic_init30.fs"; "lib_deterministic_init30.fs"; "flag_deterministic_init31.fs"; "lib_deterministic_init31.fs"; "flag_deterministic_init32.fs"; "lib_deterministic_init32.fs"; "flag_deterministic_init33.fs"; "lib_deterministic_init33.fs"; "flag_deterministic_init34.fs"; "lib_deterministic_init34.fs"; "flag_deterministic_init35.fs"; "lib_deterministic_init35.fs"; "flag_deterministic_init36.fs"; "lib_deterministic_init36.fs"; "flag_deterministic_init37.fs"; "lib_deterministic_init37.fs"; "flag_deterministic_init38.fs"; "lib_deterministic_init38.fs"; "flag_deterministic_init39.fs"; "lib_deterministic_init39.fs"; "flag_deterministic_init40.fs"; "lib_deterministic_init40.fs"; "flag_deterministic_init41.fs"; "lib_deterministic_init41.fs"; "flag_deterministic_init42.fs"; "lib_deterministic_init42.fs"; "flag_deterministic_init43.fs"; "lib_deterministic_init43.fs"; "flag_deterministic_init44.fs"; "lib_deterministic_init44.fs"; "flag_deterministic_init45.fs"; "lib_deterministic_init45.fs"; "flag_deterministic_init46.fs"; "lib_deterministic_init46.fs"; "flag_deterministic_init47.fs"; "lib_deterministic_init47.fs"; "flag_deterministic_init48.fs"; "lib_deterministic_init48.fs"; "flag_deterministic_init49.fs"; "lib_deterministic_init49.fs"; "flag_deterministic_init50.fs"; "lib_deterministic_init50.fs"; "flag_deterministic_init51.fs"; "lib_deterministic_init51.fs"; "flag_deterministic_init52.fs"; "lib_deterministic_init52.fs"; "flag_deterministic_init53.fs"; "lib_deterministic_init53.fs"; "flag_deterministic_init54.fs"; "lib_deterministic_init54.fs"; "flag_deterministic_init55.fs"; "lib_deterministic_init55.fs"; "flag_deterministic_init56.fs"; "lib_deterministic_init56.fs"; "flag_deterministic_init57.fs"; "lib_deterministic_init57.fs"; "flag_deterministic_init58.fs"; "lib_deterministic_init58.fs"; "flag_deterministic_init59.fs"; "lib_deterministic_init59.fs"; "flag_deterministic_init60.fs"; "lib_deterministic_init60.fs"; "flag_deterministic_init61.fs"; "lib_deterministic_init61.fs"; "flag_deterministic_init62.fs"; "lib_deterministic_init62.fs"; "flag_deterministic_init63.fs"; "lib_deterministic_init63.fs"; "flag_deterministic_init64.fs"; "lib_deterministic_init64.fs"; "flag_deterministic_init65.fs"; "lib_deterministic_init65.fs"; "flag_deterministic_init66.fs"; "lib_deterministic_init66.fs"; "flag_deterministic_init67.fs"; "lib_deterministic_init67.fs"; "flag_deterministic_init68.fs"; "lib_deterministic_init68.fs"; "flag_deterministic_init69.fs"; "lib_deterministic_init69.fs"; "flag_deterministic_init70.fs"; "lib_deterministic_init70.fs"; "flag_deterministic_init71.fs"; "lib_deterministic_init71.fs"; "flag_deterministic_init72.fs"; "lib_deterministic_init72.fs"; "flag_deterministic_init73.fs"; "lib_deterministic_init73.fs"; "flag_deterministic_init74.fs"; "lib_deterministic_init74.fs"; "flag_deterministic_init75.fs"; "lib_deterministic_init75.fs"; "flag_deterministic_init76.fs"; "lib_deterministic_init76.fs"; "flag_deterministic_init77.fs"; "lib_deterministic_init77.fs"; "flag_deterministic_init78.fs"; "lib_deterministic_init78.fs"; "flag_deterministic_init79.fs"; "lib_deterministic_init79.fs"; "flag_deterministic_init80.fs"; "lib_deterministic_init80.fs"; "flag_deterministic_init81.fs"; "lib_deterministic_init81.fs"; "flag_deterministic_init82.fs"; "lib_deterministic_init82.fs"; "flag_deterministic_init83.fs"; "lib_deterministic_init83.fs"; "flag_deterministic_init84.fs"; "lib_deterministic_init84.fs"; "flag_deterministic_init85.fs"; "lib_deterministic_init85.fs"] fsc cfg "%s --optimize- -o test_deterministic_init.exe" cfg.fsc_flags (dicases @ ["test_deterministic_init.fs"]) @@ -1763,7 +1765,7 @@ module CoreTests = exec cfg ("." ++ "test.exe") "" testOkFile.CheckExists() - + [] let verify () = let cfg = testConfig "core/verify" @@ -1781,6 +1783,31 @@ module CoreTests = peverifyWithArgs cfg "/nologo" "xmlverify.exe" #endif +module VersionTests = + [] + let ``member-selfidentifier-version4.6``() = singleTestBuildAndRunVersion "core/members/self-identifier/version46" FSC_BUILDONLY "4.6" + + [] + let ``member-selfidentifier-version4.7``() = singleTestBuildAndRun "core/members/self-identifier/version47" FSC_BUILDONLY + + [] + let ``indent-version4.6``() = singleTestBuildAndRunVersion "core/indent/version46" FSC_BUILDONLY "4.6" + + [] + let ``indent-version4.7``() = singleTestBuildAndRun "core/indent/version47" FSC_BUILDONLY + + [] + let ``nameof-version4.6``() = singleTestBuildAndRunVersion "core/nameof/version46" FSC_BUILDONLY "4.6" + + [] + let ``nameof-versionpreview``() = singleTestBuildAndRunVersion "core/nameof/preview" FSC_BUILDONLY "preview" + + [] + let ``nameof-execute``() = singleTestBuildAndRunVersion "core/nameof/preview" FSC_BASIC "preview" + + [] + let ``nameof-fsi``() = singleTestBuildAndRunVersion "core/nameof/preview" FSI_BASIC "preview" + #if !FSHARP_SUITE_DRIVES_CORECLR_TESTS module ToolsTests = @@ -1790,7 +1817,7 @@ module ToolsTests = let cfg = testConfig "tools/bundle" fsc cfg "%s --progress --standalone -o:test-one-fsharp-module.exe -g" cfg.fsc_flags ["test-one-fsharp-module.fs"] - + peverify cfg "test-one-fsharp-module.exe" fsc cfg "%s -a -o:test_two_fsharp_modules_module_1.dll -g" cfg.fsc_flags ["test_two_fsharp_modules_module_1.fs"] @@ -2069,10 +2096,8 @@ module TypecheckTests = let cfg = testConfig "typecheck/full-rank-arrays" SingleTest.singleTestBuildAndRunWithCopyDlls cfg "full-rank-arrays.dll" FSC_BASIC -#if !FX_NO_CONVERTER [] let misc () = singleTestBuildAndRun "typecheck/misc" FSC_BASIC -#endif #if !FSHARP_SUITE_DRIVES_CORECLR_TESTS @@ -2336,10 +2361,21 @@ module TypecheckTests = [] let ``type check neg23`` () = singleNegTest (testConfig "typecheck/sigs") "neg23" - [] - let ``type check neg24`` () = singleNegTest (testConfig "typecheck/sigs") "neg24" + [] + let ``type check neg24 version 4.6`` () = + let cfg = testConfig "typecheck/sigs/version46" + // For some reason this warning is off by default in the test framework but in this case we are testing for it + let cfg = { cfg with fsc_flags = cfg.fsc_flags.Replace("--nowarn:20", "") } + singleVersionedNegTest cfg "4.6" "neg24" [] + let ``type check neg24 version 4.7`` () = + let cfg = testConfig "typecheck/sigs/version47" + // For some reason this warning is off by default in the test framework but in this case we are testing for it + let cfg = { cfg with fsc_flags = cfg.fsc_flags.Replace("--nowarn:20", "") } + singleVersionedNegTest cfg "preview" "neg24" + + [] let ``type check neg25`` () = singleNegTest (testConfig "typecheck/sigs") "neg25" [] diff --git a/tests/fsharp/typecheck/sigs/neg24.bsl b/tests/fsharp/typecheck/sigs/version46/neg24.bsl similarity index 99% rename from tests/fsharp/typecheck/sigs/neg24.bsl rename to tests/fsharp/typecheck/sigs/version46/neg24.bsl index b782269bb54..96a64e8c88f 100644 --- a/tests/fsharp/typecheck/sigs/neg24.bsl +++ b/tests/fsharp/typecheck/sigs/version46/neg24.bsl @@ -27,4 +27,4 @@ neg24.fs(62,31,62,41): typecheck error FS0816: One or more of the overloads of t neg24.fs(64,44,64,48): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. -neg24.fs(70,15,70,18): typecheck error FS0495: The member or object constructor 'M' has no argument or settable return property 'qez'. The required signature is member C.M : abc:int * def:string -> int. +neg24.fs(70,15,70,18): typecheck error FS0495: The member or object constructor 'M' has no argument or settable return property 'qez'. The required signature is member C.M : abc:int * def:string -> int. \ No newline at end of file diff --git a/tests/fsharp/typecheck/sigs/neg24.fs b/tests/fsharp/typecheck/sigs/version46/neg24.fs similarity index 99% rename from tests/fsharp/typecheck/sigs/neg24.fs rename to tests/fsharp/typecheck/sigs/version46/neg24.fs index 22a8f4df45f..745cb52fffc 100644 --- a/tests/fsharp/typecheck/sigs/neg24.fs +++ b/tests/fsharp/typecheck/sigs/version46/neg24.fs @@ -68,4 +68,3 @@ type C() = // Check that the error for a named argument/setter that does not exist is located in a good place let _ = C().M(qez=3) - diff --git a/tests/fsharp/typecheck/sigs/version47/neg24.bsl b/tests/fsharp/typecheck/sigs/version47/neg24.bsl new file mode 100644 index 00000000000..f276c01968b --- /dev/null +++ b/tests/fsharp/typecheck/sigs/version47/neg24.bsl @@ -0,0 +1,44 @@ + +neg24.fs(53,24,53,30): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. + +neg24.fs(55,31,55,37): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. + +neg24.fs(57,38,57,42): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. + +neg24.fs(60,24,60,34): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. + +neg24.fs(62,31,62,41): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. + +neg24.fs(64,44,64,48): typecheck error FS0816: One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. + +neg24.fs(70,15,70,18): typecheck error FS0495: The member or object constructor 'M' has no argument or settable return property 'qez'. The required signature is member C.M : abc:int * def:string -> int. + +neg24.fs(300,29,300,30): typecheck error FS0020: The result of this expression has type 'int' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. + +neg24.fs(301,17,301,18): typecheck error FS0020: The result of this expression has type 'int' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. + +neg24.fs(302,33,302,34): typecheck error FS0001: All elements of a list must be of the same type as the first element, which here is 'unit'. This element has type 'int'. + +neg24.fs(302,36,302,37): typecheck error FS0001: All elements of a list must be of the same type as the first element, which here is 'unit'. This element has type 'int'. + +neg24.fs(304,11,305,32): typecheck error FS0193: Type constraint mismatch. The type + 'int' +is not compatible with type + 'unit' + + +neg24.fs(308,30,308,31): typecheck error FS0020: The result of this expression has type 'int' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. + +neg24.fs(309,31,309,32): typecheck error FS0001: This 'if' expression is missing an 'else' branch. Because 'if' is an expression, and not a statement, add an 'else' branch which also returns a value of type 'int'. + +neg24.fs(312,33,312,34): typecheck error FS0020: The result of this expression has type 'int' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. + +neg24.fs(313,38,313,39): typecheck error FS0020: The result of this expression has type 'int' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. + +neg24.fs(313,47,313,48): typecheck error FS0020: The result of this expression has type 'int' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. + +neg24.fs(331,24,331,25): typecheck error FS0001: The 'if' expression needs to have type 'obj' to satisfy context type requirements. It currently has type 'int'. + +neg24.fs(337,30,337,31): typecheck error FS0001: The 'if' expression needs to have type 'obj' to satisfy context type requirements. It currently has type 'int'. + +neg24.fs(337,37,337,42): typecheck error FS0020: The result of this expression has type 'obj' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. diff --git a/tests/fsharp/typecheck/sigs/version47/neg24.fs b/tests/fsharp/typecheck/sigs/version47/neg24.fs new file mode 100644 index 00000000000..6e1e072cf1a --- /dev/null +++ b/tests/fsharp/typecheck/sigs/version47/neg24.fs @@ -0,0 +1,339 @@ +module Test +open Microsoft.FSharp.Quotations + + +let test2 (v : Expr<'a> -> Expr<'b>) = <@ fun (i: 'a) -> %v <@i@> @> + +let test (v : 'a -> Expr<'b>) = <@ fun (i: 'a) -> %(v i) @> + + +module OldNegative = + let v1 = [ if true then 1 else 2 ] // no longer an error or warning + let v2 = [ if true then () else () ] // no longer an error or warning + let v6 = [ if true then () ] // no longer an error or warning + let a1 = [| if true then 1 else 2 |] // no longer an error or warning + let a2 = [| if true then () else () |] // no longer an error or warning + let a6 = [| if true then () |] // no longer an error or warning + let s3 = seq { (if true then 1 else 2) } // no longer an error or warning + +// expect no warning +module Positive = + let v3 = [ (if true then 1 else 2) ] + let v4 = [ if true then yield 1 else yield 2 ] + let v5 = [ if true then yield 1 ] + let a3 = [| (if true then 1 else 2) |] + let a4 = [| if true then yield 1 else yield 2 |] + let a5 = [| if true then yield 1 |] + let s2 = seq { if true then () else () } + let s6 = seq { if true then () } + let s4 = seq { if true then yield 1 else yield 2 } + let s5 = seq { if true then yield 1 } + + +module BadCurriedExtensionMember = + type C() = + member x.P = 1 + + module M1 = + type C with + member x.M1 a b = a + b + member x.M2 (a,b) c = a + b + c + + module M2 = + type C with + member x.M1 a b = a + b + member x.M2 (a,b) c = a + b + c + + open M1 + open M2 + + let c = C() + + // negative test - error expected here + let x1 : int = c.M1 3 4 + // negative test - error expected here + let x2 : int -> int = c.M1 3 + // negative test - error expected here + let x3 : int -> int -> int = c.M1 + + // negative test - error expected here + let y1 : int = c.M2 (3,4) 4 + // negative test - error expected here + let y2 : int -> int = c.M2 (3,4) + // negative test - error expected here + let y3 : int * int -> int -> int = c.M2 + +type C() = + member x.M(abc:int,def:string) = abc + def.Length + +// Check that the error for a named argument/setter that does not exist is located in a good place +let _ = C().M(qez=3) + +module ListPositive2 = + // In this example, implicit yield is enabled becaue there is no explicit 'yield' + let v3 = + [ if true then 1 else 2 ] + + // In this example, implicit yield is enabled because there is no explicit 'yield'. + // When using implicit yield, statements are detected via a type-directed rule which tries + // checks the statement without an expected type and then checks if the type of the resulting + // expression has type 'unit'. + let v3a = + [ printfn "hello" + if true then 1 else 2 // implicit yield enabled + ] + + // In this example, implicit yield is enabled even though there is an explicit 'yield!' + // This is because using 'yield!' is the only way to yield anything + let v3b = + [ printfn "hello" + if true then 1 else 2 + yield! [] ] + + // This example checks subsumption is permitted when using implicit yield + let v3c : obj list = + [ printfn "hello" + if true then 1 else obj() ] + + // Another check that implicit yield is enabled , even though there is a `yield!` + let v3d = + [ if true then 1 else 2 + yield! [] ] + + // Another check that implicit yield is enabled , even though there is a `yield!` + let v3e = + [ yield! [] + if true then 1 else 2 + ] + + // Another check that implicit yield is enabled + let v3f = + [ if true then + printfn "hello" + 1 + else + 2 ] + + // Another check that implicit yield is enabled + let v3g = + [ if true then + 1 + else + printfn "hello" + 2 ] + + // Another check that implicit yield is enabled + let v3h = + [ for i in 1 .. 10 do + 10 + printfn "hello" ] + + // Another check that implicit yield is enabled + let v5 = + [ if true then 1 ] + + // Another check that implicit yield is enabled + let v5a = + [ printfn "hello"; + if true then 1 ] + + // Another check that implicit yield is enabled + let v5b = + [ if true then + printfn "hello" + 1 + ] + +module ArrayPositive2 = + let a3 = + [| (if true then 1 else 2) |] // simple single element sequence + + let a5 = + [| if true then 1 |] + + let l10 = + [ printfn "hello"; yield 1; yield 2 ] // expect ok - the printfn has type unit and is not interpreted as a yield + + // simple case of explicit yield + let l12 : int list = + [ printfn "hello" + if true then yield 1 else yield 2 ] + + // check subsumption is allowed when using explicit yield + let l13 : obj list = + [ printfn "hello" + if true then yield 1 else yield 2 ] + + // check subsumption is allowed when using explicit yield + let l14 : obj list = + [ printfn "hello" + if true then yield 1 ] + +module SeqPositive2 = + let s2 = + seq { if true then () else () } + + let s6 = + seq { if true then () } + + let s4 = + seq { if true then 1 else 2 } + + let s6 = + seq { if true then 1 } + + let s7 = + seq { match 1 with 1 -> 4 | 2 -> 5 | 3 -> 6 | _ -> () } + +module BuilderPositive2 = + type L<'T> = { Make: (unit -> 'T list) } + let L f = { Make = f } + + type ListBuilder() = + member __.Combine(x1: L<'T>, x2: L<'T>) = L(fun () -> x1.Make() @ x2.Make()) + member __.Delay(f: unit -> L<'T>) = L(fun () -> f().Make()) + member __.Zero() = L(fun () -> []) + member __.Yield(a: 'T) = L(fun () -> [a]) + member __.YieldFrom(x: L<'T>) = x + + let list = ListBuilder() + let empty<'T> : L<'T> = list.Zero() + + let v3 = + list { if true then 1 else 2 } // implicit yield enabled + + let v3y = + list { if true then yield 1 else yield 2 } // equivalent explicit yield + + let v3a = + list { + printfn "hello" + if true then 1 else 2 // implicit yield enabled + } + + let v3ay = + list { + printfn "hello" + if true then yield 1 else yield 2 // equivalent explicit yield + } + + let v3b = + list { + printfn "hello" + if true then 1 else 2 // implicit yield, even though there is a `yield!` + yield! empty + } + + let v3bc = + list { + printfn "hello" + if true then yield 1 else yield 2 // equivalent explicit yield + yield! empty + } + + + + + + + + + + + + + + let v3d = + list { + if true then 1 else 2 // implicit yield enabled , even though there is a `yield!` + yield! empty + } + + let v3dy = + list { + if true then yield 1 else yield 2 // equivalent explicit yield + yield! empty + } + + let v3e = + list { + yield! empty + if true then 1 else 2 // implicit yield enabled , even though there is a `yield!` + } + + let v3f = + list { + if true then + printfn "hello" + 1 + else 2 + } + + let v3g = + list { + if true then + 1 + else + printfn "hello" + 2 + } + + let v5 = + list { + if true then 1 + } + + let v5a = + list { + printfn "hello"; + if true then 1 + } + + let v5b = + list { + if true then + printfn "hello" + 1 + } + +module ListNegative2 = + let v4 = [ if true then 1 else yield 2 ] // expect warning about "1" being ignored. There is a 'yield' so statements are statements. + let l11 = [ 4; yield 1; yield 2 ] // expect warning about "1" being ignored. There is a 'yield' so statements are statements. + let l9 = [ printfn "hello"; 1; 2 ] // Note, this is interpreted as a "SimpleSemicolonSequence", so we get "All elements of a list must be of the same type as the first element, which here is 'unit'. This element..." + let v3a : unit list = + [ printfn "hello" + if true then 1 else 2 ] + +module ArrayNegative2 = + let a4 = [| if true then 1 else yield 2 |] // expect warning about "1" being ignored. There is a 'yield' so statements are statements. + let a4 = [| (if true then 1) |] + +module SeqNegative2 = + let s5 = seq { if true then 1 else yield 2 } // expect warning about "1" being ignored. There is a 'yield' so statements are statements. + let s8 = seq { match 1 with 1 -> 4 | 2 -> 5 | 3 -> yield 6 | _ -> () } // expect warning about "4" being ignored. There is a 'yield' so statements are statements. + +module BuilderNegative2 = + type L<'T> = { Make: (unit -> 'T list) } + let L f = { Make = f } + + type ListBuilder() = + member __.Combine(x1: L<'T>, x2: L<'T>) = L(fun () -> x1.Make() @ x2.Make()) + member __.Delay(f: unit -> L<'T>) = L(fun () -> f().Make()) + member __.Zero() = L(fun () -> []) + member __.Yield(a: 'T) = L(fun () -> [a]) + member __.YieldFrom(x: L<'T>) = x + + let list = ListBuilder() + + let v3c : L = + list { + printfn "hello" + if true then 1 else obj() + } + + let v3c : L = + list { + printfn "hello" + if true then yield 1 else obj() + } + diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/help/help40.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsc/help/help40.437.1033.bsl index 9309a03e5e6..5c4045831d7 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsc/help/help40.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/help/help40.437.1033.bsl @@ -98,6 +98,10 @@ Copyright (c) Microsoft Corporation. All Rights Reserved. - LANGUAGE - +--langversion:{?|version|latest|preview} Display the allowed values for + language version, specify language + version such as 'latest' or + 'preview' --checked[+|-] Generate overflow checks --define: Define conditional compilation symbols (Short form: -d) diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/badlangversion.fsx b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/badlangversion.fsx new file mode 100644 index 00000000000..b41237cd0b3 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/badlangversion.fsx @@ -0,0 +1,5 @@ +// #NoMT #CompilerOptions #RequiresENU +// Unrecognized value '4.5' for --langversion use --langversion:? for complete list +// +#light +exit 0 diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/dummy.fsx b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/dummy.fsx new file mode 100644 index 00000000000..c5ecbb36434 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/dummy.fsx @@ -0,0 +1,3 @@ +// #NoMT #CompilerOptions #RequiresENU +#light +exit 0 diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/env.lst b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/env.lst new file mode 100644 index 00000000000..bba306f616a --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/env.lst @@ -0,0 +1,4 @@ +# ReqENU means that the test is non-localized + +ReqENU SOURCE=dummy.fsx COMPILE_ONLY=1 PRECMD="\$FSC_PIPE >langversionhelp.txt --langversion:? 2>&1" POSTCMD="\$FSI_PIPE --nologo --quiet --exec ..\\..\\..\\comparer.fsx langversionhelp.txt langversionhelp.437.1033.bsl" # --langversion:? +ReqENU SOURCE=badlangversion.fsx SCFLAGS=" --langversion:4.5" # --langversion:4.5 diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/langversionhelp.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/langversionhelp.437.1033.bsl new file mode 100644 index 00000000000..83fd0bfa996 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/langversion/langversionhelp.437.1033.bsl @@ -0,0 +1,7 @@ +Supported language versions: +preview +default +latest +latestmajor +4.6 +4.7 (Default) \ No newline at end of file diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl index d19a024e300..8a9d6d418ab 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/exename/help40.437.1033.bsl @@ -49,6 +49,10 @@ Usage: fsharpi [script.fsx []] - LANGUAGE - +--langversion:{?|version|latest|preview} Display the allowed values for + language version, specify language + version such as 'latest' or + 'preview' --checked[+|-] Generate overflow checks --define: Define conditional compilation symbols (Short form: -d) diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl index 242cb274d2d..041e86b8287 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40-nologo.437.1033.bsl @@ -49,6 +49,10 @@ Usage: fsi.exe [script.fsx []] - LANGUAGE - +--langversion:{?|version|latest|preview} Display the allowed values for + language version, specify language + version such as 'latest' or + 'preview' --checked[+|-] Generate overflow checks --define: Define conditional compilation symbols (Short form: -d) diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl index 34d28e5f70b..24fbfc4de40 100644 --- a/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/help/help40.437.1033.bsl @@ -51,6 +51,10 @@ Usage: fsi.exe [script.fsx []] - LANGUAGE - +--langversion:{?|version|latest|preview} Display the allowed values for + language version, specify language + version such as 'latest' or + 'preview' --checked[+|-] Generate overflow checks --define: Define conditional compilation symbols (Short form: -d) diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/badlangversion.fsx b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/badlangversion.fsx new file mode 100644 index 00000000000..b41237cd0b3 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/badlangversion.fsx @@ -0,0 +1,5 @@ +// #NoMT #CompilerOptions #RequiresENU +// Unrecognized value '4.5' for --langversion use --langversion:? for complete list +// +#light +exit 0 diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/dummy.fsx b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/dummy.fsx new file mode 100644 index 00000000000..c5ecbb36434 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/dummy.fsx @@ -0,0 +1,3 @@ +// #NoMT #CompilerOptions #RequiresENU +#light +exit 0 diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/env.lst b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/env.lst new file mode 100644 index 00000000000..fa31a7b0e41 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/env.lst @@ -0,0 +1,4 @@ +# ReqENU means that the test is non-localized + +ReqENU SOURCE=dummy.fsx COMPILE_ONLY=1 SCFLAGS="--nologo" FSIMODE=EXEC PRECMD="\$FSI_PIPE --langversion:? >langversionhelp.txt 2>&1" POSTCMD="\$FSI_PIPE --nologo --quiet --exec ..\\..\\..\\comparer.fsx langversionhelp.txt langversionhelp.437.1033.bsl" # --langversion:? +ReqENU SOURCE=badlangversion.fsx SCFLAGS=" --langversion:4.5" # --langversion:4.5 diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/langversionhelp.437.1033.bsl b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/langversionhelp.437.1033.bsl new file mode 100644 index 00000000000..83fd0bfa996 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/langversion/langversionhelp.437.1033.bsl @@ -0,0 +1,7 @@ +Supported language versions: +preview +default +latest +latestmajor +4.6 +4.7 (Default) \ No newline at end of file diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAdditionExpr.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAdditionExpr.fs new file mode 100644 index 00000000000..2fd34fa161a --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAdditionExpr.fs @@ -0,0 +1,7 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on const string +//Expression does not have a name. + +let x = nameof(1+2) + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAppliedFunction.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAppliedFunction.fs new file mode 100644 index 00000000000..666ba1453f3 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAppliedFunction.fs @@ -0,0 +1,8 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on applied functions +//Expression does not have a name. + +let f() = 1 +let x = nameof(f()) + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAsAFunction.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAsAFunction.fs new file mode 100644 index 00000000000..4fba9670064 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfAsAFunction.fs @@ -0,0 +1,7 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof can't be used as a function. +//Using the 'nameof' operator as a first-class function value is not permitted + +let f = nameof + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfDictLookup.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfDictLookup.fs new file mode 100644 index 00000000000..988863a0e1f --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfDictLookup.fs @@ -0,0 +1,8 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on dictionary lookup +//Expression does not have a name. + +let dict = new System.Collections.Generic.Dictionary() +let b = nameof(dict.[2]) + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfIntConst.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfIntConst.fs new file mode 100644 index 00000000000..9a2487e534f --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfIntConst.fs @@ -0,0 +1,7 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on const int +//Expression does not have a name. + +let x = nameof 1 + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfIntegerAppliedFunction.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfIntegerAppliedFunction.fs new file mode 100644 index 00000000000..303bd2b9a31 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfIntegerAppliedFunction.fs @@ -0,0 +1,8 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on applied functions +//Expression does not have a name. + +let f x = 1 * x +let x = nameof(f 2) + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfParameterAppliedFunction.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfParameterAppliedFunction.fs new file mode 100644 index 00000000000..252e867c91a --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfParameterAppliedFunction.fs @@ -0,0 +1,9 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on applied functions +//Expression does not have a name. + +let f x y = x y +let z x = 1 * x +let b = nameof(f z 1) + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfPartiallyAppliedFunction.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfPartiallyAppliedFunction.fs new file mode 100644 index 00000000000..be11b22a6a6 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfPartiallyAppliedFunction.fs @@ -0,0 +1,8 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on partially applied functions +//Expression does not have a name. + +let f x y = y * x +let x = nameof(f 2) + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfStringConst.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfStringConst.fs new file mode 100644 index 00000000000..f901f6f72ff --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfStringConst.fs @@ -0,0 +1,7 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof doesn't work on const string +//Expression does not have a name. + +let x = nameof "string" + +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfUnresolvableName.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfUnresolvableName.fs new file mode 100644 index 00000000000..2f998cbb172 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfUnresolvableName.fs @@ -0,0 +1,6 @@ +// #Regression #Conformance #DataExpressions +// Verify that passing unresolvable symbol name results with compilation error. +//The value, constructor, namespace or type 'Unknown' is not defined. + +let b = nameof System.Collections.Generic.Unknown +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfWithPipe.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfWithPipe.fs new file mode 100644 index 00000000000..26074a4cac6 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/E_NameOfWithPipe.fs @@ -0,0 +1,7 @@ +// #Regression #Conformance #DataExpressions +// Verify that nameof can't be used as a function. +//Using the 'nameof' operator as a first-class function value is not permitted. + +let curriedFunction x y = x * y +let b = curriedFunction |> nameof +exit 0 diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/env.lst b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/env.lst new file mode 100644 index 00000000000..9d473234e60 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/NameOf/env.lst @@ -0,0 +1,11 @@ + SOURCE=E_NameOfIntConst.fs SCFLAGS="--langversion:preview" # E_NameOfIntConst.fs + SOURCE=E_NameOfStringConst.fs SCFLAGS="--langversion:preview" # E_NameOfStringConst.fs + SOURCE=E_NameOfAppliedFunction.fs SCFLAGS="--langversion:preview" # E_NameOfAppliedFunction.fs + SOURCE=E_NameOfIntegerAppliedFunction.fs SCFLAGS="--langversion:preview" # E_NameOfIntegerAppliedFunction.fs + SOURCE=E_NameOfPartiallyAppliedFunction.fs SCFLAGS="--langversion:preview" # E_NameOfPartiallyAppliedFunction.fs + SOURCE=E_NameOfDictLookup.fs SCFLAGS="--langversion:preview" # E_NameOfDictLookup.fs + SOURCE=E_NameOfAdditionExpr.fs SCFLAGS="--langversion:preview" # E_NameOfAdditionExpr.fs + SOURCE=E_NameOfParameterAppliedFunction.fs SCFLAGS="--langversion:preview" # E_NameOfParameterAppliedFunction.fs + SOURCE=E_NameOfAsAFunction.fs SCFLAGS="--langversion:preview" # E_NameOfAsAFunction.fs + SOURCE=E_NameOfWithPipe.fs SCFLAGS="--langversion:preview" # E_NameOfWithPipe.fs + SOURCE=E_NameOfUnresolvableName.fs SCFLAGS="--langversion:preview" # E_NameOfUnresolvableName.fs diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/env.lst b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/env.lst index e0c8f701ba8..c769c0a0950 100644 --- a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/env.lst +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/env.lst @@ -1,6 +1,10 @@ - SOURCE=W_IfThenElse01.fs SCFLAGS="--test:ErrorRanges" # W_IfThenElse01.fs - SOURCE=W_IfThenElse02.fs SCFLAGS="--test:ErrorRanges" # W_IfThenElse02.fs - SOURCE=W_IfThenElse03.fs SCFLAGS="--test:ErrorRanges" # W_IfThenElse03.fs + SOURCE=version46/W_IfThenElse01.fs SCFLAGS="--langversion:4.6 --test:ErrorRanges" # version46 W_IfThenElse01.fs + SOURCE=version46/W_IfThenElse02.fs SCFLAGS="--langversion:4.6 --test:ErrorRanges" # version46 W_IfThenElse02.fs + SOURCE=version46/W_IfThenElse03.fs SCFLAGS="--langversion:4.6 --test:ErrorRanges" # version46 W_IfThenElse03.fs + SOURCE=version47/W_IfThenElse01.fs SCFLAGS="--test:ErrorRanges" # W_IfThenElse01.fs + SOURCE=version47/W_IfThenElse02.fs SCFLAGS="--test:ErrorRanges" # W_IfThenElse02.fs + SOURCE=version47/W_IfThenElse03.fs SCFLAGS="--test:ErrorRanges" # W_IfThenElse03.fs + SOURCE=IfThenElse04.fs SCFLAGS="--test:ErrorRanges --warnaserror" # IfThenElse04.fs SOURCE=IfThenElse05.fs SCFLAGS="--test:ErrorRanges --warnaserror" # IfThenElse05.fs SOURCE=IfThenElse06.fs SCFLAGS="--test:ErrorRanges --warnaserror" # IfThenElse06.fs diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse01.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse01.fs similarity index 93% rename from tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse01.fs rename to tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse01.fs index 56a7a819935..4e948ea575f 100644 --- a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse01.fs +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse01.fs @@ -8,4 +8,4 @@ // disambiguate this from a list generated using a sequence expression. let p = [ if true then 1 else 2 ] -(if p = [ 1 ] then 0 else 1) |> exit +(if p = [ 1 ] then 0 else 1) |> exit \ No newline at end of file diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse02.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse02.fs similarity index 93% rename from tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse02.fs rename to tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse02.fs index 724a9b55cc3..805af8ee0ea 100644 --- a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse02.fs +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse02.fs @@ -8,4 +8,4 @@ // disambiguate this from a list generated using a sequence expression. let p = [ if true then 1 else printfn "hello"; 3 ] -(if p = [ 1 ] then 0 else 1) |> exit +(if p = [ 1 ] then 0 else 1) |> exit \ No newline at end of file diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse03.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse03.fs similarity index 93% rename from tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse03.fs rename to tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse03.fs index 0d139cd7151..9a357a9f2c6 100644 --- a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/W_IfThenElse03.fs +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version46/W_IfThenElse03.fs @@ -8,4 +8,4 @@ // disambiguate this from a list generated using a sequence expression. let p = [ if true then printfn "hello"; () ];; -(if p = [ () ] then 0 else 1) |> exit +(if p = [ () ] then 0 else 1) |> exit \ No newline at end of file diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse01.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse01.fs new file mode 100644 index 00000000000..c2b85aece6a --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse01.fs @@ -0,0 +1,11 @@ +// #Regression #Conformance #DataExpressions #Sequences +// Note, implicit yield is enabled because no 'yield' is used + + + + + + + +let p = [ if true then 1 else 2 ] +(if p = [ 1 ] then 0 else 1) |> exit diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse02.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse02.fs new file mode 100644 index 00000000000..cabe197b92d --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse02.fs @@ -0,0 +1,11 @@ +// #Regression #Conformance #DataExpressions #Sequences +// Note, implicit yield is enabled because no 'yield' is used + + + + + + + +let p = [ if false then 1 else printfn "hello"; 3 ] +(if p = [ 3 ] then 0 else 1) |> exit diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse03.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse03.fs new file mode 100644 index 00000000000..286fecdce6a --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/SequenceExpressions/version47/W_IfThenElse03.fs @@ -0,0 +1,11 @@ +// #Regression #Conformance #DataExpressions #Sequences +// Note, implicit yield is enabled because no 'yield' is used + + + + + + + +let p : unit list = [ if true then printfn "hello"; () ];; // note, both unit-typed expressions interpreted as side-effecting operations +(match p with [ ] -> 0 | _ -> 1) |> exit diff --git a/tests/fsharpqa/Source/Misc/AsyncOperations.fs b/tests/fsharpqa/Source/Misc/AsyncOperations.fs index 4b53b0ccff7..2bc7738de70 100644 --- a/tests/fsharpqa/Source/Misc/AsyncOperations.fs +++ b/tests/fsharpqa/Source/Misc/AsyncOperations.fs @@ -127,8 +127,7 @@ namespace Microsoft.FSharp.Control type System.Net.WebRequest with member req.AsyncGetResponse() = callFSharpCoreAsyncGetResponse req // this calls the FSharp.Core method member req.GetResponseAsync() = callFSharpCoreAsyncGetResponse req // this calls the FSharp.Core method - -#if !FX_NO_WEB_CLIENT + [] module WebClientExtensions = open System.Net @@ -138,5 +137,4 @@ namespace Microsoft.FSharp.Control type WebClient with member this.AsyncDownloadString address = callFSharpCoreAsyncDownloadString this address -#endif diff --git a/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList.fs b/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList.fs new file mode 100644 index 00000000000..d47a4c13769 --- /dev/null +++ b/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList.fs @@ -0,0 +1,14 @@ +// #Warnings +// + +let div _ _ = 1 +let subView _ _ = [1; 2] + +// elmish view +let view model dispatch = + [ + yield! subView model dispatch + div [] [] + ] + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList2.fs b/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList2.fs new file mode 100644 index 00000000000..cf0a8cc6e89 --- /dev/null +++ b/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList2.fs @@ -0,0 +1,19 @@ +// #Warnings +// + +// stupid things to make the sample compile +let div _ _ = 1 +let subView _ _ = [1; 2] +let y = 1 + +// elmish view +let view model dispatch = + [ + div [] [ + match y with + | 1 -> yield! subView model dispatch + | _ -> subView model dispatch + ] + ] + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList3.fs b/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList3.fs new file mode 100644 index 00000000000..238d4388f9e --- /dev/null +++ b/tests/fsharpqa/Source/Warnings/version46/WarnIfDiscardedInList3.fs @@ -0,0 +1,19 @@ +// #Warnings +// + +// stupid things to make the sample compile +let div _ _ = 1 +let subView _ _ = true +let y = 1 + +// elmish view +let view model dispatch = + [ + div [] [ + match y with + | 1 -> () + | _ -> subView model dispatch + ] + ] + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList.fs b/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList.fs new file mode 100644 index 00000000000..87bf47412c4 --- /dev/null +++ b/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList.fs @@ -0,0 +1,14 @@ +// This no longer gives a warning because implicit yields are now allowed + + +let div _ _ = 1 +let subView _ _ = [1; 2] + +// elmish view +let view model dispatch = + [ + yield! subView model dispatch + div [] [] + ] + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList2.fs b/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList2.fs new file mode 100644 index 00000000000..d7ca60baec4 --- /dev/null +++ b/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList2.fs @@ -0,0 +1,20 @@ +// This no longer gives a warning because implicit yields are now allowed + + +// stupid things to make the sample compile +let div _ _ = 1 +let subView _ _ = [1; 2] +let subView2 _ _ = 1 +let y = 1 + +// elmish view +let view model dispatch = + [ + div [] [ + match y with + | 1 -> yield! subView model dispatch + | _ -> subView2 model dispatch + ] + ] + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList3.fs b/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList3.fs new file mode 100644 index 00000000000..e5035827521 --- /dev/null +++ b/tests/fsharpqa/Source/Warnings/version47/WarnIfDiscardedInList3.fs @@ -0,0 +1,19 @@ +// This no longer gives a warning because implicit yields are now allowed + + +// stupid things to make the sample compile +let div _ _ = 1 +let subView _ _ = true +let y = 1 + +// elmish view +let view model dispatch = + [ + div [] [ + match y with + | 1 -> () + | _ -> subView model dispatch + ] + ] + +exit 0 \ No newline at end of file diff --git a/tests/fsharpqa/Source/test.lst b/tests/fsharpqa/Source/test.lst index 667bda8cef8..8a3aeac76b2 100644 --- a/tests/fsharpqa/Source/test.lst +++ b/tests/fsharpqa/Source/test.lst @@ -42,6 +42,7 @@ CompilerOptions01,NoMT CompilerOptions\fsc\flaterrors CompilerOptions02,NoMT CompilerOptions\fsc\gccerrors CompilerOptions01,NoMT,help CompilerOptions\fsc\help CompilerOptions01,NoMT CompilerOptions\fsc\highentropyva +CompilerOptions01,NoMT CompilerOptions\fsc\langversion CompilerOptions01,NoMT CompilerOptions\fsc\lib CompilerOptions01,NoMT CompilerOptions\fsc\noframework CompilerOptions01,NoMT CompilerOptions\fsc\nologo @@ -63,6 +64,7 @@ CompilerOptions01,NoMT CompilerOptions\fsc\warnon CompilerOptions01,NoMT CompilerOptions\fsc\responsefile CompilerOptions01,NoMT,help CompilerOptions\fsi\help CompilerOptions01,NoMT CompilerOptions\fsi\highentropyva +CompilerOptions01,NoMT CompilerOptions\fsi\langversion CompilerOptions01,NoMT CompilerOptions\fsi\nologo CompilerOptions01,NoMT CompilerOptions\fsi\subsystemversion CompilerOptions01,NoMT CompilerOptions\fsi\times @@ -240,6 +242,7 @@ Conformance08 Conformance\UnitsOfMeasure\Parenthesis Conformance08 Conformance\UnitsOfMeasure\Parsing Conformance08 Conformance\UnitsOfMeasure\TypeChecker Conformance08 Conformance\UnitsOfMeasure\WithOOP +Conformance08 Conformance\Expressions\DataExpressions\NameOf Misc01 ClrFx\PseudoCustomAttributes\AssemblyAlgorithmId Misc01 ClrFx\PseudoCustomAttributes\AssemblyConfiguration diff --git a/tests/fsharpqa/comparer.fsx b/tests/fsharpqa/comparer.fsx new file mode 100644 index 00000000000..26bff8cb785 --- /dev/null +++ b/tests/fsharpqa/comparer.fsx @@ -0,0 +1,44 @@ +// #NoMT #CompilerOptions #RequiresENU +#light +open System +open System.IO +open System.Text.RegularExpressions + +let arg0 = Environment.GetCommandLineArgs().[0] +let path = Environment.GetEnvironmentVariable("PATH") +let fn1 = fsi.CommandLineArgs.[1] +let fn2 = fsi.CommandLineArgs.[2] + +// Read file into an array +let File2List (filename:string) = File.ReadAllLines(filename) + +let f1 = File2List fn1 +let f2 = File2List fn2 + +let mutable i = 0 +let compare (f1:string[]) (f2:string[]) = + if f1.Length <> f2.Length then failwithf "Help text did not match. f1.Length = %d, f2.Length = %d, Check you have right fsi on path. fsi = %s, PATH=%s" f1.Length f2.Length arg0 path + (f1, f2) ||> Array.forall2 (fun (a:string) (b:string) -> + + let replace (sourcepattern:string) (replacement:string) (str:string) : string = + Regex.Replace(str, sourcepattern, replacement) + + let normalizeText (str:string) = + str |> replace @"F# Interactive version .+" "F# Interactive" + |> replace @"F# Compiler version .+" "F# Compiler" + |> replace "fsiAnyCpu.exe" "fsi.exe" + + let aa = normalizeText a + let bb = normalizeText b + + i <- i+1 + if (aa = bb) then + true + else + printfn "Files differ at line %d:" i + printfn "\t>> %s" a + printfn "\t<< %s" b + false + ) + +exit (if compare f1 f2 then 0 else 1) diff --git a/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard1.6/Sample_NETCoreSDK_FSharp_Library_netstandard1.6.fsproj b/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard1.6/Sample_NETCoreSDK_FSharp_Library_netstandard1.6.fsproj index abac283cf0c..a237159916f 100644 --- a/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard1.6/Sample_NETCoreSDK_FSharp_Library_netstandard1.6.fsproj +++ b/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard1.6/Sample_NETCoreSDK_FSharp_Library_netstandard1.6.fsproj @@ -1,6 +1,6 @@ - netstandard1.6 + netstandard2.0 diff --git a/tests/projects/stress/Templates/fsproj.template b/tests/projects/stress/Templates/fsproj.template index 2e87b3a4a85..9af6ff1673d 100644 --- a/tests/projects/stress/Templates/fsproj.template +++ b/tests/projects/stress/Templates/fsproj.template @@ -36,7 +36,7 @@ - ..\packages\FSharp.Core.4.6.2\lib\net45\FSharp.Core.dll + ..\packages\FSharp.Core.4.7.0\lib\net45\FSharp.Core.dll diff --git a/tests/service/Common.fs b/tests/service/Common.fs index 0ec9aa2ab3c..6920e682afe 100644 --- a/tests/service/Common.fs +++ b/tests/service/Common.fs @@ -6,10 +6,6 @@ open System.Collections.Generic open FSharp.Compiler open FSharp.Compiler.SourceCodeServices -#if FX_RESHAPED_REFLECTION -open ReflectionAdapters -#endif - #if NETCOREAPP2_0 let readRefs (folder : string) (projectFile: string) = let runProcess (workingDir: string) (exePath: string) (args: string) = @@ -71,14 +67,10 @@ let sysLib nm = #if !NETCOREAPP2_0 if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows let programFilesx86Folder = System.Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") - programFilesx86Folder + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\" + nm + ".dll" + programFilesx86Folder + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\" + nm + ".dll" else #endif -#if FX_NO_RUNTIMEENVIRONMENT let sysDir = System.AppContext.BaseDirectory -#else - let sysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() -#endif let (++) a b = System.IO.Path.Combine(a,b) sysDir ++ nm + ".dll" diff --git a/tests/service/EditorTests.fs b/tests/service/EditorTests.fs index 63406f09cb4..69b9e407645 100644 --- a/tests/service/EditorTests.fs +++ b/tests/service/EditorTests.fs @@ -1288,16 +1288,6 @@ let ``Test TPProject param info`` () = #endif // TEST_TP_PROJECTS -#if EXE - -``Intro test`` () -//``Test TPProject all symbols`` () -//``Test TPProject errors`` () -//``Test TPProject quick info`` () -//``Test TPProject param info`` () -``Basic cancellation test`` () -``Intro test`` () -#endif [] let ``FSharpField.IsNameGenerated`` () = diff --git a/tests/service/FscTests.fs b/tests/service/FscTests.fs index 9bedfd38b1b..b7ff870675e 100644 --- a/tests/service/FscTests.fs +++ b/tests/service/FscTests.fs @@ -20,10 +20,6 @@ open FSharp.Compiler.Service.Tests.Common open NUnit.Framework -#if FX_RESHAPED_REFLECTION -open ReflectionAdapters -#endif - exception VerificationException of (*assembly:*)string * (*errorCode:*)int * (*output:*)string with override e.Message = sprintf "Verification of '%s' failed with code %d, message <<<%s>>>" e.Data0 e.Data1 e.Data2 diff --git a/tests/service/ReshapedReflection.fs b/tests/service/ReshapedReflection.fs deleted file mode 100644 index 3b1ba07ce81..00000000000 --- a/tests/service/ReshapedReflection.fs +++ /dev/null @@ -1,9 +0,0 @@ -namespace FSharp.Compiler.Service.Tests - -#if FX_RESHAPED_REFLECTION -module internal ReflectionAdapters = - open System.Reflection - - type System.Type with - member this.Assembly = this.GetTypeInfo().Assembly -#endif diff --git a/tests/service/data/samename/tempet.fsproj b/tests/service/data/samename/tempet.fsproj index 682a3ec1a30..03da397c8db 100644 --- a/tests/service/data/samename/tempet.fsproj +++ b/tests/service/data/samename/tempet.fsproj @@ -1,6 +1,6 @@ - netstandard1.6 + netstandard2.0 diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/ConsoleApplication.vstemplate b/vsintegration/ProjectTemplates/ConsoleProject/Template/ConsoleApplication.vstemplate index 457a0d84b66..fea0279b943 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/ConsoleApplication.vstemplate +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/ConsoleApplication.vstemplate @@ -27,7 +27,7 @@ - + diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.de.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.de.xlf index 87fa85b31c9..8df6ae7fc3b 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.de.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.de.xlf @@ -19,17 +19,17 @@ Setting ComVisible to false makes the types in this assembly not visible - Durch Festlegen von ComVisible auf 'false' werden die Typen in dieser Assembly unsichtbar + Durch Festlegen von ComVisible auf FALSE sind die Typen in dieser Assembly nicht to COM components. If you need to access a type in this assembly from - für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von + für COM-Komponenten sichtbar. Wenn Sie auf einen Typ in dieser Assembly von COM, set the ComVisible attribute to true on that type. - COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. + COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf TRUE festlegen. diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.cs.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.cs.xlf index ffd1deada4e..0a1913fea3f 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.cs.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.cs.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Další informace o F# na https://fsharp.org + Další informace o F# najdete na https://fsharp.org. diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.de.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.de.xlf index 59272645d4f..8c434e9d7d1 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.de.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.de.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Weitere Informationen zu F# unter "https://fsharp.org". + Weitere Informationen zu F# unter https://fsharp.org. diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.es.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.es.xlf index 081582225ec..1472966885a 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.es.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.es.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Más información acerca de F# en https://fsharp.org + Más información sobre F# en https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.fr.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.fr.xlf index c2ed6e21e30..8052d98708d 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.fr.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.fr.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - En savoir plus sur F# sur le site https://fsharp.org + En savoir plus sur F# : https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.it.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.it.xlf index 5b9b76eb7f9..c9027ad5b69 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.it.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.it.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Altre informazioni su F# all'indirizzo https://fsharp.org + Altre informazioni su F# disponibili all'indirizzo https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ja.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ja.xlf index e0935dc2910..c24608aec3b 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ja.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ja.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - F# の詳細については、https://fsharp.org を参照してください + F# の詳細については、https://fsharp.org をご覧ください diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ko.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ko.xlf index e41549ea2a6..7d9f7dc54e7 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ko.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ko.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - hF#에 대해 https://fsharp.org에서 자세히 알아보기 + https://fsharp.org에서 F#에 대해 자세히 알아보기 diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pl.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pl.xlf index 298af71ef08..763d2db3df3 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pl.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pl.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Dowiedz się więcej na temat języka F# pod adresem https://fsharp.org + Dowiedz się więcej o języku F# na stronie https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pt-BR.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pt-BR.xlf index 701d39192b5..7af54cd8fd5 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pt-BR.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.pt-BR.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Saiba mais sobre F# em https://fsharp.org + Saiba mais sobre o F# em https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ru.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ru.xlf index 57caaf2c822..54eb018503e 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ru.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.ru.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Дополнительные сведения о F# см. на https://fsharp.org + Дополнительные сведения об F# см. на странице https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.tr.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.tr.xlf index deaa07d46bb..c584140b66b 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.tr.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.tr.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - F# hakkında daha fazla bilgi için bkz. https://fsharp.org + F# hakkında daha fazla bilgi edinmek için bkz. https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hans.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hans.xlf index 74de5b0fe08..27df727dbda 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hans.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hans.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - 在 https://fsharp.org 上了解有关 F# 的详细信息 + 了解更多关于 F# 的信息,请访问 https://fsharp.org diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hant.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hant.xlf index b0f43a7d4a4..5f67238de8b 100644 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hant.xlf +++ b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.zh-Hant.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - 請參閱 https://fsharp.org,進一步了解 F# + 前往 https://fsharp.org 深入了解 F# diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/Library.vstemplate b/vsintegration/ProjectTemplates/LibraryProject/Template/Library.vstemplate index 07c8ab1065e..d7f9a14d8d2 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/Library.vstemplate +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/Library.vstemplate @@ -27,7 +27,7 @@ - + diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.de.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.de.xlf index 87fa85b31c9..8df6ae7fc3b 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.de.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.de.xlf @@ -19,17 +19,17 @@ Setting ComVisible to false makes the types in this assembly not visible - Durch Festlegen von ComVisible auf 'false' werden die Typen in dieser Assembly unsichtbar + Durch Festlegen von ComVisible auf FALSE sind die Typen in dieser Assembly nicht to COM components. If you need to access a type in this assembly from - für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von + für COM-Komponenten sichtbar. Wenn Sie auf einen Typ in dieser Assembly von COM, set the ComVisible attribute to true on that type. - COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. + COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf TRUE festlegen. diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.cs.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.cs.xlf index fc829e7113d..e9771690a96 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.cs.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.cs.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Další informace o F# na https://fsharp.org + Další informace o F# najdete na https://fsharp.org. diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.de.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.de.xlf index 28fe2b6f408..61df76a2804 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.de.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.de.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Weitere Informationen zu F# unter "https://fsharp.org". + Weitere Informationen zu F# unter https://fsharp.org. diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.es.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.es.xlf index 507619b46b4..96fb3d36476 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.es.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.es.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Más información acerca de F# en https://fsharp.org + Más información sobre F# en https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.fr.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.fr.xlf index 53a859e0d59..cb48575303e 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.fr.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.fr.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - En savoir plus sur F# sur le site https://fsharp.org + Pour en savoir plus sur le F# : https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.it.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.it.xlf index d65ce6f70ce..42558ead9d1 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.it.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.it.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Altre informazioni su F# all'indirizzo https://fsharp.org + Altre informazioni su F# disponibili all'indirizzo https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ja.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ja.xlf index 45cbcbec9ad..45967e26bfd 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ja.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ja.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - F# の詳細については、https://fsharp.org を参照してください + F# の詳細については、https://fsharp.org をご覧ください diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ko.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ko.xlf index 45d7cd9e47c..661f9e6344d 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ko.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ko.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - hF#에 대해 https://fsharp.org에서 자세히 알아보기 + https://fsharp.org에서 F#에 대해 자세히 알아보기 diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pl.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pl.xlf index 94269ce71bf..e32717ff706 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pl.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pl.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Dowiedz się więcej na temat języka F# pod adresem https://fsharp.org + Dowiedz się więcej o języku F# na stronie https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pt-BR.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pt-BR.xlf index f1be7744b14..1bd32f9343a 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pt-BR.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.pt-BR.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Saiba mais sobre F# em https://fsharp.org + Saiba mais sobre o F# em https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ru.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ru.xlf index 08746c4a7f6..b8a6d8cced2 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ru.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.ru.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - Дополнительные сведения о F# см. на https://fsharp.org + Дополнительные сведения об F# см. на странице https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.tr.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.tr.xlf index 564cfc2dca4..1b3c2476e69 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.tr.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.tr.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - F# hakkında daha fazla bilgi için bkz. https://fsharp.org + F# hakkında daha fazla bilgi edinmek için bkz. https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hans.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hans.xlf index 0859fdcd1a1..4d849f68e3b 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hans.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hans.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - 在 https://fsharp.org 上了解有关 F# 的详细信息 + 了解更多关于 F# 的信息,请访问 https://fsharp.org diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hant.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hant.xlf index 9edde3fd88b..14ed4156de2 100644 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hant.xlf +++ b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.zh-Hant.xlf @@ -4,7 +4,7 @@ Learn more about F# at https://fsharp.org - 請參閱 https://fsharp.org,進一步了解 F# + 前往 https://fsharp.org 深入了解 F# diff --git a/vsintegration/ProjectTemplates/TutorialProject/Template/Tutorial.vstemplate b/vsintegration/ProjectTemplates/TutorialProject/Template/Tutorial.vstemplate index 73b11c8c907..adb7d6e2306 100644 --- a/vsintegration/ProjectTemplates/TutorialProject/Template/Tutorial.vstemplate +++ b/vsintegration/ProjectTemplates/TutorialProject/Template/Tutorial.vstemplate @@ -25,7 +25,7 @@ - + diff --git a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.de.xlf b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.de.xlf index 5fbb27634d8..0908855049f 100644 --- a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.de.xlf +++ b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.de.xlf @@ -84,7 +84,7 @@ and they also allow editors (such as Visual Studio) to extract information from them. - und sie ermöglichen das Extrahieren von Informationen über Editoren (z. B. Visual Studio). + und sie ermöglichen das Extrahieren von Informationen über Editoren (z.B. Visual Studio). @@ -104,7 +104,7 @@ A module is a grouping of F# code, such as values, types, and function values. - Ein Modul ist eine Gruppierung von F#-Code, z. B. Werte, Typen und Funktionswerte. + Ein Modul ist eine Gruppierung von F#-Code, z.B. Werte, Typen und Funktionswerte. @@ -199,7 +199,7 @@ You could not use '=' here for this purpose since it is used for equality - Sie können '=' hier nicht verwenden, da es für Gleichheit verwendet wird. + Sie können "=" hier nicht verwenden, da es für Gleichheit verwendet wird. @@ -234,7 +234,7 @@ Apply the function, naming the function return result using 'let'. - Die Funktion anwenden, und das Rückgabeergebnis der Funktion mithilfe von 'let' benennen. + Die Funktion anwenden, und das Rückgabeergebnis der Funktion mithilfe von "let" benennen. @@ -249,7 +249,7 @@ If 'result1' were not of type 'int', then the line would fail to compile. - Wenn "result1" nicht vom Typ "int" wäre, würde die Kompilierung der Zeile fehlschlagen. + Wenn "result1" nicht vom Typ "int" wäre, käme es bei der Kompilierung der Zeile zu einem Fehler. @@ -1294,7 +1294,7 @@ Option values are any kind of value tagged with either 'Some' or 'None'. - Bei Optionswerten handelt es sich um eine beliebige Art von Werten, die entweder mit 'Some' oder mit 'None' markiert sind. + Bei Optionswerten handelt es sich um eine beliebige Art von Werten, die entweder mit "Some" oder mit "None" markiert sind. @@ -1394,7 +1394,7 @@ Values using Units of Measure can be used just like the primitive numeric type for things like printing. - Werte, die Maßeinheiten verwenden, können wie der primitive numerische Typ z. B. zum Drucken genutzt werden. + Werte, die Maßeinheiten verwenden, können wie der primitive numerische Typ z.B. zum Drucken genutzt werden. @@ -1444,7 +1444,7 @@ 'this' specifies a name for the object's self identifier. - 'this' gibt einen Namen für den Selbstbezeichner des Objekts an. + "this" gibt einen Namen für den Selbstbezeichner des Objekts an. @@ -1494,7 +1494,7 @@ use the '<-' operator to mutate the value. - Den '<-'-Operator verwenden, um den Wert zu mutieren + Den "<-"-Operator verwenden, um den Wert zu mutieren @@ -1509,7 +1509,7 @@ An 'int' instance of the state tracker class. Note that the type parameter is inferred. - Eine 'int'-Instanz der 'state tracker'-Klasse. Beachten Sie, dass der Typ-Parameter abgeleitet wird. + Eine int-Instanz der state tracker-Klasse. Beachten Sie, dass der Typ-Parameter abgeleitet wird. diff --git a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.ja.xlf b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.ja.xlf index 5694cd3bf7b..0eda61edb13 100644 --- a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.ja.xlf +++ b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.ja.xlf @@ -1324,7 +1324,7 @@ Next, define an interface type that represents an object to compute the shipping zone for the customer's zip code, - 他に多くのリストの組み合わせがあります。次の二乗和をコンピューティングします: + 次に、オブジェクトを表すインターフェイスの型を定義して、顧客の郵便番号の出荷ゾーンをコンピューティングし、 diff --git a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.zh-Hant.xlf b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.zh-Hant.xlf index fea7e0434e6..fd33d17fa37 100644 --- a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.zh-Hant.xlf +++ b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.zh-Hant.xlf @@ -14,7 +14,7 @@ and select "Execute in Interactive". You can open the F# Interactive Window from the "View" menu. - 並選取 [以互動方式執行]5D;。您可以從 [檢視]5D; 功能表開啟 F# Interactive 視窗。 + 並選取 [以互動方式執行]。您可以從 [檢視] 功能表開啟 F# 互動式視窗。 diff --git a/vsintegration/Utils/LanguageServiceProfiling/Options.fs b/vsintegration/Utils/LanguageServiceProfiling/Options.fs index 1747ff3bfe6..23a3ac25596 100644 --- a/vsintegration/Utils/LanguageServiceProfiling/Options.fs +++ b/vsintegration/Utils/LanguageServiceProfiling/Options.fs @@ -29,7 +29,6 @@ let FCS (repositoryDir: string) : Options = @"src\fsharp\FSharp.Compiler.Service\obj\Release\FSIstrings.fs" @"src\assemblyinfo\assemblyinfo.FSharp.Compiler.Private.dll.fs" @"src\assemblyinfo\assemblyinfo.shared.fs" - @"src\utils\reshapedreflection.fs" @"src\utils\sformat.fsi" @"src\utils\sformat.fs" @"src\fsharp\sr.fsi" @@ -209,7 +208,7 @@ let FCS (repositoryDir: string) : Options = [|@"-o:obj\Release\FSharp.Compiler.Private.dll"; "-g"; "--noframework"; @"--baseaddress:0x06800000"; "--define:DEBUG"; @"--define:CROSS_PLATFORM_COMPILER"; - @"--define:FX_ATLEAST_40"; "--define:BE_SECURITY_TRANSPARENT"; + @"--define:FX_ATLEAST_40"; @"--define:COMPILER"; @"--define:ENABLE_MONO_SUPPORT"; "--define:FX_MSBUILDRESOLVER_RUNTIMELIKE"; @"--define:FX_RESX_RESOURCE_READER"; "--define:FX_RESIDENT_COMPILER"; diff --git a/vsintegration/Vsix/RegisterFsharpPackage.pkgdef b/vsintegration/Vsix/RegisterFsharpPackage.pkgdef index cc6731507ec..b0b49ad4efd 100644 --- a/vsintegration/Vsix/RegisterFsharpPackage.pkgdef +++ b/vsintegration/Vsix/RegisterFsharpPackage.pkgdef @@ -7,6 +7,9 @@ "Name"="F#" @="{871d2a70-12a2-4e42-9440-425dd92a4116}" +[$RootKey$\Editors\{8a5aa6cf-46e3-4520-a70a-7393d15233e9}] +"DeferUntilIntellisenseIsReady"=dword:00000000 + [$RootKey$\Editors\{8a5aa6cf-46e3-4520-a70a-7393d15233e9}\LogicalViews] "{7651a700-06e5-11d1-8ebd-00a0c90f26ea}"="" "{7651a701-06e5-11d1-8ebd-00a0c90f26ea}"="" diff --git a/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj b/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj index 0f3774974e1..cfab3f5dfa6 100644 --- a/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj +++ b/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj @@ -15,9 +15,9 @@ packages\System.ValueTuple.4.4.0.nupkg true - + PreserveNewest - packages\FSharp.Core.4.6.2.nupkg + packages\FSharp.Core.$(FSharpCoreShippedPackageVersion).nupkg true @@ -27,7 +27,7 @@ - + diff --git a/vsintegration/src/FSharp.Editor/CodeFix/RenameUnusedValue.fs b/vsintegration/src/FSharp.Editor/CodeFix/RenameUnusedValue.fs index 57d4eff5eff..67379326323 100644 --- a/vsintegration/src/FSharp.Editor/CodeFix/RenameUnusedValue.fs +++ b/vsintegration/src/FSharp.Editor/CodeFix/RenameUnusedValue.fs @@ -69,12 +69,8 @@ type internal FSharpRenameUnusedValueCodeFixProvider match symbolUse.Symbol with | :? FSharpMemberOrFunctionOrValue as func -> createCodeFix(context, symbolName, SR.PrefixValueNameWithUnderscore(), TextChange(TextSpan(context.Span.Start, 0), "_")) - - if func.IsMemberThisValue then - createCodeFix(context, symbolName, SR.RenameValueToDoubleUnderscore(), TextChange(context.Span, "__")) - elif func.IsValue then - createCodeFix(context, symbolName, SR.RenameValueToUnderscore(), TextChange(context.Span, "_")) + if func.IsValue then createCodeFix(context, symbolName, SR.RenameValueToUnderscore(), TextChange(context.Span, "_")) | _ -> () } |> Async.Ignore - |> RoslynHelpers.StartAsyncUnitAsTask(context.CancellationToken) \ No newline at end of file + |> RoslynHelpers.StartAsyncUnitAsTask(context.CancellationToken) diff --git a/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.de.xlf b/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.de.xlf index a77fe0da025..d397b748508 100644 --- a/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.de.xlf +++ b/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.de.xlf @@ -29,17 +29,17 @@ Cannot navigate to the provided member '{0}'. - Wechseln zum angegebenen Member '{0}' ist nicht möglich. + Wechseln zum angegebenen Member "{0}" ist nicht möglich. Cannot navigate to the provided type '{0}'. - Wechseln zum angegebenen Typ '{0}' ist nicht möglich. + Wechseln zum angegebenen Typ "{0}" ist nicht möglich. Cannot navigate to definition. Type check information is not available, please try later. - Wechseln zur Definition ist nicht möglich. Die Informationen zum Überprüfen des Typen sind nicht verfügbar. Versuchen Sie es später erneut. + Wechseln zur Definition ist nicht möglich. Die Informationen zum Überprüfen des Typen sind nicht verfügbar. Versuchen Sie es später noch mal. diff --git a/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.ja.xlf b/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.ja.xlf index 3b541159f28..8e843b7338e 100644 --- a/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.ja.xlf +++ b/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.ja.xlf @@ -4,7 +4,7 @@ (The documentation cache is still being constructed. Please try again in a few seconds.) - (ドキュメント キャッシュの作成中です。何秒か待ってからもう 一度操作を行ってください。 + (ドキュメント キャッシュの作成中です。何秒か待ってからもう 一度操作を行ってください。) diff --git a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.de.xlf b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.de.xlf index ffc095348b1..2a026b25d58 100644 --- a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.de.xlf +++ b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.de.xlf @@ -29,12 +29,12 @@ F# Interface File (*.fsi) - F# Schnittstellendatei (*.fsi) + F#-Schnittstellendatei (*.fsi) F# Script File (*.fsx) - F# Skriptdatei (*.fsx) + F#-Skriptdatei (*.fsx) @@ -59,7 +59,7 @@ Number - Anzahl + Zahl diff --git a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.it.xlf b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.it.xlf index e0c47b9efa7..a79fee23068 100644 --- a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.it.xlf +++ b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.it.xlf @@ -19,7 +19,7 @@ Operator - operatore + Operatore @@ -49,7 +49,7 @@ Identifier - identificatore + Identificatore diff --git a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.pt-BR.xlf b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.pt-BR.xlf index 2f9badfbb4a..502d5956dac 100644 --- a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.pt-BR.xlf +++ b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.pt-BR.xlf @@ -49,7 +49,7 @@ Identifier - identificador + Identificador diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.de.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.de.xlf index b9b597b8d53..d5de79f0e5c 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.de.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.de.xlf @@ -64,7 +64,7 @@ If you change a file name extension, the file may become unusable. Are you sure you want to change it? - Wenn Sie eine Dateinamenerweiterung ändern, wird die Datei möglicherweise unbrauchbar. Möchten Sie sie wirklich ändern? + Wenn Sie eine Dateinamenerweiterung ändern, wird die Datei möglicherweise unbrauchbar. Möchten Sie sie ändern? @@ -129,10 +129,10 @@ - contain only '.' - have any of the following characters: / ? : & \ * " < > | # % Für Dateien und Ordner gilt Folgendes: -- Sie dürfen keine leeren Zeichenfolgen sein. -- Sie dürfen keine für das System reservierten Namen aufweisen, einschließlich "CON", "AUX", PRN", "COM1" oder "LPT2". -- Sie dürfen nicht nur "." enthalten. -- Sie dürfen folgende Zeichen nicht aufweisen: / ? : & \ * " < > | # % +– Sie dürfen keine leeren Zeichenfolgen sein. +– Sie dürfen keine für das System reservierten Namen aufweisen, einschließlich "CON", "AUX", PRN", "COM1" oder "LPT2". +– Sie dürfen nicht ausschließlich "." enthalten. +– Sie dürfen folgende Zeichen nicht aufweisen: / ? : & \ * " < > | # % @@ -252,22 +252,22 @@ Minimal - minimal + Minimal Misc - Verschiedenes + Verschiedene None - NONE + Keine Normal - NORMAL + Normal @@ -802,7 +802,7 @@ Version - VERSION + Version diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.es.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.es.xlf index b94354b317b..a6784f5ff50 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.es.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.es.xlf @@ -119,7 +119,7 @@ error - Fehler + error @@ -252,7 +252,7 @@ Minimal - mínimo + Mínimo @@ -387,7 +387,7 @@ warning - Advertencia + advertencia diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.it.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.it.xlf index ce42e4ef509..2f9d2203399 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.it.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.it.xlf @@ -119,7 +119,7 @@ error - Errore + errore @@ -387,7 +387,7 @@ warning - Avviso + avviso diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pl.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pl.xlf index 00055ae4a89..8c5a5b3bf50 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pl.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pl.xlf @@ -119,7 +119,7 @@ error - Błąd + błąd @@ -387,7 +387,7 @@ warning - Ostrzeżenie + ostrzeżenie @@ -462,7 +462,7 @@ Build - Kompiluj + Kompilacja diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pt-BR.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pt-BR.xlf index f72f70bbe81..904ef68a5c5 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pt-BR.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.pt-BR.xlf @@ -252,7 +252,7 @@ Minimal - mínimo + Mínimo diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.zh-Hant.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.zh-Hant.xlf index 52c142cf47a..ad597cad5bf 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.zh-Hant.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.zh-Hant.xlf @@ -627,7 +627,7 @@ The project location is not trusted:{0}{0}{1}{0}{0}Running the application may result in security exceptions when it attempts to perform actions which require full trust.{0}{0}Click OK to ignore and continue. - 專案位置不受信任:{0}{0}{1}{0}{0}執行應用程式時若嘗試執行需要完全信任的動作,可能會產生安全性例外狀況。{0}{0}按一下 [確定]5D; 以忽略並繼續。 + 專案位置不受信任:{0}{0}{1}{0}{0}執行應用程式時若嘗試執行需要完全信任的動作,可能會產生安全性例外狀況。{0}{0}按一下 [確定] 以忽略並繼續。 diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.zh-Hant.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.zh-Hant.xlf index f1c96d5286c..918c8824296 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.zh-Hant.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.zh-Hant.xlf @@ -49,7 +49,7 @@ F# Interactive - F# Interactive + F# 互動 @@ -84,12 +84,12 @@ &Send to F# Interactive - 傳送到 F# Interactive(&S) + 傳送到 F# 互動(&S) &Send to F# Interactive - 傳送到 F# Interactive(&S) + 傳送到 F# 互動(&S) @@ -114,12 +114,12 @@ &Send Project Output to F# Interactive - 傳送專案輸出到 F# Interactive(&S) + 傳送專案輸出到 F# 互動(&S) &Send Project Output to F# Interactive - 傳送專案輸出到 F# Interactive(&S) + 傳送專案輸出到 F# 互動(&S) diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.cs.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.cs.xlf index 34cc71a6cf9..e27841feae2 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.cs.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.cs.xlf @@ -544,7 +544,7 @@ Referencing this version of FSharp.Core will cause your project to be incompatible with older versions of Visual Studio. Do you want to continue? - Odkazování na tuto verzi oboru názvů FSharp.Core zapříčíní nekompatibilitu projektu se staršími verzemi Visual Studia. Chcete pokračovat? + Odkazování na tuto verzi oboru názvů FSharp.Core zapříčiní nekompatibilitu projektu se staršími verzemi sady Visual Studio. Chcete pokračovat? diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.ja.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.ja.xlf index 0e69ee238b8..e0c79c4a2bf 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.ja.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.ja.xlf @@ -434,12 +434,12 @@ Microsoft Visual F# Tools 10.4 for F# 4.6 - F# 4.6 用 Microsoft Visual F# Tools + F# 4.6 用 Microsoft Visual F# Tools 10.4 Microsoft Visual F# Tools 10.4 for F# 4.6 - F# 4.6 用 Microsoft Visual F# Tools + F# 4.6 用 Microsoft Visual F# Tools 10.4 diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pl.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pl.xlf index 827c5be8302..5ae72d11dc8 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pl.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pl.xlf @@ -144,7 +144,7 @@ Build - Kompiluj + Kompilacja diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pt-BR.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pt-BR.xlf index aaa4543ca54..eb0221892ad 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pt-BR.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.pt-BR.xlf @@ -334,17 +334,17 @@ SQL Database Connection (LINQ to SQL, type provider) - Conexão de Banco de Dados SQL (LINQ para SQL, provedor de tipos) + Conexão de Banco de Dados SQL (LINQ to SQL, provedor de tipos) A project item for using the SqlDataConnection (LINQ to SQL) type provider to generate types and consume data in a live SQL database. - Um item de projeto para usar o provedor de tipos SqlDataConnection (LINQ para SQL) para gerar tipos e consumir dados em um banco de dados SQL dinâmico. + Um item de projeto para usar o provedor de tipos SqlDataConnection (LINQ to SQL) para gerar tipos e consumir dados em um banco de dados SQL dinâmico. SQL Database Connection (LINQ to Entities, type provider) - Conexão de Banco de Dados SQL (LINQ para Entidades, provedor de tipos) + Conexão de Banco de Dados SQL (LINQ to Entities, provedor de tipos) @@ -434,12 +434,12 @@ Microsoft Visual F# Tools 10.4 for F# 4.6 - Ferramentas F# do Microsoft Visual 10.4 para F# 4.6 + Microsoft Visual F# Tools 10.4 para F# 4.6 Microsoft Visual F# Tools 10.4 for F# 4.6 - Ferramentas F# do Microsoft Visual 10.4 para F# 4.6 + Microsoft Visual F# Tools 10.4 para F# 4.6 @@ -454,7 +454,7 @@ Visual F# Tools 10.4 for F# 4.6 - Ferramentas F# do Visual 10.4 para F# 4.6 + Visual F# Tools 10.4 para F# 4.6 diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.zh-Hant.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.zh-Hant.xlf index 6b452390e2b..326a36bb813 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.zh-Hant.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.zh-Hant.xlf @@ -409,7 +409,7 @@ F# Interactive - F# Interactive + F# 互動 @@ -459,7 +459,7 @@ F# Interactive - F# Interactive + F# 互動 @@ -509,7 +509,7 @@ Change path and command line arguments passed to the F# Interactive - 變更傳遞到 F# Interactive 的路徑和命令列引數 + 變更傳遞到 F# 互動的路徑和命令列引數 diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.de.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.de.xlf index 88fafb076b2..b106a3db12d 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.de.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.de.xlf @@ -44,7 +44,7 @@ Target F# runtime: - F#-Ziellaufzeit: + F#-Zielruntime: diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.cs.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.cs.xlf index 860555f3440..5340031907e 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.cs.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.cs.xlf @@ -295,7 +295,7 @@ Vyberte prosím platnou cestu ke složce. Solution Explorer), and make changes on the Application tab. - průzkumníku řešení), a proveďte změny v kartě Aplikace. + Průzkumníku řešení), a proveďte změny v kartě Aplikace. diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.de.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.de.xlf index 65b4328fdc2..2ca4bd450e9 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.de.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.de.xlf @@ -355,7 +355,7 @@ Wählen Sie einen gültigen Ordnerpfad aus. None - NONE + Keine @@ -2148,12 +2148,12 @@ CONSIDER: get this from CodeDom The file '{0}' already exists. Do you want to replace it? - Die Datei "{0}" ist bereits vorhanden. Möchten Sie sie ersetzen? + Die Datei "{0}" ist bereits vorhanden. Möchten Sie sie ersetzen? {0} = full file path and name The following files already exist. Do you want to replace them? - Die folgenden Dateien sind bereits vorhanden. Möchten Sie sie ersetzen? + Die folgenden Dateien sind bereits vorhanden. Möchten Sie sie ersetzen? diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.es.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.es.xlf index 1153755c3dd..394481ad696 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.es.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.es.xlf @@ -39,7 +39,7 @@ Debug - depurar + Depurar @@ -365,7 +365,7 @@ Seleccione una ruta de acceso de carpeta válida. Error - Fehler + Error @@ -614,7 +614,7 @@ Error: Error - Fehler + Error diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.fr.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.fr.xlf index cd60e9f07e9..821545638e2 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.fr.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.fr.xlf @@ -39,7 +39,7 @@ Debug - déboguer + Déboguer diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.ja.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.ja.xlf index bdb896a5c83..c0221174d97 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.ja.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.ja.xlf @@ -2930,7 +2930,7 @@ app.config ファイルでの新しい値は '{1}' です The application will fail to run in the selected zone because of this requested elevated permission. Click the help link above for more info. - この引き上げられたアクセス許可が原因で、選択されたゾーンでのアプリケーションの実行は失敗します。詳細については、ヘルプ リンクをクリックしてください。 + 要求されたこの引き上げられたアクセス許可が原因で、選択されたゾーンでのアプリケーションの実行は失敗します。詳細については、ヘルプ リンクをクリックしてください。 diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pl.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pl.xlf index 73bef853b9f..f912b6b4c78 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pl.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pl.xlf @@ -59,7 +59,7 @@ Build - Kompiluj + Kompilacja diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pt-BR.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pt-BR.xlf index 3e8a1693485..5a2b75dce09 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pt-BR.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.pt-BR.xlf @@ -1969,7 +1969,7 @@ CONSIDER: get this from CodeDom Portable Network Graphics - formato PNG + Formato PNG Friendly Image types @@ -2063,7 +2063,7 @@ CONSIDER: get this from CodeDom Portable Network Graphics - formato PNG + Formato PNG # File dialog filters # # E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources @@ -2072,7 +2072,7 @@ CONSIDER: get this from CodeDom Graphics Interchange Format - Formato de intercâmbio de gráficos + Graphics Interchange Format # File dialog filters # # E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.de.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.de.xlf index 584143c8116..1b8578d6fe3 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.de.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.de.xlf @@ -9,7 +9,7 @@ Unable to find a code generator (CodeDomProvider). - Code-Generator (CodeDomProvider) kann nicht gefunden werden. + Es wurde kein Code-Generator (CodeDomProvider) gefunden. @@ -259,7 +259,7 @@ The requested operation is not valid while an asynchronous operation is in progress. - Der angeforderte Vorgang ist unzulässig, während ein asynchroner Vorgang läuft. + Der angeforderte Vorgang ist unzulässig, während ein asynchroner Vorgang ausgeführt wird. diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.ja.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.ja.xlf index 76999ca3e0b..def3cf20486 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.ja.xlf +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.ja.xlf @@ -279,7 +279,7 @@ The file is already opened in an incompatible editor. - ファイルは、互換性のないエディターで既に開かれています。 + ファイルが、互換性のないエディターで既に開かれています。 diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.de.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.de.xlf index 7178a91c605..989b2031fee 100644 --- a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.de.xlf +++ b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.de.xlf @@ -24,7 +24,7 @@ Misc - Verschiedenes + Verschiedene diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.pt-BR.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.pt-BR.xlf index b3f7cfc54ad..6099d3d9fda 100644 --- a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.pt-BR.xlf +++ b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.pt-BR.xlf @@ -4,17 +4,17 @@ 64-bit F# Interactive - F# Interative de 64 bits + F# Interativo de 64 bits If set to true, and the current machine is 64-bit, then run F# Interactive as a 64-bit process. (Otherwise, F# Interactive is a 32-bit process.) - Se estiver definido como true, e o computador atual for 64 bits, execute o F# Interactive como um processo de 64 bits. (Caso contrário, o F# Interactive será um processo de 32 bits.) + Se estiver definido como true, e o computador atual for 64 bits, execute o F# Interativo como um processo de 64 bits. (Caso contrário, o F# Interactive será um processo de 32 bits.) F# Interactive options - Opções interativas F# + Opções do F# Interativo @@ -34,7 +34,7 @@ Prevents referenced assemblies from being locked by the F# Interactive process. - Impede que os assemblies referenciados sejam bloqueados pelo processo de F# interativo. + Impede que os assemblies referenciados sejam bloqueados pelo processo do F# Interativo. diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.zh-Hant.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.zh-Hant.xlf index 3b60c892d47..dd4f7af3268 100644 --- a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.zh-Hant.xlf +++ b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.zh-Hant.xlf @@ -4,7 +4,7 @@ 64-bit F# Interactive - 64 位元 F# Interactive + 64 位元 F# 互動 @@ -19,7 +19,7 @@ Additional command line arguments passed to the F# Interactive executable by Visual Studio. (optimization and debug flags are ignored if script debugging is enabled) - 由 Visual Studio 額外傳遞給 F# Interactive 可執行檔的命令列引數。(若啟用指令碼偵錯,則會忽略最佳化及偵錯旗標) + 由 Visual Studio 額外傳遞給 F# 互動可執行檔的命令列引數。(若啟用指令碼偵錯,則會忽略最佳化及偵錯旗標) @@ -34,7 +34,7 @@ Prevents referenced assemblies from being locked by the F# Interactive process. - 避免參考的組件遭 F# 互動式處理序封鎖。 + 避免參考的組件遭 F# 互動處理序封鎖。 diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.pt-BR.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.pt-BR.xlf index e8cc3f22c76..a3d2f3edb35 100644 --- a/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.pt-BR.xlf +++ b/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.pt-BR.xlf @@ -34,7 +34,7 @@ Could not find fsi.exe, the F# Interactive executable.\nThis file does not exist:\n\n{0}\n - Não foi possível encontrar fsi.exe, o Executável interativo F#.\nEste arquivo não existe:\n\n{0}\n + Não foi possível encontrar fsi.exe, o executável do F# Interativo.\nEste arquivo não existe:\n\n{0}\n diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.zh-Hant.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.zh-Hant.xlf index b891d6630c1..ba06ff32813 100644 --- a/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.zh-Hant.xlf +++ b/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.zh-Hant.xlf @@ -29,12 +29,12 @@ F# Interactive - F# Interactive + F# 互動 Could not find fsi.exe, the F# Interactive executable.\nThis file does not exist:\n\n{0}\n - 找不到 F# Interactive 可執行檔 fsi.exe。\n這個檔案不存在:\n\n{0}\n + 找不到 F# 互動可執行檔 fsi.exe。\n這個檔案不存在:\n\n{0}\n diff --git a/vsintegration/tests/UnitTests/CompletionProviderTests.fs b/vsintegration/tests/UnitTests/CompletionProviderTests.fs index 91339ffde4a..97ea7cbeff8 100644 --- a/vsintegration/tests/UnitTests/CompletionProviderTests.fs +++ b/vsintegration/tests/UnitTests/CompletionProviderTests.fs @@ -444,6 +444,14 @@ List(). "ExtensionMeth"] VerifyCompletionListExactly(fileContents, "List().", expected) +[] +let ``Completion for open contains namespaces and static types``() = + let fileContents = """ +open System.Ma +""" + let expected = ["Management"; "Math"] // both namespace and static type + VerifyCompletionList(fileContents, "System.Ma", expected, []) + [] let ``No completion on type name at declaration site``() = let fileContents = """ diff --git a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Completion.fs b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Completion.fs index 9e58d24c1f1..a1ea76e7172 100644 --- a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Completion.fs +++ b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Completion.fs @@ -3639,8 +3639,8 @@ let x = query { for bbbb in abbbbc(*D0*) do AssertAutoCompleteContains [ "open System." ] "." // marker - [ "Collections" ] // should contain (namespace) - [ "Console" ] // should not contain (type) + [ "Collections"; "Console" ] // should contain (namespace, static type) + [ "Int32" ] // should not contain (non-static type) [] member public this.``OpenNamespaceOrModule.CompletionOnlyContainsNamespaceOrModule.Case2``() =