• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

TyRoXx / NonlocalityOS / 15094543999

18 May 2025 09:28AM UTC coverage: 71.894% (-0.2%) from 72.054%
15094543999

Pull #245

github

web-flow
Merge b2ba4ee99 into 4e7b17925
Pull Request #245: GH-244: multiple parameters actually work

149 of 186 new or added lines in 7 files covered. (80.11%)

6 existing lines in 2 files now uncovered.

3177 of 4419 relevant lines covered (71.89%)

2245.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.55
/lambda/src/expressions.rs
1
use crate::name::Name;
2
use astraea::tree::{BlobDigest, HashedTree, ReferenceIndex, Tree, TreeDeserializationError};
3
use astraea::{
4
    storage::{LoadTree, StoreError, StoreTree},
5
    tree::TreeBlob,
6
};
7
use serde::{Deserialize, Serialize};
8
use std::fmt::Display;
9
use std::future::Future;
10
use std::hash::Hash;
11
use std::{pin::Pin, sync::Arc};
12

13
pub trait PrintExpression {
14
    fn print(&self, writer: &mut dyn std::fmt::Write, level: usize) -> std::fmt::Result;
15
}
16

17
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone, Serialize, Deserialize)]
18
pub enum Expression<E, TreeLike>
19
where
20
    E: Clone + Display + PrintExpression,
21
    TreeLike: Clone + Display,
22
{
23
    Literal(TreeLike),
24
    Apply { callee: E, argument: E },
25
    Argument,
26
    Environment,
27
    Lambda { environment: E, body: E },
28
    ConstructTree(Vec<E>),
29
}
30

31
impl<E, V> PrintExpression for Expression<E, V>
32
where
33
    E: Clone + Display + PrintExpression,
34
    V: Clone + Display,
35
{
36
    fn print(&self, writer: &mut dyn std::fmt::Write, level: usize) -> std::fmt::Result {
19✔
37
        match self {
19✔
38
            Expression::Literal(literal_value) => {
8✔
39
                write!(writer, "literal({literal_value})")
8✔
40
            }
41
            Expression::Apply { callee, argument } => {
1✔
42
                callee.print(writer, level)?;
1✔
43
                write!(writer, "(")?;
1✔
44
                argument.print(writer, level)?;
1✔
45
                write!(writer, ")")
1✔
46
            }
NEW
47
            Expression::Argument => {
×
48
                write!(writer, "$arg")
1✔
49
            }
NEW
50
            Expression::Environment => {
×
51
                write!(writer, "$env")
2✔
52
            }
53
            Expression::Lambda { environment, body } => {
4✔
54
                write!(writer, "$env={{")?;
4✔
55
                let indented = level + 1;
4✔
56
                environment.print(writer, indented)?;
4✔
57
                writeln!(writer, "}}($arg) =>")?;
4✔
58
                for _ in 0..(indented * 2) {
4✔
59
                    write!(writer, " ")?;
10✔
60
                }
61
                body.print(writer, indented)
4✔
62
            }
63
            Expression::ConstructTree(arguments) => {
3✔
64
                write!(writer, "[")?;
3✔
65
                for argument in arguments {
13✔
66
                    argument.print(writer, level)?;
5✔
67
                    write!(writer, ", ")?;
5✔
68
                }
69
                write!(writer, "]")
3✔
70
            }
71
        }
72
    }
73
}
74

75
impl<E, TreeLike> Expression<E, TreeLike>
76
where
77
    E: Clone + Display + PrintExpression,
78
    TreeLike: Clone + Display,
