devise::syn::parse

Struct ParseBuffer

Source
pub struct ParseBuffer<'a> { /* private fields */ }
Expand description

Cursor position within a buffered token stream.

This type is more commonly used through the type alias ParseStream which is an alias for &ParseBuffer.

ParseStream is the input type for all parser functions in Syn. They have the signature fn(ParseStream) -> Result<T>.

§Calling a parser function

There is no public way to construct a ParseBuffer. Instead, if you are looking to invoke a parser function that requires ParseStream as input, you will need to go through one of the public parsing entry points.

Implementations§

Source§

impl<'a> ParseBuffer<'a>

Source

pub fn parse<T>(&self) -> Result<T, Error>
where T: Parse,

Parses a syntax tree node of type T, advancing the position of our parse stream past it.

Source

pub fn call<T>( &'a self, function: fn(_: &'a ParseBuffer<'a>) -> Result<T, Error>, ) -> Result<T, Error>

Calls the given parser function to parse a syntax tree node of type T from this stream.

§Example

The parser below invokes Attribute::parse_outer to parse a vector of zero or more outer attributes.

use syn::{Attribute, Ident, Result, Token};
use syn::parse::{Parse, ParseStream};

// Parses a unit struct with attributes.
//
//     #[path = "s.tmpl"]
//     struct S;
struct UnitStruct {
    attrs: Vec<Attribute>,
    struct_token: Token![struct],
    name: Ident,
    semi_token: Token![;],
}

impl Parse for UnitStruct {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(UnitStruct {
            attrs: input.call(Attribute::parse_outer)?,
            struct_token: input.parse()?,
            name: input.parse()?,
            semi_token: input.parse()?,
        })
    }
}
Source

pub fn peek<T>(&self, token: T) -> bool
where T: Peek,

Looks at the next token in the parse stream to determine whether it matches the requested type of token.

Does not advance the position of the parse stream.

§Syntax

Note that this method does not use turbofish syntax. Pass the peek type inside of parentheses.

  • input.peek(Token![struct])
  • input.peek(Token![==])
  • input.peek(syn::Ident)(does not accept keywords)
  • input.peek(syn::Ident::peek_any)
  • input.peek(Lifetime)
  • input.peek(token::Brace)
§Example

In this example we finish parsing the list of supertraits when the next token in the input is either where or an opening curly brace.

use syn::{braced, token, Generics, Ident, Result, Token, TypeParamBound};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;

// Parses a trait definition containing no associated items.
//
//     trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {}
struct MarkerTrait {
    trait_token: Token![trait],
    ident: Ident,
    generics: Generics,
    colon_token: Option<Token![:]>,
    supertraits: Punctuated<TypeParamBound, Token![+]>,
    brace_token: token::Brace,
}

impl Parse for MarkerTrait {
    fn parse(input: ParseStream) -> Result<Self> {
        let trait_token: Token![trait] = input.parse()?;
        let ident: Ident = input.parse()?;
        let mut generics: Generics = input.parse()?;
        let colon_token: Option<Token![:]> = input.parse()?;

        let mut supertraits = Punctuated::new();
        if colon_token.is_some() {
            loop {
                supertraits.push_value(input.parse()?);
                if input.peek(Token![where]) || input.peek(token::Brace) {
                    break;
                }
                supertraits.push_punct(input.parse()?);
            }
        }

        generics.where_clause = input.parse()?;
        let content;
        let empty_brace_token = braced!(content in input);

        Ok(MarkerTrait {
            trait_token,
            ident,
            generics,
            colon_token,
            supertraits,
            brace_token: empty_brace_token,
        })
    }
}
Source

pub fn peek2<T>(&self, token: T) -> bool
where T: Peek,

Looks at the second-next token in the parse stream.

This is commonly useful as a way to implement contextual keywords.

§Example

This example needs to use peek2 because the symbol union is not a keyword in Rust. We can’t use just peek and decide to parse a union if the very next token is union, because someone is free to write a mod union and a macro invocation that looks like union::some_macro! { ... }. In other words union is a contextual keyword.

use syn::{Ident, ItemUnion, Macro, Result, Token};
use syn::parse::{Parse, ParseStream};

// Parses either a union or a macro invocation.
enum UnionOrMacro {
    // union MaybeUninit<T> { uninit: (), value: T }
    Union(ItemUnion),
    // lazy_static! { ... }
    Macro(Macro),
}

