|
| 1 | +namespace ProviderImplementation |
| 2 | + |
| 3 | +open System |
| 4 | +open System.IO |
| 5 | +open FSharp.Core.CompilerServices |
| 6 | +open ProviderImplementation |
| 7 | +open ProviderImplementation.ProvidedTypes |
| 8 | +open ProviderImplementation.ProviderHelpers |
| 9 | +open FSharp.Data |
| 10 | +open FSharp.Data.Runtime |
| 11 | +open FSharp.Data.Runtime.BaseTypes |
| 12 | +open FSharp.Data.Runtime.StructuralTypes |
| 13 | +open FSharp.Data.Runtime.StructuralInference |
| 14 | +open System.Net |
| 15 | + |
| 16 | +// ---------------------------------------------------------------------------------------------- |
| 17 | + |
| 18 | +#nowarn "10001" |
| 19 | + |
| 20 | +[<TypeProvider>] |
| 21 | +type public YamlProvider(cfg: TypeProviderConfig) as this = |
| 22 | + inherit |
| 23 | + DisposableTypeProviderForNamespaces(cfg, assemblyReplacementMap = [ "FSharp.Data.DesignTime", "FSharp.Data" ]) |
| 24 | + |
| 25 | + // Generate namespace and type 'FSharp.Data.YamlProvider' |
| 26 | + do AssemblyResolver.init () |
| 27 | + let asm = System.Reflection.Assembly.GetExecutingAssembly() |
| 28 | + let ns = "FSharp.Data" |
| 29 | + |
| 30 | + let yamlProvTy = |
| 31 | + ProvidedTypeDefinition(asm, ns, "YamlProvider", None, hideObjectMethods = true, nonNullable = true) |
| 32 | + |
| 33 | + let buildTypes (typeName: string) (args: obj[]) = |
| 34 | + |
| 35 | + // Enable TLS 1.2 for samples requested through https. |
| 36 | + ServicePointManager.SecurityProtocol <- ServicePointManager.SecurityProtocol ||| SecurityProtocolType.Tls12 |
| 37 | + |
| 38 | + // Generate the required type |
| 39 | + let tpType = |
| 40 | + ProvidedTypeDefinition(asm, ns, typeName, None, hideObjectMethods = true, nonNullable = true) |
| 41 | + |
| 42 | + let sample = args.[0] :?> string |
| 43 | + let sampleIsList = args.[1] :?> bool |
| 44 | + let rootName = args.[2] :?> string |
| 45 | + |
| 46 | + let rootName = |
| 47 | + if String.IsNullOrWhiteSpace rootName then |
| 48 | + "Root" |
| 49 | + else |
| 50 | + NameUtils.singularize rootName |
| 51 | + |
| 52 | + let cultureStr = args.[3] :?> string |
| 53 | + let encodingStr = args.[4] :?> string |
| 54 | + let resolutionFolder = args.[5] :?> string |
| 55 | + let resource = args.[6] :?> string |
| 56 | + let inferTypesFromValues = args.[7] :?> bool |
| 57 | + let preferDictionaries = args.[8] :?> bool |
| 58 | + let inferenceMode = args.[9] :?> InferenceMode |
| 59 | + let preferDateOnly = args.[10] :?> bool |
| 60 | + let useOriginalNames = args.[11] :?> bool |
| 61 | + |
| 62 | + let inferenceMode = |
| 63 | + InferenceMode'.FromPublicApi(inferenceMode, inferTypesFromValues) |
| 64 | + |
| 65 | + let cultureInfo = TextRuntime.GetCulture cultureStr |
| 66 | + let unitsOfMeasureProvider = ProviderHelpers.unitsOfMeasureProvider |
| 67 | + |
| 68 | + let getSpec _ value = |
| 69 | + |
| 70 | + let inferedType = |
| 71 | + use _holder = IO.logTime "Inference" sample |
| 72 | + |
| 73 | + // Parse YAML sample into JsonValue, then use JSON inference |
| 74 | + let rawInfered = |
| 75 | + let samples = |
| 76 | + use _holder = IO.logTime "Parsing" sample |
| 77 | + |
| 78 | + if sampleIsList then |
| 79 | + // If SampleIsList, parse as a YAML sequence or multiple documents |
| 80 | + match YamlDocument.ParseToJsonValue value with |
| 81 | + | JsonValue.Array items -> items |
| 82 | + | single -> [| single |] |
| 83 | + else |
| 84 | + [| YamlDocument.ParseToJsonValue value |] |
| 85 | + |
| 86 | + samples |
| 87 | + |> Array.map (fun sampleJson -> |
| 88 | + JsonInference.inferType unitsOfMeasureProvider inferenceMode cultureInfo "" sampleJson) |
| 89 | + |> Array.fold (StructuralInference.subtypeInfered false) InferedType.Top |
| 90 | + |
| 91 | +#if NET6_0_OR_GREATER |
| 92 | + if preferDateOnly && ProviderHelpers.runtimeSupportsNet6Types cfg.RuntimeAssembly then |
| 93 | + rawInfered |
| 94 | + else |
| 95 | + StructuralInference.downgradeNet6Types rawInfered |
| 96 | +#else |
| 97 | + rawInfered |
| 98 | +#endif |
| 99 | + |
| 100 | + use _holder = IO.logTime "TypeGeneration" sample |
| 101 | + |
| 102 | + let ctx = |
| 103 | + JsonGenerationContext.Create( |
| 104 | + cultureStr, |
| 105 | + tpType, |
| 106 | + unitsOfMeasureProvider, |
| 107 | + inferenceMode, |
| 108 | + ?preferDictionaries = Some preferDictionaries, |
| 109 | + ?useOriginalNames = Some useOriginalNames |
| 110 | + ) |
| 111 | + |
| 112 | + let result = JsonTypeBuilder.generateJsonType ctx false false rootName inferedType |
| 113 | + |
| 114 | + { GeneratedType = tpType |
| 115 | + RepresentationType = result.ConvertedType |
| 116 | + CreateFromTextReader = fun reader -> result.Convert <@@ YamlDocument.Create(%reader) @@> |
| 117 | + CreateListFromTextReader = Some(fun reader -> result.Convert <@@ YamlDocument.CreateList(%reader) @@>) |
| 118 | + CreateFromTextReaderForSampleList = fun reader -> result.Convert <@@ YamlDocument.CreateList(%reader) @@> |
| 119 | + CreateFromValue = |
| 120 | + Some(typeof<JsonValue>, (fun value -> result.Convert <@@ YamlDocument.Create(%value, "") @@>)) } |
| 121 | + |
| 122 | + let source = if sampleIsList then SampleList sample else Sample sample |
| 123 | + |
| 124 | + generateType "YAML" source getSpec this cfg encodingStr resolutionFolder resource typeName None |
| 125 | + |
| 126 | + // Add static parameter that specifies the API we want to get (compile-time) |
| 127 | + let parameters = |
| 128 | + [ ProvidedStaticParameter("Sample", typeof<string>, parameterDefaultValue = "") |
| 129 | + ProvidedStaticParameter("SampleIsList", typeof<bool>, parameterDefaultValue = false) |
| 130 | + ProvidedStaticParameter("RootName", typeof<string>, parameterDefaultValue = "Root") |
| 131 | + ProvidedStaticParameter("Culture", typeof<string>, parameterDefaultValue = "") |
| 132 | + ProvidedStaticParameter("Encoding", typeof<string>, parameterDefaultValue = "") |
| 133 | + ProvidedStaticParameter("ResolutionFolder", typeof<string>, parameterDefaultValue = "") |
| 134 | + ProvidedStaticParameter("EmbeddedResource", typeof<string>, parameterDefaultValue = "") |
| 135 | + ProvidedStaticParameter("InferTypesFromValues", typeof<bool>, parameterDefaultValue = true) |
| 136 | + ProvidedStaticParameter("PreferDictionaries", typeof<bool>, parameterDefaultValue = false) |
| 137 | + ProvidedStaticParameter( |
| 138 | + "InferenceMode", |
| 139 | + typeof<InferenceMode>, |
| 140 | + parameterDefaultValue = InferenceMode.BackwardCompatible |
| 141 | + ) |
| 142 | + ProvidedStaticParameter("PreferDateOnly", typeof<bool>, parameterDefaultValue = false) |
| 143 | + ProvidedStaticParameter("UseOriginalNames", typeof<bool>, parameterDefaultValue = false) ] |
| 144 | + |
| 145 | + let helpText = |
| 146 | + """<summary>Typed representation of a YAML document.</summary> |
| 147 | + <param name='Sample'>Location of a YAML sample file or a string containing a sample YAML document.</param> |
| 148 | + <param name='SampleIsList'>If true, the sample should be a YAML sequence (list) and each element is used as an individual sample for type inference.</param> |
| 149 | + <param name='RootName'>The name to be used for the root type. Defaults to `Root`.</param> |
| 150 | + <param name='Culture'>The culture used for parsing numbers and dates. Defaults to the invariant culture.</param> |
| 151 | + <param name='Encoding'>The encoding used to read the sample. You can specify either the character set name or the codepage number. Defaults to UTF8 for files, and to ISO-8859-1 for HTTP requests, unless `charset` is specified in the `Content-Type` response header.</param> |
| 152 | + <param name='ResolutionFolder'>A directory that is used when resolving relative file references (at design time and in hosted execution).</param> |
| 153 | + <param name='EmbeddedResource'>When specified, the type provider first attempts to load the sample from the specified resource |
| 154 | + (e.g. 'MyCompany.MyAssembly, resource_name.yaml'). This is useful when exposing types generated by the type provider.</param> |
| 155 | + <param name='InferTypesFromValues'> |
| 156 | + This parameter is deprecated. Please use InferenceMode instead. |
| 157 | + If true, turns on additional type inference from values. |
| 158 | + (e.g. type inference infers string values such as "123" as ints and values constrained to 0 and 1 as booleans.)</param> |
| 159 | + <param name='PreferDictionaries'>If true, YAML mappings are interpreted as dictionaries when the names of all the fields are inferred (by type inference rules) into the same non-string primitive type.</param> |
| 160 | + <param name='InferenceMode'>Possible values: |
| 161 | + | NoInference -> Inference is disabled. All values are inferred as the most basic type permitted for the value (i.e. string or number or bool). |
| 162 | + | ValuesOnly -> Types of values are inferred from the Sample. This is the default. |
| 163 | + | ValuesAndInlineSchemasHints -> Types of values are inferred from both values and inline schemas. Inline schemas are special string values that can define a type and/or unit of measure. |
| 164 | + | ValuesAndInlineSchemasOverrides -> Same as ValuesAndInlineSchemasHints, but value inferred types are ignored when an inline schema is present. |
| 165 | + </param> |
| 166 | + <param name='PreferDateOnly'>When true on .NET 6+, date-only strings (e.g. "2023-01-15") are inferred as DateOnly and time-only strings as TimeOnly. Defaults to false for backward compatibility.</param> |
| 167 | + <param name='UseOriginalNames'>When true, YAML key names are used as-is for generated property names instead of being normalized to PascalCase. Defaults to false.</param>""" |
| 168 | + |
| 169 | + do yamlProvTy.AddXmlDoc helpText |
| 170 | + do yamlProvTy.DefineStaticParameters(parameters, buildTypes) |
| 171 | + |
| 172 | + // Register the main type with F# compiler |
| 173 | + do this.AddNamespace(ns, [ yamlProvTy ]) |
0 commit comments