Skip to content
Open
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
7 changes: 4 additions & 3 deletions aas_core_codegen/java/lib/_generate_enhancing.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ def _generate_transform(cls: intermediate.ConcreteClass) -> Stripped:
optional = isinstance(prop.type_annotation, intermediate.OptionalTypeAnnotation)

value_wrap = _generate_wrap_expr(
f"that.{getter_name}().get()" if optional else f"that.{getter_name}()",
"value" if optional else f"that.{getter_name}()",
intermediate.beneath_optional(prop.type_annotation),
descendability,
)
Expand All @@ -694,11 +694,12 @@ def _generate_transform(cls: intermediate.ConcreteClass) -> Stripped:
)

if optional:
# Call the getter only once as it allocates an ``Optional``.
stmt = Stripped(
f"""\
if (that.{getter_name}().isPresent()) {{
that.{getter_name}().ifPresent(value -> {{
{I}{indent_but_first_line(stmt, I)}
}}"""
}});"""
)

blocks.append(stmt)
Expand Down
2 changes: 1 addition & 1 deletion aas_core_codegen/java/lib/_generate_jsonization.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ def _generate_from_object_body(
foreach_writer = io.StringIO()
foreach_writer.write(
f"""\
for (Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); iterator.hasNext(); ) {{
for (Iterator<Map.Entry<String, JsonNode>> iterator = node.properties().iterator(); iterator.hasNext(); ) {{
{I}final Map.Entry<String, JsonNode> keyValue = iterator.next();
{I}final String key = keyValue.getKey();
"""
Expand Down
18 changes: 6 additions & 12 deletions aas_core_codegen/java/lib/_generate_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1053,21 +1053,14 @@ def _generate_mandatory_constructor(
"""
Generate a default constructor for the given concrete class ``cls``.

Return empty string if there is an empty constructor or no default constructor
can be constructed.
Return empty string if there is an empty constructor.
"""
if (
len(cls.constructor.arguments) == 0
and len(cls.constructor.inlined_statements) == 0
):
return Stripped(""), None

if all(
isinstance(arg.type_annotation, intermediate.OptionalTypeAnnotation)
for arg in cls.constructor.arguments
):
return Stripped(""), None

cls_name = java_naming.class_name(cls.name)

blocks: List[str] = []
Expand All @@ -1085,9 +1078,9 @@ def _generate_mandatory_constructor(

arg_codes.append(Stripped(f"{arg_type} {arg_name}"))

assert len(arg_codes) > 0

if len(arg_codes) == 1:
if len(arg_codes) == 0:
blocks.append(f"public {cls_name}() {{")
elif len(arg_codes) == 1:
blocks.append(f"public {cls_name}({arg_codes[0]}) {{")
else:
arg_block = ",\n".join(arg_codes)
Expand Down Expand Up @@ -1170,7 +1163,8 @@ def _generate_mandatory_constructor(
else:
assert_never(stmt)

blocks.append("\n".join(textwrap.indent(stmt_code, I) for stmt_code in body))
if len(body) > 0:
blocks.append("\n".join(textwrap.indent(stmt_code, I) for stmt_code in body))

blocks.append("}")

Expand Down
91 changes: 86 additions & 5 deletions aas_core_codegen/java/lib/_generate_verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io
import textwrap
from typing import (
Dict,
List,
Mapping,
Optional,
Expand Down Expand Up @@ -678,6 +679,33 @@ def _generate_enum_value_sets(symbol_table: intermediate.SymbolTable) -> Strippe
return Stripped(writer.getvalue())


class _HoistedOptionals:
"""Collect the ``Optional`` properties of ``that`` which are read once."""

def __init__(self) -> None:
"""Initialize with no properties hoisted."""
self._declarations: Dict[Identifier, Stripped] = dict()
self._locals: Dict[Identifier, Stripped] = dict()

def hoist(self, prop: intermediate.Property) -> Stripped:
"""Declare the local variable for ``prop`` and return its name."""
local = self._locals.get(prop.name, None)
if local is None:
local = Stripped(java_naming.variable_name(Identifier(f"that_{prop.name}")))
prop_type = java_common.generate_type(prop.type_annotation)
getter_name = java_naming.getter_name(prop.name)
self._locals[prop.name] = local
self._declarations[prop.name] = Stripped(
f"final {prop_type} {local} = that.{getter_name}();"
)

return local

def declarations(self) -> List[Stripped]:
"""List the declarations of all the hoisted variables."""
return list(self._declarations.values())


class _InvariantTranspiler(java_transpilation.Transpiler):
def __init__(
self,
Expand All @@ -691,6 +719,7 @@ def __init__(
environment: intermediate_type_inference.Environment,
downcast_map: Mapping[parse_tree.Node, intermediate_type_inference.Downcast],
symbol_table: intermediate.SymbolTable,
hoisted: _HoistedOptionals,
) -> None:
"""Initialize with the given values."""
java_transpilation.Transpiler.__init__(
Expand All @@ -702,6 +731,38 @@ def __init__(
)

self._symbol_table = symbol_table
self._hoisted = hoisted

def transform_member(
self, node: parse_tree.Member
) -> Tuple[Optional[Stripped], Optional[Error]]:
code, error = super().transform_member(node)
if error is not None:
return None, error

assert code is not None

# Every call of an optional getter allocates an ``Optional``, so we read
# each optional property of ``that`` once and refer to the local variable.
if (
isinstance(node.instance, parse_tree.Name)
and node.instance.identifier == "self"
and self._optional_map[node]
):
instance_type = intermediate_type_inference.beneath_optional(
self.type_map[node.instance]
)
assert isinstance(
instance_type, intermediate_type_inference.OurTypeAnnotation
) and isinstance(instance_type.our_type, intermediate.Class)

prop = instance_type.our_type.properties_by_name[node.name]
local = self._hoisted.hoist(prop)
getter_call = f"that.{java_naming.getter_name(prop.name)}()"
assert code.startswith(getter_call), code
return Stripped(local + code[len(getter_call) :]), None

return code, None

def transform_name(
self, node: parse_tree.Name
Expand Down Expand Up @@ -742,8 +803,9 @@ def _transpile_invariant(
invariant: intermediate.Invariant,
symbol_table: intermediate.SymbolTable,
type_inference: intermediate_type_inference.TypeInference,
hoisted: _HoistedOptionals,
) -> Tuple[Optional[Stripped], Optional[Error]]:
"""Translate the invariant from the meta-model into C# code."""
"""Translate the invariant from the meta-model into Java code."""
inference = type_inference.by_invariant[invariant]
environment = inference.environment_with_self
type_map = inference.type_map
Expand All @@ -768,6 +830,7 @@ def _transpile_invariant(
environment=environment,
downcast_map=inference.downcast_map,
symbol_table=symbol_table,
hoisted=hoisted,
)

expr, error = transpiler.transform(invariant.parsed.body)
Expand Down Expand Up @@ -1123,6 +1186,7 @@ def _generate_transform_for_class(
"""Generate the transform method to errors for the given concrete class."""
errors: List[Error] = []
blocks: List[Stripped] = []
hoisted = _HoistedOptionals()

name = java_naming.class_name(cls.name)

Expand All @@ -1131,6 +1195,7 @@ def _generate_transform_for_class(
invariant=invariant,
symbol_table=symbol_table,
type_inference=type_inference,
hoisted=hoisted,
)
if error is not None:
errors.append(
Expand Down Expand Up @@ -1159,9 +1224,11 @@ def _generate_transform_for_class(

optional = isinstance(prop.type_annotation, intermediate.OptionalTypeAnnotation)

source_expr = (
f"that.{getter_name}().get()" if optional else f"that.{getter_name}()"
)
if optional:
local = hoisted.hoist(prop)
source_expr = f"{local}.get()"
else:
source_expr = f"that.{getter_name}()"

block = Stripped(
f"""\
Expand All @@ -1178,7 +1245,7 @@ def _generate_transform_for_class(
if optional:
block = Stripped(
f"""\
if (that.{getter_name}().isPresent()) {{
if ({local}.isPresent()) {{
{I}{indent_but_first_line(block, I)}
}}"""
)
Expand Down Expand Up @@ -1208,6 +1275,13 @@ def _generate_transform_for_class(
"""
)

for declaration in hoisted.declarations():
writer.write(textwrap.indent(declaration, I))
writer.write("\n")

if len(hoisted.declarations()) > 0:
writer.write("\n")

for i, stmt in enumerate(blocks):
if i > 0:
writer.write("\n\n")
Expand Down Expand Up @@ -1618,6 +1692,7 @@ def _generate_verify_constrained_primitive(
invariant=invariant,
symbol_table=symbol_table,
type_inference=type_inference,
hoisted=_HoistedOptionals(),
)
if error is not None:
errors.append(
Expand Down Expand Up @@ -1813,9 +1888,15 @@ def generate(
):
imports.append(Stripped("import java.util.List;"))

# NOTE:
# The verification of a class reads its optional properties as ``Optional``.
if any(
isinstance(type_annotation, intermediate.OptionalTypeAnnotation)
for type_annotation in signature_type_annotations
) or any(
isinstance(prop.type_annotation, intermediate.OptionalTypeAnnotation)
for cls in symbol_table.concrete_classes
for prop in cls.properties
):
imports.append(Stripped("import java.util.Optional;"))

Expand Down
3 changes: 2 additions & 1 deletion aas_core_codegen/java/lib/_generate_xml_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,7 @@ def _generate_write_element(uses_json_types: bool) -> Stripped:
* <p>This is what an item of a list or of a tuple is written with. It
* contributes no segment to the error path: its container has already
* contributed the item's index, and the index selects this very element
* (see {{@link #writeListOf}} in the generated writers).
* (see {{@code writeListOf}} in the generated writers).
*/
public static <T> void writeElement(
{I}String name,
Expand Down Expand Up @@ -876,6 +876,7 @@ def generate(
Stripped("import javax.xml.stream.XMLStreamWriter;"),
Stripped("import java.util.Optional;"),
Stripped("import java.util.regex.Pattern;"),
Stripped(f"import {package}.types.model.*;"),
Stripped(f"import {package}.reporting.Reporting;"),
]

Expand Down
Loading
Loading