Skip to content

Standandize generated local vars #167

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 21, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion json_serializable/lib/src/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@
// 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.

const toJsonMapVarName = 'val';
/// Name used for closure argument when generating calls to `map`.
final closureArg = 'e';

const generatedLocalVarName = 'val';
const toJsonMapHelperName = 'writeNotNull';
12 changes: 6 additions & 6 deletions json_serializable/lib/src/generator_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ class _GeneratorHelper {
void _writeToJsonWithNullChecks(Iterable<FieldElement> fields) {
_buffer.writeln('{');

_buffer.writeln('var $toJsonMapVarName = <String, dynamic>{');
_buffer.writeln('var $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
Expand All @@ -252,7 +252,7 @@ class _GeneratorHelper {

// If `fieldName` collides with one of the local helpers, prefix
// access with `this.`.
if (safeFieldAccess == toJsonMapVarName ||
if (safeFieldAccess == generatedLocalVarName ||
safeFieldAccess == toJsonMapHelperName) {
safeFieldAccess = 'this.$safeFieldAccess';
}
Expand All @@ -262,8 +262,8 @@ class _GeneratorHelper {
if (directWrite) {
_buffer.writeln('$safeJsonKeyString : $expression,');
} else {
_buffer
.writeln('$toJsonMapVarName[$safeJsonKeyString] = $expression;');
_buffer.writeln(
'$generatedLocalVarName[$safeJsonKeyString] = $expression;');
}
} else {
if (directWrite) {
Expand All @@ -276,7 +276,7 @@ class _GeneratorHelper {
_buffer.writeln('''
void $toJsonMapHelperName(String key, dynamic value) {
if (value != null) {
$toJsonMapVarName[key] = value;
$generatedLocalVarName[key] = value;
}
}''');
directWrite = false;
Expand All @@ -286,7 +286,7 @@ void $toJsonMapHelperName(String key, dynamic value) {
}
}

_buffer.writeln('return $toJsonMapVarName;');
_buffer.writeln('return $generatedLocalVarName;');

_buffer.writeln('}');
}
Expand Down
6 changes: 4 additions & 2 deletions json_serializable/lib/src/type_helpers/enum_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/dart/element/type.dart';

import '../constants.dart';
import '../type_helper.dart';
import '../utils.dart';

Expand Down Expand Up @@ -35,7 +37,7 @@ class EnumHelper extends TypeHelper {
return commonNullPrefix(
context.nullable,
expression,
'$targetType.values.singleWhere('
"(x) => x.toString() == '$targetType.\$$wrappedExpression')");
'$targetType.values.singleWhere(($closureArg) => $closureArg.toString()'
" == '$targetType.\$$wrappedExpression')");
}
}
18 changes: 8 additions & 10 deletions json_serializable/lib/src/type_helpers/iterable_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
import 'package:analyzer/dart/element/type.dart';
import 'package:source_gen/source_gen.dart' show TypeChecker;

import '../constants.dart';
import '../shared_checkers.dart';
import '../type_helper.dart';

/// Name used for closure argument when generating calls to `map`.
final _closureArg = 'e';

class IterableHelper extends TypeHelper {
const IterableHelper();

Expand All @@ -27,26 +25,26 @@ class IterableHelper extends TypeHelper {
// Although it's possible that child elements may be marked unsafe

var isList = _coreListChecker.isAssignableFromType(targetType);
var subField = context.serialize(itemType, _closureArg);
var subField = context.serialize(itemType, closureArg);

var optionalQuestion = context.nullable ? '?' : '';

// In the case of trivial JSON types (int, String, etc), `subField`
// will be identical to `substitute` – so no explicit mapping is needed.
// If they are not equal, then we to write out the substitution.
if (subField != _closureArg) {
if (subField != closureArg) {
if (context.useWrappers && isList) {
var method = '\$wrapList';
if (context.nullable) {
method = '${method}HandleNull';
}

return '$method<$itemType>($expression, ($_closureArg) => $subField)';
return '$method<$itemType>($expression, ($closureArg) => $subField)';
}

// TODO: the type could be imported from a library with a prefix!
expression =
'$expression$optionalQuestion.map(($_closureArg) => $subField)';
'$expression$optionalQuestion.map(($closureArg) => $subField)';

// expression now represents an Iterable (even if it started as a List
// ...resetting `isList` to `false`.
Expand All @@ -70,17 +68,17 @@ class IterableHelper extends TypeHelper {

var iterableGenericType = coreIterableGenericType(targetType);

var itemSubVal = context.deserialize(iterableGenericType, _closureArg);
var itemSubVal = context.deserialize(iterableGenericType, closureArg);

// If `itemSubVal` is the same, then we don't need to do anything fancy
if (_closureArg == itemSubVal) {
if (closureArg == itemSubVal) {
return '$expression as List';
}

var optionalQuestion = context.nullable ? '?' : '';

var output =
'($expression as List)$optionalQuestion.map(($_closureArg) => $itemSubVal)';
'($expression as List)$optionalQuestion.map(($closureArg) => $itemSubVal)';

if (_coreListChecker.isAssignableFromType(targetType)) {
output += '$optionalQuestion.toList()';
Expand Down
16 changes: 7 additions & 9 deletions json_serializable/lib/src/type_helpers/map_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@

import 'package:analyzer/dart/element/type.dart';

import '../constants.dart';
import '../shared_checkers.dart';
import '../type_helper.dart';
import '../type_helper_context.dart';
import '../utils.dart';

/// Name used for closure argument when generating calls to `map`.
final _closureArg = 'e';

class MapHelper extends TypeHelper {
const MapHelper();

Expand All @@ -29,9 +27,9 @@ class MapHelper extends TypeHelper {

_checkSafeKeyType(expression, keyType);

var subFieldValue = context.serialize(valueType, _closureArg);
var subFieldValue = context.serialize(valueType, closureArg);

if (_closureArg == subFieldValue) {
if (closureArg == subFieldValue) {
return expression;
}

Expand All @@ -41,13 +39,13 @@ class MapHelper extends TypeHelper {
method = '${method}HandleNull';
}

return '$method<$keyType, $valueType>($expression, ($_closureArg) => $subFieldValue)';
return '$method<$keyType, $valueType>($expression, ($closureArg) => $subFieldValue)';
}

final optionalQuestion = context.nullable ? '?' : '';

return '$expression$optionalQuestion'
'.map((k, $_closureArg) => new MapEntry(k, $subFieldValue))';
'.map((k, $closureArg) => new MapEntry(k, $subFieldValue))';
}

@override
Expand Down Expand Up @@ -89,7 +87,7 @@ class MapHelper extends TypeHelper {
// In this case, we're going to create a new Map with matching reified
// types.

final itemSubVal = context.deserialize(valueArg, _closureArg);
final itemSubVal = context.deserialize(valueArg, closureArg);

final optionalQuestion = context.nullable ? '?' : '';

Expand All @@ -99,7 +97,7 @@ class MapHelper extends TypeHelper {
(isAnyMap && !_isObjectOrDynamic(keyArg)) ? 'k as String' : 'k';

return '($expression $mapCast)$optionalQuestion'
'.map((k, $_closureArg) => new MapEntry($keyUsage, $itemSubVal))';
'.map((k, $closureArg) => new MapEntry($keyUsage, $itemSubVal))';
}
}

Expand Down
2 changes: 1 addition & 1 deletion json_serializable/test/json_serializable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ abstract class _$OrderSerializerMixin {
group('includeIfNull', () {
test('some', () async {
var output = await runForElementNamed('IncludeIfNullAll');
expect(output, isNot(contains(toJsonMapVarName)));
expect(output, isNot(contains(generatedLocalVarName)));
expect(output, isNot(contains(toJsonMapHelperName)));
});

Expand Down
6 changes: 3 additions & 3 deletions json_serializable/test/kitchen_sink_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ final _validValues = const {
'dynamicIntMap': const {},
'objectDateTimeMap': const <String, dynamic>{},
'crazyComplex': const [],
toJsonMapVarName: const {},
generatedLocalVarName: const {},
toJsonMapHelperName: null,
r'$string': null,
'simpleObject': const {'value': 42},
Expand All @@ -310,7 +310,7 @@ final _invalidValueTypes = const {
'dynamicIntMap': const {'key': 'value'},
'objectDateTimeMap': const {'key': 42},
'crazyComplex': const [true],
toJsonMapVarName: const {'key': 42},
generatedLocalVarName: const {'key': 42},
toJsonMapHelperName: 42,
r'$string': true,
'simpleObject': 42,
Expand All @@ -330,5 +330,5 @@ final _excludeIfNullKeys = const [
'iterable',
'dateTimeList',
'crazyComplex',
toJsonMapVarName
generatedLocalVarName
];
6 changes: 3 additions & 3 deletions json_serializable/test/test_files/json_test_example.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
json[r'$house'] == null
? null
: House.values
.singleWhere((x) => x.toString() == 'House.${json[r'$house']}'),
.singleWhere((e) => e.toString() == 'House.${json[r'$house']}'),
middleName: json['middleName'] as String,
dateOfBirth: json['dateOfBirth'] == null
? null
Expand All @@ -29,7 +29,7 @@ Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
k,
e == null
? null
: House.values.singleWhere((x) => x.toString() == 'House.$e')));
: House.values.singleWhere((e) => e.toString() == 'House.$e')));

abstract class _$PersonSerializerMixin {
String get firstName;
Expand All @@ -53,7 +53,7 @@ abstract class _$PersonSerializerMixin {

Order _$OrderFromJson(Map<String, dynamic> json) => new Order(
Category.values
.singleWhere((x) => x.toString() == 'Category.${json['category']}'),
.singleWhere((e) => e.toString() == 'Category.${json['category']}'),
(json['items'] as List)?.map(
(e) => e == null ? null : new Item.fromJson(e as Map<String, dynamic>)))
..count = json['count'] as int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ part of 'json_test_example.non_nullable.dart';
Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
json['firstName'] as String,
json['lastName'] as String,
House.values.singleWhere((x) => x.toString() == 'House.${json[r'$house']}'),
House.values.singleWhere((e) => e.toString() == 'House.${json[r'$house']}'),
middleName: json['middleName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String))
..order = new Order.fromJson(json['order'] as Map<String, dynamic>)
..houseMap = (json['houseMap'] as Map<String, dynamic>).map((k, e) =>
new MapEntry(
k, House.values.singleWhere((x) => x.toString() == 'House.$e')));
k, House.values.singleWhere((e) => e.toString() == 'House.$e')));

abstract class _$PersonSerializerMixin {
String get firstName;
Expand All @@ -43,7 +43,7 @@ abstract class _$PersonSerializerMixin {

Order _$OrderFromJson(Map<String, dynamic> json) => new Order(
Category.values
.singleWhere((x) => x.toString() == 'Category.${json['category']}'),
.singleWhere((e) => e.toString() == 'Category.${json['category']}'),
(json['items'] as List)
.map((e) => new Item.fromJson(e as Map<String, dynamic>)))
..count = json['count'] as int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ part of 'json_test_example.non_nullable.wrapped.dart';
Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
json['firstName'] as String,
json['lastName'] as String,
House.values.singleWhere((x) => x.toString() == 'House.${json[r'$house']}'),
House.values.singleWhere((e) => e.toString() == 'House.${json[r'$house']}'),
middleName: json['middleName'] as String,
dateOfBirth: DateTime.parse(json['dateOfBirth'] as String))
..order = new Order.fromJson(json['order'] as Map<String, dynamic>)
..houseMap = (json['houseMap'] as Map<String, dynamic>).map((k, e) =>
new MapEntry(
k, House.values.singleWhere((x) => x.toString() == 'House.$e')));
k, House.values.singleWhere((e) => e.toString() == 'House.$e')));

abstract class _$PersonSerializerMixin {
String get firstName;
Expand Down Expand Up @@ -74,7 +74,7 @@ class _$PersonJsonMapWrapper extends $JsonMapWrapper {

Order _$OrderFromJson(Map<String, dynamic> json) => new Order(
Category.values
.singleWhere((x) => x.toString() == 'Category.${json['category']}'),
.singleWhere((e) => e.toString() == 'Category.${json['category']}'),
(json['items'] as List)
.map((e) => new Item.fromJson(e as Map<String, dynamic>)))
..count = json['count'] as int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
json[r'$house'] == null
? null
: House.values
.singleWhere((x) => x.toString() == 'House.${json[r'$house']}'),
.singleWhere((e) => e.toString() == 'House.${json[r'$house']}'),
middleName: json['middleName'] as String,
dateOfBirth: json['dateOfBirth'] == null
? null
Expand All @@ -29,7 +29,7 @@ Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
k,
e == null
? null
: House.values.singleWhere((x) => x.toString() == 'House.$e')));
: House.values.singleWhere((e) => e.toString() == 'House.$e')));

abstract class _$PersonSerializerMixin {
String get firstName;
Expand Down Expand Up @@ -84,7 +84,7 @@ class _$PersonJsonMapWrapper extends $JsonMapWrapper {

Order _$OrderFromJson(Map<String, dynamic> json) => new Order(
Category.values
.singleWhere((x) => x.toString() == 'Category.${json['category']}'),
.singleWhere((e) => e.toString() == 'Category.${json['category']}'),
(json['items'] as List)?.map(
(e) => e == null ? null : new Item.fromJson(e as Map<String, dynamic>)))
..count = json['count'] as int
Expand Down