geo_aid_script/unroll/
library.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
//! `GeoScript`'s builtin functions and types

use std::{
    collections::HashMap,
    fmt::Display,
    marker::PhantomData,
    mem,
    ops::{Deref, DerefMut},
};

use num_rational::Ratio;

use crate::{
    parser::Type,
    token::number::ProcNum,
    unit,
    unroll::{AnyExpr, Expr, GeoType, Number, PointCollection},
    ComplexUnit,
};

use super::{
    context::CompileContext, figure::Node, most_similar, Convert, ConvertFrom, Dummy, Generic,
    NumberData, Properties,
};

pub mod angle;
pub mod area;
pub mod bisector;
pub mod circle;
pub mod complex;
pub mod degrees;
pub mod dst;
pub mod intersection;
pub mod lies_on;
pub mod line;
pub mod mid;
pub mod parallel;
pub mod perpendicular;
pub mod point;
pub mod polygon;
pub mod radians;
pub mod segment;
pub mod transform;
pub mod trigonometry;

/// A prelude for builtin functions.
pub mod prelude {
    pub(crate) use crate::{
        ty, unit,
        unroll::{
            context::CompileContext,
            figure::{
                BuildAssociated, CollectionNode, HierarchyNode, LineNode, LineType, NumberNode,
                PointNode,
            },
            library::{macros::*, Angle, Area, Distance, Function, Library, Pc, Rule, Unitless},
            Circle, CloneWithNode, Derived, DerivedType, Expr, GeoType, Line, NumberData, Point,
            Properties, UnrolledRule, UnrolledRuleKind,
        },
    };
    pub(crate) use geo_aid_figure::Style;
    pub(crate) use std::rc::Rc;
}
/// A `GeoScript` function.
pub struct Function {
    /// Name of this function.
    pub name: &'static str,
    /// Function's overloads.
    pub overloads: Vec<Box<dyn Overload>>,
    /// Aliases of this function
    pub aliases: Vec<&'static str>,
    /// Method aliases of this function
    pub method_aliases: Vec<(Type, &'static str)>,
}

impl Function {
    /// Create a new function with the given name. The name MUST be ascii and lowercase
    #[must_use]
    pub fn new(name: &'static str) -> Self {
        if name
            .chars()
            .any(|c| !c.is_ascii() || !c.is_lowercase() && c.is_alphabetic() || c == '_')
        {
            panic!("Function name must be ASCII, lowercase and not contain underscores. Received name: {name}");
        }

        Self {
            name,
            overloads: Vec::new(),
            aliases: Vec::new(),
            method_aliases: Vec::new(),
        }
    }

    /// Create an alias for this function
    #[must_use]
    pub fn alias(mut self, name: &'static str) -> Self {
        if name
            .chars()
            .any(|c| !c.is_ascii() || !c.is_lowercase() && c.is_alphabetic() || c == '_')
        {
            panic!("Function name must be ASCII, lowercase and not contain underscores. Received name: {name}");
        }

        self.aliases.push(name);
        self
    }

    /// Create an alias for this function. For point collections, `self_type` length of 0
    /// means any point collection. For numbers, unit of `None` means any unit.
    #[must_use]
    pub fn alias_method(mut self, self_type: Type, name: &'static str) -> Self {
        if name
            .chars()
            .any(|c| !c.is_ascii() || !c.is_lowercase() && c.is_alphabetic())
        {
            panic!("Function name must be ASCII and lowercase. Received name: {name}");
        }

        self.method_aliases.push((self_type, name));
        self
    }

    /// Add a new overload to this function.
    #[must_use]
    pub fn overload<Marker>(mut self, f: impl IntoOverload<Marker>) -> Self {
        self.overloads.push(Box::new(f.into_overload()));
        self
    }

    /// Tries to find an overload for the given param types.
    #[must_use]
    pub fn get_overload(&self, params: &[AnyExpr]) -> Option<&dyn Overload> {
        self.overloads
            .iter()
            .map(AsRef::as_ref)
            .find(|x| x.get_returned_type(params).is_some())
    }
}

/// Trait for function overloads
pub trait Overload {
    /// Get the return type for the given parameters. Returns `None` if the overload
    /// cannot be called with these parameters.
    #[must_use]
    fn get_returned_type(&self, params: &[AnyExpr]) -> Option<Type>;