79
{
80
    pub fn make_literal(value: TreeLike) -> Self {
46✔
81
        Expression::Literal(value)
46✔
82
    }
83

84
    pub fn make_apply(callee: E, argument: E) -> Self {
6✔
85
        Expression::Apply { callee, argument }
86
    }
87

88
    pub fn make_argument() -> Self {
18✔
89
        Expression::Argument
18✔
90
    }
91

92
    pub fn make_environment() -> Self {
2✔
93
        Expression::Environment
2✔
94
    }
95

96
    pub fn make_lambda(environment: E, body: E) -> Self {
14✔
97
        Expression::Lambda { environment, body }
98
    }
99

100
    pub fn make_construct_tree(arguments: Vec<E>) -> Self {
9✔
101
        Expression::ConstructTree(arguments)
9✔
102
    }
103

104
    pub async fn map_child_expressions<
65✔
105
        't,
106
        Expr: Clone + Display + PrintExpression,
107
        TreeLike2: Clone + Display,
108
        Error,
109
        F,
110
        G,
111
    >(
112
        &self,
113
        transform_expression: &'t F,
114
        transform_tree: &'t G,
115
    ) -> Result<Expression<Expr, TreeLike2>, Error>
116
    where
117
        F: Fn(&E) -> Pin<Box<dyn Future<Output = Result<Expr, Error>> + 't>>,
118
        G: Fn(&TreeLike) -> Pin<Box<dyn Future<Output = Result<TreeLike2, Error>> + 't>>,
119
    {
120
        match self {
65✔
121
            Expression::Literal(value) => Ok(Expression::Literal(transform_tree(value).await?)),
27✔
122
            Expression::Apply { callee, argument } => Ok(Expression::Apply {
6✔
123
                callee: transform_expression(callee).await?,
6✔
124
                argument: transform_expression(argument).await?,
6✔
125
            }),
126
            Expression::Argument => Ok(Expression::Argument),
9✔
127
            Expression::Environment => Ok(Expression::Environment),
4✔
128
            Expression::Lambda { environment, body } => Ok(Expression::Lambda {
6✔
129
                environment: transform_expression(environment).await?,
6✔
130
                body: transform_expression(body).await?,
6✔
131
            }),
132
            Expression::ConstructTree(items) => {
13✔
133
                let mut transformed_items = Vec::new();
13✔
134
                for item in items.iter() {
32✔
135
                    transformed_items.push(transform_expression(item).await?);
57✔
136
                }
137
                Ok(Expression::ConstructTree(transformed_items))
13✔
138
            }
139
        }
140
    }
141
}
142

143
impl<E, V> Display for Expression<E, V>
144
where
145
    E: Clone + Display + PrintExpression,
146
    V: Clone + Display,
147
{
148
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
×
149
        self.print(f, 0)
×
150
    }
151
}
152

153
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Clone)]
154
pub struct DeepExpression(pub Expression<Arc<DeepExpression>, BlobDigest>);
155

156
impl PrintExpression for DeepExpression {
157
    fn print(&self, writer: &mut dyn std::fmt::Write, level: usize) -> std::fmt::Result {
1✔
158
        self.0.print(writer, level)
1✔
159
    }
160
}
161

162
impl PrintExpression for Arc<DeepExpression> {
163
    fn print(&self, writer: &mut dyn std::fmt::Write, level: usize) -> std::fmt::Result {
15✔
164
        self.0.print(writer, level)
15✔
165
    }
166
}
167

168
impl Display for DeepExpression {
169
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
×
170
        write!(f, "{}", self.0)
×
171
    }
172
}
173

174
pub type ShallowExpression = Expression<BlobDigest, BlobDigest>;
175

176
impl PrintExpression for BlobDigest {
177
    fn print(&self, writer: &mut dyn std::fmt::Write, _level: usize) -> std::fmt::Result {
1✔
178
        write!(writer, "{self}")
1✔
179
    }
180
}
181

182
pub type ReferenceExpression = Expression<ReferenceIndex, ReferenceIndex>;
183

184
impl PrintExpression for ReferenceIndex {
185
    fn print(&self, writer: &mut dyn std::fmt::Write, _level: usize) -> std::fmt::Result {
1✔
186
        write!(writer, "{self}")
1✔
187
    }
188
}
189

