1
use crate::ast::enumerated::EnumeratedType;
2

            
3
use super::categories::{Category, CategoryOf};
4
use super::name::Name;
5
use super::serde::{DefaultWithId, HasId, IdPtr, ObjId, PtrAsInner};
6
use super::{
7
    DecisionVariable, DomainPtr, Expression, GroundDomain, HasDomain, Moo, Reference, ReturnType,
8
    Typeable,
9
};
10
use crate::representation::{ReprRule, ReprStore};
11
use parking_lot::{
12
    MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockWriteGuard,
13
};
14
use serde::{Deserialize, Serialize};
15
use serde_with::serde_as;
16
use std::any::TypeId;
17
use std::collections::BTreeSet;
18
use std::collections::VecDeque;
19
use std::fmt::{Debug, Display};
20
use std::hash::{DefaultHasher, Hash, Hasher};
21
use std::mem;
22
use std::ops::{Deref, DerefMut};
23
use std::sync::Arc;
24
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
25
use uniplate::{Biplate, Tree, Uniplate};
26

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

            
33
/// Global generation of declaration contents.
34
///
35
/// Declaration pointers are shared across symbol tables, so an in-place update cannot cheaply
36
/// notify every table that contains the pointer. Symbol-table content caches compare against this
37
/// generation instead.
38
static DECLARATION_CONTENT_GENERATION: AtomicU64 = const { AtomicU64::new(1) };
39

            
40
/// Returns the generation shared by all mutable declaration contents.
41
2408343223
pub(crate) fn declaration_content_generation() -> u64 {
42
2408343223
    DECLARATION_CONTENT_GENERATION.load(Ordering::Acquire)
43
2408343223
}
44

            
45
/// Records that a declaration's contents may have changed.
46
47260506
fn mark_declaration_content_changed() {
47
47260506
    DECLARATION_CONTENT_GENERATION.fetch_add(1, Ordering::AcqRel);
48
47260506
}
49

            
50
/// Mutable access to part of a declaration that records a semantic change when released.
51
pub struct DeclarationMutGuard<'a, T: ?Sized> {
52
    inner: Option<MappedRwLockWriteGuard<'a, T>>,
53
}
54

            
55
impl<'a, T: ?Sized> DeclarationMutGuard<'a, T> {
56
    /// Wraps a mapped write guard so dropping it records a content change.
57
46088766
    fn new(inner: MappedRwLockWriteGuard<'a, T>) -> Self {
58
46088766
        Self { inner: Some(inner) }
59
46088766
    }
60
}
61

            
62
impl<T: ?Sized> Deref for DeclarationMutGuard<'_, T> {
63
    type Target = T;
64

            
65
264387
    fn deref(&self) -> &Self::Target {
66
264387
        self.inner.as_deref().expect("declaration guard is live")
67
264387
    }
68
}
69

            
70
impl<T: ?Sized> DerefMut for DeclarationMutGuard<'_, T> {
71
45824442
    fn deref_mut(&mut self) -> &mut Self::Target {
72
45824442
        self.inner
73
45824442
            .as_deref_mut()
74
45824442
            .expect("declaration guard is live")
75
45824442
    }
76
}
77

            
78
impl<T: ?Sized> Drop for DeclarationMutGuard<'_, T> {
79
46088766
    fn drop(&mut self) {
80
46088766
        drop(self.inner.take());
81
46088766
        mark_declaration_content_changed();
82
46088766
    }
83
}
84

            
85
#[doc(hidden)]
86
/// Resets the id counter of `DeclarationPtr` to 0.
87
///
88
/// This is probably always a bad idea.
89
pub fn reset_declaration_id_unchecked() {
90
    let _ = DECLARATION_PTR_ID_COUNTER.swap(0, Ordering::Relaxed);
91
}
92

            
93
/// A shared pointer to a [`Declaration`].
94
///
95
/// Two declaration pointers are equal if they point to the same underlying declaration.
96
///
97
/// # Id
98
///
99
///  The id of `DeclarationPtr` obeys the following invariants:
100
///
101
/// 1. Declaration pointers have the same id if they point to the same
102
///    underlying declaration.
103
///
104
/// 2. The id is immutable.
105
///
106
/// 3. Changing the declaration pointed to by the declaration pointer does not change the id. This
107
///    allows declarations to be updated by replacing them with a newer version of themselves.
108
///
109
/// `Ord`, `Hash`, and `Eq` use id for comparisons.
110
/// # Serde
111
///
112
/// Declaration pointers can be serialised using the following serializers:
113
///
114
/// + [`DeclarationPtrFull`](serde::DeclarationPtrFull)
115
/// + [`DeclarationPtrAsId`](serde::DeclarationPtrAsId)
116
///
117
/// See their documentation for more information.
118
#[derive(Clone, Debug)]
119
pub struct DeclarationPtr
120
where
121
    Self: Send + Sync,
122
{
123
    // the shared bits of the pointer
124
    inner: Arc<DeclarationPtrInner>,
125
}
126

            
127
// The bits of a declaration that are shared between all pointers.
128
#[derive(Debug)]
129
struct DeclarationPtrInner {
130
    // Identity hash/order key. Declaration content is mutable and is hashed separately by
131
    // `DeclarationPtr::content_hash`.
132
    // We don't want this to be mutable, as `HashMap` and `BTreeMap` rely on the hash or order of
133
    // keys to be unchanging.
134
    //
135
    // See:  https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key_type
136
    id: ObjId,
137

            
138
    // The contents of the declaration itself should be mutable.
139
    value: RwLock<Declaration>,
140

            
141
    /// Representations initialised for this declaration.
142
    representations: RwLock<ReprStore>,
143

            
144
    /// The declaration from which this auxiliary declaration was created.
145
    source: RwLock<Option<DeclarationPtr>>,
146
}
147

            
148
impl DeclarationPtrInner {
149
774102046
    fn new(value: RwLock<Declaration>) -> Arc<DeclarationPtrInner> {
150
774102046
        Arc::new(DeclarationPtrInner {
151
774102046
            id: ObjId {
152
774102046
                type_name: ustr::ustr(DeclarationPtr::TYPE_NAME),
153
774102046
                object_id: DECLARATION_PTR_ID_COUNTER.fetch_add(1, Ordering::Relaxed),
154
774102046
            },
155
774102046
            value,
156
774102046
            representations: RwLock::new(ReprStore::new()),
157
774102046
            source: RwLock::new(None),
158
774102046
        })
159
774102046
    }
160

            
161
    // SAFETY: only use if you are really really sure you arn't going to break the id invariants of
162
    // DeclarationPtr and HasId!
163
    fn new_with_id_unchecked(value: RwLock<Declaration>, id: ObjId) -> Arc<DeclarationPtrInner> {
164
        Arc::new(DeclarationPtrInner {
165
            id,
166
            value,
167
            representations: RwLock::new(ReprStore::new()),
168
            source: RwLock::new(None),
169
        })
170
    }
171
}
172

            
173
#[allow(dead_code)]
174
impl DeclarationPtr {
175
    /******************************/
176
    /*        Constructors        */
177
    /******************************/
178

            
179
    /// Creates a `DeclarationPtr` for the given `Declaration`.
180
700707563
    fn from_declaration(declaration: Declaration) -> DeclarationPtr {
181
700707563
        DeclarationPtr {
182
700707563
            inner: DeclarationPtrInner::new(RwLock::new(declaration)),
183
700707563
        }
184
700707563
    }
185

            
186
    /// Gets the declaration from which this auxiliary declaration was created.
187
740477234
    pub fn source(&self) -> RwLockReadGuard<'_, Option<DeclarationPtr>> {
188
740477234
        self.inner.source.read()
189
740477234
    }