impl Parse for UnionOrMacro {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(Token![union]) && input.peek2(Ident) {
            input.parse().map(UnionOrMacro::Union)
        } else {
            input.parse().map(UnionOrMacro::Macro)
        }
    }
}
Source

pub fn peek3<T>(&self, token: T) -> bool
where T: Peek,

Looks at the third-next token in the parse stream.

Source

pub fn parse_terminated<T, P>( &'a self, parser: fn(_: &'a ParseBuffer<'a>) -> Result<T, Error>, separator: P, ) -> Result<Punctuated<T, <P as Peek>::Token>, Error>
where P: Peek, <P as Peek>::Token: Parse,

Parses zero or more occurrences of T separated by punctuation of type P, with optional trailing punctuation.

Parsing continues until the end of this parse stream. The entire content of this parse stream must consist of T and P.

§Example
use syn::{parenthesized, token, Ident, Result, Token, Type};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;

// Parse a simplified tuple struct syntax like:
//
//     struct S(A, B);
struct TupleStruct {
    struct_token: Token![struct],
    ident: Ident,
    paren_token: token::Paren,
    fields: Punctuated<Type, Token![,]>,
    semi_token: Token![;],
}

impl Parse for TupleStruct {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(TupleStruct {
            struct_token: input.parse()?,
            ident: input.parse()?,
            paren_token: parenthesized!(content in input),
            fields: content.parse_terminated(Type::parse, Token![,])?,
            semi_token: input.parse()?,
        })
    }
}
§See also

If your separator is anything more complicated than an invocation of the Token! macro, this method won’t be applicable and you can instead directly use Punctuated’s parser functions: parse_terminated, parse_separated_nonempty etc.

use syn::{custom_keyword, Expr, Result, Token};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;

mod kw {
    syn::custom_keyword!(fin);
}

struct Fin(kw::fin, Token![;]);

impl Parse for Fin {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Self(input.parse()?, input.parse()?))
    }
}

struct Thing {
    steps: Punctuated<Expr, Fin>,
}

impl Parse for Thing {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Thing {
            steps: Punctuated::parse_terminated(input)?,
        })
        // or equivalently, this means the same thing:
            steps: input.call(Punctuated::parse_terminated)?,
    }
}
Source

pub fn is_empty(&self) -> bool

Returns whether there are no more tokens remaining to be parsed from this stream.

This method returns true upon reaching the end of the content within a set of delimiters, as well as at the end of the tokens provided to the outermost parsing entry point.

This is equivalent to .peek(syn::parse::End). Use .peek2(End) or .peek3(End) to look for the end of a parse stream further ahead than the current position.

§Example
use syn::{braced, token, Ident, Item, Result, Token};
use syn::parse::{Parse, ParseStream};

// Parses a Rust `mod m { ... }` containing zero or more items.
struct Mod {
    mod_token: Token![mod],
    name: Ident,
    brace_token: token::Brace,
    items: Vec<Item>,
}

impl Parse for Mod {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(Mod {
            mod_token: input.parse()?,
            name: input.parse()?,
            brace_token: braced!(content in input),
            items: {
                let mut items = Vec::new();
                while !content.is_empty() {
                    items.push(content.parse()?);
                }
                items
            },
        })
    }
}
Source

pub fn lookahead1(&self) -> Lookahead1<'a>

Constructs a helper for peeking at the next token in this stream and building an error message if it is not one of a set of expected tokens.

§Example
use syn::{ConstParam, Ident, Lifetime, LifetimeParam, Result, Token, TypeParam};
use syn::parse::{Parse, ParseStream};

// A generic parameter, a single one of the comma-separated elements inside
// angle brackets in:
//
//     fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
//
// On invalid input, lookahead gives us a reasonable error message.
//
//     error: expected one of: identifier, lifetime, `const`
//       |
//     5 |     fn f<!Sized>() {}
//       |          ^
enum GenericParam {
    Type(TypeParam),
    Lifetime(LifetimeParam),
    Const(ConstParam),
}

impl Parse for GenericParam {
    fn parse(input: ParseStream) -> Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(Ident) {
            input.parse().map(GenericParam::Type)
        } else if lookahead.peek(Lifetime) {
            input.parse().map(GenericParam::Lifetime)
        } else if lookahead.peek(Token![const]) {
            input.parse().map(GenericParam::Const)
        } else {
            Err(lookahead.error())
        }
    }
}
Source

pub fn fork(&self) -> ParseBuffer<'a>

Forks a parse stream so that parsing tokens out of either the original or the fork does not advance the position of the other.

§Performance

