| 1 | use document; |
| 2 | use document::{YamlNode, YamlNodeData}; |
| 3 | use ffi::{YamlErrorType, YamlScalarStyle}; |
| 4 | use error::{YamlMark, YamlError, YamlErrorContext}; |
| 5 | |
| 6 | use std::f64; |
| 7 | use std::char; |
| 8 | use regex::Regex; |
| 9 | |
| 10 | pub trait YamlConstructor<T, E> { |
| 11 | fn construct_scalar(&self, scalar: document::YamlScalarData) -> Result<T, E>; |
| 12 | fn construct_sequence(&self, sequence: document::YamlSequenceData) -> Result<T, E>; |
| 13 | fn construct_mapping(&self, mapping: document::YamlMappingData) -> Result<T, E>; |
| 14 | |
| 15 | fn construct<'r>(&self, node: document::YamlNode<'r>) -> Result<T, E> { |
| 16 | match node { |
| 17 | YamlNode::YamlScalarNode(scalar) => self.construct_scalar(scalar), |
| 18 | YamlNode::YamlSequenceNode(sequence) => self.construct_sequence(sequence), |
| 19 | YamlNode::YamlMappingNode(mapping) => self.construct_mapping(mapping) |
| 20 | } |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | #[derive(PartialEq, Clone, Debug)] |
| 25 | pub enum YamlStandardData { |
| 26 | YamlInteger(isize), |
| 27 | YamlFloat(f64), |
| 28 | YamlString(String), |
| 29 | YamlNull, |
| 30 | YamlBool(bool), |
| 31 | YamlSequence(Vec<YamlStandardData>), |
| 32 | YamlMapping(Vec<(YamlStandardData, YamlStandardData)>), |
| 33 | } |
| 34 | |
| 35 | #[derive(Clone)] |
| 36 | pub struct YamlStandardConstructor { |
| 37 | dec_int_pat:Regex, |
| 38 | oct_int_pat:Regex, |
| 39 | hex_int_pat:Regex, |
| 40 | bin_int_pat:Regex, |
| 41 | flt_pat:Regex, |
| 42 | pos_inf_pat:Regex, |
| 43 | neg_inf_pat:Regex, |
| 44 | nan_pat:Regex, |
| 45 | null_pat:Regex, |
| 46 | true_pat:Regex, |
| 47 | false_pat:Regex |
| 48 | } |
| 49 | |
| 50 | fn standard_error(message: String, mark: &YamlMark) -> YamlError { |
| 51 | let context = YamlErrorContext { |
| 52 | byte_offset: mark.index, |
| 53 | problem_mark: *mark, |
| 54 | context: None, |
| 55 | context_mark: *mark, |
| 56 | }; |
| 57 | |
| 58 | YamlError { |
| 59 | kind: YamlErrorType::YAML_PARSER_ERROR, |
| 60 | problem: Some(message), |
| 61 | io_error: None, |
| 62 | context: Some(context) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | fn take(iter: &mut Iterator<Item=char>, n: usize) -> String |
| 67 | { |
| 68 | let mut s = String::new(); |
| 69 | for _ in 0..n { |
| 70 | match iter.next() { |
| 71 | Some(c) => s.push(c), |
| 72 | None => break |
| 73 | } |
| 74 | } |
| 75 | return s; |
| 76 | } |
| 77 | |
| 78 | impl YamlStandardConstructor { |
| 79 | pub fn new() -> YamlStandardConstructor { |
| 80 | YamlStandardConstructor { |
| 81 | dec_int_pat: Regex::new(r"^[-+]?(0|[1-9][0-9_]*)$").unwrap(), |
| 82 | oct_int_pat: Regex::new(r"^([-+]?)0o?([0-7_]+)$").unwrap(), |
| 83 | hex_int_pat: Regex::new(r"^([-+]?)0x([0-9a-fA-F_]+)$").unwrap(), |
| 84 | bin_int_pat: Regex::new(r"^([-+]?)0b([0-1_]+)$").unwrap(), |
| 85 | flt_pat: Regex::new(r"^([-+]?)(\.[0-9]+|[0-9]+(\.[0-9]*)?([eE][-+]?[0-9]+)?)$").unwrap(), |
| 86 | pos_inf_pat: Regex::new(r"^[+]?(\.inf|\.Inf|\.INF)$").unwrap(), |
| 87 | neg_inf_pat: Regex::new(r"^-(\.inf|\.Inf|\.INF)$").unwrap(), |
| 88 | nan_pat: Regex::new(r"^(\.nan|\.NaN|\.NAN)$").unwrap(), |
| 89 | null_pat: Regex::new(r"^(null|Null|NULL|~)$").unwrap(), |
| 90 | true_pat: Regex::new(r"^(true|True|TRUE|yes|Yes|YES)$").unwrap(), |
| 91 | false_pat: Regex::new(r"^(false|False|FALSE|no|No|NO)$").unwrap() |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | fn parse_double_quoted(value: &str, mark: &YamlMark) -> Result<String, YamlError> { |
| 96 | let mut buf = String::new(); |
| 97 | let mut it = value.chars(); |
| 98 | |
| 99 | loop { |
| 100 | match it.next() { |
| 101 | None => return Ok(buf), |
| 102 | Some('\\') => { |
| 103 | // escape sequences |
| 104 | match it.next() { |
| 105 | None => return Err(standard_error( |
| 106 | "unexpected end of string after escape".to_string(), |
| 107 | mark |
| 108 | )), |
| 109 | Some('0') => buf.push('\x00'), // null |
| 110 | Some('a') => buf.push('\x07'), // ASCII bell |
| 111 | Some('b') => buf.push('\x08'), // backspace |
| 112 | Some('t') | Some('\t') => buf.push('\t'), // horizontal tab |
| 113 | Some('n') => buf.push('\n'), // linefeed |
| 114 | Some('v') => buf.push('\x0b'), // vertical tab |
| 115 | Some('f') => buf.push('\x0c'), // form feed |
| 116 | Some('r') => buf.push('\x0d'), // carriage return |
| 117 | Some('e') => buf.push('\x1b'), // ASCII escape |
| 118 | Some('N') => buf.push('\u{85}'), // unicode next line |
| 119 | Some('_') => buf.push('\u{a0}'), // unicode non-breaking space |
| 120 | Some('L') => buf.push('\u{2028}'), // unicode line separator |
| 121 | Some('P') => buf.push('\u{2029}'), // unicode paragraph separator |
| 122 | Some('x') => { |
| 123 | let code:String = take(&mut it, 2); |
| 124 | match parse_escape_sequence(&code[..], 2) { |
| 125 | Some(c) => buf.push(c), |
| 126 | None => return Err(standard_error( |
| 127 | format!("invalid escape sequence {}", code), |
| 128 | mark |
| 129 | )) |
| 130 | } |
| 131 | }, |
| 132 | Some('u') => { |
| 133 | let code:String = take(&mut it, 4); |
| 134 | match parse_escape_sequence(&code[..], 4) { |
| 135 | Some(c) => buf.push(c), |
| 136 | None => return Err(standard_error( |
| 137 | format!("invalid escape sequence {}", code), |
| 138 | mark |
| 139 | )) |
| 140 | } |
| 141 | }, |
| 142 | Some('U') => { |
| 143 | let code:String = take(&mut it, 8); |
| 144 | match parse_escape_sequence(&code[..], 8) { |
| 145 | Some(c) => buf.push(c), |
| 146 | None => return Err(standard_error( |
| 147 | format!("invalid escape sequence {}", code), |
| 148 | mark |
| 149 | )) |
| 150 | } |
| 151 | }, |
| 152 | Some(c) => buf.push(c) |
| 153 | } |
| 154 | }, |
| 155 | Some(c) => buf.push(c) |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | fn parse_escape_sequence(rep: &str, expected_len: usize) -> Option<char> { |
| 162 | match u32::from_str_radix(rep, 16) { |
| 163 | Ok(code) if rep.len() == expected_len => char::from_u32(code), |
| 164 | _ => None |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | fn parse_int(sign: &str, data: &str, radix: u32) -> isize { |
| 169 | let sign_flag = if sign == "-" { |
| 170 | -1 |
| 171 | } else { |
| 172 | 1 |
| 173 | }; |
| 174 | |
| 175 | let filtered:String = data.chars().filter(|&c| c != '_').collect(); |
| 176 | let unsigned:isize = isize::from_str_radix(&filtered[..], radix).unwrap(); |
| 177 | return unsigned * sign_flag; |
| 178 | } |
| 179 | |
| 180 | fn parse_float(sign: &str, data: &str) -> f64 { |
| 181 | let unsigned:f64 = data.parse().unwrap(); |
| 182 | if sign == "-" { |
| 183 | return -unsigned; |
| 184 | } else { |
| 185 | return unsigned; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | impl YamlConstructor<YamlStandardData, YamlError> for YamlStandardConstructor { |
| 190 | fn construct_scalar(&self, scalar: document::YamlScalarData) -> Result<YamlStandardData, YamlError> { |
| 191 | let value = scalar.get_value(); |
| 192 | let mark = scalar.start_mark(); |
| 193 | |
| 194 | match scalar.style() { |
| 195 | YamlScalarStyle::YamlPlainScalarStyle => { |
| 196 | match self.bin_int_pat.captures(&value[..]) { |
| 197 | Some(caps) => return Ok(YamlStandardData::YamlInteger(parse_int( |
| 198 | &caps[1], &caps[2], 2))), |
| 199 | None => () |
| 200 | }; |
| 201 | match self.oct_int_pat.captures(&value[..]) { |
| 202 | Some(caps) => return Ok(YamlStandardData::YamlInteger(parse_int( |
| 203 | &caps[1], &caps[2], 8))), |
| 204 | None => () |
| 205 | }; |
| 206 | match self.hex_int_pat.captures(&value[..]) { |
| 207 | Some(caps) => return Ok(YamlStandardData::YamlInteger(parse_int( |
| 208 | &caps[1], &caps[2], 16))), |
| 209 | None => () |
| 210 | }; |
| 211 | |
| 212 | if self.dec_int_pat.is_match(&value[..]) { |
| 213 | return Ok(YamlStandardData::YamlInteger(parse_int("", &value[..], 10))); |
| 214 | } |
| 215 | |
| 216 | match self.flt_pat.captures(&value[..]) { |
| 217 | Some(caps) => return Ok(YamlStandardData::YamlFloat(parse_float( |
| 218 | &caps[1], &caps[2]))), |
| 219 | None => () |
| 220 | }; |
| 221 | |
| 222 | if self.pos_inf_pat.is_match(&value[..]) { |
| 223 | Ok(YamlStandardData::YamlFloat(f64::INFINITY)) |
| 224 | } else if self.neg_inf_pat.is_match(&value[..]) { |
| 225 | Ok(YamlStandardData::YamlFloat(f64::NEG_INFINITY)) |
| 226 | } else if self.nan_pat.is_match(&value[..]) { |
| 227 | Ok(YamlStandardData::YamlFloat(f64::NAN)) |
| 228 | } else if self.null_pat.is_match(&value[..]) { |
| 229 | Ok(YamlStandardData::YamlNull) |
| 230 | } else if self.true_pat.is_match(&value[..]) { |
| 231 | Ok(YamlStandardData::YamlBool(true)) |
| 232 | } else if self.false_pat.is_match(&value[..]) { |
| 233 | Ok(YamlStandardData::YamlBool(false)) |
| 234 | } else { |
| 235 | Ok(YamlStandardData::YamlString(value)) |
| 236 | } |
| 237 | }, |
| 238 | YamlScalarStyle::YamlDoubleQuotedScalarStyle => { |
| 239 | YamlStandardConstructor::parse_double_quoted(&value[..], &mark).map(YamlStandardData::YamlString) |
| 240 | }, |
| 241 | _ => { |
| 242 | Ok(YamlStandardData::YamlString(value)) |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn construct_sequence(&self, sequence: document::YamlSequenceData) -> Result<YamlStandardData, YamlError> { |
| 248 | let res:Result<Vec<YamlStandardData>, YamlError> = sequence.values().map(|node| { self.construct(node) }).collect(); |
| 249 | res.map(|list| YamlStandardData::YamlSequence(list)) |
| 250 | } |
| 251 | |
| 252 | fn construct_mapping(&self, mapping: document::YamlMappingData) -> Result<YamlStandardData, YamlError> { |
| 253 | let pairs = mapping.pairs().map(|(key_node, value_node)| { |
| 254 | match self.construct(key_node) { |
| 255 | Ok(key) => match self.construct(value_node) { |
| 256 | Ok(value) => Ok((key, value)), |
| 257 | Err(e) => Err(e) |
| 258 | }, |
| 259 | Err(e) => Err(e) |
| 260 | } |
| 261 | }); |
| 262 | let res:Result<Vec<(YamlStandardData, YamlStandardData)>, YamlError> = pairs.collect(); |
| 263 | res.map(YamlStandardData::YamlMapping) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | #[cfg(test)] |
| 268 | mod test { |
| 269 | use super::YamlStandardData::*; |
| 270 | use parser::{YamlParser, YamlByteParser}; |
| 271 | use std::f64; |
| 272 | use ffi::YamlEncoding::YamlUtf8Encoding; |
| 273 | use constructor::{YamlConstructor, YamlStandardConstructor}; |
| 274 | |
| 275 | #[test] |
| 276 | fn test_standard_constructor() { |
| 277 | let data = "[1, 2, 3]"; |
| 278 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 279 | |
| 280 | match parser.load().next() { |
| 281 | Some(Ok(doc)) => { |
| 282 | let ctor = YamlStandardConstructor::new(); |
| 283 | assert_eq!(Ok(YamlSequence(vec![YamlInteger(1), YamlInteger(2), YamlInteger(3)])), ctor.construct(doc.root().unwrap())) |
| 284 | }, |
| 285 | _ => panic!("unexpected result") |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn test_integer_parser() { |
| 291 | let data = "[0o10, 0x21, -30]"; |
| 292 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 293 | |
| 294 | match parser.load().next() { |
| 295 | Some(Ok(doc)) => { |
| 296 | let ctor = YamlStandardConstructor::new(); |
| 297 | assert_eq!(Ok(YamlSequence(vec![YamlInteger(0o10), YamlInteger(0x21), YamlInteger(-30)])), ctor.construct(doc.root().unwrap())) |
| 298 | }, |
| 299 | _ => panic!("unexpected result") |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | #[test] |
| 304 | fn test_float_parser() { |
| 305 | let data = "[0.3, -.4, 1e+2, -1.2e-3]"; |
| 306 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 307 | |
| 308 | match parser.load().next() { |
| 309 | Some(Ok(doc)) => { |
| 310 | let ctor = YamlStandardConstructor::new(); |
| 311 | let value = ctor.construct(doc.root().unwrap()); |
| 312 | match value { |
| 313 | Ok(YamlSequence(seq)) => { |
| 314 | match &seq[..] { |
| 315 | &[YamlFloat(f1), YamlFloat(f2), YamlFloat(f3), YamlFloat(f4)] => { |
| 316 | assert!((f1 - 0.3).abs() < 1.0e-6); |
| 317 | assert!((f2 + 0.4) < 1.0e-6); |
| 318 | assert!((f3 - 1e+2) < 1.0e-6); |
| 319 | assert!((f4 + 1.2e-3) < 1.0e-6); |
| 320 | }, |
| 321 | _ => panic!("unexpected sequence") |
| 322 | } |
| 323 | }, |
| 324 | _ => panic!("unexpected result") |
| 325 | } |
| 326 | }, |
| 327 | _ => panic!("document parse failure") |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | #[test] |
| 332 | fn test_inf_parser() { |
| 333 | let data = "[.inf, -.INF]"; |
| 334 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 335 | |
| 336 | match parser.load().next() { |
| 337 | Some(Ok(doc)) => { |
| 338 | let ctor = YamlStandardConstructor::new(); |
| 339 | assert_eq!(Ok(YamlSequence(vec![YamlFloat(f64::INFINITY), YamlFloat(f64::NEG_INFINITY)])), ctor.construct(doc.root().unwrap())) |
| 340 | }, |
| 341 | _ => panic!("document parse failure") |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn test_misc_parser() { |
| 347 | let data = "[yes, False, ~]"; |
| 348 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 349 | |
| 350 | match parser.load().next() { |
| 351 | Some(Ok(doc)) => { |
| 352 | let ctor = YamlStandardConstructor::new(); |
| 353 | assert_eq!(Ok(YamlSequence(vec![YamlBool(true), YamlBool(false), YamlNull])), ctor.construct(doc.root().unwrap())) |
| 354 | }, |
| 355 | _ => panic!("document parse failure") |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn test_double_quoted_parser() { |
| 361 | let data = r#""hello, \"world\"""#; |
| 362 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 363 | |
| 364 | match parser.load().next() { |
| 365 | Some(Ok(doc)) => { |
| 366 | let ctor = YamlStandardConstructor::new(); |
| 367 | assert_eq!(Ok(YamlString("hello, \"world\"".to_string())), ctor.construct(doc.root().unwrap())) |
| 368 | }, |
| 369 | _ => panic!("document parse failure") |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn test_single_quoted_parser() { |
| 375 | let data = r#"'here''s to "quotes"'"#; |
| 376 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 377 | |
| 378 | match parser.load().next() { |
| 379 | Some(Ok(doc)) => { |
| 380 | let ctor = YamlStandardConstructor::new(); |
| 381 | assert_eq!(Ok(YamlString(r#"here's to "quotes""#.to_string())), ctor.construct(doc.root().unwrap())) |
| 382 | }, |
| 383 | _ => panic!("document parse failure") |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | #[test] |
| 388 | fn test_underlined_integer() { |
| 389 | let data = "[1_000, -2_000_000]"; |
| 390 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 391 | |
| 392 | match parser.load().next() { |
| 393 | Some(Ok(doc)) => { |
| 394 | let ctor = YamlStandardConstructor::new(); |
| 395 | assert_eq!(Ok(YamlSequence(vec![YamlInteger(1000), YamlInteger(-2000000)])), ctor.construct(doc.root().unwrap())) |
| 396 | }, |
| 397 | _ => panic!("document parse failure") |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn test_negative_radix() { |
| 403 | let data = "[-0x30, -0700, -0b110]"; |
| 404 | let parser = YamlByteParser::init(data.as_bytes(), YamlUtf8Encoding); |
| 405 | |
| 406 | match parser.load().next() { |
| 407 | Some(Ok(doc)) => { |
| 408 | let ctor = YamlStandardConstructor::new(); |
| 409 | assert_eq!(Ok(YamlSequence(vec![YamlInteger(-48), YamlInteger(-448), YamlInteger(-6)])), ctor.construct(doc.root().unwrap())) |
| 410 | }, |
| 411 | _ => panic!("document parse failure") |
| 412 | } |
| 413 | } |
| 414 | } |