-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathdecode_helper.dart
375 lines (318 loc) · 11.3 KB
/
decode_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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// 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/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:source_helper/source_helper.dart';
import 'helper_core.dart';
import 'json_literal_generator.dart';
import 'type_helpers/generic_factory_helper.dart';
import 'unsupported_type_error.dart';
import 'utils.dart';
class CreateFactoryResult {
final String output;
final Set<String> usedFields;
CreateFactoryResult(this.output, this.usedFields);
}
abstract class DecodeHelper implements HelperCore {
CreateFactoryResult createFactory(
Map<String, FieldElement> accessibleFields,
Map<String, String> unavailableReasons,
List<FieldElement> extras,
) {
assert(config.createFactory);
final buffer = StringBuffer();
final mapType = config.anyMap ? 'Map' : 'Map<String, dynamic>';
buffer.write('$targetClassReference '
'${prefix}FromJson${genericClassArgumentsImpl(true)}'
'($mapType json');
if (config.genericArgumentFactories) {
for (var arg in element.typeParameters) {
final helperName = fromJsonForType(
arg.instantiate(nullabilitySuffix: NullabilitySuffix.none),
);
buffer.write(', ${arg.name} Function(Object? json) $helperName');
}
if (element.typeParameters.isNotEmpty) {
buffer.write(',');
}
}
if (extras.isNotEmpty) {
buffer.writeln(', {');
for (final extra in extras) {
if (!extra.type.isNullableType) buffer.write('required ');
buffer.writeln(
'${extra.type.getDisplayString(withNullability: true)} ${extra.name},');
}
buffer.write('}');
}
buffer.write(')');
final fromJsonLines = <String>[];
String deserializeFun(String paramOrFieldName,
{ParameterElement? ctorParam}) =>
_deserializeForField(accessibleFields[paramOrFieldName]!,
ctorParam: ctorParam);
final extraNames = [for (final extra in extras) extra.name];
final data = _writeConstructorInvocation(
element,
config.constructor,
[...accessibleFields.keys, ...extraNames],
accessibleFields.values
.where((fe) => element.lookUpSetter(fe.name, element.library) != null)
.map((fe) => fe.name)
.toList(),
unavailableReasons,
extraNames,
deserializeFun,
);
final checks = _checkKeys(
accessibleFields.values
.where((fe) => data.usedCtorParamsAndFields.contains(fe.name)),
).toList();
if (config.checked) {
final classLiteral = escapeDartString(element.name);
final sectionBuffer = StringBuffer()
..write('''
\$checkedCreate(
$classLiteral,
json,
(\$checkedConvert) {\n''')
..write(checks.join())
..write('''
final val = ${data.content};''');
for (final fieldName in data.fieldsToSet) {
sectionBuffer.writeln();
final fieldValue = accessibleFields[fieldName]!;
final safeName = safeNameAccess(fieldValue);
sectionBuffer
..write('''
\$checkedConvert($safeName, (v) => ''')
..write('val.$fieldName = ')
..write(
_deserializeForField(fieldValue, checkedProperty: true),
);
final readValueFunc = jsonKeyFor(fieldValue).readValueFunctionName;
if (readValueFunc != null) {
sectionBuffer.writeln(',readValue: $readValueFunc,');
}
sectionBuffer.write(');');
}
sectionBuffer.write('''\n return val;
}''');
final fieldKeyMap = Map.fromEntries(data.usedCtorParamsAndFields
.map((k) => MapEntry(k, nameAccess(accessibleFields[k]!)))
.where((me) => me.key != me.value));
String fieldKeyMapArg;
if (fieldKeyMap.isEmpty) {
fieldKeyMapArg = '';
} else {
final mapLiteral = jsonMapAsDart(fieldKeyMap);
fieldKeyMapArg = ', fieldKeyMap: const $mapLiteral';
}
sectionBuffer
..write(fieldKeyMapArg)
..write(',);');
fromJsonLines.add(sectionBuffer.toString());
} else {
fromJsonLines.addAll(checks);
final sectionBuffer = StringBuffer()..write('''
${data.content}''');
for (final field in data.fieldsToSet) {
sectionBuffer
..writeln()
..write(' ..$field = ')
..write(deserializeFun(field));
}
sectionBuffer.writeln(';');
fromJsonLines.add(sectionBuffer.toString());
}
if (fromJsonLines.length == 1) {
buffer
..write('=>')
..write(fromJsonLines.single);
} else {
buffer
..write('{')
..writeAll(fromJsonLines.take(fromJsonLines.length - 1))
..write('return ')
..write(fromJsonLines.last)
..write('}');
}
return CreateFactoryResult(buffer.toString(), data.usedCtorParamsAndFields);
}
Iterable<String> _checkKeys(Iterable<FieldElement> accessibleFields) sync* {
final args = <String>[];
String constantList(Iterable<FieldElement> things) =>
'const ${jsonLiteralAsDart(things.map(nameAccess).toList())}';
if (config.disallowUnrecognizedKeys) {
final allowKeysLiteral = constantList(accessibleFields);
args.add('allowedKeys: $allowKeysLiteral');
}
final requiredKeys =
accessibleFields.where((fe) => jsonKeyFor(fe).required).toList();
if (requiredKeys.isNotEmpty) {
final requiredKeyLiteral = constantList(requiredKeys);
args.add('requiredKeys: $requiredKeyLiteral');
}
final disallowNullKeys = accessibleFields
.where((fe) => jsonKeyFor(fe).disallowNullValue)
.toList();
if (disallowNullKeys.isNotEmpty) {
final disallowNullKeyLiteral = constantList(disallowNullKeys);
args.add('disallowNullValues: $disallowNullKeyLiteral');
}
if (args.isNotEmpty) {
yield '\$checkKeys(json, ${args.map((e) => '$e, ').join()});\n';
}
}
/// If [checkedProperty] is `true`, we're using this function to write to a
/// setter.
String _deserializeForField(
FieldElement field, {
ParameterElement? ctorParam,
bool checkedProperty = false,
}) {
final jsonKeyName = safeNameAccess(field);
final targetType = ctorParam?.type ?? field.type;
final contextHelper = getHelperContext(field);
final jsonKey = jsonKeyFor(field);
final defaultValue = jsonKey.defaultValue;
final readValueFunc = jsonKey.readValueFunctionName;
String deserialize(String expression) => contextHelper
.deserialize(
targetType,
expression,
defaultValue: defaultValue,
)
.toString();
String value;
try {
if (config.checked) {
value = deserialize('v');
if (!checkedProperty) {
final readValueBit =
readValueFunc == null ? '' : ',readValue: $readValueFunc,';
value = '\$checkedConvert($jsonKeyName, (v) => $value$readValueBit)';
}
} else {
assert(
!checkedProperty,
'should only be true if `_generator.checked` is true.',
);
value = deserialize(
readValueFunc == null
? 'json[$jsonKeyName]'
: '$readValueFunc(json, $jsonKeyName)',
);
}
} on UnsupportedTypeError catch (e) // ignore: avoid_catching_errors
{
throw createInvalidGenerationError('fromJson', field, e);
}
if (defaultValue != null) {
if (jsonKey.disallowNullValue && jsonKey.required) {
log.warning('The `defaultValue` on field `${field.name}` will have no '
'effect because both `disallowNullValue` and `required` are set to '
'`true`.');
}
}
return value;
}
}
/// [availableConstructorParameters] is checked to see if it is available. If
/// [availableConstructorParameters] does not contain the parameter name,
/// an [UnsupportedError] is thrown.
///
/// To improve the error details, [unavailableReasons] is checked for the
/// unavailable constructor parameter. If the value is not `null`, it is
/// included in the [UnsupportedError] message.
///
/// [writableFields] are also populated, but only if they have not already
/// been defined by a constructor parameter with the same name.
_ConstructorData _writeConstructorInvocation(
ClassElement classElement,
String constructorName,
Iterable<String> availableConstructorParameters,
Iterable<String> writableFields,
Map<String, String> unavailableReasons,
List<String> extras,
String Function(String paramOrFieldName, {ParameterElement ctorParam})
deserializeForField,
) {
final className = classElement.name;
final ctor = constructorByName(classElement, constructorName);
final usedCtorParamsAndFields = <String>{};
final constructorArguments = <ParameterElement>[];
final namedConstructorArguments = <ParameterElement>[];
for (final arg in ctor.parameters) {
if (!availableConstructorParameters.contains(arg.name)) {
// ignore: deprecated_member_use
if (arg.isNotOptional) {
var msg = 'Cannot populate the required constructor '
'argument: ${arg.name}.';
final additionalInfo = unavailableReasons[arg.name];
if (additionalInfo != null) {
msg = '$msg $additionalInfo';
}
throw InvalidGenerationSourceError(msg, element: ctor);
}
continue;
}
// TODO: validate that the types match!
if (arg.isNamed) {
namedConstructorArguments.add(arg);
} else {
constructorArguments.add(arg);
}
if (!extras.contains(arg.name)) usedCtorParamsAndFields.add(arg.name);
}
// fields that aren't already set by the constructor and that aren't final
final remainingFieldsForInvocationBody =
writableFields.toSet().difference(usedCtorParamsAndFields);
final constructorExtra = constructorName.isEmpty ? '' : '.$constructorName';
final buffer = StringBuffer()
..write(
'$className'
'${genericClassArguments(classElement, false)}'
'$constructorExtra(',
);
if (constructorArguments.isNotEmpty) {
buffer
..writeln()
..writeAll(constructorArguments.map((paramElement) {
final content = extras.contains(paramElement.name)
? paramElement.name
: deserializeForField(paramElement.name, ctorParam: paramElement);
return ' $content,\n';
}));
}
if (namedConstructorArguments.isNotEmpty) {
buffer
..writeln()
..writeAll(namedConstructorArguments.map((paramElement) {
final value = extras.contains(paramElement.name)
? paramElement.name
: deserializeForField(paramElement.name, ctorParam: paramElement);
return ' ${paramElement.name}: $value,\n';
}));
}
buffer.write(')');
usedCtorParamsAndFields.addAll(remainingFieldsForInvocationBody);
return _ConstructorData(
buffer.toString(),
remainingFieldsForInvocationBody,
usedCtorParamsAndFields,
);
}
class _ConstructorData {
final String content;
final Set<String> fieldsToSet;
final Set<String> usedCtorParamsAndFields;
_ConstructorData(
this.content,
this.fieldsToSet,
this.usedCtorParamsAndFields,
);
}