scheme-rs 0.1.0

Embedded scheme for the Rust ecosystem
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Scheme compatible hashtables

use indexmap::IndexSet;
use parking_lot::RwLock;
use std::{
    collections::HashSet,
    fmt,
    hash::{DefaultHasher, Hash, Hasher},
};

use crate::{
    exceptions::Exception,
    gc::{Gc, Trace},
    proc::Procedure,
    registry::bridge,
    strings::WideString,
    symbols::Symbol,
    value::{Expect1, Value, ValueType},
};

#[derive(Clone, Trace)]
struct TableEntry {
    key: Value,
    val: Value,
    hash: u64,
}

impl TableEntry {
    fn get_hash(&self) -> u64 {
        self.hash
    }
}

#[derive(Trace)]
pub(crate) struct HashTableInner {
    /// Inner table of values. This uses an inner RwLock to ensure that we can
    /// access eq and hash even if the table is locked.
    ///
    /// We can't use the std library hashmap since we don't want to bundle the
    /// eq and hash functions with the key Value, so we use hashbrown's
    /// HashTable
    table: RwLock<hashbrown::HashTable<TableEntry>>,
    /// Equivalence function.
    eq: Procedure,
    /// Hash function.
    hash: Procedure,
    /// Whether or not the hashtable is mutable
    mutable: bool,
}

impl HashTableInner {
    pub fn size(&self) -> usize {
        self.table.read().len()
    }

    #[cfg(not(feature = "async"))]
    pub fn hash(&self, val: Value) -> Result<u64, Exception> {
        self.hash.call(&[val])?.expect1()
    }

    #[cfg(feature = "async")]
    pub fn hash(&self, val: Value) -> Result<u64, Exception> {
        self.hash.call_sync(&[val])?.expect1()
    }

    #[cfg(not(feature = "async"))]
    pub fn eq(&self, lhs: Value, rhs: Value) -> Result<bool, Exception> {
        self.eq.call(&[lhs, rhs])?.expect1()
    }

    #[cfg(feature = "async")]
    pub fn eq(&self, lhs: Value, rhs: Value) -> Result<bool, Exception> {
        self.eq.call_sync(&[lhs, rhs])?.expect1()
    }

    /// Equivalent to `hashtable-ref`
    pub fn get(&self, key: &Value, default: &Value) -> Result<Value, Exception> {
        let table = self.table.read();
        let hash = self.hash(key.clone())?;
        for entry in table.iter_hash(hash) {
            if entry.hash == hash && self.eq(key.clone(), entry.key.clone())? {
                return Ok(entry.val.clone());
            }
        }
        Ok(default.clone())
    }

    pub fn set(&self, key: &Value, val: &Value) -> Result<(), Exception> {
        if !self.mutable {
            return Err(Exception::error("hashtable is immutable"));
        }

        let mut table = self.table.write();
        let hash = self.hash(key.clone())?;
        for entry in table.iter_hash_mut(hash) {
            if entry.hash == hash && self.eq(key.clone(), entry.key.clone())? {
                entry.val = val.clone();
                return Ok(());
            }
        }

        // Insert the new entry, guaranteed to be unique.
        table.insert_unique(
            hash,
            TableEntry {
                key: key.clone(),
                val: val.clone(),
                hash,
            },
            TableEntry::get_hash,
        );

        Ok(())
    }

    pub fn delete(&self, key: &Value) -> Result<(), Exception> {
        if !self.mutable {
            return Err(Exception::error("hashtable is immutable"));
        }

        let mut table = self.table.write();
        let hash = self.hash(key.clone())?;
        let buckets = table.iter_hash_buckets(hash).collect::<Vec<_>>();
        for bucket in buckets.into_iter() {
            if let Ok(entry) = table.get_bucket_entry(bucket)
                && let inner = entry.get()
                && inner.hash == hash
                && self.eq(key.clone(), inner.key.clone())?
            {
                entry.remove();
                return Ok(());
            }
        }

        Ok(())
    }

