Skip to main content

Document

Struct Document 

Source
pub struct Document { /* private fields */ }
Expand description

A SOML document as a lossless syntax tree, to read with positions, change, and print.

An unchanged document prints the exact text it was parsed from. A changed one keeps the comments, blank lines, indentation, member order, and the author’s spelling of every value outside the change. New values are written in canonical style, and on one line in a container that is on one line.

let mut document: soml::Document = "
# The edge service.
name: 'api-gateway'
port: 0x1F90 # The default.
".parse()?;

document.set(["port"], 8080)?;
document.set(["replicas"], 3)?;
document.remove(["name"])?;

assert_eq!(document.to_string(), "
# The edge service.
port: 8080 # The default.
replicas: 3
");

See tree for the nodes and how whitespace and comments are kept.

Implementations§

Source§

impl Document

Source

pub const fn root(&self) -> &Node

The top-level object or array.

Source

pub const fn root_mut(&mut self) -> &mut Node

The top-level object or array, to change. Changes here can make a document that is not valid, such as one with two members with the same key; to_value finds that. set and remove keep the document valid.

Source

pub const fn outer_decor(&self) -> &Decor

The text before a top-level collection written with braces, as its leading decor, and the text after it, as its trailing decor. Both are empty for a top-level object without braces, where that text belongs to its first member and to the object itself.

Source

pub fn get<'a>( &self, path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>, ) -> Option<&Node>

The node at a path. None when nothing is there.

let document: soml::Document = "server: {port: 8080}\nhosts: ['a', 'b']".parse()?;

let port = document.get(["server", "port"]).and_then(soml::tree::Node::as_scalar);
assert_eq!(port.map(soml::tree::Scalar::value), Some(&soml::Value::Int(8080)));

let host = document.get([soml::PathSegment::from("hosts"), 1.into()]).and_then(soml::tree::Node::as_scalar);
assert_eq!(host.and_then(soml::tree::Scalar::raw), Some("'b'"));
Source

pub fn get_mut<'a>( &mut self, path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>, ) -> Option<&mut Node>

The node at a path, to change. See get.

Source

pub fn set<'a>( &mut self, path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>, value: impl Into<Value>, ) -> Result<(), Error>

Sets the value at a path, replacing what is there or adding it.

  • An existing value is replaced, and the comments around it stay. A value that replaces a block string on the line after its key goes on the key’s line, as the formatter writes it, unless a comment comes between them.
  • A new member goes after the last member of its object, and after the comments that member owns (see remove), so [1, 2 /* note */] with a new item 3 becomes [1, 2 /* note */, 3]. When something follows that member on its line, such as the closing bracket, the new one goes on that line, after a comma. Otherwise, it goes on a line of its own, with the indentation of that member and no comma, because a line break separates it.
  • A missing parent object is created with braces.
  • An index equal to an array’s length appends. The keys after it in the path are new objects in the new item, so setting ["b", 0, "c"] to 1 in b: [] adds the item {c: 1}.
  • A new value is written in canonical style, on lines of its own. In a container that stays on one line, it is written on one line, so [1, 2] with a new item {a: 3} becomes [1, 2, {a: 3}]. A container stays on one line when its brackets are on one line and something other than spaces and tabs is between them, as in [1, 2] and [/* note */], or when it is inside a container that stays on one line.
  • In a container with no entries, a new entry goes on a line of its own, so deps: {} gets its first member on a line of its own, because the formatter writes every empty container as {}. In a container that stays on one line, it goes before the closing bracket instead, so [/* note */] becomes [/* note */ 1], and a: [1, []] becomes a: [1, [2]].

A change always gives a valid document with the expected value, and it keeps every comment except those inside a value it replaces and those that a member or an item it removes owns. These are the spec’s editing rules, as in the JavaScript reference, so a change to a formatted document gives a formatted document, with the same text as there. A comment on a line of its own before a closing bracket belongs to no member or item, so a new entry goes before it, and it stays when the last entry is removed.

§Errors

Returns an error of kind ErrorKind::Data when the path is empty, when it goes through a scalar, when it uses a key on an array or an index on an object, when an index is past the end of its array, so that the item before the new one would be missing, or when an index is below a value that does not exist, because a missing value is made as an object. Returns an error of kind ErrorKind::Write when the value holds something SOML cannot represent, and when the result would not be a valid document, such as one nested more than 100 levels deep. Such an error has no position, because the place it is about is not in the document. The document is unchanged after an error.

Each change reads the result back to check it, so it takes time in proportion to the size of the document.

Source

pub fn remove<'a>( &mut self, path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>, ) -> Result<bool, Error>

Removes the member or item at a path, with the comments it owns and its comma. A member or an item owns the comments that the formatter keeps with it: the comments after it on its line, before its comma, or after its comma when nothing else follows on that line, and the block comments before it on its line, back to the comma or bracket before it. So in [1 /* a */, /* b */ 2 /* c */], 1 owns /* a */, and 2 owns /* b */ and /* c */. A comment on a line of its own belongs to no member or item, so the comment lines above and below a removed one stay.

The other entries keep their commas, except that when the removed entries are the last ones and the last of them has no comma after it, the comma directly before them goes too, when only spaces, tabs, and the comments the first of them owns are between, so [1, 2] and [1, /* note */ 2] become [1], and [\n\t1,\n\t2\n] becomes [\n\t1,\n]. A blank line the removal leaves next to another blank line, or directly inside a bracket or at the start or end of the document, goes too, the one before it when there is a choice, so a formatted document stays formatted. This takes at most one blank line, so other blank lines stay as written.

Removing every entry of a container closes it up to [] or {}, unless a comment is left inside. Removing the only member of a top-level object without braces leaves {} in its place, because a document cannot be empty, and members set later go inside the braces. The {} keeps the comments that the member owned, so a: 1 # note without a becomes {} # note.

These are the spec’s editing rules, as in the JavaScript reference. See set for which layouts are kept exactly.

Removing a value that does not exist changes nothing and is not an error: a missing member, a missing object or array on the way, or an index at or past the end of its array, and anything below them. So removing the same path twice is safe. Returns whether something was removed, so a caller who expected a value can notice that it was missing.

§Errors

Returns an error of kind ErrorKind::Data when the path is empty, when it goes through a scalar, or when it uses a key on an array or an index on an object, before it reaches a value that does not exist. The document is unchanged after an error.

Source

pub fn comments(&self) -> Vec<Comment>

The comments, in order, with their positions in the document’s current text, which is the parsed text when nothing changed.

After a change, these spans do not fit position, which uses the parsed text. Print the document and parse it again to get both for the new text.

Source

pub fn position(&self, offset: usize) -> LineColumn

The line and column of a byte offset in the text the document was parsed from, as for a node’s span.

let document: soml::Document = "name: 'a'\nport: 80".parse()?;
let span = document.get(["port"]).and_then(soml::tree::Node::span).unwrap();

assert_eq!(document.position(span.start), soml::LineColumn { line: 2, column: 7 });
Source

pub fn format(&self) -> String

The document in the layout of the spec’s formatter, which changes layout and nothing else.

It keeps the comments where they are, the member order, the spelling of every key and value, block strings, and a top level with or without braces. It writes one tab of indentation per level, every member and item on its own line, no commas, at most one blank line in a row, no trailing spaces or tabs, and one line feed at the end. An object or an array whose brackets are on one line stays on one line, with a comma and a space between its members or items. To give it one member or item per line, put a line break anywhere inside it. Formatting a formatted document gives the same text.

let document: soml::Document = "# Server\nserver: {host: 'a',   port: 0x50,} # Main.\n\n\nlist: [1,\n2]".parse()?;

assert_eq!(document.format(), "# Server\nserver: {host: 'a', port: 0x50} # Main.\n\nlist: [\n\t1\n\t2\n]\n");

The spec’s formatter rules are normative, so every conforming formatter gives the same text. The tree module lists them in detail.

Source

pub fn to_value(&self) -> Result<Value, Error>

The value of the document, with every check of the spec, such as for duplicate keys, which a change through root_mut can make.

It prints the document and reads it back, so an error’s position refers to the printed text, which is the parsed text when nothing changed.

§Errors

Returns an error when the document, as changed, is not valid.

Trait Implementations§

Source§

impl Clone for Document

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Document

Prints the document: the exact text it was parsed from, with any changes.

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for Document

Source§

fn from_str(text: &str) -> Result<Self, Error>

Parses a document, with the same checks and errors as from_str.

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

impl PartialEq for Document

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Document

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.