summaryrefslogtreecommitdiff
path: root/src/ast/convert.rs
blob: 8051c904d2295ab1ed278225397f7b7f488d2dc4 (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
147
148
149
150
151
152
153
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;

use super::Term;

#[derive(Debug, Default)]
/// The variable context for converting a concrete syntax tree to an abstract
/// one.
///
/// There are two name scopes in a context. Bindings are used by fixed points.
/// Variables are formal parameters of macros.
pub struct Context {
    bindings: Vec<String>,
    variables: HashMap<String, usize>,
}

impl Context {
    /// Creates a new variable context. No names are bound.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns [`Some`] index of a binding `name`.
    ///
    /// # Errors
    /// Returns [`None`] if `name.is_empty()` or if `name` is unbound.
    ///
    /// # Examples
    /// ```
    /// use chomp::ast::convert::Context;
    ///
    /// let mut context = Context::new();
    /// assert_eq!(context.get_binding("x"), None);
    ///
    /// context.with_binding("x".to_owned(), |c| {
    ///     assert_eq!(c.get_binding("x"), Some(0));
    ///
    ///     c.with_binding("y".to_owned(), |c| {
    ///         assert_eq!(c.get_binding("x"), Some(1));
    ///     })
    /// });
    ///
    /// assert_eq!(context.get_binding("x"), None);
    /// ```
    pub fn get_binding<T: ?Sized + PartialEq<str>>(&self, name: &T) -> Option<usize> {
        let mut iter = self.bindings.iter();
        let mut pos = 0;

        if name == "" {
            return None;
        }

        while let Some(var) = iter.next_back() {
            if T::eq(&name, &var) {
                return Some(pos);
            } else {
                pos += 1;
            }
        }

        None
    }

    /// Adds a binding `name` for the duration of the function `f`.
    ///
    /// # Panics
    /// If `name.is_empty()`.
    ///
    /// # Examples
    /// ```
    /// use chomp::ast::convert::Context;
    ///
    /// let mut context = Context::new();
    /// assert_eq!(context.get_binding("x"), None);
    ///
    /// context.with_binding("x".to_owned(), |c| {
    ///     assert_eq!(c.get_binding("x"), Some(0));
    /// });
    ///
    /// assert_eq!(context.get_binding("x"), None);
    /// ```
    pub fn with_binding<F: FnOnce(&mut Self) -> T, T>(&mut self, name: String, f: F) -> T {
        if name.is_empty() {
            panic!()
        }

        self.bindings.push(name);
        let res = f(self);
        self.bindings.pop();
        res
    }

    /// Returns [`Some`] index of a variable `name`.
    ///
    /// # Errors
    /// If `name == "".to_owned().borrow()` or `name` is unbound.
    ///
    /// # Examples
    /// ```
    /// use chomp::ast::convert::Context;
    ///
    /// let mut ctx = Context::new();
    /// assert_eq!(ctx.get_variable("x"), None);
    ///
    /// ctx.set_variables(vec!["x".to_owned(), "y".to_owned()]);
    /// assert_eq!(ctx.get_variable("x"), Some(0));
    /// assert_eq!(ctx.get_variable("y"), Some(1));
    ///
    /// ctx.set_variables(vec![]);
    /// assert_eq!(ctx.get_variable("x"), None);
    /// ```
    pub fn get_variable<T: ?Sized + Hash + Eq>(&self, name: &T) -> Option<usize>
    where
        String: Borrow<T>,
    {
        if name == "".to_owned().borrow() {
            return None;
        }

        self.variables.get(name).copied()
    }

    /// Reassigns all variable indices based off of their position in `args`.
    ///
    /// # Examples
    /// ```
    /// use chomp::ast::convert::Context;
    ///
    /// let mut ctx = Context::new();
    /// assert_eq!(ctx.get_variable("x"), None);
    ///
    /// ctx.set_variables(vec!["x".to_owned(), "y".to_owned()]);
    /// assert_eq!(ctx.get_variable("x"), Some(0));
    /// assert_eq!(ctx.get_variable("y"), Some(1));
    ///
    /// ctx.set_variables(vec![]);
    /// assert_eq!(ctx.get_variable("x"), None);
    /// ```
    pub fn set_variables<I: IntoIterator<Item = String>>(&mut self, args: I) {
        self.variables = args
            .into_iter()
            .enumerate()
            .map(|(index, name)| (name, index))
            .collect();
    }
}

/// Used to convert a concrete term into an abstract term.
pub trait Convert {
    /// Performs the conversion.
    fn convert(&self, context: &mut Context) -> Term;
}