blob: 86bd91bfab81f2430376d21cb1345bcb2c289c62 [file] [log] [blame]
Martí Bolívardc85edd2020-02-28 15:26:52 -08001#!/usr/bin/env python3
2
3# Copyright (c) 2019 - 2020 Nordic Semiconductor ASA
4# Copyright (c) 2019 Linaro Limited
5# SPDX-License-Identifier: BSD-3-Clause
6
7# This script uses edtlib to generate a header file from a devicetree
8# (.dts) file. Information from binding files in YAML format is used
9# as well.
10#
11# Bindings are files that describe devicetree nodes. Devicetree nodes are
12# usually mapped to bindings via their 'compatible = "..."' property.
13#
14# See Zephyr's Devicetree user guide for details.
15#
16# Note: Do not access private (_-prefixed) identifiers from edtlib here (and
17# also note that edtlib is not meant to expose the dtlib API directly).
18# Instead, think of what API you need, and add it as a public documented API in
19# edtlib. This will keep this script simple.
20
21import argparse
Martí Bolívara3fae2f2020-03-25 14:18:27 -070022from collections import defaultdict
Martí Bolívar09858492020-12-08 09:41:49 -080023import logging
Martí Bolívardc85edd2020-02-28 15:26:52 -080024import os
25import pathlib
Martí Bolívar533f4512020-07-01 10:43:43 -070026import pickle
Martí Bolívardc85edd2020-02-28 15:26:52 -080027import re
28import sys
29
Jordan Yates8e4107f2022-04-30 21:13:52 +100030sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'python-devicetree',
31 'src'))
Martí Bolívar53328472021-03-26 16:18:58 -070032
33from devicetree import edtlib
Martí Bolívardc85edd2020-02-28 15:26:52 -080034
Martí Bolívar9c229a42021-04-14 15:26:42 -070035# The set of binding types whose values can be iterated over with
36# DT_FOREACH_PROP_ELEM(). If you change this, make sure to update the
37# doxygen string for that macro.
38FOREACH_PROP_ELEM_TYPES = set(['string', 'array', 'uint8-array', 'string-array',
39 'phandles', 'phandle-array'])
40
Martí Bolívar09858492020-12-08 09:41:49 -080041class LogFormatter(logging.Formatter):
42 '''A log formatter that prints the level name in lower case,
43 for compatibility with earlier versions of edtlib.'''
44
45 def __init__(self):
46 super().__init__(fmt='%(levelnamelower)s: %(message)s')
47
48 def format(self, record):
49 record.levelnamelower = record.levelname.lower()
50 return super().format(record)
51
Martí Bolívardc85edd2020-02-28 15:26:52 -080052def main():
53 global header_file
Kumar Galabd973782020-05-06 20:54:29 -050054 global flash_area_num
Martí Bolívardc85edd2020-02-28 15:26:52 -080055
56 args = parse_args()
57
Martí Bolívar09858492020-12-08 09:41:49 -080058 setup_edtlib_logging()
59
Martí Bolívar85837e12021-08-19 11:09:05 -070060 vendor_prefixes = {}
61 for prefixes_file in args.vendor_prefixes:
62 vendor_prefixes.update(edtlib.load_vendor_prefixes_txt(prefixes_file))
Martí Bolívarf261d772021-05-18 15:09:49 -070063
Martí Bolívardc85edd2020-02-28 15:26:52 -080064 try:
65 edt = edtlib.EDT(args.dts, args.bindings_dirs,
66 # Suppress this warning if it's suppressed in dtc
67 warn_reg_unit_address_mismatch=
Kumar Galabc48f1c2020-05-01 12:33:00 -050068 "-Wno-simple_bus_reg" not in args.dtc_flags,
Peter Bigot932532e2020-09-02 05:05:19 -050069 default_prop_types=True,
Martí Bolívardf5a55c2021-02-14 17:52:57 -080070 infer_binding_for_paths=["/zephyr,user"],
Martí Bolívarc4079e42021-07-30 15:43:27 -070071 werror=args.edtlib_Werror,
Martí Bolívarf261d772021-05-18 15:09:49 -070072 vendor_prefixes=vendor_prefixes)
Martí Bolívardc85edd2020-02-28 15:26:52 -080073 except edtlib.EDTError as e:
74 sys.exit(f"devicetree error: {e}")
75
Kumar Galabd973782020-05-06 20:54:29 -050076 flash_area_num = 0
77
Martí Bolívardc85edd2020-02-28 15:26:52 -080078 # Save merged DTS source, as a debugging aid
79 with open(args.dts_out, "w", encoding="utf-8") as f:
80 print(edt.dts_source, file=f)
81
Martí Bolívare96ca542020-05-07 12:07:02 -070082 # The raw index into edt.compat2nodes[compat] is used for node
83 # instance numbering within a compatible.
84 #
85 # As a way to satisfy people's intuitions about instance numbers,
86 # though, we sort this list so enabled instances come first.
87 #
88 # This might look like a hack, but it keeps drivers and
89 # applications which don't use instance numbers carefully working
90 # as expected, since e.g. instance number 0 is always the
91 # singleton instance if there's just one enabled node of a
92 # particular compatible.
93 #
94 # This doesn't violate any devicetree.h API guarantees about
95 # instance ordering, since we make no promises that instance
96 # numbers are stable across builds.
97 for compat, nodes in edt.compat2nodes.items():
98 edt.compat2nodes[compat] = sorted(
99 nodes, key=lambda node: 0 if node.status == "okay" else 1)
100
Martí Bolívar533f4512020-07-01 10:43:43 -0700101 # Create the generated header.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800102 with open(args.header_out, "w", encoding="utf-8") as header_file:
103 write_top_comment(edt)
104
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000105 # populate all z_path_id first so any children references will
106 # work correctly.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800107 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívar186bace2020-04-08 15:02:18 -0700108 node.z_path_id = node_z_path_id(node)
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000109
Jordan Yates9c98d4f2021-07-28 20:01:16 +1000110 # Check to see if we have duplicate "zephyr,memory-region" property values.
111 regions = dict()
112 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
113 if 'zephyr,memory-region' in node.props:
114 region = node.props['zephyr,memory-region'].val
115 if region in regions:
116 sys.exit(f"ERROR: Duplicate 'zephyr,memory-region' ({region}) properties "
117 f"between {regions[region].path} and {node.path}")
118 regions[region] = node
119
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000120 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800121 write_node_comment(node)
122
Kumar Gala270a05f2021-02-24 11:28:21 -0600123 out_comment("Node's full path:")
Martí Bolívar00ffc7e2020-12-13 12:27:04 -0800124 out_dt_define(f"{node.z_path_id}_PATH", f'"{escape(node.path)}"')
125
Kumar Gala4aac9082021-02-24 10:44:07 -0600126 out_comment("Node's name with unit-address:")
127 out_dt_define(f"{node.z_path_id}_FULL_NAME",
128 f'"{escape(node.name)}"')
129
Martí Bolívar6e273432020-04-08 15:04:15 -0700130 if node.parent is not None:
131 out_comment(f"Node parent ({node.parent.path}) identifier:")
132 out_dt_define(f"{node.z_path_id}_PARENT",
133 f"DT_{node.parent.z_path_id}")
134
Martí Bolívar50f9b3c2022-03-23 13:41:09 -0700135 out_comment(f"Node's index in its parent's list of children:")
136 out_dt_define(f"{node.z_path_id}_CHILD_IDX",
137 node.parent.child_index(node))
138
Martí Bolívar355cc012022-03-23 13:26:24 -0700139 write_children(node)
Martí Bolívar305379e2020-06-08 14:59:19 -0700140 write_dep_info(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800141 write_idents_and_existence(node)
142 write_bus(node)
143 write_special_props(node)
144 write_vanilla_props(node)
145
146 write_chosen(edt)
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700147 write_global_compat_info(edt)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800148
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600149 write_device_extern_header(args.device_header_out, edt)
150
Martí Bolívar533f4512020-07-01 10:43:43 -0700151 if args.edt_pickle_out:
152 write_pickled_edt(edt, args.edt_pickle_out)
153
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600154
155def write_device_extern_header(device_header_out, edt):
156 # Generate header that will extern devicetree struct device's
157
158 with open(device_header_out, "w", encoding="utf-8") as dev_header_file:
159 print("#ifndef DEVICE_EXTERN_GEN_H", file=dev_header_file)
160 print("#define DEVICE_EXTERN_GEN_H", file=dev_header_file)
161 print("", file=dev_header_file)
162 print("#ifdef __cplusplus", file=dev_header_file)
163 print('extern "C" {', file=dev_header_file)
164 print("#endif", file=dev_header_file)
165 print("", file=dev_header_file)
166
167 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Peter Bigotf91e9fb2021-01-23 07:56:09 -0600168 print(f"extern const struct device DEVICE_DT_NAME_GET(DT_{node.z_path_id}); /* dts_ord_{node.dep_ordinal} */",
169 file=dev_header_file)
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600170
171 print("", file=dev_header_file)
172 print("#ifdef __cplusplus", file=dev_header_file)
173 print("}", file=dev_header_file)
174 print("#endif", file=dev_header_file)
175 print("", file=dev_header_file)
176 print("#endif /* DEVICE_EXTERN_GEN_H */", file=dev_header_file)
177
178
Martí Bolívar09858492020-12-08 09:41:49 -0800179def setup_edtlib_logging():
180 # The edtlib module emits logs using the standard 'logging' module.
181 # Configure it so that warnings and above are printed to stderr,
182 # using the LogFormatter class defined above to format each message.
183
184 handler = logging.StreamHandler(sys.stderr)
185 handler.setFormatter(LogFormatter())
186
187 logger = logging.getLogger('edtlib')
188 logger.setLevel(logging.WARNING)
189 logger.addHandler(handler)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800190
Martí Bolívar186bace2020-04-08 15:02:18 -0700191def node_z_path_id(node):
192 # Return the node specific bit of the node's path identifier:
193 #
194 # - the root node's path "/" has path identifier "N"
195 # - "/foo" has "N_S_foo"
196 # - "/foo/bar" has "N_S_foo_S_bar"
197 # - "/foo/bar@123" has "N_S_foo_S_bar_123"
198 #
199 # This is used throughout this file to generate macros related to
200 # the node.
201
202 components = ["N"]
203 if node.parent is not None:
204 components.extend(f"S_{str2ident(component)}" for component in
205 node.path.split("/")[1:])
206
207 return "_".join(components)
208
Martí Bolívardc85edd2020-02-28 15:26:52 -0800209def parse_args():
210 # Returns parsed command-line arguments
211
212 parser = argparse.ArgumentParser()
213 parser.add_argument("--dts", required=True, help="DTS file")
214 parser.add_argument("--dtc-flags",
215 help="'dtc' devicetree compiler flags, some of which "
216 "might be respected here")
217 parser.add_argument("--bindings-dirs", nargs='+', required=True,
218 help="directory with bindings in YAML format, "
219 "we allow multiple")
220 parser.add_argument("--header-out", required=True,
221 help="path to write header to")
222 parser.add_argument("--dts-out", required=True,
223 help="path to write merged DTS source code to (e.g. "
224 "as a debugging aid)")
Kumar Gala98b6e4f2021-01-13 11:06:46 -0600225 parser.add_argument("--device-header-out", required=True,
226 help="path to write device struct extern header to")
Martí Bolívar533f4512020-07-01 10:43:43 -0700227 parser.add_argument("--edt-pickle-out",
228 help="path to write pickled edtlib.EDT object to")
Martí Bolívar85837e12021-08-19 11:09:05 -0700229 parser.add_argument("--vendor-prefixes", action='append', default=[],
230 help="vendor-prefixes.txt path; used for validation; "
231 "may be given multiple times")
Martí Bolívarc4079e42021-07-30 15:43:27 -0700232 parser.add_argument("--edtlib-Werror", action="store_true",
233 help="if set, edtlib-specific warnings become errors. "
234 "(this does not apply to warnings shared "
235 "with dtc.)")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800236
237 return parser.parse_args()
238
239
240def write_top_comment(edt):
241 # Writes an overview comment with misc. info at the top of the header and
242 # configuration file
243
244 s = f"""\
245Generated by gen_defines.py
246
247DTS input file:
248 {edt.dts_path}
249
250Directories with bindings:
251 {", ".join(map(relativize, edt.bindings_dirs))}
252
Martí Bolívar305379e2020-06-08 14:59:19 -0700253Node dependency ordering (ordinal and path):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800254"""
255
Martí Bolívarb6db2012020-08-24 13:33:53 -0700256 for scc in edt.scc_order:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800257 if len(scc) > 1:
258 err("cycle in devicetree involving "
259 + ", ".join(node.path for node in scc))
260 s += f" {scc[0].dep_ordinal:<3} {scc[0].path}\n"
261
262 s += """
263Definitions derived from these nodes in dependency order are next,
264followed by /chosen nodes.
265"""
266
267 out_comment(s, blank_before=False)
268
269
270def write_node_comment(node):
271 # Writes a comment describing 'node' to the header and configuration file
272
273 s = f"""\
Martí Bolívarb6e6ba02020-04-08 15:09:46 -0700274Devicetree node: {node.path}
275
Martí Bolívar305379e2020-06-08 14:59:19 -0700276Node identifier: DT_{node.z_path_id}
Martí Bolívardc85edd2020-02-28 15:26:52 -0800277"""
278
279 if node.matching_compat:
Peter Bigot932532e2020-09-02 05:05:19 -0500280 if node.binding_path:
281 s += f"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800282Binding (compatible = {node.matching_compat}):
283 {relativize(node.binding_path)}
284"""
Peter Bigot932532e2020-09-02 05:05:19 -0500285 else:
286 s += f"""
287Binding (compatible = {node.matching_compat}):
288 No yaml (bindings inferred from properties)
289"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800290
Martí Bolívardc85edd2020-02-28 15:26:52 -0800291 if node.description:
Martí Bolívarf7d33f22020-10-30 17:45:27 -0700292 # We used to put descriptions in the generated file, but
293 # devicetree bindings now have pages in the HTML
294 # documentation. Let users who are accustomed to digging
295 # around in the generated file where to find the descriptions
296 # now.
297 #
298 # Keeping them here would mean that the descriptions
299 # themselves couldn't contain C multi-line comments, which is
300 # inconvenient when we want to do things like quote snippets
301 # of .dtsi files within the descriptions, or otherwise
302 # include the string "*/".
303 s += ("\n(Descriptions have moved to the Devicetree Bindings Index\n"
304 "in the documentation.)\n")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800305
306 out_comment(s)
307
308
309def relativize(path):
310 # If 'path' is within $ZEPHYR_BASE, returns it relative to $ZEPHYR_BASE,
311 # with a "$ZEPHYR_BASE/..." hint at the start of the string. Otherwise,
312 # returns 'path' unchanged.
313
314 zbase = os.getenv("ZEPHYR_BASE")
315 if zbase is None:
316 return path
317
318 try:
319 return str("$ZEPHYR_BASE" / pathlib.Path(path).relative_to(zbase))
320 except ValueError:
321 # Not within ZEPHYR_BASE
322 return path
323
324
325def write_idents_and_existence(node):
326 # Writes macros related to the node's aliases, labels, etc.,
327 # as well as existence flags.
328
329 # Aliases
330 idents = [f"N_ALIAS_{str2ident(alias)}" for alias in node.aliases]
331 # Instances
332 for compat in node.compats:
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700333 instance_no = node.edt.compat2nodes[compat].index(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800334 idents.append(f"N_INST_{instance_no}_{str2ident(compat)}")
335 # Node labels
336 idents.extend(f"N_NODELABEL_{str2ident(label)}" for label in node.labels)
337
338 out_comment("Existence and alternate IDs:")
339 out_dt_define(node.z_path_id + "_EXISTS", 1)
340
341 # Only determine maxlen if we have any idents
342 if idents:
343 maxlen = max(len("DT_" + ident) for ident in idents)
344 for ident in idents:
345 out_dt_define(ident, "DT_" + node.z_path_id, width=maxlen)
346
347
348def write_bus(node):
349 # Macros about the node's bus controller, if there is one
350
351 bus = node.bus_node
352 if not bus:
353 return
354
Martí Bolívardc85edd2020-02-28 15:26:52 -0800355 out_comment(f"Bus info (controller: '{bus.path}', type: '{node.on_bus}')")
356 out_dt_define(f"{node.z_path_id}_BUS_{str2ident(node.on_bus)}", 1)
357 out_dt_define(f"{node.z_path_id}_BUS", f"DT_{bus.z_path_id}")
358
359
360def write_special_props(node):
361 # Writes required macros for special case properties, when the
362 # data cannot otherwise be obtained from write_vanilla_props()
363 # results
364
Martí Bolívardc85edd2020-02-28 15:26:52 -0800365 # Macros that are special to the devicetree specification
Martí Bolívar7f69a032021-08-11 15:14:51 -0700366 out_comment("Macros for properties that are special in the specification:")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800367 write_regs(node)
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200368 write_ranges(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800369 write_interrupts(node)
370 write_compatibles(node)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700371 write_status(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800372
Martí Bolívar7f69a032021-08-11 15:14:51 -0700373 # Macros that are special to bindings inherited from Linux, which
374 # we can't capture with the current bindings language.
Martí Bolívar9df04932021-08-11 15:43:24 -0700375 write_pinctrls(node)
Martí Bolívar7f69a032021-08-11 15:14:51 -0700376 write_fixed_partitions(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800377
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200378def write_ranges(node):
379 # ranges property: edtlib knows the right #address-cells and
380 # #size-cells of parent and child, and can therefore pack the
381 # child & parent addresses and sizes correctly
382
383 idx_vals = []
384 path_id = node.z_path_id
385
386 if node.ranges is not None:
387 idx_vals.append((f"{path_id}_RANGES_NUM", len(node.ranges)))
388
389 for i,range in enumerate(node.ranges):
390 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_EXISTS", 1))
391
392 if node.bus == "pcie":
393 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS_EXISTS", 1))
394 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS"
395 idx_value = range.child_bus_addr >> ((range.child_bus_cells - 1) * 32)
396 idx_vals.append((idx_macro,
397 f"{idx_value} /* {hex(idx_value)} */"))
398 if range.child_bus_addr is not None:
399 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_ADDRESS"
400 if node.bus == "pcie":
401 idx_value = range.child_bus_addr & ((1 << (range.child_bus_cells - 1) * 32) - 1)
402 else:
403 idx_value = range.child_bus_addr
404 idx_vals.append((idx_macro,
405 f"{idx_value} /* {hex(idx_value)} */"))
406 if range.parent_bus_addr is not None:
407 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_PARENT_BUS_ADDRESS"
408 idx_vals.append((idx_macro,
409 f"{range.parent_bus_addr} /* {hex(range.parent_bus_addr)} */"))
410 if range.length is not None:
411 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_LENGTH"
412 idx_vals.append((idx_macro,
413 f"{range.length} /* {hex(range.length)} */"))
414
415 for macro, val in idx_vals:
416 out_dt_define(macro, val)
417
418 out_dt_define(f"{path_id}_FOREACH_RANGE(fn)",
419 " ".join(f"fn(DT_{path_id}, {i})" for i,range in enumerate(node.ranges)))
420
Martí Bolívardc85edd2020-02-28 15:26:52 -0800421def write_regs(node):
422 # reg property: edtlib knows the right #address-cells and
423 # #size-cells, and can therefore pack the register base addresses
424 # and sizes correctly
425
426 idx_vals = []
427 name_vals = []
428 path_id = node.z_path_id
429
430 if node.regs is not None:
431 idx_vals.append((f"{path_id}_REG_NUM", len(node.regs)))
432
433 for i, reg in enumerate(node.regs):
Kumar Gala4e2ad002020-04-14 14:27:20 -0500434 idx_vals.append((f"{path_id}_REG_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800435 if reg.addr is not None:
436 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_ADDRESS"
437 idx_vals.append((idx_macro,
438 f"{reg.addr} /* {hex(reg.addr)} */"))
439 if reg.name:
440 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_ADDRESS"
441 name_vals.append((name_macro, f"DT_{idx_macro}"))
442
443 if reg.size is not None:
444 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_SIZE"
445 idx_vals.append((idx_macro,
446 f"{reg.size} /* {hex(reg.size)} */"))
447 if reg.name:
448 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_SIZE"
449 name_vals.append((name_macro, f"DT_{idx_macro}"))
450
451 for macro, val in idx_vals:
452 out_dt_define(macro, val)
453 for macro, val in name_vals:
454 out_dt_define(macro, val)
455
456def write_interrupts(node):
457 # interrupts property: we have some hard-coded logic for interrupt
458 # mapping here.
459 #
460 # TODO: can we push map_arm_gic_irq_type() and
461 # encode_zephyr_multi_level_irq() out of Python and into C with
462 # macro magic in devicetree.h?
463
464 def map_arm_gic_irq_type(irq, irq_num):
465 # Maps ARM GIC IRQ (type)+(index) combo to linear IRQ number
466 if "type" not in irq.data:
467 err(f"Expected binding for {irq.controller!r} to have 'type' in "
468 "interrupt-cells")
469 irq_type = irq.data["type"]
470
471 if irq_type == 0: # GIC_SPI
472 return irq_num + 32
473 if irq_type == 1: # GIC_PPI
474 return irq_num + 16
475 err(f"Invalid interrupt type specified for {irq!r}")
476
477 def encode_zephyr_multi_level_irq(irq, irq_num):
478 # See doc/reference/kernel/other/interrupts.rst for details
479 # on how this encoding works
480
481 irq_ctrl = irq.controller
482 # Look for interrupt controller parent until we have none
483 while irq_ctrl.interrupts:
484 irq_num = (irq_num + 1) << 8
485 if "irq" not in irq_ctrl.interrupts[0].data:
486 err(f"Expected binding for {irq_ctrl!r} to have 'irq' in "
487 "interrupt-cells")
488 irq_num |= irq_ctrl.interrupts[0].data["irq"]
489 irq_ctrl = irq_ctrl.interrupts[0].controller
490 return irq_num
491
492 idx_vals = []
493 name_vals = []
494 path_id = node.z_path_id
495
496 if node.interrupts is not None:
497 idx_vals.append((f"{path_id}_IRQ_NUM", len(node.interrupts)))
498
499 for i, irq in enumerate(node.interrupts):
500 for cell_name, cell_value in irq.data.items():
501 name = str2ident(cell_name)
502
503 if cell_name == "irq":
504 if "arm,gic" in irq.controller.compats:
505 cell_value = map_arm_gic_irq_type(irq, cell_value)
506 cell_value = encode_zephyr_multi_level_irq(irq, cell_value)
507
Kumar Gala4e2ad002020-04-14 14:27:20 -0500508 idx_vals.append((f"{path_id}_IRQ_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800509 idx_macro = f"{path_id}_IRQ_IDX_{i}_VAL_{name}"
510 idx_vals.append((idx_macro, cell_value))
511 idx_vals.append((idx_macro + "_EXISTS", 1))
512 if irq.name:
513 name_macro = \
514 f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}"
515 name_vals.append((name_macro, f"DT_{idx_macro}"))
516 name_vals.append((name_macro + "_EXISTS", 1))
517
518 for macro, val in idx_vals:
519 out_dt_define(macro, val)
520 for macro, val in name_vals:
521 out_dt_define(macro, val)
522
523
524def write_compatibles(node):
525 # Writes a macro for each of the node's compatibles. We don't care
526 # about whether edtlib / Zephyr's binding language recognizes
527 # them. The compatibles the node provides are what is important.
528
529 for compat in node.compats:
530 out_dt_define(
531 f"{node.z_path_id}_COMPAT_MATCHES_{str2ident(compat)}", 1)
532
533
Martí Bolívar355cc012022-03-23 13:26:24 -0700534def write_children(node):
535 # Writes helper macros for dealing with node's children.
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000536
Martí Bolívar7b2a7282022-07-08 11:04:46 -0700537 out_comment("Helper macros for child nodes of this node.")
538
Kumar Gala4a5a90a2020-05-08 12:25:25 -0500539 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)",
540 " ".join(f"fn(DT_{child.z_path_id})" for child in
541 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000542
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400543 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_VARGS(fn, ...)",
544 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)" for child in
545 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000546
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800547 functions = ''
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400548 functions_args = ''
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800549 for child in node.children.values():
550 if child.status == "okay":
551 functions = functions + f"fn(DT_{child.z_path_id}) "
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400552 functions_args = functions_args + f"fn(DT_{child.z_path_id}, " \
553 "__VA_ARGS__) "
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800554
555 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY(fn)", functions)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400556 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_VARGS(fn, ...)",
557 functions_args)
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800558
559
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700560def write_status(node):
561 out_dt_define(f"{node.z_path_id}_STATUS_{str2ident(node.status)}", 1)
562
563
Martí Bolívar9df04932021-08-11 15:43:24 -0700564def write_pinctrls(node):
565 # Write special macros for pinctrl-<index> and pinctrl-names properties.
566
567 out_comment("Pin control (pinctrl-<i>, pinctrl-names) properties:")
568
569 out_dt_define(f"{node.z_path_id}_PINCTRL_NUM", len(node.pinctrls))
570
571 if not node.pinctrls:
572 return
573
574 for pc_idx, pinctrl in enumerate(node.pinctrls):
575 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_EXISTS", 1)
576
577 if not pinctrl.name:
578 continue
579
580 name = pinctrl.name_as_token
581
582 # Below we rely on the fact that edtlib ensures the
583 # pinctrl-<pc_idx> properties are contiguous, start from 0,
584 # and contain only phandles.
585 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_TOKEN", name)
586 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_UPPER_TOKEN", name.upper())
587 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_EXISTS", 1)
588 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX", pc_idx)
589 for idx, ph in enumerate(pinctrl.conf_nodes):
590 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX_{idx}_PH",
591 f"DT_{ph.z_path_id}")
592
593
Martí Bolívar7f69a032021-08-11 15:14:51 -0700594def write_fixed_partitions(node):
595 # Macros for child nodes of each fixed-partitions node.
596
597 if not (node.parent and "fixed-partitions" in node.parent.compats):
598 return
599
600 global flash_area_num
601 out_comment("fixed-partitions identifier:")
602 out_dt_define(f"{node.z_path_id}_PARTITION_ID", flash_area_num)
603 flash_area_num += 1
604
605
Martí Bolívardc85edd2020-02-28 15:26:52 -0800606def write_vanilla_props(node):
607 # Writes macros for any and all properties defined in the
608 # "properties" section of the binding for the node.
609 #
610 # This does generate macros for special properties as well, like
611 # regs, etc. Just let that be rather than bothering to add
612 # never-ending amounts of special case code here to skip special
613 # properties. This function's macros can't conflict with
614 # write_special_props() macros, because they're in different
615 # namespaces. Special cases aren't special enough to break the rules.
616
617 macro2val = {}
618 for prop_name, prop in node.props.items():
Martí Bolívar9c229a42021-04-14 15:26:42 -0700619 prop_id = str2ident(prop_name)
620 macro = f"{node.z_path_id}_P_{prop_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800621 val = prop2value(prop)
622 if val is not None:
623 # DT_N_<node-id>_P_<prop-id>
624 macro2val[macro] = val
625
Carlo Caionef4db14f2021-05-17 17:24:27 +0200626 if prop.spec.type == 'string':
627 macro2val[macro + "_STRING_TOKEN"] = prop.val_as_token
628 macro2val[macro + "_STRING_UPPER_TOKEN"] = prop.val_as_token.upper()
629
Martí Bolívardc85edd2020-02-28 15:26:52 -0800630 if prop.enum_index is not None:
631 # DT_N_<node-id>_P_<prop-id>_ENUM_IDX
632 macro2val[macro + "_ENUM_IDX"] = prop.enum_index
Peter Bigot345da782020-12-02 09:04:27 -0600633 spec = prop.spec
634
635 if spec.enum_tokenizable:
636 as_token = prop.val_as_token
637
638 # DT_N_<node-id>_P_<prop-id>_ENUM_TOKEN
639 macro2val[macro + "_ENUM_TOKEN"] = as_token
640
641 if spec.enum_upper_tokenizable:
642 # DT_N_<node-id>_P_<prop-id>_ENUM_UPPER_TOKEN
643 macro2val[macro + "_ENUM_UPPER_TOKEN"] = as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800644
645 if "phandle" in prop.type:
646 macro2val.update(phandle_macros(prop, macro))
647 elif "array" in prop.type:
648 # DT_N_<node-id>_P_<prop-id>_IDX_<i>
Martí Bolívarffc03122020-11-12 20:27:20 -0800649 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
Martí Bolívardc85edd2020-02-28 15:26:52 -0800650 for i, subval in enumerate(prop.val):
651 if isinstance(subval, str):
652 macro2val[macro + f"_IDX_{i}"] = quote_str(subval)
Martí Bolívard6f68f02022-07-08 11:21:34 -0700653 subval_as_token = edtlib.str_as_token(subval)
654 macro2val[macro + f"_IDX_{i}_TOKEN"] = subval_as_token
655 macro2val[macro + f"_IDX_{i}_UPPER_TOKEN"] = subval_as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800656 else:
657 macro2val[macro + f"_IDX_{i}"] = subval
Martí Bolívarffc03122020-11-12 20:27:20 -0800658 macro2val[macro + f"_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800659
Martí Bolívar9c229a42021-04-14 15:26:42 -0700660 if prop.type in FOREACH_PROP_ELEM_TYPES:
661 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM
662 macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \
663 ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
664 for i in range(len(prop.val)))
665
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400666 macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \
667 ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i},'
668 ' __VA_ARGS__)'
669 for i in range(len(prop.val)))
670
Martí Bolívardc85edd2020-02-28 15:26:52 -0800671 plen = prop_len(prop)
672 if plen is not None:
673 # DT_N_<node-id>_P_<prop-id>_LEN
674 macro2val[macro + "_LEN"] = plen
675
676 macro2val[f"{macro}_EXISTS"] = 1
677
678 if macro2val:
679 out_comment("Generic property macros:")
680 for macro, val in macro2val.items():
681 out_dt_define(macro, val)
682 else:
683 out_comment("(No generic property macros)")
684
685
Martí Bolívar305379e2020-06-08 14:59:19 -0700686def write_dep_info(node):
687 # Write dependency-related information about the node.
688
689 def fmt_dep_list(dep_list):
690 if dep_list:
691 # Sort the list by dependency ordinal for predictability.
692 sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal)
693 return "\\\n\t" + \
694 " \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */"
695 for n in sorted_list)
696 else:
697 return "/* nothing */"
698
699 out_comment("Node's dependency ordinal:")
700 out_dt_define(f"{node.z_path_id}_ORD", node.dep_ordinal)
701
702 out_comment("Ordinals for what this node depends on directly:")
703 out_dt_define(f"{node.z_path_id}_REQUIRES_ORDS",
704 fmt_dep_list(node.depends_on))
705
706 out_comment("Ordinals for what depends directly on this node:")
707 out_dt_define(f"{node.z_path_id}_SUPPORTS_ORDS",
708 fmt_dep_list(node.required_by))
709
710
Martí Bolívardc85edd2020-02-28 15:26:52 -0800711def prop2value(prop):
712 # Gets the macro value for property 'prop', if there is
713 # a single well-defined C rvalue that it can be represented as.
714 # Returns None if there isn't one.
715
716 if prop.type == "string":
717 return quote_str(prop.val)
718
719 if prop.type == "int":
720 return prop.val
721
722 if prop.type == "boolean":
723 return 1 if prop.val else 0
724
725 if prop.type in ["array", "uint8-array"]:
726 return list2init(f"{val} /* {hex(val)} */" for val in prop.val)
727
728 if prop.type == "string-array":
729 return list2init(quote_str(val) for val in prop.val)
730
731 # phandle, phandles, phandle-array, path, compound: nothing
732 return None
733
734
735def prop_len(prop):
736 # Returns the property's length if and only if we should generate
737 # a _LEN macro for the property. Otherwise, returns None.
738 #
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200739 # This deliberately excludes ranges, dma-ranges, reg and interrupts.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800740 # While they have array type, their lengths as arrays are
741 # basically nonsense semantically due to #address-cells and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200742 # #size-cells for "reg", #interrupt-cells for "interrupts"
743 # and #address-cells, #size-cells and the #address-cells from the
744 # parent node for "ranges" and "dma-ranges".
Martí Bolívardc85edd2020-02-28 15:26:52 -0800745 #
746 # We have special purpose macros for the number of register blocks
747 # / interrupt specifiers. Excluding them from this list means
748 # DT_PROP_LEN(node_id, ...) fails fast at the devicetree.h layer
749 # with a build error. This forces users to switch to the right
750 # macros.
751
752 if prop.type == "phandle":
753 return 1
754
755 if (prop.type in ["array", "uint8-array", "string-array",
756 "phandles", "phandle-array"] and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200757 prop.name not in ["ranges", "dma-ranges", "reg", "interrupts"]):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800758 return len(prop.val)
759
760 return None
761
762
763def phandle_macros(prop, macro):
764 # Returns a dict of macros for phandle or phandles property 'prop'.
765 #
766 # The 'macro' argument is the N_<node-id>_P_<prop-id> bit.
767 #
768 # These are currently special because we can't serialize their
769 # values without using label properties, which we're trying to get
770 # away from needing in Zephyr. (Label properties are great for
771 # humans, but have drawbacks for code size and boot time.)
772 #
773 # The names look a bit weird to make it easier for devicetree.h
774 # to use the same macros for phandle, phandles, and phandle-array.
775
776 ret = {}
777
778 if prop.type == "phandle":
779 # A phandle is treated as a phandles with fixed length 1.
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500780 ret[f"{macro}"] = f"DT_{prop.val.z_path_id}"
781 ret[f"{macro}_IDX_0"] = f"DT_{prop.val.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800782 ret[f"{macro}_IDX_0_PH"] = f"DT_{prop.val.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800783 ret[f"{macro}_IDX_0_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800784 elif prop.type == "phandles":
785 for i, node in enumerate(prop.val):
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500786 ret[f"{macro}_IDX_{i}"] = f"DT_{node.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800787 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{node.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800788 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800789 elif prop.type == "phandle-array":
790 for i, entry in enumerate(prop.val):
Martí Bolívar38ede5a2020-12-17 14:12:01 -0800791 if entry is None:
792 # Unspecified element. The phandle-array at this index
793 # does not point at a ControllerAndData value, but
794 # subsequent indices in the array may.
795 ret[f"{macro}_IDX_{i}_EXISTS"] = 0
796 continue
797
Martí Bolívardc85edd2020-02-28 15:26:52 -0800798 ret.update(controller_and_data_macros(entry, i, macro))
799
800 return ret
801
802
803def controller_and_data_macros(entry, i, macro):
804 # Helper procedure used by phandle_macros().
805 #
806 # Its purpose is to write the "controller" (i.e. label property of
807 # the phandle's node) and associated data macros for a
808 # ControllerAndData.
809
810 ret = {}
811 data = entry.data
812
Martí Bolívarffc03122020-11-12 20:27:20 -0800813 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
814 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800815 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_PH
816 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{entry.controller.z_path_id}"
817 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_VAL_<VAL>
818 for cell, val in data.items():
819 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}"] = val
820 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}_EXISTS"] = 1
821
822 if not entry.name:
823 return ret
824
825 name = str2ident(entry.name)
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200826 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
827 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800828 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_NAME
829 ret[f"{macro}_IDX_{i}_NAME"] = quote_str(entry.name)
830 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_PH
831 ret[f"{macro}_NAME_{name}_PH"] = f"DT_{entry.controller.z_path_id}"
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200832 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_EXISTS
833 ret[f"{macro}_NAME_{name}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800834 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL>
835 for cell, val in data.items():
836 cell_ident = str2ident(cell)
837 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \
838 f"DT_{macro}_IDX_{i}_VAL_{cell_ident}"
839 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1
840
841 return ret
842
843
844def write_chosen(edt):
845 # Tree-wide information such as chosen nodes is printed here.
846
847 out_comment("Chosen nodes\n")
848 chosen = {}
849 for name, node in edt.chosen_nodes.items():
850 chosen[f"DT_CHOSEN_{str2ident(name)}"] = f"DT_{node.z_path_id}"
851 chosen[f"DT_CHOSEN_{str2ident(name)}_EXISTS"] = 1
Kumar Gala299bfd02020-03-25 15:32:58 -0500852 max_len = max(map(len, chosen), default=0)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800853 for macro, value in chosen.items():
854 out_define(macro, value, width=max_len)
855
856
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700857def write_global_compat_info(edt):
858 # Tree-wide information related to each compatible, such as number
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700859 # of instances with status "okay", is printed here.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800860
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700861 n_okay_macros = {}
862 for_each_macros = {}
863 compat2buses = defaultdict(list) # just for "okay" nodes
864 for compat, okay_nodes in edt.compat2okay.items():
865 for node in okay_nodes:
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700866 bus = node.on_bus
867 if bus is not None and bus not in compat2buses[compat]:
868 compat2buses[compat].append(bus)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800869
Martí Bolívar63d55292020-04-06 15:13:53 -0700870 ident = str2ident(compat)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700871 n_okay_macros[f"DT_N_INST_{ident}_NUM_OKAY"] = len(okay_nodes)
Martí Bolívare7d42ff2021-08-05 15:24:50 -0700872
873 # Helpers for non-INST for-each macros that take node
874 # identifiers as arguments.
875 for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \
876 " ".join(f"fn(DT_{node.z_path_id})"
877 for node in okay_nodes)
878 for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \
879 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)"
880 for node in okay_nodes)
881
882 # Helpers for INST versions of for-each macros, which take
883 # instance numbers. We emit separate helpers for these because
884 # avoiding an intermediate node_id --> instance number
885 # conversion in the preprocessor helps to keep the macro
886 # expansions simpler. That hopefully eases debugging.
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700887 for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \
888 " ".join(f"fn({edt.compat2nodes[compat].index(node)})"
889 for node in okay_nodes)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400890 for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \
891 " ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)"
892 for node in okay_nodes)
893
Kumar Galabd973782020-05-06 20:54:29 -0500894 for compat, nodes in edt.compat2nodes.items():
895 for node in nodes:
896 if compat == "fixed-partitions":
897 for child in node.children.values():
898 if "label" in child.props:
899 label = child.props["label"].val
900 macro = f"COMPAT_{str2ident(compat)}_LABEL_{str2ident(label)}"
901 val = f"DT_{child.z_path_id}"
902
903 out_dt_define(macro, val)
904 out_dt_define(macro + "_EXISTS", 1)
905
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700906 out_comment('Macros for compatibles with status "okay" nodes\n')
907 for compat, okay_nodes in edt.compat2okay.items():
908 if okay_nodes:
909 out_define(f"DT_COMPAT_HAS_OKAY_{str2ident(compat)}", 1)
910
911 out_comment('Macros for status "okay" instances of each compatible\n')
912 for macro, value in n_okay_macros.items():
Martí Bolívar63d55292020-04-06 15:13:53 -0700913 out_define(macro, value)
914 for macro, value in for_each_macros.items():
915 out_define(macro, value)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800916
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700917 out_comment('Bus information for status "okay" nodes of each compatible\n')
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700918 for compat, buses in compat2buses.items():
919 for bus in buses:
920 out_define(
921 f"DT_COMPAT_{str2ident(compat)}_BUS_{str2ident(bus)}", 1)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800922
923def str2ident(s):
924 # Converts 's' to a form suitable for (part of) an identifier
925
926 return re.sub('[-,.@/+]', '_', s.lower())
927
928
929def list2init(l):
930 # Converts 'l', a Python list (or iterable), to a C array initializer
931
932 return "{" + ", ".join(l) + "}"
933
934
935def out_dt_define(macro, val, width=None, deprecation_msg=None):
936 # Writes "#define DT_<macro> <val>" to the header file
937 #
938 # The macro will be left-justified to 'width' characters if that
939 # is specified, and the value will follow immediately after in
940 # that case. Otherwise, this function decides how to add
941 # whitespace between 'macro' and 'val'.
942 #
943 # If a 'deprecation_msg' string is passed, the generated identifiers will
944 # generate a warning if used, via __WARN(<deprecation_msg>)).
945 #
946 # Returns the full generated macro for 'macro', with leading "DT_".
947 ret = "DT_" + macro
948 out_define(ret, val, width=width, deprecation_msg=deprecation_msg)
949 return ret
950
951
952def out_define(macro, val, width=None, deprecation_msg=None):
953 # Helper for out_dt_define(). Outputs "#define <macro> <val>",
954 # adds a deprecation message if given, and allocates whitespace
955 # unless told not to.
956
957 warn = fr' __WARN("{deprecation_msg}")' if deprecation_msg else ""
958
959 if width:
960 s = f"#define {macro.ljust(width)}{warn} {val}"
961 else:
962 s = f"#define {macro}{warn} {val}"
963
964 print(s, file=header_file)
965
966
967def out_comment(s, blank_before=True):
968 # Writes 's' as a comment to the header and configuration file. 's' is
969 # allowed to have multiple lines. blank_before=True adds a blank line
970 # before the comment.
971
972 if blank_before:
973 print(file=header_file)
974
975 if "\n" in s:
976 # Format multi-line comments like
977 #
978 # /*
979 # * first line
980 # * second line
981 # *
982 # * empty line before this line
983 # */
984 res = ["/*"]
985 for line in s.splitlines():
986 # Avoid an extra space after '*' for empty lines. They turn red in
987 # Vim if space error checking is on, which is annoying.
988 res.append(" *" if not line.strip() else " * " + line)
989 res.append(" */")
990 print("\n".join(res), file=header_file)
991 else:
992 # Format single-line comments like
993 #
994 # /* foo bar */
995 print("/* " + s + " */", file=header_file)
996
997
998def escape(s):
999 # Backslash-escapes any double quotes and backslashes in 's'
1000
1001 # \ must be escaped before " to avoid double escaping
1002 return s.replace("\\", "\\\\").replace('"', '\\"')
1003
1004
1005def quote_str(s):
1006 # Puts quotes around 's' and escapes any double quotes and
1007 # backslashes within it
1008
1009 return f'"{escape(s)}"'
1010
1011
Martí Bolívar533f4512020-07-01 10:43:43 -07001012def write_pickled_edt(edt, out_file):
1013 # Writes the edt object in pickle format to out_file.
1014
1015 with open(out_file, 'wb') as f:
1016 # Pickle protocol version 4 is the default as of Python 3.8
1017 # and was introduced in 3.4, so it is both available and
1018 # recommended on all versions of Python that Zephyr supports
1019 # (at time of writing, Python 3.6 was Zephyr's minimum
1020 # version, and 3.8 the most recent CPython release).
1021 #
1022 # Using a common protocol version here will hopefully avoid
1023 # reproducibility issues in different Python installations.
1024 pickle.dump(edt, f, protocol=4)
1025
1026
Martí Bolívardc85edd2020-02-28 15:26:52 -08001027def err(s):
1028 raise Exception(s)
1029
1030
1031if __name__ == "__main__":
1032 main()