1
//! The symbol table.
2
//!
3
//! See the item documentation for [`SymbolTable`] for more details.
4

            
5
use crate::bug;
6
use crate::representation::{Representation, get_repr_rule};
7
use std::any::TypeId;
8

            
9
use std::collections::BTreeSet;
10
use std::collections::btree_map::Entry;
11
use std::collections::{BTreeMap, VecDeque};
12
use std::hash::{Hash, Hasher};
13
use std::sync::Arc;
14
use std::sync::atomic::{AtomicU32, Ordering};
15

            
16
use super::comprehension::Comprehension;
17
use super::serde::{AsId, DefaultWithId, HasId, IdPtr, ObjId, PtrAsInner};
18
use super::{
19
    DeclarationPtr, DomainPtr, Expression, GroundDomain, Moo, Name, ReturnType, SubModel, Typeable,
20
};
21
use itertools::{Itertools as _, izip};
22
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
23
use serde::{Deserialize, Serialize};
24
use serde_with::serde_as;
25
use tracing::trace;
26
use uniplate::{Biplate, Tree, Uniplate};
27

            
28
/// Global counter of symbol tables.
29
/// Note that the counter is shared between all threads
30
/// Thus, when running multiple models in parallel, IDs may
31
/// be different with every run depending on scheduling order
32
static SYMBOL_TABLE_ID_COUNTER: AtomicU32 = const { AtomicU32::new(0) };
33

            
34
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
35
pub struct SymbolTablePtr
36
where
37
    Self: Send + Sync,
38
{
39
    inner: Arc<SymbolTablePtrInner>,
40
}
41

            
42
impl SymbolTablePtr {
43
    /// Create an empty new [SymbolTable] and return a shared pointer to it
44
27036
    pub fn new() -> Self {
45
27036
        Self::new_with_data(SymbolTable::new())
46
27036
    }
47

            
48
    /// Create an empty new [SymbolTable] with the given parent and return a shared pointer to it
49
3280
    pub fn with_parent(symbols: SymbolTablePtr) -> Self {
50
3280
        Self::new_with_data(SymbolTable::with_parent(symbols))
51
3280
    }
52

            
53
30316
    fn new_with_data(data: SymbolTable) -> Self {
54
30316
        let object_id = SYMBOL_TABLE_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
55
30316
        let id = ObjId {
56
30316
            object_id,
57
30316
            type_name: SymbolTablePtr::TYPE_NAME.into(),
58
30316
        };
59
30316
        Self::new_with_id_and_data(id, data)
60
30316
    }
61

            
62
31516
    fn new_with_id_and_data(id: ObjId, data: SymbolTable) -> Self {
63
31516
        Self {
64
31516
            inner: Arc::new(SymbolTablePtrInner {
65
31516
                id,
66
31516
                value: RwLock::new(data),
67
31516
            }),
68
31516
        }
69
31516
    }
70

            
71
    /// Read the underlying symbol table.
72
    /// This will block the current thread until a read lock can be acquired.
73
    ///
74
    /// # WARNING
75
    ///
76
    /// - If the current thread already holds a lock over this table, this may deadlock.
77
44703308
    pub fn read(&self) -> RwLockReadGuard<'_, SymbolTable> {
78
44703308
        self.inner.value.read()
79
44703308
    }
80

            
81
    /// Mutate the underlying symbol table.
82
    /// This will block the current thread until an exclusive write lock can be acquired.
83
    ///
84
    /// # WARNING
85
    ///
86
    /// - If the current thread already holds a lock over this table, this may deadlock.
87
    /// - Trying to acquire any other lock until the write lock is released will cause a deadlock.
88
    /// - This will mutate the underlying data, which may be shared between other `SymbolTablePtr`s.
89
    ///   Make sure that this is what you want.
90
    ///
91
    /// To create a separate copy of the table, see [SymbolTablePtr::detach].
92
    ///
93
88408
    pub fn write(&self) -> RwLockWriteGuard<'_, SymbolTable> {
94
88408
        self.inner.value.write()
95
88408
    }
96

            
97
    /// Create a new symbol table with the same contents as this one, but a new ID,
98
    /// and return a pointer to it.
99
    pub fn detach(&self) -> Self {
100
        Self::new_with_data(self.read().clone())
101
    }
