geo_aid_script/unroll/
figure.rs

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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
//! Everything related to unrolled figures.

use crate::figure::{CircleItem, LineItem, PointItem, RayItem};
use crate::math::Build;
use crate::{
    figure::SpannedMathString as MathString,
    parser::{FromProperty, Parse, PropertyValue},
    span, Error,
};
use geo_aid_figure::Style;
use std::{collections::HashMap, fmt::Debug, ops::Deref};

use super::{
    AnyExpr, Bundle, Circle, CloneWithNode, CompileContext, Displayed, Dummy, Expr, Line, Point,
    PointCollection, Properties, Scalar, Unknown,
};

/// A node is a trait characterising objects meant to be parts of the figure's display tree.
pub trait Node: Debug {
    /// Set the general display flag that decides whether this node and its children should be displayed.
    fn set_display(&mut self, display: bool);

    /// Get whether this node should be displayed.
    fn get_display(&self) -> bool;

    /// Build this node.
    fn build(self: Box<Self>, build: &mut Build);

    /// Build this node, with an unboxed `self` type.
    fn build_unboxed(self, compiler: &mut Build)
    where
        Self: Sized,
    {
        Box::new(self).build(compiler);
    }
}

/// Helper trait for building nodes out of unrolled expressions.
pub trait FromExpr<T: Displayed>: Node + Sized {
    /// Build a node out of an unrolled expression.
    #[must_use]
    fn from_expr(expr: &Expr<T>, display: Properties, context: &CompileContext) -> Self;
}

/// Helper type for identifying whether a value was explicitly set or it is left default.
#[derive(Debug, Clone, Copy)]
pub struct MaybeUnset<T> {
    /// Inner value.
    value: T,
    /// Whether it was explicitly set.
    set: bool,
}

impl<T> MaybeUnset<T> {
    /// Create a new unset value.
    pub fn new(default: T) -> Self {
        Self {
            value: default,
            set: false,
        }
    }

    /// Create a new value from an `Option`. If it is `Some`, the value is considered set with
    /// the contained value. Otherwise it is considered unset with the default.
    pub fn new_or(default: T, value: Option<T>) -> Self {
        let set = value.is_some();

        Self {
            value: value.unwrap_or(default),
            set,
        }
    }

    /// Check if this value was explicitly set.
    pub fn is_set(&self) -> bool {
        self.set
    }

    /// Set this value. Explicitly.
    pub fn set(&mut self, value: T) {
        self.value = value;
        self.set = true;
    }

    /// Will set the value if `value` is `Some`. If `value` is `None`, the state of the object is unchanged.
    pub fn try_set(&mut self, value: Option<T>) {
        if let Some(value) = value {
            self.value = value;
            self.set = true;
        }
    }

    /// Only sets the value if the `set` flag is false.
    /// Returns whether a new value was set.
    pub fn set_if_unset(&mut self, value: T) -> bool {
        let set = !self.set;

        if set {
            self.set(value);
        }

        set
    }

    /// Only sets the value if the `set` flag is false and `value` is `Some`.
    /// Returns whether a new value was set.
    pub fn try_set_if_unset(&mut self, value: Option<T>) -> bool {
        let set = !self.set && value.is_some();

        if let Some(value) = value {
            if set {
                self.set(value);
            }
        }

        set
    }

    /// Get a reference to the contained value.
    #[must_use]
    pub fn get(&self) -> &T {
        &self.value
    }

    /// Will return a `Some` only if the value has been set.
    pub fn try_get(&self) -> Option<&T> {
        if self.set {
            Some(self.get())
        } else {
            None
        }
    }

    /// Unwrap this value from the [`MaybeUnset`] wrapper. Never panics.
    pub fn unwrap(self) -> T {
        self.value
    }

    /// Map this value using a function. The `set` flag is carried over.
    #[must_use]
    pub fn map<U, P: FnOnce(T) -> U>(self, f: P) -> MaybeUnset<U> {
        MaybeUnset {
            value: f(self.value),
            set: self.set,
        }
    }
}

impl<T> AsRef<T> for MaybeUnset<T> {
    fn as_ref(&self) -> &T {
        &self.value
    }
}

impl<T: Clone> MaybeUnset<T> {
    /// Clone the underlying value.
    #[must_use]
    pub fn get_cloned(&self) -> T {
        self.value.clone()
    }

