pliron/common_traits.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) The pliron contributors
3
4//! Utility traits such as [Named], [Verify] etc.
5
6use crate::{
7 context::Context,
8 identifier::{Identifier, underscore},
9 result::Result,
10};
11
12/// Check and ensure correctness.
13pub trait Verify {
14 fn verify(&self, ctx: &Context) -> Result<()>;
15}
16
17/// Sugar to implement a verifier that always succeeds.
18/// Usage:
19/// ```
20/// use pliron::{context::Context, impl_verify_succ, common_traits::Verify};
21/// struct A;
22/// let a = A;
23/// let ctx = Context::new();
24/// assert!(a.verify(&ctx).is_ok());
25/// impl_verify_succ!(A);
26/// ```
27#[deprecated(
28 since = "0.14.0",
29 note = "Consider using `pliron::derive::verify_succ` instead"
30)]
31#[macro_export]
32macro_rules! impl_verify_succ {
33 ($op_name:path) => {
34 impl $crate::common_traits::Verify for $op_name {
35 fn verify(&self, _ctx: &$crate::context::Context) -> $crate::result::Result<()> {
36 Ok(())
37 }
38 }
39 };
40}
41
42/// Anything that has a name.
43pub trait Named {
44 /// A (not necessarily unique) name.
45 fn given_name(&self, ctx: &Context) -> Option<Identifier>;
46 /// A Unique (within the context) ID.
47 fn id(&self, ctx: &Context) -> Identifier;
48 /// A unique name; concatenation of name and id.
49 fn unique_name(&self, ctx: &Context) -> Identifier {
50 match self.given_name(ctx) {
51 Some(given_name) => given_name + underscore() + self.id(ctx),
52 None => self.id(ctx),
53 }
54 }
55}
56
57/// For reference-counted containers, [share](Self::share) data by increasing the reference count.
58/// This is equivalent in semantics to (i.e., [Rc::clone](alloc::rc::Rc::clone)),
59/// but with a goal of having a less ambiguous name.
60pub trait RcShare {
61 /// Share this object with someone else by increasing the reference count.
62 fn share(&self) -> Self;
63}