eggplant 0.2.4

eggplant is a High-Level Rust API crate for Egglog
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
use crate::wrap::constraint::IntoConstraintFact;
use crate::wrap::{
    EValue, EgglogFunc, EgglogFuncInputs, EgglogFuncOutput, EgglogTy, FactsBuilder, FromBase,
    RuleCtx, SortName, SymLit, VarName, tx_rx_vt::TxRxVT,
};
use crate::wrap::{RuleCtxHook, RuleRunnerSgl};
use dashmap::DashMap;
use derive_more::{Debug, Deref, DerefMut, IntoIterator};
use egglog::ast::{RustSpan, Span};
use egglog::prelude::span;
use egglog::{
    ArcSort, BaseValue, ContainerValue, EGraph,
    ast::{Command, GenericAction, GenericExpr},
};
use egglog::{TermDag, TermId, ast::Literal};
use smallvec::SmallVec;
use std::{
    any::Any,
    borrow::Borrow,
    collections::HashMap,
    fmt,
    hash::Hash,
    marker::PhantomData,
    panic::Location,
    path::Path,
    sync::{Arc, atomic::AtomicU32},
};
use strum::IntoDiscriminant;
use strum_macros::{EnumDiscriminants, EnumIs};
use symbol_table::GlobalSymbol;
pub type EgglogAction = GenericAction<String, String>;
pub type TermToNode = fn(TermId, &TermDag, &mut HashMap<TermId, Sym>) -> Box<dyn EgglogNode>;

#[derive(Debug)]
pub enum TxCommand {
    StringCommand { command: String },
    NativeCommand { command: Command },
}

/// This trait is useful when defining pattern.
/// We assume every node is a placeholder if it doesn't drop after call the defining function.
pub trait NodeDropper: NodeOwner + 'static {
    fn on_drop(&self, _dropped: &mut (impl EgglogNode + 'static)) {
        // do nothing as default
    }
}
pub trait Tx: 'static + NodeOwner + NodeDropper {
    /// receive is guaranteed to not be called in proc macro
    #[track_caller]
    fn send(&self, sended: TxCommand);
    #[track_caller]
    fn on_new(&self, node: &(impl EgglogNode + 'static));
    #[track_caller]
    fn on_func_set<'a, F: EgglogFunc>(
        &self,
        input: <F::Input as EgglogFuncInputs>::Ref<'a>,
        output: <F::Output as EgglogFuncOutput>::Ref<'a>,
    );
    #[track_caller]
    fn on_union(&self, node1: &(impl EgglogNode + 'static), node2: &(impl EgglogNode + 'static));
}
pub trait Rx: 'static {
    #[track_caller]
    fn on_func_get<'a, F: EgglogFunc>(
        &self,
        input: <F::Input as EgglogFuncInputs>::Ref<'a>,
    ) -> F::Output;
    #[track_caller]
    fn on_funcs_get<'a, 'b, F: EgglogFunc>(
        &self,
        max_size: Option<usize>,
    ) -> Vec<(
        <F::Input as EgglogFuncInputs>::Ref<'b>,
        <F::Output as EgglogFuncOutput>::Ref<'b>,
    )>;
    #[track_caller]
    fn on_pull<T: EgglogTy>(&self, node: &(impl EgglogNode + 'static)) {
        self.on_pull_sym::<T>(node.cur_sym());
    }

    #[track_caller]
    fn on_pull_sym<T: EgglogTy>(&self, sym: Sym) -> SymLit;
    #[track_caller]
    fn on_pull_value<T: EgglogTy>(&self, value: Value<T>) -> SymLit;
}