Forking a parse stream is a cheap fixed amount of work and does not involve copying token buffers. Where you might hit performance problems is if your macro ends up parsing a large amount of content more than once.

// Do not do this.
if input.fork().parse::<Expr>().is_ok() {
    return input.parse::<Expr>();
}

As a rule, avoid parsing an unbounded amount of tokens out of a forked parse stream. Only use a fork when the amount of work performed against the fork is small and bounded.

When complex speculative parsing against the forked stream is unavoidable, use parse::discouraged::Speculative to advance the original stream once the fork’s parse is determined to have been successful.

For a lower level way to perform speculative parsing at the token level, consider using ParseStream::step instead.

§Example

The parse implementation shown here parses possibly restricted pub visibilities.

  • pub
  • pub(crate)
  • pub(self)
  • pub(super)
  • pub(in some::path)

To handle the case of visibilities inside of tuple structs, the parser needs to distinguish parentheses that specify visibility restrictions from parentheses that form part of a tuple type.

struct S(pub(crate) A, pub (B, C));

In this example input the first tuple struct element of S has pub(crate) visibility while the second tuple struct element has pub visibility; the parentheses around (B, C) are part of the type rather than part of a visibility restriction.

The parser uses a forked parse stream to check the first token inside of parentheses after the pub keyword. This is a small bounded amount of work performed against the forked parse stream.

use syn::{parenthesized, token, Ident, Path, Result, Token};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};

struct PubVisibility {
    pub_token: Token![pub],
    restricted: Option<Restricted>,
}

struct Restricted {
    paren_token: token::Paren,
    in_token: Option<Token![in]>,
    path: Path,
}

impl Parse for PubVisibility {
    fn parse(input: ParseStream) -> Result<Self> {
        let pub_token: Token![pub] = input.parse()?;

        if input.peek(token::Paren) {
            let ahead = input.fork();
            let mut content;
            parenthesized!(content in ahead);

            if content.peek(Token![crate])
                || content.peek(Token![self])
                || content.peek(Token![super])
            {
                return Ok(PubVisibility {
                    pub_token,
                    restricted: Some(Restricted {
                        paren_token: parenthesized!(content in input),
                        in_token: None,
                        path: Path::from(content.call(Ident::parse_any)?),
                    }),
                });
            } else if content.peek(Token![in]) {
                return Ok(PubVisibility {
                    pub_token,
                    restricted: Some(Restricted {
                        paren_token: parenthesized!(content in input),
                        in_token: Some(content.parse()?),
                        path: content.call(Path::parse_mod_style)?,
                    }),
                });
            }
        }

        Ok(PubVisibility {
            pub_token,
            restricted: None,
        })
    }
}
Source

pub fn error<T>(&self, message: T) -> Error
where T: Display,

Triggers an error at the current position of the parse stream.

§Example
use syn::{Expr, Result, Token};
use syn::parse::{Parse, ParseStream};

// Some kind of loop: `while` or `for` or `loop`.
struct Loop {
    expr: Expr,
}

impl Parse for Loop {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(Token![while])
            || input.peek(Token![for])
            || input.peek(Token![loop])
        {
            Ok(Loop {
                expr: input.parse()?,
            })
        } else {
            Err(input.error("expected some kind of loop"))
        }
    }
}
Source

pub fn step<F, R>(&self, function: F) -> Result<R, Error>
where F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>), Error>,

Speculatively parses tokens from this parse stream, advancing the position of this stream only if parsing succeeds.

This is a powerful low-level API used for defining the Parse impls of the basic built-in token types. It is not something that will be used widely outside of the Syn codebase.

§Example
use proc_macro2::TokenTree;
use syn::Result;
use syn::parse::ParseStream;

// This function advances the stream past the next occurrence of `@`. If
// no `@` is present in the stream, the stream position is unchanged and
// an error is returned.
fn skip_past_next_at(input: ParseStream) -> Result<()> {
    input.step(|cursor| {
        let mut rest = *cursor;
        while let Some((tt, next)) = rest.token_tree() {
            match &tt {
                TokenTree::Punct(punct) if punct.as_char() == '@' => {
                    return Ok(((), next));
                }
                _ => rest = next,
            }
        }
        Err(cursor.error("no `@` was found after this point"))
    })
}
Source

pub fn span(&self) -> Span

Returns the Span of the next token in the parse stream, or Span::call_site() if this parse stream has completely exhausted its input TokenStream.

Source

pub fn cursor(&self) -> Cursor<'a>

