Skip to main content

litext

Macro litext 

Source
macro_rules! litext {
    ($input:ident $(as String)?) => { ... };
    ($input:ident as LitStr) => { ... };
}
Expand description

The whole point.

Extracts the inner text content from a token stream representing a string literal.

This macro is the primary interface for extracting string content from tokens. It takes a TokenStream that should represent a single string literal and returns either a String or a LitStr depending on the form used. If the input is invalid, the macro triggers a compile error at the call site.

§Forms

§litext!(input) and litext!(input as String)

Both forms are equivalent. They extract the string content and return a plain String. The as String form is purely cosmetic, it can be useful for readability when it isn’t immediately obvious what the macro returns.

§litext!(input as LitStr)

Returns a LitStr bundling the extracted string value with its source Span. Use this form when you need to emit diagnostics that point back at the exact location of the literal in the macro input.

§Arguments

The input argument must be an identifier referring to a TokenStream containing exactly one token that represents a string literal. This can be:

  • A regular string: "hello world"
  • A raw string: r#"hello world"#
  • A raw string with multiple hashes: r##"hello # world"##

§Errors

Both forms produce compile-time errors for:

  • Empty input: litext! expected a string literal, got nothing
  • Multiple tokens: litext! expected exactly one string literal
  • Not a string literal: litext! expected a string literal, found ...
  • Byte strings: litext: expected a string literal, not a byte string

§Examples

Basic usage, returning a String:

use litext::{litext, TokenStream};

pub fn my_macro(input: TokenStream) -> TokenStream {
    let content = litext!(input);
    // or equivalently:
    let content = litext!(input as String);
}

Using as LitStr to retain span information for diagnostics:

use litext::{litext, TokenStream};

pub fn my_macro(input: TokenStream) -> TokenStream {
    let lit = litext!(input as LitStr);
    let value = lit.value();
    let span = lit.span();
}