aboutsummaryrefslogtreecommitdiffstats
path: root/src/transpile_scheme.rs
blob: 6f993b39f0462c39ecd6db1ce737cb05d9dc0e78 (plain)
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

extern crate modelica_parser;

use self::modelica_parser::*;
use errors::Result;

pub trait TranspileScheme {
    fn transpile_scheme(&self) -> Result<String>;
}


impl TranspileScheme for ModelicaModel {
    fn transpile_scheme(&self) -> Result<String> {
        let mut params = vec![];
        let mut constants = vec![];
        for (c, e) in self.get_constant_vars() {
            if let Some(v) = e {
                constants.push(format!("({} {})", c, try!(v.transpile_scheme())));
            } else {
                params.push(c);
            }
        }
        // HashMaps are unsorted, so we need to re-sort here
        constants.sort();
        params.sort();
        let mut binds = vec![];
        let mut outputs = vec![];
        for eq in self.equations.iter() {
            if let Expr::Ident(ref symb) = eq.lhs {
                binds.push(format!("({} {})", symb, try!(eq.rhs.transpile_scheme())));
                outputs.push(symb.to_string());
            } else {
                bail!("Expected an identifier on LHS (in this partial implementation)")
            }
        }
        let mut args: Vec<String> = self.get_free_vars().iter().map(|s| s.clone()).collect();
        args.sort();
        args.extend(params);
        Ok(format!(r#"(lambda ({args})
            (let ({constants})
              (letrec ({binds})
                (list {outputs}))))"#,
                   args = args.join(" "),
                   constants = constants.join("\n    "),
                   binds = binds.join("\n      "),
                   outputs = outputs.join(" ")))
    }
}

impl TranspileScheme for Expr {
    fn transpile_scheme(&self) -> Result<String> {
        use modelica_parser::Expr::*;
        match *self {
            Integer(e) => Ok(format!("{}", e)),
            Float(e) => Ok(format!("{}", e)),
            Boolean(true) => Ok(format!("#t")),
            Boolean(false) => Ok(format!("#f")),
            StringLiteral(ref s) => Ok(format!("\"{}\"", s)),
            Ident(ref e) => Ok(format!("{}", e)),
            Der(ref e) => Ok(format!("(der {})", try!(e.transpile_scheme()))),
            Sign(ref e) => Ok(format!("(sign {})", try!(e.transpile_scheme()))),
            MathUnaryExpr(func, ref e) => Ok(format!("({:?} {})", func, try!(e.transpile_scheme()))),
            BinExpr(op, ref l, ref r) => {
                Ok(format!("({:?} {} {})",
                           op,
                           try!(l.transpile_scheme()),
                           try!(r.transpile_scheme())))
            }
            Array(_) => unimplemented!(),
        }
    }
}