190
pub fn to_reference_expression(
24✔
191
    expression: &ShallowExpression,
192
) -> (ReferenceExpression, Vec<BlobDigest>) {
193
    match expression {
24✔
194
        Expression::Literal(value) => (
9✔
195
            ReferenceExpression::Literal(ReferenceIndex(0)),
9✔
196
            vec![*value],
9✔
197
        ),
198
        Expression::Apply { callee, argument } => (
2✔
199
            ReferenceExpression::Apply {
2✔
200
                callee: ReferenceIndex(0),
2✔
201
                argument: ReferenceIndex(1),
2✔
202
            },
203
            // TODO: deduplicate?
204
            vec![*callee, *argument],
2✔
205
        ),
206
        Expression::Argument => (ReferenceExpression::Argument, vec![]),
4✔
207
        Expression::Environment => (ReferenceExpression::Environment, vec![]),
2✔
208
        Expression::Lambda { environment, body } => (
2✔
209
            ReferenceExpression::Lambda {
2✔
210
                environment: ReferenceIndex(0),
2✔
211
                body: ReferenceIndex(1),
2✔
212
            },
213
            vec![*environment, *body],
2✔
214
        ),
215
        Expression::ConstructTree(items) => (
5✔
216
            ReferenceExpression::ConstructTree(
5✔
217
                (0..items.len())
5✔
218
                    .map(|index| ReferenceIndex(index as u64))
12✔
219
                    .collect(),
5✔
220
            ),
221
            // TODO: deduplicate?
222
            items.clone(),
5✔
223
        ),
224
    }
225
}
226

227
pub async fn deserialize_shallow(tree: &Tree) -> Result<ShallowExpression, ()> {
42✔
228
    let reference_expression: ReferenceExpression = postcard::from_bytes(tree.blob().as_slice())
21✔
229
        .unwrap(/*TODO*/);
230
    reference_expression
21✔
231
        .map_child_expressions(
232
            &|child: &ReferenceIndex| -> Pin<Box<dyn Future<Output = Result<BlobDigest, ()>>>> {
14✔
233
                let child = tree.references()[child.0 as usize];
14✔
234
                Box::pin(async move { Ok(child) })
28✔
235
            },
236
            &|child: &ReferenceIndex| -> Pin<Box<dyn Future<Output = Result<BlobDigest, ()>>>> {
9✔
237
                let child = tree.references()[child.0 as usize];
9✔
238
                Box::pin(async move { Ok(child) })
18✔
239
            },
240
        )
241
        .await
21✔
242
}
243

244
pub async fn deserialize_recursively(
21✔
245
    root: &BlobDigest,
246
    load_tree: &(dyn LoadTree + Sync),
247
) -> Result<DeepExpression, ()> {
248
    let root_loaded = load_tree.load_tree(root).await.unwrap(/*TODO*/).hash().unwrap(/*TODO*/);
63✔
249
    let shallow = deserialize_shallow(root_loaded.tree()).await?;
42✔
250
    let deep = shallow
21✔
251
        .map_child_expressions(
252
            &|child: &BlobDigest| -> Pin<Box<dyn Future<Output = Result<Arc<DeepExpression>, ()>>>> {
14✔
253
                let child = *child;
14✔
254
                Box::pin(async move { deserialize_recursively(&child, load_tree)
28✔
255
                    .await
14✔
256
                    .map(Arc::new) })
14✔
257
            },
258
            &|child: &BlobDigest| -> Pin<Box<dyn Future<Output = Result<BlobDigest, ()>>>> {
9✔
259
                let child = *child;
9✔
260
                Box::pin(async move { Ok(child) })
18✔
261
            },
262
        )
263
        .await?;
×
264
    Ok(DeepExpression(deep))
×
265
}
266

267
pub fn expression_to_tree(expression: &ShallowExpression) -> Tree {
23✔
268
    let (reference_expression, references) = to_reference_expression(expression);
23✔
269
    let blob = postcard::to_allocvec(&reference_expression).unwrap(/*TODO*/);
23✔
270
    Tree::new(
271
        TreeBlob::try_from(bytes::Bytes::from_owner(blob)).unwrap(/*TODO*/),
23✔
272
        references,
23✔
273
    )
274
}
275

276
pub async fn serialize_shallow(
23✔
277
    expression: &ShallowExpression,
278
    storage: &(dyn StoreTree + Sync),
279
) -> std::result::Result<BlobDigest, StoreError> {
280
    let tree = expression_to_tree(expression);
23✔
281
    storage.store_tree(&HashedTree::from(Arc::new(tree))).await
23✔
282
}
283

