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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::collections::{BTreeMap, BTreeSet};
use number::{Dim, Number, Unit};
use num::Num;
use ast::{Expr, DatePattern};
use search;
use substance::Substance;
use reply::NotFoundError;

/// The evaluation context that contains unit definitions.
#[derive(Debug)]
pub struct Context {
    pub dimensions: BTreeSet<Dim>,
    pub canonicalizations: BTreeMap<String, String>,
    pub units: BTreeMap<String, Number>,
    pub quantities: BTreeMap<Unit, String>,
    pub reverse: BTreeMap<Unit, String>,
    pub prefixes: Vec<(String, Number)>,
    pub definitions: BTreeMap<String, Expr>,
    pub docs: BTreeMap<String, String>,
    pub categories: BTreeMap<String, String>,
    pub category_names: BTreeMap<String, String>,
    pub datepatterns: Vec<Vec<DatePattern>>,
    pub substances: BTreeMap<String, Substance>,
    pub substance_symbols: BTreeMap<String, String>,
    pub temporaries: BTreeMap<String, Number>,
    pub short_output: bool,
    pub use_humanize: bool,
}

impl Context {
    /// Creates a new, empty context
    pub fn new() -> Context {
        Context {
            dimensions: BTreeSet::new(),
            canonicalizations: BTreeMap::new(),
            units: BTreeMap::new(),
            quantities: BTreeMap::new(),
            reverse: BTreeMap::new(),
            prefixes: Vec::new(),
            definitions: BTreeMap::new(),
            docs: BTreeMap::new(),
            categories: BTreeMap::new(),
            category_names: BTreeMap::new(),
            datepatterns: Vec::new(),
            substances: BTreeMap::new(),
            substance_symbols: BTreeMap::new(),
            temporaries: BTreeMap::new(),
            short_output: false,
            use_humanize: true,
        }
    }

    pub fn load_dates(&mut self, mut dates: Vec<Vec<DatePattern>>) {
        self.datepatterns.append(&mut dates)
    }

    /// Given a unit name, returns its value if it exists. Supports SI
    /// prefixes, plurals, bare dimensions like length, and quantities.
    pub fn lookup(&self, name: &str) -> Option<Number> {
        fn inner(ctx: &Context, name: &str) -> Option<Number> {
            if let Some(v) = ctx.temporaries.get(name).cloned() {
                return Some(v)
            }
            if let Some(k) = ctx.dimensions.get(name) {
                return Some(Number::one_unit(k.to_owned()))
            }
            if let Some(v) = ctx.units.get(name).cloned() {
                return Some(v)
            }
            for (unit, quantity) in &ctx.quantities {
                if name == quantity {
                    return Some(Number {
                        value: Num::one(),
                        unit: unit.clone()
                    })
                }
            }
            None
        }
        if let Some(v) = inner(self, name) {
            return Some(v)
        }
        for &(ref pre, ref value) in &self.prefixes {
            if name.starts_with(pre) {
                if let Some(v) = inner(self, &name[pre.len()..]) {
                    return Some((&v * &value).unwrap())
                }
            }
        }
        // after so that "ks" is kiloseconds
        if name.ends_with("s") {
            let name = &name[0..name.len()-1];
            if let Some(v) = inner(self, name) {
                return Some(v)
            }
            for &(ref pre, ref value) in &self.prefixes {
                if name.starts_with(pre) {
                    if let Some(v) = inner(self, &name[pre.len()..]) {
                        return Some((&v * &value).unwrap())
                    }
                }
            }
        }
        None
    }