    #[must_use]
    pub fn cloned(&self) -> Self {
        self.clone()
    }
}

impl<T: Copy> MaybeUnset<T> {
    /// Copy the underlying value.
    #[must_use]
    pub fn get_copied(&self) -> T {
        self.value
    }

    #[must_use]
    pub fn copied(&self) -> Self {
        *self
    }
}

impl<T> Deref for MaybeUnset<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T: Default> Default for MaybeUnset<T> {
    fn default() -> Self {
        Self {
            value: T::default(),
            set: false,
        }
    }
}

/// A node that represents multiple node. No hierarchy is involved.
#[derive(Debug)]
pub struct CollectionNode {
    /// Whether the node should be displayed.
    pub display: MaybeUnset<bool>,
    /// Nodes
    pub children: Vec<Box<dyn Node>>,
}

impl Default for CollectionNode {
    fn default() -> Self {
        Self::new()
    }
}

impl CollectionNode {
    /// Create a new, empty, displayed collection node.
    #[must_use]
    pub fn new() -> Self {
        Self {
            display: MaybeUnset::new(true),
            children: Vec::new(),
        }
    }

    /// Create a new, empty collection node with given display properties
    #[must_use]
    pub fn from_display(mut display: Properties, context: &CompileContext) -> Self {
        let node = Self {
            display: display.get("display").maybe_unset(true),
            children: Vec::new(),
        };

        display.finish(context);

        node
    }

    /// Push a node.
    pub fn push<T: Node + 'static>(&mut self, node: T) {
        self.children.push(Box::new(node));
    }

    /// Push a boxed node.
    pub fn push_boxed(&mut self, node: Box<dyn Node>) {
        self.children.push(node);
    }

    /// Extend the nodes.
    pub fn extend<T: Node + 'static, U: IntoIterator<Item = T>>(&mut self, nodes: U) {
        self.children
            .extend(nodes.into_iter().map(|x| Box::new(x) as Box<dyn Node>));
    }
}

impl Node for CollectionNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, compiler: &mut Build) {
        if self.display.unwrap() {
            for child in self.children {
                child.build(compiler);
            }
        }
    }
}

/// Nodes can have associated nodes. They're a special kind of nodes unique to specific expressions.
/// Usually utilized by builtins.
pub trait BuildAssociated<T: Node>: Debug {
    /// Build the associated node.
    fn build_associated(self: Box<Self>, build: &mut Build, associated: &mut HierarchyNode<T>);
}

/// Associated data used in constructing the associated node.
#[derive(Debug)]
pub enum AssociatedData {
    /// A boolean value
    Bool(MaybeUnset<bool>),
    /// A style (brush) value
    Style(MaybeUnset<Style>),
    /// A line type - line, ray or segment.
    LineType(MaybeUnset<LineType>),
}

