trphoenix
2018-11-12 29fbfc5dd1d55d189f23eb6d32f000252f92985f
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
// 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:json_annotation/json_annotation.dart';
 
import 'constants.dart';
import 'helper_core.dart';
import 'type_helper.dart';
 
abstract class EncodeHelper implements HelperCore {
  String _fieldAccess(FieldElement field) {
    var fieldAccess = field.name;
    if (config.generateToJsonFunction) {
      fieldAccess = '$_toJsonParamName.$fieldAccess';
    }
    return fieldAccess;
  }
 
  String _mixinClassName(bool withConstraints) =>
      '${prefix}SerializerMixin${genericClassArgumentsImpl(withConstraints)}';
 
  String _wrapperClassName([bool withConstraints]) =>
      '${prefix}JsonMapWrapper${genericClassArgumentsImpl(withConstraints)}';
 
  Iterable<String> createToJson(Set<FieldElement> accessibleFields) sync* {
    assert(config.createToJson);
 
    final buffer = StringBuffer();
 
    if (config.generateToJsonFunction) {
      final functionName = '${prefix}ToJson${genericClassArgumentsImpl(true)}';
      buffer.write('Map<String, dynamic> $functionName'
          '($targetClassReference $_toJsonParamName) ');
    } else {
      //
      // Generate the mixin class
      //
      buffer.writeln('abstract class ${_mixinClassName(true)} {');
 
      // write copies of the fields - this allows the toJson method to access
      // the fields of the target class
      for (final field in accessibleFields) {
        //TODO - handle aliased imports
        buffer.writeln('  ${field.type} get ${field.name};');
      }
 
      buffer.write('  Map<String, dynamic> toJson() ');
    }
 
    final writeNaive = accessibleFields.every(_writeJsonValueNaive);
 
    if (config.useWrappers) {
      final param = config.generateToJsonFunction ? _toJsonParamName : 'this';
      buffer.writeln('=> ${_wrapperClassName(false)}($param);');
    } else {
      if (writeNaive) {
        // write simple `toJson` method that includes all keys...
        _writeToJsonSimple(buffer, accessibleFields);
      } else {
        // At least one field should be excluded if null
        _writeToJsonWithNullChecks(buffer, accessibleFields);
      }
    }
 
    if (!config.generateToJsonFunction) {
      // end of the mixin class
      buffer.writeln('}');
    }
 
    yield buffer.toString();
 
    if (config.useWrappers) {
      yield _createWrapperClass(accessibleFields);
    }
  }
 
  String _createWrapperClass(Iterable<FieldElement> fields) {
    final buffer = StringBuffer();
    buffer.writeln();
    // TODO(kevmoo): write JsonMapWrapper if annotation lib is prefix-imported
 
    final fieldType = config.generateToJsonFunction
        ? targetClassReference
        : _mixinClassName(false);
 
    buffer.writeln('''
class ${_wrapperClassName(true)} extends \$JsonMapWrapper {
  final $fieldType _v;
  ${_wrapperClassName()}(this._v);
''');
 
    if (fields.every(_writeJsonValueNaive)) {
      // TODO(kevmoo): consider just doing one code path – if it's fast
      //               enough
      final jsonKeys = fields.map(safeNameAccess).join(', ');
 
      // TODO(kevmoo): maybe put this in a static field instead?
      //               const lists have unfortunate overhead
      buffer.writeln('''
  @override
  Iterable<String> get keys => const [$jsonKeys];
''');
    } else {
      // At least one field should be excluded if null
      buffer.writeln('  @override\n  Iterable<String> get keys sync* {');
 
      for (final field in fields) {
        final nullCheck = !_writeJsonValueNaive(field);
        if (nullCheck) {
          buffer.write('    if (_v.${field.name} != null) {\n  ');
        }
        buffer.writeln('    yield ${safeNameAccess(field)};');
        if (nullCheck) {
          buffer.writeln('    }');
        }
      }
 
      buffer.writeln('  }\n');
    }
 
    buffer.writeln('''
  @override
  dynamic operator [](Object key) {
    if (key is String) {
      switch (key) {''');
 
    for (final field in fields) {
      final valueAccess = '_v.${field.name}';
      buffer.writeln('''
        case ${safeNameAccess(field)}:
          return ${_serializeField(field, valueAccess)};''');
    }
 
    buffer.writeln('''
      }
    }
    return null;
  }''');
 
    buffer.writeln('}');
    return buffer.toString();
  }
 
