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
use failure::{format_err, Error}; use serde_json::{self, Map, Value}; use std::collections::{hash_map::Entry, HashMap}; use std::fs; use std::path::Path; #[derive(Debug, Clone)] pub struct Bindings { bindings: HashMap<String, HashMap<String, String>>, } impl Bindings { pub fn new(bindings: HashMap<String, HashMap<String, String>>) -> Bindings { Self { bindings: bindings } } pub fn env(env: HashMap<String, String>) -> Bindings { let mut bindings = HashMap::new(); bindings.insert("env".to_owned(), env); Self::new(bindings) } pub fn empty() -> Bindings { Self::new(HashMap::new()) } pub fn from_json(v: &Value) -> Result<Bindings, Error> { match v.as_object() { Some(modules) => Self::parse_modules_json_obj(modules), None => Err(format_err!("top level json expected to be object"))?, } } pub fn from_str(s: &str) -> Result<Bindings, Error> { let top: Value = serde_json::from_str(s)?; Ok(Self::from_json(&top)?) } pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Bindings, Error> { let contents = fs::read_to_string(path.as_ref())?; Ok(Self::from_str(&contents)?) } pub fn extend(&mut self, other: &Bindings) -> Result<(), Error> { for (modname, othermodbindings) in other.bindings.iter() { match self.bindings.entry(modname.clone()) { Entry::Occupied(mut e) => { let existing = e.get_mut(); for (bindname, binding) in othermodbindings { match existing.entry(bindname.clone()) { Entry::Vacant(e) => { e.insert(binding.clone()); } Entry::Occupied(e) => { if binding != e.get() { Err(format_err!( "cannot re-bind {} from {} to {}", e.key(), binding, e.get() ))?; } } } } } Entry::Vacant(e) => { e.insert(othermodbindings.clone()); } } } Ok(()) } pub fn translate(&self, module: &str, symbol: &str) -> Result<String, Error> { match self.bindings.get(module) { Some(m) => match m.get(symbol) { Some(s) => Ok(s.clone()), None => Err(format_err!("Unknown symbol `{}::{}`", module, symbol)), }, None => Err(format_err!( "Unknown module for symbol `{}::{}`", module, symbol )), } } fn parse_modules_json_obj(m: &Map<String, Value>) -> Result<Self, Error> { let mut res = HashMap::new(); for (modulename, values) in m { match values.as_object() { Some(methods) => { let methodmap = Self::parse_methods_json_obj(methods)?; res.insert(modulename.to_owned(), methodmap); } None => Err(format_err!(""))?, } } Ok(Self::new(res)) } fn parse_methods_json_obj(m: &Map<String, Value>) -> Result<HashMap<String, String>, Error> { let mut res = HashMap::new(); for (method, i) in m { match i.as_str() { Some(importbinding) => { res.insert(method.to_owned(), importbinding.to_owned()); } None => Err(format_err!(""))?, } } Ok(res) } pub fn to_string(&self) -> Result<String, Error> { let s = serde_json::to_string(&self.to_json())?; Ok(s) } pub fn to_json(&self) -> Value { Value::from(self.serialize_modules_json_obj()) } fn serialize_modules_json_obj(&self) -> Map<String, Value> { let mut m = Map::new(); for (modulename, values) in self.bindings.iter() { m.insert( modulename.to_owned(), Value::from(Self::serialize_methods_json_obj(values)), ); } m } fn serialize_methods_json_obj(methods: &HashMap<String, String>) -> Map<String, Value> { let mut m = Map::new(); for (methodname, symbol) in methods.iter() { m.insert(methodname.to_owned(), Value::from(symbol.to_owned())); } m } } #[cfg(test)] mod tests { fn test_file(f: &str) -> PathBuf { PathBuf::from(format!("tests/bindings/{}", f)) } use super::Bindings; use std::collections::HashMap; use std::path::PathBuf; #[test] fn explicit() { let mut explicit_map = HashMap::new(); explicit_map.insert(String::from("hello"), String::from("goodbye")); let map = Bindings::env(explicit_map); let result = map.translate("env", "hello").unwrap(); assert!(result == "goodbye"); let result = map.translate("env", "nonexistent"); if let Ok(_) = result { assert!( false, "explicit import map returned value for non-existent symbol" ) } } #[test] fn explicit_from_nonexistent_file() { let fail_map = Bindings::from_file(&test_file("nonexistent_bindings.json")); assert!( fail_map.is_err(), "ImportMap::explicit_from_file did not fail on a non-existent file" ); } #[test] fn explicit_from_garbage_file() { let fail_map = Bindings::from_file(&test_file("garbage.json")); assert!( fail_map.is_err(), "ImportMap::explicit_from_file did not fail on a garbage file" ); } #[test] fn explicit_from_file() { let map = Bindings::from_file(&test_file("bindings_test.json")) .expect("load valid bindings from file"); let result = map.translate("env", "hello").expect("hello has a binding"); assert!(result == "json is cool"); assert!( map.translate("env", "nonexistent").is_err(), "bindings from file returned value for non-existent symbol" ); } }