fips_md/parser/
constant.rs

1//! Structs for compile time constants
2
3use std::fmt::Display;
4
5/// A compile time constant, i.e. a literal, some pre-defined constant (or an expression of such, TODO)
6#[derive(Clone,Eq,PartialEq,Debug)]
7pub enum CompileTimeConstant<T:PartialEq> {
8    /// A literal (i.e. some concrete value)
9    Literal(T),
10    /// An identifier (i.e. some not yet substituted value)
11    Identifier(String),
12    /// An identifier after substitution (the old name is saved for debugging)
13    Substituted(T,String)
14}
15
16impl<T:PartialEq> CompileTimeConstant<T> {
17    /// In-place-ish substitution (does nothing, if substitution not possible)
18    pub fn substitute(&mut self, value: T) {
19        match self {
20            CompileTimeConstant::Identifier(old_name) => {
21                // Switch names around
22                let mut tmp = String::new();
23                std::mem::swap(&mut tmp, old_name);
24                // Create new variant
25                let new = CompileTimeConstant::Substituted(value, tmp);
26                // Switch around round 2
27                *self = new;
28            }
29            _ => {}
30        }
31
32    }
33}
34
35impl<T:Display+PartialEq> Display for CompileTimeConstant<T> {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            CompileTimeConstant::Literal(x) => x.fmt(f),
39            CompileTimeConstant::Identifier(ident) => f.write_str(&ident),
40            CompileTimeConstant::Substituted(x, ident) => f.write_fmt(format_args!("{} (substituted from '{}')", x, ident))
41        }
42    }
43}
44
45impl<T:PartialEq> From<T> for CompileTimeConstant<T> {
46    fn from(val: T) -> Self {
47        CompileTimeConstant::Literal(val)
48    }
49}