  void _writeToJsonSimple(StringBuffer buffer, Iterable<FieldElement> fields) {
    buffer.writeln('=> <String, dynamic>{');
 
    buffer.writeAll(fields.map((field) {
      final access = _fieldAccess(field);
      final value =
          '${safeNameAccess(field)}: ${_serializeField(field, access)}';
      return '        $value';
    }), ',\n');
 
    if (fields.isNotEmpty) {
      buffer.write('\n      ');
    }
 
    buffer.writeln('};');
  }
 
  /// Name of the parameter used when generating top-level `toJson` functions
  /// if [JsonSerializable.generateToJsonFunction] is `true`.
  static const _toJsonParamName = 'instance';
 
  void _writeToJsonWithNullChecks(
      StringBuffer buffer, Iterable<FieldElement> fields) {
    buffer.writeln('{');
 
    buffer.writeln('    final $generatedLocalVarName = <String, dynamic>{');
 
    // Note that the map literal is left open above. As long as target fields
    // don't need to be intercepted by the `only if null` logic, write them
    // to the map literal directly. In theory, should allow more efficient
    // serialization.
    var directWrite = true;
 
    for (final field in fields) {
      var safeFieldAccess = _fieldAccess(field);
      final safeJsonKeyString = safeNameAccess(field);
 
      // If `fieldName` collides with one of the local helpers, prefix
      // access with `this.`.
      if (safeFieldAccess == generatedLocalVarName ||
          safeFieldAccess == toJsonMapHelperName) {
        assert(!config.generateToJsonFunction,
            'This code path should only be hit during the mixin codepath.');
        safeFieldAccess = 'this.$safeFieldAccess';
      }
 
      final expression = _serializeField(field, safeFieldAccess);
      if (_writeJsonValueNaive(field)) {
        if (directWrite) {
          buffer.writeln('      $safeJsonKeyString: $expression,');
        } else {
          buffer.writeln(
              '    $generatedLocalVarName[$safeJsonKeyString] = $expression;');
        }
      } else {
        if (directWrite) {
          // close the still-open map literal
          buffer.writeln('    };');
          buffer.writeln();
 
          // write the helper to be used by all following null-excluding
          // fields
          buffer.writeln('''
    void $toJsonMapHelperName(String key, dynamic value) {
      if (value != null) {
        $generatedLocalVarName[key] = value;
      }
    }
''');
          directWrite = false;
        }
        buffer.writeln(
            '    $toJsonMapHelperName($safeJsonKeyString, $expression);');
      }
    }
 
    buffer.writeln('    return $generatedLocalVarName;');
    buffer.writeln('  }');
  }
 
  String _serializeField(FieldElement field, String accessExpression) {
    try {
      return getHelperContext(field)
          .serialize(field.type, accessExpression)
          .toString();
    } on UnsupportedTypeError catch (e) {
      throw createInvalidGenerationError('toJson', field, e);
    }
  }
 
  /// Returns `true` if the field can be written to JSON 'naively' – meaning
  /// we can avoid checking for `null`.
  ///
  /// `true` if either:
  ///   `includeIfNull` is `true`
  ///   or
  ///   `nullable` is `false`.
  bool _writeJsonValueNaive(FieldElement field) =>
      jsonKeyFor(field).includeIfNull || !jsonKeyFor(field).nullable;
}