    /// Given a unit name, try to return a canonical name (expanding aliases and such)
    pub fn canonicalize(&self, name: &str) -> Option<String> {
        fn inner(ctx: &Context, name: &str) -> Option<String> {
            if let Some(v) = ctx.canonicalizations.get(name) {
                return Some(v.clone())
            }
            if let Some(k) = ctx.dimensions.get(name) {
                return Some((*k.0).clone())
            }
            if let Some(v) = ctx.definitions.get(name) {
                if let Expr::Unit(ref name) = *v {
                    if let Some(r) = ctx.canonicalize(&*name) {
                        return Some(r)
                    } else {
                        return Some(name.clone())
                    }
                } else {
                    // we cannot canonicalize it further
                    return Some(name.to_owned())
                }
            }
            None
        }
        if let Some(v) = inner(self, name) {
            return Some(v)
        }
        for &(ref pre, ref val) in &self.prefixes {
            if name.starts_with(pre) {
                if let Some(v) = inner(self, &name[pre.len()..]) {
                    let mut pre = pre;
                    for &(ref other, ref otherval) in &self.prefixes {
                        if other.len() > pre.len() && val == otherval {
                            pre = other;
                        }
                    }
                    return Some(format!("{}{}", pre, v))
                }
            }
        }
        if name.ends_with("s") {
            let name = &name[0..name.len()-1];
            if let Some(v) = inner(self, name) {
                return Some(v)
            }
            for &(ref pre, ref val) in &self.prefixes {
                if name.starts_with(pre) {
                    if let Some(v) = inner(self, &name[pre.len()..]) {
                        let mut pre = pre;
                        for &(ref other, ref otherval) in &self.prefixes {
                            if other.len() > pre.len() && val == otherval {
                                pre = other;
                            }
                        }
                        return Some(format!("{}{}", pre, v))
                    }
                }
            }
        }
        None
    }

    /// Describes a value's unit, gives true if the unit is reciprocal
    /// (e.g. you should prefix "1.0 / " or replace "multiply" with
    /// "divide" when rendering it).
    pub fn describe_unit(&self, value: &Number) -> (bool, String) {
        use std::io::Write;

        let mut buf = vec![];
        let mut recip = false;
        let square = Number {
            value: Num::one(),
            unit: value.unit.clone()
        }.root(2).ok();
        let inverse = (&Number::one() / &Number {
            value: Num::one(),
            unit: value.unit.clone()
        }).unwrap();
        if let Some(name) = self.quantities.get(&value.unit) {
            write!(buf, "{}", name).unwrap();
        } else if let Some(name) = square.and_then(|square| self.quantities.get(&square.unit)) {
            write!(buf, "{}^2", name).unwrap();
        } else if let Some(name) = self.quantities.get(&inverse.unit) {
            recip = true;
            write!(buf, "{}", name).unwrap();
        } else {
            let mut frac = vec![];
            let mut found = false;
            for (dim, &pow) in &value.unit {
                if pow < 0 {
                    frac.push((dim, -pow));
                } else {
                    found = true;
                    let mut map = Unit::new();
                    map.insert(dim.clone(), pow);
                    if let Some(name) = self.quantities.get(&map) {
                        write!(buf, " {}", name).unwrap();
                    } else {
                        let mut map = Unit::new();
                        map.insert(dim.clone(), 1);
                        if let Some(name) = self.quantities.get(&map) {
                            write!(buf, " {}", name).unwrap();
                        } else {
                            write!(buf, " '{}'", dim).unwrap();
                        }
                        if pow != 1 {
                            write!(buf, "^{}", pow).unwrap();
                        }
                    }
                }
            }
            if frac.len() > 0 {
                if !found {
                    recip = true;
                } else {
                    write!(buf, " /").unwrap();
                }
                for (dim, pow) in frac {
                    let mut map = Unit::new();
                    map.insert(dim.clone(), pow);
                    if let Some(name) = self.quantities.get(&map) {
                        write!(buf, " {}", name).unwrap();
                    } else {
                        let mut map = Unit::new();
                        map.insert(dim.clone(), 1);
                        if let Some(name) = self.quantities.get(&map) {
                            write!(buf, " {}", name).unwrap();
                        } else {
                            write!(buf, " '{}'", dim).unwrap();
                        }
                        if pow != 1 {
                            write!(buf, "^{}", pow).unwrap();
                        }
                    }
                }
            }
            buf.remove(0);
        }

        (recip, String::from_utf8(buf).unwrap())
    }

    pub fn typo_dym<'a>(&'a self, what: &str) -> Option<&'a str> {
        search::search(self, what, 1).into_iter().next()
    }

    pub fn unknown_unit_err(&self, name: &str) -> NotFoundError {
        NotFoundError {
            got: name.to_owned(),
            suggestion: self.typo_dym(name).map(|x| x.to_owned()),
        }
    }
}