102
}
103

            
104
impl Default for SymbolTablePtr {
105
    fn default() -> Self {
106
        Self::new()
107
    }
108
}
109

            
110
impl HasId for SymbolTablePtr {
111
    const TYPE_NAME: &'static str = "SymbolTable";
112

            
113
2404
    fn id(&self) -> ObjId {
114
2404
        self.inner.id.clone()
115
2404
    }
116
}
117

            
118
impl DefaultWithId for SymbolTablePtr {
119
    fn default_with_id(id: ObjId) -> Self {
120
        Self::new_with_id_and_data(id, SymbolTable::default())
121
    }
122
}
123

            
124
impl IdPtr for SymbolTablePtr {
125
    type Data = SymbolTable;
126

            
127
602
    fn get_data(&self) -> Self::Data {
128
602
        self.read().clone()
129
602
    }
130

            
131
1200
    fn with_id_and_data(id: ObjId, data: Self::Data) -> Self {
132
1200
        Self::new_with_id_and_data(id, data)
133
1200
    }
134
}
135

            
136
// TODO: this code is almost exactly copied from [DeclarationPtr].
137
//       It should be possible to eliminate the duplication...
138
//       Perhaps by merging SymbolTablePtr and DeclarationPtr together?
139
//       (Alternatively, a macro?)
140

            
141
impl Uniplate for SymbolTablePtr {
142
    fn uniplate(&self) -> (Tree<Self>, Box<dyn Fn(Tree<Self>) -> Self>) {
143
        let symtab = self.read();
144
        let (tree, recons) = Biplate::<SymbolTablePtr>::biplate(&symtab as &SymbolTable);
145

            
146
        let self2 = self.clone();
147
        (
148
            tree,
149
            Box::new(move |x| {
150
                let self3 = self2.clone();
151
                *(self3.write()) = recons(x);
152
                self3
153
            }),
154
        )
155
    }
156
}
157

            
158
impl<To> Biplate<To> for SymbolTablePtr
159
where
160
    SymbolTable: Biplate<To>,
161
    To: Uniplate,
