Skip to content

Finish implementation of defaultValue #191

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 29, 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
10 changes: 7 additions & 3 deletions json_annotation/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@

* Added `JsonKey.defaultValue`.

* Added helpers for deserialization of `enum` values.
These functions starting with `$` are referenced by generated code.
They are not meant for direct use.

## 0.2.5

* Added `CheckedFromJsonException` which is thrown by code generated when
`checked` is enabled in `json_serializable`.

* Added functions to support the `checked` generation option. These
functions start with `$` are referenced by generated code. They are not meant
for direct use.
* Added functions to support the `checked` generation option.
These functions starting with `$` are referenced by generated code.
They are not meant for direct use.

## 0.2.4

Expand Down
42 changes: 42 additions & 0 deletions json_annotation/lib/src/json_serializable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,45 @@ class JsonKey {
this.toJson,
this.defaultValue});
}

// Until enum supports parse: github.com/dart-lang/sdk/issues/33244
/// *Helper function used in generated code with `enum` values – should not be
/// used directly.*
///
/// Returns an enum instance corresponding to [enumValue] from the enum named
/// [enumName] with [values].
///
/// If [enumValue] is null or no corresponding values exists, an `ArgumentError`
/// is thrown.
///
/// Given an enum named `Example`, an invocation would look like
///
/// ```dart
/// $enumDecode('Example', Example.values, 'desiredValue')
/// ```
T $enumDecode<T>(String enumName, List<T> values, String enumValue) =>
values.singleWhere((e) => e.toString() == '$enumName.$enumValue',
orElse: () => throw new ArgumentError(
'`$enumValue` is not one of the supported values: '
'${values.map(_nameForEnumValue).join(', ')}'));

/// *Helper function used in generated code with `enum` values – should not be
/// used directly.*
///
/// Returns an enum instance corresponding to [enumValue] from the enum named
/// [enumName] with [values].
///
/// If [enumValue] is `null`, `null` is returned.
///
/// If no corresponding values exists, an `ArgumentError` is thrown.
///
/// Given an enum named `Example`, an invocation would look like
///
/// ```dart
/// $enumDecodeNullable('Example', Example.values, 'desiredValue')
/// ```
T $enumDecodeNullable<T>(String enumName, List<T> values, String enumValue) =>
enumValue == null ? null : $enumDecode(enumName, values, enumValue);

// Until enum has a name property: github.com/dart-lang/sdk/issues/21712
String _nameForEnumValue(Object value) => value.toString().split('.')[1];
2 changes: 2 additions & 0 deletions json_serializable/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

* Added support for `JsonKey.defaultValue`.

* `enum` deserialization now uses helpers provided by `json_annotation`.

* Small change to how nullable `Map` values are deserialized.

