diff --git a/README.md b/README.md index bba28c8..265c5f3 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,102 @@ -An expermintal (possibly optimal) lambda calculus machine +An experimental (possibly optimal) lambda calculus machine --------------------------------------------------------- -The goal is simple, make pure lambda reduction fast by treating terms as flat -data rather than heap-allocated trees. No pointers, no string-based variables, -and no intermediate allocations during evaluation. +In standard interpreters, pure lambda calculus is evaluated as graph reduction +over heap-allocated trees: every application is a heap node, every abstraction +is a pointer, and every beta-step allocates intermediate terms. -References are compact 32-bit integers: 2 bits for node kind, 30 bits for arena -offset. +The cost is not in the lambda calculus; the cost is in the memory model. When +terms are pointer graphs, evaluation is dominated by cache misses and allocator +pressure. + +This machine models reduction as flat array transformations over contiguous +arenas, treating the lambda calculus through Data-Oriented Design. + +1. Pointers Are Distances + +To a programmer, a pointer is an abstraction. To hardware, a pointer is a +commute: an unpredictable jump across RAM that stalls execution on an L3 or +main-memory miss. + +Terms are packed into contiguous 32-bit indices inside typed arenas: ```rust -pub struct Variable { - pub index: u32, // 4 bytes -} - -pub struct Lambda { - pub body: TermId, // 4 bytes -} - -pub struct Apply { - pub function: TermId, // 4 bytes - pub argument: TermId, // 4 bytes -} +pub struct Variable { pub index: u32 } +pub struct Lambda { pub body: TermId } +pub struct Apply { pub function: TermId, pub argument: TermId } ``` -Every node is either 4 or 8 bytes. A single 64-byte cache line holds 8 `Apply` -or 16 `Lambda` nodes. Identical nodes are deduplicated via canonical -hash-consing on insertion. +Every node is 4 or 8 bytes. A single 64-byte cache line brings in up to 16 +terms in one memory transaction. -Spine Evaluation ----------------- +Canonical hash-consing deduplicates identical subterms on insertion. Terms +form a Directed Acyclic Graph (DAG) rather than a tree, reducing memory +footprint and turning structural equality into an O(1) index check. -Normal-order reduction uses a pre-allocated stack (`Vec`) to unwind -the left spine in a tight loop. Arguments are popped and substituted in place -without allocating intermediate application trees. +2. The Spine Is a Stack -Usage ------ +Normal-order reduction searches for the leftmost, outermost redex. Instead of +recursive calls unwinding the syntax tree, the left spine is walked into a +pre-allocated evaluation stack. -```sh -cargo build --release -``` +Arguments are consumed in place without constructing transient intermediate +terms. Beta-substitution rewrites arena indices directly, avoiding heap churn +during tight reduction loops. + +Pure lambda calculus has no primitive types; data is represented by Church, +Scott, or Boehm encodings. -Run and decode Church encodings: +Under Church encoding, representations can be structurally indistinguishable: + + λf. λx. x + +This term is simultaneously `false` and the numeral `0`. The bit-pattern is +identical; the type depends on the evaluation context. + +When decoding normal forms back into host values (`--decode`), `--prefer` sets +the inspection precedence: ```sh -$ lambdac factorial.lam --decode=church -6 +$ lambdac examples/basic/zero.lam --decode=church --prefer=number +0 -$ lambdac arithmetic.lam --decode=church -7 +$ lambdac examples/basic/zero.lam --decode=church --prefer=bool +false ``` -Trace beta reductions: +If the preferred rule fails to match, the decoder falls back to alternative +patterns. -```hs -$ lambdac identity.lam --trace -(λx. λz. x z) (λx. x) y -> (λx. (λz. z) x) y -(λx. (λz. z) x) y -> (λx. x) y -(λx. x) y -> y -y +4. Reduction Tracing and Statistics + +The tracer instruments reduction steps across rules (α, β, η, δ) with zero +heap allocations per step: + +```text +$ lambdac examples/basic/not.lam --decode=church --trace --prefer=bool +(λnot. λfalse. not false) (λb. λt. λf. b f t) (λt. λf. f) +│ β (not ↦ λb. λt. λf. b f t) +↓ +(λfalse. (λb. λt. λf. b f t) false) (λt. λf. f) +│ β (false ↦ λt. λf. f) +↓ +(λb. λt. λf. b f t) (λt. λf. f) +│ β (b ↦ λt. λf. f) +↓ +λt. λf. (λx. λy. y) f t +│ β (t ↦ f) +↓ +λt. λf. (λx. x) t +│ β (f ↦ t) +↓ +λt. λf. t +true ``` -Execution statistics: +Graph topology and reduction metrics are measured directly via `--stats`: ```text -$ lambdac factorial.lam --stats +$ lambdac examples/recursion/factorial.lam --stats term nodes: 98 depth: 21 diff --git a/examples/basic/zero.lam b/examples/basic/zero.lam new file mode 100644 index 0000000..09ae2d9 --- /dev/null +++ b/examples/basic/zero.lam @@ -0,0 +1 @@ +(λf r . r) diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 7267ec3..6f10728 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -3,7 +3,7 @@ pub mod options; use clap::Parser; use std::path::PathBuf; -use self::options::{ColorChoice, Emit, Encoding, Options}; +use self::options::{ColorChoice, DecodePreference, Emit, Encoding, Options}; #[derive(Debug, Parser)] #[command( @@ -47,13 +47,20 @@ pub struct Cli { value_name = "ENCODING", num_args = 0..=1, default_missing_value = "church", - require_equals = true, hide_possible_values = true, value_enum, help = "Decode lambda encoding (church, scott, boehm)" )] pub decode: Option, + #[arg( + long, + value_name = "TYPE", + value_enum, + help = "Preferred type when decoding ambiguous values (number, boolean)" + )] + pub prefer: Option, + #[arg(long, help = "Show evaluation steps")] pub trace: bool, @@ -96,12 +103,17 @@ impl Cli { let color = if self.no_color { ColorChoice::Never } else { self.color }; + let decode = self + .decode + .or_else(|| if self.prefer.is_some() { Some(Encoding::Church) } else { None }); + Options { input, output: self.output, check: self.check, emit: self.emit, - decode: self.decode, + decode, + prefer: self.prefer, trace: self.trace, stats: self.stats, limit: self.limit, diff --git a/src/cli/options/options.rs b/src/cli/options/options.rs index af86546..d655463 100644 --- a/src/cli/options/options.rs +++ b/src/cli/options/options.rs @@ -16,6 +16,7 @@ pub struct Options { pub check: bool, pub emit: Option, pub decode: Option, + pub prefer: Option, pub trace: bool, pub stats: bool, pub limit: usize, @@ -33,6 +34,7 @@ impl Options { check: false, emit: None, decode: None, + prefer: None, trace: false, stats: false, limit: 10000, @@ -63,3 +65,11 @@ pub enum Encoding { Scott, Boehm, } + +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum DecodePreference { + #[value(alias = "int", alias = "nat")] + Number, + #[value(alias = "bool")] + Boolean, +} diff --git a/src/decode/church/mod.rs b/src/decode/church/mod.rs index e458c35..61fd654 100644 --- a/src/decode/church/mod.rs +++ b/src/decode/church/mod.rs @@ -5,6 +5,7 @@ mod number; mod pair; use crate::{ + cli::options::DecodePreference, context::Context, core::TermId, decode::value::{ValueId, Values}, @@ -12,18 +13,25 @@ use crate::{ }; pub fn decode(ctx: &Context, values: &mut Values, term: TermId) -> result::Result> { - if let Some(value) = bool::decode(ctx, values, term)? { - return Ok(Some(value)); - } - - if let Some(value) = number::decode(ctx, values, term)? { - return Ok(Some(value)); + if ctx.options.prefer == Some(DecodePreference::Number) { + if let Some(value) = number::decode(ctx, values, term)? { + return Ok(Some(value)); + } + if let Some(value) = bool::decode(ctx, values, term)? { + return Ok(Some(value)); + } + } else { + if let Some(value) = bool::decode(ctx, values, term)? { + return Ok(Some(value)); + } + if let Some(value) = number::decode(ctx, values, term)? { + return Ok(Some(value)); + } } if let Some(value) = list::decode(ctx, values, term)? { return Ok(Some(value)); } - if let Some(value) = pair::decode(ctx, values, term)? { return Ok(Some(value)); } diff --git a/tests/decode.rs b/tests/decode.rs new file mode 100644 index 0000000..a4b0ef1 --- /dev/null +++ b/tests/decode.rs @@ -0,0 +1,88 @@ +use lambdac::{ + cli::options::{DecodePreference, Encoding, Options}, + context::Context, + driver::Driver, +}; + +fn eval_and_decode(code: &str, prefer: Option) -> String { + let mut options = Options::default(); + options.decode = Some(Encoding::Church); + options.prefer = prefer; + + let mut ctx = Context::new(options); + let mut driver = Driver::new(&mut ctx); + let term = driver.compile_source("test", code).expect("compile error"); + let (evaluated, _) = driver.evaluate_term(term).expect("evaluation error"); + + let mut decoder = lambdac::decode::Decoder::new(&mut driver.ctx); + let value_id = decoder.church(evaluated).expect("decode error"); + decoder.print(value_id) +} + +#[test] +fn test_church_zero_ambiguity_resolution() { + // Church zero / false representation: \f x. x + let code = "(λf x. x)"; + + // Default preference (bool first) + assert_eq!(eval_and_decode(code, None), "false"); + + // Prefer number + assert_eq!(eval_and_decode(code, Some(DecodePreference::Number)), "0"); + + // Prefer boolean + assert_eq!(eval_and_decode(code, Some(DecodePreference::Boolean)), "false"); +} + +#[test] +fn test_fallback_when_preferred_type_fails() { + // Church true: \t f. t (cannot be a church number) + let true_code = "(λt f. t)"; + + // Even when preferring number, it should fall back to boolean + assert_eq!(eval_and_decode(true_code, Some(DecodePreference::Number)), "true"); + + // Church one: \f x. f x (cannot be a boolean) + let one_code = "(λf x. f x)"; + + // Even when preferring boolean, it should fall back to number + assert_eq!(eval_and_decode(one_code, Some(DecodePreference::Boolean)), "1"); +} + +#[test] +fn test_nested_decode_with_preference() { + // A pair of Church zeroes: (\a b x. x a b) (\f x. x) (\f x. x) + let pair_code = "(λa b x. x a b) (λf x. x) (λf x. x)"; + + // With number preference, pair contents are decoded as numbers + assert_eq!(eval_and_decode(pair_code, Some(DecodePreference::Number)), "(0, 0)"); + + // With boolean preference, pair contents are decoded as booleans + assert_eq!(eval_and_decode(pair_code, Some(DecodePreference::Boolean)), "(false, false)"); +} + +#[test] +fn test_cli_prefer_parsing() { + use clap::Parser; + use lambdac::cli::Cli; + + let cli = + Cli::try_parse_from(["lambdac", "file.lam", "--decode", "church", "--prefer", "number"]) + .unwrap(); + let opts = cli.into_options(); + assert_eq!(opts.prefer, Some(DecodePreference::Number)); + assert_eq!(opts.decode, Some(Encoding::Church)); + + let cli = Cli::try_parse_from(["lambdac", "file.lam", "--prefer", "int"]).unwrap(); + let opts = cli.into_options(); + assert_eq!(opts.prefer, Some(DecodePreference::Number)); + assert_eq!(opts.decode, Some(Encoding::Church)); + + let cli = Cli::try_parse_from(["lambdac", "file.lam", "--prefer", "bool"]).unwrap(); + let opts = cli.into_options(); + assert_eq!(opts.prefer, Some(DecodePreference::Boolean)); + + let cli = Cli::try_parse_from(["lambdac", "file.lam", "--prefer", "boolean"]).unwrap(); + let opts = cli.into_options(); + assert_eq!(opts.prefer, Some(DecodePreference::Boolean)); +}