Skip to content

Commit

Permalink
refactor(parser): Encapsulate state
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Dec 22, 2022
1 parent eeb2794 commit dbc70a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
12 changes: 5 additions & 7 deletions crates/toml_edit/src/parser/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub(crate) fn document(s: &[u8]) -> Result<Document, TomlError> {
// Remove BOM if present
let s = s.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(s);

let mut parser = RefCell::new(ParseState::default());
let parser = RefCell::new(ParseState::default());
let input = Stream::new(s);

let parsed = parse_ws(&parser)
Expand Down Expand Up @@ -56,13 +56,11 @@ pub(crate) fn document(s: &[u8]) -> Result<Document, TomlError> {
s,
)),
Ok(..) => {
parser
.get_mut()
.finalize_table()
let doc = parser
.into_inner()
.into_document()
.map_err(|e| TomlError::custom(e.to_string()))?;
let trailing = parser.borrow().trailing.as_str().into();
parser.get_mut().document.trailing = trailing;
Ok(parser.into_inner().document)
Ok(doc)
}
Err(e) => Err(TomlError::new(e, s)),
}
Expand Down
19 changes: 13 additions & 6 deletions crates/toml_edit/src/parser/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,22 @@ use crate::table::TableKeyValue;
use crate::{ArrayOfTables, Document, InternalString, Item, Table};

pub(crate) struct ParseState {
pub(crate) document: Document,
pub(crate) trailing: String,
pub(crate) current_table_position: usize,
pub(crate) current_table: Table,
pub(crate) current_is_array: bool,
pub(crate) current_table_path: Vec<Key>,
document: Document,
trailing: String,
current_table_position: usize,
current_table: Table,
current_is_array: bool,
current_table_path: Vec<Key>,
}

impl ParseState {
pub(crate) fn into_document(mut self) -> Result<Document, CustomError> {
self.finalize_table()?;
let trailing = self.trailing.as_str().into();
self.document.trailing = trailing;
Ok(self.document)
}

pub(crate) fn on_ws(&mut self, w: &str) {
self.trailing.push_str(w);
}
Expand Down

0 comments on commit dbc70a8

Please sign in to comment.