cainome_parser/tokens/
basic.rs

1use super::constants::CAIRO_CORE_BASIC;
2use crate::{CainomeResult, Error};
3
4#[derive(Debug, Clone, PartialEq)]
5pub struct CoreBasic {
6    pub type_path: String,
7}
8
9impl CoreBasic {
10    pub fn parse(type_path: &str) -> CainomeResult<Self> {
11        // Unit type is for now included in basic type.
12        if type_path == "()" {
13            return Ok(Self {
14                type_path: type_path.to_string(),
15            });
16        }
17
18        if !CAIRO_CORE_BASIC.contains(&type_path) {
19            return Err(Error::TokenInitFailed(format!(
20                "CoreBasic token couldn't be initialized from `{}`",
21                type_path,
22            )));
23        }
24
25        Ok(Self {
26            type_path: type_path.to_string(),
27        })
28    }
29
30    pub fn type_name(&self) -> String {
31        // TODO: need to opti that with regex?
32        let f = self
33            .type_path
34            .split('<')
35            .nth(0)
36            .unwrap_or(&self.type_path)
37            .trim_end_matches("::")
38            .to_string();
39
40        f.split("::").last().unwrap_or(&f).to_string()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_parse() {
50        assert_eq!(
51            CoreBasic::parse("core::felt252").unwrap(),
52            CoreBasic {
53                type_path: "core::felt252".to_string(),
54            }
55        );
56
57        assert_eq!(
58            CoreBasic::parse("core::integer::u64").unwrap(),
59            CoreBasic {
60                type_path: "core::integer::u64".to_string(),
61            }
62        );
63    }
64
65    #[test]
66    fn test_parse_unit() {
67        assert_eq!(
68            CoreBasic::parse("()").unwrap(),
69            CoreBasic {
70                type_path: "()".to_string(),
71            }
72        );
73    }
74
75    #[test]
76    fn test_parse_array_span_invalid() {
77        assert!(CoreBasic::parse("core::array::Array<core::felt252>").is_err());
78        assert!(CoreBasic::parse("core::array::Span<core::felt252>").is_err());
79    }
80
81    #[test]
82    fn test_parse_composite_invalid() {
83        assert!(CoreBasic::parse("mymodule::MyStruct").is_err());
84        assert!(CoreBasic::parse("module2::module3::MyStruct<core::felt252>").is_err());
85    }
86}