-
Notifications
You must be signed in to change notification settings - Fork 457
Expand file tree
/
Copy pathenum_utils.dart
More file actions
253 lines (213 loc) · 7.17 KB
/
Copy pathenum_utils.dart
File metadata and controls
253 lines (213 loc) · 7.17 KB
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
// Copyright (c) 2021, 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/element2.dart';
import 'package:analyzer/dart/element/type.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 'utils.dart';
String constMapName(DartType targetType) =>
'_\$${targetType.element!.name}EnumMap';
String constDecodeMapName(DartType targetType) =>
'_\$${targetType.element!.name}EnumDecodeMap';
/// If [targetType] is not an enum, return `null`.
///
/// Otherwise, returns `true` if [targetType] is nullable OR if one of the
/// encoded values of the enum is `null`.
bool? enumFieldWithNullInEncodeMap(DartType targetType) {
final enumMap = _enumMap(targetType);
if (enumMap == null) return null;
if (targetType.isNullableType) {
return true;
}
return enumMap.values.contains(null);
}
String? enumValueMapFromType(
DartType targetType, {
bool nullWithNoAnnotation = false,
}) {
final enumMap = _enumMap(
targetType,
nullWithNoAnnotation: nullWithNoAnnotation,
);
final enumAliases = _enumAliases(
targetType,
nullWithNoAnnotation: nullWithNoAnnotation,
);
final valuesItems = enumMap?.entries
.map(
(e) =>
' ${targetType.element3!.name3}.${e.key.name3}: '
'${jsonLiteralAsDart(e.value)},',
)
.join();
final valuesMap = valuesItems == null
? null
: '// ignore: unused_element\n'
'const ${constMapName(targetType)} = {\n$valuesItems\n};';
final decodeItems = enumAliases?.entries
.map(
(e) =>
' ${jsonLiteralAsDart(e.key)}: '
'${targetType.element!.name}.${e.value.name3},',
)
.join();
final decodeMap = decodeItems == null
? null
: '// ignore: unused_element\n'
'const ${constDecodeMapName(targetType)} = {\n$decodeItems\n};';
return valuesMap == null && decodeMap == null
? null
: [valuesMap, decodeMap].join('\n\n');
}
Map<FieldElement2, Object?>? _enumMap(
DartType targetType, {
bool nullWithNoAnnotation = false,
}) {
final targetTypeElement = targetType.element;
if (targetTypeElement == null) return null;
final annotation = _jsonEnumChecker.firstAnnotationOf(targetTypeElement);
final jsonEnum = _fromAnnotation(annotation);
final enumFields = iterateEnumFields(targetType);
if (enumFields == null || (nullWithNoAnnotation && !jsonEnum.alwaysCreate)) {
return null;
}
return {
for (var field in enumFields)
field: _generateEntry(
field: field,
jsonEnum: jsonEnum,
targetType: targetType,
),
};
}
Map<Object?, FieldElement2>? _enumAliases(
DartType targetType, {
bool nullWithNoAnnotation = false,
}) {
final targetTypeElement = targetType.element;
if (targetTypeElement == null) return null;
final annotation = _jsonEnumChecker.firstAnnotationOf(targetTypeElement);
final jsonEnum = _fromAnnotation(annotation);
final enumFields = iterateEnumFields(targetType);
if (enumFields == null || (nullWithNoAnnotation && !jsonEnum.alwaysCreate)) {
return null;
}
return {
for (var field in enumFields) ...{
_generateEntry(field: field, jsonEnum: jsonEnum, targetType: targetType):
field,
for (var alias in _generateAliases(field: field, targetType: targetType))
alias: field,
},
};
}
Object? _generateEntry({
required FieldElement2 field,
required JsonEnum jsonEnum,
required DartType targetType,
}) {
final annotation = const TypeChecker.fromRuntime(
JsonValue,
).firstAnnotationOfExact(field);
if (annotation == null) {
final valueField = jsonEnum.valueField;
if (valueField != null) {
// TODO: fieldRename is pointless here!!! At least log a warning!
final fieldElementType = field.type.element3 as EnumElement2;
final e = fieldElementType.getField2(valueField);
if (e == null && valueField == 'index') {
return fieldElementType.fields2
.where((element) => element.isEnumConstant)
.toList(growable: false)
.indexOf(field);
}
if (e == null || e.isStatic) {
throw InvalidGenerationSourceError(
'`JsonEnum.valueField` was set to "$valueField", but '
'that is not a valid, instance field on '
'`${typeToCode(targetType)}`.',
element: targetType.element3,
);
}
final reader = ConstantReader(field.computeConstantValue());
final valueReader = reader.read(valueField);
if (valueReader.validValueType) {
return valueReader.literalValue;
} else {
throw InvalidGenerationSourceError(
'`JsonEnum.valueField` was set to "$valueField", but '
'that field does not have a type of String, int, or null.',
element: targetType.element3,
);
}
} else {
return encodedFieldName(jsonEnum.fieldRename, field.name3!);
}
} else {
final reader = ConstantReader(annotation);
final valueReader = reader.read('value');
if (valueReader.validValueType) {
return valueReader.literalValue;
} else {
final targetTypeCode = typeToCode(targetType);
throw InvalidGenerationSourceError(
'The `JsonValue` annotation on `$targetTypeCode.${field.name3}` does '
'not have a value of type String, int, or null.',
element: field,
);
}
}
}
List<Object?> _generateAliases({
required FieldElement2 field,
required DartType targetType,
}) {
final annotation = const TypeChecker.fromRuntime(
JsonValue,
).firstAnnotationOfExact(field);
if (annotation == null) {
return const [];
} else {
final reader = ConstantReader(annotation);
final valueReader = reader.read('aliases');
if (valueReader.validAliasesType) {
return [
for (final value in valueReader.setValue)
ConstantReader(value).literalValue,
];
} else {
final targetTypeCode = typeToCode(targetType);
throw InvalidGenerationSourceError(
'The `JsonValue` annotation on `$targetTypeCode.${field.name3}` '
'aliases should all be of type String or int.',
element: field,
);
}
}
}
const _jsonEnumChecker = TypeChecker.fromRuntime(JsonEnum);
JsonEnum _fromAnnotation(DartObject? dartObject) {
if (dartObject == null) {
return const JsonEnum();
}
final reader = ConstantReader(dartObject);
return JsonEnum(
alwaysCreate: reader.read('alwaysCreate').literalValue as bool,
fieldRename: readEnum(reader.read('fieldRename'), FieldRename.values)!,
valueField: reader.read('valueField').literalValue as String?,
);
}
extension on ConstantReader {
bool get validValueType => isString || isNull || isInt;
bool get validAliasesType =>
isSet &&
setValue.every(
(element) =>
(element.type?.isDartCoreString ?? false) ||
(element.type?.isDartCoreInt ?? false),
);
}