[BUG][DART] Fields named json get shadowed by ToJson and become unserializable due to cyclic pointer reference
Created by: 0xNF
Bug Report Checklist
-
Have you provided a full/minimal spec to reproduce the issue? -
Have you validated the input using an OpenAPI validator (example)? -
Have you tested with the latest master to confirm the issue still exists? -
Have you searched for related issues/PRs? -
What's the actual output vs expected output? -
[Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
Here's a repo for the issue: https://github.com/0xNF/openapi_gen_dart_json_shadow
The Dart SDK generator will incorrectly shadow field variables named json
in the generated toJson()
method, resulting in a cyclic pointer loop when running the toJson()
method.
openapi-generator version
jar name: openapi-generator-cli-6.0.0-20220412.074015-127.jar
jar version: 6.0.0-SNAPSHOT
OpenAPI declaration file content or url
openapi: 3.0.3
info:
version: "1.0"
title: Dart Shadow Json Demo
servers:
- url: 'localhost'
variables:
host:
default: localhost
components:
schemas:
ItemWithFieldNamedJson:
type: object
properties:
json:
type: object
additionalProperties: {}
paths:
/:
get:
operationId: shadow
responses:
'200':
description: produces a shadowed json field when generated in dart
content:
application/json:
schema:
$ref: '#/components/schemas/ItemWithFieldNamedJson'
Generation Details
class ItemWithFieldNamedJson {
ItemWithFieldNamedJson({
this.json = const {},
});
Map<String, Object> json;
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
json[r'json'] = json;
return json;
}
Steps to reproduce
- Run the generator command
java -jar openapi-generator-cli-6.0.0-20220412.074015-127.jar generate -i .\shadowspec.yaml -g dart -o shadowed
- Examine the
shadowed/lib/model/item_with_field_named_json.dart
- See the shadowed variable on line 34, and the infinite reference on line 35
Related issues/PRs
Use another parameter name to stop variable shadowing. related to https://github.com/OpenAPITools/openapi-generator/pull/10263
Suggest a fix
The hard fix:
- For any variables that are generated by the Generator, use static analysis to determine if there are any conflicting variable names in the namespace in the generated functions, and then modify the desired generated variable name appropriately, repeating as many times as necessary to ensure truly unique variable names within the functions scope.
The easier fix:
- The Dart generator already knows about reserved keywords. For fields that are named
int
, generated fields are namedint_
with an underscore. Extend this idea tojson
. This is a half measure though, as if I name my field variablejson_
, then we're back to being shadowed.