    pub fn contains(&self, key: &Value) -> Result<bool, Exception> {
        let table = self.table.write();
        let hash = self.hash(key.clone())?;
        for entry in table.iter_hash(hash) {
            if entry.hash == hash && self.eq(key.clone(), entry.key.clone())? {
                return Ok(true);
            }
        }

        Ok(false)
    }

    pub fn update(&self, key: &Value, proc: &Procedure, default: &Value) -> Result<(), Exception> {
        use std::slice;

        if !self.mutable {
            return Err(Exception::error("hashtable is immutable"));
        }

        let mut table = self.table.write();
        let hash = self.hash(key.clone())?;
        for entry in table.iter_hash_mut(hash) {
            if entry.hash == hash && self.eq(key.clone(), entry.key.clone())? {
                #[cfg(not(feature = "async"))]
                let updated = proc.call(slice::from_ref(&entry.val))?[0].clone();

                #[cfg(feature = "async")]
                let updated = proc.call_sync(slice::from_ref(&entry.val))?[0].clone();

                entry.val = updated;
                return Ok(());
            }
        }

        #[cfg(not(feature = "async"))]
        let updated = proc.call(slice::from_ref(default))?[0].clone();

        #[cfg(feature = "async")]
        let updated = proc.call_sync(slice::from_ref(default))?[0].clone();

        table.insert_unique(
            hash,
            TableEntry {
                key: key.clone(),
                val: updated,
                hash,
            },
            TableEntry::get_hash,
        );

        Ok(())
    }

    pub fn copy(&self, mutable: bool) -> Self {
        Self {
            table: RwLock::new(self.table.read().clone()),
            eq: self.eq.clone(),
            hash: self.hash.clone(),
            mutable,
        }
    }

    pub fn clear(&self) -> Result<(), Exception> {
        if !self.mutable {
            return Err(Exception::error("hashtable is immutable"));
        }

        self.table.write().clear();

        Ok(())
    }

    pub fn keys(&self) -> Vec<Value> {
        self.table
            .read()
            .iter()
            .map(|entry| entry.key.clone())
            .collect()
    }

    pub fn entries(&self) -> (Vec<Value>, Vec<Value>) {
        self.table
            .read()
            .iter()
            .map(|entry| (entry.key.clone(), entry.val.clone()))
            .unzip()
    }
}

#[derive(Clone, Trace)]
pub struct HashTable(pub(crate) Gc<HashTableInner>);

impl HashTable {
    /*
    pub fn new_eq() -> Self {
        todo!()
    }

    pub fn new_eqv() -> Self {
        todo!()
    }

    pub fn new_equal() -> Self {
        todo!()
    }
    */

    pub fn new(hash: Procedure, eq: Procedure) -> Self {
        Self(Gc::new(HashTableInner {
            table: RwLock::new(hashbrown::HashTable::new()),
            eq,
            hash,
            mutable: true,
        }))
    }

    pub fn with_capacity(hash: Procedure, eq: Procedure, cap: usize) -> Self {
        Self(Gc::new(HashTableInner {
            table: RwLock::new(hashbrown::HashTable::with_capacity(cap)),
            eq,
            hash,
            mutable: true,
        }))
    }

    pub fn size(&self) -> usize {
        self.0.size()
    }

    pub fn get(&self, key: &Value, default: &Value) -> Result<Value, Exception> {
        self.0.get(key, default)
    }

    pub fn set(&self, key: &Value, val: &Value) -> Result<(), Exception> {
        self.0.set(key, val)
    }

    pub fn delete(&self, key: &Value) -> Result<(), Exception> {
        self.0.delete(key)
    }

    pub fn contains(&self, key: &Value) -> Result<bool, Exception> {
        self.0.contains(key)
    }

    pub fn update(&self, key: &Value, proc: &Procedure, default: &Value) -> Result<(), Exception> {
        self.0.update(key, proc, default)
    }

    pub fn copy(&self, mutable: bool) -> Self {
        Self(Gc::new(self.0.copy(mutable)))
    }

