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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use std::iter;
use std::borrow::Borrow;
use std::fmt;

pub use bad_idea::BrokenF32;
use print::*;

/// An all-in-one package for building `ATerm`s. Maybe be pure, or have internal mutability to give
/// you maximally shared `ATerm`s.
pub trait ATermFactory<'a, B: 'a> {
    /// The `ATerm` the factory builds
    type ATerm: ATerm<Blob = B, Rec = Self::ATermRef>;
    /// The reference to an `ATerm` that's returned. You usually want these to be cheaply cloneable!
    type ATermRef: Borrow<Self::ATerm>;

    fn int(&'a self, value: i32) -> Self::ATermRef {
        self.no_annos(self.t_int(value))
    }
    /// The string variant in ATerms is represented as an application with zero children!
    fn string(&'a self, value: String) -> Self::ATermRef {
        self.application(format!("{:?}", value), iter::empty())
    }
    /// The tuple in ATerms is represented as an application with an empty constructor string!
    fn tuple<I>(&'a self, children: I) -> Self::ATermRef
        where I: IntoIterator<Item = Self::ATermRef>
    {
        self.application(String::new(), children)
    }
    fn real(&'a self, value: f32) -> Self::ATermRef {
        self.no_annos(self.t_real(value))
    }
    fn application<I>(&'a self, constructor: String, children: I) -> Self::ATermRef
        where I: IntoIterator<Item = Self::ATermRef>
    {
        self.no_annos(self.t_application(constructor, children))
    }
    fn list<I>(&'a self, value: I) -> Self::ATermRef
        where I: IntoIterator<Item = Self::ATermRef>
    {
        self.no_annos(self.t_list(value))
    }
    fn placeholder(&'a self, value: TermPlaceholder<Self::ATermRef>) -> Self::ATermRef {
        self.no_annos(self.t_placeholder(value))
    }
    fn blob(&'a self, value: B) -> Self::ATermRef {
        self.no_annos(self.t_blob(value))
    }
    fn long(&'a self, value: i64) -> Self::ATermRef {
        self.no_annos(self.t_long(value))
    }

    fn t_int(&'a self, value: i32) -> Term<Self::ATermRef, B> {
        Term::Int(value)
    }
    /// The string variant in ATerms is represented as an application with zero children!
    fn t_string(&'a self, value: String) -> Term<Self::ATermRef, B> {
        self.t_application(format!("{:?}", value), iter::empty())
    }
    /// The tuple in ATerms is represented as an application with an empty constructor string!
    fn t_tuple<I>(&'a self, children: I) -> Term<Self::ATermRef, B>
        where I: IntoIterator<Item = Self::ATermRef>
    {
        self.t_application(String::new(), children)
    }
    fn t_real(&'a self, value: f32) -> Term<Self::ATermRef, B> {
        Term::Real(BrokenF32(value))
    }
    fn t_application<I>(&'a self, constructor: String, children: I) -> Term<Self::ATermRef, B>
        where I: IntoIterator<Item = Self::ATermRef>
    {
        Term::Application(constructor,
                          children
                              .into_iter()
                              .collect::<Vec<_>>()
                              .into_boxed_slice())
    }
    fn t_list<I>(&'a self, value: I) -> Term<Self::ATermRef, B>
        where I: IntoIterator<Item = Self::ATermRef>
    {
        Term::List(value.into_iter().collect::<Vec<_>>().into_boxed_slice())
    }
    fn t_placeholder(&'a self, value: TermPlaceholder<Self::ATermRef>) -> Term<Self::ATermRef, B> {
        Term::Placeholder(value)
    }
    fn t_blob(&'a self, value: B) -> Term<Self::ATermRef, B> {
        Term::Blob(value)
    }
    fn t_long(&'a self, value: i64) -> Term<Self::ATermRef, B> {
        Term::Long(value)
    }

    fn no_annos(&'a self, term: Term<Self::ATermRef, B>) -> Self::ATermRef;

    fn with_annos<A>(&'a self, term: Term<Self::ATermRef, B>, annos: A) -> Self::ATermRef
        where A: IntoIterator<Item = Self::ATermRef>;
}

pub trait SharedATermFactory<'a, B: 'a>: ATermFactory<'a, B> {
    fn get_shared(&'a self, value: Self::ATermRef) -> Self::ATermRef
        where Self::ATermRef: Clone,
              B: Clone;
}

/// The basic term type, without annotations
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum Term<Rec, Blob> {
    /// An 32bit signed integer
    Int(i32),
    /// A 64bit signed integer. This is an optional component in the spec, but it's easy to support.
    Long(i64),
    /// An 32bit floating point number, but with a broken equality so a coherent implementation of
    /// Hash could be given (if NaN != NaN, then what Hash should it get?). You shouldn't directly
    /// check equality of floating point numbers anyways because of rounding.
    Real(BrokenF32),
    /// The main thing: Application of a constructor, using a string for the constructor name.
    Application(String, Box<[Rec]>),
    /// A list of ATerms.
    List(Box<[Rec]>),
    /// A placeholder for pattern matching. Only here for compatibility with the spec, use Rust's
    /// pattern matching facilities instead!
    Placeholder(TermPlaceholder<Rec>),
    /// A Binary Large OBject. Here used to embed any other type. Note it will need to implement
    /// some traits if you still want to parse or print it.
    Blob(Blob),
}

impl<Rec, B> fmt::Display for Term<Rec, B>
    where Rec: ATermWrite,
          B: ATermWrite
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_ascii(f)
    }
}

/// These placeholders match the constructors of Term.
/// The Application has sub-placeholders for the children of the constructor. The Term placeholder
/// is basically a wildcard, it matches anything.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum TermPlaceholder<Rec> {
    Int,
    String,
    Real,
    Term,
    Application(Box<[Rec]>),
    List,
    Placeholder,
    Blob,
    Long,
}

impl<Rec> fmt::Display for TermPlaceholder<Rec>
    where Rec: ATermWrite
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_ascii(f)
    }
}

/// The annotated term. This only combines the term with the annotations.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct ATermInner<ATerm, B> {
    /// The actual term.
    pub term: Term<ATerm, B>,
    /// The annotations on the term. The spec says this is an ATerm list of pairs of ATerms. We
    /// extend this to a general list of aterms so we can support more systems (e.g. Stratego/XT).
    pub annotations: Box<[ATerm]>,
}

impl<ATerm, B> ATermInner<ATerm, B> {
    pub fn no_annos(term: Term<ATerm, B>) -> Self {
        ATermInner {
            term: term,
            annotations: Box::new([]),
        }
    }

    pub fn with_annos<A>(term: Term<ATerm, B>, annos: A) -> Self
        where A: IntoIterator<Item =ATerm>
    {
        ATermInner {
            term: term,
            annotations: annos.into_iter().collect::<Vec<_>>().into_boxed_slice(),
        }
    }
}

/// The generic description of what it means to be an `ATerm`. That is: you need to be convertible
/// to an `ATermInner` to provide the minimum of term and annotations. Also gives you useful getters
/// so matching on different terms is easier.
pub trait ATerm {
    /// Basically the current type, but you may want to add something extra, so this is more
    /// flexible.
    type Rec: Borrow<Self>;
    /// The extension point to add more variants to terms.
    type Blob;

    fn into_inner(self) -> ATermInner<Self::Rec, Self::Blob>;
    fn as_inner(&self) -> &ATermInner<Self::Rec, Self::Blob>;

    fn get_int(&self) -> Option<i32> {
        match self.as_inner().term {
            Term::Int(i) => Some(i),
            _ => None,
        }
    }

    fn get_long(&self) -> Option<i64> {
        match self.as_inner().term {
            Term::Long(l) => Some(l),
            _ => None,
        }
    }

    fn get_real(&self) -> Option<f32> {
        match self.as_inner().term {
            Term::Real(BrokenF32(r)) => Some(r),
            _ => None,
        }
    }

    fn get_application(&self) -> Option<(&str, &[Self::Rec])> {
        match self.as_inner().term {
            Term::Application(ref c, ref r) => Some((c, r)),
            _ => None,
        }
    }

    fn get_list(&self) -> Option<&[Self::Rec]> {
        match self.as_inner().term {
            Term::List(ref r) => Some(r),
            _ => None,
        }
    }

    fn get_placeholder(&self) -> Option<&TermPlaceholder<Self::Rec>> {
        match self.as_inner().term {
            Term::Placeholder(ref tp) => Some(tp),
            _ => None,
        }
    }

    fn get_blob(&self) -> Option<&Self::Blob> {
        match self.as_inner().term {
            Term::Blob(ref b) => Some(b),
            _ => None,
        }
    }

    fn get_string(&self) -> Option<String> {
        use utils::string_unescape;
        match self.as_inner().term {
            Term::Application(ref c, ref r) if r.is_empty() && c.starts_with('"') &&
                                               c.ends_with('"') => Some(string_unescape(c)),
            _ => None,
        }
    }

    fn get_tuple(&self) -> Option<&[Self::Rec]> {
        match self.as_inner().term {
            Term::Application(ref c, ref r) if c.is_empty() => Some(r),
            _ => None,
        }
    }
}

impl<Rec, B> ATerm for ATermInner<Rec, B>
    where Rec: Borrow<ATermInner<Rec, B>>
{
    type Rec = Rec;
    type Blob = B;

    #[inline]
    fn into_inner(self) -> ATermInner<Rec, B> {
        self
    }
    #[inline]
    fn as_inner(&self) -> &ATermInner<Self::Rec, Self::Blob> {
        self
    }
}

impl<ATerm, B> fmt::Display for ATermInner<ATerm, B>
    where ATerm: ATermWrite,
          B: ATermWrite
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_ascii(f)
    }
}