aboutsummaryrefslogtreecommitdiff
path: root/src/sexp/util.rs
blob: db400e9da43638597e6c218dc8d265066231a5d2 (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
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

use std::iter;

use crate::sexp::SExp;
use crate::sexp::SLeaf;
use crate::sexp::SExp::*;
use crate::sexp::SLeaf::*;

impl From<i32> for Box<SExp> {
    fn from(int: i32) -> Self {
        Box::new(Atom(Int(int)))
    }
}

impl From<bool> for SExp {
    fn from(bl: bool) -> Self {
        Atom( if bl { True } else { False } )
    }
}

impl From<SLeaf> for Box<SExp> {
    fn from(leaf: SLeaf) -> Self {
        Box::new(Atom(leaf))
    }
}

impl From<i32> for SLeaf {
    fn from(int: i32) -> Self {
        Int(int)
    }
}

pub fn scons(x: impl Into<Box<SExp>>, y: impl Into<Box<SExp>>) -> SExp {
    SCons(x.into(), y.into())
}

pub fn var(name: &str) -> SExp {
    Atom(Var(name.to_string()))
}

impl SExp {
    /// Transforms this SExp into a Vec<SLeaf>.
    ///
    /// Errors if the left-hand side of SCons has an SCons,
    /// or if the passed SExp is an Atom, or if the
    /// lists aren't Nil-terminated.
    ///
    /// ```rust
    /// use myslip::sexp::{SExp::*, SLeaf::*, util::*};
    /// assert_eq!(
    ///     scons(1, scons(2, scons(3, Nil))).into_vec(),
    ///     Ok(vec![Int(1), Int(2), Int(3)])
    /// );
    /// assert!(scons(scons(1, Nil), Nil).into_vec().is_err());
    /// assert!(scons(1, 2).into_vec().is_err());
    /// ```
    pub fn into_vec(self) -> Result<Vec<SLeaf>, String> {
        match self {
            SCons(a, b) => match (*a, *b) {
                (Atom(a), Atom(Nil)) => Ok(iter::once(a).collect::<Vec<SLeaf>>()),
                (Atom(a), b) => Ok(iter::once(a).chain(b.into_vec()?).collect::<Vec<SLeaf>>()),
                (a, b) => Err(format!("invalid list structure: {:?}", scons(a, b)))
            },
            _ => Err("expected list, found atom".to_string()),
        }
    }

    pub fn parts(self) -> Vec<SExp> {
        match self {
            Atom(x) => vec![Atom(x)],
            SCons(a, b) if *b == Atom(Nil) => vec![*a],
            SCons(a, b) => {
                let mut res = vec![*a];
                res.extend_from_slice(&(*b).parts());
                res
            },
        }
    }

    pub fn check_let(self) -> Option<(String, SExp)> {
        match &(self.parts())[..] {
            [l, n, v] if *l == Atom(Let) => match (n.clone(), v.clone()) {
                (Atom(Var(name)), val) => Some((name, val)),
                _ => None
            },
            _ => None
        }
    }

    pub fn get_vars_bound_by_pattern(&self) -> Vec<String> {
	match self {
	    Atom(Var(s)) => vec![s.clone()],
	    Atom(RestPat(s)) => vec![s.clone()],
	    SCons(a, b) =>
		(*a).get_vars_bound_by_pattern()
		.into_iter()
		.chain((*b).get_vars_bound_by_pattern())
		.collect(),
	    _ => vec![],
	}
    }

    pub fn get_case_scrut_pats_and_arms(self) ->
	Option<(SExp, Vec<(SExp, SExp)>)> {
	    let (scrutinee, patarms) = self.check_case()?;

	    let scrutinee = match scrutinee {
		SCons(q, v) if *q == Atom(Quote) || *q == Atom(Vector) => *v,
		t => t,
	    };

	    let mut res = vec![];
	    for patarm in patarms {
		let (pat, arm) = match patarm {
		    SCons(pat, arm) => Some((*pat, *arm)),
		    _ => {
			println!("warn: invalid structure in case arms,");
			println!("      should be unreachable after type checking");
			None
		    },
		}?;
		let arm = match arm {
		    SCons(x, n) if *n == Atom(Nil) => *x,
		    t => t,
		};
		res.push((pat, arm));
	    }
	    Some((scrutinee, res))
	}

    pub fn check_case(self) -> Option<(SExp, Vec<SExp>)> {
        match &(self.parts())[..] {
	    [casekw, scrutinee, cases @ ..] if casekw.clone() == Atom(Case) =>
		Some((scrutinee.clone(), cases.to_vec())),
	    _ => None,
	}
    }

    pub fn back_to_case(scrutinee: SExp, arms: Vec<SExp>) -> SExp {
	let mut res = Atom(Nil);
	for arm in arms.into_iter().rev() {
	    res = scons(arm, res);
	}
	scons(Case, scons(scrutinee, res))
    }
}