pepl-stdlib 0.1.1

Standard library for the PEPL language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;

use crate::error::StdlibError;

/// Runtime value in PEPL.
///
/// All PEPL values are immutable — operations that "modify" a value return a
/// new value instead. [`BTreeMap`] is used for records to guarantee
/// deterministic iteration order (a core PEPL invariant).
///
/// # Type names
///
/// [`Value::type_name`] returns the string used by `core.type_of()`:
/// `"number"`, `"string"`, `"bool"`, `"nil"`, `"list"`, `"record"` (or the
/// declared type name for named records/sum variants), `"color"`, `"result"`.
#[derive(Debug, Clone)]
pub enum Value {
    /// 64-bit IEEE 754 floating-point number.
    ///
    /// NaN is prevented from entering state — operations that would produce
    /// NaN trap instead.
    Number(f64),

    /// UTF-8 string.
    String(String),

    /// Boolean value.
    Bool(bool),

    /// The absence of a value.
    Nil,

    /// Ordered collection of values.
    List(Vec<Value>),

    /// Named fields with values. Uses [`BTreeMap`] for deterministic ordering.
    ///
    /// `type_name` is `Some("Todo")` for named record types (`type Todo = { ... }`),
    /// `None` for anonymous inline records (`{ x: 1, y: 2 }`).
    Record {
        type_name: Option<String>,
        fields: BTreeMap<String, Value>,
    },

    /// RGBA color value. Each component is in the range 0.0–1.0.
    Color { r: f64, g: f64, b: f64, a: f64 },

    /// Result type for fallible operations (`Ok` or `Err`).
    Result(Box<ResultValue>),

    /// Sum type variant (e.g., `Shape.Circle(5, 10)`).
    ///
    /// `type_name` is the declaring sum type (e.g., `"Shape"`).
    /// `variant` is the variant name (e.g., `"Circle"`).
    /// `fields` holds positional values — empty for unit variants like `Active`.
    SumVariant {
        type_name: String,
        variant: String,
        fields: Vec<Value>,
    },

    /// A callable function value for higher-order stdlib operations (map, filter, etc.).
    ///
    /// Wraps an `Arc<dyn Fn>` so it can be cloned and passed through `Vec<Value>`.
    /// The evaluator creates these by wrapping PEPL lambdas/functions.
    Function(StdlibFn),
}

/// A callable function value for higher-order stdlib operations.
///
/// Wraps an `Arc<dyn Fn>` so it can be cloned, and provides Debug/PartialEq
/// implementations that the derive macros can't auto-generate for `dyn Fn`.
#[derive(Clone)]
pub struct StdlibFn(pub Arc<dyn Fn(Vec<Value>) -> Result<Value, StdlibError> + Send + Sync>);

impl StdlibFn {
    /// Create a new stdlib function from a closure.
    pub fn new(
        f: impl Fn(Vec<Value>) -> Result<Value, StdlibError> + Send + Sync + 'static,
    ) -> Self {
        Self(Arc::new(f))
    }

    /// Call the function with the given arguments.
    pub fn call(&self, args: Vec<Value>) -> Result<Value, StdlibError> {
        (self.0)(args)
    }
}

impl fmt::Debug for StdlibFn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<function>")
    }
}

impl PartialEq for StdlibFn {
    fn eq(&self, other: &Self) -> bool {
        // Function identity by Arc pointer equality
        Arc::ptr_eq(&self.0, &other.0)
    }
}

/// The two variants of a PEPL `Result` value.
#[derive(Debug, Clone)]
pub enum ResultValue {
    Ok(Value),
    Err(Value),
}