    /// Unroll the function for the given params. The resulting expression
    /// matches the type returned by `get_returned_type`.
    #[must_use]
    fn unroll(
        &self,
        params: Vec<AnyExpr>,
        context: &mut CompileContext,
        props: Properties,
    ) -> AnyExpr;
}

/// An overload of a function in `GeoScript`.
#[derive(Debug)]
pub struct FunctionOverload<F, A, R, C>(F, PhantomData<(A, R, C)>);

macro_rules! tuple_size {
    () => {
        0
    };
    ($first:ident $(, $arg:ident)*) => {
        1 + tuple_size!($($arg),*)
    }
}

macro_rules! impl_overload_function {
    ($($arg:ident),* $(,)?) => {
        impl<$($arg,)* R, F> Overload for FunctionOverload<F, ($($arg,)*), R, &mut CompileContext>
        where
            $($arg: GeoType + 'static,)*
            R: GeoType + Into<AnyExpr> + 'static,
            F: Fn($($arg,)* &mut CompileContext, Properties) -> R
        {
            fn get_returned_type(&self, params: &[AnyExpr]) -> Option<Type> {
                let types = [$($arg::get_type()),*];
                if params.len() == tuple_size!($($arg),*)
                    && params
                    .iter()
                    .map(|p| p.get_type())
                    .zip(types)
                    .all(|(a, b)| a.can_cast(&b)) {
                    Some(R::get_type())
                } else {
                    None
                }
            }

            fn unroll(&self, params: Vec<AnyExpr>, context: &mut CompileContext, props: Properties) -> AnyExpr {
                #[allow(unused_mut, unused_variables)]
                let mut param = params.into_iter();
                (self.0)(
                    $($arg::Target::convert_from(param.next().unwrap(), context).into(),)*
                    context, props
                ).into()
            }
        }

        impl<$($arg,)* R, F> Overload for FunctionOverload<F, ($($arg,)*), R, &CompileContext>
        where
            $($arg: GeoType + 'static,)*
            R: GeoType + Into<AnyExpr> + 'static,
            F: Fn($($arg,)* &CompileContext, Properties) -> R
        {
            fn get_returned_type(&self, params: &[AnyExpr]) -> Option<Type> {
                let types = [$($arg::get_type()),*];
                if params.len() == tuple_size!($($arg),*)
                    && params
                    .iter()
                    .map(|p| p.get_type())
                    .zip(types)
                    .all(|(a, b)| a.can_cast(&b)) {
                    Some(R::get_type())
                } else {
                    None
                }
            }

            fn unroll(&self, params: Vec<AnyExpr>, context: &mut CompileContext, props: Properties) -> AnyExpr {
                #[allow(unused_mut, unused_variables)]
                let mut param = params.into_iter();
                (self.0)(
                    $($arg::Target::convert_from(param.next().unwrap().convert_to($arg::get_type(), context), context).into(),)*
                    context, props
                ).into()
            }
        }
    };
}

/// Helper trait for overloading a function. Features a special marker for
/// managing possible different implementations on the same type.
pub trait IntoOverload<Marker>: Sized {
    /// Target overload type
    type Target: Overload + 'static;

    /// Turn this into a function overload.
    fn into_overload(self) -> Self::Target;
}

impl<T: Overload + 'static> IntoOverload<T> for T {
    type Target = T;

    fn into_overload(self) -> Self::Target {
        self
    }
}

macro_rules! impl_into_overload {
    ($($arg:ident),* $(,)?) => {
        impl<$($arg,)* R, F> IntoOverload<(F, ($($arg,)*), R, &mut CompileContext)> for F
        where
            $($arg: GeoType + 'static,)*
            R: GeoType + Into<AnyExpr> + 'static,
            F: Fn($($arg,)* &mut CompileContext, Properties) -> R + 'static
        {
            type Target = FunctionOverload<F, ($($arg,)*), R, &'static mut CompileContext>;

            fn into_overload(self) -> Self::Target {
                FunctionOverload(self, PhantomData)
            }
        }

        impl<$($arg,)* R, F> IntoOverload<(F, ($($arg,)*), R, &CompileContext)> for F
        where
            $($arg: GeoType + 'static,)*
            R: GeoType + Into<AnyExpr> + 'static,
            F: Fn($($arg,)* &CompileContext, Properties) -> R + 'static
        {
            type Target = FunctionOverload<F, ($($arg,)*), R, &'static CompileContext>;

            fn into_overload(self) -> Self::Target {
                FunctionOverload(self, PhantomData)
            }
        }

        impl_overload_function! {$($arg),*}
    };
}

impl_into_overload! {}
impl_into_overload! {T0}
impl_into_overload! {T0, T1}
impl_into_overload! {T0, T1, T2}
impl_into_overload! {T0, T1, T2, T3}

/// A rule operator.
pub struct Rule {
    /// Rule's name
    pub name: &'static str,
    /// Rule's overloads.
    pub overloads: Vec<Box<dyn RuleOverload>>,
    /// Aliases this rule has.
    pub aliases: Vec<&'static str>,
}

impl Rule {
    /// Create a new rule with no overloads. The name must be ascii and all lowercase.
    #[must_use]
    pub fn new(name: &'static str) -> Self {
        if name
            .chars()
            .any(|c| !c.is_ascii() || !c.is_lowercase() && c.is_alphabetic() || c == '_')
        {
            panic!("Function name must be ASCII, lowercase and not contain underscores. Received name: {name}");
        }

        Self {
            name,
            overloads: Vec::new(),
            aliases: Vec::new(),
        }
    }

    /// Create an alias for this rule
    #[must_use]
    pub fn alias(mut self, name: &'static str) -> Self {
        if name
            .chars()
            .any(|c| !c.is_ascii() || !c.is_lowercase() && c.is_alphabetic() || c == '_')
        {
            panic!("Rule name must be ASCII, lowercase and not contain underscores. Received name: {name}");
        }

        self.aliases.push(name);
        self
    }

    /// Add an overload to this rule
    #[must_use]
    pub fn overload<M>(mut self, f: impl IntoRuleOverload<M>) -> Self {
        self.overloads.push(Box::new(f.into_overload()));
        self
    }

    /// Tries to find an overload for the given param types.
    #[must_use]
    pub fn get_overload(&self, lhs: &AnyExpr, rhs: &AnyExpr) -> Option<&dyn RuleOverload> {
        self.overloads
            .iter()
            .map(AsRef::as_ref)
            .find(|x| x.matches(lhs, rhs))
    }
}

/// Trait for rule overloads
pub trait RuleOverload {
    /// Check if this overload can be called with the given expressions.
    #[must_use]
    fn matches(&self, lhs: &AnyExpr, rhs: &AnyExpr) -> bool;

    /// Unroll this rule.
    #[must_use]
    fn unroll(
        &self,
        lhs: AnyExpr,
        rhs: AnyExpr,
        context: &mut CompileContext,
        props: Properties,
        inverted: bool,
        weight: ProcNum,
    ) -> Box<dyn Node>;
}

/// Trait for things convertible into rule overloads
pub trait IntoRuleOverload<Marker> {
    type Target: RuleOverload + 'static;

    fn into_overload(self) -> Self::Target;
}

impl<T: RuleOverload + 'static> IntoRuleOverload<T> for T {
    type Target = Self;

    fn into_overload(self) -> Self::Target {
        self
    }
}

impl<
        L: GeoType + 'static,
        R: GeoType + 'static,
        N: Node + 'static,
        F: Fn(L, R, &mut CompileContext, Properties, bool, ProcNum) -> N + 'static,
    > IntoRuleOverload<(L, R, F)> for F
{
    type Target = FunctionRuleOverload<L, R, F>;

    fn into_overload(self) -> Self::Target {
        FunctionRuleOverload(self, PhantomData)
    }
}

/// A rule overload made from a function.
pub struct FunctionRuleOverload<L, R, F>(F, PhantomData<(L, R)>);

impl<
        L: GeoType,
        R: GeoType,
        N: Node + 'static,
        F: Fn(L, R, &mut CompileContext, Properties, bool, ProcNum) -> N,
    > RuleOverload for FunctionRuleOverload<L, R, F>
{
    fn matches(&self, lhs: &AnyExpr, rhs: &AnyExpr) -> bool {
        lhs.can_convert_to(L::get_type()) && rhs.can_convert_to(R::get_type())
    }

    fn unroll(
        &self,
        lhs: AnyExpr,
        rhs: AnyExpr,
        context: &mut CompileContext,
        props: Properties,
        inverted: bool,
        weight: ProcNum,
    ) -> Box<dyn Node> {
        Box::new((self.0)(
            L::from(lhs.convert(context)),
            R::from(rhs.convert(context)),
            context,
            props,
            inverted,
            weight,
        ))
    }
}

/// A direct definition or an alias
pub enum Definition<T> {
    /// A direct function definition
    Direct(T),
    Alias(&'static str),
}

/// The library of all rules and functions available in geoscript.
#[derive(Default)]
pub struct Library {
    /// Functions
    functions: HashMap<&'static str, Definition<Function>>,
    /// Methods. Note that methods can only be aliased to functions, never to methods or the other way around.
    methods: HashMap<Type, HashMap<&'static str, Definition<Function>>>,
    /// The rule operators.
    rule_ops: HashMap<&'static str, Definition<Rule>>,
}

impl Library {
    /// Create a new empty library.
    #[must_use]
    pub fn new() -> Self {
        let mut library = Self {
            functions: HashMap::new(),
            methods: HashMap::new(),
            rule_ops: HashMap::new(),
        };

        complex::register(&mut library);
        trigonometry::register(&mut library);
        transform::register(&mut library);
        point::register(&mut library); // Point()
        dst::register(&mut library); // dst()
        angle::register(&mut library); // angle()
        degrees::register(&mut library); // degrees()
        radians::register(&mut library); // radians()
        mid::register(&mut library); // mid()
        perpendicular::register(&mut library); // perpendicular_through()
        parallel::register(&mut library); // parallel_through()
        intersection::register(&mut library); // intersection()
        bisector::register(&mut library); // bisector()
        circle::register(&mut library); // Circle()
        segment::register(&mut library); // Segment()
        line::register(&mut library); // Line()
        area::register(&mut library);
        polygon::register(&mut library);

        lies_on::register(&mut library); // lies_on

        library
    }

    /// Add a definition
    pub fn add<T: Addable>(&mut self, def: T) -> &mut Self {
        def.add_to(self);
        self
    }

    /// Get the function by its name. If the function doesn't exist,
    /// return the most similar name if one exists. The search is case-insensitive and ignores underscores.
    pub fn get_function(&self, name: &str) -> Result<&Function, Option<&'static str>> {
        let mut name = name.to_lowercase();
        name.retain(|c| c != '_');
        self.functions
            .get(name.as_str())
            .ok_or_else(|| most_similar(self.functions.keys().copied(), name.as_str()))
            .and_then(|f| match f {
                Definition::Direct(f) => Ok(f),
                Definition::Alias(n) => self.get_function(n),
            })
    }

    /// Get the method by its name and self type. If the method doesn't exist,
    /// return the most similar name if one exists. The search is case-insensitive and ignores underscores.
    /// Self type is expected to be concrete. Internal use only.
    fn get_method_concrete(
        &self,
        self_type: Type,
        name: &str,
    ) -> Result<&Function, Option<&'static str>> {
        let methods = self.methods.get(&self_type).ok_or(None)?;

        methods
            .get(name.to_lowercase().as_str())
            .ok_or_else(|| most_similar(methods.keys().copied(), name))
            .and_then(|f| match f {
                Definition::Direct(f) => Ok(f),
                Definition::Alias(n) => self.get_function(n),
            })
    }

    /// Get the method by its name and self type. If the method doesn't exist,
    /// return the most similar name if one exists. The search is case-insensitive and ignores underscores.
    pub fn get_method(
        &self,
        self_type: Type,
        name: &str,
    ) -> Result<&Function, Option<&'static str>> {
        let suggested = match self.get_method_concrete(self_type, name) {
            Ok(method) => return Ok(method),
            Err(suggested) => suggested,
        };

        self.get_method_concrete(
            match self_type {
                Type::PointCollection(_) => Type::PointCollection(0),
                Type::Number(_) => Type::Number(None),
                _ => return Err(suggested),
            },
            name,
        )
        .map_err(|err| most_similar(suggested.into_iter().chain(err), name))
    }

    /// Get the rule operator by its name. If the rule doesn't exist,
    /// return the most similar name if one exists. The search is case-insensitive and ignores underscores.
    pub fn get_rule(&self, name: &str) -> Result<&Rule, Option<&'static str>> {
        let mut name = name.to_lowercase();
        name.retain(|c| c != '_');
        self.rule_ops
            .get(name.as_str())
            .ok_or_else(|| most_similar(self.rule_ops.keys().copied(), name.as_str()))
            .and_then(|f| match f {
                Definition::Direct(f) => Ok(f),
                Definition::Alias(n) => self.get_rule(n),
            })
    }
}

