Skip to main content

Crate legalis_core

Crate legalis_core 

Source
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.

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:

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:

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§

AbductiveReasoner
Abductive reasoning engine for explaining legal outcomes.
AnyJurisdiction
Generic marker for any jurisdiction.
AttributeBasedContext
Context for evaluating conditions (simple attribute-based implementation).
BasicEntity
A simple implementation of LegalEntity for testing and basic use cases.
California
California (US-CA) jurisdiction marker.
ComposedEffect
Composed effect combining multiple effects with priority ordering.
ConditionBuilder
Builder for constructing Condition objects with a fluent API.
ConditionCache
Cache for memoizing condition evaluation results.
ConditionEvaluator
Memoization cache for condition evaluation results.
ConditionalEffect
Effect that depends on runtime conditions.
Contradiction
Represents a logical contradiction between statutes.
CrossJurisdictionAnalyzer
Cross-jurisdiction statute equivalence detector.
DefaultValueContext
Context wrapper that provides default values for missing attributes.
DiagnosticContext
Diagnostic context for detailed error reporting.
DiagnosticReporter
Diagnostic error reporter for collecting and formatting errors.
DiagnosticValidationError
Enhanced validation error with diagnostic context.
EU
European Union jurisdiction marker.
Effect
Legal effect produced when statute conditions are met.
EffectBuilder
Builder for constructing Effect objects with a fluent API.
EffectDependencyGraph
Effect dependency graph for tracking and detecting cycles.
EntailmentEngine
Legal entailment engine that determines what conclusions follow from statutes and facts.
EntailmentResult
Result of applying a statute in the entailment process.
EvaluationAuditTrail
Audit trail for tracking condition evaluations.
EvaluationExplanation
Detailed explanation of a condition evaluation.
EvaluationRecord
A single evaluation record in the audit trail.
ExplanationStep
A single step in the evaluation trace.
FallbackContext
Context wrapper that provides fallback evaluation strategies.
ForwardChainingEngine
Forward chaining entailment with multi-step inference.
InferenceStep
Inference step in legal reasoning chains.
JurisdictionStatute
Jurisdiction-specific statute wrapper using phantom types.
JurisdictionStatuteRegistry
Collection of jurisdiction-specific statutes.
LegalExplanation
Explanation for why a legal outcome occurred.
NewYork
New York (US-NY) jurisdiction marker.
ReasoningStep
A single step in the reasoning chain.
SourceLocation
Source location information for error diagnostics.
Statute
StatuteBuilder
Simple builder for constructing Statute objects with template support and progressive validation.
StatuteConflictAnalyzer
Statute conflict analyzer.
StatuteDiff
Represents differences between two versions of a statute.
StatuteException
Statute (legal article) definition.
StatuteGraph
Statute dependency graph for tracking relationships between statutes.
StatuteQuery
Fluent query builder for searching and filtering statutes.
StatuteRegistry
Statute registry for managing collections of statutes with query capabilities.
SubsumptionAnalyzer
Subsumption analyzer for determining if one statute subsumes another.
TemporalEffect
Effect with temporal validity constraints.
TemporalValidity
Temporal validity for statutes.
TypedEntity
A type-safe implementation of LegalEntity using strongly-typed attributes.
TypedStatuteBuilder
Type-safe builder for Statute using the typestate pattern.
UK
United Kingdom jurisdiction marker.
US
United States jurisdiction marker.

Enums§

ComparisonOp
Comparison operators for conditions.
CompositionStrategy
Strategies for resolving conflicts between composed effects.
Condition
Condition type for statute preconditions.
ConditionError
Condition evaluation errors.
ConflictReason
Reason why one statute prevails over another.
ConflictResolution
Represents the outcome of a conflict resolution between two statutes.
ContradictionType
Types of contradictions that can occur between statutes.
DurationUnit
Time unit for duration conditions.
EffectType
Types of legal effects.
ErrorSeverity
Error severity levels.
EvaluationError
Errors that can occur during condition evaluation.
LegalResult
Legal judgment result as an Algebraic Data Type (ADT).
PartialBool
Three-valued logic result with uncertainty propagation.
RecurrencePattern
Recurrence patterns for temporal effects.
RegionType
Geographic region types.
RelationshipType
Entity relationship types.
StatuteChange
Types of changes that can occur in a statute.
StepResult
Result of a reasoning step.
ValidationError
Validation errors for statutes with error codes and severity.

Traits§

EvaluationContext
Context trait for evaluating conditions against legal entities.
Jurisdiction
Marker trait for jurisdictions.
LegalEntity
Legal entity (natural person, legal person, or AI agent).