Skip to content

Commit

Permalink
Remove redundant initilaizations with None (#435)
Browse files Browse the repository at this point in the history
I (mristin) was not aware of the syntax such as `name: str` where mypy
forces name to be initialized in all the execution paths. Hence, I
previously always wrote:

```python
name = None  # type: Optional[str]

...

assert name is not None
```

which is unnecessarily verbose and includes a redundant is-not-None
check at the end.
  • Loading branch information
mristin authored Jan 19, 2024
1 parent 973926a commit 5a9b835
Show file tree
Hide file tree
Showing 46 changed files with 194 additions and 319 deletions.
3 changes: 2 additions & 1 deletion .idea/aas-core-csharp-codegen.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 8 additions & 12 deletions aas_core_codegen/cpp/constants/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,7 @@ def _generate_constant_set_of_primitives_definition(
writer.write(comment)
writer.write("\n")

# noinspection PyUnusedLocal
set_type = None # type: Optional[str]
set_type: Optional[str]

if constant.a_type is intermediate.PrimitiveType.BOOL:
set_type = "std::unordered_set<bool>"
Expand All @@ -220,8 +219,6 @@ def _generate_constant_set_of_primitives_definition(
assert_never(constant.a_type)
raise AssertionError("Unexpected execution path")

assert set_type is not None

constant_name = cpp_naming.constant_name(constant.name)

writer.write(
Expand All @@ -239,8 +236,7 @@ def _generate_constant_set_of_primitives_implementation(
"""Generate the implementation of a constant set of primitives."""
literal_codes = [] # type: List[str]

# noinspection PyUnusedLocal
set_type = None # type: Optional[str]
set_type: str

if constant.a_type is intermediate.PrimitiveType.BOOL:
set_type = "std::unordered_set<bool>"
Expand Down Expand Up @@ -290,8 +286,6 @@ def _generate_constant_set_of_primitives_implementation(
assert_never(constant.a_type)
raise AssertionError("Unexpected execution path")

assert set_type is not None

literals_joined = ",\n".join(literal_codes)

constant_name = cpp_naming.constant_name(constant.name)
Expand Down Expand Up @@ -431,8 +425,9 @@ def generate_header(
]

for constant in symbol_table.constants:
block = None # type: Optional[Stripped]
error = None # type: Optional[Error]
block: Optional[Stripped]
error: Optional[Error]

if isinstance(constant, intermediate.ConstantPrimitive):
block, error = _generate_constant_primitive_definition(constant=constant)
elif isinstance(constant, intermediate.ConstantSetOfPrimitives):
Expand Down Expand Up @@ -524,8 +519,9 @@ def generate_implementation(
]

for constant in symbol_table.constants:
block = None # type: Optional[Stripped]
error = None # type: Optional[Error]
block: Optional[Stripped]
error: Optional[Error]

if isinstance(constant, intermediate.ConstantPrimitive):
block, error = _generate_constant_primitive_implementation(
constant=constant
Expand Down
11 changes: 3 additions & 8 deletions aas_core_codegen/cpp/description.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def transform_text(
def transform_reference_to_our_type_in_doc(
self, element: intermediate_doc.ReferenceToOurType
) -> Tuple[Optional[str], Optional[List[str]]]:
result = None # type: Optional[str]
result: str

if isinstance(
element.our_type,
Expand All @@ -191,7 +191,7 @@ def transform_reference_to_our_type_in_doc(
intermediate.ConcreteClass,
),
):
name = None # type: Optional[str]
name: str

if isinstance(element.our_type, intermediate.Enumeration):
name = cpp_naming.enum_name(element.our_type.name)
Expand All @@ -208,8 +208,6 @@ def transform_reference_to_our_type_in_doc(
else:
assert_never(element.our_type)

assert name is not None

if self.context.namespace == cpp_common.TYPES_NAMESPACE:
result = f"{name}"
else:
Expand All @@ -226,13 +224,12 @@ def transform_reference_to_our_type_in_doc(
else:
assert_never(element.our_type)

assert result is not None
return result, None

def transform_reference_to_attribute_in_doc(
self, element: intermediate_doc.ReferenceToAttribute
) -> Tuple[Optional[str], Optional[List[str]]]:
result = None # type: Optional[str]
result: str

if isinstance(element.reference, intermediate_doc.ReferenceToProperty):
interface_name = cpp_naming.interface_name(element.reference.cls.name)
Expand All @@ -258,8 +255,6 @@ def transform_reference_to_attribute_in_doc(
else:
assert_never(element.reference)

assert result is not None

return result, None

def transform_reference_to_argument_in_doc(
Expand Down
4 changes: 1 addition & 3 deletions aas_core_codegen/cpp/jsonization/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1278,7 +1278,7 @@ def _generate_deserialize_property(
"""
type_anno = intermediate.beneath_optional(prop.type_annotation)

code = None # type: Optional[Stripped]
code: Stripped

if isinstance(type_anno, intermediate.PrimitiveTypeAnnotation):
code = _generate_deserialize_primitive_property(prop=prop, ok_type=ok_type)
Expand Down Expand Up @@ -1315,8 +1315,6 @@ def _generate_deserialize_property(
else:
assert_never(type_anno)

assert code is not None

if isinstance(prop.type_annotation, intermediate.OptionalTypeAnnotation):
json_prop_literal = cpp_common.string_literal(naming.json_property(prop.name))

Expand Down
3 changes: 1 addition & 2 deletions aas_core_codegen/cpp/optionaling.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,8 +470,7 @@ def transform_for_each(self, node: parse_tree.ForEach) -> Optional[Error]:
return None

def transform_for_range(self, node: parse_tree.ForRange) -> Optional[Error]:
# noinspection PyUnusedLocal
error = None # type: Optional[Error]
error: Optional[Error]

variable_type_in_env = self._environment.find(node.variable.identifier)
if variable_type_in_env is not None:
Expand Down
8 changes: 4 additions & 4 deletions aas_core_codegen/cpp/structure/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def _human_readable_identifier(
# code was nigh unreadable. So we preferred a little bit of copying to a little
# bit of complexity.

result = None # type: Optional[str]
result: str

if isinstance(something, intermediate.Enumeration):
result = f"meta-model enumeration {something.name!r}"
Expand All @@ -72,7 +72,6 @@ def _human_readable_identifier(
else:
assert_never(something)

assert result is not None
return result


Expand All @@ -94,7 +93,7 @@ def _verify_structure_name_collisions(
# region Inter-structure collisions

for enum_or_cls in itertools.chain(symbol_table.enumerations, symbol_table.classes):
names = None # type: Optional[List[Identifier]]
names: List[Identifier]

if isinstance(enum_or_cls, intermediate.Enumeration):
names = [cpp_naming.enum_name(enum_or_cls.name)]
Expand Down Expand Up @@ -1246,7 +1245,8 @@ def _generate_method_implementation(
spec_impls: specific_implementations.SpecificImplementations,
) -> Tuple[Optional[Stripped], Optional[Error]]:
"""Generate the implementation of the method."""
body = None # type: Optional[Stripped]
body: Optional[Stripped]

if isinstance(method, intermediate.ImplementationSpecificMethod):
implementation_key = specific_implementations.ImplementationKey(
f"types/{method.specified_for.name}/{method.name}.body.cpp"
Expand Down
23 changes: 6 additions & 17 deletions aas_core_codegen/cpp/transpilation.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,7 @@ def transform_member(
member_type = self.type_map[node]
member_type_beneath = intermediate_type_inference.beneath_optional(member_type)

# noinspection PyUnusedLocal
member_accessor = None # type: Optional[str]
member_accessor: str

if isinstance(
instance_type_beneath, intermediate_type_inference.OurTypeAnnotation
Expand Down Expand Up @@ -446,8 +445,6 @@ def transform_member(
f"the member {node.name!r} in {instance_type}.",
)

assert member_accessor is not None

assert isinstance(
instance_type_beneath, intermediate_type_inference.OurTypeAnnotation
) and isinstance(instance_type_beneath.our_type, intermediate.Class), (
Expand Down Expand Up @@ -638,8 +635,7 @@ def transform_method_call(
for arg_node in node.args:
arg_type = self.type_map[arg_node]

# noinspection PyUnusedLocal
arg = None # type: Optional[Stripped]
arg: Optional[Stripped]
if isinstance(arg_type, intermediate_type_inference.OptionalTypeAnnotation):
arg, error = self.transform(arg_node)
else:
Expand Down Expand Up @@ -684,8 +680,7 @@ def transform_function_call(
for arg_node in node.args:
arg_type = self.type_map[arg_node]

# noinspection PyUnusedLocal
arg = None # type: Optional[Stripped]
arg: Optional[Stripped]
if isinstance(arg_type, intermediate_type_inference.OptionalTypeAnnotation):
arg, error = self.transform(arg_node)
else:
Expand Down Expand Up @@ -986,7 +981,7 @@ def _transform_add_or_sub(
errors.append(error)

if len(errors) > 0:
operation_name = None # type: Optional[str]
operation_name: str
if isinstance(node, parse_tree.Add):
operation_name = "the addition"
elif isinstance(node, parse_tree.Sub):
Expand Down Expand Up @@ -1175,16 +1170,14 @@ def _transform_any_or_all(
if isinstance(node.generator, parse_tree.ForEach):
assert iteration is not None

qualifier_function = None # type: Optional[str]
qualifier_function: str
if isinstance(node, parse_tree.Any):
qualifier_function = cpp_naming.function_name(Identifier("Some"))
elif isinstance(node, parse_tree.All):
qualifier_function = cpp_naming.function_name(Identifier("All"))
else:
assert_never(node)

assert qualifier_function is not None

no_parentheses_types_in_this_context = (
parse_tree.Member,
parse_tree.MethodCall,
Expand Down Expand Up @@ -1221,16 +1214,13 @@ def _transform_any_or_all(
)

elif isinstance(node.generator, parse_tree.ForRange):
qualifier_function = None
if isinstance(node, parse_tree.Any):
qualifier_function = "SomeRange"
elif isinstance(node, parse_tree.All):
qualifier_function = "AllRange"
else:
assert_never(node)

assert qualifier_function is not None

assert start is not None
assert end is not None

Expand Down Expand Up @@ -1304,8 +1294,7 @@ def transform_assignment(
assert target is not None
assert target_type is not None

# noinspection PyUnusedLocal
value = None # type: Optional[Stripped]
value: Optional[Stripped]

if isinstance(
target_type, intermediate_type_inference.OptionalTypeAnnotation
Expand Down
4 changes: 1 addition & 3 deletions aas_core_codegen/cpp/visitation/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def _generate_recursive_visit_for_property(
else:
get_expr = Stripped(f"that->{getter}()")

code = None # type: Optional[Stripped]
code: Stripped

if isinstance(type_anno, intermediate.PrimitiveTypeAnnotation):
# No visits to primitive values.
Expand Down Expand Up @@ -371,8 +371,6 @@ def _generate_recursive_visit_for_property(
else:
assert_never(type_anno)

assert code is not None

if not isinstance(prop.type_annotation, intermediate.OptionalTypeAnnotation):
return Stripped(
f"""\
Expand Down
5 changes: 3 additions & 2 deletions aas_core_codegen/csharp/constants/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,8 +336,9 @@ def generate(
errors = [] # type: List[Error]

for constant in symbol_table.constants:
constants_block = None # type: Optional[Stripped]
error = None # type: Optional[Error]
constants_block: Optional[Stripped]
error: Optional[Error]

if isinstance(constant, intermediate.ConstantPrimitive):
constants_block, error = _generate_constant_primitive(constant=constant)
elif isinstance(constant, intermediate.ConstantSetOfPrimitives):
Expand Down
11 changes: 3 additions & 8 deletions aas_core_codegen/csharp/description.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def transform_text(
def transform_reference_to_our_type_in_doc(
self, element: intermediate_doc.ReferenceToOurType
) -> Tuple[Optional[_NodeUnion], Optional[List[str]]]:
name = None # type: Optional[str]
name: str

if isinstance(element.our_type, intermediate.Enumeration):
name = csharp_naming.enum_name(element.our_type.name)
Expand Down Expand Up @@ -204,8 +204,6 @@ def transform_reference_to_our_type_in_doc(

assert_never(element.our_type)

assert name is not None

# NOTE (mristin, 2022-06-19):
# We need to prefix the cref in case there are naming conflicts.
prefixed_name = f"Aas.{name}"
Expand All @@ -220,10 +218,10 @@ def transform_reference_to_our_type_in_doc(
def transform_reference_to_attribute_in_doc(
self, element: intermediate_doc.ReferenceToAttribute
) -> Tuple[Optional[_NodeUnion], Optional[List[str]]]:
cref = None # type: Optional[str]
cref: str

if isinstance(element.reference, intermediate_doc.ReferenceToProperty):
name_of_our_type = None # type: Optional[str]
name_of_our_type: str

if isinstance(element.reference.cls, intermediate.AbstractClass):
# We do not generate C# code for abstract classes, so we have to refer
Expand All @@ -244,7 +242,6 @@ def transform_reference_to_attribute_in_doc(

prop_name = csharp_naming.property_name(element.reference.prop.name)

assert name_of_our_type is not None
cref = f"{name_of_our_type}.{prop_name}"
elif isinstance(
element.reference, intermediate_doc.ReferenceToEnumerationLiteral
Expand Down Expand Up @@ -273,8 +270,6 @@ def transform_reference_to_attribute_in_doc(

assert_never(element.reference)

assert cref is not None

# NOTE (mristin, 2022-06-19):
# We need to prefix the cref in case there are naming conflicts.
prefixed_cref = f"Aas.{cref}"
Expand Down
4 changes: 1 addition & 3 deletions aas_core_codegen/csharp/enhancing/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def _generate_transform(cls: intermediate.ConcreteClass) -> Stripped:
type_anno = intermediate.beneath_optional(prop.type_annotation)
prop_name = csharp_naming.property_name(prop.name)

wrap_stmt = None # type: Optional[Stripped]
wrap_stmt: Stripped

if isinstance(type_anno, intermediate.PrimitiveTypeAnnotation):
# We can not enhance primitive types; nothing to do here.
Expand Down Expand Up @@ -320,8 +320,6 @@ def _generate_transform(cls: intermediate.ConcreteClass) -> Stripped:
else:
assert_never(type_anno.our_type)

assert wrap_stmt is not None

if isinstance(prop.type_annotation, intermediate.OptionalTypeAnnotation):
wrap_stmt = Stripped(
f"""\
Expand Down
Loading

0 comments on commit 5a9b835

Please sign in to comment.