kodept_ast/node/
literal.rs

1#[cfg(feature = "serde")]
2use serde::{Deserialize, Serialize};
3
4use kodept_core::structure::rlt;
5use kodept_core::structure::span::CodeHolder;
6
7use crate::graph::NodeId;
8use crate::graph::{SyntaxTreeBuilder};
9use crate::traits::Linker;
10use crate::traits::PopulateTree;
11use crate::{node, node_sub_enum, Operation};
12
13node_sub_enum! {
14    #[derive(Debug, PartialEq)]
15    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
16    pub enum Lit {
17        Num(NumLit),
18        Char(CharLit),
19        Str(StrLit),
20        Tuple(TupleLit)
21    }
22}
23
24node! {
25    #[derive(Debug, PartialEq)]
26    #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
27    pub struct NumLit {
28        pub value: String,;
29    }
30}
31
32node! {
33    #[derive(Debug, PartialEq)]
34    #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
35    pub struct CharLit {
36        pub value: String,;
37    }
38}
39
40node! {
41    #[derive(Debug, PartialEq)]
42    #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
43    pub struct StrLit {
44        pub value: String,;
45    }
46}
47
48node! {
49    #[derive(Debug, PartialEq)]
50    #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
51    pub struct TupleLit {;
52        pub value: Vec<Operation>,
53    }
54}
55
56impl PopulateTree for rlt::Literal {
57    type Output = Lit;
58
59    fn convert(
60        &self,
61        builder: &mut SyntaxTreeBuilder,
62        context: &mut (impl Linker + CodeHolder),
63    ) -> NodeId<Self::Output> {
64        let mut from_num = |x| {
65            builder
66                .add_node(NumLit::uninit(
67                    context.get_chunk_located(x).to_string(),
68                ))
69                .with_rlt(context, self)
70                .id()
71                .cast()
72        };
73
74        match self {
75            rlt::Literal::Binary(x) => from_num(x),
76            rlt::Literal::Octal(x) => from_num(x),
77            rlt::Literal::Hex(x) => from_num(x),
78            rlt::Literal::Floating(x) => from_num(x),
79            rlt::Literal::Char(x) => builder
80                .add_node(CharLit::uninit(
81                    context.get_chunk_located(x).to_string(),
82                ))
83                .with_rlt(context, self)
84                .id()
85                .cast(),
86            rlt::Literal::String(x) => builder
87                .add_node(StrLit::uninit(
88                    context.get_chunk_located(x).to_string(),
89                ))
90                .with_rlt(context, self)
91                .id()
92                .cast(),
93            rlt::Literal::Tuple(x) => builder
94                .add_node(TupleLit::uninit())
95                .with_children_from(x.inner.as_ref(), context)
96                .with_rlt(context, self)
97                .id()
98                .cast(),
99        }
100    }
101}