    pub fn clear(&self) -> Result<(), Exception> {
        self.0.clear()
    }

    pub fn keys(&self) -> Vec<Value> {
        self.0.keys()
    }

    pub fn entries(&self) -> (Vec<Value>, Vec<Value>) {
        self.0.entries()
    }
}

impl fmt::Debug for HashTable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#hash(")?;
        for (i, entry) in self.0.table.read().iter().enumerate() {
            if i > 0 {
                write!(f, " ")?;
            }
            write!(f, "({:?} . {:?})", entry.key, entry.val)?;
        }
        write!(f, ")")
    }
}

#[derive(Default, Trace)]
pub struct EqualHashSet {
    set: HashSet<EqualValue>,
}

impl EqualHashSet {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&mut self, new_value: Value) {
        let new_value = EqualValue(new_value);
        if !self.set.contains(&new_value) {
            self.set.insert(new_value);
        }
    }

    pub fn get(&mut self, val: &Value) -> &Value {
        let val = EqualValue(val.clone());
        &self.set.get(&val).unwrap().0
    }
}

#[derive(Clone, Eq, Trace)]
pub struct EqualValue(pub Value);

impl PartialEq for EqualValue {
    fn eq(&self, rhs: &Self) -> bool {
        self.0.equal(&rhs.0)
    }
}

impl Hash for EqualValue {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.equal_hash(&mut IndexSet::new(), state)
    }
}

#[bridge(name = "make-hashtable", lib = "(rnrs hashtables builtins (6))")]
pub fn make_hashtable(
    hash_function: &Value,
    equiv: &Value,
    rest: &[Value],
) -> Result<Vec<Value>, Exception> {
    let hash: Procedure = hash_function.clone().try_into()?;
    let equiv: Procedure = equiv.clone().try_into()?;
    let k = match rest {
        [] => None,
        [k] => Some(k.try_into()?),
        x => return Err(Exception::wrong_num_of_args(3, 2 + x.len())),
    };
    let hashtable = if let Some(k) = k {
        HashTable::with_capacity(hash, equiv, k)
    } else {
        HashTable::new(hash, equiv)
    };
    Ok(vec![Value::from(hashtable)])
}

#[bridge(name = "hashtable?", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_pred(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    Ok(vec![Value::from(
        hashtable.type_of() == ValueType::HashTable,
    )])
}

#[bridge(name = "hashtable-size", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_size(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    Ok(vec![Value::from(hashtable.size())])
}

#[bridge(name = "hashtable-ref", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_ref(
    hashtable: &Value,
    key: &Value,
    default: &Value,
) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    Ok(vec![hashtable.get(key, default)?])
}

#[bridge(name = "hashtable-set!", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_set_bang(
    hashtable: &Value,
    key: &Value,
    obj: &Value,
) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    hashtable.set(key, obj)?;
    Ok(Vec::new())
}

#[bridge(name = "hashtable-delete!", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_delete_bang(hashtable: &Value, key: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    hashtable.delete(key)?;
    Ok(Vec::new())
}

#[bridge(name = "hashtable-contains?", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_contains_pred(hashtable: &Value, key: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    Ok(vec![Value::from(hashtable.contains(key)?)])
}

#[bridge(name = "hashtable-update!", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_update_bang(
    hashtable: &Value,
    key: &Value,
    proc: &Value,
    default: &Value,
) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let proc: Procedure = proc.clone().try_into()?;
    hashtable.update(key, &proc, default)?;
    Ok(Vec::new())
}

#[bridge(name = "hashtable-copy", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_copy(hashtable: &Value, rest: &[Value]) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let mutable = match rest {
        [] => false,
        [mutable] => mutable.is_true(),
        x => return Err(Exception::wrong_num_of_args(2, 1 + x.len())),
    };
    let new_hashtable = hashtable.copy(mutable);
    Ok(vec![Value::from(new_hashtable)])
}

