Skip to content

new_backend

Scaffold a new circuit backend (stub, export, and test).

BackendNames dataclass

Derived names for a scaffolded circuit backend.

Source code in shadowsim/cli/new_backend.py
@dataclass(frozen=True)
class BackendNames:
    """Derived names for a scaffolded circuit backend."""

    base_name: str
    class_name: str
    snake_name: str
    module_name: str
    backend_id: str

    @property
    def stub_filename(self) -> str:
        """Return the stub module filename."""
        return f"{self.module_name}.py"

    @property
    def test_filename(self) -> str:
        """Return the scaffolded test filename."""
        return f"test_{self.snake_name}_backend.py"

stub_filename property

stub_filename: str

Return the stub module filename.

test_filename property

test_filename: str

Return the scaffolded test filename.

ScaffoldError

Bases: Exception

Raised when backend scaffolding cannot proceed.

Source code in shadowsim/cli/new_backend.py
class ScaffoldError(Exception):
    """Raised when backend scaffolding cannot proceed."""

pascal_to_snake

pascal_to_snake(name: str) -> str

Convert a PascalCase name to snake_case.

Source code in shadowsim/cli/new_backend.py
def pascal_to_snake(name: str) -> str:
    """Convert a PascalCase name to snake_case."""
    return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()

normalize_base_name

normalize_base_name(raw: str) -> str

Validate PascalCase input and strip a trailing backend suffix.

CircuitBackend is removed first, then Backend, so Cirq and CirqCircuitBackend both become Cirq.

Raises:

  • ScaffoldError –

    raw is empty, not PascalCase, or a reserved name.

Source code in shadowsim/cli/new_backend.py
def normalize_base_name(raw: str) -> str:
    """Validate PascalCase input and strip a trailing backend suffix.

    ``CircuitBackend`` is removed first, then ``Backend``, so ``Cirq`` and
    ``CirqCircuitBackend`` both become ``Cirq``.

    Raises:
        ScaffoldError: ``raw`` is empty, not PascalCase, or a reserved name.
    """
    name = raw.strip()
    if not name:
        raise ScaffoldError("Name must not be empty")
    if any(ch.isspace() for ch in name):
        raise ScaffoldError("Name must not contain spaces")
    if "_" in name or "-" in name:
        raise ScaffoldError("Name must be PascalCase with no underscores or hyphens")
    if not _PASCAL_RE.fullmatch(name):
        raise ScaffoldError("Name must be PascalCase (start with an uppercase letter; letters and digits only)")
    if name.endswith("CircuitBackend") and name != "CircuitBackend":
        name = name[: -len("CircuitBackend")]
    elif name.endswith("Backend") and name != "Backend":
        name = name[: -len("Backend")]
    # Defensive: unreachable after _PASCAL_RE, kept for clear errors if the regex changes.
    if not name or not _PASCAL_RE.fullmatch(name):  # pragma: no cover
        raise ScaffoldError("Name must include a PascalCase prefix before 'Backend'")
    if name in _RESERVED:
        raise ScaffoldError(f"Name {name!r} is reserved")
    return name

normalize_kind

normalize_kind(raw: str) -> Kind

Validate a backend kind.

expectation stores no shot budget, the same shape as the NumPy backend. sampling stores shots, the same shape as the Aer backend.

Raises:

Source code in shadowsim/cli/new_backend.py
def normalize_kind(raw: str) -> Kind:
    """Validate a backend kind.

    ``expectation`` stores no shot budget, the same shape as the NumPy backend.
    ``sampling`` stores ``shots``, the same shape as the Aer backend.

    Raises:
        ScaffoldError: ``raw`` is not ``expectation`` or ``sampling``.
    """
    kind = raw.strip().lower()
    if kind == "expectation":
        return "expectation"
    if kind == "sampling":
        return "sampling"
    raise ScaffoldError("Kind must be 'expectation' or 'sampling'")

derive_names

derive_names(raw: str) -> BackendNames

Derive class, module, and catalog id from a PascalCase name.

The catalog id is the class name with CircuitBackend and then Backend removed, lowercased. WaveMatrix becomes wavematrix.

Source code in shadowsim/cli/new_backend.py
def derive_names(raw: str) -> BackendNames:
    """Derive class, module, and catalog id from a PascalCase name.

    The catalog id is the class name with ``CircuitBackend`` and then
    ``Backend`` removed, lowercased. ``WaveMatrix`` becomes ``wavematrix``.
    """
    base = normalize_base_name(raw)
    snake = pascal_to_snake(base)
    return BackendNames(
        base_name=base,
        class_name=f"{base}CircuitBackend",
        snake_name=snake,
        module_name=snake,
        backend_id=base.lower(),
    )

default_repo_root

default_repo_root() -> Path

