diff --git a/numbast/src/numbast/static/enum.py b/numbast/src/numbast/static/enum.py index 0ad55d06..ce9bd63c 100644 --- a/numbast/src/numbast/static/enum.py +++ b/numbast/src/numbast/static/enum.py @@ -32,6 +32,16 @@ class {enum_name}(IntEnum): def __init__( self, decl: Enum, enum_prefix_removal: list[str] | None = None ): + """ + Initialize the renderer for a single C++ enum and derive its Python enum name. + + Parameters: + decl (Enum): The parsed C++ enum declaration to render. + enum_prefix_removal (list[str] | None): Prefix strings to remove from the C++ enum and enumerator names when deriving Python identifiers; empty list if None. + + Description: + Stores the declaration and prefix-removal configuration, computes the Python enum name from the C++ name using the provided prefixes, and appends that Python name to the renderer's symbol list. + """ self._decl = decl self._enum_prefix_removal = enum_prefix_removal or [] @@ -42,6 +52,15 @@ def __init__( self._enum_symbols.append(self._enum_name) def _render(self): + """ + Render the stored C++ enum declaration into a Python IntEnum class and store the generated source. + + This method: + - Ensures required imports for `IntEnum`, `IntEnumMember`, and `int64` are added to the renderer's import set. + - Registers the mapping from the original C++ enum name to the computed Python enum name. + - Applies configured prefix removal to each enumerator, formats enumerator lines, and assembles the final class text. + - Writes the resulting Python class source into `self._python_rendered`. + """ self.Imports.add("from enum import IntEnum") self.Imports.add("from numba.types import IntEnumMember") self.Imports.add("from numba.types import int64") @@ -73,6 +92,16 @@ class StaticEnumsRenderer(BaseRenderer): def __init__( self, decls: list[Enum], enum_prefix_removal: list[str] | None = None ): + """ + Initialize the renderer for a collection of C++ enum declarations. + + Parameters: + decls (list[Enum]): The list of enum declarations to render. + enum_prefix_removal (list[str] | None): Optional list of prefixes to remove from enum and enumerator names when generating Python bindings; defaults to an empty list. + + Notes: + Initializes internal state and a list to accumulate per-enum rendered Python strings. + """ super().__init__(decls) self._decls = decls self._enum_prefix_removal = enum_prefix_removal or [] @@ -80,7 +109,14 @@ def __init__( self._python_rendered: list[str] = [] def _render(self, with_imports): - """Render python bindings for enums.""" + """ + Render all stored C++ enum declarations into Python binding source and store the result on the renderer instance. + + This populates self._python_rendered with each enum's rendered string and assembles the combined output into self._python_str. If with_imports is True, the module import block is included at the top of the assembled output. + + Parameters: + with_imports (bool): If True, prepend the rendered import block to the assembled Python output. + """ self._python_str = "" for decl in self._decls: diff --git a/numbast/src/numbast/static/function.py b/numbast/src/numbast/static/function.py index 217eabb5..20da4ac0 100644 --- a/numbast/src/numbast/static/function.py +++ b/numbast/src/numbast/static/function.py @@ -412,6 +412,18 @@ def __init__( use_cooperative: bool, function_prefix_removal: list[str] = [], ): + """ + Initialize the non-operator function renderer, compute the Python-facing function name by removing configured prefixes, and update tracked function symbols accordingly. + + Parameters: + decl (Function): The parsed function declaration to render. + header_path (str): Path to the C++ header containing the declaration. + use_cooperative (bool): Whether the function requires cooperative launch support. + function_prefix_removal (list[str]): List of prefixes to remove from the original function name to produce the Python-visible name. + + Notes: + This initializer replaces the original C++ name in the renderer's tracked function symbols with the computed Python name. + """ super().__init__(decl, header_path, use_cooperative) self._python_func_name = _apply_prefix_removal( decl.name, function_prefix_removal @@ -426,7 +438,12 @@ def __init__( @property def func_name_python(self): - """The name of the function in python with prefix removal applied.""" + """ + Python-visible function name after applying configured prefix removal. + + Returns: + str: The Python-exposed function name with any configured prefixes removed. + """ return self._python_func_name def _render_python_api(self): diff --git a/numbast/src/numbast/static/renderer.py b/numbast/src/numbast/static/renderer.py index 58b64eb5..5e337088 100644 --- a/numbast/src/numbast/static/renderer.py +++ b/numbast/src/numbast/static/renderer.py @@ -87,6 +87,15 @@ def reset(self): """List of new enum handles to expose.""" def __init__(self, decl): + """ + Initialize the BaseRenderer with a declaration and ensure required base imports are registered. + + Parameters: + decl: The parsed declaration object the renderer will use to produce code. + + Notes: + This constructor records "import numba" and "import io" in the class-level Imports set as part of instance initialization. + """ self.Imports.add("import numba") self.Imports.add("import io") self._decl = decl @@ -123,6 +132,13 @@ def render_as_str( def clear_base_renderer_cache(): + """ + Clear all class-level caches and exposed-symbol lists on BaseRenderer. + + This resets shared renderer state by removing all entries from the following BaseRenderer attributes: + `Imports`, `Imported_VectorTypes`, `Includes`, `ShimFunctions`, `_imported_numba_types`, + `_nbtype_symbols`, `_record_symbols`, `_function_symbols`, and `_enum_symbols`. + """ BaseRenderer.Imports.clear() BaseRenderer.Imported_VectorTypes.clear() BaseRenderer.Includes.clear() @@ -137,6 +153,17 @@ def clear_base_renderer_cache(): def get_reproducible_info( config_rel_path: str, cmd: str, sbg_params: dict[str, str] ) -> str: + """ + Produce a reproducible information header composed of commented lines documenting versions, the generation command, generator parameters, and the config path. + + Parameters: + config_rel_path (str): Path to the generator configuration file relative to the generated binding file. + cmd (str): The command line used to invoke the generation. + sbg_params (dict[str, str]): Static binding generator parameters to record. + + Returns: + str: A multi-line string where each line is prefixed with "# " and the block ends with a single trailing newline. + """ info = [ f"Ast_canopy version: {ast_canopy_ver}", f"Numbast version: {numbast_ver}", @@ -238,6 +265,12 @@ def _get_record_symbols() -> str: def _get_function_symbols() -> str: + """ + Render a Python code block that defines the _FUNCTION_SYMBOLS list from BaseRenderer._function_symbols. + + Returns: + code (str): A string containing a Python assignment that defines `_FUNCTION_SYMBOLS` as a list of symbol names quoted and comma-separated. + """ template = """ _FUNCTION_SYMBOLS = [{function_symbols}] """ @@ -250,6 +283,14 @@ def _get_function_symbols() -> str: def _get_enum_symbols() -> str: + """ + Generate a Python source snippet that defines the `_ENUM_SYMBOLS` list from BaseRenderer._enum_symbols. + + The returned string is a ready-to-insert code block where each enum name is quoted and placed into a Python list assigned to `_ENUM_SYMBOLS`. + + Returns: + A string containing Python code that assigns `_ENUM_SYMBOLS` to a list of quoted enum symbol names (e.g., `_ENUM_SYMBOLS = ["A","B"]`). + """ template = """ _ENUM_SYMBOLS = [{enum_symbols}] """ @@ -262,12 +303,12 @@ def _get_enum_symbols() -> str: def get_all_exposed_symbols() -> str: - """Return the definition of all exposed symbols via `__all__`. + """ + Produce the code block that defines and exposes all symbol name lists and the module __all__. - A generated binding module exposes the following symbols: - - Name of a record, corresponds to the handle of the python object - - Name of the record type instance in Numba, corresponds to the record's numba type - - Name of a function, corresponds to the handle of the python object + Returns: + A string containing Python code that defines `_NBTYPE_SYMBOLS`, `_RECORD_SYMBOLS`, `_FUNCTION_SYMBOLS`, `_ENUM_SYMBOLS` + and an `__all__` list that is the concatenation of those symbol lists. """ nbtype_symbols = _get_nbtype_symbols() diff --git a/numbast/src/numbast/static/struct.py b/numbast/src/numbast/static/struct.py index b2990196..ea253bf2 100644 --- a/numbast/src/numbast/static/struct.py +++ b/numbast/src/numbast/static/struct.py @@ -149,6 +149,17 @@ def __init__( header_path: str, ctor_decl: StructMethod, ): + """ + Initialize a renderer for a single struct constructor and prepare cached type/name representations used during code generation. + + Parameters: + struct_name (str): Original C/C++ struct identifier. + python_struct_name (str): Python-facing name to use in generated bindings and typing. + struct_type_class (str): Name of the generated Numba type class for the struct. + struct_type_name (str): Name of the generated Numba type identifier for the struct. + header_path (str): Path to the C/C++ header that declares the struct. + ctor_decl (StructMethod): Parsed constructor declaration describing parameter names, types, and mangled name. + """ self._struct_name = struct_name self._python_struct_name = python_struct_name self._struct_type_class = struct_type_class @@ -247,7 +258,14 @@ def _render_shim_function(self): self.ShimFunctions.append(self._c_ext_shim_rendered) def _render_lowering(self): - """Render lowering codes for this struct constructor.""" + """ + Generate and store the Numba lowering code for this struct constructor. + + Formats the constructor lowering from the renderer's templates and writes the result to + self._lowering_rendered. If the constructor is a converting (non-explicit single-argument) + constructor, also append a `lower_cast` lowering that enables implicit conversion from the + argument type to the struct type. + """ self._lowering_rendered = self.struct_ctor_lowering_template.format( struct_name=self._python_struct_name, @@ -344,6 +362,17 @@ def __init__( struct_type_name, header_path, ): + """ + Initialize the renderer for all constructors of a CUDA struct, storing inputs and preparing Python/C output accumulators. + + Parameters: + ctor_decls (list[StructMethod]): List of constructor declarations to render. + struct_name (str): Original struct name from the declaration. + python_struct_name (str): Python-facing struct name to use in generated bindings and typing. + struct_type_class (str): Name of the generated Numba type class for the struct. + struct_type_name (str): Name of the generated Numba type instance for the struct. + header_path (str | os.PathLike): Path to the C/C++ header containing the struct declaration. + """ self._ctor_decls = ctor_decls self._struct_name = struct_name self._python_struct_name = python_struct_name @@ -357,13 +386,11 @@ def __init__( self._struct_ctor_template_name = f"_ctor_template_{struct_name}" def _render_typing(self, signature_strs: list[str]): - """Renders the typing of the constructors. + """ + Render the ConcreteTemplate typing class for the struct's constructors using provided overload signatures. - Parameter - --------- - signature_strs: list[str] - A list of `numba.signature` strings containing all overloads of - the constructors. + Parameters: + signature_strs (list[str]): Numba `signature` strings for each constructor overload to include in the generated typing template. """ self.Imports.add( @@ -382,7 +409,16 @@ def _render_typing(self, signature_strs: list[str]): ) def _render(self): - """Render all struct constructors.""" + """ + Render all constructors for the struct and assemble their Python and C outputs. + + Iterates over the stored constructor declarations, instantiates a StaticStructCtorRenderer + for each, and invokes its rendering. Accumulates each renderer's Python and C fragments + into this renderer's outputs and collects constructor typing signatures. + If a constructor references a type not known to Numba, a warning is emitted and that + constructor is skipped. After processing all constructors, the collected signatures + are used to render the combined typing block which is appended to the Python output. + """ signatures: list[str] = [] for ctor_decl in self._ctor_decls: @@ -734,6 +770,17 @@ def __init__( header_path: str, method_decl: StructMethod, ): + """ + Initialize a renderer for a single struct regular method and cache derived naming and type info used during code + generation. + + Parameters: + struct_name (str): Original C/C++ struct name from the header. + python_struct_name (str): Python-facing struct name used for generated Numba/typing symbols. + struct_type_name (str): Fully-qualified Numba type identifier for the struct. + header_path (str): Path to the C/C++ header that declares the struct. + method_decl (StructMethod): Parsed method declaration; used to derive parameter/return types, mangled names, and signatures. + """ super().__init__(method_decl) self._struct_name = struct_name self._python_struct_name = python_struct_name @@ -756,6 +803,15 @@ def __init__( # Pointers for interop def wrap_pointer(typ): + """ + Construct a CPointer wrapper string for the given type. + + Parameters: + typ (str): The underlying type name or type-string to wrap. + + Returns: + str: A string representing the CPointer-wrapped type, e.g. "CPointer(int32)". + """ return f"CPointer({typ})" _pointer_wrapped_param_types = [ @@ -780,7 +836,14 @@ def wrap_pointer(typ): @property def signature_str(self) -> str: - """signature string for typing with recvr specified""" + """ + Builds the typing signature string for this method including the receiver. + + Returns: + signature_str (str): A string formatted as + "signature(, , recvr=)" or + "signature(, recvr=)" when there are no parameters. + """ recvr = self._struct_type_name if self._nb_param_types_str: return ( @@ -791,6 +854,17 @@ def signature_str(self) -> str: return f"signature({self._nb_return_type_str}, recvr={recvr})" def _render_decl_device(self): + """ + Render the CUDA device declaration and its Python-facing device-caller for this struct method and store the + combined source. + + This method: + - Ensures required imports are registered on self.Imports. + - Formats the device declaration and a small Python device-caller using the renderer's template fields + (device/caller names, return type, struct type, pointer-wrapped parameter types). + - Builds a positional argument list based on the method's parameters and concatenates the declaration and caller + into self._decl_device_rendered. + """ self.Imports.add("from numba.cuda import declare_device") self.Imports.add("from numba.core.typing import signature") self.Imports.add("from numba.types import CPointer") @@ -818,6 +892,12 @@ def _render_decl_device(self): ) def _render_shim_function(self): + """ + Generate and register the C-extension shim for this struct method. + + Stores the generated C shim text in _c_ext_shim_rendered, creates a variable-wrapped string in + _c_ext_shim_var_rendered, and appends the shim to the ShimFunctions list. + """ self._c_ext_shim_rendered = make_struct_regular_method_shim( shim_name=self._unique_shim_name, struct_name=self._struct_name, @@ -831,6 +911,12 @@ def _render_shim_function(self): self.ShimFunctions.append(self._c_ext_shim_rendered) def _render_lowering(self): + """ + Render and store the Numba lowering code for the struct method. + + Generates the CUDA lowering function for this method using the renderer's lowering template, registers the + required `lower` import, and assigns the resulting source string to `self._lowering_rendered`. + """ self.Imports.add("from numba.cuda.cudaimpl import lower") param_types = self._nb_param_types_str or "" @@ -848,6 +934,14 @@ def _render_lowering(self): self._lowering_rendered = lowering_rendered def _render(self): + """ + Orchestrates rendering of a single struct conversion/operator: produces the Python lowering scope and the C + shim. + + Calls the device declaration, C shim generation, and lowering renderers, then combines their template outputs + into the final Python lowering body (stored on self._python_rendered) and the final C shim string (stored on + self._c_rendered). + """ self._render_decl_device() self._render_shim_function() self._render_lowering() @@ -884,6 +978,18 @@ def __init__( header_path: str, method_decls: list[StructMethod], ): + """ + Initialize the renderer for a struct's regular member methods. + + Parameters: + struct_name (str): Original C/C++ struct name. + python_struct_name (str): Public Python-facing name used in generated typing and symbols. + struct_type_name (str): Internal Numba type name for the struct. + header_path (str): Path to the C/C++ header that declares the struct. + method_decls (list[StructMethod]): Declarations of the struct's member functions to render. + + Initializes internal containers for accumulated Python and C output, and maps for per-method typing templates and collected signatures. + """ super().__init__(method_decls) self._struct_name = struct_name self._python_struct_name = python_struct_name @@ -897,6 +1003,19 @@ def __init__( self._method_signatures: dict[str, list[str]] = {} def _render(self): + """ + Render lowering, C shims, and typing templates for all regular methods of the struct. + + This populates the renderer's imports and appends per-overload lowering/python bindings and C shim code to self._python_rendered and self._c_rendered. For each method declaration it collects a typing signature (stored in self._method_signatures) and, after processing overloads, emits a ConcreteTemplate typing class for each method name and records the template name in self._method_templates. + + Side effects: + - Adds required imports to self.Imports. + - Appends generated Python lowering/typing code to self._python_rendered. + - Appends generated C shim code to self._c_rendered. + - Updates self._method_signatures (mapping method name -> list of signatures). + - Updates self._method_templates (mapping method name -> generated template name). + - Emits a warning and skips a method if an unknown type is encountered. + """ self.Imports.add( "from numba.cuda.typing.templates import ConcreteTemplate" ) @@ -1050,6 +1169,23 @@ def __init__( struct_prefix_removal: list[str] | None = None, aliases: list[str] = [], ): + """ + Initialize renderer state for a CUDA struct binding and register related symbols and imports. + + Parameters: + decl (Struct): Parsed struct declaration to render. + parent_type (type | None): Numba parent type to inherit from; defaults to `Type` when None. + data_model (type | None): Numba data model to use (`StructModel` by default). + header_path (os.PathLike | str): Path to the C/C++ header that declares the struct. + struct_prefix_removal (list[str] | None): Optional list of prefixes to remove from the struct's name for Python-facing identifiers. + aliases (list[str]): Optional additional public names to expose for the struct. + + Side effects: + - Registers required numba type and datamodel imports. + - Computes and stores python-facing and internal identifier names. + - Records a mapping from the original struct name to the generated Numba type name in CTYPE_TO_NBTYPE_STR. + - Appends public symbol names to internal symbol lists used for export. + """ super().__init__(decl) self._struct_prefix_removal = struct_prefix_removal or [] @@ -1098,7 +1234,11 @@ def __init__( self._record_symbols.append(self._python_struct_name) def _render_typing(self): - """Render typing of the struct.""" + """ + Render the Numba typing block for this struct. + + Derives implicit conversion types from any converting constructors and formats the typing template, storing the result on self._typing_rendered. + """ implicit_conversion_types = ", ".join( [ @@ -1132,7 +1272,18 @@ def _render_python_api(self): ) def _render_data_model(self): - """Renders the data model of the struct.""" + """ + Render and store the Numba data model representation for this struct. + + If the configured data model is PrimitiveModel, add the required IR import and populate + self._data_model_rendered with the primitive model template. If the data model is StructModel, + collect the struct fields' Numba type strings, format them into a member tuple list, and + populate self._data_model_rendered with the struct model template. + + Side effects: + - Adds imports to self.Imports as needed. + - Sets self._data_model_rendered. + """ self.Imports.add("from numba.core.extending import register_model") @@ -1244,7 +1395,11 @@ def _render_regular_methods(self): self._method_template_map = static_methods_renderer.method_templates def _render_struct_ctors(self): - """Render constructors of the struct.""" + """ + Render all constructors for the struct and store their rendered outputs. + + Populates self._struct_ctors_python_rendered with the combined Python typing and lowering code for the struct's constructors, and self._struct_ctors_c_rendered with the combined C shim implementations. + """ static_ctors_renderer = StaticStructCtorsRenderer( struct_name=self._struct_name, python_struct_name=self._python_struct_name, @@ -1382,6 +1537,21 @@ def __init__( struct_prefix_removal: list[str] | None = None, excludes: list[str] = [], ): + """ + Initialize the renderer for multiple CUDA struct declarations. + + Create an instance that will render Python bindings and C shim code for the provided struct declarations and track rendering results. + + Parameters: + decls (list[Struct]): List of parsed struct declarations to render. + specs (dict[str, tuple[type | None, type | None, os.PathLike]]): Per-struct rendering specifications mapping struct name to a tuple of (parent Numba type or None, data model type or None, header path). + default_header (os.PathLike | str | None): Fallback header path to use when a struct's header is not provided in `specs`. + struct_prefix_removal (list[str] | None): Optional list of name prefixes to remove from struct names when generating python-facing identifiers; empty list if not provided. + excludes (list[str]): Names of structs to skip during rendering. + + Side effects: + Initializes internal accumulators `._python_rendered` and `._c_rendered` and stores provided configuration on the instance. + """ self._decls = decls self._specs = specs self._default_header = default_header @@ -1397,7 +1567,18 @@ def _render( with_imports: bool, with_shim_stream: bool, ): - """Render all structs in `decls`.""" + """ + Render Python and C bindings for the configured CUDA structs and assemble the final script strings. + + Processes each struct declaration (skipping any in the excludes list), instantiates a StaticStructRenderer for each, and collects per-struct Python and C outputs. Aggregates imports and concatenates the Python renderings into the instance attribute `_python_str`. Optionally prepends rendered imports when `with_imports` is True and injects a shim include when `with_shim_stream` is True. Clears `_shim_function_pystr` and `_c_str` at the end. + + Parameters: + with_imports (bool): If True, prepend the global rendered imports to the final Python string. + with_shim_stream (bool): If True, prepend a shim include for the default header to the final Python string. + + Raises: + ValueError: If a struct declaration does not provide a header path. + """ for decl in self._decls: name = decl.name if name in self._excludes: diff --git a/numbast/src/numbast/static/types.py b/numbast/src/numbast/static/types.py index 61af19d8..60d5459a 100644 --- a/numbast/src/numbast/static/types.py +++ b/numbast/src/numbast/static/types.py @@ -17,7 +17,13 @@ def register_enum_type_str(ctype_enum_name: str, enum_name: str): - """Register the C++ enum type name mapping to its Numba type.""" + """ + Register a mapping from a C++ enum type name to its corresponding Numba type string. + + Parameters: + ctype_enum_name (str): The C++ enum type name to register (as it appears in C/C++ headers). + enum_name (str): The enum identifier to use inside the generated Numba type string (becomes the first argument to `IntEnumMember`). + """ global CTYPE_TO_NBTYPE_STR CTYPE_TO_NBTYPE_STR[ctype_enum_name] = f"IntEnumMember({enum_name}, int64)" diff --git a/numbast/src/numbast/tools/static_binding_generator.py b/numbast/src/numbast/tools/static_binding_generator.py index 2ed0e615..9cf28d8b 100644 --- a/numbast/src/numbast/tools/static_binding_generator.py +++ b/numbast/src/numbast/tools/static_binding_generator.py @@ -350,23 +350,14 @@ def convert(self, value, param, ctx): def _typedef_to_aliases(typedef_decls: list[Typedef]) -> dict[str, list[str]]: - """Convert C++ typedef declarations into aliases. - - `typedef` declarations contains a 1-1 mapping from "name" to "underlying name". - There can be multiple typedefs of the same underlying name. - - This function aggregates them so that each "underlying name" maps to all names, - aka, its aliases. + """ + Group C++ typedef declarations by their underlying type name. - Parameter - --------- - typedef_decls: list[Typedef] - A list of C++ typedef declarations + Parameters: + typedef_decls (list[Typedef]): Typedef declarations to process. - Return - ------ - aliases: dict[str, list[str]] - Dictionary mapping underlying names to a list of aliases. + Returns: + dict[str, list[str]]: Mapping from an underlying type name to a list of alias names (typedef names). """ aliases = defaultdict(list) for typedef in typedef_decls: @@ -383,7 +374,20 @@ def _generate_structs( struct_prefix_removal, excludes, ): - """Convert CLI inputs into structure that fits `StaticStructsRenderer` and create struct bindings.""" + """ + Render struct declarations into the Python source for struct bindings. + + Parameters: + struct_decls (list): List of struct declaration objects to render. + header_path (str): Path to the original header file associated with the declarations. + types (dict): Mapping from struct name to corresponding numba type object (or None). + data_models (dict): Mapping from struct name to corresponding numba datamodel object (or None). + struct_prefix_removal (list): List of name prefixes to remove from struct identifiers when rendering. + excludes (list): List of struct names to exclude from rendering. + + Returns: + str: Rendered source code for the struct bindings. + """ specs = {} for struct_decl in struct_decls: struct_name = struct_decl.name @@ -409,7 +413,20 @@ def _generate_functions( function_prefix_removal: list[str], skip_prefix: str | None, ) -> str: - """Convert CLI inputs into structure that fits `StaticStructsRenderer` and create struct bindings.""" + """ + Render Python bindings for the provided function declarations. + + Parameters: + func_decls (list[Function]): Parsed function declarations to render. + header_path (str): Path to the original header file used for the shim stream. + excludes (list[str]): Function names to exclude from rendering. + cooperative_launch_functions (list[str]): Regex patterns or exact names identifying functions that require cooperative launch handling. + function_prefix_removal (list[str]): List of prefixes to strip from function names when generating bindings. + skip_prefix (str | None): If provided, skip generating bindings for functions whose names start with this prefix. + + Returns: + binding_source (str): Generated source code for the functions section (imports and shim stream are omitted). + """ SFR = StaticFunctionsRenderer( func_decls, @@ -426,7 +443,16 @@ def _generate_functions( def _generate_enums( enum_decls: list[Enum], enum_prefix_removal: list[str] = [] ): - """Create enum bindings.""" + """ + Render enum declarations into binding source code. + + Parameters: + enum_decls (list[Enum]): Parsed enum declarations to render. + enum_prefix_removal (list[str]): Prefixes to remove from enum names before rendering. + + Returns: + str: The rendered enum bindings as a source string. + """ SER = StaticEnumsRenderer(enum_decls, enum_prefix_removal) return SER.render_as_str(with_imports=False, with_shim_stream=False) @@ -468,19 +494,18 @@ def _static_binding_generator( bypass_parse_error: bool = False, ) -> str: """ - A function to generate CUDA static bindings for CUDA C++ headers. + Generate static Python bindings for a CUDA C++ header using the provided configuration. Parameters: - - config (Config): Configuration object containing all binding generation settings. - - output_dir (str): Path to the output directory where the processed files will be saved. - - log_generates (bool, optional): Whether to log the list of generated bindings. Defaults to False. - - cfg_file_path (str, optional): Path to the configuration file. Defaults to None. - - sbg_params (dict, optional): A dictionary of parameters for the static binding generator. Defaults to empty dict. - - bypass_parse_error (bool, optional): Whether to bypass parse error and continue generating bindings. Defaults to False. + config (Config): Configuration containing entry point, parsing and rendering options. + output_dir (str): Directory where the generated binding file will be written. + log_generates (bool): If True, print counts and lists of declarations that will be generated. + cfg_file_path (str | None): Path to the config file used to produce these bindings (used for reproducible metadata); may be None. + sbg_params (dict[str, str]): Extra parameters to include in the generator metadata. + bypass_parse_error (bool): If True, continue generation when source parsing reports recoverable errors. Returns: - str - Path to the generated binding file + str: Absolute path to the generated binding file. """ try: basename = os.path.basename(config.entry_point) diff --git a/numbast/src/numbast/tools/tests/test_prefix_removal.py b/numbast/src/numbast/tools/tests/test_prefix_removal.py index 4e913ecb..33a52f10 100644 --- a/numbast/src/numbast/tools/tests/test_prefix_removal.py +++ b/numbast/src/numbast/tools/tests/test_prefix_removal.py @@ -42,6 +42,11 @@ def test_prefix_removal(run_in_isolated_folder, arch_str): @cuda.jit def kernel(): + """ + Exercise generated bindings for `foo`, `Foo`, and `Bar` in a CUDA kernel. + + This kernel invokes the top-level function `foo` with example arguments, constructs a `Foo` instance and accesses its `get_x()` method and `x` attribute, and reads the `BAR_A` and `BAR_B` attributes from `Bar`. It is intended for use in tests that verify API symbol exposure and runtime linkage. + """ result = foo(1, 2) # noqa: F841 foo_obj = Foo() x = foo_obj.get_x() # noqa: F841 diff --git a/numbast/src/numbast/utils.py b/numbast/src/numbast/utils.py index b9a8ed1f..1bca7013 100644 --- a/numbast/src/numbast/utils.py +++ b/numbast/src/numbast/utils.py @@ -319,17 +319,15 @@ def make_struct_conversion_operator_shim( def _apply_prefix_removal(name: str, prefix_to_remove: list[str]) -> str: - """Apply prefix removal to a name based on the configuration. + """ + Remove the first matching prefix from a name. - Parameters - ---------- - name : str - The original struct, function or enum type name, or named enum values. + Parameters: + name (str): The original identifier (e.g., struct, function, or enum name). + prefix_to_remove (list[str]): Ordered list of prefixes to try; the first prefix that matches the start of `name` will be removed. - Returns - ------- - str - The name with prefixes removed + Returns: + str: The name with the first matching prefix removed, or the original name if no prefixes match. """ for prefix in prefix_to_remove: if name.startswith(prefix):