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
use std::{path::Path, str::FromStr};

use crate::{run_scilla_fmt, Error, FieldList, TransitionList};

#[derive(Debug, PartialEq)]
pub struct Contract {
    /// Name of the parsed contract
    pub name: String,
    /// List of parameters needed to deploy the contract.
    pub init_params: FieldList,
    /// List of the contract's fields.
    pub fields: FieldList,
    /// List of the contract's transitions.
    pub transitions: TransitionList,
}

impl FromStr for Contract {
    type Err = Error;

    /// Parse a Contract from a string slice
    fn from_str(sexp: &str) -> Result<Self, Self::Err> {
        // Bug in lexpr crate requires escaping backslashes
        let v = lexpr::from_str(&sexp.replace("\\", ""))?;
        let name = v["contr"][0]["cname"]["Ident"][0][1].to_string();
        let transitions = (&v["contr"][0]["ccomps"][0]).try_into()?;
        let init_params = (&v["contr"][0]["cparams"][0]).try_into()?;
        let fields = (&v["contr"][0]["cfields"][0]).try_into()?;
        Ok(Contract {
            name,
            transitions,
            init_params,
            fields,
        })
    }
}

impl Contract {
    /// Parse a contract from a given path.
    pub fn from_path(contract_path: &Path) -> Result<Self, Error> {
        run_scilla_fmt(contract_path)?.parse()
    }
}