From 2fcd829b1d9c70d0981411b4f4adca9124985b54 Mon Sep 17 00:00:00 2001 From: Andrzej Janik Date: Thu, 4 Jun 2015 20:23:46 +0200 Subject: Disallow table redefinitions --- src/parser.rs | 51 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 19 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index 9a15de8..ccf0d3a 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -162,7 +162,7 @@ impl<'a> Parser<'a> { /// If an error occurs, the `errors` field of this parser can be consulted /// to determine the cause of the parse failure. pub fn parse(&mut self) -> Option { - let mut ret = BTreeMap::new(); + let mut ret = TomlTable(BTreeMap::new(), false); while self.peek(0).is_some() { self.ws(); if self.newline() { continue } @@ -189,7 +189,7 @@ impl<'a> Parser<'a> { if keys.len() == 0 { return None } // Build the section table - let mut table = BTreeMap::new(); + let mut table = TomlTable(BTreeMap::new(), false); if !self.values(&mut table) { return None } if array { self.insert_array(&mut ret, &*keys, Table(table), start) @@ -715,7 +715,7 @@ impl<'a> Parser<'a> { fn inline_table(&mut self, _start: usize) -> Option { if !self.expect('{') { return None } self.ws(); - let mut ret = BTreeMap::new(); + let mut ret = TomlTable(BTreeMap::new(), true); if self.eat('}') { return Some(Table(ret)) } loop { let lo = self.next_pos(); @@ -734,14 +734,14 @@ impl<'a> Parser<'a> { fn insert(&mut self, into: &mut TomlTable, key: String, value: Value, key_lo: usize) { - if into.contains_key(&key) { + if into.0.contains_key(&key) { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), desc: format!("duplicate key: `{}`", key), }) } else { - into.insert(key, value); + into.0.insert(key, value); } } @@ -751,8 +751,8 @@ impl<'a> Parser<'a> { for part in keys[..keys.len() - 1].iter() { let tmp = cur; - if tmp.contains_key(part) { - match *tmp.get_mut(part).unwrap() { + if tmp.0.contains_key(part) { + match *tmp.0.get_mut(part).unwrap() { Table(ref mut table) => { cur = table; continue @@ -785,8 +785,8 @@ impl<'a> Parser<'a> { } // Initialize an empty table as part of this sub-key - tmp.insert(part.clone(), Table(BTreeMap::new())); - match *tmp.get_mut(part).unwrap() { + tmp.0.insert(part.clone(), Table(TomlTable(BTreeMap::new(), false))); + match *tmp.0.get_mut(part).unwrap() { Table(ref mut inner) => cur = inner, _ => unreachable!(), } @@ -802,22 +802,22 @@ impl<'a> Parser<'a> { }; let key = format!("{}", key); let mut added = false; - if !into.contains_key(&key) { - into.insert(key.clone(), Table(BTreeMap::new())); + if !into.0.contains_key(&key) { + into.0.insert(key.clone(), Table(TomlTable(BTreeMap::new(), true))); added = true; } - match into.get_mut(&key) { + match into.0.get_mut(&key) { Some(&mut Table(ref mut table)) => { - let any_tables = table.values().any(|v| v.as_table().is_some()); - if !any_tables && !added { + let any_tables = table.0.values().any(|v| v.as_table().is_some()); + if !added && (!any_tables || table.1) { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), desc: format!("redefinition of table `{}`", key), }); } - for (k, v) in value.into_iter() { - if table.insert(k.clone(), v).is_some() { + for (k, v) in value.0.into_iter() { + if table.0.insert(k.clone(), v).is_some() { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), @@ -844,10 +844,10 @@ impl<'a> Parser<'a> { None => return, }; let key = format!("{}", key); - if !into.contains_key(&key) { - into.insert(key.clone(), Array(Vec::new())); + if !into.0.contains_key(&key) { + into.0.insert(key.clone(), Array(Vec::new())); } - match *into.get_mut(&key).unwrap() { + match *into.0.get_mut(&key).unwrap() { Array(ref mut vec) => { match vec.first() { Some(ref v) if !v.same_type(&value) => { @@ -1333,4 +1333,17 @@ trimmed in raw strings. c = 2 ", "duplicate key `c` in table"); } + + #[test] + fn bad_table_redefine() { + let mut p = Parser::new(" + [a] + foo=\"bar\" + [a.b] + foo=\"bar\" + [a] + baz=\"bar\" + "); + assert!(p.parse().is_none()); + } } -- cgit v1.2.3 From 8487b63c97080296269242c31f36a557a90da0cf Mon Sep 17 00:00:00 2001 From: Andrzej Janik Date: Sat, 6 Jun 2015 18:11:48 +0200 Subject: Rework fix for table redefinition to avoid breaking AST-compatiblity --- src/parser.rs | 127 +++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 103 insertions(+), 24 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index ccf0d3a..068bf1d 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -5,13 +5,92 @@ use std::error::Error; use std::fmt; use std::str; -use Table as TomlTable; -use Value::{self, Array, Table, Float, Integer, Boolean, Datetime}; - macro_rules! try { ($e:expr) => (match $e { Some(s) => s, None => return None }) } +/* + * We redefine Array, Table and Value, because we need to keep track of + * encountered table definitions, eg when parsing: + * [a] + * [a.b] + * [a] + * we have to error out on redefinition of [a]. + * This bit of data is impossible to represent in the user-consumed table + * without breaking compatibility, so we use one AST structure during parsing + * and expose another (after running convert(...) on it) to the user. + */ +type Array = Vec; + +#[derive(PartialEq, Clone, Debug)] +// If the bool flag is true, the table was explicitly defined +// e.g. in a toml document: `[a.b] foo = "bar"`, Table `a` would be false, +// where table `b` (contained inside `a`) would be true. +struct TomlTable(BTreeMap, bool); +impl TomlTable { + fn convert(self) -> super::Table { + self.0.into_iter().map(|(k,v)| (k,v.convert())).collect() + } +} + +#[derive(PartialEq, Clone, Debug)] +enum Value { + String(String), + Integer(i64), + Float(f64), + Boolean(bool), + Datetime(String), + Array(Array), + Table(TomlTable), +} + +impl Value { + fn type_str(&self) -> &'static str { + match *self { + Value::String(..) => "string", + Value::Integer(..) => "integer", + Value::Float(..) => "float", + Value::Boolean(..) => "boolean", + Value::Datetime(..) => "datetime", + Value::Array(..) => "array", + Value::Table(..) => "table", + } + } + + fn as_table<'a>(&'a self) -> Option<&'a TomlTable> { + match *self { Value::Table(ref s) => Some(s), _ => None } + } + + fn same_type(&self, other: &Value) -> bool { + match (self, other) { + (&Value::String(..), &Value::String(..)) | + (&Value::Integer(..), &Value::Integer(..)) | + (&Value::Float(..), &Value::Float(..)) | + (&Value::Boolean(..), &Value::Boolean(..)) | + (&Value::Datetime(..), &Value::Datetime(..)) | + (&Value::Array(..), &Value::Array(..)) | + (&Value::Table(..), &Value::Table(..)) => true, + + _ => false, + } + } + + fn convert(self) -> super::Value { + match self { + Value::String(x) => super::Value::String(x), + Value::Integer(x) => super::Value::Integer(x), + Value::Float(x) => super::Value::Float(x), + Value::Boolean(x) => super::Value::Boolean(x), + Value::Datetime(x) => super::Value::Datetime(x), + Value::Array(v) => + super::Value::Array( + v.into_iter().map(|x| x.convert()).collect() + ), + Value::Table(t) => super::Value::Table(t.convert()) + } + } +} + /// Parser for converting a string to a TOML `Value` instance. /// /// This parser contains the string slice that is being parsed, and exports the @@ -161,7 +240,7 @@ impl<'a> Parser<'a> { /// /// If an error occurs, the `errors` field of this parser can be consulted /// to determine the cause of the parse failure. - pub fn parse(&mut self) -> Option { + pub fn parse(&mut self) -> Option { let mut ret = TomlTable(BTreeMap::new(), false); while self.peek(0).is_some() { self.ws(); @@ -192,7 +271,7 @@ impl<'a> Parser<'a> { let mut table = TomlTable(BTreeMap::new(), false); if !self.values(&mut table) { return None } if array { - self.insert_array(&mut ret, &*keys, Table(table), start) + self.insert_array(&mut ret, &*keys, Value::Table(table), start) } else { self.insert_table(&mut ret, &*keys, table, start) } @@ -203,7 +282,7 @@ impl<'a> Parser<'a> { if self.errors.len() > 0 { None } else { - Some(ret) + Some(ret.convert()) } } @@ -519,9 +598,9 @@ impl<'a> Parser<'a> { }; let input = input.trim_left_matches('+'); if is_float { - input.parse().ok().map(Float) + input.parse().ok().map(Value::Float) } else { - input.parse().ok().map(Integer) + input.parse().ok().map(Value::Integer) } }; if ret.is_none() { @@ -603,12 +682,12 @@ impl<'a> Parser<'a> { for _ in 0..4 { self.cur.next(); } - Some(Boolean(true)) + Some(Value::Boolean(true)) } else if rest.starts_with("false") { for _ in 0..5 { self.cur.next(); } - Some(Boolean(false)) + Some(Value::Boolean(false)) } else { let next = self.next_pos(); self.errors.push(ParserError { @@ -659,7 +738,7 @@ impl<'a> Parser<'a> { valid = valid && it.next().map(is_digit).unwrap_or(false); valid = valid && it.next().map(|c| c == 'Z').unwrap_or(false); if valid { - Some(Datetime(date.clone())) + Some(Value::Datetime(date.clone())) } else { self.errors.push(ParserError { lo: start, @@ -683,7 +762,7 @@ impl<'a> Parser<'a> { loop { // Break out early if we see the closing bracket consume(self); - if self.eat(']') { return Some(Array(ret)) } + if self.eat(']') { return Some(Value::Array(ret)) } // Attempt to parse a value, triggering an error if it's the wrong // type. @@ -709,14 +788,14 @@ impl<'a> Parser<'a> { } consume(self); if !self.expect(']') { return None } - return Some(Array(ret)) + return Some(Value::Array(ret)) } fn inline_table(&mut self, _start: usize) -> Option { if !self.expect('{') { return None } self.ws(); let mut ret = TomlTable(BTreeMap::new(), true); - if self.eat('}') { return Some(Table(ret)) } + if self.eat('}') { return Some(Value::Table(ret)) } loop { let lo = self.next_pos(); let key = try!(self.key_name()); @@ -729,7 +808,7 @@ impl<'a> Parser<'a> { if !self.expect(',') { return None } self.ws(); } - return Some(Table(ret)) + return Some(Value::Table(ret)) } fn insert(&mut self, into: &mut TomlTable, key: String, value: Value, @@ -753,13 +832,13 @@ impl<'a> Parser<'a> { if tmp.0.contains_key(part) { match *tmp.0.get_mut(part).unwrap() { - Table(ref mut table) => { + Value::Table(ref mut table) => { cur = table; continue } - Array(ref mut array) => { + Value::Array(ref mut array) => { match array.last_mut() { - Some(&mut Table(ref mut table)) => cur = table, + Some(&mut Value::Table(ref mut table)) => cur = table, _ => { self.errors.push(ParserError { lo: key_lo, @@ -785,9 +864,9 @@ impl<'a> Parser<'a> { } // Initialize an empty table as part of this sub-key - tmp.0.insert(part.clone(), Table(TomlTable(BTreeMap::new(), false))); + tmp.0.insert(part.clone(), Value::Table(TomlTable(BTreeMap::new(), false))); match *tmp.0.get_mut(part).unwrap() { - Table(ref mut inner) => cur = inner, + Value::Table(ref mut inner) => cur = inner, _ => unreachable!(), } } @@ -803,11 +882,11 @@ impl<'a> Parser<'a> { let key = format!("{}", key); let mut added = false; if !into.0.contains_key(&key) { - into.0.insert(key.clone(), Table(TomlTable(BTreeMap::new(), true))); + into.0.insert(key.clone(), Value::Table(TomlTable(BTreeMap::new(), true))); added = true; } match into.0.get_mut(&key) { - Some(&mut Table(ref mut table)) => { + Some(&mut Value::Table(ref mut table)) => { let any_tables = table.0.values().any(|v| v.as_table().is_some()); if !added && (!any_tables || table.1) { self.errors.push(ParserError { @@ -845,10 +924,10 @@ impl<'a> Parser<'a> { }; let key = format!("{}", key); if !into.0.contains_key(&key) { - into.0.insert(key.clone(), Array(Vec::new())); + into.0.insert(key.clone(), Value::Array(Vec::new())); } match *into.0.get_mut(&key).unwrap() { - Array(ref mut vec) => { + Value::Array(ref mut vec) => { match vec.first() { Some(ref v) if !v.same_type(&value) => { self.errors.push(ParserError { -- cgit v1.2.3 From 6580b77a203f360cf9f519e773b1d89de4d1336b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 7 Jun 2015 22:38:36 -0700 Subject: Re-structure control flow a bit + modernization --- src/parser.rs | 87 ++++++++++++++++++++++++----------------------------------- 1 file changed, 35 insertions(+), 52 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index 068bf1d..d9c04cb 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -9,7 +9,7 @@ macro_rules! try { ($e:expr) => (match $e { Some(s) => s, None => return None }) } -/* +/* * We redefine Array, Table and Value, because we need to keep track of * encountered table definitions, eg when parsing: * [a] @@ -56,7 +56,7 @@ impl Value { Value::Table(..) => "table", } } - + fn as_table<'a>(&'a self) -> Option<&'a TomlTable> { match *self { Value::Table(ref s) => Some(s), _ => None } } @@ -254,9 +254,8 @@ impl<'a> Parser<'a> { let mut keys = Vec::new(); loop { self.ws(); - match self.key_name() { - Some(s) => keys.push(s), - None => {} + if let Some(s) = self.key_name() { + keys.push(s); } self.ws(); if self.eat(']') { @@ -293,18 +292,13 @@ impl<'a> Parser<'a> { self.finish_string(start, false) } else { let mut ret = String::new(); - loop { - match self.cur.clone().next() { - Some((_, ch)) => { - match ch { - 'a' ... 'z' | - 'A' ... 'Z' | - '0' ... '9' | - '_' | '-' => { self.cur.next(); ret.push(ch) } - _ => break, - } - } - None => break + while let Some((_, ch)) = self.cur.clone().next() { + match ch { + 'a' ... 'z' | + 'A' ... 'Z' | + '0' ... '9' | + '_' | '-' => { self.cur.next(); ret.push(ch) } + _ => break, } } Some(ret) @@ -423,9 +417,8 @@ impl<'a> Parser<'a> { return Some(ret) } Some((pos, '\\')) => { - match escape(self, pos, multiline) { - Some(c) => ret.push(c), - None => {} + if let Some(c) = escape(self, pos, multiline) { + ret.push(c); } } Some((pos, ch)) if ch < '\u{1f}' => { @@ -470,32 +463,26 @@ impl<'a> Parser<'a> { } else { "invalid" }; - match u32::from_str_radix(num, 16).ok() { - Some(n) => { - match char::from_u32(n) { - Some(c) => { - me.cur.by_ref().skip(len - 1).next(); - return Some(c) - } - None => { - me.errors.push(ParserError { - lo: pos + 1, - hi: pos + 5, - desc: format!("codepoint `{:x}` is \ - not a valid unicode \ - codepoint", n), - }) - } - } - } - None => { + if let Some(n) = u32::from_str_radix(num, 16).ok() { + if let Some(c) = char::from_u32(n) { + me.cur.by_ref().skip(len - 1).next(); + return Some(c) + } else { me.errors.push(ParserError { - lo: pos, - hi: pos + 1, - desc: format!("expected {} hex digits \ - after a `{}` escape", len, c), + lo: pos + 1, + hi: pos + 5, + desc: format!("codepoint `{:x}` is \ + not a valid unicode \ + codepoint", n), }) } + } else { + me.errors.push(ParserError { + lo: pos, + hi: pos + 1, + desc: format!("expected {} hex digits \ + after a `{}` escape", len, c), + }) } None } @@ -832,10 +819,7 @@ impl<'a> Parser<'a> { if tmp.0.contains_key(part) { match *tmp.0.get_mut(part).unwrap() { - Value::Table(ref mut table) => { - cur = table; - continue - } + Value::Table(ref mut table) => cur = table, Value::Array(ref mut array) => { match array.last_mut() { Some(&mut Value::Table(ref mut table)) => cur = table, @@ -849,7 +833,6 @@ impl<'a> Parser<'a> { return None } } - continue } _ => { self.errors.push(ParserError { @@ -861,6 +844,7 @@ impl<'a> Parser<'a> { return None } } + continue } // Initialize an empty table as part of this sub-key @@ -922,11 +906,10 @@ impl<'a> Parser<'a> { Some(pair) => pair, None => return, }; - let key = format!("{}", key); - if !into.0.contains_key(&key) { - into.0.insert(key.clone(), Value::Array(Vec::new())); + if !into.0.contains_key(key) { + into.0.insert(key.to_owned(), Value::Array(Vec::new())); } - match *into.0.get_mut(&key).unwrap() { + match *into.0.get_mut(key).unwrap() { Value::Array(ref mut vec) => { match vec.first() { Some(ref v) if !v.same_type(&value) => { -- cgit v1.2.3 From 68924534e271fe5ce534e9d274af081ce2579803 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 7 Jun 2015 23:13:14 -0700 Subject: Use deref coercions --- src/parser.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index d9c04cb..5224804 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -270,9 +270,10 @@ impl<'a> Parser<'a> { let mut table = TomlTable(BTreeMap::new(), false); if !self.values(&mut table) { return None } if array { - self.insert_array(&mut ret, &*keys, Value::Table(table), start) + self.insert_array(&mut ret, &keys, Value::Table(table), + start) } else { - self.insert_table(&mut ret, &*keys, table, start) + self.insert_table(&mut ret, &keys, table, start) } } else { if !self.values(&mut ret) { return None } -- cgit v1.2.3 From 88461157f267cbc4b4ee1352ed225667d4acc466 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 7 Jun 2015 23:16:56 -0700 Subject: Clean up more style --- src/parser.rs | 84 +++++++++++++++++++++++------------------------------------ 1 file changed, 33 insertions(+), 51 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index 5224804..b37621a 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -9,38 +9,31 @@ macro_rules! try { ($e:expr) => (match $e { Some(s) => s, None => return None }) } -/* - * We redefine Array, Table and Value, because we need to keep track of - * encountered table definitions, eg when parsing: - * [a] - * [a.b] - * [a] - * we have to error out on redefinition of [a]. - * This bit of data is impossible to represent in the user-consumed table - * without breaking compatibility, so we use one AST structure during parsing - * and expose another (after running convert(...) on it) to the user. - */ -type Array = Vec; - -#[derive(PartialEq, Clone, Debug)] -// If the bool flag is true, the table was explicitly defined -// e.g. in a toml document: `[a.b] foo = "bar"`, Table `a` would be false, -// where table `b` (contained inside `a`) would be true. +// We redefine Array, Table and Value, because we need to keep track of +// encountered table definitions, eg when parsing: +// +// [a] +// [a.b] +// [a] +// +// we have to error out on redefinition of [a]. This bit of data is difficult to +// track in a side table so we just have a "stripped down" AST to work with +// which has the relevant metadata fields in it. struct TomlTable(BTreeMap, bool); + impl TomlTable { fn convert(self) -> super::Table { self.0.into_iter().map(|(k,v)| (k,v.convert())).collect() } } -#[derive(PartialEq, Clone, Debug)] enum Value { String(String), Integer(i64), Float(f64), Boolean(bool), Datetime(String), - Array(Array), + Array(Vec), Table(TomlTable), } @@ -57,10 +50,6 @@ impl Value { } } - fn as_table<'a>(&'a self) -> Option<&'a TomlTable> { - match *self { Value::Table(ref s) => Some(s), _ => None } - } - fn same_type(&self, other: &Value) -> bool { match (self, other) { (&Value::String(..), &Value::String(..)) | @@ -267,7 +256,7 @@ impl<'a> Parser<'a> { if keys.len() == 0 { return None } // Build the section table - let mut table = TomlTable(BTreeMap::new(), false); + let mut table = TomlTable(BTreeMap::new(), true); if !self.values(&mut table) { return None } if array { self.insert_array(&mut ret, &keys, Value::Table(table), @@ -864,40 +853,33 @@ impl<'a> Parser<'a> { Some(pair) => pair, None => return, }; - let key = format!("{}", key); - let mut added = false; - if !into.0.contains_key(&key) { - into.0.insert(key.clone(), Value::Table(TomlTable(BTreeMap::new(), true))); - added = true; + if !into.0.contains_key(key) { + into.0.insert(key.to_owned(), Value::Table(value)); + return } - match into.0.get_mut(&key) { - Some(&mut Value::Table(ref mut table)) => { - let any_tables = table.0.values().any(|v| v.as_table().is_some()); - if !added && (!any_tables || table.1) { + if let Value::Table(ref mut table) = *into.0.get_mut(key).unwrap() { + if table.1 { + self.errors.push(ParserError { + lo: key_lo, + hi: key_lo + key.len(), + desc: format!("redefinition of table `{}`", key), + }); + } + for (k, v) in value.0 { + if table.0.insert(k.clone(), v).is_some() { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), - desc: format!("redefinition of table `{}`", key), + desc: format!("duplicate key `{}` in table", k), }); } - for (k, v) in value.0.into_iter() { - if table.0.insert(k.clone(), v).is_some() { - self.errors.push(ParserError { - lo: key_lo, - hi: key_lo + key.len(), - desc: format!("duplicate key `{}` in table", k), - }); - } - } - } - Some(_) => { - self.errors.push(ParserError { - lo: key_lo, - hi: key_lo + key.len(), - desc: format!("duplicate key `{}` in table", key), - }); } - None => {} + } else { + self.errors.push(ParserError { + lo: key_lo, + hi: key_lo + key.len(), + desc: format!("duplicate key `{}` in table", key), + }); } } -- cgit v1.2.3 From 00baf76107ed8c40c3b96dcc191277dfaab82ca1 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 7 Jun 2015 23:46:02 -0700 Subject: Add a few more tests for redefining tables --- src/parser.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index b37621a..68fa546 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1381,14 +1381,29 @@ trimmed in raw strings. #[test] fn bad_table_redefine() { - let mut p = Parser::new(" + bad!(" [a] foo=\"bar\" [a.b] foo=\"bar\" [a] - baz=\"bar\" - "); - assert!(p.parse().is_none()); + ", "redefinition of table `a`"); + bad!(" + [a] + foo=\"bar\" + b = { foo = \"bar\" } + [a] + ", "redefinition of table `a`"); + bad!(" + [a] + b = {} + [a.b] + ", "redefinition of table `b`"); + + bad!(" + [a] + b = {} + [a] + ", "redefinition of table `a`"); } } -- cgit v1.2.3 From 27a70d4024bcc769e6ff031a302fff9c7a2a2c70 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 8 Jun 2015 00:03:36 -0700 Subject: Name the fields of the custom table AST --- src/parser.rs | 55 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 23 deletions(-) (limited to 'src/parser.rs') diff --git a/src/parser.rs b/src/parser.rs index 68fa546..b7a810f 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -9,8 +9,8 @@ macro_rules! try { ($e:expr) => (match $e { Some(s) => s, None => return None }) } -// We redefine Array, Table and Value, because we need to keep track of -// encountered table definitions, eg when parsing: +// We redefine Value because we need to keep track of encountered table +// definitions, eg when parsing: // // [a] // [a.b] @@ -19,11 +19,14 @@ macro_rules! try { // we have to error out on redefinition of [a]. This bit of data is difficult to // track in a side table so we just have a "stripped down" AST to work with // which has the relevant metadata fields in it. -struct TomlTable(BTreeMap, bool); +struct TomlTable { + values: BTreeMap, + defined: bool, +} impl TomlTable { fn convert(self) -> super::Table { - self.0.into_iter().map(|(k,v)| (k,v.convert())).collect() + self.values.into_iter().map(|(k,v)| (k, v.convert())).collect() } } @@ -230,7 +233,7 @@ impl<'a> Parser<'a> { /// If an error occurs, the `errors` field of this parser can be consulted /// to determine the cause of the parse failure. pub fn parse(&mut self) -> Option { - let mut ret = TomlTable(BTreeMap::new(), false); + let mut ret = TomlTable { values: BTreeMap::new(), defined: false }; while self.peek(0).is_some() { self.ws(); if self.newline() { continue } @@ -256,7 +259,10 @@ impl<'a> Parser<'a> { if keys.len() == 0 { return None } // Build the section table - let mut table = TomlTable(BTreeMap::new(), true); + let mut table = TomlTable { + values: BTreeMap::new(), + defined: true, + }; if !self.values(&mut table) { return None } if array { self.insert_array(&mut ret, &keys, Value::Table(table), @@ -771,7 +777,7 @@ impl<'a> Parser<'a> { fn inline_table(&mut self, _start: usize) -> Option { if !self.expect('{') { return None } self.ws(); - let mut ret = TomlTable(BTreeMap::new(), true); + let mut ret = TomlTable { values: BTreeMap::new(), defined: true }; if self.eat('}') { return Some(Value::Table(ret)) } loop { let lo = self.next_pos(); @@ -790,14 +796,14 @@ impl<'a> Parser<'a> { fn insert(&mut self, into: &mut TomlTable, key: String, value: Value, key_lo: usize) { - if into.0.contains_key(&key) { + if into.values.contains_key(&key) { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), desc: format!("duplicate key: `{}`", key), }) } else { - into.0.insert(key, value); + into.values.insert(key, value); } } @@ -807,8 +813,8 @@ impl<'a> Parser<'a> { for part in keys[..keys.len() - 1].iter() { let tmp = cur; - if tmp.0.contains_key(part) { - match *tmp.0.get_mut(part).unwrap() { + if tmp.values.contains_key(part) { + match *tmp.values.get_mut(part).unwrap() { Value::Table(ref mut table) => cur = table, Value::Array(ref mut array) => { match array.last_mut() { @@ -838,8 +844,11 @@ impl<'a> Parser<'a> { } // Initialize an empty table as part of this sub-key - tmp.0.insert(part.clone(), Value::Table(TomlTable(BTreeMap::new(), false))); - match *tmp.0.get_mut(part).unwrap() { + tmp.values.insert(part.clone(), Value::Table(TomlTable { + values: BTreeMap::new(), + defined: false, + })); + match *tmp.values.get_mut(part).unwrap() { Value::Table(ref mut inner) => cur = inner, _ => unreachable!(), } @@ -848,25 +857,25 @@ impl<'a> Parser<'a> { } fn insert_table(&mut self, into: &mut TomlTable, keys: &[String], - value: TomlTable, key_lo: usize) { + table: TomlTable, key_lo: usize) { let (into, key) = match self.recurse(into, keys, key_lo) { Some(pair) => pair, None => return, }; - if !into.0.contains_key(key) { - into.0.insert(key.to_owned(), Value::Table(value)); + if !into.values.contains_key(key) { + into.values.insert(key.to_owned(), Value::Table(table)); return } - if let Value::Table(ref mut table) = *into.0.get_mut(key).unwrap() { - if table.1 { + if let Value::Table(ref mut into) = *into.values.get_mut(key).unwrap() { + if into.defined { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), desc: format!("redefinition of table `{}`", key), }); } - for (k, v) in value.0 { - if table.0.insert(k.clone(), v).is_some() { + for (k, v) in table.values { + if into.values.insert(k.clone(), v).is_some() { self.errors.push(ParserError { lo: key_lo, hi: key_lo + key.len(), @@ -889,10 +898,10 @@ impl<'a> Parser<'a> { Some(pair) => pair, None => return, }; - if !into.0.contains_key(key) { - into.0.insert(key.to_owned(), Value::Array(Vec::new())); + if !into.values.contains_key(key) { + into.values.insert(key.to_owned(), Value::Array(Vec::new())); } - match *into.0.get_mut(key).unwrap() { + match *into.values.get_mut(key).unwrap() { Value::Array(ref mut vec) => { match vec.first() { Some(ref v) if !v.same_type(&value) => { -- cgit v1.2.3