1
use crate::ast::serde::{AsId, HasId};
2
use crate::{ast::DeclarationPtr, bug};
3
use derivative::Derivative;
4
use parking_lot::MappedRwLockReadGuard;
5
use serde::{Deserialize, Serialize};
6
use serde_with::serde_as;
7
use std::fmt::{Display, Formatter};
8
use uniplate::Uniplate;
9

            
10
use super::{
11
    Atom, DeclarationKind, DomainPtr, Expression, GroundDomain, Literal, Metadata, Moo, Name,
12
    categories::{Category, CategoryOf},
13
    domains::HasDomain,
14
};
15

            
16
/// A reference to a declaration (variable, parameter, etc.)
17
///
18
/// This is a thin wrapper around [`DeclarationPtr`] with two main purposes:
19
/// 1. Encapsulate the serde pragmas (e.g., serializing as IDs rather than full objects)
20
/// 2. Enable type-directed traversals of references via uniplate
21
#[serde_as]
22
#[derive(
23
    Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Uniplate, Derivative,
24
)]
25
#[derivative(Hash)]
26
#[uniplate()]
27
#[biplate(to=DeclarationPtr)]
28
#[biplate(to=Name)]
29
pub struct Reference {
30
    #[serde_as(as = "AsId")]
31
    pub ptr: DeclarationPtr,
32
}
33

            
34
impl Reference {
35
1066786
    pub fn new(ptr: DeclarationPtr) -> Self {
36
1066786
        Reference { ptr }
37
1066786
    }
38

            
39
15510760
    pub fn ptr(&self) -> &DeclarationPtr {
40
15510760
        &self.ptr
41
15510760
    }
42

            
43
780
    pub fn into_ptr(self) -> DeclarationPtr {
44
780
        self.ptr
45
780
    }
46

            
47
87241740
    pub fn name(&self) -> MappedRwLockReadGuard<'_, Name> {
48
87241740
        self.ptr.name()
49
87241740
    }
50

            
51
5280
    pub fn id(&self) -> crate::ast::serde::ObjId {
52
5280
        self.ptr.id()
53
5280
    }
54

            
55
2723680
    pub fn domain(&self) -> Option<DomainPtr> {
56
2723680
        self.ptr.domain()
57
2723680
    }
58

            
59
2682800
    pub fn resolved_domain(&self) -> Option<Moo<GroundDomain>> {
60
2682800
        self.domain()?.resolve()
61
2682800
    }
62

            
63
    /// Returns the expression behind a value-letting reference, if this is one.
64
13593800
    pub fn resolve_expression(&self) -> Option<Expression> {
65
13593800
        if let Some(expr) = self.ptr().as_value_letting() {
66
1615280
            return Some(expr.clone());
67
11978520
        }
68

            
69
11978520
        let generator = {
70
11978520
            let kind = self.ptr.kind();
71
11978520
            if let DeclarationKind::Quantified(inner) = &*kind {
72
178500
                inner.generator().cloned()
73
            } else {
74
11800020
                None
75
            }
76
        };
77

            
78
11978520
        if let Some(generator) = generator
79
120
            && let Some(expr) = generator.as_value_letting()
80
        {
81
            return Some(expr.clone());
82
11978520
        }
83

            
84
11978520
        None
85
13593800
    }
86

            
87
    /// Evaluates this reference to a literal if it resolves to a constant.
88
13395220
    pub fn resolve_constant(&self) -> Option<Literal> {
89
13395220
        self.resolve_expression()
90
13395220
            .and_then(|expr| super::eval::eval_constant(&expr))
91
13395220
    }
92

            
93
    /// Resolves this reference to an atomic expression, if possible.
94
198580
    pub fn resolve_atomic(&self) -> Option<Atom> {
95
198580
        self.resolve_expression().and_then(|expr| match expr {
96
            Expression::Atomic(_, atom) => Some(atom),
97
            _ => None,
98
        })
99
198580
    }
100
}
101

            
102
impl From<Reference> for Expression {
103
540
    fn from(value: Reference) -> Self {
104
540
        Expression::Atomic(Metadata::new(), value.into())
105
540
    }
106
}
107

            
108
impl From<DeclarationPtr> for Reference {
109
    fn from(ptr: DeclarationPtr) -> Self {
110
        Reference::new(ptr)
111
    }
112
}
113

            
114
impl CategoryOf for Reference {
115
1836780
    fn category_of(&self) -> Category {
116
1836780
        self.ptr.category_of()
117
1836780
    }
118
}
119

            
120
impl HasDomain for Reference {
121
524580
    fn domain_of(&self) -> DomainPtr {
122
524580
        self.ptr.domain().unwrap_or_else(|| {
123
            bug!(
124
                "reference ({name}) should have a domain",
125
                name = self.ptr.name()
126
            )
127
        })
128
524580
    }
129
}
130

            
131
impl Display for Reference {
132
32873320
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
133
32873320
        self.ptr.name().fmt(f)
134
32873320
    }
135
}