Code Monkey home page Code Monkey logo

rust-custom-derive's Introduction

macro-attr

This crate provides the macro_attr! macro that enables the use of custom, macro-based attributes and derivations. Supercedes the custom_derive crate.

Links

Compatibility

macro-attr is compatible with Rust 1.2 and higher.

Example

#[macro_use] extern crate macro_attr;

// Define some traits to be derived.

trait TypeName {
    fn type_name() -> &'static str;
}

trait ReprType {
    type Repr;
}

// Define macros which derive implementations of these macros.

macro_rules! TypeName {
    // We can support any kind of item we want.
    (() $(pub)* enum $name:ident $($tail:tt)*) => { TypeName! { @impl $name } };
    (() $(pub)* struct $name:ident $($tail:tt)*) => { TypeName! { @impl $name } };

    // Inner rule to cut down on repetition.
    (@impl $name:ident) => {
        impl TypeName for $name {
            fn type_name() -> &'static str { stringify!($name) }
        }
    };
}

macro_rules! ReprType {
    // Note that we use a "derivation argument" here for the `$repr` type.
    (($repr:ty) $(pub)* enum $name:ident $($tail:tt)*) => {
        impl ReprType for $name {
            type Repr = $repr;
        }
    };
}

// Here is a macro that *modifies* the item.

