Streamline [ syn::parse::Parse ] and [ quote::ToTokens ]
Declarative programming is fast and reliable. Implementing syn::parse::Parse or quote::ToTokens commonly follow a cooking recipe. This gave the idea for impl_parse.
- Derive macro. Save time using
ParseStructandParseEnum. - Meaningful Errors. Guiding errors and what could follow instead.
- Building blocks. Basic and custom types to allow scalable logic.
- Baseline dependencies. Depends only on
proc-macro2,synandquote. - Full transparency. Allows to output the generated code. No hidden code!
- Quick Start
- Introduction
- Available attributes
- Checkout Documentation
- Checkout examples
- Why nightly?
- Contact
- Support impl_parse
- Contributors
Either directly target the github repository:
[dependencies]
impl_parse = { git = "https://github.com/be-mevsane/impl_parse.git" }Or clone the repo and use as local dependency target:
git clone https://github.com/be-mevsane/impl_parse.gitfollowed by
[dependencies]
impl_parse = { version = "0.0.1", path = "[PATH_TO]/impl_parse" }Using on struct's with named or unnamed fields. This parses the input while expecting the tokens to match the sequence defined in the order of the struct fields:
use impl_parse::ParseStruct;
// UNNAMED FIELD
#[derive(ParseStruct)]
struct ToParse(
// `syn::LitStr` already implements syn::parse::Parse
syn::LitStr,
// `syn::LitStr` already implements syn::parse::Parse
syn::LitInt,
);Use custom struct ToParse in other structs:
use impl_parse::ParseStruct;
// NAMED FIELDS
#[derive(ParseStruct)]
struct CustomStruct {
// `syn::LitInt` already implements syn::parse::Parse
int: syn::LitInt,
// `ToParse` is expected to implement syn::parse::Parse
str: ToParse,
}Combining the target ToParse with mutiple Wrappers:
use impl_parse::ParseStruct;
use std::sync::{Arc, Mutex};
use std::cell::RefCell;
// UNNAMED FIELDS with wrapper types
#[derive(ParseStruct)]
struct WrappedFieldsUnnamed(
// inner = `syn::LitInt` already implements syn::parse::Parse
Arc<Mutex<syn::LitInt>>,
// inner = `ToParse` is expected to implement syn::parse::Parse
Option<RefCell<ToParse>>,
);Using on enums's. This parses the input while expecting the tokens to match any one variant (matching order = definition order):
use impl_parse::ParseEnum;
// inner types already implement syn::parse::Parse
#[derive(ParseEnum)]
enum EnumType {
IDENT(syn::Ident),
STR(syn::LitStr),
INT(syn::LitInt),
AND(syn::token::And),
}Combining the target ToParse with mutiple Wrappers:
use impl_parse::ParseEnum;
use std::sync::{Arc, Mutex};
use std::cell::RefCell;
#[derive(ParseEnum)]
enum EnumType {
One(syn::Ident),
Two(syn::LitStr, syn::Ident),
}
#[derive(ParseEnum)]
enum CustomEnum {
// inner = `syn::LitInt` already implements syn::parse::Parse
One(Arc<Mutex<syn::LitInt>>),
// inner = `EnumType` is expected to implement syn::parse::Parse
Two(Option<RefCell<EnumType>>, syn::Ident),
// Only `Option` types are not allowed when using `ParseEnum`.
// Uncomment to trigger compiler error.
// Three(Option<syn::LitStr>, Option<syn::LitInt>, Option<syn::Ident>),
}Using on enums's. This implements a convenience function to check enums on equality based on the variant without comparing the inner types using:
fn variant_eq(&self, other: &Self) -> boolBring into scope and use it:
use impl_parse::VariantEq;
use syn::{LitInt, LitStr, LitFloat};
#[derive(VariantEq)]
enum Variants {
ONE(LitInt),
TWO(LitStr),
THREE(LitFloat),
}
fn do_something_with_variants(arg: Variants, other: Variants) {
// alternatively
// other.variant_eq(&arg)
if arg.variant_eq(&other) {
// do something
}
assert!(arg.variant_eq(&other) == other.variant_eq(&arg));
}Checkout Documentation
Types are classified into categories. ToParse, Groups, Lists and Tuple will contain their respective logic to be parsed. Wrappers affect construction and dereferencing. PhantomData maintains its purpose as a zero sized marker type, plus an additional but optional parsing logic.
ToParse:
ToParseis expected to implement[syn::parse::Parse]
Groups:
Paren (...)see[syn::token::Paren]Bracket [...]see[syn::token::Bracket]Brace {...}see[syn::token::Brace]
Lists:
Punctuatedsee[syn::punctuated::Punctuated]Vecsee[std::vec::Vec]Array[T, N]
Tuple:
(T),(T1, T2),(T1, T2, ...)
PhantomData:
PhantomDatasee[std::marker::PhantomData]
Optionsee[std::option::Option]Boxsee[std::boxed::Box]Cowsee[std::borrow::Cow]Rcsee[std::rc::Rc]Cellsee[std::cell::Cell]RefCellsee[std::cell::RefCell]Arcsee[std::sync::Arc]RwLocksee[std::sync::RwLock]Mutexsee[std::sync::Mutex]
Note that Cell<T> requires T: Clone which syn structs and enums generally do not implement.
- Deactivated by default.
- Defaults to
2021when onlystyle_editionis used. - Specifies which edition is used by the parser.
- Deactivated by default.
- Defaults to
2021when onlyeditionis used. - Specifies the edition of the Rust Style Guide to use for formatting.
- Deactivated by default.
- Specifies edition and style_edition simultaneously. Will be applied when
rustfmt.editionorrustfmt.style_editionnot specified.
Supported editions 2015, 2018, 2021, 2024, 2027. For more details see rustfmt docs.
Use any one of the above to write the generated code to file located at: {CARGO_MANIFEST_DIR}/target/debug/build/impl_parse.
use impl_parse::{ParseEnum, ParseStruct};
// Uncomment one to generate output at:
// - path/to//target/debug/build/impl_parse-###/ToParse-###.rs
// - path/to//target/debug/build/impl_parse-###/ToParseEnum-###.rs
// where ### stands for hash of 16 characters.
#[derive(ParseStruct)]
// #[impl_parse(rustfmt.edition = 2021)]
// #[impl_parse(rustfmt.style_edition = 2021)]
// #[impl_parse(rustfmt = 2021)]
struct ToParse(syn::LitStr);
#[derive(ParseEnum)]
// #[impl_parse(rustfmt.edition = 2021)]
// #[impl_parse(rustfmt.style_edition = 2021)]
// #[impl_parse(rustfmt = 2021)]
enum ToParseEnum { A(syn::LitStr) }CARGO_MANIFEST_DIR is usually where your projects Cargo.toml is located.
- Deactivated by default.
- Implements the trait
quote::ToTokens. - Expects all fields to also implement
quote::ToTokens. - Trait
syn::spanned::Spannedalso gets enabled. - Individual fields with
PhantomData<T>are ignored.
use impl_parse::{ParseEnum, ParseStruct};
#[derive(ParseStruct)]
#[impl_parse(quote::ToTokens)]
struct ToParse(syn::LitStr);
#[derive(ParseEnum)]
#[impl_parse(quote::ToTokens)]
enum ToParseEnum { A(syn::LitStr) }- Deactivated by default.
- Without: Code immediately calls
return Err(...);upon failing to parse. - With: Code collects and combines additional and nested errors before calling
return Err(...);upon failing to parse.
use impl_parse::{ParseEnum, ParseStruct};
#[derive(ParseStruct)]
#[impl_parse(extend_errors)]
struct ToParse(syn::LitStr);
#[derive(ParseEnum)]
#[impl_parse(extend_errors)]
enum ToParseEnum { A(syn::LitStr) }Check distance in bytes to previously parsed tokens after successfull parsing:
- Deactivated by default.
- Supports nesting like
lines => x && (lines != y || spaces <= z). - Requires tokens to implement
span(&self). - Without: Skips check for distance.
- With: Code checks for distance and calls
return Err(...);on mismatch.
Check distance in bytes to parsed tokens right before closing token ), ] or } after successfull parsing:
- Deactivated by default.
- Supports nesting like
end_lines => x && (end_lines != y || end_spaces <= z). - Requires tokens to implement
span(&self). - Without: Skips check for distance.
- With: Code checks for distance and calls
return Err(...);on mismatch.
use impl_parse::{ParseEnum, ParseStruct};
use syn::spanned::Spanned;
/// e.g.: `help "text";`
#[derive(ParseStruct)]
struct FunctionCall(
syn::Ident,
// same line and 2 spaces to `syn::Ident`
#[impl_parse(lines == 0 || spaces == 2)]
syn::LitStr,
// same line and no spaces to `syn::LitStr`
#[impl_parse(lines == 0 || spaces == 0)]
syn::token::Semi,
);
#[derive(ParseEnum)]
enum FunctionCallEnum{
A(
syn::Ident,
// same line and 2 spaces to `syn::Ident`
#[impl_parse(lines == 0 || spaces == 2)]
syn::LitStr,
// same line and no spaces to `syn::LitStr`
#[impl_parse(lines == 0 || spaces == 0)]
syn::token::Semi,
),
B(syn::Ident),
}- Deactivated by default.
- Without: Code calls
return Err(...);. - With: Code calls
break;inside loops.
- Deactivated by default.
- Supports nesting like
length => x && (length != y || length <= z). - Requires
#[impl_parse(continue_on_error)]. - BinOp one of
[<, <=, ==, !=, >=, >]. - Without: Adds
intentional empty?warning to next error message instead of check. - With: Code checks for length and calls
return Err(...);on mismatch.
use impl_parse::{ParseEnum, ParseStruct};
#[derive(ParseStruct)]
struct ToParse(
#[impl_parse(continue_on_error)]
#[impl_parse(length > 2)]
Vec<syn::LitStr>
);
#[derive(ParseEnum)]
enum ToParseEnum{
A(
#[impl_parse(continue_on_error)]
#[impl_parse(length > 2)]
Vec<syn::LitStr>
)
}Will attempt to parse the inner type T from PhantomData<T> and advances the input stream cursor on success. The result will not be stored. The field for PhantomData<T> still remains zero-sized.
- Deactivated by default.
Tbecomes expected to also implementsyn::parse::Parse.- Without: Only initialize
std::marker::PhantomData<T>. - With: Parse
Tand initializestd::marker::PhantomData<T>upon success and drops parsedT.
use impl_parse::{ParseEnum, ParseStruct};
#[derive(ParseStruct)]
struct ToParse(
syn::token::Paren,
#[impl_parse(parse_inner_type)]
std::marker::PhantomData<syn::LitStr>
);
#[derive(ParseEnum)]
enum ToParseEnum{
A(
syn::token::Paren,
#[impl_parse(parse_inner_type)]
std::marker::PhantomData<syn::LitStr>
),
B(syn::Ident),
}- Matrix 3x3
Possible implementations how a 3x3 matrix can be parsed. - Output derive-macro to file
How the generated code from the derive macro can be written to a file. - PhantomData
Marker type and optional check. - Sql Parser
Possible sqlSELECTquery with optionalWHEREclause. - Symbol Distance
How to uselinesandspacesto define distance to preceding symbol.
The feature #![feature(proc_macro_span)] is specifically used for span(&self).start() and span(&self).end().
Both functions are already stabilized. See the issue tracker: rust-lang/rust#54725
Without this feature, parsing a custom struct or enum inside another struct or enum that also implements syn::parse::Parse results in losing the line and column information of that type. It is treated as a continuous stream from a single line.
Questions should be posted in:
Bugs and feature requests belong in the
Anyone contributing or representing impl_parse both inside and outside of this GitHub repository has to abide by:
Matters and issues that should be privately communicated with the author:
Maintainer's personal address:
impl_parse should make it simpler for everyone to get into developing custom macros in rust.
It is Apache-2.0 and free — forever. If impl_parse saved you time, leave a star as it helps the most.
If you would like to fund the work directly:
🎁❤️ Donate — one-off, any amount. Payments are processed by Stripe under the personal account, Mevluet Beser — that name, not "impl_parse", is what appears on the checkout page and only KO-FI MEVLUET BESER or KO-FI M.B. on your card statement.
Why Ko-fi?
Open-source software takes time, coffee, and server costs to maintain. By buying me a coffee, you are directly supporting the development, maintenance, and hosting of these tools. Every bit of support keeps these projects free, well-documented, and actively updated for everyone.
Thank you for supporting independent open-source development!