diff --git a/examples/SDK_DEFECTS.md b/examples/SDK_DEFECTS.md index 93703c28..b26962a5 100644 --- a/examples/SDK_DEFECTS.md +++ b/examples/SDK_DEFECTS.md @@ -328,6 +328,55 @@ that surfaced it is in brackets. - **Fix direction:** done. Every `ql` factory should resolve against any scope that contains its kind; check each (kind, scope) pair when adding a factory. +## 21. `phase_offset` of the gear, belt and rack-pinion constraints is a length, and nothing said so [catalog] + +- **Symptom:** next to `drive_angle_degrees`, `phase_offset` reads like an + angle; a GUI or agent would pass degrees. +- **Trigger:** `add_gear_constraint_rassembly(..., phase_offset=...)` (also + belt, rack_pinion). +- **Root cause:** the coupling phase is `r_a * theta_a + r_b * theta_b` + (`coupling.cpp: phase_from_supports`), an arc length on the pitch circle in + mm; the binding took `py::object` and the docstring did not say. +- **Status:** the signature now says `phase_offset: Length | None`. +- **Fix direction:** say "pitch-circle arc length (mm)" in the docstrings too; + consider renaming to `phase_offset_length` in a major version. + +## 22. The std bindings are registered before the product classes [catalog] + +- **Symptom:** `simplecadapi._cpp.std.bearing.make_ball_bearing_rassembly` + prints its return type as `scad::product::Assembly` (the C++ name); a + `Material` argument cannot take its name from the registered class. +- **Trigger:** `bind_std(m)` runs before `bind_product(m)` in `module.cpp`; pybind + writes the signature when the function is defined. Likewise `bind_semantic` + runs before `bind_ql`, so `apply_tag_rselection` spells out `ShapeSelector`. +- **Root cause:** registration order. +- **Status:** open; the names are written out where needed. The C++ + `std.bearing.make_ball_bearing_rassembly` is also shadowed by the Python one + in `simplecadapi.std.bearing` (two implementations of one operation). +- **Fix direction:** bind the value classes (product, ql) before any operation + that uses them; drop one of the two bearing factories. + +## 23. `catalog.classify` read a union that starts with `Literal[` as one Literal [catalog] + +- **Symptom:** `Literal['auto', ...] | tuple[Angle, Angle]` gave the choices + `"rear_left'] | tuple[Angle"` and `'Angle'`. +- **Root cause:** the `Literal[...]` / `Sequence[...]` / `Annotated[...]` + regexes were `fullmatch`ed on the whole union text. +- **Status:** fixed. Unions are split first; a union of bracketed members is + the members' kinds joined (`enum|numbers`, `query|shape`, `solid` many for + `Solid | Sequence[Solid]`). Also new: `path`, `scalar_limit`, `_map` + for `dict[str, X]`, and str-enum defaults (`` -> `'x'`). +- **Fix direction:** done. + +## 24. Style and view strings are case-insensitive, the signatures list one spelling [catalog] + +- **Symptom:** `make_bolt_rsolid(head_style="HEX")`, `render_screenshot_rpath(view="Top")` work, yet the signature + says `Literal['hex', ...]` / `Literal['top', ...]`. +- **Root cause:** `stdlib::choice` and `view_preset` lower-case the value before matching. +- **Status:** open by choice: the Literal lists the canonical spellings (what a form offers); the runtime still + accepts any case. `apply_tag_rselection`'s enums are case-sensitive. +- **Fix direction:** pick one rule for every string enum of the SDK. + ## Heuristics - Run every notebook three times: fresh, all cached, `--no-cache`. The three diff --git a/src/cpp/bindings/python/bind_ops_geometry.cpp b/src/cpp/bindings/python/bind_ops_geometry.cpp index 3e1f45ae..14653776 100644 --- a/src/cpp/bindings/python/bind_ops_geometry.cpp +++ b/src/cpp/bindings/python/bind_ops_geometry.cpp @@ -2,6 +2,7 @@ // simplecadapi/operators/geometry.py, under the Python names, argument names and // defaults (keyword-only where Python is keyword-only), plus the create_* aliases. #include "bindings.hpp" +#include "typed_args.hpp" #include "scad/core/tolerance.hpp" #include "scad/io/brep_region.hpp" @@ -53,6 +54,12 @@ SplineSpec spline_spec(std::vector control_points, const py::object .periodic = periodic}; } +// A file path argument: what os.fspath takes, for the signature. +struct PathName { + static constexpr auto name = py::detail::const_name("str | os.PathLike[str]"); +}; +using PathArg = scad::pybind::Typed; + std::string path_text(const py::object& path) { return py::str(py::module_::import("os").attr("fspath")(path)).cast(); } @@ -297,7 +304,7 @@ void bind_primitives(py::module_& m) { void bind_brep_region(py::module_& m) { m.def( "load_brep_region_rsolid", - [](const py::object& path, const std::string& sha256, const OptionalString& tag_prefix) { + [](const PathArg& path, const std::string& sha256, const OptionalString& tag_prefix) { return load_brep_region_rsolid(path_text(path), sha256, tag_prefix); }, py::arg("path"), py::arg("sha256"), py::kw_only(), py::arg("tag_prefix") = py::none(), @@ -313,7 +320,7 @@ void bind_brep_region(py::module_& m) { "The checks on a .scadbrep locator (graph replay: relative, no drive, no '..', '/' separators)."); m.def( "load_brep_region_rshell", - [](const py::object& path, const std::string& sha256, const OptionalString& tag_prefix) { + [](const PathArg& path, const std::string& sha256, const OptionalString& tag_prefix) { return load_brep_region_rshell(path_text(path), sha256, tag_prefix); }, py::arg("path"), py::arg("sha256"), py::kw_only(), py::arg("tag_prefix") = py::none(), diff --git a/src/cpp/bindings/python/bind_product.cpp b/src/cpp/bindings/python/bind_product.cpp index f3a9ba33..37423cc1 100644 --- a/src/cpp/bindings/python/bind_product.cpp +++ b/src/cpp/bindings/python/bind_product.cpp @@ -4,8 +4,10 @@ // // Every operator takes py::object for the arguments whose type Python checks inside its wrapped // body, and converts them inside guard_operation, so a wrong type is the operation's -// SimpleCADError exactly as in Python (see bind_product_args.hpp). +// SimpleCADError exactly as in Python (see bind_product_args.hpp). The py::object arrives as a +// `Typed` (typed_args.hpp), so the signature still says what each argument is. #include "bind_product_args.hpp" +#include "typed_args.hpp" #include "scad/reactive/registry.hpp" @@ -15,6 +17,71 @@ using namespace scad; using namespace scad::product_binding; using sp::guard_operation; +// What each argument is, for the signature; the bodies still receive the py::object and check it themselves. +namespace names { +using py::detail::const_name; +using scad::pybind::kOr; +using scad::pybind::kOrNone; +using scad::pybind::type_name; +SCAD_SIGNATURE_NAME(Text, const_name("str")); +SCAD_SIGNATURE_NAME(TextOrNone, const_name("str | None")); +SCAD_SIGNATURE_NAME(Number, const_name("float | Expr")); +SCAD_SIGNATURE_NAME(NumberOrNone, const_name("float | Expr | None")); +SCAD_SIGNATURE_NAME(Bool, const_name("bool")); +SCAD_SIGNATURE_NAME(Color, const_name("collections.abc.Sequence[float] | None")); +SCAD_SIGNATURE_NAME(Length, scad::pybind::LengthTag::name); +SCAD_SIGNATURE_NAME(LengthOrNone, scad::pybind::LengthTag::name + kOrNone); +SCAD_SIGNATURE_NAME(AngleOrNone, scad::pybind::AngleTag::name + kOrNone); +SCAD_SIGNATURE_NAME(Point, scad::pybind::PointTag::name); +SCAD_SIGNATURE_NAME(PointOrNone, scad::pybind::PointTag::name + kOrNone); +SCAD_SIGNATURE_NAME(Direction, scad::pybind::DirectionTag::name); +SCAD_SIGNATURE_NAME(DirectionOrNone, scad::pybind::DirectionTag::name + kOrNone); +SCAD_SIGNATURE_NAME(Directions, const_name("dict[str, ") + scad::pybind::DirectionTag::name + const_name("] | None")); +SCAD_SIGNATURE_NAME(Weights, const_name("dict[str, float | Expr] | None")); +SCAD_SIGNATURE_NAME(Solid, type_name()); +SCAD_SIGNATURE_NAME(Face, type_name()); +SCAD_SIGNATURE_NAME(Edge, type_name()); +SCAD_SIGNATURE_NAME(Vertex, type_name()); +SCAD_SIGNATURE_NAME(Part, type_name()); +SCAD_SIGNATURE_NAME(Assembly, type_name()); +SCAD_SIGNATURE_NAME(Item, type_name() + kOr + type_name()); +SCAD_SIGNATURE_NAME(Placement, type_name()); +SCAD_SIGNATURE_NAME(Material, type_name()); +SCAD_SIGNATURE_NAME(Connector, type_name()); +SCAD_SIGNATURE_NAME(Ref, type_name()); +SCAD_SIGNATURE_NAME(Limit, type_name() + kOrNone); +} // namespace names + +using scad::pybind::Typed; +using TextArg = Typed; +using NameArg = Typed; // anything str() takes: a display name +using TextOrNoneArg = Typed; +using NumberArg = Typed; +using NumberOrNoneArg = Typed; +using BoolArg = Typed; // any object, read by its truth value +using ColorArg = Typed; +using LengthArg = Typed; +using LengthOrNoneArg = Typed; +using AngleOrNoneArg = Typed; +using PointArg = Typed; +using PointOrNoneArg = Typed; +using DirectionArg = Typed; +using DirectionOrNoneArg = Typed; +using DirectionsArg = Typed; +using WeightsArg = Typed; +using SolidArg = Typed; +using FaceArg = Typed; +using EdgeArg = Typed; +using VertexArg = Typed; +using PartArg = Typed; +using AssemblyArg = Typed; +using ItemArg = Typed; +using PlacementArg = Typed; +using MaterialArg = Typed; +using ConnectorArg = Typed; +using RefArg = Typed; +using LimitArg = Typed; + const sp::Assembly& assembly_arg(const py::object& value) { return typed(value, "assembly must be an Assembly"); } @@ -46,8 +113,8 @@ Scalar3 point_arg(const py::object& value, const char* field) { void bind_structure(py::module_& m) { m.def( "make_material_rmaterial", - [](const py::object& material_id, const py::object& name, const py::object& density, - const py::object& density_unit, const py::object& color) { + [](const TextArg& material_id, const NameArg& name, const NumberOrNoneArg& density, + const TextOrNoneArg& density_unit, const ColorArg& color) { return guard_operation("make_material_rmaterial", [&] { sp::OptionalString unit; if (!density_unit.is_none()) @@ -65,7 +132,7 @@ void bind_structure(py::module_& m) { m.def( "make_placement_rplacement", - [](const py::object& origin, const py::object& x_axis, const py::object& y_axis) { + [](const PointArg& origin, const DirectionArg& x_axis, const DirectionArg& y_axis) { return guard_operation("make_placement_rplacement", [&] { return sp::make_placement_rplacement(point_arg(origin, "origin"), point_arg(x_axis, "x_axis"), point_arg(y_axis, "y_axis")); @@ -79,7 +146,7 @@ void bind_structure(py::module_& m) { m.def( "make_part_rpart", - [](const py::object& part_id, const py::object& body, const py::object& name) { + [](const TextArg& part_id, const SolidArg& body, const NameArg& name) { return guard_operation("make_part_rpart", [&] { return sp::make_part_rpart(text(part_id, "part_id"), typed(body, "body must be a Solid"), optional_name(name)); @@ -89,7 +156,7 @@ void bind_structure(py::module_& m) { "Wrap exactly one Solid as a semantic single-body Part."); m.def( "assign_material_rpart", - [](const py::object& part, const py::object& material) { + [](const PartArg& part, const MaterialArg& material) { return guard_operation("assign_material_rpart", [&] { return sp::assign_material_rpart(part_arg(part), typed(material, "material must be a Material")); @@ -99,7 +166,7 @@ void bind_structure(py::module_& m) { m.def( "make_assembly_rassembly", - [](const py::object& assembly_id, const py::object& name) { + [](const TextArg& assembly_id, const NameArg& name) { return guard_operation("make_assembly_rassembly", [&] { return sp::make_assembly_rassembly(text(assembly_id, "assembly_id"), optional_name(name)); }); @@ -107,8 +174,8 @@ void bind_structure(py::module_& m) { py::arg("assembly_id"), py::arg("name") = py::none(), "Create an empty assembly product structure."); m.def( "add_component_rassembly", - [](const py::object& assembly, const py::object& item, const py::object& component_id, - const py::object& placement, const py::object& name) { + [](const AssemblyArg& assembly, const ItemArg& item, const TextArg& component_id, const PlacementArg& placement, + const NameArg& name) { return guard_operation("add_component_rassembly", [&] { const sp::Assembly& target = assembly_arg(assembly); const sp::Item chosen = item_of(item); @@ -120,7 +187,7 @@ void bind_structure(py::module_& m) { "Add a placed Part or subassembly component instance to an Assembly."); m.def( "place_component_rassembly", - [](const py::object& assembly, const py::object& component_id, const py::object& placement) { + [](const AssemblyArg& assembly, const TextArg& component_id, const PlacementArg& placement) { return guard_operation("place_component_rassembly", [&] { const sp::Assembly& target = assembly_arg(assembly); return sp::place_component_rassembly(target, text(component_id, "component_id"), placement_arg(placement)); @@ -130,8 +197,8 @@ void bind_structure(py::module_& m) { "Move an existing assembly component by replacing its placement."); m.def( "explode_rassembly", - [](const py::object& assembly, const py::object& factor, const py::object& center, const py::object& axis, - const py::object& directions, const py::object& weights) { + [](const AssemblyArg& assembly, const NumberArg& factor, const PointOrNoneArg& center, + const DirectionOrNoneArg& axis, const DirectionsArg& directions, const WeightsArg& weights) { return guard_operation("explode_rassembly", [&] { const sp::Assembly& target = assembly_arg(assembly); std::map direction_map; @@ -162,7 +229,7 @@ void bind_structure(py::module_& m) { void bind_connectors(py::module_& m) { m.def( "make_face_connector_rconnector", - [](const py::object& connector_id, const py::object& face, const py::object& name, const py::object& flip) { + [](const TextArg& connector_id, const FaceArg& face, const NameArg& name, const BoolArg& flip) { return guard_operation("make_face_connector_rconnector", [&] { const Face& target = typed(face, "face must be a Face"); return sp::make_face_connector_rconnector(text(connector_id, "connector_id"), target, optional_name(name), @@ -174,7 +241,7 @@ void bind_connectors(py::module_& m) { "Set flip=True to negate the Z axis (point it opposite to the normal)."); m.def( "make_edge_connector_rconnector", - [](const py::object& connector_id, const py::object& edge, const py::object& name, const py::object& flip) { + [](const TextArg& connector_id, const EdgeArg& edge, const NameArg& name, const BoolArg& flip) { return guard_operation("make_edge_connector_rconnector", [&] { const Edge& target = typed(edge, "edge must be an Edge"); return sp::make_edge_connector_rconnector(text(connector_id, "connector_id"), target, optional_name(name), @@ -187,7 +254,7 @@ void bind_connectors(py::module_& m) { "Set flip=True to negate the Z axis."); m.def( "make_vertex_connector_rconnector", - [](const py::object& connector_id, const py::object& vertex, const py::object& name, const py::object& flip) { + [](const TextArg& connector_id, const VertexArg& vertex, const NameArg& name, const BoolArg& flip) { return guard_operation("make_vertex_connector_rconnector", [&] { const Vertex& target = typed(vertex, "vertex must be a Vertex"); return sp::make_vertex_connector_rconnector(text(connector_id, "connector_id"), target, optional_name(name), @@ -199,7 +266,7 @@ void bind_connectors(py::module_& m) { "flip has no effect on vertex connectors (no direction)."); m.def( "make_placement_connector_rconnector", - [](const py::object& connector_id, const py::object& placement, const py::object& name) { + [](const TextArg& connector_id, const PlacementArg& placement, const NameArg& name) { return guard_operation("make_placement_connector_rconnector", [&] { const sp::Placement& frame = placement_arg(placement); return sp::make_placement_connector_rconnector(text(connector_id, "connector_id"), frame, @@ -210,7 +277,7 @@ void bind_connectors(py::module_& m) { "Create a connector anchored to an explicit local placement frame."); m.def( "add_connector_rpart", - [](const py::object& part, const py::object& connector) { + [](const PartArg& part, const ConnectorArg& connector) { return guard_operation("add_connector_rpart", [&] { const sp::Part& target = part_arg(part); return sp::add_connector_rpart(target, typed(connector, "connector must be a Connector")); @@ -219,8 +286,8 @@ void bind_connectors(py::module_& m) { py::arg("part"), py::arg("connector"), "Attach a connector datum frame to a Part definition."); m.def( "set_public_connector_rassembly", - [](const py::object& assembly, const py::object& public_id, const py::object& component_id, - const py::object& connector_id, const py::object& name) { + [](const AssemblyArg& assembly, const TextArg& public_id, const TextArg& component_id, + const TextArg& connector_id, const NameArg& name) { return guard_operation("set_public_connector_rassembly", [&] { const sp::Assembly& target = assembly_arg(assembly); return sp::set_public_connector_rassembly(target, text(public_id, "public_connector_id"), @@ -233,7 +300,7 @@ void bind_connectors(py::module_& m) { "Expose an existing connector on a direct child component."); m.def( "make_connector_ref_rconnectorref", - [](const py::object& component_id, const py::object& connector_id) { + [](const TextArg& component_id, const TextArg& connector_id) { return guard_operation("make_connector_ref_rconnectorref", [&] { return sp::make_connector_ref_rconnectorref(text(component_id, "component_id"), text(connector_id, "connector_id")); @@ -242,7 +309,7 @@ void bind_connectors(py::module_& m) { py::arg("component_id"), py::arg("connector_id"), "Reference a connector through a component instance."); m.def( "make_scalar_limit_rscalarlimit", - [](const py::object& lower_value, const py::object& upper_value) { + [](const NumberArg& lower_value, const NumberArg& upper_value) { return guard_operation("make_scalar_limit_rscalarlimit", [&] { return sp::make_scalar_limit_rscalarlimit(scalar(lower_value, "lower_value"), scalar(upper_value, "upper_value")); @@ -257,7 +324,7 @@ void bind_connectors(py::module_& m) { void bind_constraints(py::module_& m) { m.def( "ground_component_rassembly", - [](const py::object& assembly, const py::object& component_id) { + [](const AssemblyArg& assembly, const TextArg& component_id) { return guard_operation("ground_component_rassembly", [&] { const sp::Assembly& target = assembly_arg(assembly); return sp::ground_component_rassembly(target, text(component_id, "component_id")); @@ -266,7 +333,7 @@ void bind_constraints(py::module_& m) { py::arg("assembly"), py::arg("component_id"), "Ground a component at its current authored placement."); m.def( "unground_component_rassembly", - [](const py::object& assembly, const py::object& component_id) { + [](const AssemblyArg& assembly, const TextArg& component_id) { return guard_operation("unground_component_rassembly", [&] { const sp::Assembly& target = assembly_arg(assembly); return sp::unground_component_rassembly(target, text(component_id, "component_id")); @@ -285,8 +352,8 @@ void bind_constraints(py::module_& m) { m.def( "add_fixed_constraint_rassembly", - [ref](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b, - const py::object& name) { + [ref](const AssemblyArg& assembly, const TextArg& constraint_id, const RefArg& a, const RefArg& b, + const NameArg& name) { return sp::add_fixed_constraint_rassembly(constraint_assembly("add_fixed_constraint_rassembly", assembly), text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"), optional_name(name)); @@ -295,9 +362,8 @@ void bind_constraints(py::module_& m) { py::arg("name") = py::none(), "Constrain two component connectors to the same frame."); m.def( "add_revolute_constraint_rassembly", - [ref, limit](const py::object& assembly, const py::object& constraint_id, const py::object& a, - const py::object& b, const py::object& drive_angle_degrees, const py::object& angle_limit, - const py::object& name) { + [ref, limit](const AssemblyArg& assembly, const TextArg& constraint_id, const RefArg& a, const RefArg& b, + const AngleOrNoneArg& drive_angle_degrees, const LimitArg& angle_limit, const NameArg& name) { return sp::add_revolute_constraint_rassembly( constraint_assembly("add_revolute_constraint_rassembly", assembly), text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"), optional_scalar(drive_angle_degrees, "drive_angle_degrees"), @@ -308,9 +374,8 @@ void bind_constraints(py::module_& m) { "Constrain two connectors as a revolute axis pair."); m.def( "add_prismatic_constraint_rassembly", - [ref, limit](const py::object& assembly, const py::object& constraint_id, const py::object& a, - const py::object& b, const py::object& drive_distance, const py::object& distance_limit, - const py::object& name) { + [ref, limit](const AssemblyArg& assembly, const TextArg& constraint_id, const RefArg& a, const RefArg& b, + const LengthOrNoneArg& drive_distance, const LimitArg& distance_limit, const NameArg& name) { return sp::add_prismatic_constraint_rassembly( constraint_assembly("add_prismatic_constraint_rassembly", assembly), text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"), optional_scalar(drive_distance, "drive_distance"), @@ -321,9 +386,9 @@ void bind_constraints(py::module_& m) { "Constrain two connectors as a prismatic slider pair."); m.def( "add_gear_constraint_rassembly", - [ref](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b, - const py::object& pitch_radius_a, const py::object& pitch_radius_b, const py::object& phase_offset, - const py::object& name) { + [ref](const AssemblyArg& assembly, const TextArg& constraint_id, const RefArg& a, const RefArg& b, + const LengthArg& pitch_radius_a, const LengthArg& pitch_radius_b, const LengthOrNoneArg& phase_offset, + const NameArg& name) { return sp::add_gear_constraint_rassembly(constraint_assembly("add_gear_constraint_rassembly", assembly), text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"), scalar(pitch_radius_a, "pitch_radius_a"), @@ -335,9 +400,9 @@ void bind_constraints(py::module_& m) { py::arg("name") = py::none(), "Couple two revolute axes as meshing gears with inverse rotation."); m.def( "add_belt_constraint_rassembly", - [ref](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b, - const py::object& pulley_radius_a, const py::object& pulley_radius_b, const py::object& phase_offset, - const py::object& name) { + [ref](const AssemblyArg& assembly, const TextArg& constraint_id, const RefArg& a, const RefArg& b, + const LengthArg& pulley_radius_a, const LengthArg& pulley_radius_b, const LengthOrNoneArg& phase_offset, + const NameArg& name) { return sp::add_belt_constraint_rassembly(constraint_assembly("add_belt_constraint_rassembly", assembly), text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"), scalar(pulley_radius_a, "pulley_radius_a"), @@ -349,9 +414,8 @@ void bind_constraints(py::module_& m) { py::arg("name") = py::none(), "Couple two revolute axes as belt-linked pulleys with same-direction rotation."); m.def( "add_rack_pinion_constraint_rassembly", - [ref](const py::object& assembly, const py::object& constraint_id, const py::object& rack, - const py::object& pinion, const py::object& pitch_radius, const py::object& phase_offset, - const py::object& name) { + [ref](const AssemblyArg& assembly, const TextArg& constraint_id, const RefArg& rack, const RefArg& pinion, + const LengthArg& pitch_radius, const LengthOrNoneArg& phase_offset, const NameArg& name) { return sp::add_rack_pinion_constraint_rassembly( constraint_assembly("add_rack_pinion_constraint_rassembly", assembly), text(constraint_id, "constraint_id"), ref(rack, "connector_a"), ref(pinion, "connector_b"), scalar(pitch_radius, "pitch_radius"), @@ -365,7 +429,7 @@ void bind_constraints(py::module_& m) { void bind_solving(py::module_& m) { m.def( "solve_assembly_constraints_rassembly", - [](const py::object& assembly, const py::object& strict) { + [](const AssemblyArg& assembly, const BoolArg& strict) { return guard_operation("solve_assembly_constraints_rassembly", [&] { return sp::solve_assembly_constraints_rassembly(assembly_ptr_arg(assembly), truthy(strict)); }); @@ -383,7 +447,7 @@ void bind_solving(py::module_& m) { "``inspect_assembly_constraints_rassembly``."); m.def( "measure_constraint_residual_rconstraintresidual", - [](const py::object& assembly, const py::object& constraint_id) { + [](const AssemblyArg& assembly, const TextArg& constraint_id) { return sp::measure_constraint_residual_rconstraintresidual(assembly_arg(assembly), text(constraint_id, "constraint_id")); }, @@ -391,13 +455,13 @@ void bind_solving(py::module_& m) { "Measure residual for one assembly constraint without mutating the assembly."); m.def( "inspect_assembly_constraints_rconstraintreport", - [](const py::object& assembly) { + [](const AssemblyArg& assembly) { return sp::inspect_assembly_constraints_rconstraintreport(assembly_arg(assembly)); }, py::arg("assembly"), "Inspect all assembly constraint residuals without mutating the assembly."); m.def( "make_compound_from_assembly_rcompound", - [](const py::object& assembly) { + [](const AssemblyArg& assembly) { return guard_operation("make_compound_from_assembly_rcompound", [&] { return sp::make_compound_from_assembly_rcompound(assembly_arg(assembly)); }); }, diff --git a/src/cpp/bindings/python/bind_semantic.cpp b/src/cpp/bindings/python/bind_semantic.cpp index 806b73b8..b5a72387 100644 --- a/src/cpp/bindings/python/bind_semantic.cpp +++ b/src/cpp/bindings/python/bind_semantic.cpp @@ -5,6 +5,7 @@ // the member or its string value ("local"), and returns members. The casters below are the only // ones for these types in the module. #include "bindings.hpp" +#include "typed_args.hpp" #include #include @@ -614,6 +615,22 @@ TagTargets targets_from_py(const py::object& targets) { return TagTargets(std::move(shapes)); } +// `targets` of apply_tag_rselection, for the signature (the body checks it: targets_from_py). ShapeSelector is bound +// after this module, so the names are written out. +struct TagTargetsName { + static constexpr auto name = py::detail::const_name( + "simplecadapi._cpp._native.ShapeSelector | collections.abc.Sequence[simplecadapi._cpp._native.AnyShape]"); +}; + +// The str enums by their values (members of the Python enums are str too). +struct TopologyPropagationName { + static constexpr auto name = py::detail::const_name("typing.Literal['local', 'downward']"); +}; +struct LineagePolicyName { + static constexpr auto name = + py::detail::const_name("typing.Literal['none', 'continuation', 'continuation_fragment', 'explicit']"); +}; + void bind_operators(py::module_& m) { m.def( "apply_tag", @@ -634,8 +651,9 @@ void bind_operators(py::module_& m) { m.def( "apply_tag_rselection", - [](const Shape& scope, const py::object& targets, const std::string& tag, TopologyPropagation topology, - LineagePolicy lineage) { + [](const Shape& scope, const scad::pybind::Typed& targets, const std::string& tag, + scad::pybind::Shown topology, + scad::pybind::Shown lineage) { static const ErrorSpec spec{ "apply_tag_rselection", "Failed to attach the tag to the selected shapes.", diff --git a/src/cpp/bindings/python/bind_std.cpp b/src/cpp/bindings/python/bind_std.cpp index f3c3f5b9..abc98f54 100644 --- a/src/cpp/bindings/python/bind_std.cpp +++ b/src/cpp/bindings/python/bind_std.cpp @@ -5,6 +5,7 @@ // executor to register: a recorded gear replays through the operators it was made of. // `build_ball_bearing` (the durable-definition wrapper over the build layer) is not provided. #include "bindings.hpp" +#include "typed_args.hpp" #include #include @@ -22,6 +23,41 @@ namespace { using namespace scad; +// What the arguments mean, for the signature (typed_args.hpp): each converts exactly as the double / int / object it +// wraps, so the factories take what they took before. +struct CountTag { + static constexpr auto name = py::detail::const_name("simplecadapi.types.Count"); +}; +using Length = scad::pybind::Shown; +using Angle = scad::pybind::Shown; +using Count = scad::pybind::Shown; + +namespace names { +using py::detail::const_name; +SCAD_SIGNATURE_NAME(CountOrNone, CountTag::name + scad::pybind::kOrNone); +// Material is bound after the std module, so its name is written out. +SCAD_SIGNATURE_NAME(MaterialOrNone, const_name("simplecadapi._cpp._native.Material | None")); +// The fastener styles are read case-insensitively; the signature lists the canonical spellings. +SCAD_SIGNATURE_NAME(HeadStyle, const_name("typing.Literal['hex', 'square', 'cylindrical', 'button', 'countersunk']")); +SCAD_SIGNATURE_NAME(ThreadStyle, const_name("typing.Literal['auto', 'full', 'partial', 'none']")); +SCAD_SIGNATURE_NAME(ThreadDetail, const_name("typing.Literal['modeled', 'cosmetic']")); +SCAD_SIGNATURE_NAME(ThreadForm, const_name("typing.Literal['v', 'trapezoidal']")); +SCAD_SIGNATURE_NAME(DriveStyle, const_name("typing.Literal['none', 'slot', 'cross', 'hex_socket']")); +SCAD_SIGNATURE_NAME(NutStyle, const_name("typing.Literal['hex', 'square', 'round', 'knurled']")); +SCAD_SIGNATURE_NAME(HoleStyle, const_name("typing.Literal['through', 'blind']")); +} // namespace names + +using CountArg = scad::pybind::Typed; // checked as a plain int by the factory +using CountOrNoneArg = scad::pybind::Typed; +using MaterialOrNoneArg = scad::pybind::Typed; +using HeadStyleArg = scad::pybind::Typed; +using ThreadStyleArg = scad::pybind::Typed; +using ThreadDetailArg = scad::pybind::Typed; +using ThreadFormArg = scad::pybind::Typed; +using DriveStyleArg = scad::pybind::Typed; +using NutStyleArg = scad::pybind::Typed; +using HoleStyleArg = scad::pybind::Typed; + // Runs `body` with the GIL released; an exception leaves with the GIL back. template auto unlocked(F&& body) { @@ -64,8 +100,8 @@ stdlib::Point2 point_from_py(const py::object& value) { void bind_gear_factories(py::module_& gear) { gear.def( "make_spur_gear_rsolid", - [](int n_teeth, double module, double pressure_angle, double gear_height, double addendum_factor, - double clearance_factor, double backlash) { + [](Count n_teeth, Length module, Angle pressure_angle, Length gear_height, double addendum_factor, + double clearance_factor, Length backlash) { return unlocked([&] { return make_spur_gear_rsolid(n_teeth, module, pressure_angle, gear_height, tuning(addendum_factor, clearance_factor, backlash)); @@ -80,8 +116,8 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_straight_bevel_gear_rsolid", - [](int n_teeth, double module, double pitch_angle, double pressure_angle, double face_width, - double addendum_factor, double clearance_factor, double backlash) { + [](Count n_teeth, Length module, Angle pitch_angle, Angle pressure_angle, Length face_width, + double addendum_factor, double clearance_factor, Length backlash) { return unlocked([&] { return make_straight_bevel_gear_rsolid(n_teeth, module, pitch_angle, pressure_angle, face_width, tuning(addendum_factor, clearance_factor, backlash)); @@ -97,8 +133,8 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_helical_gear_rsolid", - [](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height, - double addendum_factor, double clearance_factor, double backlash) { + [](Count n_teeth, Length module, Angle pressure_angle, Angle helix_angle, Length gear_height, + double addendum_factor, double clearance_factor, Length backlash) { return unlocked([&] { return make_helical_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height, tuning(addendum_factor, clearance_factor, backlash)); @@ -112,8 +148,8 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_herringbone_gear_rsolid", - [](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height, - double addendum_factor, double clearance_factor, double backlash) { + [](Count n_teeth, Length module, Angle pressure_angle, Angle helix_angle, Length gear_height, + double addendum_factor, double clearance_factor, Length backlash) { return unlocked([&] { return make_herringbone_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height, tuning(addendum_factor, clearance_factor, backlash)); @@ -127,7 +163,7 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_spur_ring_gear_rsolid", - [](int n_teeth, double module, double pressure_angle, double gear_height, double rim_thickness, double backlash, + [](Count n_teeth, Length module, Angle pressure_angle, Length gear_height, Length rim_thickness, Length backlash, double addendum_factor, double clearance_factor) { return unlocked([&] { return make_spur_ring_gear_rsolid(n_teeth, module, pressure_angle, gear_height, rim_thickness, @@ -143,8 +179,8 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_helical_ring_gear_rsolid", - [](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height, - double rim_thickness, double backlash, double addendum_factor, double clearance_factor) { + [](Count n_teeth, Length module, Angle pressure_angle, Angle helix_angle, Length gear_height, + Length rim_thickness, Length backlash, double addendum_factor, double clearance_factor) { return unlocked([&] { return make_helical_ring_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height, rim_thickness, tuning(addendum_factor, clearance_factor, backlash)); @@ -157,8 +193,8 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_herringbone_ring_gear_rsolid", - [](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height, - double rim_thickness, double backlash, double addendum_factor, double clearance_factor) { + [](Count n_teeth, Length module, Angle pressure_angle, Angle helix_angle, Length gear_height, + Length rim_thickness, Length backlash, double addendum_factor, double clearance_factor) { return unlocked([&] { return make_herringbone_ring_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height, rim_thickness, tuning(addendum_factor, clearance_factor, backlash)); @@ -171,9 +207,9 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_cycloidal_disc_rsolid", - [](int n_lobes, double ring_pin_pitch_radius, double roller_radius, double eccentricity, double gear_height, - double bore_radius, int output_pin_count, double output_pin_pitch_radius, double output_pin_clearance_radius, - double output_pin_phase, int sample_count_per_lobe, double spline_tolerance, int max_control_points) { + [](Count n_lobes, Length ring_pin_pitch_radius, Length roller_radius, Length eccentricity, Length gear_height, + Length bore_radius, Count output_pin_count, Length output_pin_pitch_radius, Length output_pin_clearance_radius, + Angle output_pin_phase, Count sample_count_per_lobe, Length spline_tolerance, Count max_control_points) { CycloidalDiscOptions options; options.bore_radius = bore_radius; options.output_pin_count = output_pin_count; @@ -199,7 +235,7 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_spur_rack_rsolid", - [](double module, int n_teeth, double pressure_angle, double rack_height) { + [](Length module, Count n_teeth, Angle pressure_angle, Length rack_height) { return unlocked([&] { return make_spur_rack_rsolid(module, n_teeth, pressure_angle, rack_height); }); }, py::arg("module"), py::arg("n_teeth") = 10, py::arg("pressure_angle") = 20.0, py::arg("rack_height") = 6.0, @@ -207,7 +243,7 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_helical_rack_rsolid", - [](double module, int n_teeth, double pressure_angle, double helix_angle, double rack_height) { + [](Length module, Count n_teeth, Angle pressure_angle, Angle helix_angle, Length rack_height) { return unlocked( [&] { return make_helical_rack_rsolid(module, n_teeth, pressure_angle, helix_angle, rack_height); }); }, @@ -216,7 +252,7 @@ void bind_gear_factories(py::module_& gear) { gear.def( "make_herringbone_rack_rsolid", - [](double module, int n_teeth, double pressure_angle, double helix_angle, double rack_height) { + [](Length module, Count n_teeth, Angle pressure_angle, Angle helix_angle, Length rack_height) { return unlocked( [&] { return make_herringbone_rack_rsolid(module, n_teeth, pressure_angle, helix_angle, rack_height); }); }, @@ -372,8 +408,8 @@ void bind_gear_internals(py::module_& gear) { void bind_chain(py::module_& chain) { chain.def( "make_roller_chain_sprocket_rsolid", - [](const py::object& n_teeth, double chain_pitch, double roller_diameter, double sprocket_thickness, - double bore_radius, double roller_clearance) { + [](const CountArg& n_teeth, Length chain_pitch, Length roller_diameter, Length sprocket_thickness, + Length bore_radius, Length roller_clearance) { if (!is_plain_int(n_teeth)) throw ValueError("n_teeth must be an integer of at least 6"); const int teeth = python_int(n_teeth); @@ -396,11 +432,11 @@ void bind_chain(py::module_& chain) { void bind_fastener(py::module_& fastener) { fastener.def( "make_bolt_rsolid", - [](double diameter, double length, const py::object& head_style, const py::object& thread_style, - const py::object& thread_detail, const py::object& thread_form, std::optional thread_pitch, - std::optional thread_depth, std::optional thread_length, std::optional head_width, - std::optional head_height, const py::object& drive_style, std::optional drive_size, - std::optional drive_depth, std::optional underhead_fillet_radius) { + [](Length diameter, Length length, const HeadStyleArg& head_style, const ThreadStyleArg& thread_style, + const ThreadDetailArg& thread_detail, const ThreadFormArg& thread_form, std::optional thread_pitch, + std::optional thread_depth, std::optional thread_length, std::optional head_width, + std::optional head_height, const DriveStyleArg& drive_style, std::optional drive_size, + std::optional drive_depth, std::optional underhead_fillet_radius) { BoltOptions options; options.head_style = text_of(head_style); options.thread_style = text_of(thread_style); @@ -430,9 +466,9 @@ void bind_fastener(py::module_& fastener) { fastener.def( "make_nut_rsolid", - [](double diameter, double width, double height, const py::object& nut_style, const py::object& hole_style, - const py::object& thread_detail, const py::object& thread_form, std::optional thread_pitch, - std::optional thread_depth, std::optional hole_depth, const py::object& knurl_count) { + [](Length diameter, Length width, Length height, const NutStyleArg& nut_style, const HoleStyleArg& hole_style, + const ThreadDetailArg& thread_detail, const ThreadFormArg& thread_form, std::optional thread_pitch, + std::optional thread_depth, std::optional hole_depth, const CountArg& knurl_count) { NutOptions options; options.nut_style = text_of(nut_style); options.hole_style = text_of(hole_style); @@ -460,10 +496,10 @@ void bind_fastener(py::module_& fastener) { void bind_bearing(py::module_& bearing) { bearing.def( "make_ball_bearing_rassembly", - [](double bore_diameter, double outer_diameter, double bearing_width, double ball_diameter, - const py::object& ball_count, double raceway_clearance, double edge_chamfer, std::string assembly_id, - std::optional drive_angle_degrees, bool fuse_rolling_elements, double rolling_element_fuse_overlap, - const py::object& material) { + [](Length bore_diameter, Length outer_diameter, Length bearing_width, Length ball_diameter, + const CountOrNoneArg& ball_count, Length raceway_clearance, Length edge_chamfer, std::string assembly_id, + std::optional drive_angle_degrees, bool fuse_rolling_elements, Length rolling_element_fuse_overlap, + const MaterialOrNoneArg& material) { BallBearingOptions options; if (!ball_count.is_none()) options.ball_count = python_int(ball_count); diff --git a/src/cpp/bindings/python/typed_args.hpp b/src/cpp/bindings/python/typed_args.hpp new file mode 100644 index 00000000..c68a9276 --- /dev/null +++ b/src/cpp/bindings/python/typed_args.hpp @@ -0,0 +1,91 @@ +// Signature types for bindings that convert their arguments themselves. +// +// Some operations take py::object and check the type inside the operation (the product operators, so a wrong type is +// the operation's SimpleCADError, not a pybind overload error), or read a value the Python way (`str(value)`, +// `int(value)`). Their signature would read `object`. `Typed` keeps the py::object (it accepts anything, as +// before) and prints Name in the signature; `Shown` converts exactly as T does and prints Name. The body of +// the binding does not change: both convert to what it took before. +// +// const Typed& part part: simplecadapi._cpp._native.Part (any object reaches the body) +// Shown diameter diameter: simplecadapi.types.Length (loaded as a double) +// +// A name is a struct with `static constexpr auto name = `; the class names come from the registered +// types (`type_name()`), so they print the way pybind prints the class itself. +#pragma once + +#include + +#include + +#include "semantic_types.hpp" + +namespace scad::pybind { + +template +struct Typed { + pybind11::object value; + operator const pybind11::object&() const { return value; } // NOLINT(google-explicit-constructor) + bool is_none() const { return value.is_none(); } + template + T cast() const { + return value.cast(); + } +}; + +template +struct Shown { + T value; + operator const T&() const { return value; } // NOLINT(google-explicit-constructor) +}; + +// The descr pybind prints for a bound class. +template +constexpr auto type_name() { + return pybind11::detail::make_caster::name; +} + +// Words for the names. +inline constexpr auto kOr = pybind11::detail::const_name(" | "); +inline constexpr auto kOrNone = pybind11::detail::const_name(" | None"); + +} // namespace scad::pybind + +// Declares a name struct: SCAD_SIGNATURE_NAME(PartName, type_name()); +#define SCAD_SIGNATURE_NAME(Struct, ...) \ + struct Struct { \ + static constexpr auto name = (__VA_ARGS__); \ + } + +namespace pybind11::detail { + +template +struct type_caster> { + PYBIND11_TYPE_CASTER(scad::pybind::Typed, Name::name); + + bool load(handle src, bool /*convert*/) { + if (!src) + return false; + value.value = reinterpret_borrow(src); + return true; + } + static handle cast(const scad::pybind::Typed& v, return_value_policy, handle) { return v.value.inc_ref(); } +}; + +template +struct type_caster> { + using Self = scad::pybind::Shown; // the macro takes no comma + PYBIND11_TYPE_CASTER(Self, Name::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::Shown& v, return_value_policy policy, handle parent) { + return make_caster::cast(v.value, policy, parent); + } +}; + +} // namespace pybind11::detail diff --git a/src/simplecadapi/_glue/render.py b/src/simplecadapi/_glue/render.py index 9b73193d..6af26479 100644 --- a/src/simplecadapi/_glue/render.py +++ b/src/simplecadapi/_glue/render.py @@ -10,9 +10,12 @@ from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Tuple, Union +import os +from typing import Any, Dict, List, Literal, Optional, Tuple, Union from ..errors import raise_harness_error +from ..types import Angle, Direction3, Length +from simplecadapi._cpp import AnyShape, Solid def _shape_types() -> tuple: @@ -167,29 +170,35 @@ def _execute_screenshot_render(prepared: Any) -> str: def render_screenshot_rpath( - shapes: Any, - output_path: str, - highlight_tags: Optional[Sequence[str]] = None, - tag_labels: Optional[Dict[str, str]] = None, - image_size: Tuple[int, int] = (1400, 900), - view: Union[Tuple[float, float], str] = "auto", - views: Optional[Sequence[Tuple[float, float, str]]] = None, + shapes: Solid | Sequence[Solid], + output_path: str | os.PathLike[str], + highlight_tags: Sequence[str] | None = None, + tag_labels: dict[str, str] | None = None, + image_size: tuple[int, int] = (1400, 900), + view: Literal[ + "auto", "iso", "isometric", "top", "bottom", "front", "back", "left", "right", + "front_right", "front_left", "rear_right", "rear_left", + ] | tuple[Angle, Angle] | None = "auto", + views: Sequence[tuple[Angle, Angle, str]] | None = None, show_axes: bool = True, show_legend: bool = True, zoom: float = 4.0, show_callouts: bool = True, - linear_deflection: Optional[float] = None, - angular_deflection: Optional[float] = None, - style: str = "studio", - edge_width_scale: Optional[float] = None, - view_up: Optional[Sequence[float]] = None, + linear_deflection: Length | None = None, + angular_deflection: float | None = None, + style: Literal["studio", "standard"] = "studio", + edge_width_scale: float | None = None, + view_up: Direction3 | None = None, supersample: int = 2, - highlight_edges: Optional[Sequence[Any]] = None, + highlight_edges: Sequence[AnyShape] | None = None, highlight_edge_width: float = 4.5, ) -> str: """Render solids through the software renderer (no OCP, VTK or display needed). - Same contract as ``simplecadapi.render_screenshot_rpath`` of the ``ocp`` backend. + Same contract as ``simplecadapi.render_screenshot_rpath`` of the ``ocp`` backend. ``shapes`` is a Solid or a + (nested) sequence of Solids; ``view`` is a preset name (matched case-insensitively) or ``(elevation, azimuth)`` + in degrees, and ``views`` a list of ``(elevation, azimuth, label)`` panels; ``linear_deflection`` is the + tessellation tolerance in mm, ``angular_deflection`` in radians. """ prepared = _prepare_screenshot_render( diff --git a/src/simplecadapi/catalog.py b/src/simplecadapi/catalog.py index a1d4fd6d..0bf6f96e 100644 --- a/src/simplecadapi/catalog.py +++ b/src/simplecadapi/catalog.py @@ -10,10 +10,12 @@ functions with the same annotations. The catalog parses both, so a GUI, an agen [('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 +``direction3``, ``vector3``, ``count``), ``number`` (a unitless ``float | Expr``), ``int``, ``bool``, ``text``, ``path`` +(``str | os.PathLike``), ``enum`` (``Literal[...]``, with ``choices``), a value type (``solid``, ``face``, ``wire``, +``edge``, ``vertex``, ``shell``, ``shape``, ``sketch``, ``part``, ``assembly``, ``scalar_limit``, ...), ``query`` (a +``ql`` selection), ``points`` / ``numbers`` (sequences), ``_map`` (``dict[str, ]``: a value per id), +``|`` (a union of kinds, e.g. ``enum|numbers`` or ``query|shape``), or ``unknown`` when the signature says no +more than ``object``. ``many`` marks a sequence of the kind, ``optional`` a ``None`` default. """ @@ -56,6 +58,9 @@ _VALUE_KINDS = { "ShapeSelector": "query", "Vec3": "vector3", "SketchPosition": "sketch_ref", + "ScalarLimit": "scalar_limit", + "PathLike": "path", + "Path": "path", } @@ -121,7 +126,9 @@ def classify(type_text: str) -> dict[str, Any]: union = [u for u in union if u != "None"] if not union: return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} - text = " | ".join(union) + if len(union) > 1: + return _classify_union(union, optional) + text = union[0] annotated = re.fullmatch(r"Annotated\[(.*)\]", text) if annotated: inner, *meta = _split_top(annotated.group(1), ",") @@ -147,7 +154,19 @@ def classify(type_text: str) -> dict[str, Any]: 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, "|")] + mapping = re.fullmatch(r"(?:dict|Dict|Mapping)\[(.*)\]", text) + if mapping: # a value per name (component id, tag ...): ``direction3_map``, ``number_map``, ``text_map`` + key_and_value = _split_top(mapping.group(1), ",") + inner = classify(key_and_value[-1]) + if inner["kind"] == "unknown" or inner["many"]: + return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} + return {"kind": f"{inner['kind']}_map", "many": False, "optional": optional, "choices": inner["choices"]} + return _classify_names([text], optional) + + +def _classify_names(names: list[str], optional: bool) -> dict[str, Any]: + """Plain type names (no brackets but ``PathLike[str]``), alone or as a union.""" + names = [re.sub(r"^(PathLike)\[.*\]$", r"\1", n.strip()) for n in names] 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"}: @@ -156,6 +175,8 @@ def classify(type_text: str) -> dict[str, Any]: return {"kind": "bool", "many": False, "optional": optional, "choices": ()} if names == ["str"]: return {"kind": "text", "many": False, "optional": optional, "choices": ()} + if set(names) <= {"str", "PathLike", "Path"} and set(names) != {"str"}: # a file path, as text or os.PathLike + return {"kind": "path", "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} @@ -165,6 +186,25 @@ def classify(type_text: str) -> dict[str, Any]: return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} +def _classify_union(union: list[str], optional: bool) -> dict[str, Any]: + """``A | B``: plain names as one kind (``float | Expr`` is a number), else the kinds of the members joined. + + ``Solid | Sequence[Solid]`` is one solid or many (``many``); ``Literal[...] | tuple[Angle, Angle]`` is + ``enum|numbers`` with the choices of the Literal. + """ + if "SketchRef" in union: # 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": ()} + if not any("[" in u for u in union) or all(re.fullmatch(r"PathLike\[.*\]", u) for u in union if "[" in u): + return _classify_names(union, optional) + infos = [classify(u) for u in union] + if any(info["kind"] == "unknown" for info in infos): + return {"kind": "unknown", "many": False, "optional": optional, "choices": ()} + kinds = sorted({info["kind"] for info in infos}) + choices = next((info["choices"] for info in infos if info["choices"]), ()) + return {"kind": "|".join(kinds), "many": any(info["many"] for info in infos), "optional": optional or any(info["optional"] for info in infos), + "choices": choices} + + def _returns(type_text: str) -> str: info = classify(type_text) if info["many"]: @@ -197,7 +237,8 @@ def _summary(fn: Callable[..., Any]) -> str: 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: + source = re.sub(r"<\w+(?:\.\w+)+: ('[^'<>]*')>", r"\1", line) # a str enum member: + source = re.sub(r"<[^<>]*>", "None", source) # defaults pybind cannot print: tree = ast.parse(f"def {source}: pass") fn = tree.body[0] assert isinstance(fn, ast.FunctionDef) diff --git a/src/simplecadapi/std/bearing.py b/src/simplecadapi/std/bearing.py index 7b0c4830..e8650bd3 100644 --- a/src/simplecadapi/std/bearing.py +++ b/src/simplecadapi/std/bearing.py @@ -41,6 +41,7 @@ from simplecadapi._cpp import ( union_rsolid, ) from ..topology.tracking import graph_tracking_scope +from ..types import Angle, Count, Length __all__ = ["build_ball_bearing", "make_ball_bearing_rassembly"] @@ -237,18 +238,18 @@ def _ball_placement(ball_pitch_radius: float, angle_degrees: float): @graph_tracking_scope def make_ball_bearing_rassembly( - bore_diameter: float, - outer_diameter: float, - bearing_width: float, - ball_diameter: float, - ball_count: Optional[int] = None, - raceway_clearance: float = 0.02, - edge_chamfer: float = 0.0, + bore_diameter: Length, + outer_diameter: Length, + bearing_width: Length, + ball_diameter: Length, + ball_count: Count | None = None, + raceway_clearance: Length = 0.02, + edge_chamfer: Length = 0.0, assembly_id: str = "ball_bearing", - drive_angle_degrees: Optional[float] = None, + drive_angle_degrees: Angle | None = None, fuse_rolling_elements: bool = False, - rolling_element_fuse_overlap: float = 0.01, - material: Optional[Material] = None, + rolling_element_fuse_overlap: Length = 0.01, + material: Material | None = None, ) -> Assembly: """Create a parameterized radial ball bearing assembly.