macro_rules! rename_to {
    (
        ($new_name:ident),
        then $cb:tt,
        $(#[$($attrs:tt)*])*
        enum $_old_name:ident $($tail:tt)*
    ) => {
        macro_attr_callback! {
            $cb,
            $(#[$($attrs)*])*
            enum $new_name $($tail)*
        }
    };
}

macro_attr! {
    #[allow(dead_code)]
    #[derive(Clone, Copy, Debug, ReprType!(u8), TypeName!)]
    #[rename_to!(Bar)]
    #[repr(u8)]
    enum Foo { A, B }
}

fn main() {
    let bar = Bar::B;
    let v = bar as <Bar as ReprType>::Repr;
    let msg = format!("{}: {:?} ({:?})", Bar::type_name(), bar, v);
    assert_eq!(msg, "Bar: B (1)");
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.

rust-custom-derive's People

Contributors

danielkeep avatar durka avatar taborkelly avatar zoxc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

rust-custom-derive's Issues

Allow lifetime usage in custom_derive! macro

Hello,

I recently tried the custom derive with derive_builder on a lifetimed struct like this:

custom_derive! {
    #[derive(Debug, PartialEq, Default, Clone, Builder)]
    struct Another<'a> {
        title: &'a str,
    }
}

The rust compiler gives me this error:

error�: expected ident, found 'a�

newtype_derive for generic types

I tried to use a generic type in the with the custom_derive / newtype_derive macro, but that doesn't compile. See also rust-bio/rust-bio#101.

custom_derive! {
    #[derive(NewtypeFrom, NewtypeDeref, Debug, Clone)]
    pub struct Interval<N>(Range<N>);
}

Looking around I think the macro doesn't currently parse the type. If I look at the effort in rust-parse-generics it also seems quite complicated. Do you expect to support this in the (near) future, or should I manually do the newtype?

NewtypeZero and NewtypeOrd macros

I'm finding I need to implement Zero, so I can call sum() on an iterator of T.

I'm also finding I need to implement Ord in order to sort a vec of T.

Could both of these have macros to derive their implementations?

Deriving non-trait methods in newtype_derive?

I'm working on a proposal to move to newtypes for a crate which makes use of type aliases, and one thing that's come up (see rust-bio/rust-bio#69) is the need to have a way to automatically provide impl's of newtype methods that aren't a part of any traits (e.g. Vec::len or Vec::shrink_to_fit).

I've sketched out a super simple macro to do this (rust-bio/rust-bio#69 (comment)), but we're also talking about using newtype_derive for some of the traits we'd like to make available (Index, for one).

Does it seem like it's in scope to provide this functionality as part of newtype_derive? I had pictured something along the lines of:

custom_derive! {
    #[derive(
        NewtypeFn(len -> usize),
        NewtypeFnMut(shrink_to_fit),
        NewtypeIndex(u8))]
   pub struct NewTypeFromVec(Vec<u8>);
};

I'm not sure about how well it would cover trait implementations like Iterator (perhaps something analogous to Index?), although that'd be something I would be interested in exploring as well.

Thoughts?

newtype_derive: interior field needs to be pub?

Having an issue when trying to modularize my project that uses newtype_derive:

custom_derive! {
    #[derive(NewtypeFrom, NewtypeAdd, NewtypeSub, NewtypeDeref,
             NewtypeBitAnd, NewtypeNot, NewtypeDiv, NewtypeRem,
             Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
    pub struct Sectors(u64);
}

I get error: cannot invoke tuple struct constructor with private fields [E0450] src/consts.rs:12 pub const MDA_ZONE_SECTORS: Sectors = Sectors(MDA_ZONE_SIZE / SECTOR_SIZE);

Then, doing what E0450 says I try to change pub struct Sectors(u64) to pub struct Sectors(pub u64) and I get:

error: local ambiguity: multiple parsing options: built-in NTs ty ('t0') or 1 other option.
src/types.rs:23     pub struct Sectors(pub u64);

and thought that might suggest a macro-related issue?

Using non-built-in derive types with custom_derive?

I want to use Serde's Serialize and Deserialize derive types, but I get these errors when compiling:

error: macro undefined: 'Serialize!'
   --> src/api/common.rs:105:1
    |
105 | custom_derive! {
    | ^
    |
    = note: this error originates in a macro outside of the current crate

error: macro undefined: 'Deserialize!'
   --> src/api/common.rs:105:1
    |
105 | custom_derive! {
    | ^
    |
    = note: this error originates in a macro outside of the current crate

Is there any way around this?

Newtype for str / String

Have you ever considered supporting newtype derivations for string-backed identifiers?

I'm thinking of a similar reference-buffer duality as one between std::path::Path and PathBuf that gives you an option to wrap a str with the newtype without allocating, e.g.:

struct DatasetID(str);
struct DatasetIDBuf(String);

While some of the existing derivations are compatible with these types it still leaves a large enough amount of boilerplate to be written to enable conversions and comparisons between the two to discourage the use of the newtype pattern for string.

Upload 0.2.1

Hi, is it possible to upload the latest version to crates.io? 0.2.0 is the latest version there but 0.2.1 seems ready to go on github

enum_derive cannot contain more than 24 variants due to recursion limit

Test case:

custom_derive! {
    #[derive(Debug, PartialEq, EnumFromStr)]
    pub enum HugeEnum {
        Case0, Case1, Case2, Case3, Case4, Case5, Case6, Case7, Case8, Case9,
        Case10, Case11, Case12, Case13, Case14, Case15, Case16, Case17, Case18, Case19,
        Case20, Case21, Case22, Case23, Case24, Case25, Case26, Case27, Case28, Case29,
        Case30, Case31, Case32, Case33, Case34, Case35, Case36, Case37, Case38, Case39,
        Case40, Case41, Case42, Case43, Case44, Case45, Case46, Case47, Case48, Case49,
        Case50, Case51, Case52, Case53, Case54, Case55, Case56, Case57, Case58, Case59,
        Case60, Case61, Case62, Case63, Case64, Case65, Case66, Case67, Case68, Case69,
        Case70, Case71, Case72, Case73, Case74, Case75, Case76, Case77, Case78, Case79,
        Case80, Case81, Case82, Case83, Case84, Case85, Case86, Case87, Case88, Case89,
        Case90, Case91, Case92, Case93, Case94, Case95, Case96, Case97, Case98, Case99,
    }
}

In version 0.1.6, with Rust 1.8.0 – 1.10.0, this fails with:

<enum_derive macros>:17:1: 19:32 error: recursion limit reached while expanding the macro `enum_derive_util`
<enum_derive macros>:17 enum_derive_util ! {
                        ^

cc rust-lang/rust#22552

TryInto

Great crate! I would love to see some support for unary enums in situation like this

custom_derive! {
    #[derive(...)]
    enum MyEnum {
        u8(u8),
        u16(u16),
    }
}
fn foo(x: MyEnum) -> Result<u8, SomeError> {
    let x:u8 = try!(x.try_into());
    x+1
}

So this is a bit like conv's TryFrom! macro but for unary enums.

Feature Request: strip custom attributes on items

@killercup have a use case, were we could use some custom attribute-annotations of struct fields (like #[customDefault(42i32)]. In our case only our own custom-derive extension would be able to make sense of it.

As illustration imagine the following macro invocation to implement the Default trait - but with special_info : i32 = 42i32 instead of 0 for Channel. This is actually quite close to our use case.

custom_derive! {
    #[derive(CustomDefault)]
    struct Channel {
        id: Uuid,
        token: Authentication,
        #[customDefault(42i32)]
        special_info: i32,
    }
}

Now the question is, is there a feasible way of extending rust-custom-derive to filter out those custom attributes on items when writing the rust code?

  • one spontaneous idea would be an explicit blacklist, e.g. #[strip_attributes(customDefault)] in front of the struct itself
  • another spontaneous idea would be an implicit whitelist in rust-custom-derive itself (probably not so good?)

@DanielKeep: How do you feel about the idea in general?

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 rust-custom-derive developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT/Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

#[deriving(EnumFromInner )] - construct from field

Just an idea: If each variant of an enum has exactly one field, and if each of these field has a different type, then it would be nice to be able to construct an enum object from a field.

struct A{x:f32};
struct B{y:u32};

// Implements From<A> and From<B> for Foo
#[deriving(EnumFromInner)]
enum Foo {A(A), B(B)};

let a = A {x:1.0};
let foo: Foo = Foo::from(a);

#[deriving(EnumKey)] - a C-like enum that enumerate variant types

Given an enum it could be nice to have a macro to construct C-like enum that enumerates the variants. It could look like this

struct A{_x:f32}
struct B{_y:u32}

#[derive(EnumKey(FooKey))]
enum Foo {
    A(A), 
    B(B)
}

fn main() {
    let _a = Foo::A(A {_x:1.0});
    let _b = Foo::B(B {_y:1});
    assert!(_a.key() == FooKey::A);
    assert!(_b.key() == FooKey::B);
}

The following code could be derived behind the scenes

pub trait Key {
    type Key;
    fn key(&self) -> Self::Key;
}

#[derive(Clone,Copy,Debug,PartialEq,Eq)]
enum FooKey {A,B}

impl Key for Foo {
    type Key=FooKey;
    fn key(&self) -> Self::Key {
        match self {
            &Foo::A(..) => FooKey::A,
            &Foo::B(..) => FooKey::B,
        }
    }
}

Gist: https://gist.github.com/4a8a0275d985e975cdeb8b438db5ff5f

Error-reporting pattern does not seem to work

I'm mainly here because I wanted to look up and copy the error reporting pattern here

const _error: () = concat!(
"cannot derive TryFrom for ",
stringify!($name),
", due to non-unitary variant ",
stringify!($var),
"."

but it does not seem to work in modern Rust; the error message does not mention the string at all.

Do you know any good way to report syntax errors in macros? Something like this seems tempting to put in the appropriate fallback branch for a macro:

struct IndexParameterMustBeFirstError;
const _error: () = IndexParameterMustBeFirstError;

#[Derive(EnumInnerAsTrait(MyTrait))] - cast variants to a trait

Here is another idea, that could be super useful:

If each variant of an enum has exactly one field, and if each of these fields implement a given trait, then it could be great to be able to cast the enum to the trait. It could look like this

trait Hello { fn hello(&self){}}

struct A{_x:f32}
struct B{_y:u32}
impl Hello for A {}
impl Hello for B {}

#[derive(EnumInnerAsTrait(Hello))]
enum Foo { A(A), B(B) }

fn main() {
    let a = Foo::A(A {_x:1.0});
    let b = Foo::B(B {_y:1});
    a.as_trait().hello();
    b.as_trait().hello();
}

The following could be derived behind the scenes

pub trait AsTrait {
    type T: ?Sized;
    fn as_trait(&self) -> &Self::T;
}

impl AsTrait for Foo {
    type T=Hello;
    fn as_trait(&self) -> &Self::T {
        match self {
            &Foo::A(ref a) => a as &Self::T,
            &Foo::B(ref b) => b as &Self::T,
        }
    }
}

I have a feeling that there are some pitfalls in this approcah, but at least the following gist works fine, so for some cases it could work out of the box https://gist.github.com/888cbd1ac4be542bce24a1fadf472566.

PS It would also be great to have mutable references

#[derive(StructGetMutField)] to get field without specifying the field name

Here is another idea that might be useful. It could be nice to have a generic macro to get a field without specifying the field name

�struct A;
struct B;

#[derive(StructGetMutField)]
struct Foo {
    a:A,
    b:B,
}

fn main() {
    let foo= Foo {a:A, b:B};
    let _a: &A = foo.get_mut_field();
    let _b: &B = foo.get_mut_field();
}

The following could be derived behind the scenes

trait GetMutField<T>   {
    fn get_mut_field(&mut self) ->&mut T;
}

impl GetMutField<A> for Foo {
    fn get_mut_field(&mut self) ->&mut A {&mut self.a}
}

impl GetMutField<B> for Foo {
    fn get_mut_field(&mut self) ->&mut B {&mut self.b}
}

This macro would allow me to do the following with minimal boiler plate code;

#[derive(StructGetMutField)]
struct Foo {
    as:Vec<A>,
    bs:Vec<B>,
}

let mut foo = Foo {as:Vec::new(), bs:Vec::new(), };
let a = A;
foo.get_mut_field().push(a);

Similarly it would allow me to create a poor mans TypeMap without using the Any-trait.

#[derive(StructGetMutField)]
struct Foo {
    a_opt:Option<A>,
    b_opt:Option<B>,
}

let mut foo = Foo {a_opt: Option::new(), b_opt: Option::new(), };
foo.get_mut_field() = Some(A);;

0.2.0 Tracking Issue

  • Switch to using #[derive(Name!)] instead of #[derive(Name)].
  • Add support for either #[custom_transform(Name!)] or #[Name!].
  • Future proofing: syntax for either invoking a macro on pre-Macros 1.1, or delegating to an actual Macros 1.1 derivation.
  • Rename to macro_derive! macro_attr!.
  • Expand support to all items (because why not?)
  • Expand all existing derivations to support everything reasonable, leveraging parse-macros. (This can just be handled separately.)

#[derive(StructIterFieldsAsTrait(....))]

Here is another idea, that may or may not be possible to implement.

If all the fields of a struct implement a given trait, then be nice to be able to iterate over fields of a struct as cast to the trait.I must admit that I don't know if this is even possible, but if it can be done, then it would be great to have something like the following

struct A;
struct B;

trait Hello { fn hello(&self) { println!("Hello")} }
impl Hello for A {};
impl Hello for B {};

// #[derive(StructIterFieldsAsTrait(pub iter_hellos -> &Hello)]
struct Foo {a: A, b: B}

fn main() {
    let foo= Foo {a:A, b:B};
    for &h in &foo.iter_fields() {
        h.hello();
    }
}

update newtype_derive for std::iter::Sum and Product

Hi, my usage of newtype_derive, which looks like this:

custom_derive! {
    #[derive(NewtypeFrom, NewtypeAdd, NewtypeSub, NewtypeDeref,
             NewtypeBitAnd, NewtypeNot, NewtypeDiv, NewtypeRem,
             NewtypeMul,
             Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
    pub struct Sectors(pub u64);
}

is now throwing this error with Rust nightly:

src/froyo.rs:1095:14: 1095:17 error: the trait bound `types::Sectors: std::iter::Sum` is not satisfied [E0277]
src/froyo.rs:1095             .sum::<Sectors>();
                               ^~~
src/froyo.rs:1095:14: 1095:17 help: run `rustc --explain E0277` to see a detailed explanation

I think this may be due to the new Sum trait: https://doc.rust-lang.org/nightly/std/iter/trait.Sum.html

Custom enum variant names

It would be helpful for me to be able to make custom enum variant names for Display/FromStr derivations. Currently I have a bespoke macro for this purpose.

error: missing fragment specifier

error: missing fragment specifier
   --> tests/stable_encodable.rs:119:28
    |
119 |         ($ty_name:ident: $($tail)*)
    |                            ^^^^^
    |
    = note: #[deny(missing_fragment_specifier)] on by default
    = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
    = note: for more information, see issue #40107 <https://github.com/rust-lang/rust/issues/40107>

Update `rustc_version` crate to a non-yanked version

No new crates can use the current version. No new crates can use other projects that use the current version. (Not without some Cargo.lock manipulation, which works in the meantime but seems unwise)

It looks like #37 was working on this, but it's stalled out since the end of 2017. Is this project being maintained anymore? I hope so, because I find it really helpful.

Previous/next enum item

Would you be open to having a derive that adds methods for selecting the previous or next variant of an enum?

enum E { A, B, C }

E::A.next();  // returns E::B
E::C.next();  // returns E::A

E::A.prev();  // returns E::C
E::C.prev();  // returns E::B

Would be a nice complement to the variant iterator.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.