Skip to content

About

Implementing syn::parse::Parse or quote::ToTokens commonly follow a cooking recipe. Save time using this.

Topics

Resources

Code of conduct

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

impl_parse

impl_parse

Streamline [ syn::parse::Parse ] and [ quote::ToTokens ]

Rust 1.101.0 Rust nightly Apache-2.0 License


Why impl_parse?

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 ParseStruct and ParseEnum.
  • 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, syn and quote.
  • Full transparency. Allows to output the generated code. No hidden code!

Table of content

Quick Start

1 Add dependencies

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.git

followed by

[dependencies]
impl_parse = { version = "0.0.1", path = "[PATH_TO]/impl_parse" }

2 Derive macros

2.1 impl_parse::ParseStruct

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>>,
);

2.2 impl_parse::ParseEnum

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>),
}

2.2 impl_parse::VariantEq

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) -> bool

Bring 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

Introduction

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:

  • ToParse is expected to implement [syn::parse::Parse]

Groups:

  • Paren (...) see [syn::token::Paren]
  • Bracket [...] see [syn::token::Bracket]
  • Brace {...} see [syn::token::Brace]

Lists:

  • Punctuated see [syn::punctuated::Punctuated]
  • Vec see [std::vec::Vec]
  • Array [T, N]

Tuple:

  • (T), (T1, T2), (T1, T2, ...)

PhantomData:

  • PhantomData see [std::marker::PhantomData]

Wrappers:

  • Option see [std::option::Option]
  • Box see [std::boxed::Box]
  • Cow see [std::borrow::Cow]
  • Rc see [std::rc::Rc]
  • Cell see [std::cell::Cell]
  • RefCell see [std::cell::RefCell]
  • Arc see [std::sync::Arc]
  • RwLock see [std::sync::RwLock]
  • Mutex see [std::sync::Mutex]

Note that Cell<T> requires T: Clone which syn structs and enums generally do not implement.

Available attributes

1 Struct and Enum level attributes:

1.1 #[impl_parse(rustfmt.edition = 2021)]

  • Deactivated by default.
  • Defaults to 2021 when only style_edition is used.
  • Specifies which edition is used by the parser.

1.2 #[impl_parse(rustfmt.style_edition = 2021)]

  • Deactivated by default.
  • Defaults to 2021 when only edition is used.
  • Specifies the edition of the Rust Style Guide to use for formatting.

1.3 #[impl_parse(rustfmt = 2021)]

  • Deactivated by default.
  • Specifies edition and style_edition simultaneously. Will be applied when rustfmt.edition or rustfmt.style_edition not 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.

1.4 #[impl_parse(quote::ToTokens)]

  • Deactivated by default.
  • Implements the trait quote::ToTokens.
  • Expects all fields to also implement quote::ToTokens.
  • Trait syn::spanned::Spanned also 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) }

1.5 #[impl_parse(extend_errors)]

  • 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) }

2 Field level attributes:

2.1 #[impl_parse(lines BinOp x && spaces BinOp y)]

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.

2.2 #[impl_parse(end_lines BinOp x && end_spaces BinOp y)] only for groups Paren, Bracket and Brace

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),
}

2.3 #[impl_parse(continue_on_error)] only for Vec and Punctuated

  • Deactivated by default.
  • Without: Code calls return Err(...);.
  • With: Code calls break; inside loops.

2.4 #[impl_parse(length BinOp x)] only for Vec and Punctuated

  • 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>
    )
}

2.5 #[impl_parse(parse_inner_type)] only for PhantomData

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.
  • T becomes expected to also implement syn::parse::Parse.
  • Without: Only initialize std::marker::PhantomData<T>.
  • With: Parse T and initialize std::marker::PhantomData<T> upon success and drops parsed T.
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),
}

Checkout examples

Why nightly?

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.

Contact

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:

  • Security
  • Code of Conduct
  • Press related
  • Issues that do not fit in any categories named in Contact

Maintainer's personal address:

be.mevsane@gmail.com

Support impl_parse

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:

Ko-fi

🎁❤️ 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!

Contributors

Contributors

About

Implementing syn::parse::Parse or quote::ToTokens commonly follow a cooking recipe. Save time using this.

Topics

Resources

Code of conduct

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages