forked from rrousselGit/freezed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy_with.dart
318 lines (267 loc) · 9.31 KB
/
copy_with.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
import 'package:freezed/src/templates/parameter_template.dart';
import 'package:freezed/src/templates/properties.dart';
import '../models.dart';
class CopyWith {
CopyWith({
required this.clonedClassName,
required this.genericsDefinition,
required this.genericsParameter,
required this.allProperties,
required this.cloneableProperties,
required this.data,
this.parent,
});
static String interfaceNameFrom(String name) {
if (name.startsWith('_')) {
return '_\$${name.substring(1)}CopyWith';
}
return '\$${name}CopyWith';
}
final String clonedClassName;
final GenericsDefinitionTemplate genericsDefinition;
final GenericsParameterTemplate genericsParameter;
final List<Property> allProperties;
final List<CloneableProperty> cloneableProperties;
final CopyWith? parent;
final Data data;
/// When collections are wrapped in an UnmodifiableView, this bool determines
/// if the raw collection can be accessed instead.
bool get canAccessRawCollection => parent != null;
String get interface {
var implements = _hasSuperClass
? 'implements ${parent!._abstractClassName}${genericsParameter.append('\$Res')}'
: '';
return '''
/// @nodoc
abstract class $_abstractClassName${genericsDefinition.append('\$Res')} $implements {
factory $_abstractClassName($clonedClassName$genericsParameter value, \$Res Function($clonedClassName$genericsParameter) then) = $_implClassName${genericsParameter.append('\$Res')};
${_copyWithPrototype('call')}
${_abstractDeepCopyMethods().join()}
}''';
}
bool get _hasSuperClass {
return parent != null && parent!.allProperties.isNotEmpty;
}
String commonContreteImpl(
List<Property> commonProperties,
) {
var copyWith = '';
if (allProperties.isNotEmpty) {
final prototype = _concreteCopyWithPrototype(
properties: allProperties,
methodName: 'call',
);
final body = _copyWithMethodBody(
parametersTemplate: ParametersTemplate(
const [],
namedParameters: commonProperties.map((e) {
return Parameter(
decorators: e.decorators,
name: e.name,
isNullable: false,
isFinal: false,
isDartList: false,
isDartMap: false,
isDartSet: false,
showDefaultValue: false,
isRequired: false,
defaultValueSource: '',
type: e.type,
doc: e.doc,
isPossiblyDartCollection: e.isPossiblyDartCollection,
isCommonWithDifferentNullability:
e.isCommonWithDifferentNullability,
parameterElement: null,
);
}).toList(),
),
returnType: '_value.copyWith',
);
copyWith = '@override $prototype $body';
}
return '''
/// @nodoc
class $_implClassName${genericsDefinition.append('\$Res')} implements $_abstractClassName${genericsParameter.append('\$Res')} {
$_implClassName(this._value, this._then);
final $clonedClassName$genericsParameter _value;
// ignore: unused_field
final \$Res Function($clonedClassName$genericsParameter) _then;
$copyWith
${_deepCopyMethods().join()}
}
''';
}
Iterable<String> _abstractDeepCopyMethods() sync* {
for (final cloneableProperty in cloneableProperties) {
var leading = '';
if (_hasSuperClass &&
parent!.cloneableProperties
.any((c) => c.name == cloneableProperty.name)) {
leading = '@override ';
}
final nullabilitySuffix = cloneableProperty.nullable ? '?' : '';
yield '$leading${_clonerInterfaceFor(cloneableProperty)}$nullabilitySuffix get ${cloneableProperty.name};';
}
}
String _copyWithPrototype(String methodName) {
if (allProperties.isEmpty) return '';
return _copyWithProtypeFor(
methodName: methodName,
properties: allProperties,
);
}
String _copyWithProtypeFor({
required String methodName,
required List<Property> properties,
}) {
final parameters = properties.map((p) {
final type = p.isCommonWithDifferentNullability
? p.type.replaceFirst(RegExp(r'\?$'), '')
: p.type;
return '${p.decorators.join()} covariant $type ${p.name}';
}).join(',');
return _maybeOverride('''
\$Res $methodName({
$parameters
});
''');
}
String get abstractCopyWithGetter {
if (allProperties.isEmpty) return '';
return _maybeOverride(
'''
@JsonKey(ignore: true)
$_abstractClassName${genericsParameter.append('$clonedClassName$genericsParameter')} get copyWith => throw $privConstUsedErrorVarName;
''',
);
}
String get concreteCopyWithGetter {
if (allProperties.isEmpty) return '';
return '''
@JsonKey(ignore: true)
@override
$_abstractClassName${genericsParameter.append('$clonedClassName$genericsParameter')} get copyWith => $_implClassName${genericsParameter.append('$clonedClassName$genericsParameter')}(this, _\$identity);
''';
}
String _copyWithMethod(ParametersTemplate parametersTemplate) {
if (allProperties.isEmpty) return '';
final prototype = _concreteCopyWithPrototype(
properties: allProperties,
methodName: 'call',
);
final body = _copyWithMethodBody(
parametersTemplate: parametersTemplate,
returnType: '$clonedClassName$genericsParameter',
);
return '@override $prototype $body';
}
String _ignoreLints(String s,
[List<String> lints = const ['cast_nullable_to_non_nullable']]) =>
'''
// ignore: ${lints.join(', ')}
$s''';
String _copyWithMethodBody({
String accessor = '_value',
required ParametersTemplate parametersTemplate,
required String returnType,
}) {
String parameterToValue(Parameter p) {
var propertyName = p.name;
if (canAccessRawCollection &&
(p.isDartList || p.isDartMap || p.isDartSet) &&
data.makeCollectionsImmutable) {
propertyName = '_$propertyName';
}
final type = p.isCommonWithDifferentNullability
? p.type!.replaceFirst(RegExp(r'\?$'), '')
: p.type;
var ternary = '${p.name} == freezed ? $accessor.$propertyName ';
if (p.isCommonWithDifferentNullability) {
ternary += 'as $type ';
}
ternary += ': ${p.name} ';
if (p.type != 'Object?' && p.type != null) {
ternary += _ignoreLints('as $type');
}
return '$ternary,';
}
final constructorParameters = StringBuffer()
..writeAll(
[
...parametersTemplate.requiredPositionalParameters,
...parametersTemplate.optionalPositionalParameters,
].map<String>(parameterToValue),
)
..writeAll(
parametersTemplate.namedParameters.map<String>(
(p) => '${p.name}: ${parameterToValue(p)}',
),
);
return '''{
return _then($returnType(
$constructorParameters
));
}''';
}
String _concreteCopyWithPrototype({
required List<Property> properties,
required String methodName,
}) {
final parameters = properties.map((p) {
return 'Object? ${p.name} = freezed,';
}).join();
return '\$Res $methodName({$parameters})';
}
String get _implClassName => '_${_abstractClassName}Impl';
/// The implementation of the callable class that contains both the copyWith
/// and the cloneable properties.
String concreteImpl(ParametersTemplate parametersTemplate) {
return '''
/// @nodoc
class $_implClassName${genericsDefinition.append('\$Res')} extends ${parent!._implClassName}${genericsParameter.append('\$Res')} implements $_abstractClassName${genericsParameter.append('\$Res')} {
$_implClassName($clonedClassName$genericsParameter _value, \$Res Function($clonedClassName$genericsParameter) _then)
: super(_value, (v) => _then(v as $clonedClassName$genericsParameter));
@override
$clonedClassName$genericsParameter get _value => super._value as $clonedClassName$genericsParameter;
${_copyWithMethod(parametersTemplate)}
${_deepCopyMethods().join()}
}''';
}
Iterable<String> _deepCopyMethods() sync* {
final toGenerateProperties = parent == null
? cloneableProperties
: cloneableProperties.where((property) {
return !parent!.cloneableProperties
.any((p) => p.name == property.name);
});
for (final cloneableProperty in toGenerateProperties) {
final earlyReturn = cloneableProperty.nullable
? '''
if (_value.${cloneableProperty.name} == null) {
return null;
}
'''
: '';
final nullabilitySuffix = cloneableProperty.nullable ? '!' : '';
final returnType = cloneableProperty.nullable
? '${_clonerInterfaceFor(cloneableProperty)}?'
: '${_clonerInterfaceFor(cloneableProperty)}';
yield '''
@override
$returnType get ${cloneableProperty.name} {
$earlyReturn
return ${_clonerInterfaceFor(cloneableProperty)}(_value.${cloneableProperty.name}$nullabilitySuffix, (value) {
return _then(_value.copyWith(${cloneableProperty.name}: value));
});
}''';
}
}
String _clonerInterfaceFor(CloneableProperty cloneableProperty) {
final name = interfaceNameFrom(cloneableProperty.typeName);
return '$name${cloneableProperty.genericParameters.append('\$Res')}';
}
String _maybeOverride(String res) {
return _hasSuperClass ? '@override $res' : res;
}
String get _abstractClassName => interfaceNameFrom(clonedClassName);
}