284
pub async fn serialize_recursively(
23✔
285
    expression: &DeepExpression,
286
    storage: &(dyn StoreTree + Sync),
287
) -> std::result::Result<BlobDigest, StoreError> {
288
    let shallow_expression: ShallowExpression = expression
46✔
289
        .0
23✔
290
        .map_child_expressions(&|child: &Arc<DeepExpression>| -> Pin<
23✔
291
            Box<dyn Future<Output = Result<BlobDigest, StoreError>>>,
292
        > {
15✔
293
            let child = child.clone();
15✔
294
            Box::pin(async move {
30✔
295
                serialize_recursively(&child, storage)
15✔
296
                    .await
15✔
297
            })
298
        },&|child: &BlobDigest| -> Pin<
15✔
299
        Box<dyn Future<Output = Result<BlobDigest, StoreError>>>,
300
        > {
9✔
301
            let child = *child;
9✔
302
            Box::pin(async move {
18✔
303
                Ok(child)
9✔
304
            })
305
        })
306
        .await?;
23✔
307
    serialize_shallow(&shallow_expression, storage).await
×
308
}
309

310
#[derive(Debug)]
311
pub struct Closure {
312
    environment: BlobDigest,
313
    body: Arc<DeepExpression>,
314
}
315

316
#[derive(Debug, Serialize, Deserialize)]
317
pub struct ClosureBlob {}
318

319
impl ClosureBlob {
320
    pub fn new() -> Self {
7✔
321
        Self {}
322
    }
323
}
324

325
impl Closure {
326
    pub fn new(environment: BlobDigest, body: Arc<DeepExpression>) -> Self {
13✔
327
        Self { environment, body }
328
    }
329

330
    pub async fn serialize(
7✔
331
        &self,
332
        store_tree: &(dyn StoreTree + Sync),
333
    ) -> Result<BlobDigest, StoreError> {
334
        let references = vec![
14✔
335
            self.environment,
7✔
336
            serialize_recursively(&self.body, store_tree).await?,
7✔
337
        ];
NEW
338
        let closure_blob = ClosureBlob::new();
×
339
        let closure_blob_bytes = postcard::to_allocvec(&closure_blob).unwrap(/*TODO*/);
×
340
        store_tree
×
341
            .store_tree(&HashedTree::from(Arc::new(Tree::new(
×
342
                TreeBlob::try_from(bytes::Bytes::from_owner(closure_blob_bytes)).unwrap(/*TODO*/),
×
343
                references,
×
344
            ))))
345
            .await
×
346
    }
347

348
    pub async fn deserialize(
6✔
349
        root: &BlobDigest,
350
        load_tree: &(dyn LoadTree + Sync),
351
    ) -> Result<Closure, TreeDeserializationError> {
352
        let loaded_root = match load_tree.load_tree(root).await {
12✔
353
            Some(success) => success,
6✔
354
            None => return Err(TreeDeserializationError::BlobUnavailable(*root)),
×
355
        };
356
        let root_tree = loaded_root.hash().unwrap(/*TODO*/).tree().clone();
6✔
357
        let _closure_blob: ClosureBlob = match postcard::from_bytes(root_tree.blob().as_slice()) {
12✔
358
            Ok(success) => success,
×
359
            Err(error) => return Err(TreeDeserializationError::Postcard(error)),
×
360
        };
NEW
361
        let environment_reference = &root_tree.references()[0];
×
NEW
362
        let body_reference = &root_tree.references()[1];
×
363
        let body = deserialize_recursively(body_reference, load_tree).await.unwrap(/*TODO*/);
12✔
364
        Ok(Closure::new(*environment_reference, Arc::new(body)))
6✔
365
    }
366
}
367

368
async fn call_method(
6✔
369
    body: &DeepExpression,
370
    argument: &BlobDigest,
371
    load_tree: &(dyn LoadTree + Sync),
372
    store_tree: &(dyn StoreTree + Sync),
373
) -> std::result::Result<BlobDigest, StoreError> {
374
    Box::pin(evaluate(body, load_tree, store_tree, &Some(*argument))).await
6✔
375
}
376

377
pub type ReadVariable =
378
    dyn Fn(&Name) -> Pin<Box<dyn core::future::Future<Output = BlobDigest> + Send>> + Send + Sync;
379

