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;
}
__init__(filename: str | PurePath, indent_width: int = 2) → None#
content() → str#

Returns the accumulated file content.

indent(amount: int | None = None) → Iterator[None]#

Increases the indentation level within the context.

name() → str#

Returns the output filename.

write_line(line: str = '') → None#

Appends a line to the buffer with the current indentation.

pw_codegen.camel_to_snake(name: str) → str#

Converts CamelCase or camelCase to snake_case.

pw_codegen.camel_to_upper_snake(name: str) → str#

Converts CamelCase or camelCase to UPPER_SNAKE_CASE.

pw_codegen.snake_to_pascal(name: str) → str#

Converts snake_case or UPPER_SNAKE_CASE to PascalCase.

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;
}
__init__(filename: str | PurePath, indent_width: int = 2) → None#
content() → str#

Returns the accumulated file content.

indent(amount: int | None = None) → Iterator[None]#

Increases the indentation level within the context.

name() → str#

Returns the output filename.

write_line(line: str = '') → None#

Appends a line to the buffer with the current indentation.

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.

cc_type: str#

Alias for field number 0

max_value: int#

Alias for field number 2

min_value: int#

Alias for field number 1

pw_codegen.cpp.byte_array(data: bytes, *, bytes_per_line: int | None = None, indent: str = '  ') → str#

Formats data as a C++ std::byte brace-enclosed initializer.

When bytes_per_line is None (the default), returns a single-line initializer such as "{std::byte{0x01}, std::byte{0x02}}" (or "{}" when data is empty). When bytes_per_line is positive and data is non-empty, formats a multiline initializer with up to bytes_per_line elements per indented line.

pw_codegen.cpp.constant_style(name: str) → str#

Formats a snake_case or UPPER_SNAKE_CASE name as a C++ constant.

Converts name to Google C++ constant style (kPascalCase).

pw_codegen.cpp.doc_comment(doc: str, indent: str = '') → Iterator[str]#

Yields /// C++ documentation comment lines for doc.

Raises:

ValueError – A line in doc ends with a backslash, which would splice the following line of generated C++ code into the comment.

pw_codegen.cpp.fix_enum_value_name(name: str, extra_reserved: Collection[str] = ()) → str#

Adjusts an enum value name if its UPPER_SNAKE_CASE form is reserved.

Checks name.upper() against RESERVED_WORDS and extra_reserved, appending an underscore to name if a collision is found. Lowercase or mixed-case entries in RESERVED_WORDS and extra_reserved (such as "int" or "Message") do not match because the UPPER_SNAKE_CASE identifier will not collide with them.

pw_codegen.cpp.fix_identifier(name: str, extra_reserved: Collection[str] = ()) → str#

Adjusts name so it does not collide with C++ reserved words.

If name is in RESERVED_WORDS or extra_reserved, an underscore is appended. Otherwise, name is 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.includes(headers: Iterable[str]) → list[str]#

Deduplicates, groups, and sorts C++ #include directives.

Each item in headers may be either a bare include target ("<cstdint>" or '"pw_foo/bar.h"') or a full #include line. 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.

pw_codegen.cpp.int_literal(value: int, int_type: str = 'int64') → str#

Formats value as a C++ integer literal suitable for int_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_type is unknown or value is out of range for int_type.

pw_codegen.cpp.is_identifier(name: str) → bool#

Returns whether name is a valid, non-reserved C++ identifier.

pw_codegen.cpp.namespace(
output: OutputFile,
name: str | None,
*,
padding: bool = True,
) → Iterator[None]#

Wraps generated lines in namespace <name> { ... }.

If name is None, "", or "::", nothing is written so callers can unconditionally wrap declarations whose namespace is optional.

pw_codegen.cpp.namespace_close(name: str) → str#

Returns }  // namespace <name> for a C++ namespace.

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 bytes or a UTF-8 str.

Uses printable ASCII characters and standard C++ escape sequences where possible, falling back to \xNN hex 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.java#

Java source code generation utilities.

pw_codegen.java.byte_array(data: bytes) → str#

Formats data as a Java byte[] literal.

pw_codegen.java.string_literal(data: str) → str#

Formats data as a quoted Java string literal.

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 text is empty. Normalizes \r\n line endings and strips trailing newlines on non-blank text before formatting with triple double-quotes, falling back to string_literal() when text contains triple quotes, backslashes, leading/trailing quotes or horizontal whitespace, or non-printable characters.

pw_codegen.python.is_identifier(name: str) → bool#

Returns whether name is a valid, non-keyword Python identifier.

pw_codegen.python.string_literal(text: str) → str#

Returns a Python string literal, preferring double quotes.

pw_codegen.rust#

Rust source code generation utilities.

pw_codegen.rust.byte_slice(data: bytes) → str#

Formats data as a Rust byte slice literal (e.g. &[1, 2, 3]).

pw_codegen.rust.string_literal(data: str) → str#

Formats data as a quoted Rust string literal.

pw_codegen.typescript#

TypeScript source code generation utilities.

pw_codegen.typescript.byte_array(data: bytes) → str#

Formats data as a TypeScript Uint8Array literal.