Skip to main content

Crate lemma

Crate lemma 

Source
Expand description

§Lemma Engine

Rules for man and machine

Lemma is a declarative programming language for expressing rules, data, and business logic in a way that is both human-readable and machine-executable.

§Quick Start

use lemma::{Engine, SourceType};

let mut engine = Engine::new();

// Load Lemma code
engine.load(r#"
    spec example
    data price: 100
    data quantity: 5
    rule total: price * quantity
"#, SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from("example.lemma")))).expect("failed to load");

// Evaluate the spec (all rules, no data values)
let now = lemma::DateTimeValue::now();
let response = engine.run(None, "example", Some(&now), std::collections::HashMap::new(), false, None).unwrap();

§Core Concepts

§Specs

A spec is a collection of data and rules. Specs can reference other Specs to build composable logic.

§Data

Data are named values: numbers, text, dates, booleans, or typed units like 50 kilograms or 100.

§Rules

Rules compute values based on data and other rules. They support conditional logic through “unless” clauses.

§Types

Lemma has a rich type system including units (mass, length, time, money) with automatic conversions.

Modules§

deps
Dependency layout under <workdir>/lemma_deps/, shared by CLI fetch and LSP.

Structs§

Cause
One evaluated unless condition, stated as a fact.
Context
Ordered store of specs keyed by (repository, name) and grouped into LemmaSpecSets.
ConversionTraceStep
DataEntry
A spec’s public interface: its data (inputs) and rules (outputs) with full structured type information.
DataGroup
Grouped data from a specific spec (semantics types only).
DataOverlay
User-provided data values resolved against a plan’s type declarations.
DataPath
Resolved path to a data (created during planning from AST DataReference)
DateTimeValue
Engine
Engine for evaluating Lemma rules.
ErrorDetails
Detailed error information with optional source location.
Errors
Load failure: errors plus the source texts we attempted to load.
ExecutionPlan
A complete execution plan ready for the evaluator
ExecutionPlanSerialized
The serializable form of an ExecutionPlan.
Explanation
Instructions
Compiled normalized equation for authoritative evaluation.
LemmaBase
The LemmaBase registry fetches Lemma source text from LemmaBase.
LemmaRepository
A Lemma repository header. Identity carrier; never owns specs.
LemmaSpec
A Lemma spec containing data and rules.
LemmaSpecSet
All spec versions sharing a (repository, name) identity, keyed by effective_from.
LemmaType
Resolved type after planning
Lexer
LiteralValue
Literal value with type. The single value type in semantics.
ParseResult
PlanningSource
Positional source location: source id and span.
QuantityUnit
A single unit within a Quantity type.
QuantityUnits
RatioUnit
RatioUnits
RegistryBundle
A bundle of Lemma source text returned by the Registry.
RegistryError
An error returned by a Registry implementation.
ResolvedRepository
A loaded repository with all its spec sets.
ResourceLimits
Limits to prevent abuse and enable predictable resource usage
Response
Response from evaluating a Lemma spec
RulePath
Resolved path to a rule (created during planning from RuleReference)
RuleResult
Result of evaluating a single rule. Struct fields match the API JSON shape.
Source
Positional source location: source id and span.
Span
Span representing a location in source code
SpecRef
A spec reference written in source.
SpecSchema
TimezoneValue

Enums§

BindingDataValue
Response/UI row for spec data: LemmaType plus optional bound literal (mirrors parse-time Definition).
ComputationKind
The kind of computation performed
ConversionTraceRole
DataDefinition
Resolved data value for the execution plan: aligned with DataValue but with source per variant.
DataValue
Parse-time data value (before type resolution)
DataValueInput
Typed data value from a client (CLI/WASM). JSON parsing stays outside [parse_data_value].
DateGranularity
EffectiveDate
Error
Error types for the Lemma system with source location tracking
ErrorKind
Classification of an Error. Serialized as the kind field on the flat object returned to JavaScript from WASM (engine/src/wasm.rs, JsError).
ExplanationNode
Instruction
One compiled operation in a rule’s instruction stream.
OperationResult
Result of an operation (evaluating a rule or expression)
RegistryErrorKind
The kind of failure that occurred during a Registry operation.
RequestErrorKind
Distinguishes HTTP 404 (not found) from 400 (bad request) for request errors.
SourceType
TokenKind
TypeSpecification
ValueKind
Value payload (shape of a literal). No type attached. Quantity unit is required; Ratio unit is optional (see plan ratio-units-optional.md).
VetoType
Why an operation yielded no value (domain veto).

Constants§

EMBEDDED_STDLIB_REPOSITORY
Repository name reserved for the embedded standard library (repo lemma, spec units). User Engine::load / Engine::load_batch must not target this name.
INSTRUCTIONS_VERSION
MAX_DATA_NAME_LENGTH
MAX_RULE_NAME_LENGTH
MAX_SPEC_NAME_LENGTH
UNITS_LEMMA

Traits§

Registry
Trait for resolving external repository references.

Functions§

collect_lemma_sources
Collect .lemma source texts from filesystem paths (paths and one-level directories). Does not touch an Engine; pair with Engine::load / Engine::load_batch.
format_explanation
format_expression
format_parse_result
Format a ParseResult (repository groups + specs) into canonical Lemma source.
format_source
Parse a source string and format it to canonical Lemma source.
format_specs
Format a sequence of parsed specs into canonical Lemma source.
parse
parse_spec_set_id
Validate and normalize a spec set identifier (a workspace spec name).
plan
Build execution plans for one or more Lemma specs.
resolve_registry_references
Resolve every uses reference that carries a registry repository qualifier in the loaded specs.
type_detail_lines
Produce a human-readable summary of type constraints, or None when there are no constraints worth showing (e.g. bare boolean). Returns one formatted string per constraint or property of the type specification. Uses rational_to_display_str for all rational bounds so they render as decimals, not as raw fractions.
validate_instruction_jumps
Planning-time invariant: every jump is patched and lands on a real instruction. Panics on violation — compiled output failing this check is a compiler bug.
validate_instructions
Validate a compiled instruction stream against its operand pools: version, jump targets, register indices, constant/data/veto-message table indices, and the trailing Instruction::Return.