pub trait SingletonGetter: 'static {
    type RetTy;
    #[track_caller]
    fn sgl() -> &'static Self::RetTy;
}
pub trait NodeOwnerSgl: SingletonGetter + 'static {
    /// helpful when you want to append additional data to node specific to your NodeOwner
    type OwnerSpecDataInNode<T: EgglogTy, V: EgglogEnumVariantTy>: Default + Copy + Send + Sync;
}
pub trait NodeOwner: 'static {
    /// helpful when you want to append additional data to node specific to your singleton
    type OwnerSpecDataInNode<T: EgglogTy, V: EgglogEnumVariantTy>: Default + Copy + Send + Sync;
}
impl<S: SingletonGetter> NodeOwnerSgl for S
where
    S::RetTy: NodeOwner,
{
    type OwnerSpecDataInNode<T: EgglogTy, V: EgglogEnumVariantTy> =
        <Self::RetTy as NodeOwner>::OwnerSpecDataInNode<T, V>;
}
pub trait NodeDropperSgl: 'static + Sized + SingletonGetter + NodeOwnerSgl {
    fn on_drop(dropped: &mut (impl EgglogNode + 'static));
}

pub trait TxSgl: 'static + Sized + NodeDropperSgl + NodeOwnerSgl {
    // delegate all functions from Tx
    fn receive(received: TxCommand);
    #[track_caller]
    fn on_new(node: &(impl EgglogNode + 'static));
    #[track_caller]
    fn on_func_set<'a, F: EgglogFunc>(
        input: <F::Input as EgglogFuncInputs>::Ref<'a>,
        output: <F::Output as EgglogFuncOutput>::Ref<'a>,
    );
    fn on_union(node1: &(impl EgglogNode + 'static), node2: &(impl EgglogNode + 'static));
}
pub trait RxSgl: 'static + Sized + SingletonGetter + NodeDropperSgl + NodeOwnerSgl {
    // delegate all functions from Rx
    #[track_caller]
    fn on_func_get<'a, 'b, F: EgglogFunc>(
        input: <F::Input as EgglogFuncInputs>::Ref<'a>,
    ) -> F::Output;
    #[track_caller]
    fn on_funcs_get<'a, 'b, F: EgglogFunc>(
        max_size: Option<usize>,
    ) -> Vec<(
        <F::Input as EgglogFuncInputs>::Ref<'b>,
        <F::Output as EgglogFuncOutput>::Ref<'b>,
    )>;
    #[track_caller]
    fn on_pull<T: EgglogTy>(node: &(impl EgglogNode + 'static));
}

impl<S: SingletonGetter> NodeDropperSgl for S
where
    S::RetTy: NodeDropper + 'static,
{
    fn on_drop(_dropped: &mut (impl EgglogNode + 'static)) {
        // do nothing as default
        // Self::sgl().on_drop(dropped);
    }
}

impl<S: SingletonGetter + 'static> TxSgl for S
where
    S::RetTy: Tx + NodeDropper + NodeSetter + 'static,
{
    fn receive(received: TxCommand) {
        Self::sgl().send(received);
    }
    fn on_new(node: &(impl EgglogNode + 'static)) {
        Self::sgl().on_new(node);
    }

    fn on_func_set<'a, F: EgglogFunc>(
        input: <F::Input as EgglogFuncInputs>::Ref<'a>,
        output: <F::Output as EgglogFuncOutput>::Ref<'a>,
    ) {
        Self::sgl().on_func_set::<F>(input, output);
    }

    fn on_union(node1: &(impl EgglogNode + 'static), node2: &(impl EgglogNode + 'static)) {
        Self::sgl().on_union(node1, node2);
    }
}
pub trait NodeSetterSgl {
    #[track_caller]
    fn on_set(node: &mut (impl EgglogNode + 'static));
}
impl<S: NodeOwnerSgl> NodeSetterSgl for S
where
    S::RetTy: NodeSetter,
{
    fn on_set(node: &mut (impl EgglogNode + 'static)) {
        Self::sgl().on_set(node);
    }
}
pub trait NodeSetter {
    #[track_caller]
    fn on_set(&self, node: &mut (impl EgglogNode + 'static));
}
impl<S: SingletonGetter + 'static> RxSgl for S
where
    S::RetTy: Rx + NodeDropper + 'static,
{
    fn on_func_get<'a, 'b, F: EgglogFunc>(
        input: <F::Input as EgglogFuncInputs>::Ref<'a>,
    ) -> F::Output {
        Self::sgl().on_func_get::<F>(input)
    }

    fn on_funcs_get<'a, 'b, F: EgglogFunc>(
        max_size: Option<usize>,
    ) -> Vec<(
        <F::Input as EgglogFuncInputs>::Ref<'b>,
        <F::Output as EgglogFuncOutput>::Ref<'b>,
    )> {
        Self::sgl().on_funcs_get::<F>(max_size)
    }
    fn on_pull<T: EgglogTy>(node: &(impl EgglogNode + 'static)) {
        Self::sgl().on_pull::<T>(node)
    }
}

/// version control triat
/// which should be implemented by Tx
pub trait VersionCtl {
    fn locate_latest(&self, node: Sym) -> Sym;
    fn locate_next(&self, node: Sym) -> Sym;
    fn locate_prev(&self, node: Sym) -> Sym;
    fn set_latest(&self, node: &mut Sym);
    fn set_next(&self, node: &mut Sym);
    fn set_prev(&self, node: &mut Sym);
}

/// pattern recorder triat
/// it's neccessary to impl NodeDropper for PatternCombine feature
/// and also should be implemented by Tx
pub trait PatRec: NodeDropper + Tx {
    #[track_caller]
    fn on_new_query_leaf(&self, node: &(impl EgglogNode + 'static));
    #[track_caller]
    fn on_new_constraint(&self, constraint: impl IntoConstraintFact);
    fn on_record_start(&self);
    fn on_record_end<T: PatRecSgl>(&self, pat_vars: &impl PatVars<T>) -> PatId;
    fn pat2fact_builder(&self, pat_id: PatId) -> FactsBuilder;
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct PatId(pub u32);

pub trait PatRecSgl: NodeDropperSgl + TxSgl {
    #[track_caller]
    fn on_new_query_leaf(node: &(impl EgglogNode + 'static));
    #[track_caller]
    fn on_new_constraint(constraint: impl IntoConstraintFact);
    fn on_record_start();
    fn on_record_end(pat_vars: &impl PatVars<Self>) -> PatId;
    fn pat2fact_builder(pat_id: PatId) -> FactsBuilder;
}
impl<T: SingletonGetter> PatRecSgl for T
where
    T::RetTy: PatRec + NodeSetter,
{
    fn on_new_query_leaf(node: &(impl EgglogNode + 'static)) {
        Self::sgl().on_new_query_leaf(node);
    }
    fn on_new_constraint(constraint: impl IntoConstraintFact) {
        Self::sgl().on_new_constraint(constraint);
    }
    fn on_record_start() {
        Self::sgl().on_record_start();
    }

    fn on_record_end(pat_vars: &impl PatVars<Self>) -> PatId {
        Self::sgl().on_record_end(pat_vars)
    }

    fn pat2fact_builder(pat_id: PatId) -> FactsBuilder {
        Self::sgl().pat2fact_builder(pat_id)
    }
}

pub trait WithPatRecSgl {
    type PatRecSgl: PatRecSgl;
}

// pub trait WithPatternRecorderSgl

/// version control triat
/// which should be implemented by Tx
pub trait VersionCtlSgl {
    fn locate_latest(node: Sym) -> Sym;
    fn locate_next(node: Sym) -> Sym;
    fn locate_prev(node: Sym) -> Sym;
    fn set_latest(node: &mut Sym);
    fn set_next(node: &mut Sym);
    fn set_prev(node: &mut Sym);
}

impl<S: SingletonGetter> VersionCtlSgl for S
where
    S::RetTy: Tx + VersionCtl + 'static,
{
    fn locate_latest(node: Sym) -> Sym {
        Self::sgl().locate_latest(node)
    }
    fn locate_next(node: Sym) -> Sym {
        Self::sgl().locate_next(node)
    }
    fn locate_prev(node: Sym) -> Sym {
        Self::sgl().locate_prev(node)
    }
    fn set_latest(node: &mut Sym) {
        Self::sgl().set_latest(node)
    }
    fn set_next(node: &mut Sym) {
        Self::sgl().set_next(node)
    }
    fn set_prev(node: &mut Sym) {
        Self::sgl().set_prev(node)
    }
}

/// this trait should not be implemented for Node because they have many variants which is recognized as different types by compiler
pub trait UpdateCounter<T: EgglogTy> {
    fn inc_counter(&mut self, counter: &mut TyCounter<T>) -> Sym<T>;
}

impl<T> Sym<T> {
    pub fn erase(&self) -> Sym<()> {
        // safety note: type erasure
        unsafe { *&*(self as *const Sym<T> as *const Sym) }
    }
    pub fn erase_ref(&self) -> &Sym<()> {
        // safety note: type erasure
        unsafe { &*(self as *const Sym<T> as *const Sym) }
    }
    pub fn erase_mut(&mut self) -> &mut Sym<()> {
        // safety note: type erasure
        unsafe { &mut *(self as *mut Sym<T> as *mut Sym) }
    }
}
impl Sym {
    pub fn typed<T: EgglogTy>(self) -> Sym<T> {
        unsafe { *(&self as *const Sym as *const Sym<T>) }
    }
}

/// trait of basic functions to interact with egglog
pub trait ToEgglog {
    fn to_egglog_string(&self) -> Option<String>;
    fn to_egglog(&self) -> EgglogAction;
    fn native_egglog(
        &self,
        ctx: &RuleCtx,
        sym_to_value_map: &DashMap<Sym, egglog::Value>,
    ) -> egglog::Value;
}

/// version control triat
/// which should be implemented by Node
pub trait LocateVersion {
    fn locate_latest(&mut self);
    fn locate_next(&mut self);
    fn locate_prev(&mut self);
}
/// trait of node behavior
pub trait EgglogNode: ToEgglog + Any + EValue + Send + Sync {
    fn succs_mut(&mut self) -> Vec<&mut Sym>;
    fn succs(&self) -> Vec<Sym>;
    /// set new sym and return the new sym
    fn roll_sym(&mut self) -> Sym;
    // return current sym
    fn cur_sym(&self) -> Sym;
    fn cur_sym_mut(&mut self) -> &mut Sym;

    fn clone_dyn(&self) -> Box<dyn EgglogNode>;

    fn ty_name(&self) -> &'static str;
    fn variant_name(&self) -> Option<&'static str>;
    fn ty_name_lower(&self) -> &'static str;
    fn basic_field_names(&self) -> &[&'static str];
    fn basic_field_types(&self) -> &[&'static str];
    fn complex_field_names(&self) -> &[&'static str];
    fn complex_field_types(&self) -> &[&'static str];

    #[track_caller]
    fn to_term(
        &self,
        term_dag: &mut TermDag,
        sym2term: &mut HashMap<Sym, TermId>,
        sym2ph_name: &HashMap<Sym, &'static str>,
    ) -> TermId;

    #[track_caller]
    fn add_table_fact(&self, query_builder: &mut FactsBuilder);
}
pub trait VarsCollector {
    /// 1. if self is a typed placeholder [`TyPH::VarPH`], collect itself and its basic vars
    /// 2. if self is a typed placeholder [`TyPH::PH`], only collect itself
    /// 3. if self is a [`PatVars`] collect recursively
    fn collect_vars(&self, vars: &mut Vec<(VarName, SortName)>);
}

pub trait EgglogEnumVariantTy: Clone + 'static + Send + Sync {
    const TY_NAME: &'static str;
    /// T represent the type call that call this type
    /// This is useful when we want to specify default for a type
    type ValuedWithDefault<T>: FromPlainValues;
    /// fields names of valued variant struct
    const BASIC_FIELD_NAMES: &[&'static str];
    const COMPLEX_FIELD_NAMES: &[&'static str];
    const BASIC_FIELD_TYPES: &[&'static str];
    const COMPLEX_FIELD_TYPES: &[&'static str];
}
/// instance of specified [`EgglogTy`] & its VariantTy
#[derive(Debug, Clone)]
pub struct Node<T, R, I, S>
where
    T: EgglogTy,
    R: NodeOwnerSgl,
    I: NodeInner,
    I::Discriminant: Clone + fmt::Debug,
    S: EgglogEnumVariantTy,
{
    // PH => PlaceHolder, Ty => normal node
    pub ty: TyPH<I>,
    pub sgl_specific: R::OwnerSpecDataInNode<T, S>,
    pub span: Option<&'static Location<'static>>,
    pub sym: Sym<T>,
    /// Rule closure requires send and sync. Make them happy.
    pub _p: PhantomData<SendSyncWrap<R>>,
    pub _s: PhantomData<SendSyncWrap<S>>,
}
pub struct SendSyncWrap<T> {
    _p: PhantomData<T>,
}
unsafe impl<T> Send for SendSyncWrap<T> {}
unsafe impl<T> Sync for SendSyncWrap<T> {}

/// allow type erasure on S
impl<T, R, I, S> AsRef<Node<T, R, I, ()>> for Node<T, R, I, S>
where
    T: EgglogTy,
    R: NodeOwnerSgl,
    I: NodeInner,
    I::Discriminant: Clone + fmt::Debug,
    S: EgglogEnumVariantTy,
{
    fn as_ref(&self) -> &Node<T, R, I, ()> {
        // Safety notes:
        // 1. Node's memory layout is unaffected by PhantomData
        // 2. We're only changing the S type parameter from a concrete type to unit type (),
        //    which doesn't affect the actual data
        unsafe { &*(self as *const Node<T, R, I, S> as *const Node<T, R, I, ()>) }
    }
}

#[derive(PartialEq, Eq, Hash, Debug)]
pub struct Sym<T = ()> {
    pub inner: GlobalSymbol,
    pub p: PhantomData<T>,
}

impl<T> Sym<T> {
    pub fn new(global_sym: GlobalSymbol) -> Self {
        Self {
            inner: global_sym,
            p: PhantomData,
        }
    }
    pub fn as_str(&self) -> &'static str {
        self.inner.as_str()
    }
    pub fn to_string(&self) -> String {
        self.inner.as_str().to_string()
    }
}
impl<T> Copy for Sym<T> {}
impl<T> Clone for Sym<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            p: PhantomData,
        }
    }
}

/// trait of egglog node inner
pub trait NodeInner: IntoDiscriminant {
    fn succs_mut(&mut self) -> Vec<&mut Sym>;
    fn succs(&self) -> Vec<Sym>;
}
impl<T> std::fmt::Display for Sym<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.inner.as_str())
    }
}
impl<T> From<Sym<T>> for &str {
    fn from(value: Sym<T>) -> Self {
        value.inner.as_str()
    }
}
impl<T: EgglogTy> From<Syms<T>> for Syms {
    fn from(value: Syms<T>) -> Self {
        value.into_iter().map(|s| s.erase()).collect()
    }
}
/// count the number of nodes of specific EgglogTy for specific binding Tx
pub struct TyCounter<T: EgglogTy> {
    counter: AtomicU32,
    t: PhantomData<T>,
}
impl<T: EgglogTy> TyCounter<T> {
    pub const fn new() -> Self {
        TyCounter {
            counter: AtomicU32::new(0),
            t: PhantomData,
        }
    }
    // get next symbol of specified type T
    pub fn next_sym(&self) -> Sym<T> {
        Sym {
            inner: format!("{}{}", T::TY_NAME_LOWER, self.inc()).into(),
            p: PhantomData::<T>,
        }
    }
    pub fn get_counter(&self) -> u32 {
        self.counter.load(std::sync::atomic::Ordering::Acquire)
    }
    /// counter increment atomically
    pub fn inc(&self) -> u32 {
        self.counter
            .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
    }
}

impl EgglogEnumVariantTy for () {
    const TY_NAME: &'static str = "Unknown";
    type ValuedWithDefault<T> = Value<T>;
    const BASIC_FIELD_NAMES: &[&'static str] = &[];
    const BASIC_FIELD_TYPES: &[&'static str] = &[];
    const COMPLEX_FIELD_NAMES: &[&'static str] = &[];
    const COMPLEX_FIELD_TYPES: &[&'static str] = &[];
}

#[derive(DerefMut, Deref)]
pub struct WorkAreaNode {
    pub next: Option<Sym>,
    pub prev: Option<Sym>,
    pub preds: Syms,
    #[deref]
    #[deref_mut]
    pub egglog: Box<dyn EgglogNode>,
    pub pulled_by: Option<egglog::Value>,
}

impl Clone for WorkAreaNode {
    fn clone(&self) -> Self {
        Self {
            next: self.next.clone(),
            preds: self.preds.clone(),
            egglog: self.egglog.clone_dyn(),
            prev: None,
            pulled_by: self.pulled_by,
        }
    }
}
impl fmt::Debug for WorkAreaNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {} | {} | pulled_by {:?}",
            self.variant_name().unwrap_or(self.ty_name()),
            self.cur_sym(),
            self.to_egglog_string().unwrap_or(
                self.egglog
                    .basic_field_types()
                    .iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<_>>()
                    .join(" ")
            ),
            self.pulled_by
        )
    }
}
impl WorkAreaNode {
    pub fn new(node: Box<dyn EgglogNode>) -> Self {
        Self {
            preds: Syms::default(),
            egglog: node,
            next: None,
            prev: None,
            pulled_by: None,
        }
    }
    pub fn new_pulled(node: Box<dyn EgglogNode>, pulled_by: egglog::Value) -> Self {
        Self {
            preds: Syms::default(),
            egglog: node,
            next: None,
            prev: None,
            pulled_by: Some(pulled_by),
        }
    }
    pub fn succs_mut(&mut self) -> impl Iterator<Item = &mut Sym> {
        self.egglog.succs_mut().into_iter()
    }
    pub fn preds_mut(&mut self) -> impl Iterator<Item = &mut Sym> {
        self.preds.iter_mut()
    }
    pub fn preds(&self) -> impl Iterator<Item = &Sym> {
        self.preds.iter()
    }
}

impl Borrow<GlobalSymbol> for Sym {
    fn borrow(&self) -> &GlobalSymbol {
        &self.inner
    }
}

#[derive(Clone, Deref, DerefMut, IntoIterator, Debug, Default)]
pub struct Syms<T = ()> {
    #[into_iterator(owned, ref, ref_mut)]
    inner: SmallVec<[Sym<T>; 4]>,
}

impl From<SmallVec<[Sym; 4]>> for Syms {
    fn from(value: SmallVec<[Sym; 4]>) -> Self {
        Syms { inner: value }
    }
}

impl<S> FromIterator<Sym<S>> for Syms<S> {
    fn from_iter<T: IntoIterator<Item = Sym<S>>>(iter: T) -> Self {
        Syms {
            inner: iter.into_iter().collect(),
        }
    }
}
impl<T> Syms<T> {
    pub fn new() -> Self {
        Syms {
            inner: SmallVec::new(),
        }
    }
}
impl From<Vec<Sym>> for Syms {
    fn from(value: Vec<Sym>) -> Self {
        value.into_iter().collect()
    }
}

/// global commit
/// This trait should be implemented for Tx singleton
/// usage:
/// ```text
/// let last_version_node = node.clone();
/// Tx::commit(&self, node);
/// ```
pub trait TxCommit {
    #[track_caller]
    fn on_stage<T: EgglogNode + ?Sized>(&self, node: &T);
    fn on_commit_op_hook<T: EgglogNode>(&self, node: &T, _: Option<Box<dyn RuleCtxHook>>);
}

pub trait TxCommitSgl {
    #[track_caller]
    fn on_commit<T: EgglogNode>(node: &T);
    #[track_caller]
    fn on_commit_with_hook<T: EgglogNode>(node: &T, hook: Box<dyn RuleCtxHook>);
    #[track_caller]
    fn on_stage<T: EgglogNode>(node: &T);
}

impl<Ret, S> TxCommitSgl for S
where
    Ret: Tx + VersionCtl + TxCommit,
    S: SingletonGetter<RetTy = Ret>,
{
    fn on_commit_with_hook<T: EgglogNode>(node: &T, hook: Box<dyn RuleCtxHook>) {
        S::sgl().on_commit_op_hook(node, Some(hook));
    }
    fn on_stage<T: EgglogNode>(node: &T) {
        S::sgl().on_stage(node);
    }

    fn on_commit<T: EgglogNode>(node: &T) {
        S::sgl().on_commit_op_hook(node, None);
    }
}

/// single node commit
/// This trait should be implemented for Node
/// usage:
/// ```text
/// let last_version_node = node.clone();
/// node.set_a()
///     .set_b()
///     .commit();
/// ```
pub trait Commit {
    #[track_caller]
    fn commit(&self);
    #[track_caller]
    fn commit_with_hook(&self, hook: Box<dyn RuleCtxHook>);
    #[track_caller]
    fn stage(&self);
}

/// In Egglog there are 2 ways to interact with egraph
/// 1. String of egglog code
/// 2. Vector of Egglog Command Struct
/// Use this Interpreter trait to concile them
///
/// Also there are
pub trait Interpreter {
    type Interpreted;
    fn interpret(interpreted: Self::Interpreted);
}

// pub trait EgglogNodeMarker{ }

impl<T: EgglogNode> From<T> for WorkAreaNode {
    fn from(value: T) -> Self {
        WorkAreaNode::new(value.clone_dyn())
    }
}

pub trait ToVar {
    fn to_var(&self) -> GenericExpr<&'static str, &'static str>;
}

impl<T> ToVar for Sym<T> {
    fn to_var(&self) -> GenericExpr<&'static str, &'static str> {
        GenericExpr::Var(span!(), self.inner.into())
    }
}
impl<T> ToVar for T
where
    Literal: FromBase<T>,
    T: Clone,
{
    fn to_var(&self) -> GenericExpr<&'static str, &'static str> {
        GenericExpr::Lit(span!(), Literal::from_base(&self))
    }
}

pub trait ToOwnedStr {
    fn to_owned_str(&self) -> GenericExpr<String, String>;
}

impl ToOwnedStr for GenericExpr<&'static str, &'static str> {
    fn to_owned_str(&self) -> GenericExpr<String, String> {
        match self {
            GenericExpr::Lit(span, literal) => GenericExpr::Lit(span.clone(), literal.clone()),
            GenericExpr::Var(span, v) => GenericExpr::Var(span.clone(), v.to_string()),
            GenericExpr::Call(span, h, generic_exprs) => GenericExpr::Call(
                span.clone(),
                h.to_string(),
                generic_exprs.iter().map(|x| x.to_owned_str()).collect(),
            ),
        }
    }
}

pub trait ToSpan {
    fn to_span(&self) -> Span;
}

impl ToSpan for &'static Location<'static> {
    fn to_span(&self) -> Span {
        Span::Rust(Arc::new(RustSpan {
            file: self.file(),
            line: self.line(),
            column: self.column(),
        }))
    }
}

impl ToSpan for Option<&'static Location<'static>> {
    fn to_span(&self) -> Span {
        match self {
            Some(value) => value.to_span(),
            None => Span::Panic,
        }
    }
}

pub trait FromTerm {
    fn term_to_node(
        term: TermId,
        dag: &TermDag,
        term2sym: &mut HashMap<TermId, Sym>,
    ) -> Box<dyn EgglogNode>;
}

/// used for type erased marker
impl SingletonGetter for () {
    type RetTy = TxRxVT;
    fn sgl() -> &'static Self::RetTy {
        panic!("illegal singleton getter, you can't get singleton of ()");
    }
}

pub enum TopoDirection {
    Up,
    Down,
}

impl std::fmt::Debug for Box<dyn EgglogNode> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{},{}",
            self.cur_sym(),
            self.to_egglog_string().unwrap_or(String::new())
        )
    }
}

// place holder for EgglogNode
#[derive(Deref, DerefMut)]
pub struct PH<N> {
    pub node: N,
}

impl<N: EgglogNode> PH<N> {
    pub fn new(node: N) -> PH<N> {
        Self { node }
    }
}
impl<T> Default for Sym<T> {
    fn default() -> Self {
        Self {
            inner: "".into(),
            p: Default::default(),
        }
    }
}

pub trait SymOrValueConstructor {
    type Constructor<T>;
}

impl SymOrValueConstructor for Sym {
    type Constructor<T> = Sym<T>;
}
// impl<T:EgglogTy> SymOrValueConstructor for Value<T> {
//     type Constructor<Ty:EgglogTy> = Value<Ty>;
// }

/// a wrapper for EgglogBackend Value with type info
/// It's useful for Node Type because in rust_rule's action part you should specify
/// value for Node rather than Sym
pub struct Value<T> {
    pub val: egglog::Value,
    p: PhantomData<T>,
}
impl<T> Value<T> {
    pub fn new(val: egglog::Value) -> Value<T> {
        Value {
            val,
            p: PhantomData,
        }
    }
    pub fn new_from_iter(val: &mut impl Iterator<Item = egglog::Value>) -> Value<T> {
        Value {
            val: val.next().unwrap(),
            p: PhantomData,
        }
    }
    pub fn erase(&self) -> egglog::Value {
        self.val
    }
}
impl<T: EgglogTy> fmt::Debug for Value<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{}{:?}",
            T::TY_NAME,
            T::EnumVariantMarker::TY_NAME,
            self.val
        )
    }
}

/// a pattern may extract values in EGraph, for example
/// if you record pattern (fib x) then x will be extracted
/// we use [`PatVars`] trait to mark such patterns
pub trait PatVars<T: PatRecSgl>: ToStrArcSort {
    type Valued: FromPlainValues;
}

/// a pattern should be transformed into [(str,Arcsort)] when registering rules
pub trait ToStrArcSort {
    fn to_str_arcsort(&self, egraph: &EGraph) -> Vec<(VarName, ArcSort)>;
}

pub trait FromPlainValues {
    fn from_plain_values(values: &mut impl Iterator<Item = egglog::Value>) -> Self;
}

/// Insertable and RetypeValue are quite different, Insertable is used in Union or table insert
/// while RetypeValueonly used when you want operational structure
pub trait Insertable<T> {
    fn to_value(&self, ctx: &RuleCtx) -> Value<T>;
}
pub trait RetypeValue {
    type Target;
    fn retype_value(val: egglog::Value) -> Value<Self::Target>;
}

impl<D: RetypeValue> RetypeValue for Value<D> {
    type Target = D::Target;
    fn retype_value(val: egglog::Value) -> Value<Self::Target> {
        Value::new(val)
    }
}
impl<T: BoxedValue> RetypeValue for T {
    type Target = T;
    fn retype_value(val: egglog::Value) -> Value<Self::Target> {
        Value::new(val)
    }
}

impl<T> Clone for Value<T> {
    fn clone(&self) -> Self {
        Self {
            val: self.val.clone(),
            p: PhantomData,
        }
    }
}
impl<T: EgglogTy> Copy for Value<T> {}

/// if one struct BoxUnBox that means it can be converted to a boxed value in database
/// this is an essential condition to be insert into egglog_backend
/// any struct implements this trait inferred to be [`Insertable`]
pub trait BoxedBase: BoxedValue {
    type Boxed: BaseValue;
    fn unbox(boxed: Self::Boxed, ctx: &RuleCtx) -> Self;
    fn box_it(self, ctx: &RuleCtx) -> Self::Boxed;
}
pub trait BoxedContainer: BoxedValue {
    type Boxed: ContainerValue;
    const CONSTRUCTOR_STR: &'static str;
    const TY_STR: &'static str;
    fn unbox(boxed: Self::Boxed, ctx: &RuleCtx) -> Self;
    fn box_it(self, ctx: &RuleCtx) -> Self::Boxed;
}

pub trait SingleFieldVariant {}

impl<T0, B: BoxedBase<Boxed = T0> + EgglogTy + Clone> Insertable<B> for B {
    fn to_value(&self, ctx: &RuleCtx) -> Value<Self> {
        ctx.intern_base(self.clone())
    }
}

pub trait BoxedValue {
    type Output<'a>;
    fn devalue<'b>(rule_ctx: &'b RuleCtx, value: egglog::Value) -> Self::Output<'b>;
}

#[derive(EnumDiscriminants, EnumIs, Debug, Clone)]
pub enum TyPH<T: strum::IntoDiscriminant>
where
    T::Discriminant: Clone + fmt::Debug,
{
    /// not be leaf node in pattern
    Ty(T),
    /// to discriminate whether this leaf node's basic fields should be recorded as action args
    VarPH(T::Discriminant, Vec<Sym>),
    /// this leaf node's basic fields should not be recorded as action args
    PH,
}

impl<T: strum::IntoDiscriminant> TyPH<T>
where
    T::Discriminant: Clone + fmt::Debug,
{
    pub fn unwrap_ref(&self) -> &T {
        if let TyPH::Ty(ty) = self {
            ty
        } else {
            panic!()
        }
    }
    pub fn ty_ref(&self) -> Option<&T> {
        if let TyPH::Ty(ty) = self {
            Some(ty)
        } else {
            None
        }
    }
    pub fn unwrap_mut(&mut self) -> &mut T {
        if let TyPH::Ty(ty) = self {
            ty
        } else {
            panic!()
        }
    }
    pub fn ty_mut(&mut self) -> Option<&mut T> {
        if let TyPH::Ty(ty) = self {
            Some(ty)
        } else {
            None
        }
    }
    pub fn map_ty_ref_or_else<'a, R>(
        &'a self,
        ph_f: impl FnOnce() -> R,
        var_ph_f: impl FnOnce(&'a T::Discriminant, &'a Vec<Sym>) -> R,
        f: impl FnOnce(&'a T) -> R,
    ) -> R {
        match self {
            Self::Ty(ty) => f(ty),
            Self::PH => ph_f(),
            Self::VarPH(dis, succs) => var_ph_f(dis, succs),
        }
    }
    pub fn map_ty_mut_or_else<'a, R>(
        &'a mut self,
        ph_f: impl FnOnce() -> R,
        var_ph_f: impl FnOnce(&'a mut T::Discriminant, &'a mut Vec<Sym>) -> R,
        f: impl FnOnce(&'a mut T) -> R,
    ) -> R {
        match self {
            Self::Ty(ty) => f(ty),
            Self::PH => ph_f(),
            Self::VarPH(dis, succs) => var_ph_f(dis, succs),
        }
    }
}

pub type SerializedPetGraph = petgraph::Graph<String, String>;
pub trait ToDotSgl {
    fn egraph_to_dot(path: impl AsRef<Path>);
    fn wag_to_dot(path: impl AsRef<Path>);
    fn wag_to_petgraph() -> SerializedPetGraph;
    // fn proof_to_dot(path: impl AsRef<Path>);
    fn table_view();
}
pub trait ToDot {
    fn egraph_to_dot(&self, path: impl AsRef<Path>);
    fn wag_to_dot(&self, path: impl AsRef<Path>);
    fn wag_to_petgraph(&self) -> SerializedPetGraph;
    // fn proof_to_dot(&self, path: impl AsRef<Path>);
    fn table_view(&self);
}
impl<S: SingletonGetter> ToDotSgl for S
where
    S::RetTy: ToDot + 'static,
{
    fn egraph_to_dot(path: impl AsRef<Path>) {
        Self::sgl().egraph_to_dot(path);
    }

    fn wag_to_dot(path: impl AsRef<Path>) {
        Self::sgl().wag_to_dot(path);
    }
    fn wag_to_petgraph() -> SerializedPetGraph {
        Self::sgl().wag_to_petgraph()
    }
    // fn proof_to_dot(path: impl AsRef<Path>) {
    //     Self::sgl().proof_to_dot(path);
    // }
    fn table_view() {
        Self::sgl().table_view();
    }
}

/// a marker trait for those not pattern recorder singleton
/// because currently rust doesn't support `!PatRecSgl` clause
pub trait NonPatRecSgl {}
impl NonPatRecSgl for () {}

pub trait G: TxSgl + NonPatRecSgl + RuleRunnerSgl {}
impl<T: TxSgl + NonPatRecSgl + RuleRunnerSgl> G for T {}