190

            
191
    /// Mutates the declaration from which this auxiliary declaration was created.
192
56714122
    pub fn source_mut(&mut self) -> RwLockWriteGuard<'_, Option<DeclarationPtr>> {
193
56714122
        self.inner.source.write()
194
56714122
    }
195

            
196
    /// Gets the representations initialised for this declaration.
197
9885267316
    pub fn reprs(&self) -> RwLockReadGuard<'_, ReprStore> {
198
9885267316
        self.inner.representations.read()
199
9885267316
    }
200

            
201
    /// Mutates the representations initialised for this declaration.
202
14211472
    pub fn reprs_mut(&mut self) -> RwLockWriteGuard<'_, ReprStore> {
203
14211472
        self.inner.representations.write()
204
14211472
    }
205

            
206
    /// Gets a particular representation state, if it has been initialised.
207
9411798
    pub fn get_repr<T: ReprRule + ?Sized>(
208
9411798
        &self,
209
9411798
    ) -> Option<MappedRwLockReadGuard<'_, T::DeclLevel>> {
210
9411798
        RwLockReadGuard::try_map(self.inner.representations.read(), |reprs| reprs.get::<T>()).ok()
211
9411798
    }
212

            
213
    /// Creates a new declaration.
214
    ///
215
    /// # Examples
216
    ///
217
    /// ```
218
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,DeclarationKind,Domain,Range};
219
    ///
220
    /// // letting MyDomain be int(1..5)
221
    /// let declaration = DeclarationPtr::new(
222
    ///     Name::User("MyDomain".into()),
223
    ///     DeclarationKind::DomainLetting(Domain::int(vec![
224
    ///         Range::Bounded(1,5)])));
225
    /// ```
226
700707563
    pub fn new(name: Name, kind: DeclarationKind) -> DeclarationPtr {
227
700707563
        DeclarationPtr::from_declaration(Declaration::new(name, kind))
228
700707563
    }
229

            
230
    /// Creates a new find declaration.
231
    ///
232
    /// # Examples
233
    ///
234
    /// ```
235
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,DeclarationKind,Domain,Range};
236
    ///
237
    /// // find x: int(1..5)
238
    /// let declaration = DeclarationPtr::new_find(
239
    ///     Name::User("x".into()),
240
    ///     Domain::int(vec![Range::Bounded(1,5)]));
241
    ///
242
    /// ```
243
56040890
    pub fn new_find(name: Name, domain: DomainPtr) -> DeclarationPtr {
244
56040890
        let kind = DeclarationKind::Find(DecisionVariable::new(domain));
245
56040890
        DeclarationPtr::new(name, kind)
246
56040890
    }
247

            
248
    /// Creates a new auxiliary find declaration.
249
    ///
250
    /// Auxiliary finds are introduced by rewriting (for example, turning a top-level `exists`
251
    /// into constraints), and can also be written in Essence as `findAux`.
252
    /// They are decision variables for solvers, but must not be branched on during search:
253
    /// different assignments to them must not produce distinct user-facing solutions.
254
642313708
    pub fn new_find_auxiliary(name: Name, domain: DomainPtr) -> DeclarationPtr {
255
642313708
        let kind = DeclarationKind::FindAuxiliary(DecisionVariable::new(domain));
256
642313708
        DeclarationPtr::new(name, kind)
257
642313708
    }
258

            
259
    /// Creates a new given declaration.
260
    ///
261
    /// # Examples
262
    ///
263
    /// ```
264
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,DeclarationKind,Domain,Range};
265
    ///
266
    /// // given n: int(1..5)
267
    /// let declaration = DeclarationPtr::new_given(
268
    ///     Name::User("n".into()),
269
    ///     Domain::int(vec![Range::Bounded(1,5)]));
270
    ///
271
    /// ```
272
261957
    pub fn new_given(name: Name, domain: DomainPtr) -> DeclarationPtr {
273
261957
        let kind = DeclarationKind::Given(domain);
274
261957
        DeclarationPtr::new(name, kind)
275
261957
    }
276

            
277
    /// Creates a new quantified declaration for local comprehension scopes.
278
    ///
279
    /// Used when creating the quantified variable in a generator.
280
580186
    pub fn new_quantified(name: Name, domain: DomainPtr) -> DeclarationPtr {
281
580186
        DeclarationPtr::new(
282
580186
            name,
283
580186
            DeclarationKind::Quantified(Quantified {
284
580186
                domain,
285
580186
                generator: None,
286
580186
            }),
287
580186
        )
288
580186
    }
289

            
290
    /// Creates a quantified declaration backed by a generator declaration.
291
    ///
292
    /// This is used in comprehensions to refer to a quantified variable that is already defined using a generator.
293
    pub fn new_quantified_from_generator(decl: &DeclarationPtr) -> Option<DeclarationPtr> {
294
        let kind = DeclarationKind::Quantified(Quantified {
295
            domain: decl.domain()?,
296
            generator: Some(decl.clone()),
297
        });
298
        Some(DeclarationPtr::new(decl.name().clone(), kind))
299
    }
300

            
301
346675
    pub fn new_quantified_expr(name: Name, expr: Expression) -> DeclarationPtr {
302
346675
        let kind = DeclarationKind::QuantifiedExpr(expr);
303
346675
        DeclarationPtr::new(name, kind)
304
346675
    }
