Crate moisture

Crate moisture 

Source
Expand description

Moisture is a Rust code parsing library with a callback interface. It is based on syn, quote and proc-macro2 and is intended to be used with procedural macros.

What Moisture does specifically is parse the entire syntax tree provided by a token stream and issue callbacks to certain objects for potential modification. A basic example:

use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{LitStr, Result, parse2};
use syn::spanned::Spanned;

use moisture::*;

fn str_callback(moisture: &Moisture, context: &Context, tokens: TokenStream) -> Result<TokenStream> {
   let lit_str = parse2::<LitStr>(tokens.clone())?;

   if lit_str.value() == "foo" { Ok(LitStr::new("bar", lit_str.span()).to_token_stream()) }
   else { let result = moisture.lit_str(context, tokens)?; Ok(result) }
}

let mut moisture = Moisture::new();
moisture.register_callback(CallbackType::LitStr, str_callback);

let foo_stream = quote! { "foo" };
let bar_stream = run_moisture!(moisture, CallbackType::LitStr, foo_stream);
let bar_lit = parse2::<LitStr>(bar_stream).unwrap();

assert_eq!(bar_lit.value(), "bar");

let baz_stream = quote! { "baz" };
let same_stream = run_moisture!(moisture, CallbackType::LitStr, baz_stream);
let baz_lit = parse2::<LitStr>(same_stream).unwrap();

assert_eq!(baz_lit.value(), "baz");

A significant chunk of syn types are supported. See CallbackType for a list of supported syn types.

Macros§

run_moisture
The macro to use in procedural macros when parsing with Moisture.

Structs§

Context
The callback context of the given syntax callback.
Moisture
The structure which holds and processes the callbacks.

Enums§

CallbackType
The type of callback to register with the Moisture structure.

Functions§

get_pat_type
Get a PatType object from a TokenStream.

Type Aliases§

Callback
The callback function to register with the Moisture structure.