Crate quote_doctest

Source
Expand description

Using the doc_test macro, we can take any TokenStream and turn it into a doctest TokenStream that can be interpolated in any quote macro invocation.

The doc_comment function takes any string and turns it into one or more comments inside a TokenStream.

use quote::quote;
use quote_doctest::{doc_comment, doc_test, FormatDocTest};

// Takes any `TokenStream` as input (but typically `quote` would be used)
let test = doc_test!(quote! {
    _comment_!("Calling fibonacci with 10 returns 55");
    assert_eq!(fibonacci(10), 55);

    _blank_!();
    _comment_!("Calling fibonacci with 1 simply returns 1");
    assert_eq!(fibonacci(1), 1);
}).unwrap();

let comment = doc_comment("This compares fib inputs and outputs:\n\n");

// Interpolates into a regular `quote` invocation
let actual = quote! {
    #comment
    #test
    fn fibonacci(n: u64) -> u64 {
        match n {
            0 => 1,
            1 => 1,
            n => fibonacci(n - 1) + fibonacci(n - 2),
        }
    }
};

// This is what is generated:
let expected = quote! {
    /// This compares fib inputs and outputs:
    ///
    /// ```
    /// // Calling fibonacci with 10 returns 55
    /// assert_eq!(fibonacci(10), 55);
    ///
    /// // Calling fibonacci with 1 simply returns 1
    /// assert_eq!(fibonacci(1), 1);
    /// ```
    fn fibonacci(n: u64) -> u64 {
        match n {
            0 => 1,
            1 => 1,
            n => fibonacci(n - 1) + fibonacci(n - 2),
        }
    }
};

assert_eq!(expected.format_tokens().unwrap(), actual.format_tokens().unwrap());

Macros§

  • A “marker” macro used to mark locations in the source code where blank lines should be inserted. If no parameter is given, one blank line is assumed, otherwise the integer literal specified gives the # of blank lines to insert.
  • A “marker” macro used to mark locations in the source code where comments should be inserted. If no parameter is given, a single blank comment is assumed, otherwise the string literal specified is broken into lines and those comments will be inserted individually.
  • Creates a doctest from a TokenStream. Typically that is all that is supplied, however, there is an optional parameter of type DocTestOptions that can be supplied to fine tune whether or not formating is used, choose a formatter (either pretty_please or rustfmt), or whether a main function generated (it is required if formatting, but one can be specified manually).

Enums§

  • Optional enum passed to doc_test for different configuration options
  • This error is returned when errors are triggered during the formatting process
  • The formatter used to format source code - either prettyplease or the system rustfmt

Constants§

  • The default amount of formatter indent to remove (when generating main)

Traits§

Functions§

  • Creates a doc comment for interpolation into a TokenStream. It takes a string as input, splits it by line, and inserts one doc comment per line.