305

            
306
    /// Creates a new value letting declaration.
307
    ///
308
    /// # Examples
309
    ///
310
    /// ```
311
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,DeclarationKind,Domain,Range, Expression,
312
    /// Literal,Atom,Moo};
313
    /// use conjure_cp_core::{matrix_expr,ast::Metadata};
314
    ///
315
    /// // letting n be 10 + 10
316
    /// let ten = Expression::Atomic(Metadata::new(),Atom::Literal(Literal::Int(10)));
317
    /// let expression = Expression::Sum(Metadata::new(),Moo::new(matrix_expr![ten.clone(),ten]));
318
    /// let declaration = DeclarationPtr::new_value_letting(
319
    ///     Name::User("n".into()),
320
    ///     expression);
321
    ///
322
    /// ```
323
640036
    pub fn new_value_letting(name: Name, expression: Expression) -> DeclarationPtr {
324
640036
        let kind = DeclarationKind::ValueLetting(expression, None);
325
640036
        DeclarationPtr::new(name, kind)
326
640036
    }
327

            
328
    /// Creates a new value letting declaration with domain.
329
    ///
330
    /// # Examples
331
    ///
332
    /// ```
333
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,DeclarationKind,Domain,Range, Expression,
334
    /// Literal,Atom,Moo,DomainPtr,Metadata};
335
    /// use conjure_cp_core::{matrix_expr};
336
    ///
337
    /// // letting n be 10 + 10
338
    /// let ten = Expression::Atomic(Metadata::new(),Atom::Literal(Literal::Int(10)));
339
    /// let expression = Expression::Sum(Metadata::new(),Moo::new(matrix_expr![ten.clone(),ten]));
340
    /// let domain = Domain::bool();
341
    /// let declaration = DeclarationPtr::new_value_letting_with_domain(
342
    ///     Name::User("n".into()),
343
    ///     expression,
344
    ///     domain,
345
    /// );
346
    /// ```
347
438681
    pub fn new_value_letting_with_domain(
348
438681
        name: Name,
349
438681
        expression: Expression,
350
438681
        domain: DomainPtr,
351
438681
    ) -> DeclarationPtr {
352
438681
        let kind = DeclarationKind::ValueLetting(expression, Some(domain));
353
438681
        DeclarationPtr::new(name, kind)
354
438681
    }
355

            
356
    /// Creates a new domain letting declaration.
357
    ///
358
    /// # Examples
359
    ///
360
    /// ```
361
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,DeclarationKind,Domain,Range};
362
    ///
363
    /// // letting MyDomain be int(1..5)
364
    /// let declaration = DeclarationPtr::new_domain_letting(
365
    ///     Name::User("MyDomain".into()),
366
    ///     Domain::int(vec![Range::Bounded(1,5)]));
367
    ///
368
    /// ```
369
84929
    pub fn new_domain_letting(name: Name, domain: DomainPtr) -> DeclarationPtr {
370
84929
        let kind = DeclarationKind::DomainLetting(domain);
371
84929
        DeclarationPtr::new(name, kind)
372
84929
    }
373

            
374
    /// Creates a new enumerated type declaration
375
    /// TODO: Example
376
30
    pub fn new_enumerated(name: Name, ty: Moo<EnumeratedType>) -> DeclarationPtr {
377
30
        let kind = DeclarationKind::EnumeratedType(ty);
378
30
        DeclarationPtr::new(name, kind)
379
30
    }
380

            
381
    /// Creates a new unnamed type declaration
382
    /// TODO: Example
383
36
    pub fn new_unnamed(name: Name, size: u32) -> DeclarationPtr {
384
36
        let kind = DeclarationKind::UnnamedType(size);
385
36
        DeclarationPtr::new(name, kind)
386
36
    }
387

            
388
    /**********************************************/
389
    /*        Declaration accessor methods        */
390
    /**********************************************/
391

            
392
    /// Gets the domain of the declaration, if it has one.
393
    ///
394
    /// # Examples
395
    ///
396
    /// ```
397
    /// use conjure_cp_core::ast::{DeclarationPtr, Name, Domain, Range, GroundDomain};
398
    ///
399
    /// // find a: int(1..5)
400
    /// let declaration = DeclarationPtr::new_find(Name::User("a".into()),Domain::int(vec![Range::Bounded(1,5)]));
401
    ///
402
    /// assert!(declaration.domain().is_some_and(|x| x.as_ground().unwrap() == &GroundDomain::Int(vec![Range::Bounded(1,5)], None)))
403
    ///
404
    /// ```
405
16365193778
    pub fn domain(&self) -> Option<DomainPtr> {
406
16365193778
        let declaration = self.read();
407
        // Expressions stored inside a declaration (as opposed to the constraint tree the rewrite
408
        // engine walks) can be mutated in place by substitution utilities that never touch
409
        // the constraint-tree metadata cache, so `domain_of`'s cache would go stale silently for
410
        // them. Use the uncached path here.
411
16365193778
        match &declaration.kind {
412
            DeclarationKind::Find(var) | DeclarationKind::FindAuxiliary(var) => {
413
16304233564
                Some(var.domain_of())
414
            }
415
            DeclarationKind::ValueLetting(e, domain) => {
416
27896524
                domain.clone().or_else(|| e.domain_of_uncached())
417
            }
418
10848
            DeclarationKind::TemporaryValueLetting(e) => e.domain_of_uncached(),
419
13939699
            DeclarationKind::DomainLetting(domain) => Some(domain.clone()),
420
1492217
            DeclarationKind::Given(domain) => Some(domain.clone()),
421
17347151
            DeclarationKind::Quantified(inner) => Some(inner.domain.clone()),
422
273571
            DeclarationKind::QuantifiedExpr(expr) => expr.domain_of_uncached()?.element_domain(),
423
66
            DeclarationKind::EnumeratedType(et) => Some(et.to_domain()),
424
138
            DeclarationKind::UnnamedType(size) => Some(
425
138
                Moo::new(crate::ast::GroundDomain::UnnamedType(Moo::new(
426
138
                    crate::ast::unnamed::UnnamedType {
427
138
                        name: declaration.name.clone(),
428
138
                        size: *size,
429
138
                    },
430
138
                )))
431
138
                .into(),
432
138
            ),
433
        }
434
16365193778
    }
435

            
436
    /// Returns true if this declaration is an auxiliary find.
437
    ///
438
    /// Auxiliary finds are solver variables that must not be included in the search/branching
439
    /// order (see [`DeclarationKind::FindAuxiliary`]).