/// Trait for adding a definition to the library.
pub trait Addable {
    fn add_to(self, library: &mut Library);
}

impl Addable for Function {
    fn add_to(mut self, library: &mut Library) {
        for alias in mem::take(&mut self.aliases) {
            library
                .functions
                .insert(alias, Definition::Alias(self.name));
        }

        for (t, alias) in mem::take(&mut self.method_aliases) {
            library
                .methods
                .entry(t)
                .or_default()
                .insert(alias, Definition::Alias(self.name));
        }

        library
            .functions
            .insert(self.name, Definition::Direct(self));
    }
}

impl Addable for Rule {
    fn add_to(mut self, library: &mut Library) {
        for alias in mem::take(&mut self.aliases) {
            library.rule_ops.insert(alias, Definition::Alias(self.name));
        }

        library.rule_ops.insert(self.name, Definition::Direct(self));
    }
}

/// Point collection with a specific size
pub struct Pc<const N: usize>(pub Expr<PointCollection>);

impl<const N: usize> GeoType for Pc<N> {
    type Target = PointCollection;

    fn get_type() -> Type {
        Type::PointCollection(N)
    }
}

impl<const N: usize> From<Expr<PointCollection>> for Pc<N> {
    fn from(value: Expr<PointCollection>) -> Self {
        assert!(value.data.length == N || N == 0);
        Self(value)
    }
}

