Skip to main content

fhy_core_py/
lib.rs

1//! `PyO3` bindings for `fhy-core`'s Rust implementation, as a library that a
2//! Python extension module is composed from.
3//!
4//! # Composition
5//!
6//! Each `PyO3` extension module links its own copy of every Rust crate it
7//! uses, so two extension modules that both link `fhy-core` in one Python
8//! process hold two identifier id counters, two registries per interned
9//! type and two sets of Python classes. This crate therefore builds no
10//! extension module itself. It is an `rlib` that adds its classes and
11//! functions to a module it is given, so that **one** `cdylib` per product
12//! links `fhy-core`, this crate, and the binding crates of the packages that
13//! build on `fhy_core`, and registers all of them into **one** module:
14//!
15//! - `fhy_core`'s own extension, `fhy_core._rs`, is the `fhy-core-ext`
16//!   crate, whose one `#[pymodule]` calls [`register`];
17//! - an aggregate extension for a downstream product is a `cdylib` whose
18//!   `#[pymodule]` calls [`register`] and then its own crates' registration
19//!   functions, and takes and returns `fhy-core` values through [`convert`].
20//!   Its classes are written over the building blocks of [`util`], as `fhy_core`'s are.
21//!
22//! The split into a library and a thin `cdylib` is deliberate. A `#[pymodule]`
23//! exports a `PyInit_<name>` symbol, which an `rlib` that is linked into an
24//! aggregate would export from it too, so a crate that is both the module and
25//! the library cannot be linked into an aggregate whose module has the same
26//! name, and every aggregate would export a second module's initializer.
27//!
28//! # Class identity
29//!
30//! Every `#[pyclass]` here names its module explicitly, `module =
31//! "fhy_core._rs"`, and so keeps the qualified name users see, such as
32//! `fhy_core._rs.Param`, whichever native module holds it: `__module__`,
33//! `repr`, and `pickle`, which imports the class by that name, all follow
34//! it. The binding also finds its own module state by that name, through
35//! `sys.modules["fhy_core._rs"]`. An aggregate module is therefore
36//! installed as `fhy_core._rs` as well as under its own name, which
37//! `fhy_core._extension` does when it loads the module: the loader documents
38//! the protocol.
39//!
40//! # Module state and version
41//!
42//! [`register`] creates the verification registry of the Python API and
43//! the kind registry of `fhy_core.search_space` in the module's state, and
44//! sets [`VERSION_ATTRIBUTE`], the version of this crate,
45//! which the loader compares with the installed package's. It refuses a
46//! module it has registered into already.
47
48mod constraint;
49mod described_tag;
50mod diagnostic;
51mod error;
52mod expression;
53mod identifier;
54mod lattice;
55mod object_table;
56mod op_attribute;
57mod param;
58mod pass;
59mod provenance;
60mod search_space;
61mod solver;
62mod symbol_table;
63mod term;
64mod types;
65mod value_domain;
66mod wire;
67
68pub mod convert;
69pub mod util;
70
71use pyo3::prelude::*;
72
73/// The attribute of a module [`register`] was called on that holds this
74/// crate's version, which is `fhy_core`'s.
75///
76/// `fhy_core._extension` compares it with the installed `fhy_core`'s
77/// version, so a stale aggregate is refused as a stale `fhy_core._rs` is.
78pub const VERSION_ATTRIBUTE: &str = "__fhy_core_version__";
79
80/// Add every class, function and piece of module state of `fhy_core`'s
81/// binding to `module`.
82///
83/// The classes keep their `fhy_core._rs` qualified names whichever module
84/// holds them. The module must be reachable as `fhy_core._rs` for the
85/// binding to work (see the [crate documentation](crate)); the loader of
86/// the Python package arranges that.
87///
88/// # Errors
89///
90/// Raises `RuntimeError` if `module` has been registered into already, and
91/// whatever adding an item to the module raises.
92pub fn register(py: Python<'_>, module: &Bound<'_, PyModule>) -> PyResult<()> {
93    if module.hasattr(VERSION_ATTRIBUTE)? {
94        return Err(pyo3::exceptions::PyRuntimeError::new_err(format!(
95            "the module {} holds fhy_core's classes already",
96            module.name()?
97        )));
98    }
99    register_part_1(module)?;
100    register_part_2(module)?;
101    register_part_3(module)?;
102    register_part_4(module)?;
103    register_part_5(module)?;
104    module.add(VERSION_ATTRIBUTE, env!("CARGO_PKG_VERSION"))?;
105    module.add(
106        pass::REGISTRY_ATTRIBUTE,
107        Py::new(py, pass::PyVerificationRegistry::new())?,
108    )?;
109    module.add(
110        search_space::KIND_REGISTRY_ATTRIBUTE,
111        Py::new(py, search_space::PyKindRegistry::new())?,
112    )
113}
114
115/// Add the classes and functions of the `constraint`, `diagnostic` and `expression` modules.
116fn register_part_1(module: &Bound<'_, PyModule>) -> PyResult<()> {
117    module.add_class::<constraint::PyConstraintSystem>()?;
118    module.add_class::<constraint::PyEquationConstraint>()?;
119    module.add_class::<constraint::PyInSetConstraint>()?;
120    module.add_class::<constraint::PyNotInSetConstraint>()?;
121    module.add_function(wrap_pyfunction!(
122        constraint::does_member_lift_to_expression,
123        module
124    )?)?;
125    module.add_class::<diagnostic::PyDiagnostic>()?;
126    module.add_class::<diagnostic::PyNote>()?;
127    module.add_class::<diagnostic::PyNoteKind>()?;
128    module.add_class::<diagnostic::PyValidationReport>()?;
129    module.add_class::<expression::PyAlternativesPattern>()?;
130    module.add_class::<expression::PyBinaryExpressionPattern>()?;
131    module.add_class::<expression::PyCallExpressionPattern>()?;
132    module.add_class::<expression::PyCapture>()?;
133    module.add_class::<expression::PyCapturePattern>()?;
134    module.add_class::<expression::PyFiredRule>()?;
135    module.add_class::<expression::PyIdentifierPattern>()?;
136    module.add_class::<expression::PyLiteralPattern>()?;
137    module.add_class::<expression::PyLogicalExpressionPattern>()?;
138    module.add_class::<expression::PyMatchBindings>()?;
139    module.add_class::<expression::PyPattern>()?;
140    module.add_class::<expression::PyPiecewiseExpressionPattern>()?;
141    module.add_class::<expression::PyPredicatePattern>()?;
142    module.add_class::<expression::PyRewriteRule>()?;
143    module.add_class::<expression::PyRuleBase>()?;
144    module.add_class::<expression::PyUnaryExpressionPattern>()?;
145    module.add_class::<expression::PyWildcardPattern>()?;
146    module.add_function(wrap_pyfunction!(expression::apply_rewrite_rules, module)?)?;
147    module.add_class::<expression::PyBinaryExpression>()?;
148    module.add_class::<expression::PyCallExpression>()?;
149    module.add_class::<expression::PyExpression>()?;
150    module.add_class::<expression::PyIdentifierExpression>()?;
151    module.add_class::<expression::PyLiteralExpression>()?;
152    module.add_class::<expression::PyLogicalExpression>()?;
153    module.add_class::<expression::PyPiecewiseExpression>()?;
154    module.add_class::<expression::PyUnaryExpression>()?;
155    module.add_function(wrap_pyfunction!(
156        expression::validate_logical_operands,
157        module
158    )?)?;
159    module.add_function(wrap_pyfunction!(expression::validate_predicate, module)?)?;
160    module.add_class::<expression::PyBuiltinNativeImplementation>()?;
161    module.add_function(wrap_pyfunction!(expression::coerce_literal_value, module)?)?;
162    module.add_function(wrap_pyfunction!(
163        expression::evaluate_expression_with_numpy,
164        module
165    )?)?;
166    module.add_function(wrap_pyfunction!(expression::fold_expression, module)?)?;
167    module.add_class::<expression::PyAffineForm>()?;
168    module.add_function(wrap_pyfunction!(expression::affine_form, module)?)?;
169    module.add_function(wrap_pyfunction!(
170        expression::is_decimal_text_exactly_binary,
171        module
172    )?)?;
173    module.add_class::<expression::PyNativeConstant>()?;
174    module.add_class::<expression::PyNativeFunction>()?;
175    module.add_class::<expression::PyRegisteredFunction>()?;
176    module.add_function(wrap_pyfunction!(
177        expression::get_native_constant_identifier,
178        module
179    )?)?;
180    module.add_function(wrap_pyfunction!(
181        expression::get_registered_entries,
182        module
183    )?)?;
184    module.add_function(wrap_pyfunction!(expression::get_registered_entry, module)?)?;
185    module.add_function(wrap_pyfunction!(expression::inline_functions, module)?)?;
186    module.add_function(wrap_pyfunction!(expression::is_entry_registered, module)?)?;
187    module.add_function(wrap_pyfunction!(expression::register_function, module)?)?;
188    module.add_function(wrap_pyfunction!(
189        expression::register_native_constant,
190        module
191    )?)?;
192    module.add_function(wrap_pyfunction!(
193        expression::register_native_function,
194        module
195    )?)?;
196    module.add_function(wrap_pyfunction!(expression::set_registry_state, module)?)?;
197    module.add_function(wrap_pyfunction!(
198        expression::try_get_native_constant_for_identifier,
199        module
200    )?)?;
201    module.add_function(wrap_pyfunction!(
202        expression::try_get_registered_result_sort,
203        module
204    )?)?;
205    Ok(())
206}
207
208/// Add the classes and functions of the `param`, `pass`, `provenance`, `solver`, `symbol_table`, `term` modules.
209fn register_part_2(module: &Bound<'_, PyModule>) -> PyResult<()> {
210    module.add_class::<param::PyCategoricalDomain>()?;
211    module.add_class::<param::PyIntegerDomain>()?;
212    module.add_class::<param::PyIntervalIntegerDomain>()?;
213    module.add_class::<param::PyOrdinalDomain>()?;
214    module.add_class::<param::PyParam>()?;
215    module.add_class::<param::PyParamAssignment>()?;
216    module.add_class::<param::PyPermutationDomain>()?;
217    module.add_class::<param::PyRealDomain>()?;
218    module.add_function(wrap_pyfunction!(
219        param::are_all_constraints_satisfied,
220        module
221    )?)?;
222    module.add_function(wrap_pyfunction!(
223        param::check_param_bounds_are_ordered,
224        module
225    )?)?;
226    module.add_function(wrap_pyfunction!(
227        param::compute_constraint_implication_subset,
228        module
229    )?)?;
230    module.add_function(wrap_pyfunction!(param::evaluate_system_outcome, module)?)?;
231    module.add_function(wrap_pyfunction!(param::is_bound_expression, module)?)?;
232    module.add_class::<pass::PyAnalysisBase>()?;
233    module.add_class::<pass::PyAnalysisManager>()?;
234    module.add_class::<pass::PyCompilerPassBase>()?;
235    module.add_class::<pass::PyFixpointGroupRecord>()?;
236    module.add_class::<pass::PyFixpointIterationRecord>()?;
237    module.add_class::<pass::PyFixpointPassGroup>()?;
238    module.add_class::<pass::PyPassManager>()?;
239    module.add_class::<pass::PyPassManagerResult>()?;
240    module.add_class::<pass::PyPassResult>()?;
241    module.add_class::<pass::PyPassRunRecord>()?;
242    module.add_class::<pass::PyPreservedAnalyses>()?;
243    module.add_class::<pass::PyValidationManager>()?;
244    module.add_class::<pass::PyValidatorBase>()?;
245    module.add_class::<pass::PyValidatorRecord>()?;
246    module.add_function(wrap_pyfunction!(pass::get_verification_passes_for, module)?)?;
247    module.add_function(wrap_pyfunction!(pass::register_verification_pass, module)?)?;
248    module.add_function(wrap_pyfunction!(pass::run_verification, module)?)?;
249    module.add_class::<provenance::PyCallSiteProvenance>()?;
250    module.add_class::<provenance::PyFileProvenance>()?;
251    module.add_class::<provenance::PyFusedProvenance>()?;
252    module.add_class::<provenance::PyNamedProvenance>()?;
253    module.add_class::<provenance::PyPosition>()?;
254    module.add_class::<provenance::PyProvenance>()?;
255    module.add_class::<provenance::PySpan>()?;
256    module.add_class::<provenance::PyUnknownProvenance>()?;
257    module.add_class::<solver::PyGroundSimplifier>()?;
258    module.add_class::<solver::PySatResult>()?;
259    module.add_class::<solver::PySimplifierBase>()?;
260    module.add_class::<solver::PySimplifyContext>()?;
261    module.add_class::<solver::PySmtLib2ProcessSolver>()?;
262    module.add_class::<solver::PySmtScript>()?;
263    module.add_class::<solver::PySmtSolverBase>()?;
264    module.add_class::<solver::PySolver>()?;
265    module.add_class::<solver::PySympySimplifier>()?;
266    module.add_function(wrap_pyfunction!(solver::get_default_solver, module)?)?;
267    module.add_function(wrap_pyfunction!(solver::set_default_solver, module)?)?;
268    module.add_class::<symbol_table::PyFunctionSymbolTableFrame>()?;
269    module.add_class::<symbol_table::PyImportSymbolTableFrame>()?;
270    module.add_class::<symbol_table::PySymbolTable>()?;
271    module.add_class::<symbol_table::PyVariableSymbolTableFrame>()?;
272    module.add_class::<term::PyAlphaRenaming>()?;
273    module.add_class::<term::PyEquivalenceRole>()?;
274    module.add_function(wrap_pyfunction!(term::binder_get_free_identifiers, module)?)?;
275    module.add_function(wrap_pyfunction!(
276        term::binder_is_alpha_equivalent_under,
277        module
278    )?)?;
279    module.add_function(wrap_pyfunction!(term::binder_substitute, module)?)?;
280    module.add_function(wrap_pyfunction!(
281        term::derived_is_alpha_equivalent_under,
282        module
283    )?)?;
284    module.add_function(wrap_pyfunction!(
285        term::derived_is_structurally_equivalent,
286        module
287    )?)?;
288    module.add_function(wrap_pyfunction!(
289        term::is_identifier_mapping_alpha_equivalent_under,
290        module
291    )?)?;
292    Ok(())
293}
294
295/// Add the classes and functions of the `types`, `value_domain`, `wire` modules.
296fn register_part_3(module: &Bound<'_, PyModule>) -> PyResult<()> {
297    module.add_class::<types::PyDataTypeBase>()?;
298    module.add_class::<types::PyIndexType>()?;
299    module.add_class::<types::PyNumericalType>()?;
300    module.add_class::<types::PyPrimitiveDataType>()?;
301    module.add_class::<types::PyTemplateDataType>()?;
302    module.add_class::<types::PyTypeBase>()?;
303    module.add_class::<types::PyTypeUnificationEnvironment>()?;
304    module.add_function(wrap_pyfunction!(
305        types::get_core_data_type_bit_width,
306        module
307    )?)?;
308    module.add_function(wrap_pyfunction!(types::is_weak_core_data_type, module)?)?;
309    module.add_function(wrap_pyfunction!(types::promote_core_data_types, module)?)?;
310    module.add_function(wrap_pyfunction!(
311        types::promote_primitive_data_types,
312        module
313    )?)?;
314    module.add_function(wrap_pyfunction!(types::promote_type_qualifiers, module)?)?;
315    module.add_function(wrap_pyfunction!(
316        types::resolve_literal_core_data_type,
317        module
318    )?)?;
319    module.add_function(wrap_pyfunction!(types::types_bind_data_template, module)?)?;
320    module.add_function(wrap_pyfunction!(types::types_bind_template, module)?)?;
321    module.add_function(wrap_pyfunction!(
322        types::types_is_structurally_equivalent,
323        module
324    )?)?;
325    module.add_function(wrap_pyfunction!(
326        types::types_substitute_data_template,
327        module
328    )?)?;
329    module.add_function(wrap_pyfunction!(types::types_substitute_template, module)?)?;
330    module.add_function(wrap_pyfunction!(types::types_unify, module)?)?;
331    module.add_function(wrap_pyfunction!(types::types_unify_expression, module)?)?;
332    module.add_function(wrap_pyfunction!(
333        types::get_core_data_type_from_literal_type,
334        module
335    )?)?;
336    module.add_function(wrap_pyfunction!(
337        types::get_result_core_data_type_for_sort,
338        module
339    )?)?;
340    module.add_function(wrap_pyfunction!(
341        types::is_core_data_type_compatible_with_sort,
342        module
343    )?)?;
344    module.add_function(wrap_pyfunction!(
345        types::types_check_all_function_bodies,
346        module
347    )?)?;
348    module.add_function(wrap_pyfunction!(types::types_check_expression, module)?)?;
349    module.add_function(wrap_pyfunction!(types::types_check_function_body, module)?)?;
350    module.add_class::<value_domain::PyValueDomain>()?;
351    module.add_function(wrap_pyfunction!(wire::decode_wire_family, module)?)?;
352    module.add_function(wrap_pyfunction!(wire::decode_wire_family_json, module)?)?;
353    module.add_function(wrap_pyfunction!(wire::deserialize_wire_value, module)?)?;
354    module.add_function(wrap_pyfunction!(wire::encode_wire_dict, module)?)?;
355    module.add_function(wrap_pyfunction!(wire::encode_wire_json, module)?)?;
356    module.add_function(wrap_pyfunction!(wire::serialize_wire_value, module)?)?;
357    Ok(())
358}
359
360/// Add the classes and functions of the `search_space` module.
361fn register_part_4(module: &Bound<'_, PyModule>) -> PyResult<()> {
362    module.add_class::<search_space::PyAlternativeBase>()?;
363    module.add_class::<search_space::PyChoice>()?;
364    module.add_class::<search_space::PyCondition>()?;
365    module.add_class::<search_space::PyConfiguration>()?;
366    module.add_class::<search_space::PyConfigurationKey>()?;
367    module.add_class::<search_space::PyForbidden>()?;
368    module.add_class::<search_space::PySpace>()?;
369    module.add_class::<search_space::PyVariableBase>()?;
370    module.add_class::<search_space::PyRng>()?;
371    module.add_class::<search_space::PyChoiceDomain>()?;
372    module.add_class::<search_space::PyOrderDomain>()?;
373    module.add_class::<search_space::PyStridedRun>()?;
374    module.add_class::<search_space::PyStridedDomain>()?;
375    module.add_class::<search_space::PyPendingStep>()?;
376    module.add_class::<search_space::PyRandomOracle>()?;
377    module.add_class::<search_space::PyReplayOracle>()?;
378    module.add_class::<search_space::PyGuidedOracle>()?;
379    module.add_class::<search_space::PyExhaustiveOracle>()?;
380    module.add_class::<search_space::PyRecorder>()?;
381    module.add_class::<search_space::PyTraceStep>()?;
382    module.add_class::<search_space::PyTrace>()?;
383    module.add_class::<search_space::PyTraceKey>()?;
384    module.add_class::<search_space::PyObjective>()?;
385    module.add_class::<search_space::PyMeasurement>()?;
386    module.add_function(wrap_pyfunction!(
387        search_space::get_search_space_kind_class,
388        module
389    )?)?;
390    module.add_function(wrap_pyfunction!(search_space::non_dominated, module)?)?;
391    Ok(())
392}
393
394/// Add the classes and functions of the `identifier`, `lattice` and `op_attribute` modules.
395fn register_part_5(module: &Bound<'_, PyModule>) -> PyResult<()> {
396    module.add_function(wrap_pyfunction!(
397        identifier::advance_identifier_counter_past,
398        module
399    )?)?;
400    module.add_function(wrap_pyfunction!(
401        identifier::allocate_identifier_id,
402        module
403    )?)?;
404    module.add_function(wrap_pyfunction!(identifier::next_identifier_id, module)?)?;
405    module.add_class::<lattice::PyLattice>()?;
406    module.add_class::<lattice::PyPartiallyOrderedSet>()?;
407    module.add_class::<op_attribute::PyOpAttribute>()?;
408    Ok(())
409}