440
81446704
    pub fn is_find_auxiliary(&self) -> bool {
441
81446704
        matches!(
442
81446704
            &self.kind() as &DeclarationKind,
443
            DeclarationKind::FindAuxiliary(_)
444
        )
445
81446704
    }
446

            
447
    /// Gets the domain of the declaration and fully resolve it
448
3750453858
    pub fn resolved_domain(&self) -> Option<Moo<GroundDomain>> {
449
3750453858
        self.domain()?.resolve().ok()
450
3750453858
    }
451

            
452
    /// Gets the kind of the declaration.
453
    ///
454
    /// # Examples
455
    ///
456
    /// ```
457
    /// use conjure_cp_core::ast::{DeclarationPtr,DeclarationKind,Name,Domain,Range};
458
    ///
459
    /// // find a: int(1..5)
460
    /// let declaration = DeclarationPtr::new_find(Name::User("a".into()),Domain::int(vec![Range::Bounded(1,5)]));
461
    /// assert!(matches!(&declaration.kind() as &DeclarationKind, DeclarationKind::Find(_)))
462
    /// ```
463
9576701100
    pub fn kind(&self) -> MappedRwLockReadGuard<'_, DeclarationKind> {
464
9576701100
        self.map(|x| &x.kind)
465
9576701100
    }
466

            
467
    /// Gets the name of the declaration.
468
    ///
469
    /// # Examples
470
    ///
471
    /// ```
472
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,Domain,Range};
473
    ///
474
    /// // find a: int(1..5)
475
    /// let declaration = DeclarationPtr::new_find(Name::User("a".into()),Domain::int(vec![Range::Bounded(1,5)]));
476
    ///
477
    /// assert_eq!(&declaration.name() as &Name, &Name::User("a".into()))
478
    /// ```
479
6634774767
    pub fn name(&self) -> MappedRwLockReadGuard<'_, Name> {
480
6634774767
        self.map(|x| &x.name)
481
6634774767
    }
482

            
483
    /// This declaration as a decision variable, if it is one.
484
    ///
485
    /// Both user [`DeclarationKind::Find`] and rewriter-introduced
486
    /// [`DeclarationKind::FindAuxiliary`] declarations are treated as decision variables.
487
5701930100
    pub fn as_find(&self) -> Option<MappedRwLockReadGuard<'_, DecisionVariable>> {
488
5701930100
        RwLockReadGuard::try_map(self.read(), |x| match &x.kind {
489
5687310797
            DeclarationKind::Find(var) | DeclarationKind::FindAuxiliary(var) => Some(var),
490
14619303
            _ => None,
491
5701930100
        })
492
        .ok()
493
5701930100
    }
494

            
495
    /// This declaration as a mutable decision variable, if it is one.
496
    ///
497
    /// Both user [`DeclarationKind::Find`] and rewriter-introduced
498
    /// [`DeclarationKind::FindAuxiliary`] declarations are treated as decision variables.
499
575090
    pub fn as_find_mut(&mut self) -> Option<DeclarationMutGuard<'_, DecisionVariable>> {
500
575090
        RwLockWriteGuard::try_map(self.write(), |x| match &mut x.kind {
501
264516
            DeclarationKind::Find(var) | DeclarationKind::FindAuxiliary(var) => Some(var),
502
310574
            _ => None,
503
575090
        })
504
        .ok()
505
575090
        .map(DeclarationMutGuard::new)
506
575090
    }
507

            
508
    /// This declaration as a domain letting, if it is one.
509
31664375
    pub fn as_domain_letting(&self) -> Option<MappedRwLockReadGuard<'_, DomainPtr>> {
510
31664375
        RwLockReadGuard::try_map(self.read(), |x| {
511
31664375
            if let DeclarationKind::DomainLetting(domain) = &x.kind {
512
31664344
                Some(domain)
513
            } else {
514
31
                None
515
            }
516
31664375
        })
517
        .ok()
518
31664375
    }
519

            
520
    /// This declaration as a mutable domain letting, if it is one.
521
    pub fn as_domain_letting_mut(&mut self) -> Option<DeclarationMutGuard<'_, DomainPtr>> {
522
        RwLockWriteGuard::try_map(self.write(), |x| {
523
            if let DeclarationKind::DomainLetting(domain) = &mut x.kind {
524
                Some(domain)
525
            } else {
526
                None
527
            }
528
        })
529
        .ok()
530
        .map(DeclarationMutGuard::new)
531
    }
532

            
533
    /// This declaration as a value letting, if it is one.
534
4998656867
    pub fn as_value_letting(&self) -> Option<MappedRwLockReadGuard<'_, Expression>> {
535
4998656867
        RwLockReadGuard::try_map(self.read(), |x| {
536
4998656867
            if let DeclarationKind::ValueLetting(expression, _)
537
4998656867
            | DeclarationKind::TemporaryValueLetting(expression) = &x.kind
538
            {
539
73865898
                Some(expression)
540
            } else {
541
4924790969
                None
542
            }
543
4998656867
        })
544
        .ok()
545
4998656867
    }
546

            
547
    /// This declaration as a mutable value letting, if it is one.
548
2161940
    pub fn as_value_letting_mut(&mut self) -> Option<DeclarationMutGuard<'_, Expression>> {
549
2161940
        RwLockWriteGuard::try_map(self.write(), |x| {
550
2161940
            if let DeclarationKind::ValueLetting(expression, _)
551
2161940
            | DeclarationKind::TemporaryValueLetting(expression) = &mut x.kind
552
            {
553
2161940
                Some(expression)
554
            } else {
555
                None
556
            }
557
2161940
        })
558
        .ok()
559
2161940
        .map(DeclarationMutGuard::new)
560
2161940
    }
561

            
562
    /// This declaration as a given statement, if it is one.
563
850216
    pub fn as_given(&self) -> Option<MappedRwLockReadGuard<'_, DomainPtr>> {
564
850216
        RwLockReadGuard::try_map(self.read(), |x| {
565
850216
            if let DeclarationKind::Given(domain) = &x.kind {
566
521861
                Some(domain)
567
            } else {
568
328355
                None
569
            }
570
850216
        })
571
        .ok()
572
850216
    }
573

            
574
    /// This declaration as a mutable given statement, if it is one.
575
    pub fn as_given_mut(&mut self) -> Option<DeclarationMutGuard<'_, DomainPtr>> {
576
        RwLockWriteGuard::try_map(self.write(), |x| {
577
            if let DeclarationKind::Given(domain) = &mut x.kind {
578
                Some(domain)
579
            } else {
580
                None
581
            }
582
        })
