1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use crate::ir::{Identifier, Literal, Type};
use std::convert::TryFrom;
use syn::{ImplItemConst, ItemConst};

#[derive(Debug, PartialEq, Clone)]
/// Constant Struct
pub struct Constant {
    /// identifier field
    pub identifier: Identifier,
    /// type_ field
    pub type_: Type,
    /// literal field
    pub literal: Literal,
}

impl From<ImplItemConst> for Constant {
    fn from(item_const: ImplItemConst) -> Self {
        if let syn::Expr::Lit(syn::ExprLit { lit, .. }) = item_const.expr {
            Self {
                identifier: Identifier::from(item_const.ident.clone()),
                type_: Type::try_from(item_const.ty).expect("Failed to convert from Type"),
                literal: Literal::from(lit),
            }
        } else {
            panic!("Undefined Constant inside Impl block");
        }
    }
}

impl From<ItemConst> for Constant {
    fn from(item_const: ItemConst) -> Self {
        if let syn::Expr::Lit(syn::ExprLit { lit, .. }) = *item_const.expr {
            Self {
                identifier: Identifier::from(item_const.ident.clone()),
                type_: Type::try_from(*item_const.ty).expect("Failed to convert from Type"),
                literal: Literal::from(lit),
            }
        } else {
            panic!("Undefined Constant");
        }
    }
}

#[cfg(test)]
mod test {
    use super::{Constant, Identifier, ImplItemConst, ItemConst, Type};
    use crate::ir::{Literal, Reference, ReferenceKind};
    use quote::quote;
    use syn::parse_quote::parse;

    #[test]
    fn impl_const_impl() {
        assert_eq!(
            Constant::from(parse::<ImplItemConst>(quote! {const a: &str = "test";})),
            Constant {
                identifier: Identifier::new("a"),
                type_: Type::Reference(
                    Reference {
                        kind: ReferenceKind::Borrow,
                        is_constant: true,
                        type_: Box::new(Type::Compound(Identifier::new("str").into()))
                    }
                ),
                literal: Literal::String(String::from("test"))
            }
        );
    }

    #[test]
    fn impl_const() {
        assert_eq!(
            Constant::from(parse::<ItemConst>(quote! {const a: &str = "test";})),
            Constant {
                identifier: Identifier::new("a"),
                type_: Type::Reference(
                    Reference {
                        kind: ReferenceKind::Borrow,
                        is_constant: true,
                        type_: Box::new(Type::Compound(Identifier::new("str").into()))
                    }
                ),
                literal: Literal::String(String::from("test"))
            }
        );
    }
}