impl<const N: usize> Deref for Pc<N> {
    type Target = Expr<PointCollection>;

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

impl<const N: usize> DerefMut for Pc<N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Number with a specific unit.
#[derive(Debug)]
pub struct NumberUnit<
    const DST_NUM: i64,
    const DST_DENOM: i64,
    const ANG_NUM: i64,
    const ANG_DENOM: i64,
>(pub Expr<Number>);

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64> Display
    for NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64>
    NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    #[must_use]
    pub fn get_unit() -> ComplexUnit {
        unit::DISTANCE.pow(Ratio::new(DST_NUM, DST_DENOM))
            * &unit::ANGLE.pow(Ratio::new(ANG_NUM, ANG_DENOM))
    }
}

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64> GeoType
    for NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    type Target = Number;

    fn get_type() -> Type {
        Type::Number(Some(Self::get_unit()))
    }
}

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64>
    From<Expr<Number>> for NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    fn from(value: Expr<Number>) -> Self {
        assert_eq!(value.data.unit, Some(Self::get_unit()));
        Self(value)
    }
}

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64> Deref
    for NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    type Target = Expr<Number>;

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

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64> DerefMut
    for NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64>
    From<NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>> for AnyExpr
{
    fn from(value: NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>) -> Self {
        value.0.into()
    }
}