Provides low-level access to the token representation underlying this parse stream.

Cursors are immutable so no operations you perform against the cursor will affect the state of this parse stream.

§Example
use proc_macro2::TokenStream;
use syn::buffer::Cursor;
use syn::parse::{ParseStream, Result};

// Run a parser that returns T, but get its output as TokenStream instead of T.
// This works without T needing to implement ToTokens.
fn recognize_token_stream<T>(
    recognizer: fn(ParseStream) -> Result<T>,
) -> impl Fn(ParseStream) -> Result<TokenStream> {
    move |input| {
        let begin = input.cursor();
        recognizer(input)?;
        let end = input.cursor();
        Ok(tokens_between(begin, end))
    }
}

// Collect tokens between two cursors as a TokenStream.
fn tokens_between(begin: Cursor, end: Cursor) -> TokenStream {
    assert!(begin <= end);

    let mut cursor = begin;
    let mut tokens = TokenStream::new();
    while cursor < end {
        let (token, next) = cursor.token_tree().unwrap();
        tokens.extend(std::iter::once(token));
        cursor = next;
    }
    tokens
}

fn main() {
    use quote::quote;
    use syn::parse::{Parse, Parser};
    use syn::Token;

    // Parse syn::Type as a TokenStream, surrounded by angle brackets.
    fn example(input: ParseStream) -> Result<TokenStream> {
        let _langle: Token![<] = input.parse()?;
        let ty = recognize_token_stream(syn::Type::parse)(input)?;
        let _rangle: Token![>] = input.parse()?;
        Ok(ty)
    }

    let tokens = quote! { <fn() -> u8> };
    println!("{}", example.parse2(tokens).unwrap());
}

Trait Implementations§

Source§

impl<'a> AnyDelimiter for ParseBuffer<'a>

Source§