380
pub async fn apply_evaluated_argument(
6✔
381
    callee: &DeepExpression,
382
    evaluated_argument: &BlobDigest,
383
    load_tree: &(dyn LoadTree + Sync),
384
    store_tree: &(dyn StoreTree + Sync),
385
    current_lambda_argument: &Option<BlobDigest>,
386
) -> std::result::Result<BlobDigest, StoreError> {
387
    let evaluated_callee = Box::pin(evaluate(
12✔
388
        callee,
6✔
389
        load_tree,
6✔
390
        store_tree,
6✔
391
        current_lambda_argument,
6✔
392
    ))
393
    .await?;
6✔
394
    let closure = match Closure::deserialize(&evaluated_callee, load_tree).await {
6✔
395
        Ok(success) => success,
6✔
396
        Err(_) => todo!(),
397
    };
398
    call_method(&closure.body, evaluated_argument, load_tree, store_tree).await
6✔
399
}
400

401
pub async fn evaluate_apply(
4✔
402
    callee: &DeepExpression,
403
    argument: &DeepExpression,
404
    load_tree: &(dyn LoadTree + Sync),
405
    store_tree: &(dyn StoreTree + Sync),
406
    current_lambda_argument: &Option<BlobDigest>,
407
) -> std::result::Result<BlobDigest, StoreError> {
408
    let evaluated_argument = Box::pin(evaluate(
8✔
409
        argument,
4✔
410
        load_tree,
4✔
411
        store_tree,
4✔
412
        current_lambda_argument,
4✔
413
    ))
414
    .await?;
4✔
415
    apply_evaluated_argument(
416
        callee,
×
417
        &evaluated_argument,
×
418
        load_tree,
×
419
        store_tree,
×
NEW
420
        current_lambda_argument,
×
421
    )
422
    .await
×
423
}
424

425
pub async fn evaluate(
33✔
426
    expression: &DeepExpression,
427
    load_tree: &(dyn LoadTree + Sync),
428
    store_tree: &(dyn StoreTree + Sync),
429
    current_lambda_argument: &Option<BlobDigest>,
430
) -> std::result::Result<BlobDigest, StoreError> {
431
    match &expression.0 {
33✔
432
        Expression::Literal(literal_value) => Ok(*literal_value),
17✔
433
        Expression::Apply { callee, argument } => {
4✔
434
            evaluate_apply(
435
                callee,
4✔
436
                argument,
4✔
437
                load_tree,
4✔
438
                store_tree,
4✔
439
                current_lambda_argument,
4✔
440
            )
441
            .await
4✔
442
        }
443
        Expression::Argument => {
444
            if let Some(argument) = current_lambda_argument {
4✔
445
                Ok(*argument)
2✔
446
            } else {
447
                todo!("We are not in a lambda context; argument is not available")
448
            }
449
        }
450
        Expression::Environment => {
451
            todo!()
452
        }
453
        Expression::Lambda { environment, body } => {
7✔
454
            let evaluated_environment = Box::pin(evaluate(
14✔
455
                environment,
7✔
456
                load_tree,
7✔
457
                store_tree,
7✔
458
                current_lambda_argument,
7✔
459
            ))
460
            .await?;
7✔
NEW
461
            let closure = Closure::new(evaluated_environment, body.clone());
×
462
            let serialized = closure.serialize(store_tree).await?;
7✔
463
            Ok(serialized)
×
464
        }
465
        Expression::ConstructTree(arguments) => {
3✔
466
            let mut evaluated_arguments = Vec::new();
3✔
467
            for argument in arguments {
13✔
468
                let evaluated_argument = Box::pin(evaluate(
10✔
469
                    argument,
5✔
470
                    load_tree,
5✔
471
                    store_tree,
5✔
472
                    current_lambda_argument,
5✔
473
                ))
474
                .await?;
5✔
UNCOV
475
                evaluated_arguments.push(evaluated_argument);
×
476
            }
477
            store_tree
3✔
478
                .store_tree(&HashedTree::from(Arc::new(Tree::new(
3✔
479
                    TreeBlob::empty(),
3✔
480
                    evaluated_arguments,
3✔
481
                ))))
482
                .await
3✔
483
        }
484
    }
485
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc