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
198
199
200
201
202
203
204
205
206
//! The basic AST types.

mod args;
mod expr;
mod header;

use std::fmt::{Debug, Formatter, Result as FmtResult};

use gc::Gc;

pub use ast::args::{Args, ArgsBindingError, ArgsConvertError};
pub use ast::expr::Expr;
pub use ast::header::{ModuleHeaderError, parse_module_header};
use context::Context;
use symbol::Symbol;
use util::{as_list, as_shl};
use value::Value;

/// An error converting a value to an AST node.
pub enum ConvertError<C: 'static + Context> {
    /// An error parsing the arguments of a `defn` or `fn`.
    ArgsConvertError(ArgsConvertError<C>),

    /// A builtin was used in an invalid way.
    InvalidBuiltin(&'static str, Gc<Value<C>>),

    /// An invalid value was found in a position where a decl should have
    /// appeared.
    InvalidDecl(Gc<Value<C>>),

    /// A `def` decl was invalid.
    InvalidDef(Gc<Value<C>>),

    /// A `defn` decl was invalid.
    InvalidDefn(Gc<Value<C>>),

    /// A value of an invalid type was encountered where an expr was expected.
    InvalidExpr(Gc<Value<C>>),
}

impl<C: 'static + Context> Debug for ConvertError<C> {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        match *self {
            ConvertError::ArgsConvertError(ref err) => {
                fmt.debug_tuple("ArgsConvertError").field(err).finish()
            }
            ConvertError::InvalidBuiltin(ref name, ref val) => {
                fmt.debug_tuple("InvalidBuiltin")
                    .field(name)
                    .field(val)
                    .finish()
            }
            ConvertError::InvalidDecl(ref val) => {
                fmt.debug_tuple("InvalidDecl").field(val).finish()
            }
            ConvertError::InvalidDef(ref val) => fmt.debug_tuple("InvalidDef").field(val).finish(),
            ConvertError::InvalidDefn(ref val) => {
                fmt.debug_tuple("InvalidDefn").field(val).finish()
            }
            ConvertError::InvalidExpr(ref val) => {
                fmt.debug_tuple("InvalidExpr").field(val).finish()
            }
        }
    }
}

impl<C: 'static + Context> From<ArgsConvertError<C>> for ConvertError<C> {
    fn from(err: ArgsConvertError<C>) -> ConvertError<C> {
        ConvertError::ArgsConvertError(err)
    }
}

/// Converts the body values of a module to an AST.
pub fn convert_body<C: 'static + Context>(
    body: Vec<Gc<Value<C>>>,
) -> Result<Vec<(Symbol, Gc<Expr<C>>)>, ConvertError<C>> {
    body.into_iter().map(convert_decl).collect()
}

/// Converts a declaration to its AST node.
pub fn convert_decl<C: 'static + Context>(
    value: Gc<Value<C>>,
) -> Result<(Symbol, Gc<Expr<C>>), ConvertError<C>> {
    let (head, mut rest) = as_shl(value.clone()).ok_or_else(|| {
        ConvertError::InvalidDecl(value.clone())
    })?;
    match head.as_str() {
        "def" => {
            if rest.len() == 2 {
                let value = rest.pop().unwrap();
                let name = rest.pop().unwrap();
                assert_eq!(rest.len(), 0);
                if let Value::Symbol(name, _) = *name {
                    convert_expr(value).map(|expr| (name, expr))
                } else {
                    Err(ConvertError::InvalidDef(value))
                }
            } else {
                Err(ConvertError::InvalidDef(value))
            }
        }
        "defn" => {
            if rest.len() > 2 {
                let name = if let Value::Symbol(sym, _) = *rest.remove(0) {
                    sym
                } else {
                    return Err(ConvertError::InvalidDefn(value));
                };
                let args = rest.remove(0);
                let expr = convert_fn(Some(name), args, rest)?;
                Ok((name, expr))
            } else {
                Err(ConvertError::InvalidDefn(value))
            }
        }
        _ => Err(ConvertError::InvalidDecl(value)),
    }
}