583
        .ok()
584
        .map(DeclarationMutGuard::new)
585
    }
586

            
587
    /// This declaration as a quantified expression, if it is one.
588
4815883
    pub fn as_quantified_expr(&self) -> Option<MappedRwLockReadGuard<'_, Expression>> {
589
4815883
        RwLockReadGuard::try_map(self.read(), |x| {
590
4815883
            if let DeclarationKind::QuantifiedExpr(expr) = &x.kind {
591
4815883
                Some(expr)
592
            } else {
593
                None
594
            }
595
4815883
        })
596
        .ok()
597
4815883
    }
598

            
599
    /// This declaration as a mutable quantified expression, if it is one.
600
    pub fn as_quantified_expr_mut(&mut self) -> Option<DeclarationMutGuard<'_, Expression>> {
601
        RwLockWriteGuard::try_map(self.write(), |x| {
602
            if let DeclarationKind::QuantifiedExpr(expr) = &mut x.kind {
603
                Some(expr)
604
            } else {
605
                None
606
            }
607
        })
608
        .ok()
609
        .map(DeclarationMutGuard::new)
610
    }
611

            
612
    /// This declaration as an enumerated type, if it is one.
613
205870
    pub fn as_enumerated_type(&self) -> Option<MappedRwLockReadGuard<'_, Moo<EnumeratedType>>> {
614
205870
        RwLockReadGuard::try_map(self.read(), |x| {
615
205870
            if let DeclarationKind::EnumeratedType(e) = &x.kind {
616
12
                Some(e)
617
            } else {
618
205858
                None
619
            }
620
205870
        })
621
        .ok()
622
205870
    }
623

            
624
    /// This declaration as a mutable enumerated type, if it is one.
625
    pub fn as_enumerated_type_mut(
626
        &mut self,
627
    ) -> Option<DeclarationMutGuard<'_, Moo<EnumeratedType>>> {
628
        RwLockWriteGuard::try_map(self.write(), |x| {
629
            if let DeclarationKind::EnumeratedType(e) = &mut x.kind {
630
                Some(e)
631
            } else {
632
                None
633
            }
634
        })
635
        .ok()
636
        .map(DeclarationMutGuard::new)
637
    }
638

            
639
    /// This declaration as an unnamed type, if it is one.
640
205906
    pub fn as_unnamed_type(&self) -> Option<MappedRwLockReadGuard<'_, u32>> {
641
205906
        RwLockReadGuard::try_map(self.read(), |x| {
642
205906
            if let DeclarationKind::UnnamedType(e) = &x.kind {
643
42
                Some(e)
644
            } else {
645
205864
                None
646
            }
647
205906
        })
648
        .ok()
649
205906
    }
650

            
651
    /// This declaration as a mutable unnamed type, if it is one.
652
    pub fn as_unnamed_type_mut(&mut self) -> Option<DeclarationMutGuard<'_, u32>> {
653
        RwLockWriteGuard::try_map(self.write(), |x| {
654
            if let DeclarationKind::UnnamedType(e) = &mut x.kind {
655
                Some(e)
656
            } else {
657
                None
658
            }
659
        })
660
        .ok()
661
        .map(DeclarationMutGuard::new)
662
    }
663

            
664
    /// Changes the name in this declaration, returning the old one.
665
    ///
666
    /// # Examples
667
    ///
668
    /// ```
669
    /// use conjure_cp_core::ast::{DeclarationPtr, Domain, Range, Name};
670
    ///
671
    /// // find a: int(1..5)
672
    /// let mut declaration = DeclarationPtr::new_find(Name::User("a".into()),Domain::int(vec![Range::Bounded(1,5)]));
673
    ///
674
    /// let old_name = declaration.replace_name(Name::User("b".into()));
675
    /// assert_eq!(old_name,Name::User("a".into()));
676
    /// assert_eq!(&declaration.name() as &Name,&Name::User("b".into()));
677
    /// ```
678
93
    pub fn replace_name(&mut self, name: Name) -> Name {
679
93
        let mut current_name = self.map_mut(|decl| &mut decl.name);
680
93
        std::mem::replace(&mut *current_name, name)
681
93
    }
682

            
683
    /// Replaces the underlying declaration kind and returns the previous kind.
684
    /// Note: this affects all cloned `DeclarationPtr`s pointing to the same declaration.
685
43662217
    pub fn replace_kind(&mut self, kind: DeclarationKind) -> DeclarationKind {
686
43662217
        let mut current_kind = self.map_mut(|decl| &mut decl.kind);
687
43662217
        std::mem::replace(&mut *current_kind, kind)
688
43662217
    }
689

            
690
    /*****************************************/
691
    /*        Pointer utility methods        */
692
    /*****************************************/
693

            
694
    // These are mostly wrappers over RefCell, Ref, and RefMut methods, re-exported here for
695
    // convenience.
696

            
697
    /// Read the underlying [Declaration].
698
    ///
699
    /// Will block the current thread until no other thread has a write lock.
700
    /// Attempting to get a read lock if the current thread already has one
701
    /// **will** cause it to deadlock.
702
    /// The lock is released when the returned guard goes out of scope.
703
47242112706
    fn read(&self) -> RwLockReadGuard<'_, Declaration> {
704
47242112706
        self.inner.value.read()
705
47242112706
    }
706

            
707
    /// Write the underlying [Declaration].
708
    ///
709
    /// Will block the current thread until no other thread has a read or write lock.
710
    /// The lock is released when the returned guard goes out of scope.
711
47571080
    fn write(&mut self) -> RwLockWriteGuard<'_, Declaration> {
712
47571080
        self.inner.value.write()
713
47571080
    }
714

            
715
    /// Creates a new declaration pointer with the same contents as `self` that is not shared with
716
    /// anyone else.
717
    ///
718
    /// As the resulting pointer is unshared, it will have a new id.
719
    ///
720
    /// # Examples
721
    ///
722
    /// ```
723
    /// use conjure_cp_core::ast::{DeclarationPtr,Name,Domain,Range};
724
    ///
725
    /// // find a: int(1..5)
726
    /// let declaration = DeclarationPtr::new_find(Name::User("a".into()),Domain::int(vec![Range::Bounded(1,5)]));
727
    ///
728
    /// let mut declaration2 = declaration.clone();
729
    ///
730
    /// declaration2.replace_name(Name::User("b".into()));
731
    ///
732
    /// assert_eq!(&declaration.name() as &Name, &Name::User("b".into()));