Resolve the repository root from the working directory or package location.

Raises:

  • ScaffoldError –

    Neither location contains shadowsim/backends.

Source code in shadowsim/cli/new_backend.py
def default_repo_root() -> Path:
    """Resolve the repository root from the working directory or package location.

    Raises:
        ScaffoldError: Neither location contains ``shadowsim/backends``.
    """
    cwd = Path.cwd()
    if (cwd / "shadowsim" / "backends").is_dir():
        return cwd
    package_root = Path(__file__).resolve().parents[1]
    repo_root = package_root.parent
    if (repo_root / "shadowsim" / "backends").is_dir():
        return repo_root
    raise ScaffoldError("Could not find the ShadowSim.py repository root. Run this command from the cloned repository.")

stub_path

stub_path(repo_root: Path, names: BackendNames) -> Path

Return the path for the new backend module.

Source code in shadowsim/cli/new_backend.py
def stub_path(repo_root: Path, names: BackendNames) -> Path:
    """Return the path for the new backend module."""
    return repo_root / "shadowsim" / "backends" / names.stub_filename

test_path

test_path(repo_root: Path, names: BackendNames) -> Path

Return the path for the scaffolded backend test.

Source code in shadowsim/cli/new_backend.py
def test_path(repo_root: Path, names: BackendNames) -> Path:
    """Return the path for the scaffolded backend test."""
    return repo_root / "test" / "backends" / names.test_filename

init_path

init_path(repo_root: Path) -> Path

Return the backends package __init__.py path.

Source code in shadowsim/cli/new_backend.py
def init_path(repo_root: Path) -> Path:
    """Return the backends package ``__init__.py`` path."""
    return repo_root / "shadowsim" / "backends" / "__init__.py"

check_collisions

check_collisions(
    repo_root: Path, names: BackendNames
) -> None

Raise if the stub, test, or export already exists for this name.

Raises:

  • ScaffoldError –

    A module, test, or export for names is already present, or the backends package init is missing.

Source code in shadowsim/cli/new_backend.py
def check_collisions(repo_root: Path, names: BackendNames) -> None:
    """Raise if the stub, test, or export already exists for this name.

    Raises:
        ScaffoldError: A module, test, or export for ``names`` is already present,
            or the backends package init is missing.
    """
    stub = stub_path(repo_root, names)
    test = test_path(repo_root, names)
    init = init_path(repo_root)
    problems: list[str] = []

    if stub.exists():
        problems.append(f"backend module already exists: {stub}")
    if test.exists():
        problems.append(f"test file already exists: {test}")
    if not init.exists():
        problems.append(f"backends package init is missing: {init}")
    else:
        init_text = init.read_text(encoding="utf-8")
        conflict = _registration_conflict(init_text, init, names)
        if conflict is not None:
            problems.append(conflict)

    if problems:
        raise ScaffoldError("Name already exists:\n- " + "\n- ".join(problems))

render_stub

render_stub(
    names: BackendNames, *, kind: str = "expectation"
) -> str

Return the source for a new backend stub module.

expectation stores no shot budget. sampling stores shots.

Raises:

Source code in shadowsim/cli/new_backend.py
def render_stub(names: BackendNames, *, kind: str = "expectation") -> str:
    """Return the source for a new backend stub module.

    ``expectation`` stores no shot budget. ``sampling`` stores ``shots``.

    Raises:
        ScaffoldError: ``kind`` is not ``expectation`` or ``sampling``.
    """
    resolved = normalize_kind(kind)
    if resolved == "sampling":
        return _render_sampling_stub(names)
    return _render_expectation_stub(names)

render_test

render_test(
    names: BackendNames, *, kind: str = "expectation"
) -> str

Return the source for a backend test that passes while the stub raises.

Raises:

Source code in shadowsim/cli/new_backend.py
def render_test(names: BackendNames, *, kind: str = "expectation") -> str:
    """Return the source for a backend test that passes while the stub raises.

    Raises:
        ScaffoldError: ``kind`` is not ``expectation`` or ``sampling``.
    """
    resolved = normalize_kind(kind)
    if resolved == "sampling":
        return _render_sampling_test(names)
    return _render_expectation_test(names)

patch_init_file

patch_init_file(path: Path, names: BackendNames) -> None

Register the new backend in _EXPORTS, TYPE_CHECKING, and __all__.

The extra is None. _EXPORTS and the type-checking import are ordered by module name. __all__ is ordered by class name.

Raises:

  • ScaffoldError –

    names is already registered, or a required block is missing or unclosed.

