Trait arithmetic_typing::PrimitiveType

source ·
pub trait PrimitiveType: Clone + PartialEq + Debug + Display + FromStr + Send + Sync + 'static {
    // Provided method
    fn well_known_constraints() -> ConstraintSet<Self> { ... }
}
Expand description

Primitive types in a certain type system.

More complex types, like Type and Function, are defined with a type param which determines the primitive type(s). This type param must implement PrimitiveType.

TypeArithmetic has a PrimitiveType impl as an associated type, and one of the required operations of this trait is to be able to infer type for literal values from a Grammar.

§Implementation Requirements

  • Display and FromStr implementations must be consistent; i.e., Display should produce output parseable by FromStr. Display will be used in Display impls for Type etc. FromStr will be used to read type annotations.
  • Display presentations must be identifiers, such as Num.
  • While not required, a PrimitiveType should usually contain a Boolean type and implement WithBoolean. This allows to reuse BoolArithmetic and/or NumArithmetic as building blocks for your TypeArithmetic.

§Examples

use arithmetic_typing::PrimitiveType;

#[derive(Debug, Clone, Copy, PartialEq)]
enum NumOrBytes {
    /// Numeric value, such as 1.
    Num,
    /// Bytes value, such as 0x1234 or "hello".
    Bytes,
}

// `NumOrBytes` should correspond to a "value" type in the `Grammar`,
// for example:
enum NumOrBytesValue {
    Num(f64),
    Bytes(Vec<u8>),
}

impl fmt::Display for NumOrBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Num => formatter.write_str("Num"),
            Self::Bytes => formatter.write_str("Bytes"),
        }
    }
}

impl FromStr for NumOrBytes {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Num" => Ok(Self::Num),
            "Bytes" => Ok(Self::Bytes),
            _ => Err(anyhow::anyhow!("expected `Num` or `Bytes`")),
        }
    }
}

impl PrimitiveType for NumOrBytes {}

Provided Methods§

source

fn well_known_constraints() -> ConstraintSet<Self>

Returns well-known constraints for this type. These constraints are used in standalone parsing of type signatures.

The default implementation returns an empty set.

Object Safety§

This trait is not object safe.

Implementors§