Skip to content

Commit

Permalink
style: edtlib: Use a better line continuation operator
Browse files Browse the repository at this point in the history
Replace backslashes('\') with PEP-8 recommended
parentheses('( )') as the line continuation operator.

Signed-off-by: James Roy <[email protected]>
  • Loading branch information
rruuaanng authored and kartben committed Jan 4, 2025
1 parent 67597cf commit 802eac7
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 82 deletions.
49 changes: 24 additions & 25 deletions scripts/dts/gen_defines.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,8 @@ def map_arm_gic_irq_type(irq, irq_num):
idx_vals.append((idx_macro, cell_value))
idx_vals.append((idx_macro + "_EXISTS", 1))
if irq.name:
name_macro = \
f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}"
name_macro = (
f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}")
name_vals.append((name_macro, f"DT_{idx_macro}"))
name_vals.append((name_macro + "_EXISTS", 1))

Expand Down Expand Up @@ -619,28 +619,27 @@ def write_vanilla_props(node: edtlib.Node) -> None:
plen = prop_len(prop)
if plen is not None:
# DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM
macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \
' \\\n\t'.join(
f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
for i in range(plen))
macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = (
' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
for i in range(plen)))

# DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM_SEP
macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP(fn, sep)"] = \
macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP(fn, sep)"] = (
' DT_DEBRACKET_INTERNAL sep \\\n\t'.join(
f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
for i in range(plen))
for i in range(plen)))

# DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM_VARGS
macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \
macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = (
' \\\n\t'.join(
f'fn(DT_{node.z_path_id}, {prop_id}, {i}, __VA_ARGS__)'
for i in range(plen))
for i in range(plen)))

# DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM_SEP_VARGS
macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP_VARGS(fn, sep, ...)"] = \
macro2val[f"{macro}_FOREACH_PROP_ELEM_SEP_VARGS(fn, sep, ...)"] = (
' DT_DEBRACKET_INTERNAL sep \\\n\t'.join(
f'fn(DT_{node.z_path_id}, {prop_id}, {i}, __VA_ARGS__)'
for i in range(plen))
for i in range(plen)))

# DT_N_<node-id>_P_<prop-id>_LEN
macro2val[f"{macro}_LEN"] = plen
Expand Down Expand Up @@ -715,9 +714,9 @@ def fmt_dep_list(dep_list):
if dep_list:
# Sort the list by dependency ordinal for predictability.
sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal)
return "\\\n\t" + \
" \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */"
for n in sorted_list)
return ("\\\n\t" + " \\\n\t"
.join(f"{n.dep_ordinal}, /* {n.path} */"
for n in sorted_list))
else:
return "/* nothing */"

Expand Down Expand Up @@ -867,8 +866,8 @@ def controller_and_data_macros(entry: edtlib.ControllerAndData, i: int, macro: s
# DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL>
for cell, val in data.items():
cell_ident = str2ident(cell)
ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \
f"DT_{macro}_IDX_{i}_VAL_{cell_ident}"
ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = (
f"DT_{macro}_IDX_{i}_VAL_{cell_ident}")
ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1

return ret
Expand Down Expand Up @@ -919,24 +918,24 @@ def write_global_macros(edt: edtlib.EDT):

# Helpers for non-INST for-each macros that take node
# identifiers as arguments.
for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \
for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = (
" ".join(f"fn(DT_{node.z_path_id})"
for node in okay_nodes)
for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \
for node in okay_nodes))
for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = (
" ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)"
for node in okay_nodes)
for node in okay_nodes))

# Helpers for INST versions of for-each macros, which take
# instance numbers. We emit separate helpers for these because
# avoiding an intermediate node_id --> instance number
# conversion in the preprocessor helps to keep the macro
# expansions simpler. That hopefully eases debugging.
for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \
for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = (
" ".join(f"fn({edt.compat2nodes[compat].index(node)})"
for node in okay_nodes)
for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \
for node in okay_nodes))
for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = (
" ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)"
for node in okay_nodes)
for node in okay_nodes))

for compat, nodes in edt.compat2nodes.items():
for node in nodes:
Expand Down
40 changes: 21 additions & 19 deletions scripts/dts/python-devicetree/src/devicetree/dtlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
import string
import sys
import textwrap
from typing import Any, Dict, Iterable, List, \
NamedTuple, NoReturn, Optional, Set, Tuple, TYPE_CHECKING, Union
from typing import (Any, Dict, Iterable, List,
NamedTuple, NoReturn, Optional,
Set, Tuple, TYPE_CHECKING, Union)

# NOTE: tests/test_dtlib.py is the test suite for this library.

Expand Down Expand Up @@ -353,8 +354,8 @@ def type(self) -> Type:
if types == [_MarkerType.PATH]:
return Type.PATH

