blob: 88fcf1c531d260419e68f5b7c90e84cf760b5d17 [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
Gerard Marull-Paretasd77f4e62022-07-05 16:50:36 +0200105 write_utils()
106
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000107 # populate all z_path_id first so any children references will
108 # work correctly.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800109 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívar186bace2020-04-08 15:02:18 -0700110 node.z_path_id = node_z_path_id(node)
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000111
Jordan Yates9c98d4f2021-07-28 20:01:16 +1000112 # Check to see if we have duplicate "zephyr,memory-region" property values.
113 regions = dict()
114 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
115 if 'zephyr,memory-region' in node.props:
116 region = node.props['zephyr,memory-region'].val
117 if region in regions:
118 sys.exit(f"ERROR: Duplicate 'zephyr,memory-region' ({region}) properties "
119 f"between {regions[region].path} and {node.path}")
120 regions[region] = node
121
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000122 for node in sorted(edt.nodes, key=lambda node: node.dep_ordinal):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800123 write_node_comment(node)
124
Kumar Gala270a05f2021-02-24 11:28:21 -0600125 out_comment("Node's full path:")
Martí Bolívar00ffc7e2020-12-13 12:27:04 -0800126 out_dt_define(f"{node.z_path_id}_PATH", f'"{escape(node.path)}"')
127
Kumar Gala4aac9082021-02-24 10:44:07 -0600128 out_comment("Node's name with unit-address:")
129 out_dt_define(f"{node.z_path_id}_FULL_NAME",
130 f'"{escape(node.name)}"')
131
Martí Bolívar6e273432020-04-08 15:04:15 -0700132 if node.parent is not None:
133 out_comment(f"Node parent ({node.parent.path}) identifier:")
134 out_dt_define(f"{node.z_path_id}_PARENT",
135 f"DT_{node.parent.z_path_id}")
136
Martí Bolívar50f9b3c2022-03-23 13:41:09 -0700137 out_comment(f"Node's index in its parent's list of children:")
138 out_dt_define(f"{node.z_path_id}_CHILD_IDX",
139 node.parent.child_index(node))
140
Martí Bolívar355cc012022-03-23 13:26:24 -0700141 write_children(node)
Martí Bolívar305379e2020-06-08 14:59:19 -0700142 write_dep_info(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800143 write_idents_and_existence(node)
144 write_bus(node)
145 write_special_props(node)
146 write_vanilla_props(node)
147
148 write_chosen(edt)
Martí Bolívar190197e2022-07-20 13:10:33 -0700149 write_global_macros(edt)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800150
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
Martí Bolívar09858492020-12-08 09:41:49 -0800155def setup_edtlib_logging():
156 # The edtlib module emits logs using the standard 'logging' module.
157 # Configure it so that warnings and above are printed to stderr,
158 # using the LogFormatter class defined above to format each message.
159
160 handler = logging.StreamHandler(sys.stderr)
161 handler.setFormatter(LogFormatter())
162
163 logger = logging.getLogger('edtlib')
164 logger.setLevel(logging.WARNING)
165 logger.addHandler(handler)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800166
Martí Bolívar186bace2020-04-08 15:02:18 -0700167def node_z_path_id(node):
168 # Return the node specific bit of the node's path identifier:
169 #
170 # - the root node's path "/" has path identifier "N"
171 # - "/foo" has "N_S_foo"
172 # - "/foo/bar" has "N_S_foo_S_bar"
173 # - "/foo/bar@123" has "N_S_foo_S_bar_123"
174 #
175 # This is used throughout this file to generate macros related to
176 # the node.
177
178 components = ["N"]
179 if node.parent is not None:
180 components.extend(f"S_{str2ident(component)}" for component in
181 node.path.split("/")[1:])
182
183 return "_".join(components)
184
Martí Bolívardc85edd2020-02-28 15:26:52 -0800185def parse_args():
186 # Returns parsed command-line arguments
187
188 parser = argparse.ArgumentParser()
189 parser.add_argument("--dts", required=True, help="DTS file")
190 parser.add_argument("--dtc-flags",
191 help="'dtc' devicetree compiler flags, some of which "
192 "might be respected here")
193 parser.add_argument("--bindings-dirs", nargs='+', required=True,
194 help="directory with bindings in YAML format, "
195 "we allow multiple")
196 parser.add_argument("--header-out", required=True,
197 help="path to write header to")
198 parser.add_argument("--dts-out", required=True,
199 help="path to write merged DTS source code to (e.g. "
200 "as a debugging aid)")
Martí Bolívar533f4512020-07-01 10:43:43 -0700201 parser.add_argument("--edt-pickle-out",
202 help="path to write pickled edtlib.EDT object to")
Martí Bolívar85837e12021-08-19 11:09:05 -0700203 parser.add_argument("--vendor-prefixes", action='append', default=[],
204 help="vendor-prefixes.txt path; used for validation; "
205 "may be given multiple times")
Martí Bolívarc4079e42021-07-30 15:43:27 -0700206 parser.add_argument("--edtlib-Werror", action="store_true",
207 help="if set, edtlib-specific warnings become errors. "
208 "(this does not apply to warnings shared "
209 "with dtc.)")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800210
211 return parser.parse_args()
212
213
214def write_top_comment(edt):
215 # Writes an overview comment with misc. info at the top of the header and
216 # configuration file
217
218 s = f"""\
219Generated by gen_defines.py
220
221DTS input file:
222 {edt.dts_path}
223
224Directories with bindings:
225 {", ".join(map(relativize, edt.bindings_dirs))}
226
Martí Bolívar305379e2020-06-08 14:59:19 -0700227Node dependency ordering (ordinal and path):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800228"""
229
Martí Bolívarb6db2012020-08-24 13:33:53 -0700230 for scc in edt.scc_order:
Martí Bolívardc85edd2020-02-28 15:26:52 -0800231 if len(scc) > 1:
232 err("cycle in devicetree involving "
233 + ", ".join(node.path for node in scc))
234 s += f" {scc[0].dep_ordinal:<3} {scc[0].path}\n"
235
236 s += """
237Definitions derived from these nodes in dependency order are next,
238followed by /chosen nodes.
239"""
240
241 out_comment(s, blank_before=False)
242
243
Gerard Marull-Paretasd77f4e62022-07-05 16:50:36 +0200244def write_utils():
245 # Writes utility macros
246
247 out_comment("Used to remove brackets from around a single argument")
248 out_define("DT_DEBRACKET_INTERNAL(...)", "__VA_ARGS__")
249
250
Martí Bolívardc85edd2020-02-28 15:26:52 -0800251def write_node_comment(node):
252 # Writes a comment describing 'node' to the header and configuration file
253
254 s = f"""\
Martí Bolívarb6e6ba02020-04-08 15:09:46 -0700255Devicetree node: {node.path}
256
Martí Bolívar305379e2020-06-08 14:59:19 -0700257Node identifier: DT_{node.z_path_id}
Martí Bolívardc85edd2020-02-28 15:26:52 -0800258"""
259
260 if node.matching_compat:
Peter Bigot932532e2020-09-02 05:05:19 -0500261 if node.binding_path:
262 s += f"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800263Binding (compatible = {node.matching_compat}):
264 {relativize(node.binding_path)}
265"""
Peter Bigot932532e2020-09-02 05:05:19 -0500266 else:
267 s += f"""
268Binding (compatible = {node.matching_compat}):
269 No yaml (bindings inferred from properties)
270"""
Martí Bolívardc85edd2020-02-28 15:26:52 -0800271
Martí Bolívardc85edd2020-02-28 15:26:52 -0800272 if node.description:
Martí Bolívarf7d33f22020-10-30 17:45:27 -0700273 # We used to put descriptions in the generated file, but
274 # devicetree bindings now have pages in the HTML
275 # documentation. Let users who are accustomed to digging
276 # around in the generated file where to find the descriptions
277 # now.
278 #
279 # Keeping them here would mean that the descriptions
280 # themselves couldn't contain C multi-line comments, which is
281 # inconvenient when we want to do things like quote snippets
282 # of .dtsi files within the descriptions, or otherwise
283 # include the string "*/".
284 s += ("\n(Descriptions have moved to the Devicetree Bindings Index\n"
285 "in the documentation.)\n")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800286
287 out_comment(s)
288
289
290def relativize(path):
291 # If 'path' is within $ZEPHYR_BASE, returns it relative to $ZEPHYR_BASE,
292 # with a "$ZEPHYR_BASE/..." hint at the start of the string. Otherwise,
293 # returns 'path' unchanged.
294
295 zbase = os.getenv("ZEPHYR_BASE")
296 if zbase is None:
297 return path
298
299 try:
300 return str("$ZEPHYR_BASE" / pathlib.Path(path).relative_to(zbase))
301 except ValueError:
302 # Not within ZEPHYR_BASE
303 return path
304
305
306def write_idents_and_existence(node):
307 # Writes macros related to the node's aliases, labels, etc.,
308 # as well as existence flags.
309
310 # Aliases
311 idents = [f"N_ALIAS_{str2ident(alias)}" for alias in node.aliases]
312 # Instances
313 for compat in node.compats:
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700314 instance_no = node.edt.compat2nodes[compat].index(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800315 idents.append(f"N_INST_{instance_no}_{str2ident(compat)}")
316 # Node labels
317 idents.extend(f"N_NODELABEL_{str2ident(label)}" for label in node.labels)
318
319 out_comment("Existence and alternate IDs:")
320 out_dt_define(node.z_path_id + "_EXISTS", 1)
321
322 # Only determine maxlen if we have any idents
323 if idents:
324 maxlen = max(len("DT_" + ident) for ident in idents)
325 for ident in idents:
326 out_dt_define(ident, "DT_" + node.z_path_id, width=maxlen)
327
328
329def write_bus(node):
330 # Macros about the node's bus controller, if there is one
331
332 bus = node.bus_node
333 if not bus:
334 return
335
Martí Bolívardc85edd2020-02-28 15:26:52 -0800336 out_comment(f"Bus info (controller: '{bus.path}', type: '{node.on_bus}')")
337 out_dt_define(f"{node.z_path_id}_BUS_{str2ident(node.on_bus)}", 1)
338 out_dt_define(f"{node.z_path_id}_BUS", f"DT_{bus.z_path_id}")
339
340
341def write_special_props(node):
342 # Writes required macros for special case properties, when the
343 # data cannot otherwise be obtained from write_vanilla_props()
344 # results
345
Martí Bolívardc85edd2020-02-28 15:26:52 -0800346 # Macros that are special to the devicetree specification
Martí Bolívar7f69a032021-08-11 15:14:51 -0700347 out_comment("Macros for properties that are special in the specification:")
Martí Bolívardc85edd2020-02-28 15:26:52 -0800348 write_regs(node)
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200349 write_ranges(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800350 write_interrupts(node)
351 write_compatibles(node)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700352 write_status(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800353
Martí Bolívar7f69a032021-08-11 15:14:51 -0700354 # Macros that are special to bindings inherited from Linux, which
355 # we can't capture with the current bindings language.
Martí Bolívar9df04932021-08-11 15:43:24 -0700356 write_pinctrls(node)
Martí Bolívar7f69a032021-08-11 15:14:51 -0700357 write_fixed_partitions(node)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800358
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200359def write_ranges(node):
360 # ranges property: edtlib knows the right #address-cells and
361 # #size-cells of parent and child, and can therefore pack the
362 # child & parent addresses and sizes correctly
363
364 idx_vals = []
365 path_id = node.z_path_id
366
367 if node.ranges is not None:
368 idx_vals.append((f"{path_id}_RANGES_NUM", len(node.ranges)))
369
370 for i,range in enumerate(node.ranges):
371 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_EXISTS", 1))
372
373 if node.bus == "pcie":
374 idx_vals.append((f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS_EXISTS", 1))
375 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_FLAGS"
376 idx_value = range.child_bus_addr >> ((range.child_bus_cells - 1) * 32)
377 idx_vals.append((idx_macro,
378 f"{idx_value} /* {hex(idx_value)} */"))
379 if range.child_bus_addr is not None:
380 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_CHILD_BUS_ADDRESS"
381 if node.bus == "pcie":
382 idx_value = range.child_bus_addr & ((1 << (range.child_bus_cells - 1) * 32) - 1)
383 else:
384 idx_value = range.child_bus_addr
385 idx_vals.append((idx_macro,
386 f"{idx_value} /* {hex(idx_value)} */"))
387 if range.parent_bus_addr is not None:
388 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_PARENT_BUS_ADDRESS"
389 idx_vals.append((idx_macro,
390 f"{range.parent_bus_addr} /* {hex(range.parent_bus_addr)} */"))
391 if range.length is not None:
392 idx_macro = f"{path_id}_RANGES_IDX_{i}_VAL_LENGTH"
393 idx_vals.append((idx_macro,
394 f"{range.length} /* {hex(range.length)} */"))
395
396 for macro, val in idx_vals:
397 out_dt_define(macro, val)
398
399 out_dt_define(f"{path_id}_FOREACH_RANGE(fn)",
400 " ".join(f"fn(DT_{path_id}, {i})" for i,range in enumerate(node.ranges)))
401
Martí Bolívardc85edd2020-02-28 15:26:52 -0800402def write_regs(node):
403 # reg property: edtlib knows the right #address-cells and
404 # #size-cells, and can therefore pack the register base addresses
405 # and sizes correctly
406
407 idx_vals = []
408 name_vals = []
409 path_id = node.z_path_id
410
411 if node.regs is not None:
412 idx_vals.append((f"{path_id}_REG_NUM", len(node.regs)))
413
414 for i, reg in enumerate(node.regs):
Kumar Gala4e2ad002020-04-14 14:27:20 -0500415 idx_vals.append((f"{path_id}_REG_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800416 if reg.addr is not None:
417 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_ADDRESS"
418 idx_vals.append((idx_macro,
419 f"{reg.addr} /* {hex(reg.addr)} */"))
420 if reg.name:
421 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_ADDRESS"
422 name_vals.append((name_macro, f"DT_{idx_macro}"))
423
424 if reg.size is not None:
425 idx_macro = f"{path_id}_REG_IDX_{i}_VAL_SIZE"
426 idx_vals.append((idx_macro,
427 f"{reg.size} /* {hex(reg.size)} */"))
428 if reg.name:
429 name_macro = f"{path_id}_REG_NAME_{reg.name}_VAL_SIZE"
430 name_vals.append((name_macro, f"DT_{idx_macro}"))
431
432 for macro, val in idx_vals:
433 out_dt_define(macro, val)
434 for macro, val in name_vals:
435 out_dt_define(macro, val)
436
437def write_interrupts(node):
438 # interrupts property: we have some hard-coded logic for interrupt
439 # mapping here.
440 #
441 # TODO: can we push map_arm_gic_irq_type() and
442 # encode_zephyr_multi_level_irq() out of Python and into C with
443 # macro magic in devicetree.h?
444
445 def map_arm_gic_irq_type(irq, irq_num):
446 # Maps ARM GIC IRQ (type)+(index) combo to linear IRQ number
447 if "type" not in irq.data:
448 err(f"Expected binding for {irq.controller!r} to have 'type' in "
449 "interrupt-cells")
450 irq_type = irq.data["type"]
451
452 if irq_type == 0: # GIC_SPI
453 return irq_num + 32
454 if irq_type == 1: # GIC_PPI
455 return irq_num + 16
456 err(f"Invalid interrupt type specified for {irq!r}")
457
458 def encode_zephyr_multi_level_irq(irq, irq_num):
459 # See doc/reference/kernel/other/interrupts.rst for details
460 # on how this encoding works
461
462 irq_ctrl = irq.controller
463 # Look for interrupt controller parent until we have none
464 while irq_ctrl.interrupts:
465 irq_num = (irq_num + 1) << 8
466 if "irq" not in irq_ctrl.interrupts[0].data:
467 err(f"Expected binding for {irq_ctrl!r} to have 'irq' in "
468 "interrupt-cells")
469 irq_num |= irq_ctrl.interrupts[0].data["irq"]
470 irq_ctrl = irq_ctrl.interrupts[0].controller
471 return irq_num
472
473 idx_vals = []
474 name_vals = []
475 path_id = node.z_path_id
476
477 if node.interrupts is not None:
478 idx_vals.append((f"{path_id}_IRQ_NUM", len(node.interrupts)))
479
480 for i, irq in enumerate(node.interrupts):
481 for cell_name, cell_value in irq.data.items():
482 name = str2ident(cell_name)
483
484 if cell_name == "irq":
485 if "arm,gic" in irq.controller.compats:
486 cell_value = map_arm_gic_irq_type(irq, cell_value)
487 cell_value = encode_zephyr_multi_level_irq(irq, cell_value)
488
Kumar Gala4e2ad002020-04-14 14:27:20 -0500489 idx_vals.append((f"{path_id}_IRQ_IDX_{i}_EXISTS", 1))
Martí Bolívardc85edd2020-02-28 15:26:52 -0800490 idx_macro = f"{path_id}_IRQ_IDX_{i}_VAL_{name}"
491 idx_vals.append((idx_macro, cell_value))
492 idx_vals.append((idx_macro + "_EXISTS", 1))
493 if irq.name:
494 name_macro = \
495 f"{path_id}_IRQ_NAME_{str2ident(irq.name)}_VAL_{name}"
496 name_vals.append((name_macro, f"DT_{idx_macro}"))
497 name_vals.append((name_macro + "_EXISTS", 1))
498
499 for macro, val in idx_vals:
500 out_dt_define(macro, val)
501 for macro, val in name_vals:
502 out_dt_define(macro, val)
503
504
505def write_compatibles(node):
506 # Writes a macro for each of the node's compatibles. We don't care
507 # about whether edtlib / Zephyr's binding language recognizes
508 # them. The compatibles the node provides are what is important.
509
510 for compat in node.compats:
511 out_dt_define(
512 f"{node.z_path_id}_COMPAT_MATCHES_{str2ident(compat)}", 1)
513
514
Martí Bolívar355cc012022-03-23 13:26:24 -0700515def write_children(node):
516 # Writes helper macros for dealing with node's children.
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000517
Martí Bolívar7b2a7282022-07-08 11:04:46 -0700518 out_comment("Helper macros for child nodes of this node.")
519
Kumar Gala4a5a90a2020-05-08 12:25:25 -0500520 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD(fn)",
521 " ".join(f"fn(DT_{child.z_path_id})" for child in
522 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000523
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400524 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_VARGS(fn, ...)",
525 " ".join(f"fn(DT_{child.z_path_id}, __VA_ARGS__)" for child in
526 node.children.values()))
Dominik Ermelba8b74d2020-04-17 06:32:28 +0000527
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800528 functions = ''
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400529 functions_args = ''
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800530 for child in node.children.values():
531 if child.status == "okay":
532 functions = functions + f"fn(DT_{child.z_path_id}) "
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400533 functions_args = functions_args + f"fn(DT_{child.z_path_id}, " \
534 "__VA_ARGS__) "
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800535
536 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY(fn)", functions)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400537 out_dt_define(f"{node.z_path_id}_FOREACH_CHILD_STATUS_OKAY_VARGS(fn, ...)",
538 functions_args)
Hou Zhiqiang0700a242021-04-26 16:22:38 +0800539
540
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700541def write_status(node):
542 out_dt_define(f"{node.z_path_id}_STATUS_{str2ident(node.status)}", 1)
543
544
Martí Bolívar9df04932021-08-11 15:43:24 -0700545def write_pinctrls(node):
546 # Write special macros for pinctrl-<index> and pinctrl-names properties.
547
548 out_comment("Pin control (pinctrl-<i>, pinctrl-names) properties:")
549
550 out_dt_define(f"{node.z_path_id}_PINCTRL_NUM", len(node.pinctrls))
551
552 if not node.pinctrls:
553 return
554
555 for pc_idx, pinctrl in enumerate(node.pinctrls):
556 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_EXISTS", 1)
557
558 if not pinctrl.name:
559 continue
560
561 name = pinctrl.name_as_token
562
563 # Below we rely on the fact that edtlib ensures the
564 # pinctrl-<pc_idx> properties are contiguous, start from 0,
565 # and contain only phandles.
566 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_TOKEN", name)
567 out_dt_define(f"{node.z_path_id}_PINCTRL_IDX_{pc_idx}_UPPER_TOKEN", name.upper())
568 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_EXISTS", 1)
569 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX", pc_idx)
570 for idx, ph in enumerate(pinctrl.conf_nodes):
571 out_dt_define(f"{node.z_path_id}_PINCTRL_NAME_{name}_IDX_{idx}_PH",
572 f"DT_{ph.z_path_id}")
573
574
Martí Bolívar7f69a032021-08-11 15:14:51 -0700575def write_fixed_partitions(node):
576 # Macros for child nodes of each fixed-partitions node.
577
578 if not (node.parent and "fixed-partitions" in node.parent.compats):
579 return
580
581 global flash_area_num
582 out_comment("fixed-partitions identifier:")
583 out_dt_define(f"{node.z_path_id}_PARTITION_ID", flash_area_num)
584 flash_area_num += 1
585
586
Martí Bolívardc85edd2020-02-28 15:26:52 -0800587def write_vanilla_props(node):
588 # Writes macros for any and all properties defined in the
589 # "properties" section of the binding for the node.
590 #
591 # This does generate macros for special properties as well, like
592 # regs, etc. Just let that be rather than bothering to add
593 # never-ending amounts of special case code here to skip special
594 # properties. This function's macros can't conflict with
595 # write_special_props() macros, because they're in different
596 # namespaces. Special cases aren't special enough to break the rules.
597
598 macro2val = {}
599 for prop_name, prop in node.props.items():
Martí Bolívar9c229a42021-04-14 15:26:42 -0700600 prop_id = str2ident(prop_name)
601 macro = f"{node.z_path_id}_P_{prop_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800602 val = prop2value(prop)
603 if val is not None:
604 # DT_N_<node-id>_P_<prop-id>
605 macro2val[macro] = val
606
Carlo Caionef4db14f2021-05-17 17:24:27 +0200607 if prop.spec.type == 'string':
608 macro2val[macro + "_STRING_TOKEN"] = prop.val_as_token
609 macro2val[macro + "_STRING_UPPER_TOKEN"] = prop.val_as_token.upper()
610
Martí Bolívardc85edd2020-02-28 15:26:52 -0800611 if prop.enum_index is not None:
612 # DT_N_<node-id>_P_<prop-id>_ENUM_IDX
613 macro2val[macro + "_ENUM_IDX"] = prop.enum_index
Peter Bigot345da782020-12-02 09:04:27 -0600614 spec = prop.spec
615
616 if spec.enum_tokenizable:
617 as_token = prop.val_as_token
618
619 # DT_N_<node-id>_P_<prop-id>_ENUM_TOKEN
620 macro2val[macro + "_ENUM_TOKEN"] = as_token
621
622 if spec.enum_upper_tokenizable:
623 # DT_N_<node-id>_P_<prop-id>_ENUM_UPPER_TOKEN
624 macro2val[macro + "_ENUM_UPPER_TOKEN"] = as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800625
626 if "phandle" in prop.type:
627 macro2val.update(phandle_macros(prop, macro))
628 elif "array" in prop.type:
629 # DT_N_<node-id>_P_<prop-id>_IDX_<i>
Martí Bolívarffc03122020-11-12 20:27:20 -0800630 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
Martí Bolívardc85edd2020-02-28 15:26:52 -0800631 for i, subval in enumerate(prop.val):
632 if isinstance(subval, str):
633 macro2val[macro + f"_IDX_{i}"] = quote_str(subval)
Martí Bolívard6f68f02022-07-08 11:21:34 -0700634 subval_as_token = edtlib.str_as_token(subval)
Radosław Koppel76141102022-05-07 20:27:49 +0200635 macro2val[macro + f"_IDX_{i}_STRING_TOKEN"] = subval_as_token
636 macro2val[macro + f"_IDX_{i}_STRING_UPPER_TOKEN"] = subval_as_token.upper()
Martí Bolívardc85edd2020-02-28 15:26:52 -0800637 else:
638 macro2val[macro + f"_IDX_{i}"] = subval
Martí Bolívarffc03122020-11-12 20:27:20 -0800639 macro2val[macro + f"_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800640
Martí Bolívar9c229a42021-04-14 15:26:42 -0700641 if prop.type in FOREACH_PROP_ELEM_TYPES:
642 # DT_N_<node-id>_P_<prop-id>_FOREACH_PROP_ELEM
643 macro2val[f"{macro}_FOREACH_PROP_ELEM(fn)"] = \
644 ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i})'
645 for i in range(len(prop.val)))
646
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400647 macro2val[f"{macro}_FOREACH_PROP_ELEM_VARGS(fn, ...)"] = \
648 ' \\\n\t'.join(f'fn(DT_{node.z_path_id}, {prop_id}, {i},'
649 ' __VA_ARGS__)'
650 for i in range(len(prop.val)))
651
Martí Bolívardc85edd2020-02-28 15:26:52 -0800652 plen = prop_len(prop)
653 if plen is not None:
654 # DT_N_<node-id>_P_<prop-id>_LEN
655 macro2val[macro + "_LEN"] = plen
656
657 macro2val[f"{macro}_EXISTS"] = 1
658
659 if macro2val:
660 out_comment("Generic property macros:")
661 for macro, val in macro2val.items():
662 out_dt_define(macro, val)
663 else:
664 out_comment("(No generic property macros)")
665
666
Martí Bolívar305379e2020-06-08 14:59:19 -0700667def write_dep_info(node):
668 # Write dependency-related information about the node.
669
670 def fmt_dep_list(dep_list):
671 if dep_list:
672 # Sort the list by dependency ordinal for predictability.
673 sorted_list = sorted(dep_list, key=lambda node: node.dep_ordinal)
674 return "\\\n\t" + \
675 " \\\n\t".join(f"{n.dep_ordinal}, /* {n.path} */"
676 for n in sorted_list)
677 else:
678 return "/* nothing */"
679
680 out_comment("Node's dependency ordinal:")
681 out_dt_define(f"{node.z_path_id}_ORD", node.dep_ordinal)
682
683 out_comment("Ordinals for what this node depends on directly:")
684 out_dt_define(f"{node.z_path_id}_REQUIRES_ORDS",
685 fmt_dep_list(node.depends_on))
686
687 out_comment("Ordinals for what depends directly on this node:")
688 out_dt_define(f"{node.z_path_id}_SUPPORTS_ORDS",
689 fmt_dep_list(node.required_by))
690
691
Martí Bolívardc85edd2020-02-28 15:26:52 -0800692def prop2value(prop):
693 # Gets the macro value for property 'prop', if there is
694 # a single well-defined C rvalue that it can be represented as.
695 # Returns None if there isn't one.
696
697 if prop.type == "string":
698 return quote_str(prop.val)
699
700 if prop.type == "int":
701 return prop.val
702
703 if prop.type == "boolean":
704 return 1 if prop.val else 0
705
706 if prop.type in ["array", "uint8-array"]:
707 return list2init(f"{val} /* {hex(val)} */" for val in prop.val)
708
709 if prop.type == "string-array":
710 return list2init(quote_str(val) for val in prop.val)
711
712 # phandle, phandles, phandle-array, path, compound: nothing
713 return None
714
715
716def prop_len(prop):
717 # Returns the property's length if and only if we should generate
718 # a _LEN macro for the property. Otherwise, returns None.
719 #
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200720 # This deliberately excludes ranges, dma-ranges, reg and interrupts.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800721 # While they have array type, their lengths as arrays are
722 # basically nonsense semantically due to #address-cells and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200723 # #size-cells for "reg", #interrupt-cells for "interrupts"
724 # and #address-cells, #size-cells and the #address-cells from the
725 # parent node for "ranges" and "dma-ranges".
Martí Bolívardc85edd2020-02-28 15:26:52 -0800726 #
727 # We have special purpose macros for the number of register blocks
728 # / interrupt specifiers. Excluding them from this list means
729 # DT_PROP_LEN(node_id, ...) fails fast at the devicetree.h layer
730 # with a build error. This forces users to switch to the right
731 # macros.
732
733 if prop.type == "phandle":
734 return 1
735
736 if (prop.type in ["array", "uint8-array", "string-array",
737 "phandles", "phandle-array"] and
Neil Armstrong1e8f0f32021-06-24 10:14:05 +0200738 prop.name not in ["ranges", "dma-ranges", "reg", "interrupts"]):
Martí Bolívardc85edd2020-02-28 15:26:52 -0800739 return len(prop.val)
740
741 return None
742
743
744def phandle_macros(prop, macro):
745 # Returns a dict of macros for phandle or phandles property 'prop'.
746 #
747 # The 'macro' argument is the N_<node-id>_P_<prop-id> bit.
748 #
749 # These are currently special because we can't serialize their
750 # values without using label properties, which we're trying to get
751 # away from needing in Zephyr. (Label properties are great for
752 # humans, but have drawbacks for code size and boot time.)
753 #
754 # The names look a bit weird to make it easier for devicetree.h
755 # to use the same macros for phandle, phandles, and phandle-array.
756
757 ret = {}
758
759 if prop.type == "phandle":
760 # A phandle is treated as a phandles with fixed length 1.
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500761 ret[f"{macro}"] = f"DT_{prop.val.z_path_id}"
762 ret[f"{macro}_IDX_0"] = f"DT_{prop.val.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800763 ret[f"{macro}_IDX_0_PH"] = f"DT_{prop.val.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800764 ret[f"{macro}_IDX_0_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800765 elif prop.type == "phandles":
766 for i, node in enumerate(prop.val):
Kumar Gala7b9fbcd2021-08-12 14:57:49 -0500767 ret[f"{macro}_IDX_{i}"] = f"DT_{node.z_path_id}"
Martí Bolívardc85edd2020-02-28 15:26:52 -0800768 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{node.z_path_id}"
Martí Bolívarffc03122020-11-12 20:27:20 -0800769 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800770 elif prop.type == "phandle-array":
771 for i, entry in enumerate(prop.val):
Martí Bolívar38ede5a2020-12-17 14:12:01 -0800772 if entry is None:
773 # Unspecified element. The phandle-array at this index
774 # does not point at a ControllerAndData value, but
775 # subsequent indices in the array may.
776 ret[f"{macro}_IDX_{i}_EXISTS"] = 0
777 continue
778
Martí Bolívardc85edd2020-02-28 15:26:52 -0800779 ret.update(controller_and_data_macros(entry, i, macro))
780
781 return ret
782
783
784def controller_and_data_macros(entry, i, macro):
785 # Helper procedure used by phandle_macros().
786 #
787 # Its purpose is to write the "controller" (i.e. label property of
788 # the phandle's node) and associated data macros for a
789 # ControllerAndData.
790
791 ret = {}
792 data = entry.data
793
Martí Bolívarffc03122020-11-12 20:27:20 -0800794 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
795 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800796 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_PH
797 ret[f"{macro}_IDX_{i}_PH"] = f"DT_{entry.controller.z_path_id}"
798 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_VAL_<VAL>
799 for cell, val in data.items():
800 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}"] = val
801 ret[f"{macro}_IDX_{i}_VAL_{str2ident(cell)}_EXISTS"] = 1
802
803 if not entry.name:
804 return ret
805
806 name = str2ident(entry.name)
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200807 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_EXISTS
808 ret[f"{macro}_IDX_{i}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800809 # DT_N_<node-id>_P_<prop-id>_IDX_<i>_NAME
810 ret[f"{macro}_IDX_{i}_NAME"] = quote_str(entry.name)
811 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_PH
812 ret[f"{macro}_NAME_{name}_PH"] = f"DT_{entry.controller.z_path_id}"
Erwan Gouriou6c8617a2020-04-06 14:56:11 +0200813 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_EXISTS
814 ret[f"{macro}_NAME_{name}_EXISTS"] = 1
Martí Bolívardc85edd2020-02-28 15:26:52 -0800815 # DT_N_<node-id>_P_<prop-id>_NAME_<NAME>_VAL_<VAL>
816 for cell, val in data.items():
817 cell_ident = str2ident(cell)
818 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}"] = \
819 f"DT_{macro}_IDX_{i}_VAL_{cell_ident}"
820 ret[f"{macro}_NAME_{name}_VAL_{cell_ident}_EXISTS"] = 1
821
822 return ret
823
824
825def write_chosen(edt):
826 # Tree-wide information such as chosen nodes is printed here.
827
828 out_comment("Chosen nodes\n")
829 chosen = {}
830 for name, node in edt.chosen_nodes.items():
831 chosen[f"DT_CHOSEN_{str2ident(name)}"] = f"DT_{node.z_path_id}"
832 chosen[f"DT_CHOSEN_{str2ident(name)}_EXISTS"] = 1
Kumar Gala299bfd02020-03-25 15:32:58 -0500833 max_len = max(map(len, chosen), default=0)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800834 for macro, value in chosen.items():
835 out_define(macro, value, width=max_len)
836
837
Martí Bolívar190197e2022-07-20 13:10:33 -0700838def write_global_macros(edt):
839 # Global or tree-wide information, such as number of instances
840 # with status "okay" for each compatible, is printed here.
Martí Bolívardc85edd2020-02-28 15:26:52 -0800841
Martí Bolívarf0d11f72022-07-20 13:15:56 -0700842
843 out_comment("Macros for iterating over all nodes and enabled nodes")
844 out_dt_define("FOREACH_HELPER(fn)",
845 " ".join(f"fn(DT_{node.z_path_id})" for node in edt.nodes))
846 out_dt_define("FOREACH_OKAY_HELPER(fn)",
847 " ".join(f"fn(DT_{node.z_path_id})" for node in edt.nodes
848 if node.status == "okay"))
849
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700850 n_okay_macros = {}
851 for_each_macros = {}
852 compat2buses = defaultdict(list) # just for "okay" nodes
853 for compat, okay_nodes in edt.compat2okay.items():
854 for node in okay_nodes:
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700855 bus = node.on_bus
856 if bus is not None and bus not in compat2buses[compat]:
857 compat2buses[compat].append(bus)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800858
Martí Bolívar63d55292020-04-06 15:13:53 -0700859 ident = str2ident(compat)
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700860 n_okay_macros[f"DT_N_INST_{ident}_NUM_OKAY"] = len(okay_nodes)
Martí Bolívare7d42ff2021-08-05 15:24:50 -0700861
862 # Helpers for non-INST for-each macros that take node
863 # identifiers as arguments.
864 for_each_macros[f"DT_FOREACH_OKAY_{ident}(fn)"] = \
865 " ".join(f"fn(DT_{node.z_path_id})"
866 for node in okay_nodes)
867 for_each_macros[f"DT_FOREACH_OKAY_VARGS_{ident}(fn, ...)"] = \
868 " ".join(f"fn(DT_{node.z_path_id}, __VA_ARGS__)"
869 for node in okay_nodes)
870
871 # Helpers for INST versions of for-each macros, which take
872 # instance numbers. We emit separate helpers for these because
873 # avoiding an intermediate node_id --> instance number
874 # conversion in the preprocessor helps to keep the macro
875 # expansions simpler. That hopefully eases debugging.
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700876 for_each_macros[f"DT_FOREACH_OKAY_INST_{ident}(fn)"] = \
877 " ".join(f"fn({edt.compat2nodes[compat].index(node)})"
878 for node in okay_nodes)
Arvin Farahmandd0b9c032021-05-06 11:19:29 -0400879 for_each_macros[f"DT_FOREACH_OKAY_INST_VARGS_{ident}(fn, ...)"] = \
880 " ".join(f"fn({edt.compat2nodes[compat].index(node)}, __VA_ARGS__)"
881 for node in okay_nodes)
882
Kumar Galabd973782020-05-06 20:54:29 -0500883 for compat, nodes in edt.compat2nodes.items():
884 for node in nodes:
885 if compat == "fixed-partitions":
886 for child in node.children.values():
887 if "label" in child.props:
888 label = child.props["label"].val
889 macro = f"COMPAT_{str2ident(compat)}_LABEL_{str2ident(label)}"
890 val = f"DT_{child.z_path_id}"
891
892 out_dt_define(macro, val)
893 out_dt_define(macro + "_EXISTS", 1)
894
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700895 out_comment('Macros for compatibles with status "okay" nodes\n')
896 for compat, okay_nodes in edt.compat2okay.items():
897 if okay_nodes:
898 out_define(f"DT_COMPAT_HAS_OKAY_{str2ident(compat)}", 1)
899
900 out_comment('Macros for status "okay" instances of each compatible\n')
901 for macro, value in n_okay_macros.items():
Martí Bolívar63d55292020-04-06 15:13:53 -0700902 out_define(macro, value)
903 for macro, value in for_each_macros.items():
904 out_define(macro, value)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800905
Martí Bolívar7e0eed92020-05-06 11:23:07 -0700906 out_comment('Bus information for status "okay" nodes of each compatible\n')
Martí Bolívara3fae2f2020-03-25 14:18:27 -0700907 for compat, buses in compat2buses.items():
908 for bus in buses:
909 out_define(
910 f"DT_COMPAT_{str2ident(compat)}_BUS_{str2ident(bus)}", 1)
Martí Bolívardc85edd2020-02-28 15:26:52 -0800911
912def str2ident(s):
913 # Converts 's' to a form suitable for (part of) an identifier
914
915 return re.sub('[-,.@/+]', '_', s.lower())
916
917
918def list2init(l):
919 # Converts 'l', a Python list (or iterable), to a C array initializer
920
921 return "{" + ", ".join(l) + "}"
922
923
924def out_dt_define(macro, val, width=None, deprecation_msg=None):
925 # Writes "#define DT_<macro> <val>" to the header file
926 #
927 # The macro will be left-justified to 'width' characters if that
928 # is specified, and the value will follow immediately after in
929 # that case. Otherwise, this function decides how to add
930 # whitespace between 'macro' and 'val'.
931 #
932 # If a 'deprecation_msg' string is passed, the generated identifiers will
933 # generate a warning if used, via __WARN(<deprecation_msg>)).
934 #
935 # Returns the full generated macro for 'macro', with leading "DT_".
936 ret = "DT_" + macro
937 out_define(ret, val, width=width, deprecation_msg=deprecation_msg)
938 return ret
939
940
941def out_define(macro, val, width=None, deprecation_msg=None):
942 # Helper for out_dt_define(). Outputs "#define <macro> <val>",
943 # adds a deprecation message if given, and allocates whitespace
944 # unless told not to.
945
946 warn = fr' __WARN("{deprecation_msg}")' if deprecation_msg else ""
947
948 if width:
949 s = f"#define {macro.ljust(width)}{warn} {val}"
950 else:
951 s = f"#define {macro}{warn} {val}"
952
953 print(s, file=header_file)
954
955
956def out_comment(s, blank_before=True):
957 # Writes 's' as a comment to the header and configuration file. 's' is
958 # allowed to have multiple lines. blank_before=True adds a blank line
959 # before the comment.
960
961 if blank_before:
962 print(file=header_file)
963
964 if "\n" in s:
965 # Format multi-line comments like
966 #
967 # /*
968 # * first line
969 # * second line
970 # *
971 # * empty line before this line
972 # */
973 res = ["/*"]
974 for line in s.splitlines():
975 # Avoid an extra space after '*' for empty lines. They turn red in
976 # Vim if space error checking is on, which is annoying.
977 res.append(" *" if not line.strip() else " * " + line)
978 res.append(" */")
979 print("\n".join(res), file=header_file)
980 else:
981 # Format single-line comments like
982 #
983 # /* foo bar */
984 print("/* " + s + " */", file=header_file)
985
986
987def escape(s):
988 # Backslash-escapes any double quotes and backslashes in 's'
989
990 # \ must be escaped before " to avoid double escaping
991 return s.replace("\\", "\\\\").replace('"', '\\"')
992
993
994def quote_str(s):
995 # Puts quotes around 's' and escapes any double quotes and
996 # backslashes within it
997
998 return f'"{escape(s)}"'
999
1000
Martí Bolívar533f4512020-07-01 10:43:43 -07001001def write_pickled_edt(edt, out_file):
1002 # Writes the edt object in pickle format to out_file.
1003
1004 with open(out_file, 'wb') as f:
1005 # Pickle protocol version 4 is the default as of Python 3.8
1006 # and was introduced in 3.4, so it is both available and
1007 # recommended on all versions of Python that Zephyr supports
1008 # (at time of writing, Python 3.6 was Zephyr's minimum
1009 # version, and 3.8 the most recent CPython release).
1010 #
1011 # Using a common protocol version here will hopefully avoid
1012 # reproducibility issues in different Python installations.
1013 pickle.dump(edt, f, protocol=4)
1014
1015
Martí Bolívardc85edd2020-02-28 15:26:52 -08001016def err(s):
1017 raise Exception(s)
1018
1019
1020if __name__ == "__main__":
1021 main()