Skip to content

Commit

Permalink
refactor(edit): Pull error out of parser
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Nov 6, 2023
1 parent 3cba874 commit 52b5c6f
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result};

use crate::parser::prelude::*;
use crate::Key;

use winnow::error::ContextError;
use winnow::error::ParseError;
Expand Down Expand Up @@ -243,73 +242,3 @@ mod test_translate_position {
assert_eq!(position, (1, 2));
}
}

#[derive(Debug, Clone)]
pub(crate) enum CustomError {
DuplicateKey {
key: String,
table: Option<Vec<Key>>,
},
DottedKeyExtendWrongType {
key: Vec<Key>,
actual: &'static str,
},
OutOfRange,
#[cfg_attr(feature = "unbounded", allow(dead_code))]
RecursionLimitExceeded,
}

impl CustomError {
pub(crate) fn duplicate_key(path: &[Key], i: usize) -> Self {
assert!(i < path.len());
let key = &path[i];
let repr = key.display_repr();
Self::DuplicateKey {
key: repr.into(),
table: Some(path[..i].to_vec()),
}
}

pub(crate) fn extend_wrong_type(path: &[Key], i: usize, actual: &'static str) -> Self {
assert!(i < path.len());
Self::DottedKeyExtendWrongType {
key: path[..=i].to_vec(),
actual,
}
}
}

impl StdError for CustomError {
fn description(&self) -> &'static str {
"TOML parse error"
}
}

impl Display for CustomError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
CustomError::DuplicateKey { key, table } => {
if let Some(table) = table {
if table.is_empty() {
write!(f, "duplicate key `{}` in document root", key)
} else {
let path = table.iter().map(|k| k.get()).collect::<Vec<_>>().join(".");
write!(f, "duplicate key `{}` in table `{}`", key, path)
}
} else {
write!(f, "duplicate key `{}`", key)
}
}
CustomError::DottedKeyExtendWrongType { key, actual } => {
let path = key.iter().map(|k| k.get()).collect::<Vec<_>>().join(".");
write!(
f,
"dotted key `{}` attempted to extend non-table type ({})",
path, actual
)
}
CustomError::OutOfRange => write!(f, "value is out of range"),
CustomError::RecursionLimitExceeded => write!(f, "recursion limit exceeded"),
}
}
}
3 changes: 2 additions & 1 deletion crates/toml_edit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ mod array;
mod array_of_tables;
mod document;
mod encode;
mod error;
mod index;
mod inline_table;
mod internal_string;
Expand All @@ -90,14 +91,14 @@ pub use crate::array_of_tables::{
ArrayOfTables, ArrayOfTablesIntoIter, ArrayOfTablesIter, ArrayOfTablesIterMut,
};
pub use crate::document::Document;
pub use crate::error::TomlError;
pub use crate::inline_table::{
InlineEntry, InlineOccupiedEntry, InlineTable, InlineTableIntoIter, InlineTableIter,
InlineTableIterMut, InlineVacantEntry,
};
pub use crate::internal_string::InternalString;
pub use crate::item::{array, table, value, Item};
pub use crate::key::{Key, KeyMut};
pub use crate::parser::TomlError;
pub use crate::raw_string::RawString;
pub use crate::repr::{Decor, Formatted, Repr};
pub use crate::table::{
Expand Down
2 changes: 1 addition & 1 deletion crates/toml_edit/src/parser/datetime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::ops::RangeInclusive;

use crate::parser::errors::CustomError;
use crate::parser::error::CustomError;
use crate::parser::prelude::*;
use crate::parser::trivia::from_utf8_unchecked;

Expand Down
74 changes: 74 additions & 0 deletions crates/toml_edit/src/parser/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result};

use crate::Key;

#[derive(Debug, Clone)]
pub(crate) enum CustomError {
DuplicateKey {
key: String,
table: Option<Vec<Key>>,
},
DottedKeyExtendWrongType {
key: Vec<Key>,
actual: &'static str,
},
OutOfRange,
#[cfg_attr(feature = "unbounded", allow(dead_code))]
RecursionLimitExceeded,
}

impl CustomError {
pub(crate) fn duplicate_key(path: &[Key], i: usize) -> Self {
assert!(i < path.len());
let key = &path[i];
let repr = key.display_repr();
Self::DuplicateKey {
key: repr.into(),
table: Some(path[..i].to_vec()),
}
}

pub(crate) fn extend_wrong_type(path: &[Key], i: usize, actual: &'static str) -> Self {
assert!(i < path.len());
Self::DottedKeyExtendWrongType {
key: path[..=i].to_vec(),
actual,
}
}
}