733
    /// assert_eq!(&declaration2.name() as &Name, &Name::User("b".into()));
734
    ///
735
    /// declaration2 = declaration2.detach();
736
    ///
737
    /// assert_eq!(&declaration2.name() as &Name, &Name::User("b".into()));
738
    ///
739
    /// declaration2.replace_name(Name::User("c".into()));
740
    ///
741
    /// assert_eq!(&declaration.name() as &Name, &Name::User("b".into()));
742
    /// assert_eq!(&declaration2.name() as &Name, &Name::User("c".into()));
743
    /// ```
744
73394483
    pub fn detach(self) -> DeclarationPtr {
745
        // despite having the same contents, the new declaration pointer is unshared, so it should
746
        // get a new id.
747
73394483
        let value = self.inner.value.read().clone();
748
73394483
        let representations = self.inner.representations.read().clone();
749
73394483
        let source = self.inner.source.read().clone();
750
73394483
        let detached = DeclarationPtr {
751
73394483
            inner: DeclarationPtrInner::new(RwLock::new(value)),
752
73394483
        };
753
73394483
        *detached.inner.representations.write() = representations;
754
73394483
        *detached.inner.source.write() = source;
755
73394483
        detached
756
73394483
    }
757

            
758
    /// Applies `f` to the declaration, returning the result as a reference.
759
16211475867
    fn map<U>(&self, f: impl FnOnce(&Declaration) -> &U) -> MappedRwLockReadGuard<'_, U> {
760
16211475867
        RwLockReadGuard::map(self.read(), f)
761
16211475867
    }
762

            
763
    /// Applies mutable function `f` to the declaration, returning the result as a mutable reference.
764
43662310
    fn map_mut<U>(
765
43662310
        &mut self,
766
43662310
        f: impl FnOnce(&mut Declaration) -> &mut U,
767
43662310
    ) -> DeclarationMutGuard<'_, U> {
768
43662310
        DeclarationMutGuard::new(RwLockWriteGuard::map(self.write(), f))
769
43662310
    }
770

            
771
    /// Replaces the declaration with a new one, returning the old value, without deinitialising
772
    /// either one.
773
1171740
    pub fn replace(&mut self, declaration: Declaration) -> Declaration {
774
1171740
        let mut guard = self.write();
775
1171740
        let ans = mem::replace(&mut *guard, declaration);
776
1171740
        drop(guard);
777
1171740
        mark_declaration_content_changed();
778
1171740
        ans
779
1171740
    }
780

            
781
    /// Hashes the declaration contents rather than the stable declaration pointer id.
782
    ///
783
    /// Pointer hashing intentionally remains id-based for map/set invariants. This helper is for
784
    /// rewrite caches that need to be invalidated when the declaration value behind a reference
785
    /// changes.
786
3199305898
    pub(crate) fn content_hash(&self) -> u64 {
787
3199305898
        let mut hasher = DefaultHasher::new();
788
3199305898
        let mut seen = BTreeSet::new();
789
3199305898
        self.hash_content(&mut hasher, &mut seen);
790
3199305898
        hasher.finish()
791
3199305898
    }
792

            
793
    /// Compares current declaration contents without considering pointer identity.
794
8147692286
    pub(crate) fn content_eq(&self, other: &Self) -> bool {
795
8147692286
        if self.id() == other.id() {
796
8147692286
            return true;
797
        }
798
        let this = self.read().clone();
799
        let other = other.read().clone();
800
        this == other
801
8147692286
    }
802

            
803
    /// Hashes this declaration's value into `state`, guarding against declaration-reference cycles.
804
3199305898
    fn hash_content<H: Hasher>(&self, state: &mut H, seen: &mut BTreeSet<ObjId>) {
805
3199305898
        let id = self.id();
806
3199305898
        if !seen.insert(id.clone()) {
807
            "recursive-declaration".hash(state);
808
            return;
809
3199305898
        }
810

            
811
3199305898
        let declaration = self.read();
812
3199305898
        declaration.name.hash(state);
813
3199305898
        declaration.kind.hash_content(state, seen);
814
3199305898
        seen.remove(&id);
815
3199305898
    }
816
}
817

            
818
impl CategoryOf for DeclarationPtr {
819
26147647
    fn category_of(&self) -> Category {
820
26147647
        match &self.kind() as &DeclarationKind {
821
            DeclarationKind::Find(decision_variable)
822
26000770
            | DeclarationKind::FindAuxiliary(decision_variable) => decision_variable.category_of(),
823
            DeclarationKind::ValueLetting(expression, _)
824
62953
            | DeclarationKind::TemporaryValueLetting(expression) => expression.category_of(),
825
            DeclarationKind::DomainLetting(_) => Category::Constant,
826
            DeclarationKind::Given(_) => Category::Parameter,
827
82684
            DeclarationKind::Quantified(..) => Category::Quantified,
828
1240
            DeclarationKind::QuantifiedExpr(..) => Category::Quantified,
829
            DeclarationKind::EnumeratedType(_) | DeclarationKind::UnnamedType(_) => {
830
                Category::Constant
831
            }
832
        }
833
26147647
    }
834
}
835
impl HasId for DeclarationPtr {
836
    const TYPE_NAME: &'static str = "DeclarationPtrInner";
837
19570394281
    fn id(&self) -> ObjId {
838
19570394281
        self.inner.id.clone()
839
19570394281
    }
840
}
841

            
842
impl DefaultWithId for DeclarationPtr {
843
    fn default_with_id(id: ObjId) -> Self {
844
        DeclarationPtr {
845
            inner: DeclarationPtrInner::new_with_id_unchecked(
846
                RwLock::new(Declaration {
847
                    name: Name::User("_UNKNOWN".into()),
848
                    kind: DeclarationKind::ValueLetting(false.into(), None),
849
                }),
850
                id,
851
            ),
852
        }
853
    }
854
}
855

            
856
impl Typeable for DeclarationPtr {
857
    fn return_type(&self) -> ReturnType {
858
        let declaration = self.read();
859
        match &declaration.kind {
860
            DeclarationKind::Find(var) | DeclarationKind::FindAuxiliary(var) => var.return_type(),
861
            DeclarationKind::ValueLetting(expression, _)
862
            | DeclarationKind::TemporaryValueLetting(expression) => expression.return_type(),
863
            DeclarationKind::DomainLetting(domain) => domain.return_type(),
864
            DeclarationKind::Given(domain) => domain.return_type(),
865
            DeclarationKind::Quantified(inner) => inner.domain.return_type(),
866
            DeclarationKind::QuantifiedExpr(expr) => expr.return_type(),
867
            DeclarationKind::EnumeratedType(ty) => ReturnType::EnumeratedType(ty.clone()),
868
            DeclarationKind::UnnamedType(size) => {
869
                ReturnType::UnnamedType(Moo::new(crate::ast::unnamed::UnnamedType {
870
                    name: declaration.name.clone(),
871
                    size: *size,
872
                }))
873
            }
874
        }
875
    }
876
}
877

            
878
impl Uniplate for DeclarationPtr {
879
14013109
    fn uniplate(&self) -> (Tree<Self>, Box<dyn Fn(Tree<Self>) -> Self>) {
880
14013109
        let decl = self.read();
881
14013109
        let (tree, recons) = Biplate::<DeclarationPtr>::biplate(&decl as &Declaration);
882

            
883
14013109
        let self2 = self.clone();
884
        (
885
14013109
            tree,
886
14013109
            Box::new(move |x| {
887
809192
                let mut self3 = self2.clone();
888
809192
                let inner = recons(x);
889
809192
                let _ = self3.replace(inner);
890
809192
                self3
891
809192
            }),
892
        )
893
14013109
    }
894
}
895

            
896
impl<To> Biplate<To> for DeclarationPtr
897
where
898
    Declaration: Biplate<To>,