* Small whitespace changes to `JsonLiteral` generation to align with `dartfmt`.
Expand Down
37 changes: 20 additions & 17 deletions json_serializable/lib/src/generator_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -382,34 +382,37 @@ class ${_wrapperClassName(true)} extends \$JsonMapWrapper {
String _deserializeForField(FieldElement field,
{ParameterElement ctorParam, bool checkedProperty}) {
checkedProperty ??= false;
var defaultValue = jsonKeyFor(field).defaultValue;
var jsonKeyName = _safeNameAccess(field);

var targetType = ctorParam?.type ?? field.type;
var contextHelper = _getHelperContext(field);

String value;
try {
if (_generator.checked) {
// TODO: default value fun here!
var value = _getHelperContext(field).deserialize(targetType, 'v');
if (checkedProperty) {
return value;
value = contextHelper.deserialize(targetType, 'v');
if (!checkedProperty) {
value = '\$checkedConvert(json, $jsonKeyName, (v) => $value)';
}
} else {
assert(!checkedProperty,
'should only be true if `_generator.checked` is true.');

return '\$checkedConvert(json, $jsonKeyName, (v) => $value)';
}
assert(!checkedProperty,
'should only be true if `_generator.checked` is true.');

var value = _getHelperContext(field)
.deserialize(targetType, 'json[$jsonKeyName]');

if (defaultValue != null) {
value = '$value ?? $defaultValue';
value = contextHelper.deserialize(targetType, 'json[$jsonKeyName]');
}
return value;
} on UnsupportedTypeError catch (e) {
throw _createInvalidGenerationError('fromJson', field, e);
}

var defaultValue = jsonKeyFor(field).defaultValue;
if (defaultValue != null) {
if (!contextHelper.nullable) {
throwUnsupported(field,
'Cannot use `defaultValue` on a field with `nullable` false.');
}

value = '$value ?? $defaultValue';
}
return value;
}

TypeHelperContext _getHelperContext(FieldElement field) {
Expand Down
73 changes: 52 additions & 21 deletions json_serializable/lib/src/json_key_helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import 'package:meta/meta.dart' show alwaysThrows;
import 'package:source_gen/source_gen.dart';

import 'json_literal_generator.dart';
import 'utils.dart';

@alwaysThrows
T _throwUnsupported<T>(FieldElement element, String message) =>
void throwUnsupported(FieldElement element, String message) =>
throw new InvalidGenerationSourceError(
'Error with `@JsonKey` on `${element.name}`. $message',
element: element);
Expand Down Expand Up @@ -45,41 +46,71 @@ JsonKeyWithConversion _from(FieldElement element) {
var fromJsonName = _getFunctionName(obj, element, true);
var toJsonName = _getFunctionName(obj, element, false);

Object _getLiteral(DartObject dartObject) {
Object _getLiteral(DartObject dartObject, Iterable<String> things) {
if (dartObject.isNull) {
return null;
}

var reader = new ConstantReader(dartObject);

String badType;
if (reader.isSymbol) {
_throwUnsupported(element,
'Values of type `Symbol` are not supported for `defaultValue`.');
badType = 'Symbol';
} else if (reader.isType) {
_throwUnsupported(element,
'Values of type `Type` are not supported for `defaultValue`.');
badType = 'Type';
} else if (dartObject.type is FunctionType) {
// TODO(kevmoo): Support calling function for the default value?
badType = 'Function';
} else if (!reader.isLiteral) {
_throwUnsupported(
element, 'The provided `defaultValue` is not a literal: $dartObject');
badType = dartObject.type.name;
}

if (badType != null) {
badType = things.followedBy([badType]).join(' > ');
throwUnsupported(
element, '`defaultValue` is `$badType`, it must be a literal.');
}

var literal = reader.literalValue;

if (literal is num || literal is String || literal is bool) {
return literal;
} else if (literal is List<DartObject>) {
return literal.map(_getLiteral).toList();
} else if (literal is Map<DartObject, DartObject>) {
return literal
.map((k, v) => new MapEntry(_getLiteral(k), _getLiteral(v)));
.map((e) => _getLiteral(e, things.followedBy(['List'])))
.toList();
} else if (literal is Map<DartObject, DartObject>) {
var mapThings = things.followedBy(['Map']);
return literal.map((k, v) =>
new MapEntry(_getLiteral(k, mapThings), _getLiteral(v, mapThings)));
}
_throwUnsupported(
element, 'The provided value is not supported: $dartObject');
}

var defaultValueLiteral = _getLiteral(obj.getField('defaultValue'));
badType = things.followedBy(['$dartObject']).join(' > ');

if (defaultValueLiteral != null) {
defaultValueLiteral = jsonLiteralAsDart(defaultValueLiteral, false);
throwUnsupported(
element,
'The provided value is not supported: $badType. '
'This may be an error in package:json_serializable. '
'Please rerun your build with `--verbose` and file an issue.');
}

var defaultValueObject = obj.getField('defaultValue');

Object defaultValueLiteral;
if (isEnum(defaultValueObject.type)) {
var interfaceType = defaultValueObject.type as InterfaceType;
var allowedValues = interfaceType.accessors
.where((p) => p.returnType == interfaceType)
.map((p) => p.name)
.toList();
var enumValueIndex = defaultValueObject.getField('index').toIntValue();
defaultValueLiteral =
'${interfaceType.name}.${allowedValues[enumValueIndex]}';
} else {
defaultValueLiteral = _getLiteral(defaultValueObject, []);
if (defaultValueLiteral != null) {
defaultValueLiteral = jsonLiteralAsDart(defaultValueLiteral, false);
}
}

return new JsonKeyWithConversion._(
Expand Down Expand Up @@ -130,7 +161,7 @@ ConvertData _getFunctionName(
var type = objectValue.type as FunctionType;

if (type.element is MethodElement) {
_throwUnsupported(
throwUnsupported(
element,
'The function provided for `$paramName` must be top-level. '
'Static class methods (`${type.element.name}`) are not supported.');
Expand All @@ -140,7 +171,7 @@ ConvertData _getFunctionName(
if (functionElement.parameters.isEmpty ||
functionElement.parameters.first.isNamed ||
functionElement.parameters.where((pe) => !pe.isOptional).length > 1) {
_throwUnsupported(
throwUnsupported(
element,
'The `$paramName` function `${functionElement.name}` must have one '
'positional paramater.');
Expand All @@ -155,7 +186,7 @@ ConvertData _getFunctionName(
// to the `fromJson` function.
// TODO: consider adding error checking here if there is confusion.
} else if (!returnType.isAssignableTo(element.type)) {
_throwUnsupported(
throwUnsupported(
element,
'The `$paramName` function `${functionElement.name}` return type '
'`$returnType` is not compatible with field type `${element.type}`.');
Expand All @@ -166,7 +197,7 @@ ConvertData _getFunctionName(
// to the `fromJson` function.
// TODO: consider adding error checking here if there is confusion.
} else if (!element.type.isAssignableTo(argType)) {
_throwUnsupported(
throwUnsupported(
element,
'The `$paramName` function `${functionElement.name}` argument type '
'`$argType` is not compatible with field type'
Expand Down
18 changes: 4 additions & 14 deletions json_serializable/lib/src/type_helpers/enum_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

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

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

Expand All @@ -31,18 +30,9 @@ class EnumHelper extends TypeHelper {
return null;
}

var wrappedExpression =
simpleExpression.hasMatch(expression) ? expression : '{$expression}';

var closureArg = consts.closureArg;
if (closureArg == wrappedExpression) {
closureArg = '${closureArg}2';
}

return commonNullPrefix(
context.nullable,
expression,
'$targetType.values.singleWhere(($closureArg) => $closureArg.toString()'
" == '$targetType.\$$wrappedExpression')");
var functionName =
context.nullable ? r'$enumDecodeNullable' : r'$enumDecode';
return "$functionName('$targetType', $targetType.values, "
'$expression as String)';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,27 @@
// GENERATED CODE - DO NOT MODIFY BY HAND

// **************************************************************************
// Generator: _NonNullableGenerator
// Generator: _CheckedGenerator
// **************************************************************************

// ignore_for_file: annotate_overrides

import 'package:json_annotation/json_annotation.dart';

part 'default_value.non_nullable.g.dart';
import 'default_value_interface.dart' as dvi hide Greek;
import 'default_value_interface.dart' show Greek;

part 'default_value.checked.g.dart';

const _intValue = 42;

@JsonSerializable(nullable: false)
class DefaultValue extends Object with _$DefaultValueSerializerMixin {
dvi.DefaultValue fromJson(Map<String, dynamic> json) =>
_$DefaultValueFromJson(json);

@JsonSerializable()
class DefaultValue extends Object
with _$DefaultValueSerializerMixin
implements dvi.DefaultValue {
@JsonKey(defaultValue: true)
bool fieldBool;

Expand Down Expand Up @@ -47,6 +55,9 @@ class DefaultValue extends Object with _$DefaultValueSerializerMixin {
})
Map<String, List<String>> fieldMapListString;

@JsonKey(defaultValue: Greek.beta)
Greek fieldEnum;

DefaultValue();

factory DefaultValue.fromJson(Map<String, dynamic> json) =>
Expand Down
Loading