Skip to main content

prune_lang/utils/
lit.rs

1use std::fmt;
2use std::str::FromStr;
3
4#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
5pub enum LitType {
6    TyInt,
7    TyFloat,
8    TyBool,
9    TyChar,
10}
11
12impl fmt::Display for LitType {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        match self {
15            LitType::TyInt => "Int".fmt(f),
16            LitType::TyFloat => "Float".fmt(f),
17            LitType::TyBool => "Bool".fmt(f),
18            LitType::TyChar => "Char".fmt(f),
19        }
20    }
21}
22
23impl FromStr for LitType {
24    type Err = ();
25
26    fn from_str(s: &str) -> Result<Self, Self::Err> {
27        match s {
28            "Int" => Ok(LitType::TyInt),
29            "Float" => Ok(LitType::TyFloat),
30            "Bool" => Ok(LitType::TyBool),
31            "Char" => Ok(LitType::TyChar),
32            _ => Err(()),
33        }
34    }
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
38pub enum LitVal {
39    Int(i64),
40    Float(f64),
41    Bool(bool),
42    Char(char),
43}
44
45impl LitVal {
46    pub fn get_typ(&self) -> LitType {
47        match self {
48            LitVal::Int(_) => LitType::TyInt,
49            LitVal::Float(_) => LitType::TyFloat,
50            LitVal::Bool(_) => LitType::TyBool,
51            LitVal::Char(_) => LitType::TyChar,
52        }
53    }
54}
55
56impl fmt::Display for LitVal {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            LitVal::Int(x) => x.fmt(f),
60            LitVal::Float(x) => x.fmt(f),
61            LitVal::Bool(x) => x.fmt(f),
62            LitVal::Char(x) => x.fmt(f),
63        }
64    }
65}
66
67impl FromStr for LitVal {
68    type Err = ();
69
70    fn from_str(s: &str) -> Result<Self, Self::Err> {
71        if let Ok(x) = s.parse::<i64>() {
72            return Ok(LitVal::Int(x));
73        }
74
75        if let Ok(x) = s.parse::<f64>() {
76            return Ok(LitVal::Float(x));
77        }
78
79        match s {
80            "true" => {
81                return Ok(LitVal::Bool(true));
82            }
83            "false" => {
84                return Ok(LitVal::Bool(false));
85            }
86            _ => {}
87        }
88
89        // todo: other basic datatypes
90        Err(())
91    }
92}