impl StdError for CustomError {
fn description(&self) -> &'static str {
"TOML parse error"
}
}

impl Display for CustomError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
CustomError::DuplicateKey { key, table } => {
if let Some(table) = table {
if table.is_empty() {
write!(f, "duplicate key `{}` in document root", key)
} else {
let path = table.iter().map(|k| k.get()).collect::<Vec<_>>().join(".");
write!(f, "duplicate key `{}` in table `{}`", key, path)
}
} else {
write!(f, "duplicate key `{}`", key)
}
}
CustomError::DottedKeyExtendWrongType { key, actual } => {
let path = key.iter().map(|k| k.get()).collect::<Vec<_>>().join(".");
write!(
f,
"dotted key `{}` attempted to extend non-table type ({})",
path, actual
)
}
CustomError::OutOfRange => write!(f, "value is out of range"),
CustomError::RecursionLimitExceeded => write!(f, "recursion limit exceeded"),
}
}
}
2 changes: 1 addition & 1 deletion crates/toml_edit/src/parser/inline_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use winnow::token::one_of;
use winnow::trace::trace;

use crate::key::Key;
use crate::parser::errors::CustomError;
use crate::parser::error::CustomError;
use crate::parser::key::key;
use crate::parser::prelude::*;
use crate::parser::trivia::ws;
Expand Down
2 changes: 1 addition & 1 deletion crates/toml_edit/src/parser/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use winnow::token::take_while;
use winnow::trace::trace;

use crate::key::Key;
use crate::parser::errors::CustomError;
use crate::parser::error::CustomError;
use crate::parser::prelude::*;
use crate::parser::strings::{basic_string, literal_string};
use crate::parser::trivia::{from_utf8_unchecked, ws};
Expand Down
12 changes: 6 additions & 6 deletions crates/toml_edit/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
pub(crate) mod array;
pub(crate) mod datetime;
pub(crate) mod document;
pub(crate) mod errors;
pub(crate) mod error;
pub(crate) mod inline_table;
pub(crate) mod key;
pub(crate) mod numbers;
Expand All @@ -13,7 +13,7 @@ pub(crate) mod table;
pub(crate) mod trivia;
pub(crate) mod value;

pub use errors::TomlError;
pub use crate::error::TomlError;

pub(crate) fn parse_document(raw: &str) -> Result<crate::Document, TomlError> {
use prelude::*;
Expand Down Expand Up @@ -95,11 +95,11 @@ pub(crate) mod prelude {

#[cfg(not(feature = "unbounded"))]
impl RecursionCheck {
pub(crate) fn check_depth(depth: usize) -> Result<(), super::errors::CustomError> {
pub(crate) fn check_depth(depth: usize) -> Result<(), super::error::CustomError> {
if depth < 128 {
Ok(())
} else {
Err(super::errors::CustomError::RecursionLimitExceeded)
Err(super::error::CustomError::RecursionLimitExceeded)
}
}

Expand All @@ -114,7 +114,7 @@ pub(crate) mod prelude {
Err(winnow::error::ErrMode::from_external_error(
input,
winnow::error::ErrorKind::Eof,
super::errors::CustomError::RecursionLimitExceeded,
super::error::CustomError::RecursionLimitExceeded,
))
}
}
Expand All @@ -126,7 +126,7 @@ pub(crate) mod prelude {

#[cfg(feature = "unbounded")]
impl RecursionCheck {
pub(crate) fn check_depth(_depth: usize) -> Result<(), super::errors::CustomError> {
pub(crate) fn check_depth(_depth: usize) -> Result<(), super::error::CustomError> {
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/toml_edit/src/parser/state.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::key::Key;
use crate::parser::errors::CustomError;
use crate::parser::error::CustomError;
use crate::repr::Decor;
use crate::table::TableKeyValue;
use crate::{ArrayOfTables, Document, InternalString, Item, RawString, Table};
Expand Down
2 changes: 1 addition & 1 deletion crates/toml_edit/src/parser/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use winnow::token::tag;
use winnow::token::take_while;
use winnow::trace::trace;

use crate::parser::errors::CustomError;
use crate::parser::error::CustomError;
use crate::parser::numbers::HEXDIG;
use crate::parser::prelude::*;
use crate::parser::trivia::{from_utf8_unchecked, newline, ws, ws_newlines, NON_ASCII, WSCHAR};
Expand Down

0 comments on commit 52b5c6f

Please sign in to comment.