if types == [_MarkerType.UINT32, _MarkerType.PHANDLE] and \
len(self.value) == 4:
if (types == [_MarkerType.UINT32, _MarkerType.PHANDLE]
and len(self.value) == 4):
return Type.PHANDLE

if set(types) == {_MarkerType.UINT32, _MarkerType.PHANDLE}:
Expand Down Expand Up @@ -608,9 +609,10 @@ def __str__(self):

pos += elm_size

if pos != 0 and \
(not next_marker or
next_marker[1] not in (_MarkerType.PHANDLE, _MarkerType.LABEL)):
if (pos != 0
and (not next_marker
or next_marker[1]
not in (_MarkerType.PHANDLE, _MarkerType.LABEL))):

s += _N_BYTES_TO_END_STR[elm_size]
if pos != len(self.value):
Expand All @@ -620,8 +622,8 @@ def __str__(self):


def __repr__(self):
return f"<Property '{self.name}' at '{self.node.path}' in " \
f"'{self.node.dt.filename}'>"
return (f"<Property '{self.name}' at '{self.node.path}' in "
f"'{self.node.dt.filename}'>")

#
# Internal functions
Expand Down Expand Up @@ -914,8 +916,8 @@ def __repr__(self):
the DT instance is evaluated.
"""
if self.filename:
return f"DT(filename='{self.filename}', " \
f"include_path={self._include_path})"
return (f"DT(filename='{self.filename}', "
f"include_path={self._include_path})")
return super().__repr__()

def __deepcopy__(self, memo):
Expand Down Expand Up @@ -1634,8 +1636,8 @@ def _next_token(self):

# State handling

if tok_id in (_T.DEL_PROP, _T.DEL_NODE, _T.OMIT_IF_NO_REF) or \
tok_val in ("{", ";"):
if (tok_id in (_T.DEL_PROP, _T.DEL_NODE, _T.OMIT_IF_NO_REF)
or tok_val in ("{", ";")):

self._lexer_state = _EXPECT_PROPNODENAME

Expand Down Expand Up @@ -1709,8 +1711,8 @@ def _enter_file(self, filename):
def _leave_file(self):
# Leaves an /include/d file, returning to the file that /include/d it

self.filename, self._lineno, self._file_contents, self._tok_end_i = \
self._filestack.pop()
self.filename, self._lineno, self._file_contents, self._tok_end_i = (
self._filestack.pop())

def _next_ref2node(self):
# Checks that the next token is a label/path reference and returns the
Expand Down Expand Up @@ -2067,10 +2069,10 @@ def _decode_and_escape(b):
# 'backslashreplace' bytes.translate() can't map to more than a single
# byte, but str.translate() can map to more than one character, so it's
# nice here. There's probably a nicer way to do this.
return b.decode("utf-8", "surrogateescape") \
.translate(_escape_table) \
.encode("utf-8", "surrogateescape") \
.decode("utf-8", "backslashreplace")
return (b.decode("utf-8", "surrogateescape")
.translate(_escape_table)
.encode("utf-8", "surrogateescape")
.decode("utf-8", "backslashreplace"))

def _root_and_path_to_node(cur, path, fullpath):
# Returns the node pointed at by 'path', relative to the Node 'cur'. For
Expand Down
78 changes: 40 additions & 38 deletions scripts/dts/python-devicetree/src/devicetree/edtlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
from typing import Any, Callable, Dict, Iterable, List, NoReturn, \
Optional, Set, TYPE_CHECKING, Tuple, Union
from typing import (Any, Callable, Dict, Iterable, List, NoReturn,
Optional, Set, TYPE_CHECKING, Tuple, Union)
import logging
import os
import re
Expand Down Expand Up @@ -401,9 +401,9 @@ def _check(self, require_compatible: bool, require_description: bool):

if "bus" in raw:
bus = raw["bus"]
if not isinstance(bus, str) and \
(not isinstance(bus, list) and \
not all(isinstance(elem, str) for elem in bus)):
if (not isinstance(bus, str) and
(not isinstance(bus, list) and
not all(isinstance(elem, str) for elem in bus))):
_err(f"malformed 'bus:' value in {self.path}, "
"expected string or list of strings")

Expand All @@ -413,17 +413,17 @@ def _check(self, require_compatible: bool, require_description: bool):
# Convert bus into a list
self._buses = [bus]

if "on-bus" in raw and \
not isinstance(raw["on-bus"], str):
if ("on-bus" in raw
and not isinstance(raw["on-bus"], str)):
_err(f"malformed 'on-bus:' value in {self.path}, "
"expected string")

self._check_properties()

for key, val in raw.items():
if key.endswith("-cells"):
if not isinstance(val, list) or \
not all(isinstance(elem, str) for elem in val):
if (not isinstance(val, list)
or not all(isinstance(elem, str) for elem in val)):
_err(f"malformed '{key}:' in {self.path}, "
"expected a list of strings")

Expand Down Expand Up @@ -460,8 +460,8 @@ def _check_properties(self) -> None:
_err(f"'{prop_name}' in 'properties' in {self.path} should not "
"have both 'deprecated' and 'required' set")

if "description" in options and \
not isinstance(options["description"], str):
if ("description" in options
and not isinstance(options["description"], str)):
_err("missing, malformed, or empty 'description' for "
f"'{prop_name}' in 'properties' in {self.path}")

Expand Down Expand Up @@ -579,9 +579,10 @@ def enum_upper_tokenizable(self) -> bool:
if not self.enum_tokenizable:
self._enum_upper_tokenizable = False
else:
self._enum_upper_tokenizable = \
(len(self._as_tokens) ==
len(set(x.upper() for x in self._as_tokens)))
self._enum_upper_tokenizable = (
len(self._as_tokens) == len(
set(x.upper() for x in self._as_tokens)
))
return self._enum_upper_tokenizable

@property
Expand Down Expand Up @@ -1585,14 +1586,14 @@ def _prop_val(

def _check_undeclared_props(self) -> None:
# Checks that all properties are declared in the binding
wl = {"compatible", "status", "ranges", "phandle",
"interrupt-parent", "interrupts-extended", "device_type"}

for prop_name in self._node.props:
# Allow a few special properties to not be declared in the binding
if prop_name.endswith("-controller") or \
prop_name.startswith("#") or \
prop_name in {
"compatible", "status", "ranges", "phandle",
"interrupt-parent", "interrupts-extended", "device_type"}:
if (prop_name.endswith("-controller")
or prop_name.startswith("#")
or prop_name in wl):
continue

if TYPE_CHECKING:
Expand Down Expand Up @@ -1807,9 +1808,9 @@ def _standard_phandle_val_list(
continue

controller_node, data = item
mapped_controller, mapped_data = \
_map_phandle_array_entry(prop.node, controller_node, data,
specifier_space)
mapped_controller, mapped_data = (
_map_phandle_array_entry(prop.node, controller_node,
data, specifier_space))

controller = self.edt._node2enode[mapped_controller]
# We'll fix up the names below.
Expand Down Expand Up @@ -2066,8 +2067,8 @@ def dts_source(self) -> str:
return f"{self._dt}"

def __repr__(self) -> str:
return f"<EDT for '{self.dts_path}', binding directories " \
f"'{self.bindings_dirs}'>"
return (f"<EDT for '{self.dts_path}', binding directories "
f"'{self.bindings_dirs}'>")

def __deepcopy__(self, memo) -> 'EDT':
"""
Expand Down Expand Up @@ -2493,12 +2494,12 @@ def _check_include_dict(name: Optional[str],

while child_filter is not None:
child_copy = deepcopy(child_filter)
child_allowlist: Optional[List[str]] = \
child_copy.pop('property-allowlist', None)
child_blocklist: Optional[List[str]] = \
child_copy.pop('property-blocklist', None)
next_child_filter: Optional[dict] = \
child_copy.pop('child-binding', None)
child_allowlist: Optional[List[str]] = (
child_copy.pop('property-allowlist', None))
child_blocklist: Optional[List[str]] = (
child_copy.pop('property-blocklist', None))
next_child_filter: Optional[dict] = (
child_copy.pop('child-binding', None))

if child_copy:
# We've popped out all the valid keys.
Expand Down Expand Up @@ -2595,8 +2596,8 @@ def _merge_props(to_dict: dict,
# These are used to generate errors for sketchy property overwrites.

for prop in from_dict:
if isinstance(to_dict.get(prop), dict) and \
isinstance(from_dict[prop], dict):
if (isinstance(to_dict.get(prop), dict)
and isinstance(from_dict[prop], dict)):
_merge_props(to_dict[prop], from_dict[prop], prop, binding_path,
check_required)
elif prop not in to_dict:
Expand Down Expand Up @@ -2709,21 +2710,22 @@ def ok_default() -> bool:
# If you change this, be sure to update the type annotation for
# PropertySpec.default.

if prop_type == "int" and isinstance(default, int) or \
prop_type == "string" and isinstance(default, str):
if (prop_type == "int" and isinstance(default, int)
or prop_type == "string" and isinstance(default, str)):
return True

# array, uint8-array, or string-array

if not isinstance(default, list):
return False

if prop_type == "array" and \
all(isinstance(val, int) for val in default):
if (prop_type == "array"
and all(isinstance(val, int) for val in default)):
return True

if prop_type == "uint8-array" and \
all(isinstance(val, int) and 0 <= val <= 255 for val in default):
if (prop_type == "uint8-array"
and all(isinstance(val, int)
and 0 <= val <= 255 for val in default)):
return True

# string-array
Expand Down

0 comments on commit 802eac7

Please sign in to comment.