Skip to main content

lemma/
lib.rs

1//! # Lemma Engine
2//!
3//! **Rules for man and machine**
4//!
5//! Consumer API: **`load`** → **`list`** → **`show`** / **`source`** → **`run`**.
6
7#[cfg(test)]
8mod tests;
9
10pub mod api;
11pub(crate) mod computation;
12pub mod documentation;
13pub(crate) mod engine;
14pub(crate) mod error;
15pub(crate) mod evaluation;
16pub(crate) mod formatting;
17pub(crate) mod limits;
18pub(crate) mod literals;
19pub(crate) mod parsing;
20pub(crate) mod planning;
21pub mod quality;
22pub(crate) mod registry;
23pub mod result_value;
24pub(crate) mod snapshot;
25pub(crate) mod spec_set_id;
26pub(crate) mod stdlib;
27pub(crate) mod string_distance;
28
29#[cfg(not(target_arch = "wasm32"))]
30pub mod deps;
31
32#[cfg(not(target_arch = "wasm32"))]
33pub mod mcp;
34
35#[cfg(target_arch = "wasm32")]
36pub mod wasm;
37
38pub use computation::{OperationResult, VetoType};
39pub use engine::{
40    resolve_effective, Engine, Errors, ListedSpec, ResolvedRepository, EMBEDDED_STDLIB_REPOSITORY,
41};
42pub use error::{
43    EngineError, EngineErrorSource, Error, ErrorDetails, ErrorKind, RegistryErrorKind,
44    RequestErrorKind,
45};
46pub use evaluation::explanations::{format_explanation, Cause, Explanation, ExplanationNode};
47pub use evaluation::response::{Response, RuleResult};
48pub use evaluation::run_data::{
49    parse_run_data_object, resolve_run_rules, run_data_value_from_json_value, RunDataValue,
50};
51pub use formatting::{format_parse_result, format_source, format_specs};
52pub use limits::{
53    ResourceLimits, MAX_DATA_NAME_LENGTH, MAX_RULE_NAME_LENGTH, MAX_SPEC_NAME_LENGTH,
54};
55pub use literals::{DateGranularity, MeasureUnit, MeasureUnits, RatioUnit, RatioUnits};
56pub use parsing::ast::DateTimeValue;
57pub use parsing::source::SourceType;
58pub use planning::execution_plan::type_detail_lines;
59pub use planning::execution_plan::{
60    Show, ShowBranch, ShowConversionTarget, ShowData, ShowExpression, ShowRule, ShowVersion,
61};
62pub use planning::explanation::{ConversionTraceRole, SerializedConversionTraceStep};
63pub use planning::semantics::{DataPath, LemmaType, LiteralValue, TypeSpecification, ValueKind};
64pub use result_value::{CalendarResult, RangeResult, RuleResultValue, RuleResultValueFailure};
65pub use spec_set_id::parse_spec_set_id;
66pub use stdlib::UNITS_LEMMA;
67
68/// Exact rational helpers for in-tree integration tests. Not a supported consumer API.
69#[doc(hidden)]
70pub mod __test_support {
71    pub use crate::computation::rational::{
72        checked_div, checked_mul, decimal_to_rational, rational_new,
73    };
74    pub use crate::literals::TimeValue;
75    pub use crate::planning::semantics::{
76        SemanticDateTime, SemanticTime, SemanticTimezone, TypedLiteral,
77    };
78
79    /// Serializes an [`Error`](crate::Error) as [`EngineError`](crate::EngineError).
80    pub fn current_binding_error_json(error: &crate::Error) -> serde_json::Value {
81        serde_json::to_value(crate::EngineError::from(error))
82            .expect("BUG: EngineError must serialize")
83    }
84
85    #[cfg(not(target_arch = "wasm32"))]
86    pub use fixture_transport::FixtureTransport;
87
88    #[cfg(not(target_arch = "wasm32"))]
89    mod fixture_transport {
90        use crate::registry::{Fetch, Header, HttpResponse, HttpTransport, TransportFailure};
91        use std::collections::HashMap;
92        use std::path::{Path, PathBuf};
93
94        /// Offline [`HttpTransport`] over bundled (or custom) LemmaBase fixture files.
95        ///
96        /// Panics if asked for a URL that is not a LemmaBase source URL.
97        pub struct FixtureTransport {
98            fixtures: HashMap<String, String>,
99        }
100
101        impl FixtureTransport {
102            pub fn new(dir: impl AsRef<Path>) -> Self {
103                let dir = dir.as_ref();
104                let mut fixtures = HashMap::new();
105                collect_fixture_files(dir, dir, &mut fixtures);
106                Self { fixtures }
107            }
108
109            pub fn bundled() -> Self {
110                Self::new(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/registry_fixtures"))
111            }
112        }
113
114        impl HttpTransport for FixtureTransport {
115            fn get(&self, fetch: &Fetch) -> Result<HttpResponse, TransportFailure> {
116                match self.fixtures.get(&fetch.repository) {
117                    Some(body) => Ok(HttpResponse {
118                        status: 200,
119                        headers: Vec::<Header>::new(),
120                        body: body.clone(),
121                    }),
122                    None => Ok(HttpResponse {
123                        status: 404,
124                        headers: Vec::new(),
125                        body: String::new(),
126                    }),
127                }
128            }
129        }
130
131        fn collect_fixture_files(dir: &Path, base: &Path, fixtures: &mut HashMap<String, String>) {
132            let entries = std::fs::read_dir(dir)
133                .unwrap_or_else(|e| panic!("BUG: read fixture dir {}: {e}", dir.display()));
134            for entry in entries {
135                let entry = entry
136                    .unwrap_or_else(|e| panic!("BUG: fixture dir entry in {}: {e}", dir.display()));
137                let path = entry.path();
138                if path.is_dir() {
139                    collect_fixture_files(&path, base, fixtures);
140                    continue;
141                }
142                if path.extension().is_none_or(|e| e != "lemma") {
143                    continue;
144                }
145                let relative = path.strip_prefix(base).unwrap_or_else(|_| {
146                    panic!("BUG: fixture path not under base: {}", path.display())
147                });
148                let identifier = relative
149                    .with_extension("")
150                    .to_string_lossy()
151                    .replace('\\', "/");
152                let content = std::fs::read_to_string(&path)
153                    .unwrap_or_else(|e| panic!("BUG: read fixture {}: {e}", path.display()));
154                fixtures.insert(identifier, content);
155            }
156        }
157    }
158}
159
160// Tier 1 — language surface (always)
161pub use parsing::ast::{
162    try_parse_type_constraint_command, DataValue, Span, SpecRef, TimezoneValue,
163};
164pub use parsing::lexer::{Lexer, TokenKind};
165pub use parsing::source::Source;
166pub use parsing::{parse, ParseResult};
167pub use quality::Recommendation;
168
169// Tier 2 — registry resolution (sans-IO; hosts supply HttpTransport)
170pub use engine::Context;
171pub use parsing::ast::{LemmaRepository, LemmaSpec, RepositoryQualifier};
172pub use planning::LemmaSpecSet;
173pub use registry::{
174    Fetch, Header, HttpResponse, HttpTransport, Install, InstallStep, LemmaBase, Registries,
175    Registry, RegistryBundle, RegistryError, RepositoryInstallResult, Resolve, ResolveStep,
176    TransportFailure,
177};