-
Notifications
You must be signed in to change notification settings - Fork 387
/
json_converter_helper.dart
334 lines (282 loc) · 9.02 KB
/
json_converter_helper.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// 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:collection/collection.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:source_gen/source_gen.dart';
import 'package:source_helper/source_helper.dart';
import '../lambda_result.dart';
import '../shared_checkers.dart';
import '../type_helper.dart';
import '../utils.dart';
/// A [TypeHelper] that supports classes annotated with implementations of
/// [JsonConverter].
class JsonConverterHelper extends TypeHelper<TypeHelperContextWithConfig> {
const JsonConverterHelper();
@override
Object? serialize(
DartType targetType,
String expression,
TypeHelperContextWithConfig context,
) {
final converter = _typeConverter(targetType, context);
if (converter == null) {
return null;
}
if (!converter.fieldType.isNullableType && targetType.isNullableType) {
const converterToJsonName = r'_$JsonConverterToJson';
context.addMember('''
Json? $converterToJsonName<Json, Value>(
Value? value,
Json? Function(Value value) toJson,
) => ${ifNullOrElse('value', 'null', 'toJson(value)')};
''');
return _nullableJsonConverterLambdaResult(
converter,
name: converterToJsonName,
targetType: targetType,
expression: expression,
callback: '${converter.accessString}.toJson',
);
}
return LambdaResult(expression, '${converter.accessString}.toJson');
}
@override
Object? deserialize(
DartType targetType,
String expression,
TypeHelperContextWithConfig context,
bool defaultProvided,
) {
final converter = _typeConverter(targetType, context);
if (converter == null) {
return null;
}
final asContent = asStatement(converter.jsonType);
if (!converter.jsonType.isNullableType && targetType.isNullableType) {
const converterFromJsonName = r'_$JsonConverterFromJson';
context.addMember('''
Value? $converterFromJsonName<Json, Value>(
Object? json,
Value? Function(Json json) fromJson,
) => ${ifNullOrElse('json', 'null', 'fromJson(json as Json)')};
''');
return _nullableJsonConverterLambdaResult(
converter,
name: converterFromJsonName,
targetType: targetType,
expression: expression,
callback: '${converter.accessString}.fromJson',
);
}
return LambdaResult(
expression,
'${converter.accessString}.fromJson',
asContent: asContent,
);
}
}
String _nullableJsonConverterLambdaResult(
_JsonConvertData converter, {
required String name,
required DartType targetType,
required String expression,
required String callback,
}) {
final jsonDisplayString = typeToCode(converter.jsonType);
final fieldTypeDisplayString = converter.isGeneric
? typeToCode(targetType)
: typeToCode(converter.fieldType);
return '$name<$jsonDisplayString, $fieldTypeDisplayString>('
'$expression, $callback)';
}
class _JsonConvertData {
final String accessString;
final DartType jsonType;
final DartType fieldType;
final bool isGeneric;
_JsonConvertData.className(
String className,
String accessor,
this.jsonType,
this.fieldType,
) : accessString = 'const $className${_withAccessor(accessor)}()',
isGeneric = false;
_JsonConvertData.genericClass(
String className,
String genericTypeArg,
String accessor,
this.jsonType,
this.fieldType,
) : accessString =
'$className<$genericTypeArg>${_withAccessor(accessor)}()',
isGeneric = true;
_JsonConvertData.propertyAccess(
this.accessString,
this.jsonType,
this.fieldType,
) : isGeneric = false;
static String _withAccessor(String accessor) =>
accessor.isEmpty ? '' : '.$accessor';
}
/// If there is no converter for the params, return `null`.
///
/// Otherwise, returns `true` if the converter has a null return value.
///
/// Used to make sure we create a smart encoding function.
bool? hasConverterNullEncode(
DartType targetType,
TypeHelperContextWithConfig ctx,
) {
final data = _typeConverter(targetType, ctx);
if (data == null) {
return null;
}
return data.jsonType.isNullableType;
}
_JsonConvertData? _typeConverter(
DartType targetType,
TypeHelperContextWithConfig ctx,
) {
List<_ConverterMatch> converterMatches(List<ElementAnnotation> items) => items
.map(
(annotation) => _compatibleMatch(
targetType,
annotation,
annotation.computeConstantValue()!,
),
)
.whereType<_ConverterMatch>()
.toList();
var matchingAnnotations = converterMatches(ctx.fieldElement.metadata);
if (matchingAnnotations.isEmpty) {
matchingAnnotations =
converterMatches(ctx.fieldElement.getter?.metadata ?? []);
if (matchingAnnotations.isEmpty) {
matchingAnnotations = converterMatches(ctx.classElement.metadata);
if (matchingAnnotations.isEmpty) {
matchingAnnotations = ctx.config.converters
.map((e) => _compatibleMatch(targetType, null, e))
.whereType<_ConverterMatch>()
.toList();
}
}
}
return _typeConverterFrom(matchingAnnotations, targetType);
}
_JsonConvertData? _typeConverterFrom(
List<_ConverterMatch> matchingAnnotations,
DartType targetType,
) {
if (matchingAnnotations.isEmpty) {
return null;
}
if (matchingAnnotations.length > 1) {
final targetTypeCode = typeToCode(targetType);
throw InvalidGenerationSourceError(
'Found more than one matching converter for `$targetTypeCode`.',
element: matchingAnnotations[1].elementAnnotation?.element,
);
}
final match = matchingAnnotations.single;
final annotationElement = match.elementAnnotation?.element;
if (annotationElement is PropertyAccessorElement) {
final enclosing = annotationElement.enclosingElement3;
var accessString = annotationElement.name;
if (enclosing is ClassElement) {
accessString = '${enclosing.name}.$accessString';
}
return _JsonConvertData.propertyAccess(
accessString,
match.jsonType,
match.fieldType,
);
}
final reviver = ConstantReader(match.annotation).revive();
if (reviver.namedArguments.isNotEmpty ||
reviver.positionalArguments.isNotEmpty) {
throw InvalidGenerationSourceError(
'Generators with constructor arguments are not supported.',
element: match.elementAnnotation?.element,
);
}
if (match.genericTypeArg != null) {
return _JsonConvertData.genericClass(
match.annotation.type!.element2!.name!,
match.genericTypeArg!,
reviver.accessor,
match.jsonType,
match.fieldType,
);
}
return _JsonConvertData.className(
match.annotation.type!.element2!.name!,
reviver.accessor,
match.jsonType,
match.fieldType,
);
}
class _ConverterMatch {
final DartObject annotation;
final DartType fieldType;
final DartType jsonType;
final ElementAnnotation? elementAnnotation;
final String? genericTypeArg;
_ConverterMatch(
this.elementAnnotation,
this.annotation,
this.jsonType,
this.genericTypeArg,
this.fieldType,
);
}
_ConverterMatch? _compatibleMatch(
DartType targetType,
ElementAnnotation? annotation,
DartObject constantValue,
) {
final converterClassElement = constantValue.type!.element2 as ClassElement;
final jsonConverterSuper =
converterClassElement.allSupertypes.singleWhereOrNull(
(e) => _jsonConverterChecker.isExactly(e.element2),
);
if (jsonConverterSuper == null) {
return null;
}
assert(jsonConverterSuper.element2.typeParameters.length == 2);
assert(jsonConverterSuper.typeArguments.length == 2);
final fieldType = jsonConverterSuper.typeArguments[0];
// Allow assigning T to T?
if (fieldType == targetType || fieldType == targetType.promoteNonNullable()) {
return _ConverterMatch(
annotation,
constantValue,
jsonConverterSuper.typeArguments[1],
null,
fieldType,
);
}
if (fieldType is TypeParameterType && targetType is TypeParameterType) {
assert(annotation?.element is! PropertyAccessorElement);
assert(converterClassElement.typeParameters.isNotEmpty);
if (converterClassElement.typeParameters.length > 1) {
throw InvalidGenerationSourceError(
'`JsonConverter` implementations can have no more than one type '
'argument. `${converterClassElement.name}` has '
'${converterClassElement.typeParameters.length}.',
element: converterClassElement);
}
return _ConverterMatch(
annotation,
constantValue,
jsonConverterSuper.typeArguments[1],
'${targetType.element2.name}${targetType.isNullableType ? '?' : ''}',
fieldType,
);
}
return null;
}
const _jsonConverterChecker = TypeChecker.fromRuntime(JsonConverter);