Skip to content

Commit

Permalink
Uphold the naming consistency as commented at https://github.com/Open…
Browse files Browse the repository at this point in the history
…Cyphal/pydsdl/pull/101\#discussion_r1590898374 and replace a few deprecated typing entities with modern alternatives
  • Loading branch information
pavel-kirienko committed Jun 28, 2024
1 parent 37de400 commit c32dae1
Show file tree
Hide file tree
Showing 7 changed files with 141 additions and 133 deletions.
33 changes: 17 additions & 16 deletions pydsdl/_data_type_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
# This software is distributed under the terms of the MIT License.
# Author: Pavel Kirienko <[email protected]>

from __future__ import annotations
import logging
from pathlib import Path
from typing import Callable, Iterable, Optional
from typing import Callable, Iterable

from . import _data_schema_builder, _error, _expression, _parser, _port_id_ranges, _serializable
from ._dsdl import DefinitionVisitor, DsdlFileBuildable
from ._dsdl import DefinitionVisitor, ReadableDSDLFile


class AssertionCheckFailureError(_error.InvalidDefinitionError):
Expand Down Expand Up @@ -42,8 +43,8 @@ class DataTypeBuilder(_parser.StatementStreamProcessor):
# pylint: disable=too-many-arguments
def __init__(
self,
definition: DsdlFileBuildable,
lookup_definitions: Iterable[DsdlFileBuildable],
definition: ReadableDSDLFile,
lookup_definitions: Iterable[ReadableDSDLFile],
definition_visitors: Iterable[DefinitionVisitor],
print_output_handler: Callable[[int, str], None],
allow_unregulated_fixed_port_id: bool,
Expand All @@ -53,10 +54,10 @@ def __init__(
self._definition_visitors = definition_visitors
self._print_output_handler = print_output_handler
self._allow_unregulated_fixed_port_id = allow_unregulated_fixed_port_id
self._element_callback = None # type: Optional[Callable[[str], None]]
self._element_callback = None # type: Callable[[str], None] | None

assert isinstance(self._definition, DsdlFileBuildable)
assert all(map(lambda x: isinstance(x, DsdlFileBuildable), lookup_definitions))
assert isinstance(self._definition, ReadableDSDLFile)
assert all(map(lambda x: isinstance(x, ReadableDSDLFile), lookup_definitions))
assert callable(self._print_output_handler)
assert isinstance(self._allow_unregulated_fixed_port_id, bool)

Expand Down Expand Up @@ -148,7 +149,7 @@ def on_padding_field(self, padding_field_type: _serializable.VoidType) -> None:
)

def on_directive(
self, line_number: int, directive_name: str, associated_expression_value: Optional[_expression.Any]
self, line_number: int, directive_name: str, associated_expression_value: _expression.Any | None
) -> None:
try:
handler = {
Expand Down Expand Up @@ -224,7 +225,7 @@ def resolve_versioned_data_type(self, name: str, version: _serializable.Version)
for visitor in self._definition_visitors:
visitor.on_definition(self._definition, target_definition)

assert isinstance(target_definition, DsdlFileBuildable)
assert isinstance(target_definition, ReadableDSDLFile)
assert target_definition.full_name == full_name
assert target_definition.version == version
# Recursion is cool.
Expand Down Expand Up @@ -252,7 +253,7 @@ def _on_attribute(self) -> None:
"This is to prevent errors if the extent is dependent on the bit length set of the data schema."
)

def _on_print_directive(self, line_number: int, value: Optional[_expression.Any]) -> None:
def _on_print_directive(self, line_number: int, value: _expression.Any | None) -> None:
_logger.info(
"Print directive at %s:%d%s",
self._definition.file_path,
Expand All @@ -261,7 +262,7 @@ def _on_print_directive(self, line_number: int, value: Optional[_expression.Any]
)
self._print_output_handler(line_number, str(value if value is not None else ""))

def _on_assert_directive(self, line_number: int, value: Optional[_expression.Any]) -> None:
def _on_assert_directive(self, line_number: int, value: _expression.Any | None) -> None:
if isinstance(value, _expression.Boolean):
if not value.native_value:
raise AssertionCheckFailureError(
Expand All @@ -273,7 +274,7 @@ def _on_assert_directive(self, line_number: int, value: Optional[_expression.Any
else:
raise InvalidDirectiveError("The assertion check expression must yield a boolean, not %s" % value.TYPE_NAME)

def _on_extent_directive(self, line_number: int, value: Optional[_expression.Any]) -> None:
def _on_extent_directive(self, line_number: int, value: _expression.Any | None) -> None:
if self._structs[-1].serialization_mode is not None:
raise InvalidDirectiveError(
"Misplaced extent directive. The serialization mode is already set to %s"
Expand All @@ -289,7 +290,7 @@ def _on_extent_directive(self, line_number: int, value: Optional[_expression.Any
else:
raise InvalidDirectiveError("The extent directive expects a rational, not %s" % value.TYPE_NAME)

def _on_sealed_directive(self, _ln: int, value: Optional[_expression.Any]) -> None:
def _on_sealed_directive(self, _ln: int, value: _expression.Any | None) -> None:
if self._structs[-1].serialization_mode is not None:
raise InvalidDirectiveError(
"Misplaced sealing directive. The serialization mode is already set to %s"
Expand All @@ -299,7 +300,7 @@ def _on_sealed_directive(self, _ln: int, value: Optional[_expression.Any]) -> No
raise InvalidDirectiveError("The sealed directive does not expect an expression")
self._structs[-1].set_serialization_mode(_data_schema_builder.SealedSerializationMode())

def _on_union_directive(self, _ln: int, value: Optional[_expression.Any]) -> None:
def _on_union_directive(self, _ln: int, value: _expression.Any | None) -> None:
if value is not None:
raise InvalidDirectiveError("The union directive does not expect an expression")
if self._structs[-1].union:
Expand All @@ -308,7 +309,7 @@ def _on_union_directive(self, _ln: int, value: Optional[_expression.Any]) -> Non
raise InvalidDirectiveError("The union directive must be placed before the first " "attribute definition")
self._structs[-1].make_union()

def _on_deprecated_directive(self, _ln: int, value: Optional[_expression.Any]) -> None:
def _on_deprecated_directive(self, _ln: int, value: _expression.Any | None) -> None:
if value is not None:
raise InvalidDirectiveError("The deprecated directive does not expect an expression")
if self._is_deprecated:
Expand All @@ -327,7 +328,7 @@ def _make_composite( # pylint: disable=too-many-arguments
name: str,
version: _serializable.Version,
deprecated: bool,
fixed_port_id: Optional[int],
fixed_port_id: int | None,
source_file_path: Path,
has_parent_service: bool,
) -> _serializable.CompositeType:
Expand Down
23 changes: 11 additions & 12 deletions pydsdl/_dsdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@
# Copyright Amazon.com Inc. or its affiliates.
# SPDX-License-Identifier: MIT

from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, Tuple, TypeVar, Union
from typing import Any, Callable, Iterable, TypeVar, List, Tuple

from ._serializable import CompositeType, Version

PrintOutputHandler = Callable[[Path, int, str], None]
"""Invoked when the frontend encounters a print directive or needs to output a generic diagnostic."""


class DsdlFile(ABC):
class DSDLFile(ABC):
"""
Interface for DSDL files. This interface is used by the parser to abstract DSDL type details inferred from the
filesystem. Where properties are duplicated between the composite type and this file the composite type is to be
Expand All @@ -22,7 +23,7 @@ class DsdlFile(ABC):

@property
@abstractmethod
def composite_type(self) -> Optional[CompositeType]:
def composite_type(self) -> CompositeType | None:
"""The composite type that was read from the DSDL file or None if the type has not been parsed yet."""
raise NotImplementedError()

Expand Down Expand Up @@ -71,7 +72,7 @@ def version(self) -> Version:

@property
@abstractmethod
def fixed_port_id(self) -> Optional[int]:
def fixed_port_id(self) -> int | None:
"""Either the fixed port ID as integer, or None if not defined for this type."""
raise NotImplementedError()

Expand All @@ -98,15 +99,15 @@ def root_namespace_path(self) -> Path:
raise NotImplementedError()


class DsdlFileBuildable(DsdlFile):
class ReadableDSDLFile(DSDLFile):
"""
A DSDL file that can construct a composite type from its contents.
"""

@abstractmethod
def read(
self,
lookup_definitions: Iterable["DsdlFileBuildable"],
lookup_definitions: Iterable["ReadableDSDLFile"],
definition_visitors: Iterable["DefinitionVisitor"],
print_output_handler: Callable[[int, str], None],
allow_unregulated_fixed_port_id: bool,
Expand Down Expand Up @@ -135,7 +136,7 @@ class DefinitionVisitor(ABC):
"""

@abstractmethod
def on_definition(self, target_dsdl_file: DsdlFile, dependency_dsdl_file: DsdlFileBuildable) -> None:
def on_definition(self, target_dsdl_file: DSDLFile, dependency_dsdl_file: ReadableDSDLFile) -> None:
"""
Called by the parser after if finds a dependent type but before it parses a file in a lookup namespace.
:param target_dsdl_file: The target DSDL file that has dependencies the parser is searching for.
Expand All @@ -144,12 +145,12 @@ def on_definition(self, target_dsdl_file: DsdlFile, dependency_dsdl_file: DsdlFi
raise NotImplementedError()


SortedFileT = TypeVar("SortedFileT", DsdlFile, DsdlFileBuildable, CompositeType)
SortedFileT = TypeVar("SortedFileT", DSDLFile, ReadableDSDLFile, CompositeType)
SortedFileList = List[SortedFileT]
"""A list of DSDL files sorted by name, newest version first."""


def get_definition_ordering_rank(d: Union[DsdlFile, CompositeType]) -> Tuple[str, int, int]:
def get_definition_ordering_rank(d: DSDLFile | CompositeType) -> Tuple[str, int, int]:
return d.full_name, -d.version.major, -d.version.minor


Expand All @@ -160,9 +161,7 @@ def file_sort(file_list: Iterable[SortedFileT]) -> SortedFileList[SortedFileT]:
return list(sorted(file_list, key=get_definition_ordering_rank))


def normalize_paths_argument_to_list(
namespaces_or_namespace: Union[None, Path, str, Iterable[Union[Path, str]]],
) -> List[Path]:
def normalize_paths_argument_to_list(namespaces_or_namespace: None | Path | str | Iterable[Path | str]) -> List[Path]:
"""
Normalizes the input argument to a list of paths.
"""
Expand Down
Loading

0 comments on commit c32dae1

Please sign in to comment.