impls-1.0.3/Cargo.toml.orig 0100644 0000765 0000024 00000001031 13602702455 0013744 0 ustar 00 0000000 0000000 [package]
name = "impls"
version = "1.0.3"
authors = ["Nikolai Vazquez", "Nadrieril Feneanar"]
license = "MIT OR Apache-2.0"
description = "Determine if a type implements a logical trait expression."
repository = "https://github.com/nvzqz/impls"
homepage = "https://github.com/nvzqz/impls"
documentation = "https://docs.rs/impls"
categories = ["no-std", "rust-patterns", "development-tools::testing"]
keywords = ["impl", "trait", "test", "macro"]
readme = "README.md"
include = ["Cargo.toml", "src", "README*", "CHANGELOG*", "LICENSE*"]
impls-1.0.3/Cargo.toml 0000644 00000002046 13602702504 0010256 0 ustar 00 # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
name = "impls"
version = "1.0.3"
authors = ["Nikolai Vazquez", "Nadrieril Feneanar"]
include = ["Cargo.toml", "src", "README*", "CHANGELOG*", "LICENSE*"]
description = "Determine if a type implements a logical trait expression."
homepage = "https://github.com/nvzqz/impls"
documentation = "https://docs.rs/impls"
readme = "README.md"
keywords = ["impl", "trait", "test", "macro"]
categories = ["no-std", "rust-patterns", "development-tools::testing"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/nvzqz/impls"
impls-1.0.3/LICENSE-APACHE 0100644 0000765 0000024 00000026136 13602270335 0013013 0 ustar 00 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
impls-1.0.3/LICENSE-MIT 0100644 0000765 0000024 00000002104 13602431014 0012501 0 ustar 00 0000000 0000000 MIT License
Copyright (c) 2019 Nikolai Vazquez, Nadrieril Feneanar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
impls-1.0.3/README.md 0100644 0000765 0000024 00000027470 13602702455 0012353 0 ustar 00 0000000 0000000
Determine if a type implements a logical trait
expression[**?**](#logical-trait-expression), brought to you by
[@NikolaiVazquez]!
This library defines [`impls!`], a macro[**?**](#macro) that returns
a [`bool`] indicating whether a type implements a boolean-like expression over a
set of traits[**?**](#trait).
```rust
assert!(impls!(String: Clone & !Copy & Send & Sync));
```
See ["Examples"](#examples) for detailed use cases and, if you're brave, see
["Trait-Dependent Type Sizes"](#trait-dependent-type-sizes) for some cursed
code.
## Index
- [Reasoning](#reasoning)
- [Usage](#usage)
- [Vocabulary](#vocabulary)
- [Macro](#macro)
- [Trait](#trait)
- [Logical Trait Expression](#logical-trait-expression)
- [Examples](#examples)
- [Constant Evaluation](#constant-evaluation)
- [Precedence and Nesting](#precedence-and-nesting)
- [Mutual Exclusion](#mutual-exclusion)
- [Reference Types](#reference-types)
- [Unsized Types](#unsized-types)
- [Generic Types](#generic-types)
- [Lifetimes](#lifetimes)
- [Trait-Dependent Type Sizes](#trait-dependent-type-sizes)
- [Authors](#authors)
- [License](#license)
## Reasoning
As a library author, it's important to ensure that your API remains stable.
Trait implementations are part of API stability. For example: if you
accidentally introduce an inner type that makes your publicly-exposed type no
longer be [`Send`] or [`Sync`], you've now broken your API without noticing it!
The most common case of this happening is adding a [raw pointer][ptr]
(i.e. `*const T`, `*mut T`) as a type field.
By checking situations like this with [`impls!`], either at [compile-time] or in
a unit test, you can ensure that no API-breaking changes are made without
noticing until it's too late.
## Usage
This crate is available [on crates.io][crate] and can be used by adding the
following to your project's [`Cargo.toml`]:
```toml
[dependencies]
impls = "1"
```
and this to your crate root (`main.rs` or `lib.rs`):
```rust
#[macro_use]
extern crate impls;
```
When using [Rust 2018 edition][2018], the following import can help if
having `#[macro_use]` is undesirable.
```rust
use impls::impls;
```
## Vocabulary
This documentation uses jargon that may be new to inexperienced Rust users.
This section exists to make these terms easier to understand. Feel free to
skip this section if these are already familiar to you.
### Macro
In Rust, macros are functions over the [abstract syntax tree (AST)][AST].
They map input tokens to output tokens by performing some operation over
them through a set of rules. Because of this, only their outputs are ever
type-checked.
If you wish to learn about implementing macros, I recommend:
- [The Little Book of Rust Macros](https://danielkeep.github.io/tlborm/book/index.html)
- ["Macros" - The Rust Programming Language](https://doc.rust-lang.org/book/ch19-06-macros.html)
- ["Macros" - The Rust Reference](https://doc.rust-lang.org/stable/reference/macros.html)
- ["Macros By Example" - The Rust Reference](https://doc.rust-lang.org/stable/reference/macros-by-example.html)
To use this crate, you do not need to know how macros are defined.
### Trait
In Rust, traits are a way of defining a generalized property. They should be
thought of expressing what a type is capable of doing. For example: if a
type implements [`Into`] for some type `T`, then we know it can be converted
into `T` by just calling the `.into()` method on it.
If you wish to learn about traits in detail, I recommend:
- ["Traits: Defining Shared Behavior" - The Rust Programming Language](https://doc.rust-lang.org/book/ch10-02-traits.html)
- ["Traits" - The Rust Reference](https://doc.rust-lang.org/stable/reference/items/traits.html)
### Logical Trait Expression
In this crate, traits should be thought of as [`bool`]s where the condition
is whether the given type implements the trait or not.
An expression can be formed from these trait operations:
- And (`&`): also known as [logical conjunction], this returns `true` if
**both** operands are `true`. This is usually defined in Rust via the
[`BitAnd`] trait.
- Or (`|`): also known as [logical disjunction], this returns `true` if
**either** of two operands is `true`. This is usually defined in Rust via
the [`BitOr`] trait.
- Exclusive-or (`^`): also known as [exclusive disjunction], this returns
`true` if **only one** of two operands is `true`. This is usually defined
in Rust via the [`BitXor`] trait.
- Not (`!`): a negation that returns `false` if the operand is `true`, or
`true` if the operand is `false`. This is usually defined in Rust via the
[`Not`] trait.
See ["Precedence and Nesting"](#precedence-and-nesting) for information
about the order in which these operations are performed.
## Examples
This macro works in every type context. See below for use cases.
### Constant Evaluation
Because types are [compile-time] constructs, the result of this macro can be
used as a `const` value:
```rust
const IMPLS: bool = impls!(u8: From);
```
Using [`static_assertions`], we can fail to compile if the trait expression
evaluates to `false`:
```rust
const_assert!(impls!(*const u8: Send | Sync));
```
### Precedence and Nesting
Trait operations abide by [Rust's expression precedence][precedence]. To
define a custom order of operations (e.g. left-to-right), simply nest the
expressions with parentheses.
```rust
let pre = impls!(u64: From | From ^ From & From);
let ltr = impls!(u64: ((From | From) ^ From) & From);
assert_eq!(pre, true | true ^ true & true);
assert_ne!(pre, ltr);
```
### Mutual Exclusion
Because exclusive-or (`^`) is a trait operation, we can check that a type
implements one of two traits, but not both:
```rust
struct T;
trait Foo {}
trait Bar {}
impl Foo for T {}
assert!(impls!(T: Foo ^ Bar));
```
### Reference Types
Something that's surprising to many Rust users is that [`&mut T`] _does not_
implement [`Copy`] _nor_ [`Clone`]:
```rust
assert!(impls!(&mut u32: !Copy & !Clone));
```
Surely you're thinking now that this macro must be broken, because you've
been able to reuse `&mut T` throughout your lifetime with Rust. This works
because, in certain contexts, the compiler silently adds "re-borrows"
(`&mut *ref`) with a shorter lifetime and shadows the original. In reality,
`&mut T` is a move-only type.
### Unsized Types
There's a variety of types in Rust that don't implement [`Sized`]:
```rust
// Slices store their size with their pointer.
assert!(impls!(str: !Sized));
assert!(impls!([u8]: !Sized));
// Trait objects store their size in a vtable.
trait Foo {}
assert!(impls!(dyn Foo: !Sized));
// Wrappers around unsized types are also unsized themselves.
struct Bar([u8]);
assert!(impls!(Bar: !Sized));
```
### Generic Types
When called from a generic function, the returned value is based on the
constraints of the generic type:
```rust
use std::cell::Cell;
struct Value {
// ...
}
impl Value {
fn do_stuff() {
assert!(impls!(Cell: Send));
// ...
}
}
```
Keep in mind that this can result in false negatives:
```rust
const fn is_copy() -> bool {
impls!(T: Copy)
}
assert_ne!(is_copy::(), impls!(u32: Copy));
```
[precedence]: https://doc.rust-lang.org/reference/expressions.html#expression-precedence
[`static_assertions`]: https://docs.rs/static_assertions
### Lifetimes
Traits with lifetimes are also supported:
```rust
trait Ref<'a> {}
impl<'a, T: ?Sized> Ref<'a> for &'a T {}
impl<'a, T: ?Sized> Ref<'a> for &'a mut T {}
assert!(impls!(&'static str: Ref<'static>));
assert!(impls!(&'static mut [u8]: Ref<'static>));
assert!(impls!(String: !Ref<'static>));
```
### Trait-Dependent Type Sizes
This macro enables something really cool (read cursed) that couldn't be done
before: making a type's size dependent on what traits it implements! Note that
this probably is a bad idea and shouldn't be used in production.
Here `Foo` becomes 32 bytes for no other reason than it implementing [`Clone`]:
```rust
const SIZE: usize = 32 * (impls!(Foo: Clone) as usize);
#[derive(Clone)]
struct Foo([u8; SIZE]);
assert_eq!(std::mem::size_of::(), 32);
```
The [`bool`] returned from [`impls!`] gets casted to a [`usize`], becoming 1 or
0 depending on if it's `true` or `false` respectively. If `true`, this becomes
32 × 1, which is 32. This then becomes the length of the byte array in `Foo`.
## Authors
- Nikolai Vazquez
(GitHub: [@nvzqz](https://github.com/nvzqz), Twitter: [@NikolaiVazquez])
Implemented the `impls!` macro with support for all logical operators and
without the limitations of the initial `does_impl!` macro by Nadrieril.
- Nadrieril Feneanar
(GitHub: [@Nadrieril](https://github.com/Nadrieril))
Implemented the initial `does_impl!` macro in
[nvzqz/static-assertions-rs#28](https://github.com/nvzqz/static-assertions-rs/pull/28)
upon which this crate was originally based.
## License
This project is released under either:
- [MIT License](https://github.com/nvzqz/impls/blob/master/LICENSE-MIT)
- [Apache License (Version 2.0)](https://github.com/nvzqz/impls/blob/master/LICENSE-APACHE)
at your choosing.
[@NikolaiVazquez]: https://twitter.com/NikolaiVazquez
[compile-time]: https://en.wikipedia.org/wiki/Compile_time
[`&mut T`]: https://doc.rust-lang.org/std/primitive.reference.html
[`bool`]: https://doc.rust-lang.org/std/primitive.bool.html
[`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html
[`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
[`Sized`]: https://doc.rust-lang.org/std/marker/trait.Sized.html
[`usize`]: https://doc.rust-lang.org/std/primitive.usize.html
[`Cargo.toml`]: https://doc.rust-lang.org/cargo/reference/manifest.html
[`impls!`]: https://docs.rs/impls/1.0.3/impls/macro.impls.html
[2018]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html#rust-2018
[crate]: https://crates.io/crates/impls
[`BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
[`BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
[`BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html
[`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
[`Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html
[`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html
[`Sync`]: https://doc.rust-lang.org/std/marker/trait.Send.html
[ptr]: https://doc.rust-lang.org/std/primitive.pointer.html
[AST]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
[exclusive disjunction]: https://en.wikipedia.org/wiki/Exclusive_disjunction
[logical conjunction]: https://en.wikipedia.org/wiki/Logical_conjunction
[logical disjunction]: https://en.wikipedia.org/wiki/Logical_disjunction
impls-1.0.3/src/lib.rs 0100644 0000765 0000024 00000061167 13602702455 0013000 0 ustar 00 0000000 0000000 //!
//!
//!
//! Determine if a type implements a logical trait
//! expression[**?**](#logical-trait-expression), brought to you by
//! [@NikolaiVazquez]!
//!
//! This library defines [`impls!`], a macro[**?**](#macro) that
//! returns a [`bool`] indicating whether a type implements a boolean-like
//! expression over a set of traits[**?**](#trait).
//!
//! ```
//! # #[macro_use] extern crate impls;
//! assert!(impls!(String: Clone & !Copy & Send & Sync));
//! ```
//!
//! See ["Examples"](#examples) for detailed use cases and, if you're brave, see
//! ["Trait-Dependent Type Sizes"](#trait-dependent-type-sizes) for some cursed
//! code.
//!
//! # Index
//!
//! - [Reasoning](#reasoning)
//! - [Usage](#usage)
//! - [Vocabulary](#vocabulary)
//! - [Macro](#macro)
//! - [Trait](#trait)
//! - [Logical Trait Expression](#logical-trait-expression)
//! - [Examples](#examples)
//! - [Constant Evaluation](#constant-evaluation)
//! - [Precedence and Nesting](#precedence-and-nesting)
//! - [Mutual Exclusion](#mutual-exclusion)
//! - [Reference Types](#reference-types)
//! - [Unsized Types](#unsized-types)
//! - [Generic Types](#generic-types)
//! - [Lifetimes](#lifetimes)
//! - [Trait-Dependent Type Sizes](#trait-dependent-type-sizes)
//! - [Authors](#authors)
//! - [License](#license)
//!
//! # Reasoning
//!
//! As a library author, it's important to ensure that your API remains stable.
//! Trait implementations are part of API stability. For example: if you
//! accidentally introduce an inner type that makes your publicly-exposed type
//! no longer be [`Send`] or [`Sync`], you've now broken your API without
//! noticing it! The most common case of this happening is adding a [raw
//! pointer][ptr] (i.e. `*const T`, `*mut T`) as a type field.
//!
//! By checking situations like this with [`impls!`], either at [compile-time]
//! or in a unit test, you can ensure that no API-breaking changes are made
//! without noticing until it's too late.
//!
//! # Usage
//!
//! This crate is available [on crates.io][crate] and can be used by adding the
//! following to your project's [`Cargo.toml`]:
//!
//! ```toml
//! [dependencies]
//! impls = "1"
//! ```
//!
//! and this to your crate root (`main.rs` or `lib.rs`):
//!
//! ```
//! # #[allow(unused_imports)]
//! #[macro_use]
//! extern crate impls;
//! # fn main() {}
//! ```
//!
//! When using [Rust 2018 edition][2018], the following import can help if
//! having `#[macro_use]` is undesirable.
//!
//! ```edition2018
//! use impls::impls;
//! ```
//!
//! # Vocabulary
//!
//! This documentation uses jargon that may be new to inexperienced Rust users.
//! This section exists to make these terms easier to understand. Feel free to
//! skip this section if these are already familiar to you.
//!
//! ## Macro
//!
//! In Rust, macros are functions over the [abstract syntax tree (AST)][AST].
//! They map input tokens to output tokens by performing some operation over
//! them through a set of rules. Because of this, only their outputs are ever
//! type-checked.
//!
//! If you wish to learn about implementing macros, I recommend:
//! - [The Little Book of Rust Macros](https://danielkeep.github.io/tlborm/book/index.html)
//! - ["Macros" - The Rust Programming Language](https://doc.rust-lang.org/book/ch19-06-macros.html)
//! - ["Macros" - The Rust Reference](https://doc.rust-lang.org/stable/reference/macros.html)
//! - ["Macros By Example" - The Rust Reference](https://doc.rust-lang.org/stable/reference/macros-by-example.html)
//!
//! To use this crate, you do not need to know how macros are defined.
//!
//! ## Trait
//!
//! In Rust, traits are a way of defining a generalized property. They should be
//! thought of expressing what a type is capable of doing. For example: if a
//! type implements [`Into`] for some type `T`, then we know it can be converted
//! into `T` by just calling the `.into()` method on it.
//!
//! If you wish to learn about traits in detail, I recommend:
//! - ["Traits: Defining Shared Behavior" - The Rust Programming Language](https://doc.rust-lang.org/book/ch10-02-traits.html)
//! - ["Traits" - The Rust Reference](https://doc.rust-lang.org/stable/reference/items/traits.html)
//!
//! ## Logical Trait Expression
//!
//! In this crate, traits should be thought of as [`bool`]s where the condition
//! is whether the given type implements the trait or not.
//!
//! An expression can be formed from these trait operations:
//!
//! - And (`&`): also known as [logical conjunction], this returns `true` if
//! **both** operands are `true`. This is usually defined in Rust via the
//! [`BitAnd`] trait.
//!
//! - Or (`|`): also known as [logical disjunction], this returns `true` if
//! **either** of two operands is `true`. This is usually defined in Rust via
//! the [`BitOr`] trait.
//!
//! - Exclusive-or (`^`): also known as [exclusive disjunction], this returns
//! `true` if **only one** of two operands is `true`. This is usually defined
//! in Rust via the [`BitXor`] trait.
//!
//! - Not (`!`): a negation that returns `false` if the operand is `true`, or
//! `true` if the operand is `false`. This is usually defined in Rust via the
//! [`Not`] trait.
//!
//! See ["Precedence and Nesting"](#precedence-and-nesting) for information
//! about the order in which these operations are performed.
//!
// IMPORTANT: These examples are copy and pasted directly from `impls!`
//! # Examples
//!
//! This macro works in every type context. See below for use cases.
//!
//! ## Constant Evaluation
//!
//! Because types are [compile-time] constructs, the result of this macro can be
//! used as a `const` value:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! const IMPLS: bool = impls!(u8: From);
//! ```
//!
//! Using [`static_assertions`], we can fail to compile if the trait expression
//! evaluates to `false`:
//!
//! ```compile_fail
//! # #[macro_use] extern crate impls;
//! # macro_rules! const_assert {
//! # ($x:expr) => { let _: [(); 1] = [(); $x as usize]; }
//! # }
//! const_assert!(impls!(*const u8: Send | Sync));
//! ```
//!
//! ## Precedence and Nesting
//!
//! Trait operations abide by [Rust's expression precedence][precedence]. To
//! define a custom order of operations (e.g. left-to-right), simply nest the
//! expressions with parentheses.
//!
//! ```
//! # #[macro_use] extern crate impls;
//! let pre = impls!(u64: From | From ^ From & From);
//! let ltr = impls!(u64: ((From | From) ^ From) & From);
//!
//! assert_eq!(pre, true | true ^ true & true);
//! assert_ne!(pre, ltr);
//! ```
//!
//! ## Mutual Exclusion
//!
//! Because exclusive-or (`^`) is a trait operation, we can check that a type
//! implements one of two traits, but not both:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! struct T;
//!
//! trait Foo {}
//! trait Bar {}
//!
//! impl Foo for T {}
//!
//! assert!(impls!(T: Foo ^ Bar));
//! ```
//!
//! ## Reference Types
//!
//! Something that's surprising to many Rust users is that [`&mut T`] _does not_
//! implement [`Copy`] _nor_ [`Clone`]:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! assert!(impls!(&mut u32: !Copy & !Clone));
//! ```
//!
//! Surely you're thinking now that this macro must be broken, because you've
//! been able to reuse `&mut T` throughout your lifetime with Rust. This works
//! because, in certain contexts, the compiler silently adds "re-borrows"
//! (`&mut *ref`) with a shorter lifetime and shadows the original. In reality,
//! `&mut T` is a move-only type.
//!
//! ## Unsized Types
//!
//! There's a variety of types in Rust that don't implement [`Sized`]:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! // Slices store their size with their pointer.
//! assert!(impls!(str: !Sized));
//! assert!(impls!([u8]: !Sized));
//!
//! // Trait objects store their size in a vtable.
//! trait Foo {}
//! assert!(impls!(dyn Foo: !Sized));
//!
//! // Wrappers around unsized types are also unsized themselves.
//! struct Bar([u8]);
//! assert!(impls!(Bar: !Sized));
//! ```
//!
//! ## Generic Types
//!
//! When called from a generic function, the returned value is based on the
//! constraints of the generic type:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! use std::cell::Cell;
//!
//! struct Value {
//! // ...
//! # value: T
//! }
//!
//! impl Value {
//! fn do_stuff() {
//! assert!(impls!(Cell: Send));
//! // ...
//! }
//! }
//! ```
//!
//! Keep in mind that this can result in false negatives:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! const fn is_copy() -> bool {
//! impls!(T: Copy)
//! }
//!
//! assert_ne!(is_copy::(), impls!(u32: Copy));
//! ```
//!
//! [precedence]: https://doc.rust-lang.org/reference/expressions.html#expression-precedence
//! [`static_assertions`]: https://docs.rs/static_assertions
//!
//! ## Lifetimes
//!
//! Traits with lifetimes are also supported:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! trait Ref<'a> {}
//! impl<'a, T: ?Sized> Ref<'a> for &'a T {}
//! impl<'a, T: ?Sized> Ref<'a> for &'a mut T {}
//!
//! assert!(impls!(&'static str: Ref<'static>));
//! assert!(impls!(&'static mut [u8]: Ref<'static>));
//! assert!(impls!(String: !Ref<'static>));
//! ```
//!
//! ## Trait-Dependent Type Sizes
//!
//! This macro enables something really cool (read cursed) that couldn't be done
//! before: making a type's size dependent on what traits it implements! Note
//! that this probably is a bad idea and shouldn't be used in production.
//!
//! Here `Foo` becomes 32 bytes for no other reason than it implementing
//! [`Clone`]:
//!
//! ```
//! # #[macro_use] extern crate impls;
//! const SIZE: usize = 32 * (impls!(Foo: Clone) as usize);
//!
//! #[derive(Clone)]
//! struct Foo([u8; SIZE]);
//!
//! assert_eq!(std::mem::size_of::(), 32);
//! ```
//!
//! The [`bool`] returned from [`impls!`] gets casted to a [`usize`], becoming 1
//! or 0 depending on if it's `true` or `false` respectively. If `true`, this
//! becomes 32 × 1, which is 32. This then becomes the length of the byte array
//! in `Foo`.
//!
//! # Authors
//!
//! - Nikolai Vazquez
//! (GitHub: [@nvzqz](https://github.com/nvzqz), Twitter: [@NikolaiVazquez])
//!
//! Implemented the `impls!` macro with support for all logical operators and
//! without the limitations of the initial `does_impl!` macro by Nadrieril.
//!
//! - Nadrieril Feneanar
//! (GitHub: [@Nadrieril](https://github.com/Nadrieril))
//!
//! Implemented the initial `does_impl!` macro in
//! [nvzqz/static-assertions-rs#28](https://github.com/nvzqz/static-assertions-rs/pull/28)
//! upon which this crate was originally based.
//!
//! # License
//!
//! This project is released under either:
//!
//! - [MIT License](https://github.com/nvzqz/impls/blob/master/LICENSE-MIT)
//! - [Apache License (Version 2.0)](https://github.com/nvzqz/impls/blob/master/LICENSE-APACHE)
//!
//! at your choosing.
//!
//! [@NikolaiVazquez]: https://twitter.com/NikolaiVazquez
//!
//! [compile-time]: https://en.wikipedia.org/wiki/Compile_time
//!
//! [`&mut T`]: https://doc.rust-lang.org/std/primitive.reference.html
//! [`bool`]: https://doc.rust-lang.org/std/primitive.bool.html
//! [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html
//! [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
//! [`Sized`]: https://doc.rust-lang.org/std/marker/trait.Sized.html
//! [`usize`]: https://doc.rust-lang.org/std/primitive.usize.html
//!
//! [`Cargo.toml`]: https://doc.rust-lang.org/cargo/reference/manifest.html
//! [`impls!`]: macro.impls.html
//! [2018]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html#rust-2018
//! [crate]: https://crates.io/crates/impls
//!
//! [`BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
//! [`BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
//! [`BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html
//! [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
//! [`Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html
//! [`Send`]: https://doc.rust-lang.org/std/marker/trait.Send.html
//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Send.html
//! [ptr]: https://doc.rust-lang.org/std/primitive.pointer.html
//!
//! [AST]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
//! [exclusive disjunction]: https://en.wikipedia.org/wiki/Exclusive_disjunction
//! [logical conjunction]: https://en.wikipedia.org/wiki/Logical_conjunction
//! [logical disjunction]: https://en.wikipedia.org/wiki/Logical_disjunction
#![deny(missing_docs)]
#![doc(
html_root_url = "https://docs.rs/impls/1.0.3",
html_logo_url = "https://raw.githubusercontent.com/nvzqz/impls/assets/logo.svg?sanitize=true"
)]
// Allocating types like `String` are used when testing.
#![cfg_attr(not(test), no_std)]
#[doc(hidden)]
pub extern crate core as _core;
/// Returns `true` if a type implements a logical trait expression.
///
// IMPORTANT: Update crate level docs when updating these examples!
/// # Examples
///
/// This macro works in every type context. See below for use cases.
///
/// ## Constant Evaluation
///
/// Because types are [compile-time] constructs, the result of this macro can be
/// used as a `const` value:
///
/// ```
/// # #[macro_use] extern crate impls;
/// const IMPLS: bool = impls!(u8: From);
/// ```
///
/// Using [`static_assertions`], we can fail to compile if the trait expression
/// evaluates to `false`:
///
/// ```compile_fail
/// # #[macro_use] extern crate impls;
/// # macro_rules! const_assert {
/// # ($x:expr) => { let _: [(); 1] = [(); $x as usize]; }
/// # }
/// const_assert!(impls!(*const u8: Send | Sync));
/// ```
///
/// ## Precedence and Nesting
///
/// Trait operations abide by [Rust's expression precedence][precedence]. To
/// define a custom order of operations (e.g. left-to-right), simply nest the
/// expressions with parentheses.
///
/// ```
/// # #[macro_use] extern crate impls;
/// let pre = impls!(u64: From | From ^ From & From);
/// let ltr = impls!(u64: ((From | From) ^ From) & From);
///
/// assert_eq!(pre, true | true ^ true & true);
/// assert_ne!(pre, ltr);
/// ```
///
/// ## Mutual Exclusion
///
/// Because exclusive-or (`^`) is a trait operation, we can check that a type
/// implements one of two traits, but not both:
///
/// ```
/// # #[macro_use] extern crate impls;
/// struct T;
///
/// trait Foo {}
/// trait Bar {}
///
/// impl Foo for T {}
///
/// assert!(impls!(T: Foo ^ Bar));
/// ```
///
/// ## Reference Types
///
/// Something that's surprising to many Rust users is that [`&mut T`] _does not_
/// implement [`Copy`] _nor_ [`Clone`]:
///
/// ```
/// # #[macro_use] extern crate impls;
/// assert!(impls!(&mut u32: !Copy & !Clone));
/// ```
///
/// Surely you're thinking now that this macro must be broken, because you've
/// been able to reuse `&mut T` throughout your lifetime with Rust. This works
/// because, in certain contexts, the compiler silently adds "re-borrows"
/// (`&mut *ref`) with a shorter lifetime and shadows the original. In reality,
/// `&mut T` is a move-only type.
///
/// ## Unsized Types
///
/// There's a variety of types in Rust that don't implement [`Sized`]:
///
/// ```
/// # #[macro_use] extern crate impls;
/// // Slices store their size with their pointer.
/// assert!(impls!(str: !Sized));
/// assert!(impls!([u8]: !Sized));
///
/// // Trait objects store their size in a vtable.
/// trait Foo {}
/// assert!(impls!(dyn Foo: !Sized));
///
/// // Wrappers around unsized types are also unsized themselves.
/// struct Bar([u8]);
/// assert!(impls!(Bar: !Sized));
/// ```
///
/// ## Generic Types
///
/// When called from a generic function, the returned value is based on the
/// constraints of the generic type:
///
/// ```
/// # #[macro_use] extern crate impls;
/// use std::cell::Cell;
///
/// struct Value {
/// // ...
/// # value: T
/// }
///
/// impl Value {
/// fn do_stuff() {
/// assert!(impls!(Cell: Send));
/// // ...
/// }
/// }
/// ```
///
/// Keep in mind that this can result in false negatives:
///
/// ```
/// # #[macro_use] extern crate impls;
/// const fn is_copy() -> bool {
/// impls!(T: Copy)
/// }
///
/// assert_ne!(is_copy::(), impls!(u32: Copy));
/// ```
///
/// [precedence]: https://doc.rust-lang.org/reference/expressions.html#expression-precedence
/// [`static_assertions`]: https://docs.rs/static_assertions
///
/// ## Lifetimes
///
/// Traits with lifetimes are also supported:
///
/// ```
/// # #[macro_use] extern crate impls;
/// trait Ref<'a> {}
/// impl<'a, T: ?Sized> Ref<'a> for &'a T {}
/// impl<'a, T: ?Sized> Ref<'a> for &'a mut T {}
///
/// assert!(impls!(&'static str: Ref<'static>));
/// assert!(impls!(&'static mut [u8]: Ref<'static>));
/// assert!(impls!(String: !Ref<'static>));
/// ```
///
/// ## Trait-Dependent Type Sizes
///
/// This macro enables something really cool (read cursed) that couldn't be done
/// before: making a type's size dependent on what traits it implements! Note
/// that this probably is a bad idea and shouldn't be used in production.
///
/// Here `Foo` becomes 32 bytes for no other reason than it implementing
/// [`Clone`]:
///
/// ```
/// # #[macro_use] extern crate impls;
/// const SIZE: usize = 32 * (impls!(Foo: Clone) as usize);
///
/// #[derive(Clone)]
/// struct Foo([u8; SIZE]);
///
/// assert_eq!(std::mem::size_of::(), 32);
/// ```
///
/// The [`bool`] returned from `impls!` gets casted to a [`usize`], becoming 1
/// or 0 depending on if it's `true` or `false` respectively. If `true`, this
/// becomes 32 × 1, which is 32. This then becomes the length of the byte array
/// in `Foo`.
///
/// [compile-time]: https://en.wikipedia.org/wiki/Compile_time
///
/// [`&mut T`]: https://doc.rust-lang.org/std/primitive.reference.html
/// [`bool`]: https://doc.rust-lang.org/std/primitive.bool.html
/// [`Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html
/// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
/// [`Sized`]: https://doc.rust-lang.org/std/marker/trait.Sized.html
/// [`usize`]: https://doc.rust-lang.org/std/primitive.usize.html
#[macro_export(local_inner_macros)]
macro_rules! impls {
($type:ty: $($trait_expr:tt)+) => {
_impls!($type: $($trait_expr)+)
};
}
/// Handles the dirty work of `impls`.
#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! _impls {
// ONE: Turn `$trait` into `true` or `false` based on whether `$type`
// implements it.
($type:ty: $(! !)* $trait:path) => {{
// Do not import types in order to prevent trait name collisions.
/// Fallback trait with `False` for `IMPLS` if the type does not
/// implement the given trait.
trait DoesNotImpl {
const IMPLS: bool = false;
}
impl DoesNotImpl for T {}
/// Concrete type with `True` for `IMPLS` if the type implements the
/// given trait. Otherwise, it falls back to `DoesNotImpl`.
struct Wrapper($crate::_core::marker::PhantomData);
#[allow(dead_code)]
impl Wrapper {
const IMPLS: bool = true;
}
>::IMPLS
}};
// NOT
($type:ty: $(! !)* !$trait:path) => {
!_impls!($type: $trait)
};
// PAREN
($type:ty: $(! !)* ($($trait_expr:tt)+)) => {
_impls!($type: $($trait_expr)+)
};
// PAREN+NOT
($type:ty: $(! !)* !($($trait_expr:tt)+)) => {
!_impls!($type: $($trait_expr)+)
};
// PAREN+OR
($type:ty: $(! !)* ($($t1:tt)+) | $($t2:tt)+) => {
_impls!($type: $($t1)+)
|
_impls!($type: $($t2)+)
};
// PAREN+OR+NOT
($type:ty: $(! !)* !($($t1:tt)+) | $($t2:tt)+) => {
!_impls!($type: $($t1)+)
|
_impls!($type: $($t2)+)
};
// PAREN+AND
($type:ty: $(! !)* ($($t1:tt)+) & $($t2:tt)+) => {
_impls!($type: $($t1)+)
&
_impls!($type: $($t2)+)
};
// PAREN+AND+NOT
($type:ty: $(! !)* !($($t1:tt)+) & $($t2:tt)+) => {
!_impls!($type: $($t1)+)
&
_impls!($type: $($t2)+)
};
// PAREN+XOR
($type:ty: $(! !)* ($($t1:tt)+) ^ $($t2:tt)+) => {
_impls!($type: $($t1)+)
^
_impls!($type: $($t2)+)
};
// PAREN+XOR+NOT
($type:ty: $(! !)* !($($t1:tt)+) ^ $($t2:tt)+) => {
!_impls!($type: $($t1)+)
^
_impls!($type: $($t2)+)
};
// OR: Any.
($type:ty: $(! !)* $t1:path | $($t2:tt)+) => {{
_impls!($type: $t1)
|
_impls!($type: $($t2)+)
}};
// OR+NOT: Any.
($type:ty: $(! !)* !$t1:path | $($t2:tt)+) => {{
!_impls!($type: $t1)
|
_impls!($type: $($t2)+)
}};
// AND: 0 lifetimes, 0 generics.
($type:ty: $(! !)* $t1:ident & $($t2:tt)+) => {{
_impls!($type: $t1)
&
_impls!($type: $($t2)+)
}};
// AND+NOT: 0 lifetimes, 0 generics.
($type:ty: $(! !)* !$t1:ident & $($t2:tt)+) => {{
!_impls!($type: $t1)
&
_impls!($type: $($t2)+)
}};
// AND: 1+ lifetimes, 0+ generics.
(
$type:ty: $(! !)*
$t1:ident < $($t1_lifetime:lifetime),+ $(, $t1_generic:ty)* $(,)? >
&
$($t2:tt)+
) => {{
_impls!($type: $t1 < $($t1_lifetime),+ $(, $t1_generic)* >)
&
_impls!($type: $($t2)+)
}};
// AND+NOT: 1+ lifetimes, 0+ generics.
(
$type:ty: $(! !)*
!$t1:ident < $($t1_lifetime:lifetime),+ $(, $t1_generic:ty)* $(,)? >
&
$($t2:tt)+
) => {{
!_impls!($type: $t1 < $($t1_lifetime),+ $(, $t1_generic)* >)
&
_impls!($type: $($t2)+)
}};
// AND: 0 lifetimes, 1+ generics.
(
$type:ty: $(! !)*
$t1:ident < $($t1_generic:ty),+ $(,)? >
&
$($t2:tt)+
) => {{
_impls!($type: $t1 < $($t1_generic),+ >)
&
_impls!($type: $($t2)+)
}};
// AND+NOT: 0 lifetimes, 1+ generics.
(
$type:ty: $(! !)*
!$t1:ident < $($t1_generic:ty),+ $(,)? >
&
$($t2:tt)+
) => {{
!_impls!($type: $t1 < $($t1_generic),+ >)
&
_impls!($type: $($t2)+)
}};
// XOR: 0 lifetimes, 0 generics.
($type:ty: $(! !)* $t1:ident ^ $($t2:tt)+) => {{
_impls!($type: $t1)
^
_impls!($type: $($t2)+)
}};
// XOR+NOT: 0 lifetimes, 0 generics.
($type:ty: $(! !)* !$t1:ident ^ $($t2:tt)+) => {{
! _impls!($type: $t1)
^
_impls!($type: $($t2)+)
}};
// XOR: 1+ lifetimes, 0+ generics.
(
$type:ty: $(! !)*
$t1:ident < $($t1_lifetime:lifetime),+ $(, $t1_generic:ty)* $(,)? >
^
$($t2:tt)+
) => {{
_impls!($type: $t1 < $($t1_lifetime),+ $(, $t1_generic)* >)
^
_impls!($type: $($t2)+)
}};
// XOR+NOT: 1+ lifetimes, 0+ generics.
(
$type:ty: $(! !)*
! $t1:ident < $($t1_lifetime:lifetime),+ $(, $t1_generic:ty)* $(,)? >
^
$($t2:tt)+
) => {{
!_impls!($type: $t1 < $($t1_lifetime),+ $(, $t1_generic)* >)
^
_impls!($type: $($t2)+)
}};
// XOR: 0 lifetimes, 1+ generics.
(
$type:ty: $(! !)*
$t1:ident < $($t1_generic:ty),+ $(,)? >
^
$($t2:tt)+
) => {{
_impls!($type: $t1 < $($t1_generic),+ >)
^
_impls!($type: $($t2)+)
}};
// XOR+NOT: 0 lifetimes, 1+ generics.
(
$type:ty: $(! !)*
! $t1:ident < $($t1_generic:ty),+ $(,)? >
^
$($t2:tt)+
) => {{
! _impls!($type: $t1 < $($t1_generic),+ >)
^
_impls!($type: $($t2)+)
}};
}
// Declare after macros in order to be able to use them.
#[cfg(test)]
mod tests;
impls-1.0.3/src/tests/bool.rs 0100644 0000765 0000024 00000000267 13602564703 0014323 0 ustar 00 0000000 0000000 pub struct True;
pub struct False;
impl True {
pub const fn value(self) -> bool {
true
}
}
impl False {
pub const fn value(self) -> bool {
false
}
}
impls-1.0.3/src/tests/mod.rs 0100644 0000765 0000024 00000005173 13602564703 0014150 0 ustar 00 0000000 0000000 #![allow(dead_code)]
mod bool;
#[derive(Clone)]
struct Test;
#[derive(Clone)]
struct Box(T);
trait True {}
impl True for T {}
trait False {}
// Tests that `impls!` follows Rust's rules of precedence.
//
// Rust's rules of precedence are defined at:
// https://doc.rust-lang.org/reference/expressions.html#expression-precedence
#[test]
fn precedence() {
macro_rules! table {
($($a:ident, $b:ident, $c:ident, $d:ident;)+) => { $({
const IMPLS: bool = bool::$a.value() | bool::$b.value() ^ bool::$c.value() & bool::$d.value();
assert_eq!(impls!(Test: $a | $b ^ $c & $d), IMPLS);
assert_eq!(impls!(Test: $a | ($b ^ ($c & $d))), IMPLS);
assert_ne!(impls!(Test: (($a | $b) ^ $c) & $d), IMPLS);
})+ };
}
// Table of cases where left-to-right parsing differs from precedence rules.
//
// https://play.rust-lang.org/?gist=7cbed02c68422f9464d0df79d39e99b0
#[rustfmt::skip]
table! {
False, True, False, False;
False, True, True, False;
True, False, False, False;
True, False, True, False;
True, False, True, True;
True, True, False, False;
True, True, True, False;
True, True, True, True;
}
}
#[test]
fn impls() {
let mut errors = String::new();
macro_rules! assert_impl {
($t:ty: $($trait_expr:tt)+) => {
if !impls!($t: $($trait_expr)+) {
errors.push_str(&format!(
"[{file}:{line}] {ty}: {expr}\n",
file = file!(),
line = line!(),
ty = stringify!($t),
expr = stringify!($($trait_expr)+)
));
}
};
}
assert_impl!(u8: (From) | (Into));
assert_impl!((): (From) | (From) | Send);
assert_impl!((): (!From) & !(From) & Send);
assert_impl!((): Copy | Clone);
assert_impl!((): Copy & Clone);
assert_impl!((): !(Copy ^ Clone));
assert_impl!(Test: Copy | Clone);
assert_impl!(Test: !Copy | Clone);
assert_impl!(Test: !Copy & Clone);
assert_impl!(Test: !Copy & (Clone));
assert_impl!(Test: !(Copy) & Clone);
assert_impl!(Test: !(!Clone));
assert_impl!(Test: !(Copy) & !(!Clone));
assert_impl!(Test: !(Copy & Clone));
assert_impl!(str: !Copy & !Clone);
assert_impl!(Box: Clone);
assert_impl!(Box: Clone & Send);
assert_impl!(Box: !(From | Into));
assert_impl!(&mut u8: !Copy);
if !errors.is_empty() {
panic!("Failed to satisfy implementations:\n{}", errors);
}
}
impls-1.0.3/.cargo_vcs_info.json 0000644 00000000112 13602702504 0012250 0 ustar 00 {
"git": {
"sha1": "a8f3599bd2f560f66dbe21047f33937420b67090"
}
}