162
{
163
1200
    fn biplate(&self) -> (Tree<To>, Box<dyn Fn(Tree<To>) -> Self>) {
164
1200
        if TypeId::of::<To>() == TypeId::of::<Self>() {
165
            unsafe {
166
                let self_as_to = std::mem::transmute::<&Self, &To>(self).clone();
167
                (
168
                    Tree::One(self_as_to),
169
                    Box::new(move |x| {
170
                        let Tree::One(x) = x else { panic!() };
171

            
172
                        let x_as_self = std::mem::transmute::<&To, &Self>(&x);
173
                        x_as_self.clone()
174
                    }),
175
                )
176
            }
177
        } else {
178
            // call biplate on the enclosed declaration
179
1200
            let decl = self.read();
180
1200
            let (tree, recons) = Biplate::<To>::biplate(&decl as &SymbolTable);
181

            
182
1200
            let self2 = self.clone();
183
            (
184
1200
                tree,
185
1200
                Box::new(move |x| {
186
                    let self3 = self2.clone();
187
                    *(self3.write()) = recons(x);
188
                    self3
189
                }),
190
            )
191
        }
192
1200
    }
193
}
194

            
195
#[derive(Debug)]
196
struct SymbolTablePtrInner {
197
    id: ObjId,
198
    value: RwLock<SymbolTable>,
199
}
200

            
201
impl Hash for SymbolTablePtrInner {
202
    fn hash<H: Hasher>(&self, state: &mut H) {
203
        self.id.hash(state);
204
    }
205
}
206

            
207
impl PartialEq for SymbolTablePtrInner {
208
600
    fn eq(&self, other: &Self) -> bool {
209
600
        self.value.read().eq(&other.value.read())
210
600
    }
211
}
212

            
213
impl Eq for SymbolTablePtrInner {}
214

            
215
/// The global symbol table, mapping names to their definitions.
216
///
217
/// Names in the symbol table are unique, including between different types of object stored in the
218
/// symbol table. For example, you cannot have a letting and decision variable with the same name.
219
///
220
/// # Symbol Kinds
221
///
222
/// The symbol table tracks the following types of symbol:
223
///
224
/// ## Decision Variables
225
///
226
/// ```text
227
/// find NAME: DOMAIN
228
/// ```
229
///
230
/// See [`DecisionVariable`](super::DecisionVariable).
231
///
232
/// ## Lettings
233
///
234
/// Lettings define constants, of which there are two types:
235
///
236
///   + **Constant values**: `letting val be A`, where A is an [`Expression`].
237
///
238
///     A can be any integer, boolean, or matrix expression.
239
///     A can include references to other lettings, model parameters, and, unlike Savile Row,
240
///     decision variables.
241
///
242
///   + **Constant domains**: `letting Domain be domain D`, where D is a [`Domain`].
243
///
244
///     D can include references to other lettings and model parameters, and, unlike Savile Row,
245
///     decision variables.
246
///
247
/// Unless otherwise stated, these follow the semantics specified in section 2.2.2 of the Savile
248
/// Row manual (version 1.9.1 at time of writing).
249
#[serde_as]
250
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
251
pub struct SymbolTable {
252
    #[serde_as(as = "Vec<(_,PtrAsInner)>")]
253
    table: BTreeMap<Name, DeclarationPtr>,
254

            
255
    #[serde_as(as = "Option<AsId>")]
256
    parent: Option<SymbolTablePtr>,
257

            
258
    next_machine_name: i32,
259
}
260

            
261
impl SymbolTable {
262
    /// Creates an empty symbol table.
263
86786
    pub fn new() -> SymbolTable {
264
86786
        SymbolTable::new_inner(None)
265
86786
    }
266

            
267
    /// Creates an empty symbol table with the given parent.
268
3280
    pub fn with_parent(parent: SymbolTablePtr) -> SymbolTable {
269
3280
        SymbolTable::new_inner(Some(parent))
270
3280
    }
271

            
272
90066
    fn new_inner(parent: Option<SymbolTablePtr>) -> SymbolTable {
273
90066
        let id = SYMBOL_TABLE_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
274
90066
        trace!(
275
            "new symbol table: id = {id}  parent_id = {}",
276
12
            parent
277
12
                .as_ref()
278
12
                .map(|x| x.id().to_string())
279
12
                .unwrap_or(String::from("none"))
280
        );
281
90066
        SymbolTable {
282
90066
            table: BTreeMap::new(),
283
90066
            next_machine_name: 0,
284
90066
            parent,
285
90066
        }
286
90066
    }
287

            
288
    /// Looks up the declaration with the given name in the current scope only.
289
    ///
290
    /// Returns `None` if there is no declaration with that name in the current scope.
291
1360372
    pub fn lookup_local(&self, name: &Name) -> Option<DeclarationPtr> {
292
1360372
        self.table.get(name).cloned()
293
1360372
    }
294

            
295
    /// Looks up the declaration with the given name, checking all enclosing scopes.
296
    ///
297
    /// Returns `None` if there is no declaration with that name in scope.
298
1336912
    pub fn lookup(&self, name: &Name) -> Option<DeclarationPtr> {
299
1336912
        self.lookup_local(name).or_else(|| {
300
144182
            self.parent
301
144182
                .as_ref()
302
144182
                .and_then(|parent| parent.read().lookup(name))
303
144182
        })
304
1336912
    }
305

            
306
    /// Inserts a declaration into the symbol table.
307
    ///
308
    /// Returns `None` if there is already a symbol with this name in the local scope.
309
23118
    pub fn insert(&mut self, declaration: DeclarationPtr) -> Option<()> {
310
23118
        let name = declaration.name().clone();
311
23118
        if let Entry::Vacant(e) = self.table.entry(name) {
312
23118
            e.insert(declaration);
313
23118
            Some(())
314
        } else {
315
            None
316
        }
317
23118
    }
318

            
319
    /// Updates or adds a declaration in the immediate local scope.
320
3800
    pub fn update_insert(&mut self, declaration: DeclarationPtr) {
321
3800
        let name = declaration.name().clone();
322
3800
        self.table.insert(name, declaration);
323
3800
    }
324

            
325
    /// Looks up the return type for name if it has one and is in scope.
326
    pub fn return_type(&self, name: &Name) -> Option<ReturnType> {
327
        self.lookup(name).map(|x| x.return_type())
328
    }
329

            
330
    /// Looks up the return type for name if has one and is in the local scope.
331
    pub fn return_type_local(&self, name: &Name) -> Option<ReturnType> {
332
        self.lookup_local(name).map(|x| x.return_type())
333
    }
334

            
335
    /// Looks up the domain of name if it has one and is in scope.
336
    ///
337
    /// This method can return domain references: if a ground domain is always required, use
338
    /// [`SymbolTable::resolve_domain`].
339
101620
    pub fn domain(&self, name: &Name) -> Option<DomainPtr> {
340
101620
        if let Name::WithRepresentation(name, _) = name {
341
23640
            self.lookup(name)?.domain()
342
        } else {
343
77980
            self.lookup(name)?.domain()
344
        }
345
101620
    }
346

            
347
    /// Looks up the domain of name, resolving domain references to ground domains.
348
    ///
349
    /// See [`SymbolTable::domain`].
350
101620
    pub fn resolve_domain(&self, name: &Name) -> Option<Moo<GroundDomain>> {
351
101620
        self.domain(name)?.resolve()
352
101620
    }
353

            
354
    /// Iterates over entries in the LOCAL symbol table.
355
141848
    pub fn into_iter_local(self) -> impl Iterator<Item = (Name, DeclarationPtr)> {
356
141848
        self.table.into_iter()
357
141848
    }
358

            
359
    /// Iterates over entries in the LOCAL symbol table, by reference.
360
1802
    pub fn iter_local(&self) -> impl Iterator<Item = (&Name, &DeclarationPtr)> {
361
1802
        self.table.iter()
362
1802
    }
363

            
364
    /// Extends the symbol table with the given symbol table, updating the gensym counter if
365
    /// necessary.
366
47690
    pub fn extend(&mut self, other: SymbolTable) {
367
47690
        if other.table.keys().count() > self.table.keys().count() {
368
4040
            let new_vars = other.table.keys().collect::<BTreeSet<_>>();
369
4040
            let old_vars = self.table.keys().collect::<BTreeSet<_>>();
370

            
371
7440
            for added_var in new_vars.difference(&old_vars) {
372
7440
                let next_var = &mut self.next_machine_name;
373
7440
                if let Name::Machine(m) = *added_var
374
3440
                    && *m >= *next_var
375
3440
                {
376
3440
                    *next_var = *m + 1;
377
4000
                }
378
            }
379
43650
        }
380

            
381
47690
        self.table.extend(other.table);
382
47690
    }
383

            
384
    /// Creates a new variable in this symbol table with a unique name, and returns its
385
    /// declaration.
386
6560
    pub fn gensym(&mut self, domain: &DomainPtr) -> DeclarationPtr {
387
6560
        let num = self.next_machine_name;
388
6560
        self.next_machine_name += 1;
389
6560
        let decl = DeclarationPtr::new_find(Name::Machine(num), domain.clone());
390
6560
        self.insert(decl.clone());
391
6560
        decl
392
6560
    }
393

            
394
    /// Gets the parent of this symbol table as a mutable reference.
395
    ///
396
    /// This function provides no sanity checks.
397
1200
    pub fn parent_mut_unchecked(&mut self) -> &mut Option<SymbolTablePtr> {
398
1200
        &mut self.parent
399
1200
    }
400

            
401
    /// Gets the parent of this symbol table.
402
800
    pub fn parent(&self) -> &Option<SymbolTablePtr> {
403
800
        &self.parent
404
800
    }
405

            
406
    /// Gets the representation `representation` for `name`.
407
    ///
408
    /// # Returns
409
    ///
410
    /// + `None` if `name` does not exist, is not a decision variable, or does not have that representation.
411
5980
    pub fn get_representation(
412
5980
        &self,
413
5980
        name: &Name,
414
5980
        representation: &[&str],
415
5980
    ) -> Option<Vec<Box<dyn Representation>>> {
416
        // TODO: move representation stuff to declaration / variable to avoid cloning? (we have to
417
        // move inside of an rc here, so cannot return borrows)
418
        //
419
        // Also would prevent constant "does exist" "is var" checks.
420
        //
421
        // The reason it is not there now is because I'm getting serde issues...
422
        //
423
        // Also might run into issues putting get_or_add into declaration/variable, as that
424
        // requires us to mutably borrow both the symbol table, and the variable inside the symbol
425
        // table..
426

            
427
5980
        let decl = self.lookup(name)?;
428
5980
        let var = &decl.as_var()?;
429

            
430
5980
        var.representations
431
5980
            .iter()
432
5980
            .find(|x| &x.iter().map(|r| r.repr_name()).collect_vec()[..] == representation)
433
5980
            .cloned()
434
5980
    }
435

            
436
    /// Gets all initialised representations for `name`.
437
    ///
438
    /// # Returns
439
    ///
440
    /// + `None` if `name` does not exist, or is not a decision variable.
441
47860
    pub fn representations_for(&self, name: &Name) -> Option<Vec<Vec<Box<dyn Representation>>>> {
442
47860
        let decl = self.lookup(name)?;
443
47860
        decl.as_var().map(|x| x.representations.clone())
444
47860
    }
445

            
446
    /// Gets the representation `representation` for `name`, creating it if it does not exist.
447
    ///
448
    /// If the representation does not exist, this method initialises the representation in this
449
    /// symbol table, adding the representation to `name`, and the declarations for the represented
450
    /// variables to the symbol table.
451
    ///
452
    /// # Usage
453
    ///
454
    /// Representations for variable references should be selected and created by the
455
    /// `select_representation` rule. Therefore, this method should not be used in other rules.
456
    /// Consider using [`get_representation`](`SymbolTable::get_representation`) instead.
457
    ///
458
    /// # Returns
459
    ///
460
    /// + `None` if `name` does not exist, is not a decision variable, or cannot be given that
461
    ///   representation.
462
10780
    pub fn get_or_add_representation(
463
10780
        &mut self,
464
10780
        name: &Name,
465
10780
        representation: &[&str],
466
10780
    ) -> Option<Vec<Box<dyn Representation>>> {
467
        // Lookup the declaration reference
468
10780
        let mut decl = self.lookup(name)?;
469

            
470
8960
        if let Some(var) = decl.as_var()
471
8960
            && let Some(existing_reprs) = var
472
8960
                .representations
473
8960
                .iter()
474
8960
                .find(|x| &x.iter().map(|r| r.repr_name()).collect_vec()[..] == representation)
475
8960
                .cloned()
476
        {
477
8020
            return Some(existing_reprs); // Found: return early
478
940
        }
479
        // Representation not found
480

            
481
        // TODO: nested representations logic...
482
940
        if representation.len() != 1 {
483
            bug!("nested representations not implemented")
484
940
        }
485
940
        let repr_name_str = representation[0];
486
940
        let repr_init_fn = get_repr_rule(repr_name_str)?;
487

            
488
940
        let reprs = vec![repr_init_fn(name, self)?];
489

            
490
        // Get mutable access to the variable part
491
940
        let mut var = decl.as_var_mut()?;
492

            
493
940
        for repr_instance in &reprs {
494
940
            repr_instance
495
940
                .declaration_down()
496
940
                .ok()?
497
940
                .into_iter()
498
3800
                .for_each(|x| self.update_insert(x));
499
        }
500

            
501
940
        var.representations.push(reprs.clone());
502

            
503
940
        Some(reprs)
504
10780
    }
505
}
506

            
507
impl IntoIterator for SymbolTable {
508
    type Item = (Name, DeclarationPtr);
509

            
510
    type IntoIter = SymbolTableIter;
511

            
512
    /// Iterates over symbol table entries in scope.
513
5590
    fn into_iter(self) -> Self::IntoIter {
514
5590
        SymbolTableIter {
515
5590
            inner: self.table.into_iter(),
516
5590
            parent: self.parent,
517
5590
        }
518
5590
    }
519
}
520

            
521
/// Iterator over all symbol table entries in scope.
522
pub struct SymbolTableIter {
523
    // iterator over the current scopes' btreemap
524
    inner: std::collections::btree_map::IntoIter<Name, DeclarationPtr>,
525

            
526
    // the parent scope
527
    parent: Option<SymbolTablePtr>,
528
}
529

            
530
impl Iterator for SymbolTableIter {
531
    type Item = (Name, DeclarationPtr);
532

            
533
24900
    fn next(&mut self) -> Option<Self::Item> {
534
24900
        let mut val = self.inner.next();
535

            
536
        // Go up the tree until we find a parent symbol table with declarations to iterate over.
537
        //
538
        // Note that the parent symbol table may be empty - this is why this is a loop!
539
24900
        while val.is_none() {
540
5590
            let parent = self.parent.clone()?;
541

            
542
            let guard = parent.read();
543
            self.inner = guard.table.clone().into_iter();
544
            self.parent.clone_from(&guard.parent);
545

            
546
            val = self.inner.next();
547
        }
548

            
549
19310
        val
550
24900
    }
551
}
552

            
553
impl Default for SymbolTable {
554
    fn default() -> Self {
555
        Self::new_inner(None)
556
    }
557
}
558

            
559
// TODO: if we could override `Uniplate` impl but still derive `Biplate` instances,
560
//       we could remove some of this manual code
561
impl Uniplate for SymbolTable {
562
    fn uniplate(&self) -> (Tree<Self>, Box<dyn Fn(Tree<Self>) -> Self>) {
563
        // do not recurse up parents, that would be weird?
564
        let self2 = self.clone();
565
        (Tree::Zero, Box::new(move |_| self2.clone()))
566
    }
567
}
568

            
569
impl Biplate<SymbolTablePtr> for SymbolTable {
570
    fn biplate(
571
        &self,
572
    ) -> (
573
        Tree<SymbolTablePtr>,
574
        Box<dyn Fn(Tree<SymbolTablePtr>) -> Self>,
575
    ) {
576
        let self2 = self.clone();
577
        (Tree::Zero, Box::new(move |_| self2.clone()))
578
    }
579
}
580

            
581
impl Biplate<Expression> for SymbolTable {
582
180584
    fn biplate(&self) -> (Tree<Expression>, Box<dyn Fn(Tree<Expression>) -> Self>) {
583
180584
        let (child_trees, ctxs): (VecDeque<_>, Vec<_>) = self
584
180584
            .table
585
180584
            .values()
586
180584
            .map(Biplate::<Expression>::biplate)
587
180584
            .unzip();
588

            
589
180584
        let tree = Tree::Many(child_trees);
590

            
591
180584
        let self2 = self.clone();
592
180584
        let ctx = Box::new(move |tree| {
593
2020
            let Tree::Many(exprs) = tree else {
594
                panic!("unexpected children structure");
595
            };
596

            
597
2020
            let mut self3 = self2.clone();
598
2020
            let self3_iter = self3.table.iter_mut();
599
2900
            for (ctx, tree, (_, decl)) in izip!(&ctxs, exprs, self3_iter) {
600
                // update declaration inside the pointer instead of creating a new one, so all
601
                // things referencing this keep referencing this.
602
2900
                *decl = ctx(tree)
603
            }
604

            
605
2020
            self3
606
2020
        });
607

            
608
180584
        (tree, ctx)
609
180584
    }
610
}
611

            
612
impl Biplate<Comprehension> for SymbolTable {
613
69840
    fn biplate(
614
69840
        &self,
615
69840
    ) -> (
616
69840
        Tree<Comprehension>,
617
69840
        Box<dyn Fn(Tree<Comprehension>) -> Self>,
618
69840
    ) {
619
69840
        let (expr_tree, expr_ctx) = <SymbolTable as Biplate<Expression>>::biplate(self);
620

            
621
69840
        let (exprs, recons_expr_tree) = expr_tree.list();
622

            
623
69840
        let (comprehension_tree, comprehension_ctx) =
624
69840
            <VecDeque<Expression> as Biplate<Comprehension>>::biplate(&exprs);
625

            
626
69840
        let ctx = Box::new(move |x| {
627
            // 1. turn comprehension tree into a list of expressions
628
            let exprs = comprehension_ctx(x);
629

            
630
            // 2. turn list of expressions into an expression tree
631
            let expr_tree = recons_expr_tree(exprs);
632

            
633
            // 3. turn expression tree into a symbol table
634
            expr_ctx(expr_tree)
635
        });
636

            
637
69840
        (comprehension_tree, ctx)
638
69840
    }
639
}
640

            
641
impl Biplate<SubModel> for SymbolTable {
642
    // walk into expressions
643
55022
    fn biplate(&self) -> (Tree<SubModel>, Box<dyn Fn(Tree<SubModel>) -> Self>) {
644
55022
        let (expr_tree, expr_ctx) = <SymbolTable as Biplate<Expression>>::biplate(self);
645

            
646
55022
        let (exprs, recons_expr_tree) = expr_tree.list();
647

            
648
55022
        let (submodel_tree, submodel_ctx) =
649
55022
            <VecDeque<Expression> as Biplate<SubModel>>::biplate(&exprs);
650

            
651
55022
        let ctx = Box::new(move |x| {
652
            // 1. turn submodel tree into a list of expressions
653
1740
            let exprs = submodel_ctx(x);
654

            
655
            // 2. turn list of expressions into an expression tree
656
1740
            let expr_tree = recons_expr_tree(exprs);
657

            
658
            // 3. turn expression tree into a symbol table
659
1740
            expr_ctx(expr_tree)
660
1740
        });
661
55022
        (submodel_tree, ctx)
662
55022
    }
663
}