Crate auto_enums
source · [−]Expand description
A library for to allow multiple return types by automatically generated enum.
This crate is a procedural macro implementation of the features discussions in [rust-lang/rfcs#2414]. This idea is also known as [“Anonymous sum types”][rust-lang/rfcs#294].
This library provides the following attribute macros:
-
#[auto_enum]
Parses syntax, creates the enum, inserts variants, and passes specified traits to
#[enum_derive]
. -
#[enum_derive]
Implements specified traits to the enum.
#[auto_enum]
#[auto_enum]
’s basic feature is to wrap the value returned by the obvious
branches (match
, if
, return
, etc..) by an enum that implemented the
specified traits.
use auto_enums::auto_enum;
#[auto_enum(Iterator)]
fn foo(x: i32) -> impl Iterator<Item = i32> {
match x {
0 => 1..10,
_ => vec![5, 10].into_iter(),
}
}
#[auto_enum]
generates code in two stages.
First, #[auto_enum]
will do the following.
- parses syntax
- creates the enum
- inserts variants
Code like this will be generated:
fn foo(x: i32) -> impl Iterator<Item = i32> {
#[::auto_enums::enum_derive(Iterator)]
enum __Enum1<__T1, __T2> {
__T1(__T1),
__T2(__T2),
}
match x {
0 => __Enum1::__T1(1..10),
_ => __Enum1::__T2(vec![5, 10].into_iter()),
}
}
Next, #[enum_derive]
implements the specified traits.
Code like this will be generated:
fn foo(x: i32) -> impl Iterator<Item = i32> {
enum __Enum1<__T1, __T2> {
__T1(__T1),
__T2(__T2),
}
impl<__T1, __T2> ::core::iter::Iterator for __Enum1<__T1, __T2>
where
__T1: ::core::iter::Iterator,
__T2: ::core::iter::Iterator<Item = <__T1 as ::core::iter::Iterator>::Item>,
{
type Item = <__T1 as ::core::iter::Iterator>::Item;
#[inline]
fn next(&mut self) -> ::core::option::Option<Self::Item> {
match self {
__Enum1::__T1(x) => x.next(),
__Enum1::__T2(x) => x.next(),
}
}
#[inline]
fn size_hint(&self) -> (usize, ::core::option::Option<usize>) {
match self {
__Enum1::__T1(x) => x.size_hint(),
__Enum1::__T2(x) => x.size_hint(),
}
}
}
match x {
0 => __Enum1::__T1(1..10),
_ => __Enum1::__T2(vec![5, 10].into_iter()),
}
}
Nested arms/branches
#[auto_enum]
can also parse nested arms/branches by using the #[nested]
attribute.
use auto_enums::auto_enum;
#[auto_enum(Iterator)]
fn foo(x: i32) -> impl Iterator<Item = i32> {
match x {
0 => 1..10,
#[nested]
_ => match x {
1 => vec![5, 10].into_iter(),
_ => 0..=x,
},
}
}
#[nested]
can be used basically in the same place as #[auto_enum]
,
except that #[nested]
cannot be used in functions.
Recursion
If an error due to recursion occurs, you need to box branches where recursion occurs.
use auto_enums::auto_enum;
struct Type {
child: Vec<Type>,
}
impl Type {
#[auto_enum(Iterator)]
fn method(&self) -> impl Iterator<Item = ()> + '_ {
if self.child.is_empty() {
Some(()).into_iter()
} else {
// Boxing is only needed on branches where recursion occurs.
Box::new(self.child.iter().flat_map(|c| c.method())) as Box<dyn Iterator<Item = _>>
}
}
}
Positions where #[auto_enum]
can be used.
#[auto_enum]
can be used in the following three places. However, since
stmt_expr_attributes and proc_macro_hygiene are not stabilized, you need
to use empty #[auto_enum]
for functions except nightly.
-
functions
use auto_enums::auto_enum; #[auto_enum(Iterator)] fn func(x: i32) -> impl Iterator<Item=i32> { if x == 0 { Some(0).into_iter() } else { 0..x } }
-
expressions
use auto_enums::auto_enum; #[auto_enum] // Nightly does not need an empty attribute to the function. fn expr(x: i32) -> impl Iterator<Item=i32> { #[auto_enum(Iterator)] match x { 0 => Some(0).into_iter(), _ => 0..x, } }
-
let binding
use auto_enums::auto_enum; #[auto_enum] // Nightly does not need an empty attribute to the function. fn let_binding(x: i32) -> impl Iterator<Item=i32> { #[auto_enum(Iterator)] let iter = match x { 0 => Some(0).into_iter(), _ => 0..x, }; iter }
Supported syntax
-
if
andmatch
Wrap each branch with a variant.
use auto_enums::auto_enum; // if #[auto_enum(Iterator)] fn expr_if(x: i32) -> impl Iterator<Item=i32> { if x == 0 { Some(0).into_iter() } else { 0..x } } // match #[auto_enum] // Nightly does not need an empty attribute to the function. fn expr_match(x: i32) -> impl Iterator<Item=i32> { #[auto_enum(Iterator)] let iter = match x { 0 => Some(0).into_iter(), _ => 0..x, }; iter }
-
loop
Wrap each
break
with a variant. Nested loops and labeledbreak
are also supported.use auto_enums::auto_enum; #[auto_enum(Iterator)] fn expr_loop(mut x: i32) -> impl Iterator<Item = i32> { loop { if x < 0 { break x..0; } else if x % 5 == 0 { break 0..=x; } x -= 1; } }
-
return
(in functions)#[auto_enum]
can parse thereturn
in the scope.This analysis is valid only when the return type is
impl Trait
.use auto_enums::auto_enum; // return (in functions) #[auto_enum(Iterator)] fn func(x: i32) -> impl Iterator<Item=i32> { if x == 0 { return Some(0).into_iter(); } if x > 0 { 0..x } else { x..=0 } }
-
return
(in closures)#[auto_enum]
can parse thereturn
in the scope.This analysis is valid only when the following two conditions are satisfied.
#[auto_enum]
must be used directly for that closure (or the let binding of the closure).?
operator not used in the scope.
use auto_enums::auto_enum; // return (in closures) #[auto_enum] // Nightly does not need an empty attribute to the function. fn closure() -> impl Iterator<Item=i32> { #[auto_enum(Iterator)] let f = |x| { if x == 0 { return Some(0).into_iter(); } if x > 0 { 0..x } else { x..=0 } }; f(1) }
-
?
operator (in functions)#[auto_enum]
can parse the?
operator in the scope.This analysis is valid only when the return type is
Result<T, impl Trait>
.use auto_enums::auto_enum; use std::fmt::{Debug, Display}; // `?` operator (in functions) #[auto_enum(Debug, Display)] fn func(x: i32) -> Result<i32, impl Debug + Display> { if x == 0 { Err("`x` is zero")?; } // The last branch of the function is not parsed. if x < 0 { Err(x)? } else { Ok(x + 1) } }
?
operator is expanded as follows:match expr { Ok(val) => val, Err(err) => return Err(Enum::Veriant(err)), }
-
?
operator (in closures)#[auto_enum]
can parse the?
operator in the scope.However,
#[auto_enum]
must be used directly for that closure (or the let binding of the closure).use auto_enums::auto_enum; use std::fmt::{Debug, Display}; // `?` operator (in closures) #[auto_enum] // Nightly does not need an empty attribute to the function. fn closure() -> Result<i32, impl Debug + Display> { #[auto_enum(Debug, Display)] let f = |x| { if x == 0 { Err("`x` is zero")? } // The last branch of the function is not interpreted as a branch. if x < 0 { Err(x)? } else { Ok(x + 1) } }; f(1) }
-
Block, unsafe block, method call, parentheses, and type ascription
The following expressions are recursively searched until an
if
,match
,loop
or unsupported expression is found.- blocks
- unsafe blocks
- method calls
- parentheses
- type ascriptions
use auto_enums::auto_enum; // block #[auto_enum] // Nightly does not need an empty attribute to the function. fn expr_block(x: i32) -> impl Iterator<Item=i32> { #[auto_enum(Iterator)] { if x == 0 { Some(0).into_iter() } else { 0..x } } } // method call #[auto_enum] // Nightly does not need an empty attribute to the function. fn expr_method(x: i32) -> impl Iterator<Item=i32> { #[auto_enum(Iterator)] match x { 0 => Some(0).into_iter(), _ => 0..x, }.map(|y| y + 1) } // parentheses #[auto_enum(Iterator)] fn expr_parentheses(x: i32) -> impl Iterator<Item=i32> { (if x == 0 { Some(0).into_iter() } else { 0..x }) }
Expression that no value will be returned
If the last expression of a branch is one of the following, it is interpreted that no value will be returned (variant assignment is skipped).
panic!(..)
unreachable!(..)
return
break
continue
None?
Err(..)?
- Expression level marker (
marker!
macro). - An item definition.
Also, if the branch contains #[nested]
, it is interpreted as returning
an anonymous enum generated by #[auto_enum]
, not a value.
use auto_enums::auto_enum;
#[auto_enum(Iterator)]
fn foo(x: i32) -> impl Iterator<Item = i32> {
match x {
0 => 1..10,
1 => panic!(), // variant assignment is skipped
_ => vec![5, 10].into_iter(),
}
}
You can also skip that branch explicitly by #[never]
attribute.
use auto_enums::auto_enum;
#[auto_enum(Iterator)]
fn foo(x: i32) -> impl Iterator<Item = i32> {
match x {
0 => 1..10,
#[never]
1 => loop {
panic!()
},
_ => vec![5, 10].into_iter(),
}
}
Expression level marker (marker!
macro)
#[auto_enum]
replaces marker!
macros with variants.
If values of two or more are specified by marker!
macros, #[auto_enum]
can be used for unsupported expressions and statements.
use auto_enums::auto_enum;
#[auto_enum(Iterator)]
fn foo(x: i32) -> impl Iterator<Item = i32> {
if x < 0 {
return x..=0;
}
marker!(1..10)
}
The default name of the macro is "marker"
, but you can change it by
marker
option.
use auto_enums::auto_enum;
#[auto_enum(marker = bar, Iterator)]
fn foo(x: i32) -> impl Iterator<Item = i32> {
if x < 0 {
return x..=0;
}
bar!(1..10)
}
Rust Nightly
When using #[auto_enum]
for expressions and statements, #[auto_enum]
for
function is unnecessary.
// Add this to your crate root:
#![feature(proc_macro_hygiene, stmt_expr_attributes)]
use auto_enums::auto_enum;
fn foo(x: i32) -> i32 {
#[auto_enum(Iterator)]
let iter = match x {
0 => 1..10,
_ => vec![5, 10].into_iter(),
};
iter.fold(0, |sum, x| sum + x)
}
You can also return closures.
// Add this to your crate root:
#![feature(fn_traits, unboxed_closures)]
use auto_enums::auto_enum;
#[auto_enum(Fn)]
fn foo(x: bool) -> impl Fn(i32) -> i32 {
if x { |y| y + 1 } else { |z| z - 1 }
}
#[enum_derive]
#[enum_derive]
implements the supported traits and passes unsupported
traits to #[derive]
.
If you want to use traits that are not supported by #[enum_derive]
, you
can use another crate that provides derives macros, or
you can define derives macros yourself (derive_utils probably can help it).
Basic usage of #[enum_derive]
use auto_enums::enum_derive;
// `#[enum_derive]` implements `Iterator`, and `#[derive]` implements `Clone`.
#[enum_derive(Iterator, Clone)]
enum Foo<A, B> {
A(A),
B(B),
}
#[enum_derive]
adds the dependency of the specified trait if it is not
specified.
use auto_enums::enum_derive;
// `#[enum_derive]` implements `Iterator` and `ExactSizeIterator`.
#[enum_derive(ExactSizeIterator)]
enum Foo<A, B> {
A(A),
B(B),
}
Supported traits
Some traits support is disabled by default. Note that some traits have aliases.
When using features that depend on unstable APIs, the unstable
feature must be explicitly enabled
The standard library (std
, core
)
[std|core]::iter
Iterator
- generated codeDoubleEndedIterator
- generated codeExactSizeIterator
- generated codeFusedIterator
- generated codeExtend
- generated codeTrustedLen
- generated code (requires"trusted_len"
and"unstable"
crate features)
See also iter-enum crate.
[std|core]::future
See also futures-enum crate.
std::io
(requires "std"
crate feature)
Read
(alias:io::Read
) - generated codeBufRead
(alias:io::BufRead
) - generated codeWrite
(alias:io::Write
) - generated codeSeek
(alias:io::Seek
) - generated code
See also io-enum crate.
[std|core]::ops
Deref
(requires"ops"
crate feature)DerefMut
(requires"ops"
crate feature)Index
(requires"ops"
crate feature)IndexMut
(requires"ops"
crate feature)RangeBounds
(requires"ops"
crate feature)Fn
(requires"fn_traits"
and"unstable"
crate features)FnMut
(requires"fn_traits"
and"unstable"
crate features)FnOnce
(requires"fn_traits"
and"unstable"
crate features)Generator
(requires"generator_trait"
and"unstable"
crate features)
[std|core]::convert
[std|core]::fmt
Debug
(alias:fmt::Debug
) - generated codeDisplay
(alias:fmt::Display
)fmt::Binary
(requires"fmt"
crate feature)fmt::LowerExp
(requires"fmt"
crate feature)fmt::LowerHex
(requires"fmt"
crate feature)fmt::Octal
(requires"fmt"
crate feature)fmt::Pointer
(requires"fmt"
crate feature)fmt::UpperExp
(requires"fmt"
crate feature)fmt::UpperHex
(requires"fmt"
crate feature)fmt::Write
std::error
(requires "std"
crate feature)
External libraries
You can use support for external library traits by activating each crate feature.
To use support for external library traits, you need to use the path starting with the feature name. For example:
use auto_enums::auto_enum;
use rayon::prelude::*;
#[auto_enum(rayon::ParallelIterator)] // Note that this is not `#[auto_enum(ParallelIterator)]`
fn func(x: i32) -> impl ParallelIterator {
match x {
0 => (1..10).into_par_iter(),
_ => vec![5, 10].into_par_iter(),
}
}
futures v0.3 (requires "futures03"
or "futures"
crate feature)
futures03::Stream
- generated codefutures03::Sink
- generated codefutures03::AsyncRead
- generated codefutures03::AsyncWrite
- generated codefutures03::AsyncSeek
- generated codefutures03::AsyncBufRead
- generated code
See also futures-enum crate.
futures v0.1 (requires "futures01"
crate feature)
rayon (requires "rayon"
crate feature)
rayon::ParallelIterator
- generated coderayon::IndexedParallelIterator
- generated coderayon::ParallelExtend
- generated code
serde (requires "serde"
crate feature)
tokio v1 (requires "tokio1"
crate feature)
tokio v0.3 (requires "tokio03"
crate feature)
tokio v0.2 (requires "tokio02"
crate feature)
tokio v0.1 (requires "tokio01"
crate feature)
Inherent methods
These don’t derive traits, but derive inherent methods instead.
-
Transpose
(requires"transpose_methods"
crate feature) - this derives the following conversion methods.-
transpose
— convert fromenum<Option<T1>,..>
toOption<enum<T1,..>>
-
transpose
— convert fromenum<Result<T1, E1>,..>
toResult<enum<T1,..>, enum<E1,..>>
-
transpose_ok
— convert fromenum<Result<T1, E>,..>
toOption<enum<T1,..>, E>
Examples:
use auto_enums::auto_enum; use std::{fs, io, path::Path}; #[auto_enum(Transpose, Write)] fn output_stream(file: Option<&Path>) -> io::Result<impl io::Write> { match file { Some(f) => fs::File::create(f), None => Ok(io::stdout()), }.transpose_ok() }
-
transpose_err
— convert fromenum<Result<T, E1>,..>
toResult<T, enum<E1,..>>
-
Optional features
std
(enabled by default)- Enable to use
std
library’s traits.
- Enable to use
ops
- Enable to use
[std|core]::ops
’sDeref
,DerefMut
,Index
,IndexMut
, andRangeBounds
traits.
- Enable to use
convert
- Enable to use
[std|core]::convert
’sAsRef
andAsMut
traits.
- Enable to use
fmt
- Enable to use
[std|core]::fmt
’s traits other thanDebug
,Display
andWrite
.
- Enable to use
transpose_methods
- Enable to use
transpose*
methods.
- Enable to use
futures03
- Enable to use futures v0.3 traits.
futures01
- Enable to use futures v0.1 traits.
rayon
- Enable to use rayon traits.
serde
- Enable to use serde traits.
tokio1
- Enable to use tokio v1 traits.
tokio03
- Enable to use tokio v0.3 traits.
tokio02
- Enable to use tokio v0.2 traits.
tokio01
- Enable to use tokio v0.1 traits.
generator_trait
- Enable to use
[std|core]::ops::Generator
trait. - Note that this feature is unstable and may cause incompatible changes between patch versions.
- Enable to use
fn_traits
- Enable to use
[std|core]::ops
’sFn
,FnMut
, andFnOnce
traits. - Note that this feature is unstable and may cause incompatible changes between patch versions.
- Enable to use
trusted_len
- Enable to use
[std|core]::iter::TrustedLen
trait. - Note that this feature is unstable and may cause incompatible changes between patch versions.
- Enable to use
type_analysis
feature
Analyze return type of function and let
binding.
Note that this feature is still experimental.
Examples:
use auto_enums::auto_enum;
#[auto_enum] // there is no need to specify std library's traits
fn func1(x: i32) -> impl Iterator<Item = i32> {
match x {
0 => 1..10,
_ => vec![5, 10].into_iter(),
}
}
#[auto_enum]
fn func2(x: i32) {
// Unlike `feature(impl_trait_in_bindings)`, this works on stable compilers.
#[auto_enum]
let iter: impl Iterator<Item = i32> = match x {
0 => Some(0).into_iter(),
_ => 0..x,
};
}
Please be careful if you return another traits with the same name.
Known limitations
- There needs to explicitly specify the trait to be implemented (
type_analysis
crate feature reduces this limitation). - There needs to be marker macros for unsupported expressions.
Attribute Macros
An attribute macro for to allow multiple return types by automatically generated enum.
An attribute macro like a wrapper of #[derive]
, implementing
the supported traits and passing unsupported traits to #[derive]
.