Skip to content

Commit

Permalink
feat: Supprt parsing dotted keys
Browse files Browse the repository at this point in the history
We support parsing a lot of expressions to help users to edit their toml
document from real world code.  One thing that was missing was dotted
key parsing.

Also, this will hopefully help with rust-lang/cargo#10176
  • Loading branch information
epage committed Dec 14, 2021
1 parent eda875c commit 36c1256
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
31 changes: 28 additions & 3 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ impl Key {
}
}

/// Parse a TOML key expression
///
/// Unlike `"".parse<Key>()`, this supports dotted keys.
pub fn parse(repr: &str) -> Result<Vec<Self>, parser::TomlError> {
Self::try_parse_path(repr)
}

pub(crate) fn with_repr_unchecked(mut self, repr: Repr) -> Self {
self.repr = Some(repr);
self
Expand Down Expand Up @@ -97,12 +104,12 @@ impl Key {
self.decor.clear();
}

fn try_parse(s: &str) -> Result<Key, parser::TomlError> {
fn try_parse_simple(s: &str) -> Result<Key, parser::TomlError> {
use combine::stream::position::{IndexPositioner, Positioner};
use combine::EasyParser;

let b = s.as_bytes();
let result = parser::key_parser().easy_parse(Stream::new(b));
let result = parser::simple_key().easy_parse(Stream::new(b));
match result {
Ok((_, ref rest)) if !rest.input.is_empty() => Err(parser::TomlError::from_unparsed(
(&rest.positioner
Expand All @@ -114,6 +121,24 @@ impl Key {
Err(e) => Err(parser::TomlError::new(e, b)),
}
}

fn try_parse_path(s: &str) -> Result<Vec<Key>, parser::TomlError> {
use combine::stream::position::{IndexPositioner, Positioner};
use combine::EasyParser;

let b = s.as_bytes();
let result = parser::key_path().easy_parse(Stream::new(b));
match result {
Ok((_, ref rest)) if !rest.input.is_empty() => Err(parser::TomlError::from_unparsed(
(&rest.positioner
as &dyn Positioner<usize, Position = usize, Checkpoint = IndexPositioner>)
.position(),
b,
)),
Ok((keys, _)) => Ok(keys),
Err(e) => Err(parser::TomlError::new(e, b)),
}
}
}

impl std::ops::Deref for Key {
Expand Down Expand Up @@ -158,7 +183,7 @@ impl FromStr for Key {
/// if fails, tries as basic quoted key (surrounds with "")
/// and then literal quoted key (surrounds with '')
fn from_str(s: &str) -> Result<Self, Self::Err> {
Key::try_parse(s)
Key::try_parse_simple(s)
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ mod value;

pub use self::errors::TomlError;
pub(crate) use self::key::is_unquoted_char;
pub(crate) use self::key::simple_key as key_parser;
pub(crate) use self::key::key as key_path;
pub(crate) use self::key::simple_key;
pub(crate) use self::value::value as value_parser;

use self::table::duplicate_key;
Expand Down

0 comments on commit 36c1256

Please sign in to comment.