899
    To: Uniplate,
900
{
901
727801432
    fn biplate(&self) -> (Tree<To>, Box<dyn Fn(Tree<To>) -> Self>) {
902
727801432
        if TypeId::of::<To>() == TypeId::of::<Self>() {
903
            unsafe {
904
14013109
                let self_as_to = std::mem::transmute::<&Self, &To>(self).clone();
905
                (
906
14013109
                    Tree::One(self_as_to),
907
14013109
                    Box::new(move |x| {
908
574956
                        let Tree::One(x) = x else { panic!() };
909

            
910
574956
                        let x_as_self = std::mem::transmute::<&To, &Self>(&x);
911
574956
                        x_as_self.clone()
912
574956
                    }),
913
                )
914
            }
915
        } else {
916
            // call biplate on the enclosed declaration
917
713788323
            let decl = self.read();
918
713788323
            let (tree, recons) = Biplate::<To>::biplate(&decl as &Declaration);
919

            
920
713788323
            let self2 = self.clone();
921
            (
922
713788323
                tree,
923
713788323
                Box::new(move |x| {
924
101719
                    let mut self3 = self2.clone();
925
101719
                    let inner = recons(x);
926
101719
                    let _ = self3.replace(inner);
927
101719
                    self3
928
101719
                }),
929
            )
930
        }
931
727801432
    }
932
}
933

            
934
type ReferenceTree = Tree<Reference>;
935
type ReferenceReconstructor<T> = Box<dyn Fn(ReferenceTree) -> T>;
936

            
937
impl Biplate<Reference> for DeclarationPtr {
938
2073531309
    fn biplate(&self) -> (ReferenceTree, ReferenceReconstructor<Self>) {
939
2073531309
        let (tree, recons_kind) = biplate_declaration_kind_references(self.kind().clone());
940

            
941
2073531309
        let self2 = self.clone();
942
        (
943
2073531309
            tree,
944
2073531309
            Box::new(move |x| {
945
111135
                let mut self3 = self2.clone();
946
111135
                let _ = self3.replace_kind(recons_kind(x));
947
111135
                self3
948
111135
            }),
949
        )
950
2073531309
    }
951
}
952

            
953
2073051279
fn biplate_domain_ptr_references(
954
2073051279
    domain: DomainPtr,
955
2073051279
) -> (ReferenceTree, ReferenceReconstructor<DomainPtr>) {
956
2073051279
    let domain_inner = domain.as_ref().clone();
957
2073051279
    let (tree, recons_domain) = Biplate::<Reference>::biplate(&domain_inner);
958
2073051279
    (tree, Box::new(move |x| Moo::new(recons_domain(x))))
959
2073051279
}
960

            
961
2073531309
fn biplate_declaration_kind_references(
962
2073531309
    kind: DeclarationKind,
963
2073531309
) -> (ReferenceTree, ReferenceReconstructor<DeclarationKind>) {
964
2073531309
    match kind {
965
        DeclarationKind::Find(var) => {
966
134186731
            let (tree, recons_domain) = biplate_domain_ptr_references(var.domain.clone());
967
            (
968
134186731
                tree,
969
134186731
                Box::new(move |x| {
970
51057
                    let mut var2 = var.clone();
971
51057
                    var2.domain = recons_domain(x);
972
51057
                    DeclarationKind::Find(var2)
973
51057
                }),
974
            )
975
        }
976
        DeclarationKind::FindAuxiliary(var) => {
977
1938068322
            let (tree, recons_domain) = biplate_domain_ptr_references(var.domain.clone());
978
            (
979
1938068322
                tree,
980
1938068322
                Box::new(move |x| {
981
60078
                    let mut var2 = var.clone();
982
60078
                    var2.domain = recons_domain(x);
983
60078
                    DeclarationKind::FindAuxiliary(var2)
984
60078
                }),
985
            )
986
        }
987
        DeclarationKind::Given(domain) => {
988
186755
            let (tree, recons_domain) = biplate_domain_ptr_references(domain);
989
            (
990
186755
                tree,
991
186755
                Box::new(move |x| DeclarationKind::Given(recons_domain(x))),
992
            )
993
        }
994
        DeclarationKind::DomainLetting(domain) => {
995
609471
            let (tree, recons_domain) = biplate_domain_ptr_references(domain);
996
            (
997
609471
                tree,
998
609471
                Box::new(move |x| DeclarationKind::DomainLetting(recons_domain(x))),
999
            )
        }
        DeclarationKind::ValueLetting(expression, domain) => {
480030
            let (tree, recons_expr) = Biplate::<Reference>::biplate(&expression);
            (
480030
                tree,
480030
                Box::new(move |x| DeclarationKind::ValueLetting(recons_expr(x), domain.clone())),
            )
        }
        DeclarationKind::TemporaryValueLetting(expression) => {
            let (tree, recons_expr) = Biplate::<Reference>::biplate(&expression);
            (
                tree,
                Box::new(move |x| DeclarationKind::TemporaryValueLetting(recons_expr(x))),
            )
        }
        DeclarationKind::Quantified(quantified) => {
            let (domain_tree, recons_domain) =
                biplate_domain_ptr_references(quantified.domain.clone());
            let (generator_tree, recons_generator) = if let Some(generator) = quantified.generator()
            {
                let generator = generator.clone();
                let (tree, recons_declaration) = Biplate::<Reference>::biplate(&generator);
                (
                    tree,
                    Box::new(move |x| Some(recons_declaration(x)))
                        as ReferenceReconstructor<Option<DeclarationPtr>>,
                )
            } else {
                (
                    Tree::Zero,
                    Box::new(|_| None) as ReferenceReconstructor<Option<DeclarationPtr>>,
                )
            };
            (
                Tree::Many(VecDeque::from([domain_tree, generator_tree])),
                Box::new(move |x| {
                    let Tree::Many(mut children) = x else {
                        panic!("unexpected biplate tree shape for quantified declaration")
                    };
                    let domain = children.pop_front().unwrap_or(Tree::Zero);
                    let generator = children.pop_front().unwrap_or(Tree::Zero);
                    let mut quantified2 = quantified.clone();
                    quantified2.domain = recons_domain(domain);
                    quantified2.generator = recons_generator(generator);
                    DeclarationKind::Quantified(quantified2)
                }),
            )
        }
        DeclarationKind::QuantifiedExpr(expr) => {
            let (tree, recons_expr) = Biplate::<Reference>::biplate(&expr);
            (
                tree,
                Box::new(move |x| DeclarationKind::QuantifiedExpr(recons_expr(x))),
            )
        }
        kind @ (DeclarationKind::EnumeratedType(_) | DeclarationKind::UnnamedType(_)) => {
            (Tree::Zero, Box::new(move |_| kind.clone()))
        }
    }
2073531309
}
impl IdPtr for DeclarationPtr {
    type Data = Declaration;
6514
    fn get_data(&self) -> Self::Data {
6514
        self.read().clone()
6514
    }
    fn with_id_and_data(id: ObjId, data: Self::Data) -> Self {
        Self {
            inner: DeclarationPtrInner::new_with_id_unchecked(RwLock::new(data), id),
        }
    }
}
impl Ord for DeclarationPtr {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.inner.id.cmp(&other.inner.id)
    }
}
impl PartialOrd for DeclarationPtr {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl PartialEq for DeclarationPtr {
124398475
    fn eq(&self, other: &Self) -> bool {
124398475
        self.inner.id == other.inner.id
124398475
    }
}
impl Eq for DeclarationPtr {}
impl std::hash::Hash for DeclarationPtr {
7812576
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // invariant: x == y -> hash(x) == hash(y)
7812576
        self.inner.id.hash(state);
7812576
    }
}
impl Display for DeclarationPtr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let value: &Declaration = &self.read();
        value.fmt(f)
    }
}
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize, Eq, Uniplate)]
#[biplate(to=Expression)]
#[biplate(to=DeclarationPtr)]
#[biplate(to=Name)]
/// The contents of a declaration
pub struct Declaration {
    /// The name of the declared symbol.
    name: Name,
    /// The kind of the declaration.
    kind: DeclarationKind,
}
impl Declaration {
    /// Creates a new declaration.
700968392
    pub fn new(name: Name, kind: DeclarationKind) -> Declaration {
700968392
        Declaration { name, kind }
700968392
    }
}
/// A specific kind of declaration.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Uniplate)]
#[biplate(to=Expression)]
#[biplate(to=DeclarationPtr)]
#[biplate(to=Declaration)]
pub enum DeclarationKind {
    Find(DecisionVariable),
    /// A rewriter-introduced or `findAux`-declared decision variable that must not be branched on
    /// during search.
    ///
    /// Used for auxiliaries such as those created when rewriting `exists` into constraints.
    FindAuxiliary(DecisionVariable),
    Given(DomainPtr),
    Quantified(Quantified),
    QuantifiedExpr(Expression),
    /// Carries an optional domain so instantiated `given`s can retain their declared domain.
    ValueLetting(Expression, Option<DomainPtr>),
    DomainLetting(DomainPtr),
    /// A short-lived value binding used internally during rewrites (e.g. comprehension unrolling).
    ///
    /// Unlike `ValueLetting`, this is not intended to represent a user-visible top-level `letting`.
    TemporaryValueLetting(Expression),
    /// An enumerated type.
    EnumeratedType(Moo<EnumeratedType>),
    /// An unnamed type.
    UnnamedType(u32),
}
impl DeclarationKind {
    /// Hashes declaration-kind contents without using declaration pointer identity.
3199305898
    fn hash_content<H: Hasher>(&self, state: &mut H, seen: &mut BTreeSet<ObjId>) {
3199305898
        mem::discriminant(self).hash(state);
3199305898
        match self {
            DeclarationKind::Find(var) | DeclarationKind::FindAuxiliary(var) => {
3176510251
                var.domain.hash(state);
3176510251
                for representation in &var.representations {
                    for repr in representation {
                        repr.repr_name().hash(state);
                        if let Ok(declarations) = repr.declaration_down() {
                            for declaration in declarations {
                                declaration.hash_content(state, seen);
                            }
                        } else {
                            "unavailable-representation-declarations".hash(state);
                        }
                    }
                }
            }
            DeclarationKind::Given(domain) | DeclarationKind::DomainLetting(domain) => {
1371788
                domain.hash(state);
            }
            DeclarationKind::Quantified(quantified) => {
687489
                quantified.domain.hash(state);
687489
                if let Some(generator) = quantified.generator() {
                    generator.hash_content(state, seen);
687489
                }
            }
            DeclarationKind::QuantifiedExpr(expr)
            | DeclarationKind::TemporaryValueLetting(expr) => {
758432
                expr.cached_content_hash().hash(state);
758432
                expr.to_string().hash(state);
            }
96
            DeclarationKind::EnumeratedType(ty) => ty.hash(state),
84
            DeclarationKind::UnnamedType(size) => size.hash(state),
            DeclarationKind::ValueLetting(expr, domain) => {
19977758
                expr.cached_content_hash().hash(state);
19977758
                expr.to_string().hash(state);
19977758
                domain.hash(state);
            }
        }
3199305898
    }
}
#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Uniplate)]
pub struct Quantified {
    domain: DomainPtr,
    #[serde_as(as = "Option<PtrAsInner>")]
    generator: Option<DeclarationPtr>,
}
impl Quantified {
23188
    pub fn domain(&self) -> &DomainPtr {
23188
        &self.domain
23188
    }
22012966
    pub fn generator(&self) -> Option<&DeclarationPtr> {
22012966
        self.generator.as_ref()
22012966
    }
}