impl AssociatedData {
    #[must_use]
    pub fn as_bool(&self) -> Option<MaybeUnset<bool>> {
        match self {
            Self::Bool(v) => Some(v.copied()),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_style(&self) -> Option<MaybeUnset<Style>> {
        match self {
            Self::Style(v) => Some(v.copied()),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_line_type(&self) -> Option<MaybeUnset<LineType>> {
        match self {
            Self::LineType(v) => Some(v.copied()),
            _ => None,
        }
    }
}

impl From<MaybeUnset<bool>> for AssociatedData {
    fn from(value: MaybeUnset<bool>) -> Self {
        Self::Bool(value)
    }
}

impl From<MaybeUnset<Style>> for AssociatedData {
    fn from(value: MaybeUnset<Style>) -> Self {
        Self::Style(value)
    }
}

impl From<MaybeUnset<LineType>> for AssociatedData {
    fn from(value: MaybeUnset<LineType>) -> Self {
        Self::LineType(value)
    }
}

/// Contains a root node, apart from its children. Simulates a hierarchy.
#[derive(Debug)]
pub struct HierarchyNode<T: Node> {
    /// The root node.
    pub root: Box<T>,
    /// The child nodes.
    pub children: Vec<Box<dyn Node>>,
    /// The associated node.
    pub associated: Option<Box<dyn BuildAssociated<T>>>,
    /// Associated data for associated node construction.
    pub associated_data: HashMap<&'static str, AssociatedData>,
}

impl<T: Node> Node for HierarchyNode<T> {
    fn set_display(&mut self, display: bool) {
        self.root.set_display(display);
    }

    fn get_display(&self) -> bool {
        self.root.get_display()
    }

    fn build(mut self: Box<Self>, build: &mut Build) {
        if self.root.get_display() {
            if let Some(associated) = self.associated.take() {
                associated.build_associated(build, &mut self);
            }

            self.root.build(build);

            for child in self.children {
                child.build(build);
            }
        }
    }
}

impl<U: Displayed, T: FromExpr<U>> FromExpr<U> for HierarchyNode<T> {
    fn from_expr(expr: &Expr<U>, props: Properties, context: &CompileContext) -> Self {
        Self {
            root: Box::new(T::from_expr(expr, props, context)),
            children: Vec::new(),
            associated: None,
            associated_data: HashMap::new(),
        }
    }
}

impl<T: Node> HierarchyNode<T> {
    /// Create a new hierarchy node from its root. No children initially.
    pub fn new(root: T) -> Self {
        Self {
            root: Box::new(root),
            children: Vec::new(),
            associated: None,
            associated_data: HashMap::new(),
        }
    }

    /// Push a child.
    pub fn push_child<U: Node + 'static>(&mut self, node: U) {
        self.children.push(Box::new(node));
    }

    /// Extend boxed children.
    pub fn extend_boxed<Iter: IntoIterator<Item = Box<dyn Node>>>(&mut self, nodes: Iter) {
        self.children.extend(nodes);
    }

    /// Extend children.
    pub fn extend_children<U: Node + 'static, Iter: IntoIterator<Item = U>>(
        &mut self,
        nodes: Iter,
    ) {
        self.children
            .extend(nodes.into_iter().map(|x| Box::new(x) as Box<dyn Node>));
    }

    /// Set the associated node.
    pub fn set_associated<U: BuildAssociated<T> + 'static>(&mut self, associated: U) {
        self.associated = Some(Box::new(associated));
    }

    /// Inset associated data with a specific key.
    pub fn insert_data<U: Into<AssociatedData>>(&mut self, key: &'static str, data: U) {
        self.associated_data.insert(key, data.into());
    }

    /// Get associated data.
    #[must_use]
    pub fn get_data(&self, key: &'static str) -> Option<&AssociatedData> {
        self.associated_data.get(key)
    }
}

/// Node for point collections
#[derive(Debug)]
pub struct PCNode {
    /// Whether to display the node
    pub display: MaybeUnset<bool>,
    /// The child nodes of the collection's points
    pub children: Vec<Option<HierarchyNode<<Point as Displayed>::Node>>>,
    /// Properties are stored for later processing as they might be used for conversions.
    pub props: Option<Properties>,
}

impl Default for PCNode {
    fn default() -> Self {
        Self::new()
    }
}

impl PCNode {
    /// Create a new, empty point collection node.
    #[must_use]
    pub fn new() -> Self {
        Self {
            display: MaybeUnset::new(true),
            children: Vec::new(),
            props: None,
        }
    }

    /// Push a child node.
    pub fn push(&mut self, node: Option<HierarchyNode<<Point as Displayed>::Node>>) {
        self.children.push(node);
    }

    /// Extend child nodes.
    pub fn extend<U: IntoIterator<Item = Option<HierarchyNode<<Point as Displayed>::Node>>>>(
        &mut self,
        nodes: U,
    ) {
        self.children.extend(nodes);
    }
}

impl Dummy for PCNode {
    fn dummy() -> Self {
        Self::new()
    }

    fn is_dummy(&self) -> bool {
        self.children.is_empty()
    }
}

impl Node for PCNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, build: &mut Build) {
        if self.display.unwrap() {
            for child in self.children.into_iter().flatten() {
                child.build_unboxed(build);
            }
        }
    }
}

macro_rules! impl_from_for_any {
    ($from:ident) => {
        impl From<HierarchyNode<<$from as Displayed>::Node>> for AnyExprNode {
            fn from(value: HierarchyNode<<$from as Displayed>::Node>) -> Self {
                Self::$from(value)
            }
        }
    };
}

/// Type-erased node for all unrolled expression nodes.
#[derive(Debug)]
pub enum AnyExprNode {
    Point(HierarchyNode<<Point as Displayed>::Node>),
    Line(HierarchyNode<<Line as Displayed>::Node>),
    Circle(HierarchyNode<<Circle as Displayed>::Node>),
    Scalar(HierarchyNode<<Scalar as Displayed>::Node>),
    PointCollection(HierarchyNode<<PointCollection as Displayed>::Node>),
    Bundle(HierarchyNode<<Bundle as Displayed>::Node>),
    Unknown(HierarchyNode<<Unknown as Displayed>::Node>),
}

