| 1 | // (c) 2016-2017 Productize SPRL <[email protected]> |
| 2 | |
| 3 | use std::fmt; |
| 4 | use std::mem; |
| 5 | |
| 6 | use error::SexpError; |
| 7 | /// like Into trait but works from a ref avoiding consumption or expensive clone |
| 8 | pub trait IntoSexp { |
| 9 | /// convert self into a Sexp |
| 10 | fn into_sexp(&self) -> Sexp; |
| 11 | } |
| 12 | |
| 13 | impl Into<Sexp> for Vec<Sexp> { |
| 14 | fn into(self: Vec<Sexp>) -> Sexp { |
| 15 | Sexp::List(self) |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | impl Into<Sexp> for String { |
| 20 | fn into(self: String) -> Sexp { |
| 21 | Sexp::String(self) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | impl<'a> From<&'a str> for Sexp { |
| 26 | fn from(t: &str) -> Sexp { |
| 27 | Sexp::String(t.into()) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | impl<'a> From<&'a String> for Sexp { |
| 32 | fn from(t: &String) -> Sexp { |
| 33 | Sexp::String(t.clone()) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl Into<Sexp> for i64 { |
| 38 | fn into(self: i64) -> Sexp { |
| 39 | Sexp::String(format!("{}", self)) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | impl Into<Sexp> for f64 { |
| 44 | fn into(self: f64) -> Sexp { |
| 45 | Sexp::String(format!("{}", self)) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl<'a> From<(&'a str, Sexp)> for Sexp { |
| 50 | fn from(kv: (&str, Sexp)) -> Sexp { |
| 51 | let (name, value) = kv; |
| 52 | let mut v = vec![]; |
| 53 | v.push(name.into()); |
| 54 | v.push(value); |
| 55 | v.into() |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl<'a, T: fmt::Display> From<(&'a str, &'a T)> for Sexp { |
| 60 | fn from(kv: (&str, &T)) -> Sexp { |
| 61 | let (name, value) = kv; |
| 62 | let mut v = vec![]; |
| 63 | v.push(name.into()); |
| 64 | v.push(format!("{}", value).into()); |
| 65 | v.into() |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// a symbolic-expression structure |
| 70 | /// Can be a string or a list or nothing |
| 71 | /// |
| 72 | /// `String` shape: hello |
| 73 | /// `List` shape: (...) |
| 74 | /// `Empty shape: |
| 75 | #[derive(Debug, Clone, PartialEq)] |
| 76 | pub enum Sexp { |
| 77 | /// plain String symbolic-expression |
| 78 | String(String), |
| 79 | /// list symbolic-expression |
| 80 | List(Vec<Sexp>), |
| 81 | /// empty, trivial symbolic-expression |
| 82 | Empty, |
| 83 | } |
| 84 | |
| 85 | // Following the KiCad file formats specification chapter 4.4 - Identifiers and Strings: |
| 86 | // A string may not contain an actual newline or carriage return, |
| 87 | // but it may use an escape sequence to encode a // newline, such as \n. |
| 88 | // If a string has any of the following conditions, then it must be quoted |
| 89 | // with a leading and trailing double quote |
| 90 | // character, otherwise it is acceptable to not quote the string: |
| 91 | // 1. has one or more of the following 4 separator bytes: ASCII space, |
| 92 | // tab, '(', or ')'. |
| 93 | // 2. has one or more of the following bytes: '%', '{', or '}'. |
| 94 | // 3. has a length of zero bytes, and you need a place holder for the field, |
| 95 | // then use "". |
| 96 | // 4. includes a byte of '-', and this byte is not in the first position of |
| 97 | // the string. |
| 98 | // |
| 99 | |
| 100 | // Joost remark: kicad no longer seems to follow Rule 4. |
| 101 | // so we don't either |
| 102 | |
| 103 | /// encode a string according to the guidelines given by Kicad |
| 104 | pub fn encode_string(s: &str) -> String { |
| 105 | // fn rule_4(s:&str) -> bool { |
| 106 | // s.contains('-') && s.len() > 1 && s.as_bytes()[0] != 45 |
| 107 | // } |
| 108 | if s.contains('(') || s.contains(' ') || s.contains(')') || s.contains('\t') || s.contains('{') |
| 109 | || s.contains('}') || s.contains('}') || s.contains('%') || s.is_empty() |
| 110 | // || rule_4(s) |
| 111 | { |
| 112 | format!("\"{}\"", s) |
| 113 | } else { |
| 114 | String::from(s) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | impl Sexp { |
| 119 | /// create an empty symbolic-expression |
| 120 | #[deprecated(since = "4.0.0", note = "please use `Sexp::default()` instead")] |
| 121 | pub fn new_empty() -> Sexp { |
| 122 | Sexp::Empty |
| 123 | } |
| 124 | |
| 125 | /// create a String type symbolic-expression |
| 126 | #[deprecated(since = "4.0.3", note = "please use `.into()` instead")] |
| 127 | pub fn new_string<T>(s: T) -> Sexp |
| 128 | where |
| 129 | T: fmt::Display, |
| 130 | { |
| 131 | format!("{}", s).into() |
| 132 | } |
| 133 | |
| 134 | /// create a list type symbolic-expression |
| 135 | #[deprecated(since = "4.0.3", note = "please use `.into()` instead")] |
| 136 | pub fn new_list(v: Vec<Sexp>) -> Sexp { |
| 137 | Sexp::List(v) |
| 138 | } |
| 139 | |
| 140 | /// create an empty list type symbolic-expression |
| 141 | pub fn start(name: &str) -> Sexp { |
| 142 | let mut v = vec![]; |
| 143 | v.push(Sexp::String(name.into())); |
| 144 | Sexp::List(v) |
| 145 | } |
| 146 | |
| 147 | /// push an element in a list |
| 148 | pub fn push<T: Into<Sexp>>(&mut self, element: T) { |
| 149 | match *self { |
| 150 | Sexp::List(ref mut v) => v.push(element.into()), |
| 151 | _ => panic!("Only use push on lists!"), |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// create a list type symbolic-expression where |
| 156 | /// the first element of the list is a string that indicates |
| 157 | /// the name, the remainder is filled in via the provided |
| 158 | /// fill function |
| 159 | /// |
| 160 | /// shape: (name ...) |
| 161 | pub fn new_named_list<F>(name: &str, fill: F) -> Sexp |
| 162 | where |
| 163 | F: Fn(&mut Vec<Sexp>), |
| 164 | { |
| 165 | let mut v = vec![]; |
| 166 | v.push(name.into()); |
| 167 | fill(&mut v); |
| 168 | Sexp::List(v) |
| 169 | } |
| 170 | |
| 171 | /// create a list type symbolic-expression where |
| 172 | /// the first element of the list is a string that indicates |
| 173 | /// the name |
| 174 | #[deprecated(since = "4.0.3", note = "please use `.into()` instead")] |
| 175 | pub fn new_named<T>(name: &str, value: T) -> Sexp |
| 176 | where |
| 177 | T: fmt::Display, |
| 178 | { |
| 179 | let mut v = vec![]; |
| 180 | v.push(name.into()); |
| 181 | v.push(format!("{}", value).into()); |
| 182 | v.into() |
| 183 | } |
| 184 | |
| 185 | /// create a list type symbolic-expression where |
| 186 | /// the first element of the list is a string that indicates |
| 187 | /// the name, and the second is another symbolic-expression |
| 188 | /// created via the IntoSexp trait |
| 189 | #[deprecated(since = "4.0.5", note = "please use `.into()` on a tuple instead")] |
| 190 | pub fn new_named_sexp<T>(name: &str, value: &T) -> Sexp |
| 191 | where |
| 192 | T: IntoSexp, |
| 193 | { |
| 194 | let mut v = vec![]; |
| 195 | v.push(name.into()); |
| 196 | v.push(value.into_sexp()); |
| 197 | Sexp::List(v) |
| 198 | } |
| 199 | |
| 200 | /// if the expression is a list, extract the `Vec<Sexp>` |
| 201 | /// from it and swap it with Empty |
| 202 | pub fn take_list(&mut self) -> Result<Vec<Sexp>, SexpError> { |
| 203 | let mut e = Sexp::Empty; |
| 204 | mem::swap(&mut e, self); |
| 205 | match e { |
| 206 | Sexp::List(v) => Ok(v), |
| 207 | _ => Err(format!("Not a list: {}", e).into()), |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// if the expression is a `String`, take it out and swap it with Empty |
| 212 | pub fn take_string(&mut self) -> Result<String, SexpError> { |
| 213 | let mut e = Sexp::Empty; |
| 214 | mem::swap(&mut e, self); |
| 215 | match e { |
| 216 | Sexp::String(s) => Ok(s), |
| 217 | _ => Err(format!("Not a string: {}", e).into()), |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// create a symbolic-expression via the `IntoSexp` trait |
| 222 | pub fn from<T: IntoSexp>(t: &T) -> Sexp { |
| 223 | t.into_sexp() |
| 224 | } |
| 225 | |
| 226 | /// access the symbolic-expression as if it is a List |
| 227 | pub fn list(&self) -> Result<&Vec<Sexp>, SexpError> { |
| 228 | match *self { |
| 229 | Sexp::List(ref v) => Ok(v), |
| 230 | _ => Err(format!("not a list: {}", self).into()), |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | /// access the symbolic-expression as if it is an `&String` |
| 235 | pub fn string(&self) -> Result<&String, SexpError> { |
| 236 | match *self { |
| 237 | Sexp::String(ref s) => Ok(s), |
| 238 | _ => Err(format!("not a string: {}", self).into()), |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | /// access the symbolic-expression as if it is a `String` |
| 243 | pub fn s(&self) -> Result<String, SexpError> { |
| 244 | match *self { |
| 245 | Sexp::String(ref s) => Ok(s.clone()), |
| 246 | _ => Err(format!("not a string: {}", self).into()), |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /// is this expression a string |
| 251 | pub fn is_string(&self) -> bool { |
| 252 | match *self { |
| 253 | Sexp::String(_) => true, |
| 254 | _ => false, |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | /// is this expression a list |
| 259 | pub fn is_list(&self) -> bool { |
| 260 | match *self { |
| 261 | Sexp::List(_) => true, |
| 262 | _ => false, |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | /// access the symbolic-expression as if it is a String |
| 267 | /// that is a f64 |
| 268 | pub fn f(&self) -> Result<f64, SexpError> { |
| 269 | let s = self.string()?; |
| 270 | let f = s.parse()?; |
| 271 | Ok(f) |
| 272 | } |
| 273 | |
| 274 | /// access the symbolic-expression as if it is a String |
| 275 | /// that is an i64 |
| 276 | pub fn i(&self) -> Result<i64, SexpError> { |
| 277 | let s = self.string()?; |
| 278 | let i = s.parse()?; |
| 279 | Ok(i) |
| 280 | } |
| 281 | |
| 282 | /// access the symbolic-expression as if it is a List |
| 283 | /// assuming the first element is a String and return that |
| 284 | pub fn list_name(&self) -> Result<&String, SexpError> { |
| 285 | let l = self.list()?; |
| 286 | let l = &l[..]; |
| 287 | let a = l[0].string()?; |
| 288 | Ok(a) |
| 289 | } |
| 290 | |
| 291 | /// access the symbolic-expression as if it is a named List |
| 292 | /// where the name is provided and returns the remaining elements |
| 293 | /// after the name as a slice |
| 294 | #[deprecated(since = "4.1.4", note = "please use `iteratom::IterAtom::new` instead")] |
| 295 | pub fn slice_atom(&self, s: &str) -> Result<&[Sexp], SexpError> { |
| 296 | let v = self.list()?; |
| 297 | let v2 = &v[..]; |
| 298 | let st = v2[0].string()?; |
| 299 | if st != s { |
| 300 | return Err(format!("list {} doesn't start with {}, but with {}", self, s, st).into()); |
| 301 | }; |
| 302 | Ok(&v[1..]) |
| 303 | } |
| 304 | |
| 305 | fn slice_atom_int(&self, s: &str) -> Result<&[Sexp], SexpError> { |
| 306 | let v = self.list()?; |
| 307 | let v2 = &v[..]; |
| 308 | let st = v2[0].string()?; |
| 309 | if st != s { |
| 310 | return Err(format!("list {} doesn't start with {}, but with {}", self, s, st).into()); |
| 311 | }; |
| 312 | Ok(&v[1..]) |
| 313 | } |
| 314 | |
| 315 | /// access the symbolic-expression as if it is a named List |
| 316 | /// with two elements where the name is provided and returns |
| 317 | /// the next element in the list |
| 318 | pub fn named_value(&self, s: &str) -> Result<&Sexp, SexpError> { |
| 319 | let v = self.list()?; |
| 320 | if v.len() != 2 { |
| 321 | return Err(format!("list {} is not a named_value", s).into()); |
| 322 | } |
| 323 | let l = self.slice_atom_int(s)?; |
| 324 | Ok(&l[0]) |
| 325 | } |
| 326 | |
| 327 | /// as named_value but converted to i64 |
| 328 | pub fn named_value_i(&self, s: &str) -> Result<i64, SexpError> { |
| 329 | self.named_value(s)?.i() |
| 330 | } |
| 331 | |
| 332 | /// as named_value but converted to f64 |
| 333 | pub fn named_value_f(&self, s: &str) -> Result<f64, SexpError> { |
| 334 | self.named_value(s)?.f() |
| 335 | } |
| 336 | |
| 337 | /// as named_value but converted to `&String` |
| 338 | pub fn named_value_string(&self, s: &str) -> Result<&String, SexpError> { |
| 339 | self.named_value(s)?.string() |
| 340 | } |
| 341 | |
| 342 | /// as named_value but converted to `String` |
| 343 | pub fn named_value_s(&self, s: &str) -> Result<String, SexpError> { |
| 344 | Ok(self.named_value(s)?.string()?.clone()) |
| 345 | } |
| 346 | |
| 347 | /// get the symbolic-expression as a list which starts |
| 348 | /// with a string that indicates the name and has num more |
| 349 | /// elements, returns those elements |
| 350 | #[deprecated(since = "4.1.4", note = "please use `iteratom::IterAtom::new` instead")] |
| 351 | pub fn slice_atom_num(&self, s: &str, num: usize) -> Result<&[Sexp], SexpError> { |
| 352 | let v = self.list()?; |
| 353 | let v2 = &v[..]; |
| 354 | let st = v2[0].string()?; |
| 355 | if st != s { |
| 356 | return Err(format!("list doesn't start with {}, but with {}", s, st).into()); |
| 357 | }; |
| 358 | if v.len() != (num + 1) { |
| 359 | return Err( |
| 360 | format!( |
| 361 | "list ({}) doesn't have {} elements but {}", |
| 362 | s, |
| 363 | num, |
| 364 | v.len() - 1 |
| 365 | ).into(), |
| 366 | ); |
| 367 | } |
| 368 | Ok(&v[1..]) |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | impl fmt::Display for Sexp { |
| 373 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
| 374 | match *self { |
| 375 | Sexp::String(ref s) => write!(f, "{}", encode_string(s)), |
| 376 | Sexp::List(ref v) => { |
| 377 | write!(f, "(")?; |
| 378 | let l = v.len(); |
| 379 | for (i, x) in v.iter().enumerate() { |
| 380 | if i < l - 1 { |
| 381 | write!(f, "{} ", x)?; |
| 382 | } else { |
| 383 | write!(f, "{}", x)?; |
| 384 | } |
| 385 | } |
| 386 | write!(f, ")") |
| 387 | } |
| 388 | Sexp::Empty => Ok(()), |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | impl Default for Sexp { |
| 394 | fn default() -> Sexp { |
| 395 | Sexp::Empty |
| 396 | } |
| 397 | } |