-
-
Notifications
You must be signed in to change notification settings - Fork 517
/
CSharpTypeResolver.cs
304 lines (251 loc) · 11.6 KB
/
CSharpTypeResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//-----------------------------------------------------------------------
// <copyright file="CSharpTypeResolver.cs" company="NJsonSchema">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System;
using System.Linq;
namespace NJsonSchema.CodeGeneration.CSharp
{
/// <summary>Manages the generated types and converts JSON types to CSharp types. </summary>
public class CSharpTypeResolver : TypeResolverBase
{
/// <summary>Initializes a new instance of the <see cref="CSharpTypeResolver"/> class.</summary>
/// <param name="settings">The generator settings.</param>
public CSharpTypeResolver(CSharpGeneratorSettings settings)
: this(settings, null)
{
}
/// <summary>Initializes a new instance of the <see cref="CSharpTypeResolver"/> class.</summary>
/// <param name="settings">The generator settings.</param>
/// <param name="exceptionSchema">The exception type schema.</param>
public CSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema? exceptionSchema)
: base(settings)
{
Settings = settings;
ExceptionSchema = exceptionSchema;
}
/// <summary>Gets the exception schema.</summary>
public JsonSchema? ExceptionSchema { get; }
/// <summary>Gets the generator settings.</summary>
public CSharpGeneratorSettings Settings { get; }
/// <summary>Resolves and possibly generates the specified schema.</summary>
/// <param name="schema">The schema.</param>
/// <param name="isNullable">Specifies whether the given type usage is nullable.</param>
/// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
/// <returns>The type name.</returns>
public override string Resolve(JsonSchema schema, bool isNullable, string? typeNameHint)
{
return Resolve(schema, isNullable, typeNameHint, true);
}
/// <summary>Resolves and possibly generates the specified schema.</summary>
/// <param name="schema">The schema.</param>
/// <param name="isNullable">Specifies whether the given type usage is nullable.</param>
/// <param name="typeNameHint">The type name hint to use when generating the type and the type name is missing.</param>
/// <param name="checkForExistingSchema">Checks whether a named schema is already registered.</param>
/// <returns>The type name.</returns>
public string Resolve(JsonSchema schema, bool isNullable, string? typeNameHint, bool checkForExistingSchema)
{
if (schema == null)
{
throw new ArgumentNullException(nameof(schema));
}
schema = GetResolvableSchema(schema);
if (schema == ExceptionSchema)
{
return "System.Exception";
}
// Primitive schemas (no new type)
if (Settings.GenerateOptionalPropertiesAsNullable &&
schema is JsonSchemaProperty property &&
!property.IsRequired)
{
isNullable = true;
}
var markAsNullableType = Settings.GenerateNullableReferenceTypes && isNullable;
if (schema.ActualTypeSchema.IsAnyType &&
schema.ActualDiscriminator == null &&
schema.InheritedSchema == null && // not in inheritance hierarchy
schema.AllOf.Count == 0 &&
!Types.ContainsKey(schema) &&
!schema.HasReference)
{
return markAsNullableType ? Settings.AnyType + "?" : Settings.AnyType;
}
var type = schema.ActualTypeSchema.Type;
if (type == JsonObjectType.None && schema.ActualTypeSchema.IsEnumeration)
{
type = schema.ActualTypeSchema.Enumeration.All(v => v is int)
? JsonObjectType.Integer
: JsonObjectType.String;
}
if (type.IsNumber())
{
return ResolveNumber(schema.ActualTypeSchema, isNullable);
}
if (type.IsInteger() && !schema.ActualTypeSchema.IsEnumeration)
{
return ResolveInteger(schema.ActualTypeSchema, isNullable, typeNameHint);
}
if (type.IsBoolean())
{
return ResolveBoolean(isNullable);
}
var nullableReferenceType = markAsNullableType ? "?" : string.Empty;
if (schema.IsBinary)
{
return "byte[]" + nullableReferenceType;
}
if (type.IsString() && !schema.ActualTypeSchema.IsEnumeration)
{
return ResolveString(schema.ActualTypeSchema, isNullable, typeNameHint);
}
// Type generating schemas
if (schema.Type.IsArray())
{
return ResolveArrayOrTuple(schema) + nullableReferenceType;
}
if (schema.IsDictionary)
{
return ResolveDictionary(schema) + nullableReferenceType;
}
if (schema.ActualTypeSchema.IsEnumeration)
{
return GetOrGenerateTypeName(schema, typeNameHint) + (isNullable ? "?" : string.Empty);
}
return GetOrGenerateTypeName(schema, typeNameHint) + nullableReferenceType;
}
/// <summary>Checks whether the given schema should generate a type.</summary>
/// <param name="schema">The schema.</param>
/// <returns>True if the schema should generate a type.</returns>
protected override bool IsDefinitionTypeSchema(JsonSchema schema)
{
if ((schema.IsDictionary && !Settings.InlineNamedDictionaries) ||
(schema.IsArray && !Settings.InlineNamedArrays) ||
(schema.IsTuple && !Settings.InlineNamedTuples))
{
return true;
}
return base.IsDefinitionTypeSchema(schema);
}
private string ResolveString(JsonSchema schema, bool isNullable, string? typeNameHint)
{
var nullableReferenceType = Settings.GenerateNullableReferenceTypes && isNullable ? "?" : string.Empty;
if (schema.Format == JsonFormatStrings.Date)
{
return isNullable && Settings.DateType?.ToLowerInvariant() != "string"
? Settings.DateType + "?"
: Settings.DateType + nullableReferenceType;
}
if (schema.Format == JsonFormatStrings.DateTime)
{
return isNullable && Settings.DateTimeType?.ToLowerInvariant() != "string"
? Settings.DateTimeType + "?"
: Settings.DateTimeType + nullableReferenceType;
}
if (schema.Format == JsonFormatStrings.Time)
{
return isNullable && Settings.TimeType?.ToLowerInvariant() != "string"
? Settings.TimeType + "?"
: Settings.TimeType + nullableReferenceType;
}
if (schema.Format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return isNullable && Settings.TimeSpanType?.ToLowerInvariant() != "string"
? Settings.TimeSpanType + "?"
: Settings.TimeSpanType + nullableReferenceType;
}
if (schema.Format == JsonFormatStrings.Uri)
{
return "System.Uri" + nullableReferenceType;
}
#pragma warning disable 618 // used to resolve type from schemas generated with previous version of the library
if (schema.Format == JsonFormatStrings.Guid || schema.Format == JsonFormatStrings.Uuid)
{
return isNullable ? "System.Guid?" : "System.Guid";
}
if (schema.Format == JsonFormatStrings.Base64 || schema.Format == JsonFormatStrings.Byte)
{
return "byte[]" + nullableReferenceType;
}
#pragma warning restore 618
return "string" + nullableReferenceType;
}
private static string ResolveBoolean(bool isNullable)
{
return isNullable ? "bool?" : "bool";
}
private static string ResolveInteger(JsonSchema schema, bool isNullable, string? typeNameHint)
{
if (schema.Format == JsonFormatStrings.Byte)
{
return isNullable ? "byte?" : "byte";
}
if (schema.Format == JsonFormatStrings.Long || schema.Format == "long")
{
return isNullable ? "long?" : "long";
}
if (schema.Format == JsonFormatStrings.Long || schema.Format == "long")
{
return isNullable ? "long?" : "long";
}
if (schema.Format == JsonFormatStrings.ULong || schema.Format == "ulong")
{
return isNullable ? "ulong?" : "ulong";
}
if (schema.Minimum.HasValue || schema.Maximum.HasValue)
{
if (string.IsNullOrEmpty(schema.Format) && schema.Type == JsonObjectType.Integer)
{
// If min/max is defined and not compatible with int32 => use int64
if (schema.Minimum < int.MinValue ||
schema.Minimum > int.MaxValue ||
schema.Maximum < int.MinValue ||
schema.Maximum > int.MaxValue)
{
return isNullable ? "long?" : "long";
}
}
}
return isNullable ? "int?" : "int";
}
private string ResolveNumber(JsonSchema schema, bool isNullable)
{
var numberType = schema.Format switch
{
JsonFormatStrings.Decimal => Settings.NumberDecimalType,
JsonFormatStrings.Double => Settings.NumberDoubleType,
JsonFormatStrings.Float => Settings.NumberFloatType,
_ => Settings.NumberType
};
if (string.IsNullOrWhiteSpace(numberType))
numberType = "double";
return isNullable ? numberType + "?" : numberType;
}
private string ResolveArrayOrTuple(JsonSchema schema)
{
if (schema.Item != null)
{
var itemTypeNameHint = (schema as JsonSchemaProperty)?.Name;
var itemType = Resolve(schema.Item, schema.Item.IsNullable(Settings.SchemaType), itemTypeNameHint);
return $"{Settings.ArrayType}<{itemType}>";
}
if (schema.Items != null && schema.Items.Count > 0)
{
var tupleTypes = schema.Items
.Select(i => Resolve(i, i.IsNullable(Settings.SchemaType), null))
.ToArray();
return $"System.Tuple<{string.Join(", ", tupleTypes)}>";
}
return Settings.ArrayType + "<object>";
}
private string ResolveDictionary(JsonSchema schema)
{
var valueType = ResolveDictionaryValueType(schema, "object");
var keyType = ResolveDictionaryKeyType(schema, "string");
return $"{Settings.DictionaryType}<{keyType}, {valueType}>";
}
}
}