Browse Source

style: edtlib: Use a better type Annotations

Use built-in types for annotations instead
of types from the typing module.

Signed-off-by: James Roy <rruuaanng@outlook.com>
pull/83673/head
James Roy 6 months ago committed by Benjamin Cabé
parent
commit
c99a61ada4
  1. 2
      .ruff-excludes.toml
  2. 42
      scripts/dts/python-devicetree/src/devicetree/dtlib.py
  3. 176
      scripts/dts/python-devicetree/src/devicetree/edtlib.py

2
.ruff-excludes.toml

@ -439,7 +439,6 @@
"E701", # https://docs.astral.sh/ruff/rules/multiple-statements-on-one-line-colon "E701", # https://docs.astral.sh/ruff/rules/multiple-statements-on-one-line-colon
"I001", # https://docs.astral.sh/ruff/rules/unsorted-imports "I001", # https://docs.astral.sh/ruff/rules/unsorted-imports
"SIM201", # https://docs.astral.sh/ruff/rules/negate-equal-op "SIM201", # https://docs.astral.sh/ruff/rules/negate-equal-op
"UP006", # https://docs.astral.sh/ruff/rules/non-pep585-annotation
"UP007", # https://docs.astral.sh/ruff/rules/non-pep604-annotation "UP007", # https://docs.astral.sh/ruff/rules/non-pep604-annotation
"UP032", # https://docs.astral.sh/ruff/rules/f-string "UP032", # https://docs.astral.sh/ruff/rules/f-string
"UP035", # https://docs.astral.sh/ruff/rules/deprecated-import "UP035", # https://docs.astral.sh/ruff/rules/deprecated-import
@ -452,7 +451,6 @@
"I001", # https://docs.astral.sh/ruff/rules/unsorted-imports "I001", # https://docs.astral.sh/ruff/rules/unsorted-imports
"SIM102", # https://docs.astral.sh/ruff/rules/collapsible-if "SIM102", # https://docs.astral.sh/ruff/rules/collapsible-if
"SIM118", # https://docs.astral.sh/ruff/rules/in-dict-keys "SIM118", # https://docs.astral.sh/ruff/rules/in-dict-keys
"UP006", # https://docs.astral.sh/ruff/rules/non-pep585-annotation
"UP007", # https://docs.astral.sh/ruff/rules/non-pep604-annotation "UP007", # https://docs.astral.sh/ruff/rules/non-pep604-annotation
"UP015", # https://docs.astral.sh/ruff/rules/redundant-open-modes "UP015", # https://docs.astral.sh/ruff/rules/redundant-open-modes
"UP032", # https://docs.astral.sh/ruff/rules/f-string "UP032", # https://docs.astral.sh/ruff/rules/f-string

42
scripts/dts/python-devicetree/src/devicetree/dtlib.py

