Expand description
Legalis-Core: Core types and traits for the Legalis-RS legal framework.
This module defines the foundational types that represent legal concepts, including the distinction between deterministic (computable) and discretionary (requiring human judgment) legal outcomes.
§Design Philosophy
§“Not Everything Should Be Computable”
Legalis-RS is built on the principle that while many legal determinations can be
automated, some require human judgment and interpretation. This is reflected in the
LegalResult type, which explicitly distinguishes between:
- Deterministic outcomes: Mechanically derivable from rules (age >= 18, income < $50k)
- Judicial Discretion: Requires human interpretation (just cause, public welfare)
- Void: Logical contradictions in the law itself
This design prevents “AI theocracy” by preserving human agency in legal interpretation where it matters most.
§Type-Safe Legal Modeling
The crate uses Rust’s type system to enforce legal invariants at compile time:
- Statutes must have IDs, titles, and effects
- Temporal validity is checked (expiry dates must follow effective dates)
- Conditions are strongly typed and composable
- Entity attributes can be type-safe via
TypedEntity
§Builder Pattern for Clarity
Complex legal structures use the builder pattern for readability:
let statute = Statute::new("tax-law-2025", "Income Tax", Effect::new(EffectType::Grant, "Tax credit"))
.with_precondition(Condition::Income { operator: ComparisonOp::LessThan, value: 50000 })
.with_temporal_validity(TemporalValidity::new()
.with_effective_date(NaiveDate::from_ymd_opt(2025, 1, 1).unwrap()))
.with_jurisdiction("US")
.with_version(1);§Validation Over Panics
The crate prefers validation methods that return errors over runtime panics:
Statute::validate()returns a list of validation errorsStatute::validated()returnsResult<Statute, Vec<ValidationError>>TypedEntityreturnsResultfor type mismatches
This allows calling code to decide how to handle invalid states.
§Temporal Awareness
Legal rules change over time. The TemporalValidity type tracks:
- Effective dates (when laws come into force)
- Expiry dates (sunset clauses)
- Enactment and amendment timestamps
This enables historical legal queries and version management.
§Architecture Decisions
§Why ADTs for Conditions?
The Condition enum uses algebraic data types (ADTs) with recursive composition
(AND/OR/NOT) rather than a trait-based visitor pattern. This provides:
- Pattern matching exhaustiveness checking at compile time
- Easier serialization/deserialization
- Simpler mental model for legal rule composition
- Better performance (no dynamic dispatch)
§Why Trait Objects for Entities?
LegalEntity is a trait rather than a concrete type because:
- Different systems may have different entity storage needs
- Allows integration with existing database models
- Supports both simple (
BasicEntity) and type-safe (TypedEntity) implementations - Enables custom entity types for domain-specific needs
§Why HashMap for Effect Parameters?
Effect parameters use HashMap<String, String> for flexibility:
- Legal effects vary widely in their parameters
- Allows extension without breaking changes
- Simple serialization format
- Type safety can be added at higher layers if needed
§Type Relationships
The following diagrams illustrate the core type relationships in legalis-core:
§Core Legal Types
classDiagram
class Statute {
+String id
+String title
+Effect effect
+Option~Condition~ precondition
+Option~TemporalValidity~ temporal
+Vec~String~ tags
+validate() Vec~ValidationError~
}
class Effect {
+EffectType effect_type
+String description
+HashMap parameters
}
class EffectType {
<<enumeration>>
Grant
Obligation
Prohibition
Conditional
Delayed
Compound
}
class LegalResult~T~ {
<<enumeration>>
Deterministic(T)
JudicialDiscretion
Void
+map(f) LegalResult~U~
+and_then(f) LegalResult~U~
}
class TemporalValidity {
+Option~NaiveDate~ effective_date
+Option~NaiveDate~ expiry_date
+Option~DateTime~ enactment_date
+is_valid_on(date) bool
}
Statute --> Effect : contains
Statute --> Condition : optional precondition
Statute --> TemporalValidity : optional temporal
Effect --> EffectType : has type
Statute ..> LegalResult : validation returns§Condition Composition
classDiagram
class Condition {
<<enumeration>>
Age
Income
Geographic
DateRange
EntityRelationship
ResidencyDuration
And(Vec~Condition~)
Or(Vec~Condition~)
Not(Box~Condition~)
+evaluate(entity) LegalResult~bool~
+normalize() Condition
}
class ComparisonOp {
<<enumeration>>
Equal
NotEqual
LessThan
LessThanOrEqual
GreaterThan
GreaterThanOrEqual
}
Condition --> Condition : recursive composition
Condition --> ComparisonOp : uses for comparisons§Entity Type Hierarchy
classDiagram
class LegalEntity {
<<trait>>
+id() String
+entity_type() String
+get_attribute(key) Option~String~
+set_attribute(key, value)
+attributes() HashMap
}
class BasicEntity {
+String id
+String entity_type
+HashMap attributes
}
class TypedEntity {
+String id
+String entity_type
+TypedAttributes attributes
+get_typed~T~(key) Result~T~
+set_typed~T~(key, value)
}
class TypedAttributes {
+HashMap~String,AttributeValue~ data
+get~T~(key) Result~T~
+set~T~(key, value)
}
class AttributeValue {
<<enumeration>>
String(String)
U32(u32)
Bool(bool)
Date(NaiveDate)
}
LegalEntity <|.. BasicEntity : implements
LegalEntity <|.. TypedEntity : implements
TypedEntity --> TypedAttributes : contains
TypedAttributes --> AttributeValue : stores§Case Law Structure
classDiagram
class Case {
+String id
+String title
+Court court
+NaiveDate decision_date
+Vec~CaseRule~ rules
}
class Court {
+String name
+String jurisdiction
+u8 level
}
class CaseRule {
+String principle
+String reasoning
+Vec~String~ facts
}
class Precedent {
+String case_id
+PrecedentWeight weight
}
class PrecedentWeight {
<<enumeration>>
Binding
Persuasive
Distinguishable
}
Case --> Court : decided by
Case --> CaseRule : contains
Precedent --> PrecedentWeight : has§Features
serde(default): Enable serialization/deserialization support for all types
§Performance Considerations
- Condition evaluation is non-allocating where possible
- Entity attributes use copy-on-write semantics
- Statutes are cheaply cloneable (most fields are small or reference-counted)
- Property-based tests ensure reasonable performance across edge cases
Re-exports§
pub use case_law::Case;pub use case_law::CaseDatabase;pub use case_law::CaseRule;pub use case_law::Court;pub use case_law::DamageType;pub use case_law::Precedent;pub use case_law::PrecedentApplication;pub use case_law::PrecedentWeight;pub use typed_attributes::AttributeError;pub use typed_attributes::AttributeValue;pub use typed_attributes::TypedAttributes;
Modules§
- adaptive_
cache - Adaptive caching strategies for optimizing condition evaluation performance.
- arena
- Arena allocator for bulk statute operations.
- autonomous_
agents - Autonomous Legal Agents (v0.3.4)
- blockchain_
verification - On-Chain Statute Verification
- builder_
states - Marker types for typestate builder pattern.
- case_
law - Case Law support for Common Law jurisdictions.
- compact
- Memory-optimized statute representation.
- const_
collections - Const generic collections for performance-critical legal operations.
- decentralized_
registry - Decentralized Legal Registry
- digital_
twin - Digital Twin Modeling for Legal Entities
- distributed
- Distributed legal reasoning framework.
- document_
processing - Legal document processing and structure recognition.
- event_
sourcing - Event Sourcing for Legal State Changes
- explainable_
ai - Explainable AI for transparent legal decision-making.
- explanation
- Legal Explanation Generation
- finetuned_
llm - Fine-tuned legal language model integration.
- formal_
methods - Formal methods integration for legal reasoning.
- formats
- Format conversion helpers for legal data interchange.
- gpu_
offload - GPU offloading framework for massively parallel evaluation.
- hybrid_
reasoning - Hybrid symbolic-neural reasoning combining traditional logic with ML.
- interning
- String interning for repeated identifiers.
- jit_
framework - JIT (Just-In-Time) compilation framework for hot evaluation paths.
- knowledge_
graph - Knowledge graph representation for legal reasoning.
- lazy
- Lazy loading for statute preconditions and effects.
- llm_
interpretation - LLM-assisted condition interpretation for complex legal reasoning.
- memory_
pool - Memory pool management for efficient allocation in batch operations.
- multi_
jurisdictional - Multi-Jurisdictional Legal Reasoning
- neural_
entailment - Neural legal entailment for automated reasoning.
- oracle
- Oracle Integration for Off-Chain Facts
- parallel_
eval - Parallel batch evaluation with work stealing.
- probabilistic
- Probabilistic Legal Reasoning
- quantum
- Quantum-Ready Legal Logic (v0.3.3)
- realtime_
sync - Real-Time Statute Synchronization
- rule_
learning - Rule Learning & Discovery
- scenario_
simulation - Scenario Simulation with Digital Twins
- simd_
eval - SIMD-accelerated condition evaluation for high-performance batch processing.
- smart_
contract - Smart Contract Compilation and Blockchain Integration
- temporal
- Advanced temporal logic for legal reasoning.
- testing
- Testing utilities for legalis-core.
- time_
travel - Time-Travel Debugging for Legal Histories
- transactions
- Transaction support for batch updates to legal data.
- typed_
attributes - Typed attribute system for LegalEntity.
- typed_
effects - Strongly-typed effects with generic parameter constraints.
- workflows
- Workflow helpers for common legal processes.
- zkp
- Zero-Knowledge Proofs for Privacy-Preserving Evaluation
Macros§
- define_
custom_ condition - Macro for defining custom condition types with automatic boilerplate.
- define_
jurisdiction - Macro for defining custom jurisdiction types with automatic boilerplate.
- statute
- Declarative macro for defining statutes with a clean, readable syntax.
Structs§
- Abductive
Reasoner - Abductive reasoning engine for explaining legal outcomes.
- AnyJurisdiction
- Generic marker for any jurisdiction.
- Attribute
Based Context - Context for evaluating conditions (simple attribute-based implementation).
- Basic
Entity - A simple implementation of LegalEntity for testing and basic use cases.
- California
- California (US-CA) jurisdiction marker.
- Composed
Effect - Composed effect combining multiple effects with priority ordering.
- Condition
Builder - Builder for constructing
Conditionobjects with a fluent API. - Condition
Cache - Cache for memoizing condition evaluation results.
- Condition
Evaluator - Memoization cache for condition evaluation results.
- Conditional
Effect - Effect that depends on runtime conditions.
- Contradiction
- Represents a logical contradiction between statutes.
- Cross
Jurisdiction Analyzer - Cross-jurisdiction statute equivalence detector.
- Default
Value Context - Context wrapper that provides default values for missing attributes.
- Diagnostic
Context - Diagnostic context for detailed error reporting.
- Diagnostic
Reporter - Diagnostic error reporter for collecting and formatting errors.
- Diagnostic
Validation Error - Enhanced validation error with diagnostic context.
- EU
- European Union jurisdiction marker.
- Effect
- Legal effect produced when statute conditions are met.
- Effect
Builder - Builder for constructing
Effectobjects with a fluent API. - Effect
Dependency Graph - Effect dependency graph for tracking and detecting cycles.
- Entailment
Engine - Legal entailment engine that determines what conclusions follow from statutes and facts.
- Entailment
Result - Result of applying a statute in the entailment process.
- Evaluation
Audit Trail - Audit trail for tracking condition evaluations.
- Evaluation
Explanation - Detailed explanation of a condition evaluation.
- Evaluation
Record - A single evaluation record in the audit trail.
- Explanation
Step - A single step in the evaluation trace.
- Fallback
Context - Context wrapper that provides fallback evaluation strategies.
- Forward
Chaining Engine - Forward chaining entailment with multi-step inference.
- Inference
Step - Inference step in legal reasoning chains.
- Jurisdiction
Statute - Jurisdiction-specific statute wrapper using phantom types.
- Jurisdiction
Statute Registry - Collection of jurisdiction-specific statutes.
- Legal
Explanation - Explanation for why a legal outcome occurred.
- NewYork
- New York (US-NY) jurisdiction marker.
- Reasoning
Step - A single step in the reasoning chain.
- Source
Location - Source location information for error diagnostics.
- Statute
- Statute
Builder - Simple builder for constructing
Statuteobjects with template support and progressive validation. - Statute
Conflict Analyzer - Statute conflict analyzer.
- Statute
Diff - Represents differences between two versions of a statute.
- Statute
Exception - Statute (legal article) definition.
- Statute
Graph - Statute dependency graph for tracking relationships between statutes.
- Statute
Query - Fluent query builder for searching and filtering statutes.
- Statute
Registry - Statute registry for managing collections of statutes with query capabilities.
- Subsumption
Analyzer - Subsumption analyzer for determining if one statute subsumes another.
- Temporal
Effect - Effect with temporal validity constraints.
- Temporal
Validity - Temporal validity for statutes.
- Typed
Entity - A type-safe implementation of LegalEntity using strongly-typed attributes.
- Typed
Statute Builder - Type-safe builder for
Statuteusing the typestate pattern. - UK
- United Kingdom jurisdiction marker.
- US
- United States jurisdiction marker.
Enums§
- Comparison
Op - Comparison operators for conditions.
- Composition
Strategy - Strategies for resolving conflicts between composed effects.
- Condition
- Condition type for statute preconditions.
- Condition
Error - Condition evaluation errors.
- Conflict
Reason - Reason why one statute prevails over another.
- Conflict
Resolution - Represents the outcome of a conflict resolution between two statutes.
- Contradiction
Type - Types of contradictions that can occur between statutes.
- Duration
Unit - Time unit for duration conditions.
- Effect
Type - Types of legal effects.
- Error
Severity - Error severity levels.
- Evaluation
Error - Errors that can occur during condition evaluation.
- Legal
Result - Legal judgment result as an Algebraic Data Type (ADT).
- Partial
Bool - Three-valued logic result with uncertainty propagation.
- Recurrence
Pattern - Recurrence patterns for temporal effects.
- Region
Type - Geographic region types.
- Relationship
Type - Entity relationship types.
- Statute
Change - Types of changes that can occur in a statute.
- Step
Result - Result of a reasoning step.
- Validation
Error - Validation errors for statutes with error codes and severity.
Traits§
- Evaluation
Context - Context trait for evaluating conditions against legal entities.
- Jurisdiction
- Marker trait for jurisdictions.
- Legal
Entity - Legal entity (natural person, legal person, or AI agent).