refinement-types 0.3.0

Refinement types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Logical operations on predicates.

use core::{fmt, marker::PhantomData};

#[cfg(feature = "diagnostics")]
use miette::Diagnostic;

use thiserror::Error;

use crate::{
    core::{ErrorCore, Predicate},
    static_str::StaticStr,
};

/// Represents predicates that are always satisfied.
pub struct True {
    private: PhantomData<()>,
}

/// Represents errors that are never encountered.
///
/// This is essentially `!`, the never type.
#[derive(Debug, Error)]
#[error("never errors")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(logic::never), help("this error is never returned"))
)]
pub enum NeverError {}

/// The `anything` string.
pub const ANYTHING: StaticStr = "anything";

/// The `true` string.
pub const TRUE: StaticStr = "true";

impl<T: ?Sized> Predicate<T> for True {
    type Error = NeverError;

    fn check(_value: &T) -> Result<(), Self::Error> {
        Ok(())
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(ANYTHING)
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(TRUE)
    }
}

/// Represents predicates that are never satisfied.
pub struct False {
    private: PhantomData<()>,
}

/// Represents errors that are always encountered.
#[derive(Debug, Error)]
#[error("always errors")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(logic::always), help("this error is always returned"))
)]
pub struct AlwaysError;

/// The `nothing` string.
pub const NOTHING: StaticStr = "nothing";

/// The `false` string.
pub const FALSE: StaticStr = "false";

impl<T: ?Sized> Predicate<T> for False {
    type Error = AlwaysError;

    fn check(_value: &T) -> Result<(), Self::Error> {
        Err(AlwaysError)
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(NOTHING)
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(FALSE)
    }
}

/// Represents errors returned by [`And`].
#[derive(Debug)]
pub enum EitherError<E, F> {
    /// Left error (`P` failed).
    Left(E),
    /// Right error (`Q` failed).
    Right(F),
}

impl<E: fmt::Display, F: fmt::Display> fmt::Display for EitherError<E, F> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Left(left) => write!(formatter, "left error: {left}"),
            Self::Right(right) => write!(formatter, "right error: {right}"),
        }
    }
}

impl<E: ErrorCore + 'static, F: ErrorCore + 'static> ErrorCore for EitherError<E, F> {
    fn source(&self) -> Option<&(dyn ErrorCore + 'static)> {
        match self {
            Self::Left(left) => Some(left),
            Self::Right(right) => Some(right),
        }
    }
}

#[cfg(feature = "diagnostics")]
impl<E: Diagnostic + 'static, F: Diagnostic + 'static> Diagnostic for EitherError<E, F> {
    fn code(&self) -> Option<Box<dyn fmt::Display + '_>> {
        Some(Box::new("logic::either"))
    }

    fn help(&self) -> Option<Box<dyn fmt::Display + '_>> {
        Some(Box::new("make sure both predicates are satisfied"))
    }

    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
        match self {
            Self::Left(left) => Some(left),
            Self::Right(right) => Some(right),
        }
    }
}

/// Represents predicates that are satisfied when both `P` and `Q` are satisfied.
pub struct And<P: ?Sized, Q: ?Sized> {
    left: PhantomData<P>,
    right: PhantomData<Q>,
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, Q: Predicate<T> + ?Sized> Predicate<T> for And<P, Q> {
    type Error = EitherError<P::Error, Q::Error>;

    fn check(value: &T) -> Result<(), Self::Error> {
        P::check(value)
            .map_err(Self::Error::Left)
            .and_then(|()| Q::check(value).map_err(Self::Error::Right))
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "({}) and ({})", P::expected(), Q::expected())
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "and<{}, {}>",
            P::expected_code(),
            Q::expected_code()
        )
    }
}

/// Represents errors returned by [`Or`].
#[derive(Debug)]
pub struct BothError<E, F> {
    /// Left error (`P` failed).
    pub left: E,
    /// Right error (`Q` failed).
    pub right: F,
}

impl<E, F> BothError<E, F> {
    /// Constructs [`Self`].
    pub const fn new(left: E, right: F) -> Self {
        Self { left, right }
    }
}

impl<E: fmt::Display, F: fmt::Display> fmt::Display for BothError<E, F> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "both errors occured: {left} and {right}",
            left = self.left,
            right = self.right
        )
    }
}

impl<E: ErrorCore, F: ErrorCore> ErrorCore for BothError<E, F> {}

#[cfg(feature = "diagnostics")]
impl<E: Diagnostic, F: Diagnostic> Diagnostic for BothError<E, F> {
    fn code(&self) -> Option<Box<dyn fmt::Display + '_>> {
        Some(Box::new("logic::both"))
    }

    fn help(&self) -> Option<Box<dyn fmt::Display + '_>> {
        Some(Box::new("make sure at least one predicate is satisfied"))
    }
}

/// Represents predicates that are satisfied when either `P` or `Q` (or both) are satisfied.
pub struct Or<P: ?Sized, Q: ?Sized> {
    left: PhantomData<P>,
    right: PhantomData<Q>,
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, Q: Predicate<T> + ?Sized> Predicate<T> for Or<P, Q> {
    type Error = BothError<P::Error, Q::Error>;

    fn check(value: &T) -> Result<(), Self::Error> {
        P::check(value)
            .or_else(|left| Q::check(value).map_err(|right| Self::Error::new(left, right)))
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "({}) or ({})", P::expected(), Q::expected())
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "or<{}, {}>",
            P::expected_code(),
            Q::expected_code()
        )
    }
}

/// Represents errors returned by [`Not`].
#[derive(Debug, Error, Default)]
#[error("negated error")]
#[cfg_attr(
    feature = "diagnostics",
    derive(Diagnostic),
    diagnostic(code(logic::not), help("make sure the negated predicate is satisfied"))
)]
pub struct NotError;