impl<const DST_NUM: i64, const DST_DENOM: i64, const ANG_NUM: i64, const ANG_DENOM: i64> Dummy
    for NumberUnit<DST_NUM, DST_DENOM, ANG_NUM, ANG_DENOM>
{
    fn dummy() -> Self {
        Self(Expr::new_spanless(Number {
            unit: Some(Self::get_unit()),
            data: NumberData::Generic(Generic::Dummy),
        }))
    }

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

pub type Distance = NumberUnit<1, 1, 0, 1>;
pub type Area = NumberUnit<2, 1, 0, 1>;
pub type Angle = NumberUnit<0, 1, 1, 1>;
pub type Unitless = NumberUnit<0, 1, 0, 1>;

/// Returns what size of point collection can the given derived type be cast onto.
/// 0 signifies that casting is not possible
pub const fn get_derived_pc(_name: &'static str) -> usize {
    0
}

/// Helper macros
pub mod macros {
    /// Get the expression at given index in a point collection.
    macro_rules! index {
        (no-node $col:expr, $at:expr) => {
            ($col).index_without_node($at)
        };
        (node $col:expr, $at:expr) => {
            ($col).index_with_node($at)
        };
    }

    /// Create a constant number expression
    macro_rules! number {
        ($v:expr) => {
            $crate::unroll::library::macros::number!(SCALAR $v)
        };
        (=$v:expr) => {
            $crate::unroll::Expr {
                span: $crate::span!(0, 0, 0, 0),
                data: std::rc::Rc::new($crate::unroll::Number {
                    unit: Some($crate::unit::DISTANCE),
                    data: $crate::unroll::NumberData::DstLiteral(
                        $v.clone()
                    )
                }),
                node: None
            }
        };
        ($t:ident $v:expr) => {
            $crate::unroll::Expr {
                span: $crate::span!(0, 0, 0, 0),
                data: std::rc::Rc::new($crate::unroll::Number {
                    unit: Some($crate::unit::$t),
                    data: $crate::unroll::NumberData::Number($v)
                }),
                node: None
            }
        };
    }

    /// Define a new derived type
    macro_rules! impl_derived {
        ($t:ty) => {
            paste::paste! {
                #[derive(Debug)]
                pub struct [<$t Expr>](pub Expr<Derived>);

                impl std::fmt::Display for [<$t Expr>] {
                    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                        std::fmt::Display::fmt(&self.0, f)
                    }
                }

                impl [<$t Expr>] {
                    #[doc = "Create a new expression out of data and a node"]
                    #[must_use]
                    pub fn new(data: $t, node: HierarchyNode<dyn $crate::unroll::figure::Node>) -> Self {
                        Self(Expr {
                            data: Rc::new(Derived {
                                name: stringify!($t),
                                data: $crate::unroll::DerivedData::Data(Rc::new(data)),
                            }),
                            span: $crate::span!(0, 0, 0, 0),
                            node: Some(node)
                        })
                    }

                    #[doc = "Get the underlying derived expression"]
                    #[must_use]
                    pub fn get(&self) -> Option<&$t> {
                        match &<Derived as $crate::unroll::GetData>::get_data(&self.0.data).data {
                            $crate::unroll::DerivedData::Generic($crate::unroll::Generic::Dummy) => {
                                None
                            }
                            $crate::unroll::DerivedData::Data(d) => {
                                d.as_ref().as_any().downcast_ref()
                            }
                            _ => unreachable!(),
                        }
                    }
                }

                impl GeoType for [<$t Expr>] {
                    type Target = Derived;

                    fn get_type() -> $crate::parser::Type {
                        $crate::parser::Type::Derived(stringify!($t))
                    }
                }

                impl From<Expr<Derived>> for [<$t Expr>] {
                    fn from(value: Expr<Derived>) -> Self {
                        assert!(value.data.name == stringify!($t));
                        Self(value)
                    }
                }

                impl From<[<$t Expr>]> for $crate::unroll::AnyExpr {
                    fn from(value: [<$t Expr>]) -> Self {
                        value.0.into()
                    }
                }

                impl std::ops::Deref for [<$t Expr>] {
                    type Target = Expr<Derived>;

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

                impl std::ops::DerefMut for [<$t Expr>] {
                    fn deref_mut(&mut self) -> &mut Self::Target {
                        &mut self.0
                    }
                }
            }
        };
    }

    pub(crate) use {impl_derived, index, number};
}