impl_from_for_any! {Point}
impl_from_for_any! {Line}
impl_from_for_any! {Circle}
impl_from_for_any! {Scalar}
impl_from_for_any! {PointCollection}
impl_from_for_any! {Bundle}
impl_from_for_any! {Unknown}

impl AnyExprNode {
    /// Erase `self`'s type completely.
    #[must_use]
    pub fn to_dyn(self) -> Box<dyn Node> {
        match self {
            Self::Point(v) => Box::new(v),
            Self::Line(v) => Box::new(v),
            Self::Circle(v) => Box::new(v),
            Self::Scalar(v) => Box::new(v),
            Self::PointCollection(v) => Box::new(v),
            Self::Bundle(v) => Box::new(v),
            Self::Unknown(v) => Box::new(v),
        }
    }

    /// # Panics
    /// If the node is not a point node.
    #[must_use]
    pub fn to_point(self) -> HierarchyNode<<Point as Displayed>::Node> {
        if let Self::Point(v) = self {
            v
        } else {
            panic!("not a point")
        }
    }

    /// # Panics
    /// If the node is not a line node.
    #[must_use]
    pub fn to_line(self) -> HierarchyNode<<Line as Displayed>::Node> {
        if let Self::Line(v) = self {
            v
        } else {
            panic!("not a line")
        }
    }

    /// # Panics
    /// If the node is not a circle node.
    #[must_use]
    pub fn to_circle(self) -> HierarchyNode<<Circle as Displayed>::Node> {
        if let Self::Circle(v) = self {
            v
        } else {
            panic!("not a circle")
        }
    }

    /// # Panics
    /// If the node is not a scalar node.
    #[must_use]
    pub fn to_scalar(self) -> HierarchyNode<<Scalar as Displayed>::Node> {
        if let Self::Scalar(v) = self {
            v
        } else {
            panic!("not a scalar")
        }
    }

    /// # Panics
    /// If the node is not a point collection node.
    #[must_use]
    pub fn to_point_collection(self) -> HierarchyNode<<PointCollection as Displayed>::Node> {
        if let Self::PointCollection(v) = self {
            v
        } else {
            panic!("not a point collection")
        }
    }

    /// # Panics
    /// If the node is not a bundle node.
    #[must_use]
    pub fn to_bundle(self) -> HierarchyNode<<Bundle as Displayed>::Node> {
        if let Self::Bundle(v) = self {
            v
        } else {
            panic!("not a bundle")
        }
    }

    /// # Panics
    /// If the node is not an unknown node.
    #[must_use]
    pub fn to_unknown(self) -> HierarchyNode<<Unknown as Displayed>::Node> {
        if let Self::Unknown(v) = self {
            v
        } else {
            panic!("not a unknown")
        }
    }
}

impl Node for AnyExprNode {
    fn set_display(&mut self, display: bool) {
        match self {
            Self::Point(v) => v.set_display(display),
            Self::Line(v) => v.set_display(display),
            Self::Circle(v) => v.set_display(display),
            Self::Scalar(v) => v.set_display(display),
            Self::PointCollection(v) => v.set_display(display),
            Self::Bundle(v) => v.set_display(display),
            Self::Unknown(v) => v.set_display(display),
        }
    }

    fn get_display(&self) -> bool {
        match self {
            Self::Point(v) => v.get_display(),
            Self::Line(v) => v.get_display(),
            Self::Circle(v) => v.get_display(),
            Self::Scalar(v) => v.get_display(),
            Self::PointCollection(v) => v.get_display(),
            Self::Bundle(v) => v.get_display(),
            Self::Unknown(v) => v.get_display(),
        }
    }

    fn build(self: Box<Self>, build: &mut Build) {
        match *self {
            Self::Point(v) => v.build_unboxed(build),
            Self::Line(v) => v.build_unboxed(build),
            Self::Circle(v) => v.build_unboxed(build),
            Self::Scalar(v) => v.build_unboxed(build),
            Self::PointCollection(v) => v.build_unboxed(build),
            Self::Bundle(v) => v.build_unboxed(build),
            Self::Unknown(v) => v.build_unboxed(build),
        }
    }
}