// ── Equality ──────────────────────────────────────────────────────────────────
//
// Structural equality per execution-semantics.md:
//   - number:  IEEE 754 (NaN != NaN) — handled by f64 partial_eq
//   - string:  byte-for-byte UTF-8
//   - bool:    value equality
//   - nil:     nil == nil
//   - list:    same length + element-by-element
//   - record:  recursive field-by-field
//   - color:   RGBA value comparison
//   - result:  same variant + same inner value
//   - record:  structural (type_name ignored — type checker ensures compatibility)
//   - sum:     nominal (type_name + variant + fields must all match)
//   - Note: Functions/lambdas live in EvalValue (pepl-eval), not here

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Value::Number(a), Value::Number(b)) => a == b, // IEEE 754: NaN != NaN
            (Value::String(a), Value::String(b)) => a == b,
            (Value::Bool(a), Value::Bool(b)) => a == b,
            (Value::Nil, Value::Nil) => true,
            (Value::List(a), Value::List(b)) => a == b,
            // Structural equality for records — type_name is metadata, not identity
            (Value::Record { fields: a, .. }, Value::Record { fields: b, .. }) => a == b,
            (
                Value::Color {
                    r: r1,
                    g: g1,
                    b: b1,
                    a: a1,
                },
                Value::Color {
                    r: r2,
                    g: g2,
                    b: b2,
                    a: a2,
                },
            ) => r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2,
            (Value::Result(a), Value::Result(b)) => a == b,
            // Nominal equality for sum variants — same type + variant + fields
            (
                Value::SumVariant {
                    type_name: t1,
                    variant: v1,
                    fields: f1,
                },
                Value::SumVariant {
                    type_name: t2,
                    variant: v2,
                    fields: f2,
                },
            ) => t1 == t2 && v1 == v2 && f1 == f2,
            // Function identity by Arc pointer equality
            (Value::Function(a), Value::Function(b)) => a == b,
            _ => false, // different variants are never equal
        }
    }
}

impl PartialEq for ResultValue {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ResultValue::Ok(a), ResultValue::Ok(b)) => a == b,
            (ResultValue::Err(a), ResultValue::Err(b)) => a == b,
            _ => false,
        }
    }
}

// ── Display ───────────────────────────────────────────────────────────────────
//
// Used by `core.log`, `convert.to_string`, and `string.from`.

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Number(n) => {
                // Print integers without decimal point
                if n.fract() == 0.0 && n.is_finite() {
                    write!(f, "{}", *n as i64)
                } else {
                    write!(f, "{n}")
                }
            }
            Value::String(s) => write!(f, "{s}"),
            Value::Bool(b) => write!(f, "{b}"),
            Value::Nil => write!(f, "nil"),
            Value::List(items) => {
                write!(f, "[")?;
                for (i, item) in items.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    // Strings inside lists/records get quoted
                    match item {
                        Value::String(s) => write!(f, "\"{s}\"")?,
                        other => write!(f, "{other}")?,
                    }
                }
                write!(f, "]")
            }
            Value::Record { type_name, fields } => {
                if let Some(name) = type_name {
                    write!(f, "{name}")?;
                }
                write!(f, "{{")?;
                for (i, (key, val)) in fields.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    match val {
                        Value::String(s) => write!(f, "{key}: \"{s}\"")?,
                        other => write!(f, "{key}: {other}")?,
                    }
                }
                write!(f, "}}")
            }
            Value::SumVariant {
                variant, fields, ..
            } => {
                write!(f, "{variant}")?;
                if !fields.is_empty() {
                    write!(f, "(")?;
                    for (i, val) in fields.iter().enumerate() {
                        if i > 0 {
                            write!(f, ", ")?;
                        }
                        write!(f, "{val}")?;
                    }
                    write!(f, ")")?;
                }
                Ok(())
            }
            Value::Color { r, g, b, a } => {
                write!(f, "color({r}, {g}, {b}, {a})")
            }
            Value::Result(res) => match res.as_ref() {
                ResultValue::Ok(v) => write!(f, "Ok({v})"),
                ResultValue::Err(v) => write!(f, "Err({v})"),
            },
            Value::Function(_) => write!(f, "<function>"),
        }
    }
}

// ── Constructors & Helpers ────────────────────────────────────────────────────

impl Value {
    /// Returns the PEPL type name as used by `core.type_of()`.
    pub fn type_name(&self) -> &str {
        match self {
            Value::Number(_) => "number",
            Value::String(_) => "string",
            Value::Bool(_) => "bool",
            Value::Nil => "nil",
            Value::List(_) => "list",
            Value::Record {
                type_name: Some(name),
                ..
            } => name.as_str(),
            Value::Record {
                type_name: None, ..
            } => "record",
            Value::Color { .. } => "color",
            Value::Result(_) => "result",
            Value::SumVariant { type_name, .. } => type_name.as_str(),
            Value::Function(_) => "function",
        }
    }