@ -20,9 +20,9 @@ import re
import string import string
import sys import sys
import textwrap import textwrap
from typing import (Any, Dict, Iterable, List, from typing import (Any, Iterable,
NamedTuple, NoReturn, Optional, NamedTuple, NoReturn, Optional,
Set, Tuple, TYPE_CHECKING, Union) TYPE_CHECKING, Union)
# NOTE: tests/test_dtlib.py is the test suite for this library. # NOTE: tests/test_dtlib.py is the test suite for this library.
@ -92,9 +92,9 @@ class Node:
# Remember to update DT.__deepcopy__() if you change this. # Remember to update DT.__deepcopy__() if you change this.
self._name = name self._name = name
self.props: Dict[str, 'Property'] = {} self.props: dict[str, Property] = {}
self.nodes: Dict[str, 'Node'] = {} self.nodes: dict[str, Node] = {}
self.labels: List[str] = [] self.labels: list[str] = []
self.parent = parent self.parent = parent
self.dt = dt self.dt = dt
@ -309,13 +309,13 @@ class Property:
self.name = name self.name = name
self.value = b"" self.value = b""
self.labels: List[str] = [] self.labels: list[str] = []
# We have to wait to set this until later, when we've got # We have to wait to set this until later, when we've got
# the entire tree. # the entire tree.
self.offset_labels: Dict[str, int] = {} self.offset_labels: dict[str, int] = {}
self.node: Node = node self.node: Node = node
self._label_offset_lst: List[Tuple[str, int]] = [] self._label_offset_lst: list[tuple[str, int]] = []
# A list of [offset, label, type] lists (sorted by offset), # A list of [offset, label, type] lists (sorted by offset),
# giving the locations of references within the value. 'type' # giving the locations of references within the value. 'type'
@ -323,7 +323,7 @@ class Property:
# _MarkerType.PHANDLE, for a phandle reference, or # _MarkerType.PHANDLE, for a phandle reference, or
# _MarkerType.LABEL, for a label on/within data. Node paths # _MarkerType.LABEL, for a label on/within data. Node paths
# and phandles need to be patched in after parsing. # and phandles need to be patched in after parsing.
self._markers: List[List] = [] self._markers: list[list] = []
@property @property
def type(self) -> Type: def type(self) -> Type:
@ -388,7 +388,7 @@ class Property:
return int.from_bytes(self.value, "big", signed=signed) return int.from_bytes(self.value, "big", signed=signed)
def to_nums(self, signed=False) -> List[int]: def to_nums(self, signed=False) -> list[int]:
""" """
Returns the value of the property as a list of numbers. Returns the value of the property as a list of numbers.
@ -455,7 +455,7 @@ class Property:
return ret # The separate 'return' appeases the type checker. return ret # The separate 'return' appeases the type checker.
def to_strings(self) -> List[str]: def to_strings(self) -> list[str]:
""" """
Returns the value of the property as a list of strings. Returns the value of the property as a list of strings.
@ -498,7 +498,7 @@ class Property:
return self.node.dt.phandle2node[int.from_bytes(self.value, "big")] return self.node.dt.phandle2node[int.from_bytes(self.value, "big")]
def to_nodes(self) -> List[Node]: def to_nodes(self) -> list[Node]:
""" """
Returns a list with the Nodes the phandles in the property point to. Returns a list with the Nodes the phandles in the property point to.
@ -761,12 +761,12 @@ class DT:
# Remember to update __deepcopy__() if you change this. # Remember to update __deepcopy__() if you change this.
self._root: Optional[Node] = None self._root: Optional[Node] = None
self.alias2node: Dict[str, Node] = {} self.alias2node: dict[str, Node] = {}
self.label2node: Dict[str, Node] = {} self.label2node: dict[str, Node] = {}
self.label2prop: Dict[str, Property] = {} self.label2prop: dict[str, Property] = {}
self.label2prop_offset: Dict[str, Tuple[Property, int]] = {} self.label2prop_offset: dict[str, tuple[Property, int]] = {}
self.phandle2node: Dict[int, Node] = {} self.phandle2node: dict[int, Node] = {}
self.memreserves: List[Tuple[Set[str], int, int]] = [] self.memreserves: list[tuple[set[str], int, int]] = []
self.filename = filename self.filename = filename
self._force = force self._force = force
@ -774,7 +774,7 @@ class DT:
if filename is not None: if filename is not None:
self._parse_file(filename, include_path) self._parse_file(filename, include_path)
else: else:
self._include_path: List[str] = [] self._include_path: list[str] = []
@property @property
def root(self) -> Node: def root(self) -> Node:
@ -1027,7 +1027,7 @@ class DT:
self._file_contents = f.read() self._file_contents = f.read()
self._tok_i = self._tok_end_i = 0 self._tok_i = self._tok_end_i = 0
self._filestack: List[_FileStackElt] = [] self._filestack: list[_FileStackElt] = []
self._lexer_state: int = _DEFAULT self._lexer_state: int = _DEFAULT
self._saved_token: Optional[_Token] = None self._saved_token: Optional[_Token] = None
@ -2027,7 +2027,7 @@ def to_num(data: bytes, length: Optional[int] = None,
return int.from_bytes(data, "big", signed=signed) return int.from_bytes(data, "big", signed=signed)
def to_nums(data: bytes, length: int = 4, signed: bool = False) -> List[int]: def to_nums(data: bytes, length: int = 4, signed: bool = False) -> list[int]:
""" """
Like Property.to_nums(), but takes an arbitrary 'bytes' array. The values Like Property.to_nums(), but takes an arbitrary 'bytes' array. The values
are assumed to be in big-endian format, which is standard in devicetree. are assumed to be in big-endian format, which is standard in devicetree.

176
scripts/dts/python-devicetree/src/devicetree/edtlib.py

@ -70,8 +70,8 @@ bindings_from_paths() helper function.
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass from dataclasses import dataclass
from typing import (Any, Callable, Dict, Iterable, List, NoReturn, from typing import (Any, Callable, Iterable, NoReturn,
Optional, Set, TYPE_CHECKING, Tuple, Union) Optional, TYPE_CHECKING, Union)
import logging import logging
import os import os
import re import re
@ -161,7 +161,7 @@ class Binding:
are multiple levels of 'child-binding' descriptions in the binding. are multiple levels of 'child-binding' descriptions in the binding.
""" """
def __init__(self, path: Optional[str], fname2path: Dict[str, str], def __init__(self, path: Optional[str], fname2path: dict[str, str],
raw: Any = None, require_compatible: bool = True, raw: Any = None, require_compatible: bool = True,
require_description: bool = True): require_description: bool = True):
""" """
@ -193,7 +193,7 @@ class Binding:
if it is present in the binding. if it is present in the binding.
""" """
self.path: Optional[str] = path self.path: Optional[str] = path
self._fname2path: Dict[str, str] = fname2path self._fname2path: dict[str, str] = fname2path
if raw is None: if raw is None:
if path is None: if path is None:
@ -225,10 +225,10 @@ class Binding:
self._check(require_compatible, require_description) self._check(require_compatible, require_description)
# Initialize look up tables. # Initialize look up tables.
self.prop2specs: Dict[str, 'PropertySpec'] = {} self.prop2specs: dict[str, 'PropertySpec'] = {}
for prop_name in self.raw.get("properties", {}).keys(): for prop_name in self.raw.get("properties", {}).keys():
self.prop2specs[prop_name] = PropertySpec(prop_name, self) self.prop2specs[prop_name] = PropertySpec(prop_name, self)
self.specifier2cells: Dict[str, List[str]] = {} self.specifier2cells: dict[str, list[str]] = {}
for key, val in self.raw.items(): for key, val in self.raw.items():
if key.endswith("-cells"): if key.endswith("-cells"):
self.specifier2cells[key[:-len("-cells")]] = val self.specifier2cells[key[:-len("-cells")]] = val
@ -252,12 +252,12 @@ class Binding:
return self.raw.get('compatible') return self.raw.get('compatible')
@property @property
def bus(self) -> Union[None, str, List[str]]: def bus(self) -> Union[None, str, list[str]]:
"See the class docstring" "See the class docstring"
return self.raw.get('bus') return self.raw.get('bus')
@property @property
def buses(self) -> List[str]: def buses(self) -> list[str]:
"See the class docstring" "See the class docstring"
if self.raw.get('bus') is not None: if self.raw.get('bus') is not None:
return self._buses return self._buses
@ -287,7 +287,7 @@ class Binding:
# file has a 'required:' for a particular property, OR the values # file has a 'required:' for a particular property, OR the values
# together, so that 'required: true' wins. # together, so that 'required: true' wins.
merged: Dict[str, Any] = {} merged: dict[str, Any] = {}
if isinstance(include, str): if isinstance(include, str):
# Simple scalar string case # Simple scalar string case
@ -530,7 +530,7 @@ class PropertySpec:
def __init__(self, name: str, binding: Binding): def __init__(self, name: str, binding: Binding):
self.binding: Binding = binding self.binding: Binding = binding
self.name: str = name self.name: str = name
self._raw: Dict[str, Any] = self.binding.raw["properties"][name] self._raw: dict[str, Any] = self.binding.raw["properties"][name]
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<PropertySpec {self.name} type '{self.type}'>" return f"<PropertySpec {self.name} type '{self.type}'>"
@ -586,12 +586,12 @@ class PropertySpec:
return self._enum_upper_tokenizable return self._enum_upper_tokenizable
@property @property
def const(self) -> Union[None, int, List[int], str, List[str]]: def const(self) -> Union[None, int, list[int], str, list[str]]:
"See the class docstring" "See the class docstring"
return self._raw.get("const") return self._raw.get("const")
@property @property
def default(self) -> Union[None, int, List[int], str, List[str]]: def default(self) -> Union[None, int, list[int], str, list[str]]:
"See the class docstring" "See the class docstring"
return self._raw.get("default") return self._raw.get("default")
@ -611,9 +611,9 @@ class PropertySpec:
return self._raw.get("specifier-space") return self._raw.get("specifier-space")
PropertyValType = Union[int, str, PropertyValType = Union[int, str,
List[int], List[str], list[int], list[str],
'Node', List['Node'], 'Node', list['Node'],
List[Optional['ControllerAndData']], list[Optional['ControllerAndData']],
bytes, None] bytes, None]
@ -697,7 +697,7 @@ class Property:
return self.spec.type return self.spec.type
@property @property
def val_as_tokens(self) -> List[str]: def val_as_tokens(self) -> list[str]:
"See the class docstring" "See the class docstring"
ret = [] ret = []
for subval in self.val if isinstance(self.val, list) else [self.val]: for subval in self.val if isinstance(self.val, list) else [self.val]:
@ -706,7 +706,7 @@ class Property:
return ret return ret
@property @property
def enum_indices(self) -> Optional[List[int]]: def enum_indices(self) -> Optional[list[int]]:
"See the class docstring" "See the class docstring"
enum = self.spec.enum enum = self.spec.enum
val = self.val if isinstance(self.val, list) else [self.val] val = self.val if isinstance(self.val, list) else [self.val]
@ -848,7 +848,7 @@ class PinCtrl:
node: 'Node' node: 'Node'
name: Optional[str] name: Optional[str]
conf_nodes: List['Node'] conf_nodes: list['Node']
@property @property
def name_as_token(self): def name_as_token(self):
@ -1020,12 +1020,12 @@ class Node:
# Public, some of which are initialized properly later: # Public, some of which are initialized properly later:
self.edt: 'EDT' = edt self.edt: 'EDT' = edt
self.dep_ordinal: int = -1 self.dep_ordinal: int = -1
self.compats: List[str] = compats self.compats: list[str] = compats
self.ranges: List[Range] = [] self.ranges: list[Range] = []
self.regs: List[Register] = [] self.regs: list[Register] = []
self.props: Dict[str, Property] = {} self.props: dict[str, Property] = {}
self.interrupts: List[ControllerAndData] = [] self.interrupts: list[ControllerAndData] = []
self.pinctrls: List[PinCtrl] = [] self.pinctrls: list[PinCtrl] = []
self.bus_node = self._bus_node(support_fixed_partitions_on_any_bus) self.bus_node = self._bus_node(support_fixed_partitions_on_any_bus)
self._init_binding() self._init_binding()
@ -1074,7 +1074,7 @@ class Node:
return None return None
@property @property
def labels(self) -> List[str]: def labels(self) -> list[str]:
"See the class docstring" "See the class docstring"
return self._node.labels return self._node.labels
@ -1084,7 +1084,7 @@ class Node:
return self.edt._node2enode.get(self._node.parent) # type: ignore return self.edt._node2enode.get(self._node.parent) # type: ignore
@property @property
def children(self) -> Dict[str, 'Node']: def children(self) -> dict[str, 'Node']:
"See the class docstring" "See the class docstring"
# Could be initialized statically too to preserve identity, but not # Could be initialized statically too to preserve identity, but not
# sure if needed. Parent nodes being initialized before their children # sure if needed. Parent nodes being initialized before their children
@ -1101,7 +1101,7 @@ class Node:
# method is callable to handle parents needing to be # method is callable to handle parents needing to be
# initialized before their chidlren. By the time we # initialized before their chidlren. By the time we
# return from __init__, 'self.children' is callable. # return from __init__, 'self.children' is callable.
self._child2index: Dict[str, int] = {} self._child2index: dict[str, int] = {}
for index, child_path in enumerate(child.path for child in for index, child_path in enumerate(child.path for child in
self.children.values()): self.children.values()):
self._child2index[child_path] = index self._child2index[child_path] = index
@ -1109,12 +1109,12 @@ class Node:
return self._child2index[node.path] return self._child2index[node.path]
@property @property
def required_by(self) -> List['Node']: def required_by(self) -> list['Node']:
"See the class docstring" "See the class docstring"
return self.edt._graph.required_by(self) return self.edt._graph.required_by(self)
@property @property
def depends_on(self) -> List['Node']: def depends_on(self) -> list['Node']:
"See the class docstring" "See the class docstring"
return self.edt._graph.depends_on(self) return self.edt._graph.depends_on(self)
@ -1153,20 +1153,20 @@ class Node:
return None return None
@property @property
def aliases(self) -> List[str]: def aliases(self) -> list[str]:
"See the class docstring" "See the class docstring"
return [alias for alias, node in self._node.dt.alias2node.items() return [alias for alias, node in self._node.dt.alias2node.items()
if node is self._node] if node is self._node]
@property @property
def buses(self) -> List[str]: def buses(self) -> list[str]:
"See the class docstring" "See the class docstring"
if self._binding: if self._binding:
return self._binding.buses return self._binding.buses
return [] return []
@property @property
def on_buses(self) -> List[str]: def on_buses(self) -> list[str]:
"See the class docstring" "See the class docstring"
bus_node = self.bus_node bus_node = self.bus_node
return bus_node.buses if bus_node else [] return bus_node.buses if bus_node else []
@ -1225,7 +1225,7 @@ class Node:
return ret return ret
@property @property
def gpio_hogs(self) -> List[ControllerAndData]: def gpio_hogs(self) -> list[ControllerAndData]:
"See the class docstring" "See the class docstring"
if "gpio-hog" not in self.props: if "gpio-hog" not in self.props:
@ -1327,12 +1327,12 @@ class Node:
_err(f"compatible in node with inferred binding: {self.path}") _err(f"compatible in node with inferred binding: {self.path}")
# Synthesize a 'raw' binding as if it had been parsed from YAML. # Synthesize a 'raw' binding as if it had been parsed from YAML.
raw: Dict[str, Any] = { raw: dict[str, Any] = {
'description': 'Inferred binding from properties, via edtlib.', 'description': 'Inferred binding from properties, via edtlib.',
'properties': {}, 'properties': {},
} }
for name, prop in self._node.props.items(): for name, prop in self._node.props.items():
pp: Dict[str, str] = {} pp: dict[str, str] = {}
if prop.type == Type.EMPTY: if prop.type == Type.EMPTY:
pp["type"] = "boolean" pp["type"] = "boolean"
elif prop.type == Type.BYTES: elif prop.type == Type.BYTES:
@ -1750,7 +1750,7 @@ class Node:
self, self,
prop: dtlib_Property, prop: dtlib_Property,
specifier_space: Optional[str] specifier_space: Optional[str]
) -> List[Optional[ControllerAndData]]: ) -> list[Optional[ControllerAndData]]:
# Parses a property like # Parses a property like
# #
# <prop.name> = <phandle cell phandle cell ...>; # <prop.name> = <phandle cell phandle cell ...>;
@ -1800,7 +1800,7 @@ class Node:
# if there is no specifier space in _check_prop_by_type(). # if there is no specifier space in _check_prop_by_type().
specifier_space = prop.name[:-1] specifier_space = prop.name[:-1]
res: List[Optional[ControllerAndData]] = [] res: list[Optional[ControllerAndData]] = []
for item in _phandle_val_list(prop, specifier_space): for item in _phandle_val_list(prop, specifier_space):
if item is None: if item is None:
@ -1829,7 +1829,7 @@ class Node:
controller: 'Node', controller: 'Node',
data: bytes, data: bytes,
basename: str basename: str
) -> Dict[str, int]: ) -> dict[str, int]:
# Returns a dictionary that maps <basename>-cells names given in the # Returns a dictionary that maps <basename>-cells names given in the
# binding for 'controller' to cell values. 'data' is the raw data, as a # binding for 'controller' to cell values. 'data' is the raw data, as a
# byte array. # byte array.
@ -1839,7 +1839,7 @@ class Node:
f"for {self._node!r} lacks binding") f"for {self._node!r} lacks binding")
if basename in controller._binding.specifier2cells: if basename in controller._binding.specifier2cells:
cell_names: List[str] = controller._binding.specifier2cells[basename] cell_names: list[str] = controller._binding.specifier2cells[basename]
else: else:
# Treat no *-cells in the binding the same as an empty *-cells, so # Treat no *-cells in the binding the same as an empty *-cells, so
# that bindings don't have to have e.g. an empty 'clock-cells:' for # that bindings don't have to have e.g. an empty 'clock-cells:' for
@ -1923,12 +1923,12 @@ class EDT:
def __init__(self, def __init__(self,
dts: Optional[str], dts: Optional[str],
bindings_dirs: List[str], bindings_dirs: list[str],
warn_reg_unit_address_mismatch: bool = True, warn_reg_unit_address_mismatch: bool = True,
default_prop_types: bool = True, default_prop_types: bool = True,
support_fixed_partitions_on_any_bus: bool = True, support_fixed_partitions_on_any_bus: bool = True,
infer_binding_for_paths: Optional[Iterable[str]] = None, infer_binding_for_paths: Optional[Iterable[str]] = None,
vendor_prefixes: Optional[Dict[str, str]] = None, vendor_prefixes: Optional[dict[str, str]] = None,
werror: bool = False): werror: bool = False):
"""EDT constructor. """EDT constructor.
@ -1977,34 +1977,34 @@ class EDT:
# and update the tests for that method. # and update the tests for that method.
# Public attributes (the rest are properties) # Public attributes (the rest are properties)
self.nodes: List[Node] = [] self.nodes: list[Node] = []
self.compat2nodes: Dict[str, List[Node]] = defaultdict(list) self.compat2nodes: dict[str, list[Node]] = defaultdict(list)
self.compat2okay: Dict[str, List[Node]] = defaultdict(list) self.compat2okay: dict[str, list[Node]] = defaultdict(list)
self.compat2notokay: Dict[str, List[Node]] = defaultdict(list) self.compat2notokay: dict[str, list[Node]] = defaultdict(list)
self.compat2vendor: Dict[str, str] = defaultdict(str) self.compat2vendor: dict[str, str] = defaultdict(str)
self.compat2model: Dict[str, str] = defaultdict(str) self.compat2model: dict[str, str] = defaultdict(str)
self.label2node: Dict[str, Node] = {} self.label2node: dict[str, Node] = {}
self.dep_ord2node: Dict[int, Node] = {} self.dep_ord2node: dict[int, Node] = {}
self.dts_path: str = dts # type: ignore self.dts_path: str = dts # type: ignore
self.bindings_dirs: List[str] = list(bindings_dirs) self.bindings_dirs: list[str] = list(bindings_dirs)
# Saved kwarg values for internal use # Saved kwarg values for internal use
self._warn_reg_unit_address_mismatch: bool = warn_reg_unit_address_mismatch self._warn_reg_unit_address_mismatch: bool = warn_reg_unit_address_mismatch
self._default_prop_types: bool = default_prop_types self._default_prop_types: bool = default_prop_types
self._fixed_partitions_no_bus: bool = support_fixed_partitions_on_any_bus self._fixed_partitions_no_bus: bool = support_fixed_partitions_on_any_bus
self._infer_binding_for_paths: Set[str] = set(infer_binding_for_paths or []) self._infer_binding_for_paths: set[str] = set(infer_binding_for_paths or [])
self._vendor_prefixes: Dict[str, str] = vendor_prefixes or {} self._vendor_prefixes: dict[str, str] = vendor_prefixes or {}
self._werror: bool = bool(werror) self._werror: bool = bool(werror)
# Other internal state # Other internal state
self._compat2binding: Dict[Tuple[str, Optional[str]], Binding] = {} self._compat2binding: dict[tuple[str, Optional[str]], Binding] = {}
self._graph: Graph = Graph() self._graph: Graph = Graph()
self._binding_paths: List[str] = _binding_paths(self.bindings_dirs) self._binding_paths: list[str] = _binding_paths(self.bindings_dirs)
self._binding_fname2path: Dict[str, str] = { self._binding_fname2path: dict[str, str] = {
os.path.basename(path): path os.path.basename(path): path
for path in self._binding_paths for path in self._binding_paths
} }
self._node2enode: Dict[dtlib_Node, Node] = {} self._node2enode: dict[dtlib_Node, Node] = {}
if dts is not None: if dts is not None:
try: try:
@ -2036,8 +2036,8 @@ class EDT:
_err(e) _err(e)
@property @property
def chosen_nodes(self) -> Dict[str, Node]: def chosen_nodes(self) -> dict[str, Node]:
ret: Dict[str, Node] = {} ret: dict[str, Node] = {}
try: try:
chosen = self._dt.get_node("/chosen") chosen = self._dt.get_node("/chosen")
@ -2092,7 +2092,7 @@ class EDT:
return ret return ret
@property @property
def scc_order(self) -> List[List[Node]]: def scc_order(self) -> list[list[Node]]:
try: try:
return self._graph.scc_order() return self._graph.scc_order()
except Exception as e: except Exception as e:
@ -2227,7 +2227,7 @@ class EDT:
def _binding(self, def _binding(self,
raw: Optional[dict], raw: Optional[dict],
binding_path: str, binding_path: str,
dt_compats: Set[str]) -> Optional[Binding]: dt_compats: set[str]) -> Optional[Binding]:
# Convert a 'raw' binding from YAML to a Binding object and return it. # Convert a 'raw' binding from YAML to a Binding object and return it.
# #
# Error out if the raw data looks like an invalid binding. # Error out if the raw data looks like an invalid binding.
@ -2387,8 +2387,8 @@ class EDT:
assert isinstance(compat, str) assert isinstance(compat, str)
def bindings_from_paths(yaml_paths: List[str], def bindings_from_paths(yaml_paths: list[str],
ignore_errors: bool = False) -> List[Binding]: ignore_errors: bool = False) -> list[Binding]:
""" """
Get a list of Binding objects from the yaml files 'yaml_paths'. Get a list of Binding objects from the yaml files 'yaml_paths'.
@ -2417,11 +2417,11 @@ class EDTError(Exception):
# #
def load_vendor_prefixes_txt(vendor_prefixes: str) -> Dict[str, str]: def load_vendor_prefixes_txt(vendor_prefixes: str) -> dict[str, str]:
"""Load a vendor-prefixes.txt file and return a dict """Load a vendor-prefixes.txt file and return a dict
representation mapping a vendor prefix to the vendor name. representation mapping a vendor prefix to the vendor name.
""" """
vnd2vendor: Dict[str, str] = {} vnd2vendor: dict[str, str] = {}
with open(vendor_prefixes, 'r', encoding='utf-8') as f: with open(vendor_prefixes, 'r', encoding='utf-8') as f:
for line in f: for line in f:
line = line.strip() line = line.strip()
@ -2443,7 +2443,7 @@ def load_vendor_prefixes_txt(vendor_prefixes: str) -> Dict[str, str]:
# #
def _dt_compats(dt: DT) -> Set[str]: def _dt_compats(dt: DT) -> set[str]:
# Returns a set() with all 'compatible' strings in the devicetree # Returns a set() with all 'compatible' strings in the devicetree
# represented by dt (a dtlib.DT instance) # represented by dt (a dtlib.DT instance)
@ -2453,7 +2453,7 @@ def _dt_compats(dt: DT) -> Set[str]:
for compat in node.props["compatible"].to_strings()} for compat in node.props["compatible"].to_strings()}
def _binding_paths(bindings_dirs: List[str]) -> List[str]: def _binding_paths(bindings_dirs: list[str]) -> list[str]:
# Returns a list with the paths to all bindings (.yaml files) in # Returns a list with the paths to all bindings (.yaml files) in
# 'bindings_dirs' # 'bindings_dirs'
@ -2475,8 +2475,8 @@ def _binding_inc_error(msg):
def _check_include_dict(name: Optional[str], def _check_include_dict(name: Optional[str],
allowlist: Optional[List[str]], allowlist: Optional[list[str]],
blocklist: Optional[List[str]], blocklist: Optional[list[str]],
child_filter: Optional[dict], child_filter: Optional[dict],
binding_path: Optional[str]) -> None: binding_path: Optional[str]) -> None:
# Check that an 'include:' named 'name' with property-allowlist # Check that an 'include:' named 'name' with property-allowlist
@ -2494,9 +2494,9 @@ def _check_include_dict(name: Optional[str],
while child_filter is not None: while child_filter is not None:
child_copy = deepcopy(child_filter) child_copy = deepcopy(child_filter)
child_allowlist: Optional[List[str]] = ( child_allowlist: Optional[list[str]] = (
child_copy.pop('property-allowlist', None)) child_copy.pop('property-allowlist', None))
child_blocklist: Optional[List[str]] = ( child_blocklist: Optional[list[str]] = (
child_copy.pop('property-blocklist', None)) child_copy.pop('property-blocklist', None))
next_child_filter: Optional[dict] = ( next_child_filter: Optional[dict] = (
child_copy.pop('child-binding', None)) child_copy.pop('child-binding', None))
@ -2516,8 +2516,8 @@ def _check_include_dict(name: Optional[str],
def _filter_properties(raw: dict, def _filter_properties(raw: dict,
allowlist: Optional[List[str]], allowlist: Optional[list[str]],
blocklist: Optional[List[str]], blocklist: Optional[list[str]],
child_filter: Optional[dict], child_filter: Optional[dict],
binding_path: Optional[str]) -> None: binding_path: Optional[str]) -> None:
# Destructively modifies 'raw["properties"]' and # Destructively modifies 'raw["properties"]' and
@ -2538,8 +2538,8 @@ def _filter_properties(raw: dict,
def _filter_properties_helper(props: Optional[dict], def _filter_properties_helper(props: Optional[dict],
allowlist: Optional[List[str]], allowlist: Optional[list[str]],
blocklist: Optional[List[str]], blocklist: Optional[list[str]],
binding_path: Optional[str]) -> None: binding_path: Optional[str]) -> None:
if props is None or (allowlist is None and blocklist is None): if props is None or (allowlist is None and blocklist is None):
return return
@ -2560,7 +2560,7 @@ def _filter_properties_helper(props: Optional[dict],
del props[prop] del props[prop]
def _check_prop_filter(name: str, value: Optional[List[str]], def _check_prop_filter(name: str, value: Optional[list[str]],
binding_path: Optional[str]) -> None: binding_path: Optional[str]) -> None:
# Ensure an include: ... property-allowlist or property-blocklist # Ensure an include: ... property-allowlist or property-blocklist
# is a list. # is a list.
@ -2832,7 +2832,7 @@ def _interrupt_parent(start_node: dtlib_Node) -> dtlib_Node:
f"nor any of its parents has an 'interrupt-parent' property") f"nor any of its parents has an 'interrupt-parent' property")
def _interrupts(node: dtlib_Node) -> List[Tuple[dtlib_Node, bytes]]: def _interrupts(node: dtlib_Node) -> list[tuple[dtlib_Node, bytes]]:
# Returns a list of (<controller>, <data>) tuples, with one tuple per # Returns a list of (<controller>, <data>) tuples, with one tuple per
# interrupt generated by 'node'. <controller> is the destination of the # interrupt generated by 'node'. <controller> is the destination of the
# interrupt (possibly after mapping through an 'interrupt-map'), and <data> # interrupt (possibly after mapping through an 'interrupt-map'), and <data>
@ -2842,7 +2842,7 @@ def _interrupts(node: dtlib_Node) -> List[Tuple[dtlib_Node, bytes]]:
if "interrupts-extended" in node.props: if "interrupts-extended" in node.props:
prop = node.props["interrupts-extended"] prop = node.props["interrupts-extended"]
ret: List[Tuple[dtlib_Node, bytes]] = [] ret: list[tuple[dtlib_Node, bytes]] = []
for entry in _phandle_val_list(prop, "interrupt"): for entry in _phandle_val_list(prop, "interrupt"):
if entry is None: if entry is None:
_err(f"node '{node.path}' interrupts-extended property " _err(f"node '{node.path}' interrupts-extended property "
@ -2869,7 +2869,7 @@ def _map_interrupt(
child: dtlib_Node, child: dtlib_Node,
parent: dtlib_Node, parent: dtlib_Node,
child_spec: bytes child_spec: bytes
) -> Tuple[dtlib_Node, bytes]: ) -> tuple[dtlib_Node, bytes]:
# Translates an interrupt headed from 'child' to 'parent' with data # Translates an interrupt headed from 'child' to 'parent' with data
# 'child_spec' through any 'interrupt-map' properties. Returns a # 'child_spec' through any 'interrupt-map' properties. Returns a
# (<controller>, <data>) tuple with the final destination after mapping. # (<controller>, <data>) tuple with the final destination after mapping.
@ -2906,7 +2906,7 @@ def _map_phandle_array_entry(
parent: dtlib_Node, parent: dtlib_Node,
child_spec: bytes, child_spec: bytes,
basename: str basename: str
) -> Tuple[dtlib_Node, bytes]: ) -> tuple[dtlib_Node, bytes]:
# Returns a (<controller>, <data>) tuple with the final destination after # Returns a (<controller>, <data>) tuple with the final destination after
# mapping through any '<basename>-map' (e.g. gpio-map) properties. See # mapping through any '<basename>-map' (e.g. gpio-map) properties. See
# _map_interrupt(). # _map_interrupt().
@ -2930,7 +2930,7 @@ def _map(
child_spec: bytes, child_spec: bytes,
spec_len_fn: Callable[[dtlib_Node], int], spec_len_fn: Callable[[dtlib_Node], int],
require_controller: bool require_controller: bool
) -> Tuple[dtlib_Node, bytes]: ) -> tuple[dtlib_Node, bytes]:
# Common code for mapping through <prefix>-map properties, e.g. # Common code for mapping through <prefix>-map properties, e.g.
# interrupt-map and gpio-map. # interrupt-map and gpio-map.
# #
@ -3105,7 +3105,7 @@ def _not(b: bytes) -> bytes:
def _phandle_val_list( def _phandle_val_list(
prop: dtlib_Property, prop: dtlib_Property,
n_cells_name: str n_cells_name: str
) -> List[Optional[Tuple[dtlib_Node, bytes]]]: ) -> list[Optional[tuple[dtlib_Node, bytes]]]:
# Parses a '<phandle> <value> <phandle> <value> ...' value. The number of # Parses a '<phandle> <value> <phandle> <value> ...' value. The number of
# cells that make up each <value> is derived from the node pointed at by # cells that make up each <value> is derived from the node pointed at by
# the preceding <phandle>. # the preceding <phandle>.
@ -3123,7 +3123,7 @@ def _phandle_val_list(
full_n_cells_name = f"#{n_cells_name}-cells" full_n_cells_name = f"#{n_cells_name}-cells"
res: List[Optional[Tuple[dtlib_Node, bytes]]] = [] res: list[Optional[tuple[dtlib_Node, bytes]]] = []
raw = prop.value raw = prop.value
while raw: while raw:
@ -3187,7 +3187,7 @@ def _interrupt_cells(node: dtlib_Node) -> int:
def _slice(node: dtlib_Node, def _slice(node: dtlib_Node,
prop_name: str, prop_name: str,
size: int, size: int,
size_hint: str) -> List[bytes]: size_hint: str) -> list[bytes]:
return _slice_helper(node, prop_name, size, size_hint, EDTError) return _slice_helper(node, prop_name, size, size_hint, EDTError)
@ -3259,7 +3259,7 @@ _BindingLoader.add_constructor("!include", _binding_include)
# include/devicetree.h. # include/devicetree.h.
# #
_DEFAULT_PROP_TYPES: Dict[str, str] = { _DEFAULT_PROP_TYPES: dict[str, str] = {
"compatible": "string-array", "compatible": "string-array",
"status": "string", "status": "string",
"ranges": "compound", # NUMS or EMPTY "ranges": "compound", # NUMS or EMPTY
@ -3272,12 +3272,12 @@ _DEFAULT_PROP_TYPES: Dict[str, str] = {
"interrupt-controller": "boolean", "interrupt-controller": "boolean",
} }
_STATUS_ENUM: List[str] = "ok okay disabled reserved fail fail-sss".split() _STATUS_ENUM: list[str] = "ok okay disabled reserved fail fail-sss".split()
def _raw_default_property_for( def _raw_default_property_for(
name: str name: str
) -> Dict[str, Union[str, bool, List[str]]]: ) -> dict[str, Union[str, bool, list[str]]]:
ret: Dict[str, Union[str, bool, List[str]]] = { ret: dict[str, Union[str, bool, list[str]]] = {
'type': _DEFAULT_PROP_TYPES[name], 'type': _DEFAULT_PROP_TYPES[name],
'required': False, 'required': False,
} }
@ -3296,7 +3296,7 @@ _DEFAULT_PROP_BINDING: Binding = Binding(
require_compatible=False, require_description=False, require_compatible=False, require_description=False,
) )
_DEFAULT_PROP_SPECS: Dict[str, PropertySpec] = { _DEFAULT_PROP_SPECS: dict[str, PropertySpec] = {
name: PropertySpec(name, _DEFAULT_PROP_BINDING) name: PropertySpec(name, _DEFAULT_PROP_BINDING)
for name in _DEFAULT_PROP_TYPES for name in _DEFAULT_PROP_TYPES
} }

Loading…
Cancel
Save