Skip to main content

Rules

Struct Rules 

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

A language’s formatting rules, as data.

Built with chained calls, then compiled against the language’s kinds. An empty Rules formats nothing: every gap keeps its original whitespace (trailing spaces at line ends and blank space at the start and end of the file are still trimmed, and a final newline is added).

§Examples

use fmt_lang::{Indent, NodeRule, Rules, Space, TokenRule, Trailing};

let rules = Rules::new()
    .indent(2)
    .verbatim("ERROR")
    .token(TokenRule::new(":").before(Space::None).after(Space::Single))
    .node(
        NodeRule::new("array")
            .group()
            .indent(Indent::Block)
            .delimiters("[", "]", Space::SoftLine)
            .separator(",", Space::Line, Trailing::Never),
    );

Implementations§

Source§

impl Rules

Source

pub fn new() -> Self

No rules: indentation step 4, at most one blank line kept, indentation capped at 120 columns, a final newline.

§Examples
use fmt_lang::Rules;

let rules = Rules::new();
assert_eq!(rules, Rules::default());
Source

pub fn conventional() -> Self

Conventional token spacing shared by most C-family languages, every rule optional so the preset compiles against any language:

  • nothing before , ; ) ], one space after , and ;;
  • nothing after ( [;
  • one space around = == != <= >= += -= *= /= %= && || => ->.

Operators that are also prefix operators in common languages (-, +, *, &, !) and the angle brackets (<, >, generics in many languages) are left out on purpose: spacing them needs node context, which a NodeRule supplies.

§Examples
use fmt_lang::{NodeRule, Rules, Space};

let rules = Rules::conventional().node(NodeRule::new("stmt").before(Space::Hard));
Source

pub fn indent(self, columns: u8) -> Self

Columns per indentation level (default 4, at most MAX_INDENT_STEP).

§Examples
use fmt_lang::Rules;

let rules = Rules::new().indent(2);
Source

pub fn max_indent(self, columns: u16) -> Self

The deepest indentation, in columns, the formatter will produce (default 120). Nesting past it stops adding indentation. This is the output budget against hostile input: without it, a file nested a million levels deep would format to terabytes of spaces.

§Examples
use fmt_lang::Rules;

let rules = Rules::new().max_indent(60);
Source

pub fn max_blank_lines(self, max: u8) -> Self

The most blank lines kept wherever a Space::Hard gap had blank lines in the source (default 1). Gaps that keep their original whitespace are not capped.

§Examples
use fmt_lang::Rules;

let rules = Rules::new().max_blank_lines(2);
Source

pub fn final_newline(self, yes: bool) -> Self

Whether non-empty output ends with a line break (default true).

§Examples
use fmt_lang::Rules;

let rules = Rules::new().final_newline(false);
Source

pub fn verbatim(self, kind: impl Into<String>) -> Self

Names a node kind whose contents are always written exactly as in the source, such as a parser’s error node ("ERROR" in languages forged by lang-forge). Only the whitespace around such a node is formatted.

§Examples
use fmt_lang::Rules;

let rules = Rules::new().verbatim("ERROR").verbatim("raw_block");
Source

pub fn token(self, rule: TokenRule) -> Self

Adds a top-level token rule: a default for that token kind (or, with TokenRule::any, for every token) wherever it appears.

§Examples
use fmt_lang::{Rules, Space, TokenRule};

let rules = Rules::new().token(TokenRule::new("+").around(Space::Single));
Source

pub fn node(self, rule: NodeRule) -> Self

Adds a node rule.

§Examples
use fmt_lang::{NodeRule, Rules, Space};

let rules = Rules::new().node(NodeRule::new("stmt").before(Space::Hard));
Source§

impl Rules

Source

pub fn compile<K: Ord + Clone>( &self, resolve: impl FnMut(&str) -> Option<K>, ) -> Result<Style<K>, RuleError>

Resolves every kind name with resolve and compiles the rules into a Style for that language.

resolve maps a name to the language’s kind, or None if the language has no such kind. For a language forged by lang-forge it is |name| lang.kind(name).

Later top-level token rules for the same kind refine earlier ones (a side set later wins), so a preset such as Rules::conventional can be adjusted by adding rules after it. The same holds for token rules within one node rule.

§Errors
§Examples
use fmt_lang::{NodeRule, Rules, Space};

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Kind { Stmt, Semi }

let style = Rules::new()
    .node(NodeRule::new("stmt").before(Space::Hard))
    .compile(|name| match name {
        "stmt" => Some(Kind::Stmt),
        ";" => Some(Kind::Semi),
        _ => None,
    })?;

Trait Implementations§

Source§

impl Clone for Rules

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 Rules

Source§

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

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

impl Default for Rules

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for Rules

Source§

impl Hash for Rules

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Rules

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 Rules

Auto Trait Implementations§

§

impl Freeze for Rules

§

impl RefUnwindSafe for Rules

§

impl Send for Rules

§

impl Sync for Rules

§

impl Unpin for Rules

§

impl UnsafeUnpin for Rules

§

impl UnwindSafe for Rules

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, 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.