    /// Returns `true` if this value is truthy.
    ///
    /// Truthiness rules (per `convert.to_bool`):
    /// - `false`, `nil`, `0`, `""` → falsy
    /// - everything else → truthy
    pub fn is_truthy(&self) -> bool {
        match self {
            Value::Bool(false) => false,
            Value::Nil => false,
            Value::Number(n) => *n != 0.0,
            Value::String(s) => !s.is_empty(),
            _ => true, // List, Record, Color, Result, SumVariant, Function are truthy
        }
    }

    /// Convenience: wrap in `Ok` result.
    pub fn ok(self) -> Value {
        Value::Result(Box::new(ResultValue::Ok(self)))
    }

    /// Convenience: wrap in `Err` result.
    pub fn err(self) -> Value {
        Value::Result(Box::new(ResultValue::Err(self)))
    }

    /// Create an anonymous record (no type name).
    pub fn record(fields: BTreeMap<String, Value>) -> Value {
        Value::Record {
            type_name: None,
            fields,
        }
    }

    /// Create a named record (e.g., `type Todo = { ... }`).
    pub fn named_record(type_name: impl Into<String>, fields: BTreeMap<String, Value>) -> Value {
        Value::Record {
            type_name: Some(type_name.into()),
            fields,
        }
    }

    /// Create a unit sum variant (no payload fields).
    pub fn unit_variant(type_name: impl Into<String>, variant: impl Into<String>) -> Value {
        Value::SumVariant {
            type_name: type_name.into(),
            variant: variant.into(),
            fields: vec![],
        }
    }

    /// Create a sum variant with positional fields.
    pub fn sum_variant(
        type_name: impl Into<String>,
        variant: impl Into<String>,
        fields: Vec<Value>,
    ) -> Value {
        Value::SumVariant {
            type_name: type_name.into(),
            variant: variant.into(),
            fields,
        }
    }

    /// Try to extract a number, returning `None` if not a `Number`.
    pub fn as_number(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// Try to extract a string reference, returning `None` if not a `String`.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Try to extract a bool, returning `None` if not a `Bool`.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Try to extract a list reference, returning `None` if not a `List`.
    pub fn as_list(&self) -> Option<&[Value]> {
        match self {
            Value::List(l) => Some(l),
            _ => None,
        }
    }

    /// Try to extract a record reference, returning `None` if not a `Record`.
    pub fn as_record(&self) -> Option<&BTreeMap<String, Value>> {
        match self {
            Value::Record { fields, .. } => Some(fields),
            _ => None,
        }
    }

    /// Try to extract sum variant info: `(type_name, variant, fields)`.
    pub fn as_variant(&self) -> Option<(&str, &str, &[Value])> {
        match self {
            Value::SumVariant {
                type_name,
                variant,
                fields,
            } => Some((type_name, variant, fields)),
            _ => None,
        }
    }

    /// Try to extract a function reference, returning `None` if not a `Function`.
    pub fn as_function(&self) -> Option<&StdlibFn> {
        match self {
            Value::Function(f) => Some(f),
            _ => None,
        }
    }

    /// Returns the declared type name for named records and sum variants.
    /// Returns `None` for anonymous records and all other value types.
    pub fn declared_type_name(&self) -> Option<&str> {
        match self {
            Value::Record {
                type_name: Some(name),
                ..
            } => Some(name),
            Value::SumVariant { type_name, .. } => Some(type_name),
            _ => None,
        }
    }
}

// ── From impls ────────────────────────────────────────────────────────────────

impl From<f64> for Value {
    fn from(n: f64) -> Self {
        Value::Number(n)
    }
}

impl From<i64> for Value {
    fn from(n: i64) -> Self {
        Value::Number(n as f64)
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(s)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Bool(b)
    }
}

impl From<BTreeMap<String, Value>> for Value {
    fn from(fields: BTreeMap<String, Value>) -> Self {
        Value::Record {
            type_name: None,
            fields,
        }
    }
}