Skip to content

Commit

Permalink
Check explicitly for invalid model type in C#
Browse files Browse the repository at this point in the history
Please see #510 for more details. This is a fix particularly for C#
generation.
  • Loading branch information
mristin committed Jul 19, 2024
1 parent cd92d20 commit 5b8e9d2
Show file tree
Hide file tree
Showing 3 changed files with 757 additions and 20 deletions.
52 changes: 50 additions & 2 deletions aas_core_codegen/csharp/jsonization/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
INDENT2 as II,
INDENT3 as III,
INDENT4 as IIII,
INDENT5 as IIIII,
)


Expand Down Expand Up @@ -381,6 +382,9 @@ def _generate_from_method_for_class(

blocks.append(Stripped(args_init_writer.getvalue()))

if cls.serialization.with_model_type:
blocks.append(Stripped("string? modelType = null;"))

# endregion

# region Switch on property name
Expand Down Expand Up @@ -419,11 +423,42 @@ def _generate_from_method_for_class(
return None, errors

if cls.serialization.with_model_type:
model_type = naming.json_model_type(cls.name)

cases.append(
Stripped(
"""\
f"""\
case "modelType":
continue;"""
{I}{{
{II}if (keyValue.Value == null)
{II}{{
{III}error = new Reporting.Error(
{IIII}"Expected a model type, but got null");
{III}return null;
{II}}}
{II}modelType = DeserializeImplementation.StringFrom(
{III}keyValue.Value,
{III}out error);
{II}if (error != null)
{II}{{
{III}error.PrependSegment(
{IIII}new Reporting.NameSegment(
{IIIII}"modelType"));
{III}return null;
{II}}}
{II}if (modelType != "{model_type}")
{II}{{
{III}error = new Reporting.Error(
{IIII}"Expected the model type '{model_type}', " +
{IIII}$"but got {{modelType}}");
{III}error.PrependSegment(
{IIII}new Reporting.NameSegment(
{IIIII}"modelType"));
{III}return null;
{II}}}
{II}break;
{I}}}"""
)
)

Expand Down Expand Up @@ -482,6 +517,19 @@ def _generate_from_method_for_class(

blocks.append(Stripped(required_check_writer.getvalue()))

if cls.serialization.with_model_type:
blocks.append(
Stripped(
f"""\
if (modelType == null)
{{
{I}error = new Reporting.Error(
{II}"Required property \\"modelType\\" is missing");
{I}return null;
}}"""
)
)

# endregion

# region Pass in arguments to the constructor
Expand Down
5 changes: 5 additions & 0 deletions aas_core_codegen/naming.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ def json_property(identifier: Identifier) -> Identifier:
@ensure(
lambda result: "_" not in result
) # This post-condition avoids naming conflicts with prefixing in the JSON schema.
@ensure(
lambda result: '"' not in result and "'" not in result and '\\' not in result
# This post-condition simplifies a lot of generator code since we can simply in-line
# the model type in strings.
)
# fmt: on
def json_model_type(identifier: Identifier) -> Identifier:
"""
Expand Down
Loading

0 comments on commit 5b8e9d2

Please sign in to comment.