/// Node for bundles
#[derive(Debug)]
pub struct BundleNode {
    /// Whether to display the node.
    pub display: MaybeUnset<bool>,
    /// Field-bound child nodes.
    pub children: HashMap<String, AnyExpr>,
}

impl Default for BundleNode {
    fn default() -> Self {
        Self::new()
    }
}

impl Dummy for BundleNode {
    fn dummy() -> Self {
        Self::new()
    }

    fn is_dummy(&self) -> bool {
        self.children.is_empty()
    }
}

impl BundleNode {
    /// Create a new, empty bundle node.
    #[must_use]
    pub fn new() -> Self {
        Self {
            display: MaybeUnset::new(true),
            children: HashMap::new(),
        }
    }

    /// Insert a field to construct its node from.
    pub fn insert<T: Displayed>(&mut self, key: String, expr: Expr<T>)
    where
        AnyExpr: From<Expr<T>>,
    {
        self.children.insert(key, AnyExpr::from(expr));
    }

    /// Extend fields
    pub fn extend<U: IntoIterator<Item = (String, AnyExpr)>>(&mut self, nodes: U) {
        self.children.extend(nodes);
    }
}

impl Node for BundleNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, build: &mut Build) {
        if self.display.get_copied() {
            for mut child in self.children.into_values() {
                if let Some(node) = child.replace_node(None) {
                    node.build_unboxed(build);
                }
            }
        }
    }
}

/// An empty node that is never displayed.
#[derive(Debug)]
pub struct EmptyNode;

impl Dummy for EmptyNode {
    fn dummy() -> Self {
        Self
    }

    fn is_dummy(&self) -> bool {
        true
    }
}

impl Node for EmptyNode {
    fn set_display(&mut self, _display: bool) {}

    fn get_display(&self) -> bool {
        false
    }

    fn build(self: Box<Self>, _build: &mut Build) {}
}

/// A node for points
#[derive(Debug)]
pub struct PointNode {
    /// Whether to display the node
    pub display: MaybeUnset<bool>,
    /// The point's label
    pub label: MaybeUnset<MathString>,
    /// Whether to display the label
    pub display_label: MaybeUnset<bool>,
    /// Whether to display the point's dot.
    pub display_dot: MaybeUnset<bool>,
    /// Default label to use if `label` is empty.
    pub default_label: MathString,
    /// Defining expression
    pub expr: Expr<Point>,
}

impl Dummy for PointNode {
    fn dummy() -> Self {
        Self {
            display: MaybeUnset::new(true),
            label: MaybeUnset::new(MathString::new(span!(0, 0, 0, 0))),
            display_label: MaybeUnset::new(true),
            display_dot: MaybeUnset::new(true),
            default_label: MathString::new(span!(0, 0, 0, 0)),
            expr: Expr::dummy(),
        }
    }

    fn is_dummy(&self) -> bool {
        self.expr.is_dummy()
    }
}

impl Node for PointNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, build: &mut Build) {
        if self.display.unwrap() && !self.is_dummy() {
            let id = build.load(&self.expr);
            build.add(PointItem {
                id,
                label: if self.display_label.unwrap() {
                    if self.label.as_ref().is_empty() {
                        // println!("{} as {}", self.expr, self.default_label);
                        self.default_label
                    } else {
                        self.label.unwrap()
                    }
                } else {
                    MathString::new(span!(0, 0, 0, 0))
                }
                .string,
                display_dot: self.display_dot.unwrap(),
            });
        }
    }
}

impl FromExpr<Point> for PointNode {
    fn from_expr(expr: &Expr<Point>, mut props: Properties, context: &CompileContext) -> Self {
        let node = Self {
            display: props.get("display").maybe_unset(true),
            label: props
                .get("label")
                .maybe_unset(MathString::new(span!(0, 0, 0, 0))),
            display_label: props.get("display_label").maybe_unset(true),
            display_dot: props.get("display_dot").maybe_unset(true),
            default_label: props
                .get("default-label")
                .ok_or(MathString::new(span!(0, 0, 0, 0))),
            expr: expr.clone_without_node(),
        };

        props.finish(context);

        node
    }
}

