-
Notifications
You must be signed in to change notification settings - Fork 409
/
Copy pathjson_key_utils.dart
294 lines (261 loc) · 9.32 KB
/
json_key_utils.dart
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
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:build/build.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:source_gen/source_gen.dart';
import 'package:source_helper/source_helper.dart';
import 'json_literal_generator.dart';
import 'shared_checkers.dart';
import 'type_helpers/config_types.dart';
import 'utils.dart';
final _jsonKeyExpando = Expando<Map<ClassConfig, KeyConfig>>();
KeyConfig jsonKeyForField(FieldElement field, ClassConfig classAnnotation) =>
(_jsonKeyExpando[field] ??= Map.identity())[classAnnotation] ??=
_from(field, classAnnotation);
KeyConfig _from(FieldElement element, ClassConfig classAnnotation) {
// If an annotation exists on `element` the source is a 'real' field.
// If the result is `null`, check the getter – it is a property.
// TODO: setters: github.com/google/json_serializable.dart/issues/24
final obj = jsonKeyAnnotation(element);
final ctorParamDefault = classAnnotation.ctorParamDefaults[element.name];
if (obj.isNull) {
return _populateJsonKey(
classAnnotation,
element,
defaultValue: ctorParamDefault,
ignore: classAnnotation.ignoreUnannotated,
);
}
/// Returns a literal value for [dartObject] if possible, otherwise throws
/// an [InvalidGenerationSourceError] using [typeInformation] to describe
/// the unsupported type.
Object? literalForObject(
String fieldName,
DartObject dartObject,
Iterable<String> typeInformation,
) {
if (dartObject.isNull) {
return null;
}
final reader = ConstantReader(dartObject);
String? badType;
if (reader.isSymbol) {
badType = 'Symbol';
} else if (reader.isType) {
badType = 'Type';
} else if (dartObject.type is FunctionType) {
// TODO: Support calling function for the default value?
badType = 'Function';
} else if (!reader.isLiteral) {
badType = dartObject.type!.element!.name;
}
if (badType != null) {
badType = typeInformation.followedBy([badType]).join(' > ');
throwUnsupported(
element,
'`$fieldName` is `$badType`, it must be a literal.',
);
}
if (reader.isDouble || reader.isInt || reader.isString || reader.isBool) {
return reader.literalValue;
}
if (reader.isList) {
return [
for (var e in reader.listValue)
literalForObject(fieldName, e, [
...typeInformation,
'List',
])
];
}
if (reader.isSet) {
return {
for (var e in reader.setValue)
literalForObject(fieldName, e, [
...typeInformation,
'Set',
])
};
}
if (reader.isMap) {
final mapTypeInformation = [
...typeInformation,
'Map',
];
return reader.mapValue.map(
(k, v) => MapEntry(
literalForObject(fieldName, k!, mapTypeInformation),
literalForObject(fieldName, v!, mapTypeInformation),
),
);
}
badType = typeInformation.followedBy(['$dartObject']).join(' > ');
throwUnsupported(
element,
'The provided value is not supported: $badType. '
'This may be an error in package:json_serializable. '
'Please rerun your build with `--verbose` and file an issue.',
);
}
/// Returns a literal object representing the value of [fieldName] in [obj].
///
/// If [mustBeEnum] is `true`, throws an [InvalidGenerationSourceError] if
/// either the annotated field is not an `enum` or `List` or if the value in
/// [fieldName] is not an `enum` value.
String? _annotationValue(String fieldName, {bool mustBeEnum = false}) {
final annotationValue = obj.read(fieldName);
late final DartType annotationType;
final enumFields = annotationValue.isNull
? null
: iterateEnumFields(annotationType = annotationValue.objectValue.type!);
if (enumFields != null) {
if (mustBeEnum) {
late DartType targetEnumType;
if (element.type.isEnum) {
targetEnumType = element.type;
} else if (coreIterableTypeChecker.isAssignableFromType(element.type)) {
targetEnumType = coreIterableGenericType(element.type);
} else {
throwUnsupported(
element,
'`$fieldName` can only be set on fields of type enum or on '
'Iterable, List, or Set instances of an enum type.',
);
}
if (_nullAsUnknownChecker.isExactlyType(annotationType)) {
return jsonKeyNullForUndefinedEnumValueFieldName;
} else if (!_interfaceTypesEqual(annotationType, targetEnumType)) {
throwUnsupported(
element,
'`$fieldName` has type '
'`${targetEnumType.getDisplayString(withNullability: false)}`, but '
'the provided unknownEnumValue is of type '
'`${annotationType.getDisplayString(withNullability: false)}`.',
);
}
}
if (_nullAsUnknownChecker.isExactlyType(annotationType)) {
throw InvalidGenerationSourceError(
'`$jsonKeyNullForUndefinedEnumValueFieldName` cannot be used with '
'`JsonKey.defaultValue`.',
element: element,
);
}
final enumValueNames =
enumFields.map((p) => p.name).toList(growable: false);
final enumValueName = enumValueForDartObject<String>(
annotationValue.objectValue, enumValueNames, (n) => n);
return '${annotationType.element!.name}'
'.$enumValueName';
} else {
final defaultValueLiteral = annotationValue.isNull
? null
: literalForObject(fieldName, annotationValue.objectValue, []);
if (defaultValueLiteral == null) {
return null;
}
if (mustBeEnum) {
throwUnsupported(
element,
'The value provided for `$fieldName` must be a matching enum.',
);
}
return jsonLiteralAsDart(defaultValueLiteral);
}
}
final defaultValue = _annotationValue('defaultValue');
if (defaultValue != null && ctorParamDefault != null) {
if (defaultValue == ctorParamDefault) {
log.info(
'The default value `$defaultValue` for `${element.name}` is defined '
'twice in the constructor and in the `JsonKey.defaultValue`.',
);
} else {
log.warning(
'The constructor parameter for `${element.name}` has a default value '
'`$ctorParamDefault`, but the `JsonKey.defaultValue` value '
'`$defaultValue` will be used for missing or `null` values in JSON '
'decoding.',
);
}
}
String? readValueFunctionName;
final readValue = obj.read('readValue');
if (!readValue.isNull) {
readValueFunctionName =
readValue.objectValue.toFunctionValue()!.qualifiedName;
}
return _populateJsonKey(
classAnnotation,
element,
defaultValue: defaultValue ?? ctorParamDefault,
disallowNullValue: obj.read('disallowNullValue').literalValue as bool?,
ignore: obj.read('ignore').literalValue as bool?,
includeIfNull: obj.read('includeIfNull').literalValue as bool?,
name: obj.read('name').literalValue as String?,
readValueFunctionName: readValueFunctionName,
required: obj.read('required').literalValue as bool?,
unknownEnumValue: _annotationValue('unknownEnumValue', mustBeEnum: true),
extra: obj.read('extra').literalValue as bool?,
);
}
KeyConfig _populateJsonKey(
ClassConfig classAnnotation,
FieldElement element, {
required String? defaultValue,
bool? disallowNullValue,
bool? ignore,
bool? includeIfNull,
String? name,
String? readValueFunctionName,
bool? required,
String? unknownEnumValue,
bool? extra,
}) {
if (disallowNullValue == true) {
if (includeIfNull == true) {
throwUnsupported(
element,
'Cannot set both `disallowNullValue` and `includeIfNull` to `true`. '
'This leads to incompatible `toJson` and `fromJson` behavior.');
}
}
return KeyConfig(
defaultValue: defaultValue,
disallowNullValue: disallowNullValue ?? false,
ignore: ignore ?? false,
includeIfNull: _includeIfNull(
includeIfNull, disallowNullValue, classAnnotation.includeIfNull),
name: name ?? encodedFieldName(classAnnotation.fieldRename, element.name),
readValueFunctionName: readValueFunctionName,
required: required ?? false,
unknownEnumValue: unknownEnumValue,
extra: extra ?? false,
);
}
bool _includeIfNull(
bool? keyIncludeIfNull,
bool? keyDisallowNullValue,
bool classIncludeIfNull,
) {
if (keyDisallowNullValue == true) {
assert(keyIncludeIfNull != true);
return false;
}
return keyIncludeIfNull ?? classIncludeIfNull;
}
bool _interfaceTypesEqual(DartType a, DartType b) {
if (a is InterfaceType && b is InterfaceType) {
// Handle nullability case. Pretty sure this is fine for enums.
return a.element == b.element;
}
return a == b;
}
const jsonKeyNullForUndefinedEnumValueFieldName =
'JsonKey.nullForUndefinedEnumValue';
final _nullAsUnknownChecker =
TypeChecker.fromRuntime(JsonKey.nullForUndefinedEnumValue.runtimeType);