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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use everscale_types::prelude::*;

pub use asm::{ArgType, AsmError, ExpectedArgType};
pub use ast::{ParserError, Span};

mod asm;
mod ast;
mod util;

pub struct Code<'a> {
    text: &'a str,
    ast: Option<ast::Code<'a>>,
    parser_errors: Vec<ast::ParserError>,
}

impl<'a> Code<'a> {
    pub fn assemble(text: &'a str) -> anyhow::Result<Cell> {
        let cell = Self::parse(text).try_into_valid()?.assemble()?;
        Ok(cell)
    }

    pub fn parse(text: &'a str) -> Self {
        let (ast, parser_errors) = ast::parse(text).into_output_errors();

        Self {
            text,
            ast,
            parser_errors,
        }
    }

    pub fn check(&self) -> Vec<AsmError> {
        if let Some(ast::Code { items, span }) = &self.ast {
            asm::check(items, *span)
        } else {
            Vec::new()
        }
    }

    pub fn try_into_valid(self) -> Result<ValidCode<'a>, ast::ParserError> {
        if self.parser_errors.is_empty() {
            if let Some(ast::Code { items, span }) = self.ast {
                return Ok(ValidCode {
                    _text: self.text,
                    span,
                    ast: items,
                });
            }
        }

        Err(self
            .parser_errors
            .into_iter()
            .next()
            .unwrap_or(ast::ParserError::UnknownError))
    }

    pub fn parser_errors(&self) -> &[ast::ParserError] {
        &self.parser_errors
    }
}

pub struct ValidCode<'a> {
    _text: &'a str,
    span: ast::Span,
    ast: Vec<ast::Instr<'a>>,
}

impl ValidCode<'_> {
    pub fn assemble(&self) -> Result<Cell, asm::AsmError> {
        asm::assemble(&self.ast, self.span)
    }

    pub fn check(self) -> Vec<asm::AsmError> {
        asm::check(&self.ast, self.span)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stack_ops() -> anyhow::Result<()> {
        let cell = Code::assemble(
            r##"
            XCHG s1, s2
            NOP
            SWAP
            XCHG3 s1, s2, s3
            "##,
        )?;

        assert_eq!(
            cell.repr_hash(),
            &"5f099122adde2ed3712374da4cd4e04e3214f0ddd7f155ffea923f1f2ab42d2b"
                .parse::<HashBytes>()
                .unwrap()
        );

        println!("{}", cell.display_tree());

        Ok(())
    }

    #[test]
    fn pushint() -> anyhow::Result<()> {
        let cell_tiny = Code::assemble("INT 7")?;
        assert_eq!(cell_tiny.data(), &[0x77]);

        let cell_byte = Code::assemble("INT 120")?;
        assert_eq!(cell_byte.data(), &[0x80, 120]);

        let cell_short = Code::assemble("INT 16000")?;
        assert_eq!(
            cell_short.data(),
            &[0x81, ((16000 >> 8) & 0xff) as u8, ((16000) & 0xff) as u8]
        );

        let cell_big = Code::assemble("INT 123123123123123123")?;
        assert_eq!(cell_big.data(), hex::decode("8229b56bd40163f3b3")?);

        let cell_max = Code::assemble(
            "INT 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        )?;
        assert_eq!(
            cell_max.data(),
            hex::decode("82f0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")?
        );

        let cell_neg_max = Code::assemble(
            "INT -0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        )?;
        assert_eq!(
            cell_neg_max.data(),
            hex::decode("82f70000000000000000000000000000000000000000000000000000000000000001")?
        );

        Ok(())
    }

    #[test]
    fn pushintx() -> anyhow::Result<()> {
        let cell_tiny = Code::assemble("INTX 7")?;
        assert_eq!(cell_tiny.data(), &[0x77]);

        let cell_byte = Code::assemble("INTX 120")?;
        assert_eq!(cell_byte.data(), &[0x80, 120]);

        let cell_short = Code::assemble("INTX 16000")?;
        assert_eq!(
            cell_short.data(),
            &[0x81, ((16000 >> 8) & 0xff) as u8, ((16000) & 0xff) as u8]
        );

        let cell_big = Code::assemble("INTX 123123123123123123")?;
        assert_eq!(cell_big.data(), hex::decode("8229b56bd40163f3b3")?);

        let cell_big = Code::assemble("INTX 90596966400")?;
        assert_eq!(cell_big.data(), hex::decode("8102a3aa1a")?);

        let cell_max = Code::assemble(
            "INTX 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        )?;
        assert_eq!(cell_max.data(), hex::decode("84ff")?);

        let cell_neg_max = Code::assemble(
            "INTX -0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        )?;
        assert_eq!(
            cell_neg_max.data(),
            hex::decode("82f70000000000000000000000000000000000000000000000000000000000000001")?
        );

        Ok(())
    }

    #[test]
    fn display() -> anyhow::Result<()> {
        let code = Code::assemble("PUSHSLICE x{6_}")?;
        println!("{}", code.display_tree());
        Ok(())
    }

    #[test]
    fn complex_asm() -> anyhow::Result<()> {
        const CODE: &str = include_str!("tests/walletv3.tvm");

        let output = Code::assemble(CODE).unwrap();
        assert_eq!(
            output.repr_hash(),
            &"84dafa449f98a6987789ba232358072bc0f76dc4524002a5d0918b9a75d2d599"
                .parse::<HashBytes>()?
        );
        Ok(())
    }
}