diff --git a/hatch_rs/structs.py b/hatch_rs/structs.py index ab8ea98..a33fe85 100644 --- a/hatch_rs/structs.py +++ b/hatch_rs/structs.py @@ -2,17 +2,15 @@ import sys import sysconfig -from ctypes import CDLL from dataclasses import dataclass from glob import glob -from importlib.util import find_spec -from json import dumps, loads +from json import loads from logging import getLogger from os import environ from os.path import relpath from pathlib import Path from platform import machine as platform_machine -from re import DOTALL, MULTILINE, escape, findall, sub +from re import sub from shlex import join as shell_join from shutil import copy2 from subprocess import run @@ -20,11 +18,24 @@ from tempfile import TemporaryDirectory from typing import Any, Literal +from hatch_native import ( + ExternalLibrary, + ExternalLibraryConfig, + LibraryValidationConfig, + ValidationCommandConfig, + check_exports, + check_headers, + header_symbols, + prefixed_header_symbols, + resolve_external_library, + resolve_library_source, + run_validation_command, + shared_library_name as _shared_library_name, + write_artifact_manifest, +) from packaging.tags import cpython_tags, mac_platforms, platform_tags from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validator -from .symbols import exported_symbols - _logger = getLogger(__name__) __all__ = ( @@ -88,18 +99,6 @@ class CopiedArtifact: distribution_path: str -@dataclass(frozen=True) -class ExternalLibrary: - """A prebuilt C ABI library resolved outside the build in external mode.""" - - name: str - library: Path - library_dir: Path - include_dir: Path | None - link_name: str - package: str | None = None - - WINDOWS_TARGETS = { "x86_64": "x86_64-pc-windows-msvc", "i686": "i686-pc-windows-msvc", @@ -270,16 +269,7 @@ def resolve_target_triple(target: str | None = None, *, platform: str | None = N def shared_library_name(library: str, *, platform: str | None = None) -> str: """Render a platform-specific standalone shared-library filename.""" - platform = _normalize_platform(platform or environ.get("HATCH_RUST_PLATFORM", sys_platform)) - if platform == "win32": - return f"{library}.dll" - if platform == "darwin": - return f"lib{library}.dylib" - if platform == "linux": - return f"lib{library}.so" - if platform == "emscripten": - return f"{library}.wasm" - raise ValueError(f"Unsupported platform: {platform}") + return _shared_library_name(library, platform=_normalize_platform(platform or environ.get("HATCH_RUST_PLATFORM", sys_platform))) def executable_name(name: str, *, platform: str | None = None) -> str: @@ -457,24 +447,6 @@ def _cargo_intermediate_dirs(target_path: Path) -> list[Path]: return [directory for directory in (target_path / "deps", *sorted(target_path.glob("build/*/*/out"))) if directory.is_dir()] -def header_symbols(text: str, prefix: str) -> list[str]: - """Functions declared in a C header whose names start with `prefix`. - - Comments, preprocessor lines, `static inline` definitions, and function - pointer declarators such as `prefix_status (*open)(...)` are skipped, since - none of them is exported by the library. Declarations are found with - regular expressions rather than a C parser, which works for a hand-written - or generated ABI header. - """ - text = sub(r"/\*.*?\*/", " ", text, flags=DOTALL) - text = sub(r"//[^\n]*", " ", text) - text = sub(r"^\s*#.*?(? Path: path = Path(path) if path.is_absolute(): @@ -540,33 +512,7 @@ def validate_source(cls, source: Path) -> Path: return source -class ValidationCommandConfig(BaseModel): - """A project-specific command used to validate a built artifact.""" - - model_config = ConfigDict(extra="ignore", populate_by_name=True) - - command: list[str] = Field(description="Validation command argv list.") - working_directory: Path | None = Field(default=None, alias="working-directory", description="Validation command working directory.") - env: dict[str, str] = Field(default_factory=dict, description="Additional environment variables for this validation command.") - - @field_validator("command", mode="before") - @classmethod - def validate_command(cls, values: Any) -> list[str]: - if isinstance(values, str): - raise TypeError("Validation command must be an argv list, not a shell string.") - return [str(value) for value in values] - - @field_validator("working_directory", mode="before") - @classmethod - def validate_working_directory(cls, path: Path | None) -> Path | None: - if path is None: - return None - if not isinstance(path, Path): - path = Path(path) - return path - - -class RustArtifactConfig(BaseModel): +class RustArtifactConfig(LibraryValidationConfig, ExternalLibraryConfig): """Configuration for one Rust build artifact.""" model_config = ConfigDict(extra="ignore", populate_by_name=True) @@ -623,28 +569,6 @@ class RustArtifactConfig(BaseModel): config: Path | None = Field(default=None, description="Generator config path, such as cbindgen.toml.") language: str | None = Field(default=None, description="Generator language, such as C, C++, or Cython.") verify: bool = Field(default=False, description="Run a generator in verification mode when supported.") - expected_symbols: list[str] = Field(default_factory=list, alias="expected-symbols", description="Exported symbols expected in a copied library.") - header_symbol_prefix: str | None = Field( - default=None, - alias="header-symbol-prefix", - description="Expect every function in expected-headers whose name starts with this prefix to be exported.", - ) - expected_headers: list[Path] = Field(default_factory=list, alias="expected-headers", description="Header files expected to exist after build.") - expected_abi_strings: list[str] = Field( - default_factory=list, - alias="expected-abi-strings", - description="ABI version strings or macros expected in the configured headers.", - ) - validate_artifact: bool = Field( - default=False, - alias="validate", - description="Load the copied library with ctypes.CDLL after copy. Requires a library built for the host.", - ) - validation_commands: list[ValidationCommandConfig] = Field( - default_factory=list, - alias="validation-commands", - description="Project-specific validation commands to run after artifact copy.", - ) include_import_lib: bool = Field( default=False, alias="include-import-lib", @@ -656,15 +580,6 @@ class RustArtifactConfig(BaseModel): alias="library-source-features", description="Cargo features per library-source value; replaces features and disables default features for that value.", ) - pkg_config: str | None = Field(default=None, alias="pkg-config", description="pkg-config module locating this library in external mode.") - library_root: Path | None = Field( - default=None, alias="library-root", description="Prefix with lib/ and include/ for this library in external mode." - ) - python_package: str | None = Field( - default=None, - alias="python-package", - description="Installed Python package shipping this library under lib/ and include/; linked from there instead of built.", - ) import_library_destination: str | None = Field( default=None, alias="import-library-destination", @@ -707,7 +622,7 @@ def validate_inputs(cls, values: Any) -> list[str]: return [values] return [str(value) for value in values] - @field_validator("expected_symbols", "expected_abi_strings", "links", mode="before") + @field_validator("links", mode="before") @classmethod def validate_string_list(cls, values: Any) -> list[str]: if values is None: @@ -716,27 +631,7 @@ def validate_string_list(cls, values: Any) -> list[str]: return [values] return [str(value) for value in values] - @field_validator("expected_headers", mode="before") - @classmethod - def validate_path_list(cls, values: Any) -> list[Path]: - if values is None: - return [] - if isinstance(values, (str, Path)): - values = [values] - return [value if isinstance(value, Path) else Path(value) for value in values] - - @field_validator("validation_commands", mode="before") - @classmethod - def validate_validation_commands(cls, values: Any) -> list[Any]: - if values is None: - return [] - if isinstance(values, dict): - return [values] - if isinstance(values, list) and values and all(not isinstance(value, dict) for value in values): - return [{"command": values}] - return list(values) - - @field_validator("working_directory", "config", "library_root", mode="before") + @field_validator("working_directory", "config", mode="before") @classmethod def validate_optional_path(cls, path: Path | None) -> Path | None: if path is None: @@ -745,12 +640,6 @@ def validate_optional_path(cls, path: Path | None) -> Path | None: path = Path(path) return path - @model_validator(mode="after") - def validate_header_symbol_prefix(self) -> RustArtifactConfig: - if self.header_symbol_prefix is not None and not self.expected_headers: - raise ValueError(f"Artifact '{self.name}' must set expected-headers when using header-symbol-prefix.") - return self - @model_validator(mode="after") def validate_python_package(self) -> RustArtifactConfig: if self.python_package is not None and (not self.name or self.manifest is not None or self.destination is not None): @@ -1217,10 +1106,7 @@ def generate(self): return self.commands def _resolve_library_source(self) -> str: - value = environ.get("HATCH_RS_LIBRARY_SOURCE") or self.library_source - if value not in ("bundled", "external", "static", "direct"): - raise ValueError(f"Unsupported HATCH_RS_LIBRARY_SOURCE: {value}") - return value + return resolve_library_source(self.library_source, env_var="HATCH_RS_LIBRARY_SOURCE") def _linked_library_names(self, artifacts: list[RustArtifactConfig]) -> set[str]: names = set() @@ -1307,66 +1193,16 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res args.extend(("-C", f"link-arg=-Wl,-rpath,{origin}/{Path(relative).as_posix()}")) return args - def _pkg_config_variable(self, artifact: RustArtifactConfig, variable: str) -> Path: - assert artifact.pkg_config is not None - command = ["pkg-config", f"--variable={variable}", artifact.pkg_config] - try: - completed = run(command, capture_output=True, text=True, check=False) - except FileNotFoundError as error: - raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' needs pkg-config on PATH to resolve '{artifact.pkg_config}'.") from error - if completed.returncode != 0 or not completed.stdout.strip(): - raise RuntimeError( - f"Artifact '{self._artifact_label(artifact)}' pkg-config lookup failed: {shell_join(command)}: {completed.stderr.strip()}" - ) - return Path(completed.stdout.strip()) - def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: str) -> ExternalLibrary: - name = self._artifact_name(artifact) - label = self._artifact_label(artifact) root = environ.get("HATCH_RS_LIBRARY_ROOT") or (str(artifact.library_root) if artifact.library_root is not None else None) - package = artifact.python_package if self._resolved_library_source == "bundled" else None - if root: - prefix = _resolve_path(root, base=Path(self.path)) - library_dir, include_dir = prefix / "lib", prefix / "include" - elif package: - spec = find_spec(package) - if spec is None or not spec.submodule_search_locations: - raise ValueError(f"Artifact '{label}' package '{package}' is not installed in the build environment.") - prefix = Path(next(iter(spec.submodule_search_locations))) - library_dir, include_dir = prefix / "lib", prefix / "include" - elif artifact.pkg_config: - library_dir = self._pkg_config_variable(artifact, "libdir") - include_dir = self._pkg_config_variable(artifact, "includedir") - else: - conda_prefix = environ.get("PREFIX") or environ.get("CONDA_PREFIX") - if not conda_prefix: - raise ValueError( - f"Artifact '{label}' is external but has no library-root, pkg-config, HATCH_RS_LIBRARY_ROOT, PREFIX, or CONDA_PREFIX." - ) - prefix = Path(conda_prefix) / "Library" if platform == "win32" else Path(conda_prefix) - library_dir, include_dir = prefix / "lib", prefix / "include" - - shared_library = shared_library_name(name, platform=platform) - if platform == "win32": - candidates = [library_dir.parent / "bin" / shared_library, library_dir / shared_library] - link_name = name if (library_dir / f"{name}.lib").is_file() else f"{name}.dll" - elif platform == "darwin": - candidates = [library_dir / shared_library, *sorted(library_dir.glob(f"lib{name}.*.dylib"))] - link_name = name - else: - candidates = [library_dir / shared_library, *sorted(library_dir.glob(f"{shared_library}.*"))] - link_name = name - library = next((candidate for candidate in candidates if candidate.is_file()), None) - if library is None: - searched = ", ".join(str(candidate.parent) for candidate in candidates[:2]) - raise FileNotFoundError(f"Artifact '{label}' external library '{shared_library}' was not found under {searched}.") - return ExternalLibrary( - name=name, - library=library, - library_dir=library_dir, - include_dir=include_dir if include_dir.is_dir() else None, - link_name=link_name, - package=package, + return resolve_external_library( + self._artifact_name(artifact), + label=self._artifact_label(artifact), + platform=platform, + root_env_var="HATCH_RS_LIBRARY_ROOT", + root=_resolve_path(root, base=Path(self.path)) if root else None, + package=artifact.python_package if self._resolved_library_source == "bundled" else None, + pkg_config=artifact.pkg_config, ) def _plan_external_library(self, artifact: RustArtifactConfig, *, global_target: str | None) -> PlannedArtifact: @@ -1884,34 +1720,10 @@ def _process_generated_outputs(self, planned_artifact: PlannedArtifact, *, build return copied_artifacts def _validate_expected_headers(self, artifact: RustArtifactConfig) -> list[Path]: - headers = [] - for header in artifact.expected_headers: - resolved_header = _resolve_path(header, base=Path(self.path)) - if not resolved_header.exists(): - raise FileNotFoundError(f"Artifact '{self._artifact_label(artifact)}' expected header does not exist: {header}") - if not resolved_header.is_file(): - raise FileNotFoundError(f"Artifact '{self._artifact_label(artifact)}' expected header is not a file: {header}") - headers.append(resolved_header) - - if artifact.expected_abi_strings and not headers: - raise ValueError(f"Artifact '{self._artifact_label(artifact)}' must set expected-headers when using expected-abi-strings.") - - for expected in artifact.expected_abi_strings: - if not any(expected in header.read_text(errors="replace") for header in headers): - raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected ABI string was not found in headers: {expected}") - return headers + return check_headers(artifact.expected_headers, artifact.expected_abi_strings, base=Path(self.path), label=self._artifact_label(artifact)) def _header_symbols(self, artifact: RustArtifactConfig, headers: list[Path]) -> list[str]: - if artifact.header_symbol_prefix is None: - return [] - symbols = sorted( - {symbol for header in headers for symbol in header_symbols(header.read_text(errors="replace"), artifact.header_symbol_prefix)} - ) - if not symbols: - raise RuntimeError( - f"Artifact '{self._artifact_label(artifact)}' expected headers declare no functions starting with '{artifact.header_symbol_prefix}'." - ) - return symbols + return prefixed_header_symbols(headers, artifact.header_symbol_prefix, label=self._artifact_label(artifact)) def _validate_library_exports(self, planned_artifact: PlannedArtifact, copied_artifacts: list[CopiedArtifact], headers: list[Path]) -> None: artifact = planned_artifact.artifact @@ -1922,24 +1734,13 @@ def _validate_library_exports(self, planned_artifact: PlannedArtifact, copied_ar raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' has no copied library to validate.") copied_library = copied_artifacts[0] - if expected: - try: - exported = exported_symbols(copied_library.destination) - except (OSError, ValueError) as error: - raise RuntimeError( - f"Artifact '{self._artifact_label(artifact)}' could not read exported symbols from '{copied_library.distribution_path}': {error}" - ) from error - missing = [symbol for symbol in expected if symbol not in exported] - if missing: - raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected symbol was not exported: {', '.join(missing)}") - - if artifact.validate_artifact: - try: - CDLL(str(copied_library.destination)) - except OSError as error: - raise RuntimeError( - f"Artifact '{self._artifact_label(artifact)}' failed validation load check for '{copied_library.distribution_path}': {error}" - ) from error + check_exports( + copied_library.destination, + expected=expected, + load=artifact.validate_artifact, + label=self._artifact_label(artifact), + display_path=copied_library.distribution_path, + ) def _validation_tokens(self, planned_artifact: PlannedArtifact, copied_artifacts: list[CopiedArtifact], headers: list[Path]) -> dict[str, str]: artifact = planned_artifact.artifact @@ -1991,15 +1792,7 @@ def _run_validation_commands( "HATCH_RS_BUILD_ROOT": str(build_root), } ) - try: - completed = run(command, cwd=working_directory, env=environment, check=False) - except FileNotFoundError as error: - raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' validation command was not found: {command[0]}") from error - if completed.returncode != 0: - raise RuntimeError( - f"Artifact '{self._artifact_label(artifact)}' validation command failed with exit code " - f"{completed.returncode}: {shell_join(command)}" - ) + run_validation_command(command, cwd=working_directory, env=environment, label=self._artifact_label(artifact)) def _validate_artifact(self, planned_artifact: PlannedArtifact, *, build_root: Path, copied_artifacts: list[CopiedArtifact]) -> None: headers = self._validate_expected_headers(planned_artifact.artifact) @@ -2030,13 +1823,7 @@ def _write_artifact_manifest(self, *, build_root: Path) -> None: distribution_path = self._format_artifact_manifest_destination() destination = build_root / distribution_path - destination.parent.mkdir(parents=True, exist_ok=True) - payload = { - "version": 1, - "module": self.module, - "artifacts": self._artifact_manifest_records, - } - destination.write_text(dumps(payload, indent=2, sort_keys=True) + "\n") + write_artifact_manifest(destination, module=self.module, records=self._artifact_manifest_records) self._copied_artifacts.append(CopiedArtifact(source=destination, destination=destination, distribution_path=distribution_path.as_posix())) def _copy_outputs(self, planned_artifact: PlannedArtifact, *, build_root: Path) -> list[CopiedArtifact]: diff --git a/hatch_rs/symbols.py b/hatch_rs/symbols.py index 7f930cd..3f52d3b 100644 --- a/hatch_rs/symbols.py +++ b/hatch_rs/symbols.py @@ -1,172 +1,3 @@ -"""Read exported symbol names from shared libraries without loading them. - -Supports ELF, Mach-O (including fat binaries), PE, and WebAssembly so that -cross-compiled and Pyodide artifacts can be checked on any host. -""" - -from __future__ import annotations - -from pathlib import Path -from struct import Struct, unpack_from +from hatch_native.symbols import exported_symbols __all__ = ("exported_symbols",) - -_ELF_MAGIC = b"\x7fELF" -_PE_MAGIC = b"MZ" -_WASM_MAGIC = b"\x00asm" -_MACHO_MAGICS = { - b"\xcf\xfa\xed\xfe": ("<", 64), - b"\xfe\xed\xfa\xcf": (">", 64), - b"\xce\xfa\xed\xfe": ("<", 32), - b"\xfe\xed\xfa\xce": (">", 32), -} -_FAT_MAGICS = {b"\xca\xfe\xba\xbe": 32, b"\xca\xfe\xba\xbf": 64} - - -def exported_symbols(path: Path | str) -> set[str]: - """Return the names a shared library exports, as a C caller would spell them.""" - data = Path(path).read_bytes() - if data[:4] == _ELF_MAGIC: - return _elf_exports(data) - if data[:4] in _MACHO_MAGICS: - return _macho_exports(data) - if data[:4] in _FAT_MAGICS: - return _fat_exports(data) - if data[:2] == _PE_MAGIC: - return _pe_exports(data) - if data[:4] == _WASM_MAGIC: - return _wasm_exports(data) - raise ValueError(f"Unrecognized shared library format: {path}") - - -def _cstring(data: bytes, offset: int) -> str: - end = data.index(b"\x00", offset) - return data[offset:end].decode("utf-8", errors="replace") - - -def _elf_exports(data: bytes) -> set[str]: - is_64 = data[4] == 2 - endian = "<" if data[5] == 1 else ">" - if is_64: - shoff, shentsize, shnum = unpack_from(f"{endian}Q", data, 0x28)[0], *unpack_from(f"{endian}HH", data, 0x3A) - section_header = Struct(f"{endian}IIQQQQIIQQ") - symbol = Struct(f"{endian}IBBHQQ") - else: - shoff, shentsize, shnum = unpack_from(f"{endian}I", data, 0x20)[0], *unpack_from(f"{endian}HH", data, 0x2E) - section_header = Struct(f"{endian}IIIIIIIIII") - symbol = Struct(f"{endian}IIIBBH") - - sections = [section_header.unpack_from(data, shoff + index * shentsize) for index in range(shnum)] - dynsym = next((section for section in sections if section[1] == 11), None) - if dynsym is None: - raise ValueError("ELF file has no dynamic symbol table") - _, _, _, _, sym_offset, sym_size, link, _, _, entsize = dynsym - str_offset = sections[link][4] - - exported = set() - for index in range(sym_size // (entsize or symbol.size)): - fields = symbol.unpack_from(data, sym_offset + index * (entsize or symbol.size)) - if is_64: - name, info, _, shndx = fields[0], fields[1], fields[2], fields[3] - else: - name, info, shndx = fields[0], fields[3], fields[5] - if shndx == 0 or info >> 4 not in (1, 2) or name == 0: - continue - exported.add(_cstring(data, str_offset + name)) - return exported - - -def _macho_exports(data: bytes, base: int = 0) -> set[str]: - endian, bits = _MACHO_MAGICS[data[base : base + 4]] - header_size = 32 if bits == 64 else 28 - ncmds = unpack_from(f"{endian}I", data, base + 16)[0] - nlist = Struct(f"{endian}IBBHQ") if bits == 64 else Struct(f"{endian}IBBhI") - - offset = base + header_size - symtab = None - for _ in range(ncmds): - cmd, cmdsize = unpack_from(f"{endian}II", data, offset) - if cmd == 0x2: - symtab = unpack_from(f"{endian}IIII", data, offset + 8) - offset += cmdsize - if symtab is None: - raise ValueError("Mach-O file has no symbol table") - symoff, nsyms, stroff, _ = symtab - - exported = set() - for index in range(nsyms): - strx, n_type, _, _, _ = nlist.unpack_from(data, base + symoff + index * nlist.size) - if n_type & 0xE0 or not n_type & 0x01 or n_type & 0x0E != 0x0E: - continue - name = _cstring(data, base + stroff + strx) - exported.add(name.removeprefix("_")) - return exported - - -def _fat_exports(data: bytes) -> set[str]: - bits = _FAT_MAGICS[data[:4]] - narch = unpack_from(">I", data, 4)[0] - arch = Struct(">IIQQII") if bits == 64 else Struct(">IIIII") - exported = set() - for index in range(narch): - fields = arch.unpack_from(data, 8 + index * arch.size) - exported |= _macho_exports(data, base=fields[2]) - return exported - - -def _pe_exports(data: bytes) -> set[str]: - pe_offset = unpack_from(" int: - for _, virtual_size, virtual_address, raw_size, raw_pointer, *_ in sections: - if virtual_address <= rva < virtual_address + max(virtual_size, raw_size): - return rva - virtual_address + raw_pointer - raise ValueError(f"PE RVA {rva:#x} is not inside any section") - - export_offset = file_offset(export_rva) - nnames, _, names_rva = unpack_from(" tuple[int, int]: - result = shift = 0 - while True: - byte = data[offset] - offset += 1 - result |= (byte & 0x7F) << shift - shift += 7 - if not byte & 0x80: - return result, offset - - -def _wasm_exports(data: bytes) -> set[str]: - offset = 8 - while offset < len(data): - section_id = data[offset] - size, offset = _leb128(data, offset + 1) - if section_id != 7: - offset += size - continue - count, offset = _leb128(data, offset) - exported = set() - for _ in range(count): - length, offset = _leb128(data, offset) - exported.add(data[offset : offset + length].decode("utf-8", errors="replace")) - offset += length - _, offset = _leb128(data, offset + 1) - return exported - return set() diff --git a/hatch_rs/tests/test_structs.py b/hatch_rs/tests/test_structs.py index 3f4ce19..a2efd7d 100644 --- a/hatch_rs/tests/test_structs.py +++ b/hatch_rs/tests/test_structs.py @@ -897,7 +897,7 @@ def _plan_with_header(tmp_path, header_text, **artifact): def test_build_plan_expects_every_header_symbol(tmp_path, monkeypatch): - monkeypatch.setattr("hatch_rs.structs.exported_symbols", lambda path: {"project_ffi_answer", "project_ffi_free"}) + monkeypatch.setattr("hatch_native.validation.exported_symbols", lambda path: {"project_ffi_answer", "project_ffi_free"}) plan = _plan_with_header( tmp_path, "int project_ffi_answer(void);\nvoid project_ffi_free(void *p);\n", @@ -907,7 +907,7 @@ def test_build_plan_expects_every_header_symbol(tmp_path, monkeypatch): def test_build_plan_missing_header_symbol_fails_clearly(tmp_path, monkeypatch): - monkeypatch.setattr("hatch_rs.structs.exported_symbols", lambda path: {"project_ffi_answer"}) + monkeypatch.setattr("hatch_native.validation.exported_symbols", lambda path: {"project_ffi_answer"}) plan = _plan_with_header( tmp_path, "int project_ffi_answer(void);\nvoid project_ffi_free(void *p);\n", @@ -918,7 +918,7 @@ def test_build_plan_missing_header_symbol_fails_clearly(tmp_path, monkeypatch): def test_build_plan_header_without_prefixed_symbols_fails_clearly(tmp_path, monkeypatch): - monkeypatch.setattr("hatch_rs.structs.exported_symbols", lambda path: set()) + monkeypatch.setattr("hatch_native.validation.exported_symbols", lambda path: set()) plan = _plan_with_header(tmp_path, "int other_answer(void);\n", **{"header-symbol-prefix": "project_ffi_"}) with pytest.raises(RuntimeError, match="no functions starting with 'project_ffi_'"): plan._copy_outputs(plan._artifact_plans[0], build_root=tmp_path) diff --git a/hatch_rs/tests/test_symbols.py b/hatch_rs/tests/test_symbols.py deleted file mode 100644 index 3416bc4..0000000 --- a/hatch_rs/tests/test_symbols.py +++ /dev/null @@ -1,31 +0,0 @@ -import _ctypes - -import pytest - -from hatch_rs.symbols import exported_symbols - - -def test_host_extension_module_exports_init_symbol(): - assert "PyInit__ctypes" in exported_symbols(_ctypes.__file__) - - -def test_wasm_export_section(tmp_path): - # (module (func $f (export "demo_answer") (result i32) i32.const 42) (memory (export "memory") 1)) - module = bytes.fromhex( - "0061736d01000000" # magic, version - "010501600001 7f" # type section: () -> i32 - "03020100" # function section: one function of type 0 - "0503010001" # memory section: min 1 page - "071802 0b64656d6f5f616e737765720000 066d656d6f72790200" # export section: demo_answer (func 0), memory (mem 0) - "0a06010400412a0b" # code section - ) - wasm = tmp_path / "demo.wasm" - wasm.write_bytes(module) - assert exported_symbols(wasm) == {"demo_answer", "memory"} - - -def test_unknown_format_fails_clearly(tmp_path): - other = tmp_path / "other.so" - other.write_bytes(b"not a library") - with pytest.raises(ValueError, match="Unrecognized shared library format"): - exported_symbols(other) diff --git a/pyproject.toml b/pyproject.toml index 68968d4..f3edfaf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,6 +34,7 @@ classifiers = [ ] dependencies = [ + "hatch-native>=0.1.0,<0.2", "hatchling>=1.20", "packaging", "pydantic",