/// Node for a circle
#[derive(Debug)]
pub struct CircleNode {
    /// Whether to display the node
    pub display: MaybeUnset<bool>,
    /// The circle's label
    pub label: MaybeUnset<MathString>,
    /// Whether to display the label
    pub display_label: MaybeUnset<bool>,
    /// Default label to use if `label` is empty
    pub default_label: MathString,
    /// How to draw the circle (brush)
    pub style: MaybeUnset<Style>,
    /// The defining expression
    pub expr: Expr<Circle>,
}

impl Dummy for CircleNode {
    fn dummy() -> Self {
        Self {
            display: MaybeUnset::new(true),
            label: MaybeUnset::new(MathString::new(span!(0, 0, 0, 0))),
            display_label: MaybeUnset::new(true),
            default_label: MathString::new(span!(0, 0, 0, 0)),
            style: MaybeUnset::new(Style::default()),
            expr: Expr::dummy(),
        }
    }

    fn is_dummy(&self) -> bool {
        self.expr.is_dummy()
    }
}

impl Node for CircleNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, build: &mut Build) {
        if self.display.unwrap() && !self.is_dummy() {
            let id = build.load(&self.expr);
            build.add(CircleItem {
                id,
                label: if self.display_label.unwrap() {
                    if self.label.as_ref().is_empty() {
                        // println!("{} as {}", self.expr, self.default_label);
                        self.default_label
                    } else {
                        self.label.unwrap()
                    }
                } else {
                    MathString::new(span!(0, 0, 0, 0))
                }
                .string,
                style: self.style.unwrap(),
            });
        }
    }
}

impl FromExpr<Circle> for CircleNode {
    fn from_expr(expr: &Expr<Circle>, mut props: Properties, context: &CompileContext) -> Self {
        let node = Self {
            display: props.get("display").maybe_unset(true),
            label: props
                .get("label")
                .maybe_unset(MathString::new(span!(0, 0, 0, 0))),
            display_label: props.get("display_label").maybe_unset(false),
            default_label: props
                .get("default-label")
                .ok_or(MathString::new(span!(0, 0, 0, 0))),
            style: props.get("style").maybe_unset(Style::default()),
            expr: expr.clone_without_node(),
        };

        props.finish(context);

        node
    }
}

macro_rules! property_enum_impl {
    ($name:ident { $($variant:ident: $key:literal),* $(,)? }) => {
        impl FromProperty for $name {
            fn from_property(property: PropertyValue) -> Result<Self, Error> {
                match property {
                    PropertyValue::Number(n) => Err(Error::StringOrIdentExpected {
                        error_span: n.get_span(),
                    }),
                    PropertyValue::Ident(i) => match i.to_string().to_lowercase().as_str() {
                        $($key => Ok(Self::$variant),)*
                        &_ => Err(Error::EnumInvalidValue {
                            error_span: i.get_span(),
                            available_values: &[$($key),*],
                            received_value: i.to_string(),
                        }),
                    },
                    PropertyValue::String(s) => match s.content.to_lowercase().as_str() {
                        $($key => Ok(Self::$variant),)*
                        &_ => Err(Error::EnumInvalidValue {
                            error_span: s.get_span(),
                            available_values: &[$($key),*],
                            received_value: s.content,
                        }),
                    },
                    PropertyValue::RawString(s) => Err(Error::NonRawStringOrIdentExpected {
                        error_span: s.get_span(),
                    }),
                }
            }
        }
    };
}

macro_rules! property_enum {
    ($name:ident { $($variant:ident: $key:literal),* $(,)? }) => {
        #[derive(Debug, Clone, Copy)]
        pub enum $name {
            $($variant),*
        }

        property_enum_impl! {$name { $($variant: $key),* }}
    };
}

property_enum! {
    LineType {
        Line: "line",
        Ray: "ray",
        Segment: "segment"
    }
}

impl Default for LineType {
    fn default() -> Self {
        Self::Line
    }
}

property_enum_impl! {
    Style {
        Solid: "solid",
        Dashed: "dashed",
        Dotted: "dotted",
        Bold: "bold"
    }
}

/// Node for a line
#[derive(Debug)]
pub struct LineNode {
    /// Whether to display the node
    pub display: MaybeUnset<bool>,
    /// The line's label
    pub label: MaybeUnset<MathString>,
    /// Whether to display the label
    pub display_label: MaybeUnset<bool>,
    /// Default label to use if `label` is empty.
    pub default_label: MathString,
    /// The type of this line
    pub line_type: MaybeUnset<LineType>,
    /// How to draw the line (brush)
    pub style: MaybeUnset<Style>,
    /// Defining expression
    pub expr: Expr<Line>,
}