Source code in shadowsim/cli/new_backend.py
def patch_init_file(path: Path, names: BackendNames) -> None:
    """Register the new backend in ``_EXPORTS``, ``TYPE_CHECKING``, and ``__all__``.

    The extra is ``None``. ``_EXPORTS`` and the type-checking import are ordered
    by module name. ``__all__`` is ordered by class name.

    Raises:
        ScaffoldError: ``names`` is already registered, or a required block is
            missing or unclosed.
    """
    content = path.read_text(encoding="utf-8")
    conflict = _registration_conflict(content, path, names)
    if conflict is not None:
        raise ScaffoldError(conflict)
    exports_start, exports_end = _delimited_span(content, path, _EXPORTS_START_RE, "}", "_EXPORTS map")
    exports = _insert_sorted(
        content[exports_start:exports_end],
        _export_line(names),
        list(_EXPORT_ENTRY_RE.finditer(content[exports_start:exports_end])),
        names.module_name,
        "module",
    )
    content = content[:exports_start] + exports + content[exports_end:]
    typing_start, typing_end = _type_checking_span(content, path)
    typing = _insert_sorted(
        content[typing_start:typing_end],
        _import_line(names),
        list(_TYPE_IMPORT_RE.finditer(content[typing_start:typing_end])),
        names.module_name,
        "module",
    )
    content = content[:typing_start] + typing + content[typing_end:]
    all_start, all_end = _delimited_span(content, path, _ALL_START_RE, "]", "__all__ list")
    exported = _insert_sorted(
        content[all_start:all_end],
        _all_line(names),
        list(_ALL_ENTRY_RE.finditer(content[all_start:all_end])),
        names.class_name,
        "name",
    )
    path.write_text(content[:all_start] + exported + content[all_end:], encoding="utf-8")

create_backend

create_backend(
    raw_name: str,
    *,
    repo_root: Path | None = None,
    kind: str = "expectation",
) -> BackendNames

Validate, check collisions, and write the stub, export, and test.

kind="expectation" writes a backend with no shots attribute. kind="sampling" writes a backend that stores shots. On failure the stub and test are removed and __init__.py is restored.

Raises:

  • ScaffoldError –

    The name or kind is invalid, or a file already exists.

Source code in shadowsim/cli/new_backend.py
def create_backend(
    raw_name: str,
    *,
    repo_root: Path | None = None,
    kind: str = "expectation",
) -> BackendNames:
    """Validate, check collisions, and write the stub, export, and test.

    ``kind="expectation"`` writes a backend with no ``shots`` attribute.
    ``kind="sampling"`` writes a backend that stores ``shots``. On failure the
    stub and test are removed and ``__init__.py`` is restored.

    Raises:
        ScaffoldError: The name or kind is invalid, or a file already exists.
    """
    names = derive_names(raw_name)
    resolved = normalize_kind(kind)
    root = repo_root if repo_root is not None else default_repo_root()
    check_collisions(root, names)

    stub = stub_path(root, names)
    test = test_path(root, names)
    init = init_path(root)

    test.parent.mkdir(parents=True, exist_ok=True)
    init_before = init.read_text(encoding="utf-8")
    stub.write_text(render_stub(names, kind=resolved), encoding="utf-8")
    try:
        patch_init_file(init, names)
        test.write_text(render_test(names, kind=resolved), encoding="utf-8")
    except Exception:
        if stub.exists():
            stub.unlink()
        if init.read_text(encoding="utf-8") != init_before:
            init.write_text(init_before, encoding="utf-8")
        if test.exists():
            test.unlink()
        raise

    return names

build_parser

build_parser() -> ArgumentParser

Build the CLI argument parser.

Source code in shadowsim/cli/new_backend.py
def build_parser() -> argparse.ArgumentParser:
    """Build the CLI argument parser."""
    parser = argparse.ArgumentParser(
        prog="new-backend",
        description="Scaffold a new ShadowSim circuit backend.",
    )
    parser.add_argument(
        "--name",
        help="PascalCase backend name (e.g. Cirq). Prompted if omitted.",
    )
    parser.add_argument(
        "--kind",
        choices=["expectation", "sampling"],
        help="expectation stores no shot budget; sampling stores shots. Prompted if omitted.",
    )
    return parser

main

main(argv: list[str] | None = None) -> int

Run the new-backend scaffolding CLI.

Source code in shadowsim/cli/new_backend.py
def main(argv: list[str] | None = None) -> int:
    """Run the new-backend scaffolding CLI."""
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        raw_name, kind = _scaffold_choices(args)
        names = create_backend(raw_name, kind=kind)
    except ScaffoldError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1

    print(f"Created {names.class_name}")
    print(f"  kind:   {kind}")
    print(f"  id:     {names.backend_id}")
    print(f"  module: shadowsim/backends/{names.stub_filename}")
    print("  export: shadowsim/backends/__init__.py")
    print(f"  test:   test/backends/{names.test_filename}")
    print("Next: implement run_counts, z_expectations, and x_expectations (look for TODO).")
    return 0