fn parse_any_delimiter( &self, ) -> Result<(Delimiter, DelimSpan, ParseBuffer<'_>), Error>

Returns the delimiter, the span of the delimiter token, and the nested contents for further parsing.
Source§

impl<'a> Debug for ParseBuffer<'a>

Source§

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

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

impl<'a> Display for ParseBuffer<'a>

Source§

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

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

impl<'a> Drop for ParseBuffer<'a>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'a> Speculative for ParseBuffer<'a>

Source§

fn advance_to(&self, fork: &ParseBuffer<'a>)

Advance this parse stream to the position of a forked parse stream. Read more
Source§

impl<'a> RefUnwindSafe for ParseBuffer<'a>

Source§

impl<'a> UnwindSafe for ParseBuffer<'a>

Auto Trait Implementations§

§

impl<'a> !Freeze for ParseBuffer<'a>

§

impl<'a> !Send for ParseBuffer<'a>

§

impl<'a> !Sync for ParseBuffer<'a>

§

impl<'a> Unpin for ParseBuffer<'a>

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> 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> Paint for T
where T: ?Sized,

Source§

fn fg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the foreground set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like red() and green(), which have the same functionality but are pithier.

§Example

Set foreground color to white using fg():

use yansi::{Paint, Color};

painted.fg(Color::White);

Set foreground color to white using white().

use yansi::Paint;

painted.white();
Source§

fn primary(&self) -> Painted<&T>

Returns self with the fg() set to Color::Primary.

§Example
println!("{}", value.primary());
Source§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to Color::Fixed.

§Example
println!("{}", value.fixed(color));
Source§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to Color::Rgb.

§Example
println!("{}", value.rgb(r, g, b));
Source§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to Color::Black.

§Example
println!("{}", value.black());
Source§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to Color::Red.

§Example
println!("{}", value.red());
Source§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to Color::Green.

§Example
println!("{}", value.green());
Source§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::Yellow.

§Example
println!("{}", value.yellow());
Source§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::Blue.

§Example
println!("{}", value.blue());
Source§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::Magenta.

§Example
println!("{}", value.magenta());
Source§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::Cyan.

§Example
println!("{}", value.cyan());
Source§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to Color::White.

§Example
println!("{}", value.white());
Source§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlack.

§Example
println!("{}", value.bright_black());
Source§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightRed.

§Example
println!("{}", value.bright_red());
Source§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightGreen.

§Example
println!("{}", value.bright_green());
Source§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightYellow.

§Example
println!("{}", value.bright_yellow());
Source§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlue.

§Example
println!("{}", value.bright_blue());
Source§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightMagenta.

§Example
println!("{}", value.bright_magenta());
Source§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightCyan.

§Example
println!("{}", value.bright_cyan());
Source§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightWhite.

§Example
println!("{}", value.bright_white());
Source§

fn bg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the background set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like on_red() and on_green(), which have the same functionality but are pithier.

§Example

Set background color to red using fg():

use yansi::{Paint, Color};

painted.bg(Color::Red);

Set background color to red using on_red().

use yansi::Paint;

painted.on_red();
Source§

fn on_primary(&self) -> Painted<&T>

Returns self with the bg() set to Color::Primary.

§Example
println!("{}", value.on_primary());
Source§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to Color::Fixed.

§Example
println!("{}", value.on_fixed(color));
Source§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to Color::Rgb.

§Example
println!("{}", value.on_rgb(r, g, b));
Source§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::Black.

§Example
println!("{}", value.on_black());
Source§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::Red.

§Example
println!("{}", value.on_red());
Source§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::Green.

§Example
println!("{}", value.on_green());
Source§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::Yellow.

§Example
println!("{}", value.on_yellow());
Source§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::Blue.

§Example
println!("{}", value.on_blue());
Source§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::Magenta.

§Example
println!("{}", value.on_magenta());
Source§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::Cyan.

§Example
println!("{}", value.on_cyan());
Source§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::White.

§Example
println!("{}", value.on_white());
Source§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightBlack.

§Example
println!("{}", value.on_bright_black());
Source§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightRed.

§Example
println!("{}", value.on_bright_red());
Source§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightGreen.

§Example
println!("{}", value.on_bright_green());
Source§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightYellow.

§Example
println!("{}", value.on_bright_yellow());
Source§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightBlue.

§Example
println!("{}", value.on_bright_blue());
Source§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightMagenta.

§Example
println!("{}", value.on_bright_magenta());
Source§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightCyan.

§Example
println!("{}", value.on_bright_cyan());
Source§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightWhite.

§Example
println!("{}", value.on_bright_white());
Source§

fn attr(&self, value: Attribute) -> Painted<&T>

Enables the styling Attribute value.

This method should be used rarely. Instead, prefer to use attribute-specific builder methods like bold() and underline(), which have the same functionality but are pithier.

§Example

Make text bold using attr():

use yansi::{Paint, Attribute};

painted.attr(Attribute::Bold);

Make text bold using using bold().

use yansi::Paint;

painted.bold();
Source§

fn bold(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Bold.

§Example
println!("{}", value.bold());
Source§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Dim.

§Example
println!("{}", value.dim());
Source§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Italic.

§Example
println!("{}", value.italic());
Source§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Underline.

§Example
println!("{}", value.underline());

Returns self with the attr() set to Attribute::Blink.

§Example
println!("{}", value.blink());

Returns self with the attr() set to Attribute::RapidBlink.

§Example
println!("{}", value.rapid_blink());
Source§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Invert.

§Example
println!("{}", value.invert());
Source§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Conceal.

§Example
println!("{}", value.conceal());
Source§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Strike.

§Example
println!("{}", value.strike());
Source§

fn quirk(&self, value: Quirk) -> Painted<&T>

Enables the yansi Quirk value.

This method should be used rarely. Instead, prefer to use quirk-specific builder methods like mask() and wrap(), which have the same functionality but are pithier.

§Example

Enable wrapping using .quirk():

use yansi::{Paint, Quirk};

painted.quirk(Quirk::Wrap);

Enable wrapping using wrap().

use yansi::Paint;

painted.wrap();
Source§

fn mask(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Mask.

§Example
println!("{}", value.mask());
Source§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Wrap.

§Example
println!("{}", value.wrap());
Source§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Linger.

§Example
println!("{}", value.linger());
Source§

fn clear(&self) -> Painted<&T>

👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear(). The clear() method will be removed in a future release.

Returns self with the quirk() set to Quirk::Clear.

§Example
println!("{}", value.clear());
Source§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Resetting.

§Example
println!("{}", value.resetting());
Source§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Bright.

§Example
println!("{}", value.bright());
Source§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::OnBright.

§Example
println!("{}", value.on_bright());
Source§

fn whenever(&self, value: Condition) -> Painted<&T>

Conditionally enable styling based on whether the Condition value applies. Replaces any previous condition.

See the crate level docs for more details.

§Example

Enable styling painted only when both stdout and stderr are TTYs:

use yansi::{Paint, Condition};

painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
Source§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new Painted with a default Style. Read more
Source§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.