impl Dummy for LineNode {
    fn dummy() -> Self {
        Self {
            display: MaybeUnset::new(true),
            label: MaybeUnset::new(MathString::new(span!(0, 0, 0, 0))),
            display_label: MaybeUnset::new(true),
            default_label: MathString::new(span!(0, 0, 0, 0)),
            line_type: MaybeUnset::new(LineType::Line),
            style: MaybeUnset::new(Style::default()),
            expr: Expr::dummy(),
        }
    }

    fn is_dummy(&self) -> bool {
        self.expr.is_dummy()
    }
}

impl Node for LineNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, build: &mut Build) {
        if self.display.unwrap() && !self.is_dummy() {
            let label = if self.display_label.unwrap() {
                let label = self.label.unwrap();

                if label.is_empty() {
                    self.default_label
                } else {
                    label
                }
            } else {
                MathString::new(span!(0, 0, 0, 0))
            };
            let style = self.style.unwrap();

            match self.line_type.unwrap() {
                LineType::Line => {
                    let id = build.load(&self.expr);
                    build.add(LineItem {
                        id,
                        label: label.string,
                        style,
                    });
                }
                LineType::Ray => match &self.expr.data.as_ref() {
                    Line::LineFromPoints(a, b) => {
                        let p_id = build.load(a);
                        let q_id = build.load(b);
                        build.add(RayItem {
                            p_id,
                            q_id,
                            label: label.string,
                            style,
                        });
                    }
                    Line::AngleBisector(a, b, c) => {
                        let x = Expr::new_spanless(Point::LineLineIntersection(
                            Expr::new_spanless(Line::LineFromPoints(
                                a.clone_without_node(),
                                c.clone_without_node(),
                            )),
                            self.expr.clone_without_node(),
                        ));

                        let p_id = build.load(b);
                        let q_id = build.load(&x);
                        build.add(RayItem {
                            p_id,
                            q_id,
                            label: label.string,
                            style,
                        });
                    }
                    _ => unreachable!(),
                },
                LineType::Segment => match &self.expr.data.as_ref() {
                    Line::LineFromPoints(a, b) => {
                        let p_id = build.load(a);
                        let q_id = build.load(b);
                        build.add(RayItem {
                            p_id,
                            q_id,
                            label: label.string,
                            style,
                        });
                    }
                    _ => unreachable!(),
                },
            }
        }
    }
}

impl FromExpr<Line> for LineNode {
    fn from_expr(expr: &Expr<Line>, mut props: Properties, context: &CompileContext) -> Self {
        let _ = props.get::<MathString>("default-label");

        let node = Self {
            display: props.get("display").maybe_unset(true),
            label: props
                .get("label")
                .maybe_unset(MathString::new(span!(0, 0, 0, 0))),
            display_label: props.get("display_label").maybe_unset(false),
            default_label: props
                .get("default-label")
                .ok_or(MathString::new(span!(0, 0, 0, 0))),
            line_type: MaybeUnset::new(LineType::Line),
            style: props.get("style").maybe_unset(Style::default()),
            expr: expr.clone_without_node(),
        };

        props.finish(context);

        node
    }
}

/// A node for a scalar.
#[derive(Debug)]
pub struct ScalarNode {
    /// Whether to display the node
    pub display: MaybeUnset<bool>,
    /// Defining expression
    pub expr: Expr<Scalar>,
}

impl Dummy for ScalarNode {
    fn dummy() -> Self {
        Self {
            display: MaybeUnset::new(true),
            expr: Expr::dummy(),
        }
    }

    fn is_dummy(&self) -> bool {
        self.expr.is_dummy()
    }
}

impl Node for ScalarNode {
    fn set_display(&mut self, display: bool) {
        self.display.set(display);
    }

    fn get_display(&self) -> bool {
        self.display.get_copied()
    }

    fn build(self: Box<Self>, _build: &mut Build) {}
}

impl FromExpr<Scalar> for ScalarNode {
    fn from_expr(expr: &Expr<Scalar>, mut props: Properties, context: &CompileContext) -> Self {
        props.ignore("label");
        props.ignore("display_label");
        props.ignore("default-label");

        let node = Self {
            display: props.get("display").maybe_unset(true),
            expr: expr.clone_without_node(),
        };

        props.finish(context);

        node
    }
}