Skip to content

Commit

Permalink
Fix fromJson generates wrong code if a number has default value
Browse files Browse the repository at this point in the history
  • Loading branch information
spideythewebhead committed Jan 6, 2024
1 parent b756f2a commit c2f66c8
Showing 1 changed file with 31 additions and 22 deletions.
53 changes: 31 additions & 22 deletions package/lib/src/backend/core/generators/from_json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -169,47 +169,56 @@ class FromJsonGenerator implements Generator {
await _parsePrimary(
dartType: dartType,
parentVariableName: parentVariableName,
defaultValue: defaultValue,
);

if (dartType.isPrimitive && defaultValue != null) {
if (dartType.isNullable) {
_logger.warning('Declared a nullable type ${dartType.fullTypeName} with default');
} else {
_codeWriter.writeln('?');
}
_codeWriter.write(' ?? $defaultValue');
}

_codeWriter.writeln(',');
}

Future<void> _parsePrimary({
required final TachyonDartType dartType,
required final String parentVariableName,
required final Expression? defaultValue,
}) async {
if (dartType.isDynamic) {
_codeWriter.writeln(parentVariableName);
return;
}

if (dartType.isPrimitive) {
if (dartType.isDouble) {
if (dartType.isNullable) {
_codeWriter.write('($parentVariableName as num?)?.toDouble()');
return;
}
_codeWriter.write('($parentVariableName as num).toDouble()');
if (dartType.isDouble) {
if (defaultValue != null) {
_codeWriter.write('($parentVariableName as num?)?.toDouble() ?? $defaultValue');
return;
}
if (dartType.isInt) {
if (dartType.isNullable) {
_codeWriter.write('($parentVariableName as num?)?.toInt()');
return;
}
_codeWriter.write('($parentVariableName as num).toInt()');
if (dartType.isNullable) {
_codeWriter.write('($parentVariableName as num?)?.toDouble()');
return;
}
_codeWriter.write('($parentVariableName as num).toDouble()');
return;
}

if (dartType.isInt) {
if (defaultValue != null) {
_codeWriter.write('($parentVariableName as num?)?.toInt() ?? $defaultValue');
return;
}
if (dartType.isNullable) {
_codeWriter.write('($parentVariableName as num?)?.toInt()');
return;
}
_codeWriter.write('($parentVariableName as num).toInt()');
return;
}

if (dartType.isPrimitive) {
_codeWriter.write('$parentVariableName as ${dartType.fullTypeName}');
if (!dartType.isNullable && defaultValue != null) {
_codeWriter.write('?');
}
if (defaultValue != null) {
_codeWriter.write(' ?? $defaultValue');
}
return;
}

Expand Down

0 comments on commit c2f66c8

Please sign in to comment.