API Reference#
pw_codegen: Source code generation utilities
pw_codegen#
Utilities for generating C++, Java, Python, Rust, and TypeScript code.
- class pw_codegen.OutputFile(filename: str | PurePath, indent_width: int = 2)#
A buffer to which generated source code is written.
Example:
output = OutputFile("hello.c") output.write_line("int main(void) {") with output.indent(): output.write_line('printf("Hello, world");') output.write_line("return 0;") output.write_line("}") print(output.content())
Produces:
int main(void) { printf("Hello, world"); return 0; }
pw_codegen.output_file#
Indentation-aware buffer for generating source files.
- class pw_codegen.output_file.OutputFile(filename: str | PurePath, indent_width: int = 2)#
A buffer to which generated source code is written.
Example:
output = OutputFile("hello.c") output.write_line("int main(void) {") with output.indent(): output.write_line('printf("Hello, world");') output.write_line("return 0;") output.write_line("}") print(output.content())
Produces:
int main(void) { printf("Hello, world"); return 0; }
pw_codegen.cpp#
C++ source code generation utilities.
- class pw_codegen.cpp.IntType(cc_type: str, min_value: int, max_value: int)#
Metadata for a fixed-width C++ integer type.
- pw_codegen.cpp.bool_literal(value: bool) str#
Formats
valueas a C++ boolean literal (trueorfalse).
- pw_codegen.cpp.byte_array(data: bytes | bytearray | memoryview, *, bytes_per_line: int | None = None, indent: str = ' ') str#
Formats
dataas a C++std::bytebrace-enclosed initializer.When
bytes_per_lineisNone(the default), returns a single-line initializer such as"{std::byte{0x01}, std::byte{0x02}}"(or"{}"whendatais empty). Whenbytes_per_lineis positive anddatais non-empty, formats a multiline initializer with up tobytes_per_lineelements per indented line.- Raises:
ValueError –
bytes_per_lineis not a positive integer.
- pw_codegen.cpp.char_literal(data: str | bytes) str#
Formats a single byte or ASCII character as a C++
charliteral.- Parameters:
data – Single-byte
bytesor 1-byte ASCIIstr.- Raises:
ValueError –
datadoes not encode to a single byte.
- pw_codegen.cpp.constant_style(name: str) str#
Formats a
snake_caseorUPPER_SNAKE_CASEname as a C++ constant.Converts
nameto Google C++ constant style (kPascalCase).
- pw_codegen.cpp.doc_comment(doc: str, indent: str = '') Iterator[str]#
Yields
///C++ documentation comment lines fordoc.- Raises:
ValueError – A line in
docends with a backslash, which would splice the following line of generated C++ code into the comment.
- pw_codegen.cpp.double_literal(value: int | float) str#
Formats
valueas a C++doubleliteral or special value.- Parameters:
value – Integer or floating-point value to format.
- Raises:
ValueError –
valueoverflowsdouble.
- pw_codegen.cpp.fix_enum_value_name(name: str, extra_reserved: Collection[str] = ()) str#
Adjusts an enum value name if its
UPPER_SNAKE_CASEform is reserved.Checks
name.upper()againstRESERVED_WORDSandextra_reserved, appending an underscore tonameif a collision is found. Lowercase or mixed-case entries inRESERVED_WORDSandextra_reserved(such as"int"or"Message") do not match because theUPPER_SNAKE_CASEidentifier will not collide with them.
- pw_codegen.cpp.fix_identifier(name: str, extra_reserved: Collection[str] = ()) str#
Adjusts
nameso it does not collide with C++ reserved words.If
nameis inRESERVED_WORDSorextra_reserved, an underscore is appended. Otherwise,nameis returned unchanged.Note that C++ reserves identifiers containing
__or starting with an underscore followed by an uppercase letter for the implementation; appending an underscore cannot make those valid, so they are not modified.
- pw_codegen.cpp.float_literal(value: int | float) str#
Formats
valueas a 32-bit C++floatliteral or special value.- Parameters:
value – Integer or floating-point value to format.
- Raises:
ValueError –
valueoverflowsfloat.
- pw_codegen.cpp.includes(headers: Iterable[str]) list[str]#
Deduplicates, groups, and sorts C++
#includedirectives.Each item in
headersmay be either a bare include target ("<cstdint>"or'"pw_foo/bar.h"') or a full#includeline, with an optional trailing// ...comment (such as'"pw_foo/bar.h" // IWYU pragma: export'). If the same header appears both with and without a comment, the comment is preserved. System headers (<...>) are emitted first in sorted order, followed by local headers ("...") in sorted order, with a blank line separating the two groups when both are non-empty.- Raises:
ValueError – An item is not a valid
#includedirective or the same header appears with conflicting comments.
- pw_codegen.cpp.int_literal(value: int, int_type: str = 'int64') str#
Formats
valueas a C++ integer literal suitable forint_type.- Parameters:
value – Integer value to format.
int_type – Canonical fixed-width integer type name from
INT_TYPES(for example"int32"or"uint64").
- Raises:
ValueError –
int_typeis unknown orvalueis out of range forint_type.
- pw_codegen.cpp.is_identifier(name: str) bool#
Returns whether
nameis a valid, non-reserved C++ identifier.
- pw_codegen.cpp.namespace(
- output: OutputFile,
- name: str | None,
- *,
- padding: bool = True,
Wraps generated lines in
namespace <name> { ... }.If
nameisNone,"", or"::", nothing is written so callers can unconditionally wrap declarations whose namespace is optional.
- pw_codegen.cpp.namespace_open(name: str) str#
Returns the opening line
namespace <name> {for a C++ namespace.
- pw_codegen.cpp.string_literal(data: str | bytes) str#
Returns a quoted C++ string literal for
bytesor a UTF-8str.Uses printable ASCII characters and standard C++ escape sequences where possible, falling back to
\xNNhex escapes for non-ASCII or control bytes and splitting adjacent string literals when a hex escape is followed by a hexadecimal ASCII character.
- pw_codegen.cpp.uint8_array(data: bytes | bytearray | memoryview, *, bytes_per_line: int | None = None, indent: str = ' ') str#
Formats
dataas a C/C++ hexadecimal byte brace-enclosed initializer.When
bytes_per_lineisNone(the default), returns a single-line initializer such as"{0x01, 0x02}"(or"{}"whendatais empty). Whenbytes_per_lineis positive anddatais non-empty, formats a multiline initializer with up tobytes_per_lineelements per indented line.- Raises:
ValueError –
bytes_per_lineis not a positive integer.
pw_codegen.java#
Java source code generation utilities.
pw_codegen.python#
Python source code generation utilities.
- pw_codegen.python.docstring(text: str, indent: str = '') Iterator[str]#
Yields an indented Python docstring for
text.Yields nothing when
textis empty. Normalizes\r\nline endings and strips trailing newlines on non-blank text before formatting with triple double-quotes, falling back tostring_literal()whentextcontains triple quotes, backslashes, leading/trailing quotes or horizontal whitespace, or non-printable characters.
pw_codegen.rust#
Rust source code generation utilities.
- class pw_codegen.rust.IntType(rust_type: str, min_value: int, max_value: int)#
Metadata for a fixed-width Rust integer type.
- pw_codegen.rust.bool_literal(value: bool) str#
Formats
valueas a Rust boolean literal (trueorfalse).
- pw_codegen.rust.byte_slice(data: bytes | bytearray | memoryview) str#
Formats
dataas a Rust byte slice literal (e.g.&[1, 2, 3]).
- pw_codegen.rust.char_literal(data: str) str#
Formats a single Unicode scalar value as a Rust
charliteral.- Raises:
ValueError –
datadoes not have length 1 or is a UTF-16 surrogate.
- pw_codegen.rust.f32_literal(value: int | float) str#
Formats
valueas a Rustf32literal or constant.- Parameters:
value – Integer or floating-point value to format.
- Raises:
ValueError –
valueoverflowsf32.
- pw_codegen.rust.f64_literal(value: int | float) str#
Formats
valueas a Rustf64literal or constant.- Parameters:
value – Integer or floating-point value to format.
- Raises:
ValueError –
valueoverflowsf64.
- pw_codegen.rust.int_literal(value: int, int_type: str) str#
Formats
valueas a typed Rust integer literal.- Parameters:
value – Integer value to format.
int_type – Fixed-width Rust integer type suffix from
INT_TYPES(for example"i32"or"u64").
- Raises:
KeyError –
int_typeis not inINT_TYPES.ValueError –
valueis out of range forint_type.
- pw_codegen.rust.is_identifier(name: str) bool#
Returns whether
nameis a valid, non-keyword Rust identifier.
- pw_codegen.rust.string_literal(data: str) str#
Formats
dataas a quoted Rust string literal.- Raises:
ValueError –
datacontains a UTF-16 surrogate.
pw_codegen.typescript#
TypeScript source code generation utilities.