/// Converts an expression to its AST node.
pub fn convert_expr<C: 'static + Context>(
    value: Gc<Value<C>>,
) -> Result<Gc<Expr<C>>, ConvertError<C>> {
    match *value.clone() {
        Value::Cons(..) => {
            if let Some(mut l) = as_list(value.clone()) {
                let func = l.remove(0);
                match *func {
                    Value::Symbol(s, _) if s.as_str() == "def" || s.as_str() == "defn" => {
                        let (n, e) = convert_decl(value)?;
                        Ok(Gc::new(Expr::Def(n, e)))
                    }
                    Value::Symbol(s, _) if s.as_str() == "fn" => {
                        if l.len() > 1 {
                            let args = l.remove(0);
                            convert_fn(None, args, l)
                        } else {
                            unimplemented!("invalid lambda: {:?}", l);
                        }
                    }
                    Value::Symbol(s, _) if s.as_str() == "if" => {
                        if l.len() == 2 {
                            let t = convert_expr(l.pop().unwrap())?;
                            let c = convert_expr(l.pop().unwrap())?;
                            let nil = Gc::new(Value::Nil(Default::default()));
                            let nil = Gc::new(Expr::Literal(nil));
                            Ok(Gc::new(Expr::If(c, t, nil)))
                        } else if l.len() == 3 {
                            let e = convert_expr(l.pop().unwrap())?;
                            let t = convert_expr(l.pop().unwrap())?;
                            let c = convert_expr(l.pop().unwrap())?;
                            Ok(Gc::new(Expr::If(c, t, e)))
                        } else {
                            Err(ConvertError::InvalidBuiltin("if".into(), value))
                        }
                    }
                    Value::Symbol(s, _) if s.as_str() == "macro-progn" || s.as_str() == "progn" => {
                        let exprs = l.into_iter().map(convert_expr).collect::<Result<_, _>>()?;
                        Ok(Gc::new(Expr::Progn(exprs)))
                    }
                    Value::Symbol(s, _) if s.as_str() == "quote" => {
                        if l.len() == 1 {
                            let value = l.pop().unwrap();
                            Ok(Gc::new(Expr::Literal(value)))
                        } else {
                            Err(ConvertError::InvalidBuiltin("quote".into(), value))
                        }
                    }
                    _ => {
                        let args = l.into_iter()
                            .map(convert_expr)
                            .collect::<Result<Vec<_>, _>>()?;
                        convert_expr(func).map(|func| Gc::new(Expr::Call(func, args)))
                    }
                }
            } else {
                Err(ConvertError::InvalidExpr(value))
            }
        }
        Value::Bytes(..) |
        Value::Fixnum(..) |
        Value::String(..) => Ok(Gc::new(Expr::Literal(value))),
        Value::Symbol(sym, _) => Ok(Gc::new(Expr::Variable(sym))),
        Value::Vector(ref v, _) => {
            let v = v.iter()
                .cloned()
                .map(|v| convert_expr(v))
                .collect::<Result<_, _>>()?;
            Ok(Gc::new(Expr::Vector(v)))
        }
        _ => Err(ConvertError::InvalidExpr(value)),
    }
}

pub(crate) fn convert_fn<C: 'static + Context>(
    name: Option<Symbol>,
    args: Gc<Value<C>>,
    body: Vec<Gc<Value<C>>>,
) -> Result<Gc<Expr<C>>, ConvertError<C>> {
    let mut body = body.into_iter()
        .map(convert_expr)
        .collect::<Result<Vec<_>, _>>()?;
    let tail = body.pop().unwrap();
    let args = Args::from_value(args)?;
    Ok(Gc::new(Expr::Lambda(name, Gc::new(args), body, tail)))
}