#[bridge(name = "hashtable-clear!", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_clear_bang(hashtable: &Value, rest: &[Value]) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let k = match rest {
        [] => None,
        [k] => Some(k.try_into()?),
        x => return Err(Exception::wrong_num_of_args(3, 2 + x.len())),
    };

    hashtable.clear()?;

    if let Some(k) = k {
        let mut table = hashtable.0.table.write();
        if table.capacity() < k {
            table.shrink_to(k, TableEntry::get_hash);
        } else {
            table.reserve(k, TableEntry::get_hash);
        }
    }

    Ok(Vec::new())
}

#[bridge(name = "hashtable-keys", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_keys(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let keys = Value::from(hashtable.keys());
    Ok(vec![keys])
}

#[bridge(name = "hashtable-entries", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_entries(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let (keys, values) = hashtable.entries();
    Ok(vec![Value::from(keys), Value::from(values)])
}

#[bridge(
    name = "hashtable-equivalence-function",
    lib = "(rnrs hashtables builtins (6))"
)]
pub fn hashtable_equivalence_function(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let eqv_func = Value::from(hashtable.0.eq.clone());
    Ok(vec![eqv_func])
}

#[bridge(
    name = "hashtable-hash-function",
    lib = "(rnrs hashtables builtins (6))"
)]
pub fn hashtable_hash_function(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let hash_func = Value::from(hashtable.0.hash.clone());
    Ok(vec![hash_func])
}

#[bridge(name = "hashtable-mutable?", lib = "(rnrs hashtables builtins (6))")]
pub fn hashtable_mutable_pred(hashtable: &Value) -> Result<Vec<Value>, Exception> {
    let hashtable: HashTable = hashtable.clone().try_into()?;
    let is_mutable = Value::from(hashtable.0.mutable);
    Ok(vec![is_mutable])
}

#[bridge(name = "eq-hash", lib = "(rnrs hashtables builtins (6))")]
pub fn eq_hash(obj: &Value) -> Result<Vec<Value>, Exception> {
    let mut hasher = DefaultHasher::new();
    obj.eq_hash(&mut hasher);
    Ok(vec![Value::from(hasher.finish())])
}

#[bridge(name = "eqv-hash", lib = "(rnrs hashtables builtins (6))")]
pub fn eqv_hash(obj: &Value) -> Result<Vec<Value>, Exception> {
    let mut hasher = DefaultHasher::new();
    obj.eqv_hash(&mut hasher);
    Ok(vec![Value::from(hasher.finish())])
}

#[bridge(name = "equal-hash", lib = "(rnrs hashtables builtins (6))")]
pub fn equal_hash(obj: &Value) -> Result<Vec<Value>, Exception> {
    let mut hasher = DefaultHasher::new();
    obj.equal_hash(&mut IndexSet::default(), &mut hasher);
    Ok(vec![Value::from(hasher.finish())])
}

#[bridge(name = "string-hash", lib = "(rnrs hashtables builtins (6))")]
pub fn string_hash(string: &Value) -> Result<Vec<Value>, Exception> {
    let string: WideString = string.clone().try_into()?;
    let mut hasher = DefaultHasher::new();
    string.hash(&mut hasher);
    Ok(vec![Value::from(hasher.finish())])
}

#[bridge(name = "string-ci-hash", lib = "(rnrs hashtables builtins (6))")]
pub fn string_ci_hash(string: &Value) -> Result<Vec<Value>, Exception> {
    let string: WideString = string.clone().try_into()?;
    let mut hasher = DefaultHasher::new();
    let chars = string.0.chars.read();
    hasher.write_usize(chars.len());
    for lowercase in chars.iter().copied().flat_map(char::to_lowercase) {
        lowercase.hash(&mut hasher);
    }
    Ok(vec![Value::from(hasher.finish())])
}

#[bridge(name = "symbol-hash", lib = "(rnrs hashtables builtins (6))")]
pub fn symbol_hash(symbol: &Value) -> Result<Vec<Value>, Exception> {
    let symbol: Symbol = symbol.clone().try_into()?;
    let mut hasher = DefaultHasher::new();
    symbol.hash(&mut hasher);
    Ok(vec![Value::from(hasher.finish())])
}