diff --git a/src/cpp/bindings/python/bind_ops_geometry.cpp b/src/cpp/bindings/python/bind_ops_geometry.cpp index aaab1cf4..3e1f45ae 100644 --- a/src/cpp/bindings/python/bind_ops_geometry.cpp +++ b/src/cpp/bindings/python/bind_ops_geometry.cpp @@ -19,6 +19,11 @@ namespace { using namespace scad; +using scad::pybind::Angle; +using scad::pybind::Direction3; +using scad::pybind::Length; +using scad::pybind::Point3; +using scad::pybind::Vector3; using namespace pybind11::literals; // Defaults as Python tuples, so help() shows (0, 0, 1) like the Python SDK. @@ -196,7 +201,7 @@ void bind_wires_and_faces(py::module_& m) { void bind_primitives(py::module_& m) { m.def( "make_box_rsolid", - [](const Scalar& width, const Scalar& height, const Scalar& depth, const Scalar3& center, + [](const Length& width, const Length& height, const Length& depth, const Point3& center, OptionalString tag_prefix, OptionalString result_tag, OptionalString bottom, OptionalString top, OptionalString front, OptionalString back, OptionalString left, OptionalString right) { return make_box_rsolid(width, height, depth, center, @@ -231,7 +236,7 @@ void bind_primitives(py::module_& m) { }; m.def( "make_cylinder_rsolid", - [axial_tags](const Scalar& radius, const Scalar& height, const Scalar3& center, const Scalar3& axis, + [axial_tags](const Length& radius, const Length& height, const Point3& center, const Direction3& axis, OptionalString tag_prefix, OptionalString result_tag, OptionalString start_face, OptionalString end_face, OptionalString side_face, OptionalString start_edge, OptionalString end_edge, OptionalString seam_edge) { diff --git a/src/cpp/bindings/python/bindings.hpp b/src/cpp/bindings/python/bindings.hpp index 352892b1..cebcbfec 100644 --- a/src/cpp/bindings/python/bindings.hpp +++ b/src/cpp/bindings/python/bindings.hpp @@ -161,3 +161,6 @@ struct type_caster { }; } // namespace pybind11::detail + +// Length, Angle, Point3, Direction3, Vector3: the meaning of a parameter, written in its type. +#include "semantic_types.hpp" // IWYU pragma: export diff --git a/src/cpp/bindings/python/semantic_types.hpp b/src/cpp/bindings/python/semantic_types.hpp new file mode 100644 index 00000000..89bb9804 --- /dev/null +++ b/src/cpp/bindings/python/semantic_types.hpp @@ -0,0 +1,99 @@ +// What a parameter means, in the signature itself: the Python-facing types of the bound operations. +// +// A binding declares `const Length& radius` instead of `const Scalar& radius`; the value converts to the Scalar the +// kernel takes (so the body of the binding does not change), and the signature pybind writes reads `radius: Length`. +// The names are the typing aliases of `simplecadapi.types`, so the stubs, the API pages and the operation catalog +// (`simplecadapi.catalog`) all read the meaning from the one place it is written: the binding. +// +// Length a distance (mm by default; a `scad.var` with a length unit) float | Expr +// Angle an angle in degrees float | Expr +// Point3 a position (x, y, z) 3 x (float | Expr) +// Direction3 a direction or an axis (its length does not matter) 3 x (float | Expr) +// Vector3 an offset (direction and length) 3 x (float | Expr) +// +// Plain `Scalar` stays for numbers without a unit (a factor, a tolerance); plain `Scalar3` for anything else. +#pragma once + +#include +#include + +#include + +#include "scad/core/scalar.hpp" + +namespace scad::pybind { + +template +struct Quantity { + Scalar value; + operator const Scalar&() const { + return value; + } // NOLINT(google-explicit-constructor): the binding passes it on as is +}; + +template +struct Quantity3 { + std::array value; + operator const std::array&() const { return value; } // NOLINT(google-explicit-constructor) +}; + +struct LengthTag { + static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Length"); +}; +struct AngleTag { + static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Angle"); +}; +struct PointTag { + static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Point3"); +}; +struct DirectionTag { + static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Direction3"); +}; +struct VectorTag { + static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Vector3"); +}; + +using Length = Quantity; +using Angle = Quantity; +using Point3 = Quantity3; +using Direction3 = Quantity3; +using Vector3 = Quantity3; + +} // namespace scad::pybind + +namespace pybind11::detail { + +// Loads and casts exactly as Scalar does; only the name in the signature differs. +template +struct type_caster> { + PYBIND11_TYPE_CASTER(scad::pybind::Quantity, Tag::name); + + bool load(handle src, bool convert) { + make_caster inner; + if (!inner.load(src, convert)) + return false; + value.value = cast_op(std::move(inner)); + return true; + } + static handle cast(const scad::pybind::Quantity& q, return_value_policy policy, handle parent) { + return make_caster::cast(q.value, policy, parent); + } +}; + +template +struct type_caster> { + PYBIND11_TYPE_CASTER(scad::pybind::Quantity3, Tag::name); + + bool load(handle src, bool convert) { + make_caster> inner; + if (!inner.load(src, convert)) + return false; + value.value = cast_op&&>(std::move(inner)); + return true; + } + static handle cast(const scad::pybind::Quantity3& q, return_value_policy policy, handle parent) { + return make_caster>::cast(q.value, policy, parent); + } +}; + +} // namespace pybind11::detail diff --git a/src/simplecadapi/catalog.py b/src/simplecadapi/catalog.py new file mode 100644 index 00000000..a1d4fd6d --- /dev/null +++ b/src/simplecadapi/catalog.py @@ -0,0 +1,290 @@ +"""The operation catalog: every public operation, its parameters and what they mean, read from the signatures. + +Nothing here is written by hand. The bound operations carry their Python signature (pybind writes it as the first line of +the native docstring, with the semantic types of :mod:`simplecadapi.types`); the standard library's operations are Python +functions with the same annotations. The catalog parses both, so a GUI, an agent or the API pages get the same answer: + + >>> from simplecadapi import catalog + >>> op = catalog.operation("make_cylinder_rsolid") + >>> [(p.name, p.kind) for p in op.params][:4] + [('radius', 'length'), ('height', 'length'), ('bottom_face_center', 'point3'), ('axis', 'direction3')] + +A parameter's ``kind`` is one of: the meanings of :mod:`simplecadapi.types` (``length``, ``angle``, ``point3``, +``direction3``, ``vector3``, ``count``), ``number`` (a unitless ``float | Expr``), ``int``, ``bool``, ``text``, ``enum`` +(``Literal[...]``, with ``choices``), a value type (``solid``, ``face``, ``wire``, ``edge``, ``vertex``, ``shell``, +``shape``, ``sketch``, ``part``, ``assembly``, ...), ``query`` (a ``ql`` selection), ``points`` / ``numbers`` (sequences), +or ``unknown`` when the signature says no more than ``object``. ``many`` marks a sequence of the kind, ``optional`` a +``None`` default. +""" + +from __future__ import annotations + +import ast +import importlib +import inspect +import re +from dataclasses import asdict, dataclass, field +from functools import lru_cache +from typing import Any, Callable + +from .types import MEANINGS + +_OP_NAME = re.compile(r"^[a-z][a-z0-9_]*_r[a-z]+$") +STD_MODULES = ("simplecadapi.std.gear", "simplecadapi.std.fastener", "simplecadapi.std.chain", "simplecadapi.std.bearing") +"""The standard-library modules whose ``*_r`` functions are operations too.""" + +_VALUE_KINDS = { + "Solid": "solid", + "Face": "face", + "Wire": "wire", + "Edge": "edge", + "Vertex": "vertex", + "Shell": "shell", + "Compound": "compound", + "AnyShape": "shape", + "Shape": "shape", + "Sketch": "sketch", + "SketchRef": "sketch_ref", + "Part": "part", + "Assembly": "assembly", + "Component": "component", + "Connector": "connector", + "ConnectorRef": "connector_ref", + "Placement": "placement", + "Material": "material", + "Query": "query", + "ShapeSelector": "query", + "Vec3": "vector3", + "SketchPosition": "sketch_ref", +} + + +@dataclass(frozen=True) +class Param: + name: str + kind: str + type: str + """The type as the signature writes it (shortened: no module paths).""" + default: Any = None + has_default: bool = False + keyword_only: bool = False + many: bool = False + optional: bool = False + choices: tuple[str, ...] = () + + +@dataclass(frozen=True) +class Operation: + name: str + module: str + """Where to import it from (``simplecadapi`` or a standard-library module).""" + returns: str + """The kind of the result (``solid``, ``face``, ``solids`` for a list ...).""" + summary: str + params: tuple[Param, ...] = field(default_factory=tuple) + + def to_dict(self) -> dict[str, Any]: + out = asdict(self) + out["params"] = [asdict(p) for p in self.params] + return out + + +# ---- types ------------------------------------------------------------------------------------------------------------- + + +def _short(text: str) -> str: + """Drop module paths: ``simplecadapi._cpp._native.Solid`` -> ``Solid``, ``collections.abc.Sequence`` -> ``Sequence``.""" + return re.sub(r"\b(?:[A-Za-z_][\w]*\.)+([A-Za-z_]\w*)", r"\1", text) + + +def _split_top(text: str, sep: str) -> list[str]: + parts, depth, start = [], 0, 0 + for i, ch in enumerate(text): + if ch in "[(": + depth += 1 + elif ch in "])": + depth -= 1 + elif ch == sep and depth == 0: + parts.append(text[start:i].strip()) + start = i + 1 + parts.append(text[start:].strip()) + return [p for p in parts if p] + + +def classify(type_text: str) -> dict[str, Any]: + """The kind of a parameter from its (shortened) type text: ``{kind, many, optional, choices}``.""" + text = _short(type_text).strip() + optional = False + union = _split_top(text, "|") + if "None" in union: + optional = True + union = [u for u in union if u != "None"] + if not union: + return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} + text = " | ".join(union) + annotated = re.fullmatch(r"Annotated\[(.*)\]", text) + if annotated: + inner, *meta = _split_top(annotated.group(1), ",") + if any("FixedSize(3)" in m for m in meta): + return {"kind": "point3", "many": False, "optional": optional, "choices": ()} + for m in meta: + word = m.strip("'\" ") + if word in MEANINGS.values(): + return {"kind": word, "many": False, "optional": optional, "choices": ()} + text = inner + literal = re.fullmatch(r"Literal\[(.*)\]", text) + if literal: + choices = tuple(c.strip().strip("'\"") for c in _split_top(literal.group(1), ",")) + return {"kind": "enum", "many": False, "optional": optional, "choices": choices} + if text in MEANINGS: + return {"kind": MEANINGS[text], "many": False, "optional": optional, "choices": ()} + sequence = re.fullmatch(r"(?:Sequence|list|List|tuple|Iterable)\[(.*)\]", text) + if sequence: + inner = classify(_split_top(sequence.group(1), ",")[0]) + kind = inner["kind"] + if kind in ("number", "length", "angle"): + return {"kind": "numbers", "many": False, "optional": optional, "choices": ()} + if kind in ("point3", "vector3", "direction3"): + return {"kind": "points", "many": False, "optional": optional, "choices": ()} + return {"kind": kind, "many": True, "optional": optional, "choices": inner["choices"]} + names = [u.strip() for u in _split_top(text, "|")] + if set(names) <= {"float", "Expr", "SupportsFloat", "SupportsIndex", "int"} and {"float", "SupportsFloat"} & set(names): + return {"kind": "number", "many": False, "optional": optional, "choices": ()} + if set(names) <= {"int", "SupportsInt", "SupportsIndex"}: + return {"kind": "int", "many": False, "optional": optional, "choices": ()} + if names == ["bool"]: + return {"kind": "bool", "many": False, "optional": optional, "choices": ()} + if names == ["str"]: + return {"kind": "text", "many": False, "optional": optional, "choices": ()} + if "SketchRef" in names: # a point or entity of the sketch, by reference or id (a position too, where allowed) + return {"kind": "sketch_ref", "many": False, "optional": optional, "choices": ()} + kinds = {_VALUE_KINDS.get(n) for n in names} + if None not in kinds: + kind = kinds.pop() if len(kinds) == 1 else "shape" if kinds <= {"solid", "face", "wire", "edge", "vertex", "shell", "compound", "shape"} else "|".join(sorted(kinds)) + return {"kind": kind, "many": False, "optional": optional, "choices": ()} + return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} + + +def _returns(type_text: str) -> str: + info = classify(type_text) + if info["many"]: + return f"{info['kind']}s" + text = _short(type_text).strip() + if text in ("list", "List"): + return "list" + return info["kind"] if info["kind"] != "unknown" else text or "unknown" + + +# ---- signatures -------------------------------------------------------------------------------------------------------- + + +def _native_signature(fn: Callable[..., Any]) -> str | None: + """The ``name(params) -> ret`` line pybind writes first in a bound function's docstring.""" + target = getattr(fn, "__wrapped__", fn) + doc = getattr(target, "__doc__", None) or "" + first = doc.lstrip().splitlines()[0] if doc.strip() else "" + return first if "(" in first and first.endswith(tuple("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]")) else None + + +def _summary(fn: Callable[..., Any]) -> str: + doc = inspect.getdoc(fn) or "" + lines = doc.splitlines() + if lines and _native_signature(fn) and lines[0].startswith(fn.__name__ + "("): + lines = lines[1:] + text = "\n".join(lines).strip() + return text.split("\n\n")[0].replace("\n", " ").strip() + + +def _parse_native(line: str) -> tuple[list[dict[str, Any]], str]: + """Params and return type from a pybind signature line (parsed as a Python ``def``).""" + source = re.sub(r"<[^<>]*>", "None", line) # defaults pybind cannot print: + tree = ast.parse(f"def {source}: pass") + fn = tree.body[0] + assert isinstance(fn, ast.FunctionDef) + args = fn.args + out: list[dict[str, Any]] = [] + positional = args.posonlyargs + args.args + defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults) + for arg, default in zip(positional, defaults): + out.append(_param_from_ast(arg, default, keyword_only=False)) + for arg, default in zip(args.kwonlyargs, args.kw_defaults): + out.append(_param_from_ast(arg, default, keyword_only=True)) + returns = ast.unparse(fn.returns) if fn.returns is not None else "" + return out, returns + + +def _param_from_ast(arg: ast.arg, default: ast.expr | None, *, keyword_only: bool) -> dict[str, Any]: + type_text = ast.unparse(arg.annotation) if arg.annotation is not None else "object" + value: Any = None + if default is not None: + try: + value = ast.literal_eval(default) + except ValueError: + value = ast.unparse(default) + return {"name": arg.arg, "type": _short(type_text), "default": value, "has_default": default is not None, "keyword_only": keyword_only} + + +def _parse_python(fn: Callable[..., Any]) -> tuple[list[dict[str, Any]], str]: + sig = inspect.signature(fn) + out = [] + for p in sig.parameters.values(): + if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD): + continue + annotation = p.annotation + type_text = "object" if annotation is p.empty else (annotation if isinstance(annotation, str) else inspect.formatannotation(annotation)) + has_default = p.default is not p.empty + out.append({"name": p.name, "type": _short(str(type_text)), "default": p.default if has_default else None, + "has_default": has_default, "keyword_only": p.kind == p.KEYWORD_ONLY}) + ret = sig.return_annotation + return out, "" if ret is sig.empty else _short(ret if isinstance(ret, str) else inspect.formatannotation(ret)) + + +def describe(fn: Callable[..., Any], module: str) -> Operation: + """The catalog entry of one operation.""" + line = _native_signature(fn) + raw, returns = _parse_native(line) if line else _parse_python(fn) + params = [] + for item in raw: + info = classify(item["type"]) + params.append(Param(name=item["name"], kind=info["kind"], type=item["type"], default=item["default"], + has_default=item["has_default"], keyword_only=item["keyword_only"], many=info["many"], + optional=info["optional"] or (item["has_default"] and item["default"] is None), + choices=info["choices"])) + return Operation(name=fn.__name__ if hasattr(fn, "__name__") else str(fn), module=module, returns=_returns(returns), + summary=_summary(fn), params=tuple(params)) + + +# ---- the catalog ------------------------------------------------------------------------------------------------------- + + +@lru_cache(maxsize=1) +def operations() -> tuple[Operation, ...]: + """Every public operation: the ``*_r`` functions of ``simplecadapi`` and of the standard library, by name.""" + import simplecadapi + + found: dict[str, Operation] = {} + for name in sorted(simplecadapi.__all__): + if _OP_NAME.match(name) and callable(getattr(simplecadapi, name, None)): + found[name] = describe(getattr(simplecadapi, name), "simplecadapi") + for module_name in STD_MODULES: + module = importlib.import_module(module_name) + for name in sorted(dir(module)): + fn = getattr(module, name) + if _OP_NAME.match(name) and callable(fn) and getattr(fn, "__module__", "") == module_name and name not in found: + found[name] = describe(fn, module_name) + return tuple(found.values()) + + +def operation(name: str) -> Operation: + for op in operations(): + if op.name == name: + return op + raise KeyError(f"no operation {name!r} in the catalog") + + +def catalog_dict() -> dict[str, Any]: + """The whole catalog as plain data (what ``sca ops --json`` prints and the editor serves).""" + return {"version": 1, "operations": [op.to_dict() for op in operations()]} + + +__all__ = ["Operation", "Param", "STD_MODULES", "catalog_dict", "classify", "describe", "operation", "operations"] diff --git a/src/simplecadapi/types.py b/src/simplecadapi/types.py new file mode 100644 index 00000000..948d2210 --- /dev/null +++ b/src/simplecadapi/types.py @@ -0,0 +1,43 @@ +"""What an operation's parameters mean, as types. + +The bound operations declare these in their signatures (``radius: Length``, ``axis: Direction3``), and so do the Python +operations of the standard library; the stubs, the API pages and the operation catalog (:mod:`simplecadapi.catalog`) read +the meaning from there. Each alias is the type a caller may pass (``Annotated`` only adds the meaning): + +- ``Length``: a distance, mm unless a ``scad.var`` says otherwise. +- ``Angle``: an angle in degrees. +- ``Point3``: a position ``(x, y, z)``. +- ``Direction3``: a direction or an axis; its length does not matter. +- ``Vector3``: an offset; direction and length both matter. +- ``Count``: a whole number of things (copies, teeth, segments). + +A plain ``float | Expr`` is a number without a unit (a factor, a tolerance). +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Annotated, Union + +from simplecadapi._cpp import Expr + +_Number = Union[float, Expr] + +Length = Annotated[_Number, "length"] +Angle = Annotated[_Number, "angle"] +Point3 = Annotated[Sequence[_Number], "point3"] +Direction3 = Annotated[Sequence[_Number], "direction3"] +Vector3 = Annotated[Sequence[_Number], "vector3"] +Count = Annotated[int, "count"] + +MEANINGS: dict[str, str] = { + "Length": "length", + "Angle": "angle", + "Point3": "point3", + "Direction3": "direction3", + "Vector3": "vector3", + "Count": "count", +} +"""The type names a signature may carry, and the meaning each stands for (what :mod:`simplecadapi.catalog` reads).""" + +__all__ = ["Angle", "Count", "Direction3", "Length", "MEANINGS", "Point3", "Vector3"] diff --git a/test/test_catalog.py b/test/test_catalog.py new file mode 100644 index 00000000..845edc9b --- /dev/null +++ b/test/test_catalog.py @@ -0,0 +1,104 @@ +"""The operation catalog is read from the signatures: every public operation is in it, and its parameters say what they mean.""" + +from __future__ import annotations + +import json + +import simplecadapi as scad +from simplecadapi import catalog + +# Operations whose signature still says ``object`` for some parameter: give them real types (simplecadapi.types, typed +# sequences, Literal choices) and remove them here. The list only shrinks. +PENDING_UNTYPED = { + "add_belt_constraint_rassembly", + "add_component_rassembly", + "add_connector_rpart", + "add_fixed_constraint_rassembly", + "add_gear_constraint_rassembly", + "add_prismatic_constraint_rassembly", + "add_rack_pinion_constraint_rassembly", + "add_revolute_constraint_rassembly", + "apply_tag_rselection", + "assign_material_rpart", + "boolean_rsolidlist", + "chamfer_rsolid", + "cut_rsolid", + "draft_rsolid", + "explode_rassembly", + "extrude_taper_rsolid", + "extrude_until_rsolid", + "fill_holes_rshell", + "fillet_rsolid", + "ground_component_rassembly", + "inspect_assembly_constraints_rconstraintreport", + "load_brep_region_rshell", + "load_brep_region_rsolid", + "loft_rshell", + "loft_rsolid", + "make_2d_cut_rface", + "make_2d_intersect_rface", + "make_2d_union_rface", + "make_assembly_rassembly", + "make_ball_bearing_rassembly", + "make_bolt_rsolid", + "make_compound_from_assembly_rcompound", + "make_connector_ref_rconnectorref", + "make_edge_connector_rconnector", + "make_face_connector_rconnector", + "make_face_from_sketch_rface", + "make_material_rmaterial", + "make_nut_rsolid", + "make_part_rpart", + "make_placement_connector_rconnector", + "make_placement_rplacement", + "make_roller_chain_sprocket_rsolid", + "make_scalar_limit_rscalarlimit", + "make_sketch_rsketch", + "make_spline_redge", + "make_spline_rwire", + "make_surface_patch_rface", + "make_vertex_connector_rconnector", + "make_wire_from_sketch_rwire", + "measure_constraint_residual_rconstraintresidual", + "offset_rsolid", + "place_component_rassembly", + "project_rsketch", + "render_screenshot_rpath", + "scale_rsolid", + "set_public_connector_rassembly", + "shell_rsolid", + "solve_assembly_constraints_rassembly", + "sweep_multisection_rsolid", + "unground_component_rassembly", + "union_rsolid", +} + + +def test_every_public_operation_is_in_the_catalog_with_its_parameters(): + names = {op.name for op in catalog.operations()} + public = {n for n in scad.__all__ if catalog._OP_NAME.match(n) and callable(getattr(scad, n))} + assert public <= names + assert {"make_spur_gear_rsolid", "make_bolt_rsolid"} <= names # the standard library too + json.dumps(catalog.catalog_dict(), default=str) # plain data + + +def test_the_meaning_comes_from_the_binding_types(): + cylinder = catalog.operation("make_cylinder_rsolid") + kinds = {p.name: p.kind for p in cylinder.params} + assert (kinds["radius"], kinds["height"], kinds["bottom_face_center"], kinds["axis"]) == ("length", "length", "point3", "direction3") + assert cylinder.returns == "solid" and cylinder.module == "simplecadapi" + assert next(p for p in cylinder.params if p.name == "axis").default == (0, 0, 1) + assert next(p for p in cylinder.params if p.name == "start_face_tag").keyword_only + + +def test_no_operation_beyond_the_pending_list_takes_an_untyped_parameter(): + untyped = {op.name for op in catalog.operations() for p in op.params if p.kind == "unknown"} + assert untyped <= PENDING_UNTYPED, sorted(untyped - PENDING_UNTYPED) + assert not (PENDING_UNTYPED - untyped), f"typed now, drop from PENDING_UNTYPED: {sorted(PENDING_UNTYPED - untyped)}" + + +def test_types_classify(): + assert catalog.classify("Sequence[Edge]") == {"kind": "edge", "many": True, "optional": False, "choices": ()} + assert catalog.classify("Literal['NEXT', 'LAST']")["choices"] == ("NEXT", "LAST") + assert catalog.classify("simplecadapi.types.Angle | None") == {"kind": "angle", "many": False, "optional": True, "choices": ()} + assert catalog.classify("Sequence[simplecadapi.types.Point3]")["kind"] == "points"