scripts: dts: dtlib: improve formatting of long arrays

Split long arrays into multiple lines to improve readability of the
output DTS file. A new line is started when the array data exceeds
80 characters.

Add a few test entries to verify the new behavior.

Note: the F821 linter suppression prevents flagging 'array_start' and
'array_newline' as undefined variables. This is because these variables
are initialized when an opening brace is output, which is necessarily
before any element in a byte or prop array. A sequence of markers not
following this pattern would indicate a bug in the DTS parsing code.

Signed-off-by: Luca Burelli <l.burelli@arduino.cc>
This commit is contained in:
Luca Burelli 2025-05-28 11:34:52 +02:00 committed by Daniel DeGrasse
commit 0a4e2e383f
2 changed files with 14 additions and 0 deletions

View file

@ -641,11 +641,16 @@ class Property:
elif marker_type is _MarkerType.PHANDLE: elif marker_type is _MarkerType.PHANDLE:
s += " &" + ref s += " &" + ref
pos += 4 pos += 4
if pos != len(self.value) and len(s) - array_start > 80: # noqa: F821
s += array_newline # noqa: F821
array_start = len(s)
# Subtle: There might be more data between the phandle and # Subtle: There might be more data between the phandle and
# the next marker, so we can't 'continue' here # the next marker, so we can't 'continue' here
else: # marker_type is _MarkerType.UINT* else: # marker_type is _MarkerType.UINT*
elm_size = _TYPE_TO_N_BYTES[marker_type] elm_size = _TYPE_TO_N_BYTES[marker_type]
s += _N_BYTES_TO_START_STR[elm_size] s += _N_BYTES_TO_START_STR[elm_size]
array_start = len(s)
array_newline = "\n" + " " * array_start
while pos != end: while pos != end:
num = int.from_bytes(self.value[pos:pos + elm_size], num = int.from_bytes(self.value[pos:pos + elm_size],
@ -656,6 +661,9 @@ class Property:
s += f" {hex(num)}" s += f" {hex(num)}"
pos += elm_size pos += elm_size
if pos != len(self.value) and len(s) - array_start > 80:
s += array_newline
array_start = len(s)
if (pos != 0 if (pos != 0
and (not next_marker and (not next_marker

View file

@ -163,6 +163,8 @@ def test_cell_parsing():
j = /bits/ 32 < 0x10 0x20 (-1) >; j = /bits/ 32 < 0x10 0x20 (-1) >;
k = /bits/ 64 < 0x10 0x20 (-1) >; k = /bits/ 64 < 0x10 0x20 (-1) >;
l = < 'a' 'b' 'c' >; l = < 'a' 'b' 'c' >;
m = [ 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b ];
n = < 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 >;
}; };
""", """,
""" """
@ -181,6 +183,10 @@ def test_cell_parsing():
j = < 0x10 0x20 0xffffffff >; j = < 0x10 0x20 0xffffffff >;
k = /bits/ 64 < 0x10 0x20 0xffffffffffffffff >; k = /bits/ 64 < 0x10 0x20 0xffffffffffffffff >;
l = < 0x61 0x62 0x63 >; l = < 0x61 0x62 0x63 >;
m = [ 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A
1B ];
n = < 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 0x11 0x12 0x13
0x14 >;
}; };
""") """)