impl NotError {
    /// Constructs [`Self`].
    pub const fn new() -> Self {
        Self
    }
}

/// Represents predicates that are satisfied when `P` is not satisfied.
pub struct Not<P: ?Sized> {
    predicate: PhantomData<P>,
}

impl<T: ?Sized, P: Predicate<T> + ?Sized> Predicate<T> for Not<P> {
    type Error = NotError;

    fn check(value: &T) -> Result<(), Self::Error> {
        match P::check(value) {
            Ok(()) => Err(Self::Error::new()),
            Err(_) => Ok(()),
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "not ({})", P::expected())
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "not<{}>", P::expected_code())
    }
}

/// Represents errors returned by [`Xor`].
#[derive(Debug)]
pub enum NeitherOrBoth<E, F> {
    /// Neither error encountered.
    Neither,
    /// Both errors encountered.
    Both(BothError<E, F>),
}

impl<E: fmt::Display, F: fmt::Display> fmt::Display for NeitherOrBoth<E, F> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Neither => formatter.write_str("neither error encountered"),
            Self::Both(both) => both.fmt(formatter),
        }
    }
}

impl<E: ErrorCore + 'static, F: ErrorCore + 'static> ErrorCore for NeitherOrBoth<E, F> {
    fn source(&self) -> Option<&(dyn ErrorCore + 'static)> {
        match self {
            Self::Neither => None,
            Self::Both(both) => Some(both),
        }
    }
}

#[cfg(feature = "diagnostics")]
impl<E: Diagnostic + 'static, F: Diagnostic + 'static> Diagnostic for NeitherOrBoth<E, F> {
    fn code(&self) -> Option<Box<dyn fmt::Display + '_>> {
        Some(Box::new("logic::neither_or_both"))
    }

    fn help(&self) -> Option<Box<dyn fmt::Display + '_>> {
        Some(Box::new("make sure only one predicate is satisfied"))
    }

    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
        match self {
            Self::Neither => None,
            Self::Both(both) => Some(both),
        }
    }
}

/// Represents predicates that are satisfied when either `P` or `Q` (but *not* both) are satisfied.
pub struct Xor<P: ?Sized, Q: ?Sized> {
    left: PhantomData<P>,
    right: PhantomData<Q>,
}

impl<T: ?Sized, P: Predicate<T> + ?Sized, Q: Predicate<T> + ?Sized> Predicate<T> for Xor<P, Q> {
    type Error = NeitherOrBoth<P::Error, Q::Error>;

    fn check(value: &T) -> Result<(), Self::Error> {
        match (P::check(value), Q::check(value)) {
            (Ok(()), Ok(())) => Err(NeitherOrBoth::Neither),
            (Err(left), Err(right)) => Err(NeitherOrBoth::Both(BothError::new(left, right))),
            _ => Ok(()),
        }
    }

    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "({}) xor ({})", P::expected(), Q::expected())
    }

    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "xor<{}, {}>",
            P::expected_code(),
            Q::expected_code()
        )
    }
}

/// Composes [`Not`] and [`And`].
pub type Nand<P, Q> = Not<And<P, Q>>;

/// Composes [`Not`] and [`Or`].
pub type Nor<P, Q> = Not<Or<P, Q>>;

/// Composes [`Not`] and [`Xor`].
pub type Xnor<P, Q> = Not<Xor<P, Q>>;

/// Represents predicates that are satisfied when `P` implies `Q`.
pub type Imply<P, Q> = Or<Not<P>, Q>;

/// Negates the given predicate.
///
/// For predicate `P`, `not!(P)` is [`Not<P>`].
#[macro_export]
macro_rules! not {
    ($predicate: ty) => {
        $crate::logic::Not<$predicate>
    }
}

/// Given two or more predicates, composes them together with [`And`].
///
/// For predicates `P` and `Q`, `and!(P, Q)` is [`And<P, Q>`].
///
/// For predicates `P`, `Q`, and `R`, `and!(P, Q, R)` is [`And<P, And<Q, R>>`].
///
/// Ad infinitum...
#[macro_export]
macro_rules! and {
    ($first: ty, $second: ty) => {
        $crate::logic::And<$first, $second>
    };

    ($first: ty, $second: ty, $($rest: ty),+ $(,)?) => {
        $crate::and!($first, $crate::and!($second, $($rest),+))
    }
}

/// Given two or more predicates, composes them together with [`Or`].
///
/// For predicates `P` and `Q`, `or!(P, Q)` is [`Or<P, Q>`].
///
/// For predicates `P`, `Q`, and `R`, `or!(P, Q, R)` is [`Or<P, Or<Q, R>>`].
///
/// Ad infinitum...
#[macro_export]
macro_rules! or {
    ($first: ty, $second: ty) => {
        $crate::logic::Or<$first, $second>
    };

    ($first: ty, $second: ty, $($rest: ty),+ $(,)?) => {
        $crate::or!($first, $crate::or!($second, $($rest),+))
    }
}

/// Given two or more predicates, composes them together with [`Xor`].
///
/// For predicates `P` and `Q`, `xor!(P, Q)` is [`Xor<P, Q>`].
///
/// For predicates `P`, `Q`, and `R`, `xor!(P, Q, R)` is [`Xor<P, Xor<Q, R>>`].
///
/// Ad infinitum...
#[macro_export]
macro_rules! xor {
    ($first: ty, $second: ty) => {
        $crate::logic::Xor<$first, $second>
    };

    ($first: ty, $second: ty, $($rest: ty),+ $(,)?) => {
        $crate::xor!($first, $crate::xor!($second, $($rest),+))
    }
}