cainome_parser/tokens/
result.rs

1//! This module provides a token type for the `Result` type.
2//!
3//! <https://github.com/starkware-libs/cairo/blob/main/corelib/src/result.cairo>
4use crate::tokens::Token;
5use crate::{CainomeResult, Error};
6
7use super::composite::escape_rust_keywords;
8use super::genericity;
9
10#[derive(Debug, Clone, PartialEq)]
11pub struct Result {
12    pub type_path: String,
13    pub inner: Box<Token>,
14    pub error: Box<Token>,
15}
16
17impl Result {
18    pub fn parse(type_path: &str) -> CainomeResult<Self> {
19        let type_path = escape_rust_keywords(type_path);
20
21        if type_path.starts_with("core::result::Result") {
22            let generic_args = genericity::extract_generics_args(&type_path)?;
23
24            if generic_args.len() != 2 {
25                return Err(Error::InvalidResultTypePath(type_path.to_string()));
26            }
27
28            let (_, generic_arg_token) = &generic_args[0];
29            let (_, error_token) = &generic_args[1];
30
31            Ok(Self {
32                type_path: type_path.to_string(),
33                inner: Box::new(generic_arg_token.clone()),
34                error: Box::new(error_token.clone()),
35            })
36        } else {
37            Err(Error::TokenInitFailed(format!(
38                "Result couldn't be initialized from `{}`.",
39                type_path,
40            )))
41        }
42    }
43
44    pub fn apply_alias(&mut self, type_path: &str, alias: &str) {
45        self.inner.apply_alias(type_path, alias);
46        self.error.apply_alias(type_path, alias);
47    }
48}