remain-0.2.6/.cargo_vcs_info.json0000644000000001360000000000100123140ustar { "git": { "sha1": "e679d6ab013ecace37d58b6190de646143e3e611" }, "path_in_vcs": "" }remain-0.2.6/.clippy.toml000064400000000000000000000000201046102023000133470ustar 00000000000000msrv = "1.31.0" remain-0.2.6/.github/FUNDING.yml000064400000000000000000000000201046102023000142510ustar 00000000000000github: dtolnay remain-0.2.6/.github/workflows/ci.yml000064400000000000000000000033431046102023000156220ustar 00000000000000name: CI on: push: pull_request: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: nightly: name: Rust nightly runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@nightly - run: cargo test test: name: Rust ${{matrix.rust}} runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [beta, stable, 1.56.0] timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - run: cargo test env: RUSTFLAGS: --cfg remain_stable_testing ${{env.RUSTFLAGS}} msrv: name: Rust 1.31.0 runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@1.31.0 - run: cargo check clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic miri: name: Miri runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@miri - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 remain-0.2.6/.gitignore000064400000000000000000000000361046102023000130730ustar 00000000000000/target **/*.rs.bk Cargo.lock remain-0.2.6/Cargo.toml0000644000000023530000000000100103150ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.31" name = "remain" version = "0.2.6" authors = ["David Tolnay "] description = "Compile-time checks that an enum, struct, or match is written in sorted order." documentation = "https://docs.rs/remain" readme = "README.md" categories = [ "development-tools", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/remain" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0" features = [ "full", "visit-mut", ] [dev-dependencies.rustversion] version = "1.0" [dev-dependencies.trybuild] version = "1.0.49" features = ["diff"] remain-0.2.6/Cargo.toml.orig000064400000000000000000000012571046102023000140000ustar 00000000000000[package] name = "remain" version = "0.2.6" authors = ["David Tolnay "] categories = ["development-tools", "no-std"] description = "Compile-time checks that an enum, struct, or match is written in sorted order." documentation = "https://docs.rs/remain" edition = "2018" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/remain" rust-version = "1.31" [lib] proc-macro = true [dependencies] proc-macro2 = "1.0" quote = "1.0" syn = { version = "1.0", features = ["full", "visit-mut"] } [dev-dependencies] rustversion = "1.0" trybuild = { version = "1.0.49", features = ["diff"] } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] remain-0.2.6/LICENSE-APACHE000064400000000000000000000251371046102023000130400ustar 00000000000000 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. remain-0.2.6/LICENSE-MIT000064400000000000000000000017771046102023000125540ustar 00000000000000Permission 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. remain-0.2.6/README.md000064400000000000000000000102741046102023000123670ustar 00000000000000Remain sorted ============= [github](https://github.com/dtolnay/remain) [crates.io](https://crates.io/crates/remain) [docs.rs](https://docs.rs/remain) [build status](https://github.com/dtolnay/remain/actions?query=branch%3Amaster) This crate provides an attribute macro to check at compile time that the variants of an enum or the arms of a match expression are written in sorted order. ```toml [dependencies] remain = "0.2" ``` ## Syntax Place a `#[remain::sorted]` attribute on enums, structs, match-expressions, or let-statements whose value is a match-expression. Alternatively, import as `use remain::sorted;` and use `#[sorted]` as the attribute. ```rust #[remain::sorted] #[derive(Debug)] pub enum Error { BlockSignal(signal::Error), CreateCrasClient(libcras::Error), CreateEventFd(sys_util::Error), CreateSignalFd(sys_util::SignalFdError), CreateSocket(io::Error), DetectImageType(qcow::Error), DeviceJail(io_jail::Error), NetDeviceNew(virtio::NetError), SpawnVcpu(io::Error), } #[remain::sorted] #[derive(Debug)] pub struct Registers { ax: u16, cx: u16, di: u16, si: u16, sp: u16, } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; #[remain::sorted] match self { BlockSignal(e) => write!(f, "failed to block signal: {}", e), CreateCrasClient(e) => write!(f, "failed to create cras client: {}", e), CreateEventFd(e) => write!(f, "failed to create eventfd: {}", e), CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e), CreateSocket(e) => write!(f, "failed to create socket: {}", e), DetectImageType(e) => write!(f, "failed to detect disk image type: {}", e), DeviceJail(e) => write!(f, "failed to jail device: {}", e), NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {}", e), SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {}", e), } } } ``` If an enum variant, struct field, or match arm is inserted out of order, ```diff NetDeviceNew(virtio::NetError), SpawnVcpu(io::Error), + AaaUhOh(Box), } ``` then the macro produces a compile error. ```console error: AaaUhOh should sort before BlockSignal --> tests/stable.rs:49:5 | 49 | AaaUhOh(Box), | ^^^^^^^ ``` ## Compiler support The attribute on enums and structs is supported on any rustc version 1.31+. Rust does not yet have stable support for user-defined attributes within a function body, so the attribute on match-expressions and let-statements requires a nightly compiler and the following two features enabled: ```rust #![feature(proc_macro_hygiene, stmt_expr_attributes)] ``` As a stable alternative, this crate provides a function-level attribute called `#[remain::check]` which makes match-expression and let-statement attributes work on any rustc version 1.31+. Place this attribute on any function containing `#[sorted]` to make them work on a stable compiler. ```rust impl Display for Error { #[remain::check] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; #[sorted] match self { /* ... */ } } } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. remain-0.2.6/src/atom.rs000064400000000000000000000072441046102023000132100ustar 00000000000000use std::cmp::{Ord, Ordering, PartialOrd}; use std::str; #[derive(Copy, Clone, Eq, PartialEq)] pub enum Atom<'a> { /// A sequence of underscores. Underscore(usize), /// A sequence of digits. Number(&'a str), /// A sequence of characters. Chars(&'a str), } impl Atom<'_> { pub fn underscores(&self) -> usize { match *self { Atom::Underscore(n) => n, _ => 0, } } } impl PartialOrd for Atom<'_> { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Atom<'_> { fn cmp(&self, other: &Self) -> Ordering { use self::Atom::*; match (self, other) { (Underscore(l), Underscore(r)) => l.cmp(r), (Underscore(_), _) => Ordering::Less, (_, Underscore(_)) => Ordering::Greater, (Number(l), Number(r)) => cmp_numeric(l, r), (Number(_), Chars(_)) => Ordering::Less, (Chars(_), Number(_)) => Ordering::Greater, (Chars(l), Chars(r)) => cmp_ignore_case(l, r), } } } fn cmp_numeric(l: &str, r: &str) -> Ordering { // Trim leading zeros. let l = l.trim_start_matches('0'); let r = r.trim_start_matches('0'); match l.len().cmp(&r.len()) { Ordering::Equal => l.cmp(r), non_eq => non_eq, } } fn cmp_ignore_case(l: &str, r: &str) -> Ordering { for (a, b) in l.bytes().zip(r.bytes()) { match a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase()) { Ordering::Equal => match a.cmp(&b) { Ordering::Equal => {} non_eq => return non_eq, }, non_eq => return non_eq, } } l.len().cmp(&r.len()) } pub fn iter_atoms(string: &str) -> AtomIter { AtomIter { bytes: string.as_bytes(), offset: 0, } } pub struct AtomIter<'a> { bytes: &'a [u8], offset: usize, } impl<'a> Iterator for AtomIter<'a> { type Item = Atom<'a>; fn next(&mut self) -> Option> { if self.offset >= self.bytes.len() { return None; } let x = self.bytes[self.offset]; match x { b'_' => { self.offset += 1; let mut n = 1; while self.offset < self.bytes.len() { match self.bytes[self.offset] { b'_' => { self.offset += 1; n += 1; } _ => break, } } Some(Atom::Underscore(n)) } b'0'..=b'9' => { let start = self.offset; self.offset += 1; while self.offset < self.bytes.len() { match self.bytes[self.offset] { b'0'..=b'9' => self.offset += 1, _ => break, } } let bytes = &self.bytes[start..self.offset]; let number = str::from_utf8(bytes).expect("valid utf8"); Some(Atom::Number(number)) } _ => { let start = self.offset; self.offset += 1; while self.offset < self.bytes.len() { match self.bytes[self.offset] { b'_' | b'0'..=b'9' => break, _ => self.offset += 1, } } let bytes = &self.bytes[start..self.offset]; let chars = str::from_utf8(bytes).expect("valid utf8"); Some(Atom::Chars(chars)) } } } } remain-0.2.6/src/check.rs000064400000000000000000000072451046102023000133260ustar 00000000000000use quote::quote; use std::cmp::Ordering; use syn::{Arm, Attribute, Ident, Result, Variant}; use syn::{Error, Field, Pat, PatIdent}; use crate::compare::{cmp, Path, UnderscoreOrder}; use crate::format; use crate::parse::Input::{self, *}; pub fn sorted(input: &mut Input) -> Result<()> { let paths = match input { Enum(item) => collect_paths(&mut item.variants)?, Struct(item) => collect_paths(&mut item.fields)?, Match(expr) | Let(expr) => collect_paths(&mut expr.arms)?, }; let mode = UnderscoreOrder::First; if find_misordered(&paths, mode).is_none() { return Ok(()); } let mode = UnderscoreOrder::Last; let wrong = match find_misordered(&paths, mode) { Some(wrong) => wrong, None => return Ok(()), }; let lesser = &paths[wrong]; let correct_pos = match paths[..wrong - 1].binary_search_by(|probe| cmp(probe, lesser, mode)) { Err(correct_pos) => correct_pos, Ok(equal_to) => equal_to + 1, }; let greater = &paths[correct_pos]; Err(format::error(lesser, greater)) } fn find_misordered(paths: &[Path], mode: UnderscoreOrder) -> Option { for i in 1..paths.len() { if cmp(&paths[i], &paths[i - 1], mode) == Ordering::Less { return Some(i); } } None } fn collect_paths<'a, I, P>(iter: I) -> Result> where I: IntoIterator, P: Sortable + 'a, { iter.into_iter() .filter_map(|item| { if remove_unsorted_attr(item.attrs()) { None } else { Some(item.to_path()) } }) .collect() } fn remove_unsorted_attr(attrs: &mut Vec) -> bool { for i in 0..attrs.len() { let path = &attrs[i].path; let path = quote!(#path).to_string(); if path == "unsorted" || path == "remain :: unsorted" { attrs.remove(i); return true; } } false } trait Sortable { fn to_path(&self) -> Result; fn attrs(&mut self) -> &mut Vec; } impl Sortable for Variant { fn to_path(&self) -> Result { Ok(Path { segments: vec![self.ident.clone()], }) } fn attrs(&mut self) -> &mut Vec { &mut self.attrs } } impl Sortable for Field { fn to_path(&self) -> Result { Ok(Path { segments: vec![self.ident.clone().expect("must be named field")], }) } fn attrs(&mut self) -> &mut Vec { &mut self.attrs } } impl Sortable for Arm { fn to_path(&self) -> Result { // Sort by just the first pat. let pat = match &self.pat { Pat::Or(pat) => pat.cases.iter().next().expect("at least one pat"), _ => &self.pat, }; let segments = match pat { Pat::Ident(pat) if is_just_ident(pat) => vec![pat.ident.clone()], Pat::Path(pat) => idents_of_path(&pat.path), Pat::Struct(pat) => idents_of_path(&pat.path), Pat::TupleStruct(pat) => idents_of_path(&pat.path), Pat::Wild(pat) => vec![Ident::from(pat.underscore_token)], other => { let msg = "unsupported by #[remain::sorted]"; return Err(Error::new_spanned(other, msg)); } }; Ok(Path { segments }) } fn attrs(&mut self) -> &mut Vec { &mut self.attrs } } fn idents_of_path(path: &syn::Path) -> Vec { path.segments.iter().map(|seg| seg.ident.clone()).collect() } fn is_just_ident(pat: &PatIdent) -> bool { pat.by_ref.is_none() && pat.mutability.is_none() && pat.subpat.is_none() } remain-0.2.6/src/compare.rs000064400000000000000000000034261046102023000136740ustar 00000000000000use proc_macro2::Ident; use std::cmp::Ordering; use crate::atom::iter_atoms; #[derive(Copy, Clone, PartialEq)] pub enum UnderscoreOrder { First, Last, } pub struct Path { pub segments: Vec, } pub fn cmp(lhs: &Path, rhs: &Path, mode: UnderscoreOrder) -> Ordering { // Lexicographic ordering across path segments. for (lhs, rhs) in lhs.segments.iter().zip(&rhs.segments) { match cmp_segment(&lhs.to_string(), &rhs.to_string(), mode) { Ordering::Equal => {} non_eq => return non_eq, } } lhs.segments.len().cmp(&rhs.segments.len()) } fn cmp_segment(lhs: &str, rhs: &str, mode: UnderscoreOrder) -> Ordering { // Sort `_` last. match (lhs, rhs) { ("_", "_") => return Ordering::Equal, ("_", _) => return Ordering::Greater, (_, "_") => return Ordering::Less, (_, _) => {} } let mut lhs_atoms = iter_atoms(lhs); let mut rhs_atoms = iter_atoms(rhs); // Path segments can't be empty. let mut left = lhs_atoms.next().unwrap(); let mut right = rhs_atoms.next().unwrap(); if mode == UnderscoreOrder::Last { // Compare leading underscores. match left.underscores().cmp(&right.underscores()) { Ordering::Equal => {} non_eq => return non_eq, } } loop { match left.cmp(&right) { Ordering::Equal => {} non_eq => return non_eq, } match (lhs_atoms.next(), rhs_atoms.next()) { (None, None) => return Ordering::Equal, (None, Some(_)) => return Ordering::Less, (Some(_), None) => return Ordering::Greater, (Some(nextl), Some(nextr)) => { left = nextl; right = nextr; } } } } remain-0.2.6/src/emit.rs000064400000000000000000000010011046102023000131670ustar 00000000000000use proc_macro::TokenStream; use quote::quote; use syn::Error; #[derive(Copy, Clone)] pub enum Kind { Enum, Match, Struct, Let, } pub fn emit(err: &Error, kind: Kind, output: TokenStream) -> TokenStream { let err = err.to_compile_error(); let output = proc_macro2::TokenStream::from(output); let expanded = match kind { Kind::Enum | Kind::Let | Kind::Struct => quote!(#err #output), Kind::Match => quote!({ #err #output }), }; TokenStream::from(expanded) } remain-0.2.6/src/format.rs000064400000000000000000000012501046102023000135270ustar 00000000000000use proc_macro2::TokenStream; use quote::TokenStreamExt; use std::fmt::{self, Display}; use syn::Error; use crate::compare::Path; impl Display for Path { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { for (i, segment) in self.segments.iter().enumerate() { if i > 0 { formatter.write_str("::")?; } segment.fmt(formatter)?; } Ok(()) } } pub fn error(lesser: &Path, greater: &Path) -> Error { let mut spans = TokenStream::new(); spans.append_all(&lesser.segments); let msg = format!("{} should sort before {}", lesser, greater); Error::new_spanned(spans, msg) } remain-0.2.6/src/lib.rs000064400000000000000000000131631046102023000130130ustar 00000000000000//! [![github]](https://github.com/dtolnay/remain) [![crates-io]](https://crates.io/crates/remain) [![docs-rs]](https://docs.rs/remain) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! This crate provides an attribute macro to check at compile time that the //! variants of an enum or the arms of a match expression are written in sorted //! order. //! //! # Syntax //! //! Place a `#[remain::sorted]` attribute on enums, structs, match-expressions, //! or let-statements whose value is a match-expression. //! //! Alternatively, import as `use remain::sorted;` and use `#[sorted]` as the //! attribute. //! //! ``` //! # use std::error::Error as StdError; //! # use std::fmt::{self, Display}; //! # use std::io; //! # //! #[remain::sorted] //! #[derive(Debug)] //! pub enum Error { //! BlockSignal(signal::Error), //! CreateCrasClient(libcras::Error), //! CreateEventFd(sys_util::Error), //! CreateSignalFd(sys_util::SignalFdError), //! CreateSocket(io::Error), //! DetectImageType(qcow::Error), //! DeviceJail(io_jail::Error), //! NetDeviceNew(virtio::NetError), //! SpawnVcpu(io::Error), //! } //! //! impl Display for Error { //! # #[remain::check] //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! use self::Error::*; //! //! #[remain::sorted] //! match self { //! BlockSignal(e) => write!(f, "failed to block signal: {}", e), //! CreateCrasClient(e) => write!(f, "failed to create cras client: {}", e), //! CreateEventFd(e) => write!(f, "failed to create eventfd: {}", e), //! CreateSignalFd(e) => write!(f, "failed to create signalfd: {}", e), //! CreateSocket(e) => write!(f, "failed to create socket: {}", e), //! DetectImageType(e) => write!(f, "failed to detect disk image type: {}", e), //! DeviceJail(e) => write!(f, "failed to jail device: {}", e), //! NetDeviceNew(e) => write!(f, "failed to set up virtio networking: {}", e), //! SpawnVcpu(e) => write!(f, "failed to spawn VCPU thread: {}", e), //! } //! } //! } //! # //! # mod signal { //! # pub use std::io::Error; //! # } //! # //! # mod libcras { //! # pub use std::io::Error; //! # } //! # //! # mod sys_util { //! # pub use std::io::{Error, Error as SignalFdError}; //! # } //! # //! # mod qcow { //! # pub use std::io::Error; //! # } //! # //! # mod io_jail { //! # pub use std::io::Error; //! # } //! # //! # mod virtio { //! # pub use std::io::Error as NetError; //! # } //! # //! # fn main() {} //! ``` //! //! If an enum variant, struct field, or match arm is inserted out of order,\ //! //! ```diff //! NetDeviceNew(virtio::NetError), //! SpawnVcpu(io::Error), //! + AaaUhOh(Box), //! } //! ``` //! //! then the macro produces a compile error. //! //! ```console //! error: AaaUhOh should sort before BlockSignal //! --> tests/stable.rs:49:5 //! | //! 49 | AaaUhOh(Box), //! | ^^^^^^^ //! ``` //! //! # Compiler support //! //! The attribute on enums is supported on any rustc version 1.31+. //! //! Rust does not yet have stable support for user-defined attributes within a //! function body, so the attribute on match-expressions and let-statements //! requires a nightly compiler and the following two features enabled: //! //! ``` //! # const IGNORE: &str = stringify! { //! #![feature(proc_macro_hygiene, stmt_expr_attributes)] //! # }; //! ``` //! //! As a stable alternative, this crate provides a function-level attribute //! called `#[remain::check]` which makes match-expression and let-statement //! attributes work on any rustc version 1.31+. Place this attribute on any //! function containing `#[sorted]` to make them work on a stable compiler. //! //! ``` //! # use std::fmt::{self, Display}; //! # //! # enum Error {} //! # //! impl Display for Error { //! #[remain::check] //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! use self::Error::*; //! //! #[sorted] //! match self { //! /* ... */ //! # _ => unimplemented!(), //! } //! } //! } //! # //! # fn main() {} //! ``` #![allow( clippy::derive_partial_eq_without_eq, clippy::enum_glob_use, clippy::manual_find, clippy::match_same_arms, clippy::module_name_repetitions, clippy::needless_doctest_main, clippy::similar_names )] extern crate proc_macro; mod atom; mod check; mod compare; mod emit; mod format; mod parse; mod visit; use proc_macro::TokenStream; use quote::quote; use syn::parse::Nothing; use syn::{parse_macro_input, ItemFn}; use crate::emit::emit; use crate::parse::Input; #[proc_macro_attribute] pub fn sorted(args: TokenStream, input: TokenStream) -> TokenStream { let _ = parse_macro_input!(args as Nothing); let mut input = parse_macro_input!(input as Input); let kind = input.kind(); let result = check::sorted(&mut input); let output = TokenStream::from(quote!(#input)); match result { Ok(_) => output, Err(err) => emit(&err, kind, output), } } #[proc_macro_attribute] pub fn check(args: TokenStream, input: TokenStream) -> TokenStream { let _ = parse_macro_input!(args as Nothing); let mut input = parse_macro_input!(input as ItemFn); visit::check(&mut input); TokenStream::from(quote!(#input)) } remain-0.2.6/src/parse.rs000064400000000000000000000045231046102023000133570ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use syn::parse::{Parse, ParseStream}; use syn::{Attribute, Error, Expr, Fields, Result, Stmt, Token, Visibility}; use crate::emit::Kind; pub enum Input { Enum(syn::ItemEnum), Match(syn::ExprMatch), Struct(syn::ItemStruct), Let(syn::ExprMatch), } impl Input { pub fn kind(&self) -> Kind { match self { Input::Enum(_) => Kind::Enum, Input::Match(_) => Kind::Match, Input::Struct(_) => Kind::Struct, Input::Let(_) => Kind::Let, } } } impl Parse for Input { fn parse(input: ParseStream) -> Result { let ahead = input.fork(); let _ = ahead.call(Attribute::parse_outer)?; if ahead.peek(Token![match]) { let expr = match input.parse()? { Expr::Match(expr) => expr, _ => unreachable!("expected match"), }; return Ok(Input::Match(expr)); } if ahead.peek(Token![let]) { let stmt = match input.parse()? { Stmt::Local(stmt) => stmt, _ => unreachable!("expected let"), }; let init = match stmt.init { Some((_, init)) => *init, None => return Err(unexpected()), }; let expr = match init { Expr::Match(expr) => expr, _ => return Err(unexpected()), }; return Ok(Input::Let(expr)); } let _: Visibility = ahead.parse()?; if ahead.peek(Token![enum]) { return input.parse().map(Input::Enum); } else if ahead.peek(Token![struct]) { let input: syn::ItemStruct = input.parse()?; if let Fields::Named(_) = &input.fields { return Ok(Input::Struct(input)); } } Err(unexpected()) } } impl ToTokens for Input { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Input::Enum(item) => item.to_tokens(tokens), Input::Struct(item) => item.to_tokens(tokens), Input::Match(expr) | Input::Let(expr) => expr.to_tokens(tokens), } } } fn unexpected() -> Error { let span = Span::call_site(); let msg = "expected enum, struct, or match expression"; Error::new(span, msg) } remain-0.2.6/src/visit.rs000064400000000000000000000036011046102023000133770ustar 00000000000000use quote::quote; use syn::visit_mut::{self, VisitMut}; use syn::{parse_quote, Attribute, Expr, ExprMatch, ItemFn, Local}; use crate::parse::Input; pub fn check(input: &mut ItemFn) { Checker.visit_item_fn_mut(input); } struct Checker; impl VisitMut for Checker { fn visit_expr_mut(&mut self, expr: &mut Expr) { visit_mut::visit_expr_mut(self, expr); let expr_match = match expr { Expr::Match(expr) => expr, _ => return, }; if !take_sorted_attr(&mut expr_match.attrs) { return; } let input = expr_match.clone(); check_and_insert_error(input, expr); } fn visit_local_mut(&mut self, local: &mut Local) { visit_mut::visit_local_mut(self, local); let init = match &local.init { Some((_, init)) => init, None => return, }; let expr_match = match init.as_ref() { Expr::Match(expr) => expr, _ => return, }; if !take_sorted_attr(&mut local.attrs) { return; } let input = expr_match.clone(); let expr = local.init.as_mut().unwrap().1.as_mut(); check_and_insert_error(input, expr); } } fn take_sorted_attr(attrs: &mut Vec) -> bool { for i in 0..attrs.len() { let path = &attrs[i].path; let path = quote!(#path).to_string(); if path == "sorted" || path == "remain :: sorted" { attrs.remove(i); return true; } } false } fn check_and_insert_error(input: ExprMatch, out: &mut Expr) { let mut input = Input::Match(input); *out = match crate::check::sorted(&mut input) { Ok(_) => parse_quote!(#input), Err(err) => { let err = err.to_compile_error(); parse_quote!({ #err #input }) } }; } remain-0.2.6/tests/compiletest.rs000064400000000000000000000002461046102023000151460ustar 00000000000000#[rustversion::attr(not(nightly), ignore)] #[cfg_attr(miri, ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } remain-0.2.6/tests/order.rs000064400000000000000000000014071046102023000137310ustar 00000000000000#![allow(dead_code, non_camel_case_types)] #![allow(clippy::enum_variant_names, clippy::upper_case_acronyms)] #[remain::sorted] enum UnderscoresFirst { __Nonexhaustive, Aaa, Bbb, } #[remain::sorted] enum UnderscoresLast { Aaa, Bbb, __Nonexhaustive, } #[remain::sorted] enum SnakeCase { under_score, underscore, } #[remain::sorted] enum NumberingSimple { E1, E9, E10, } #[remain::sorted] enum NumberingComplex { E1_Aaa, E9_Aaa, E10_Aaa, } #[remain::sorted] enum AtomOrder { A, A_, A0, AA, Aa, under_0core, under_Score, under_score, under__0core, under__Score, under__score, underscore, } #[remain::sorted] enum LargeNumber { E1, E99999999999999999999999, } remain-0.2.6/tests/stable.rs000064400000000000000000000025151046102023000140710ustar 00000000000000#![allow(dead_code)] #![allow( clippy::derive_partial_eq_without_eq, clippy::let_unit_value, clippy::match_same_arms )] #[remain::sorted] #[derive(PartialEq)] pub enum TestEnum { A, B, #[remain::unsorted] Ignored, C, #[unsorted] AlsoIgnored, D, __Nonexhaustive, } #[remain::sorted] #[derive(PartialEq)] pub struct TestStruct { a: usize, b: usize, #[unsorted] ignored: usize, c: usize, #[remain::unsorted] also_ignored: usize, d: usize, } #[test] fn test_attrs() { fn is_partial_eq() -> bool { true } assert!(is_partial_eq::()); assert!(is_partial_eq::()); } #[test] #[remain::check] fn test_let() { let value = TestEnum::A; #[sorted] let _ = match value { TestEnum::A => {} #[remain::unsorted] TestEnum::Ignored => {} TestEnum::B => {} #[unsorted] TestEnum::AlsoIgnored => {} TestEnum::C => {} _ => {} }; } #[test] #[remain::check] fn test_match() { let value = TestEnum::A; #[sorted] match value { TestEnum::A => {} TestEnum::B => {} #[unsorted] TestEnum::Ignored => {} TestEnum::C => {} #[remain::unsorted] TestEnum::AlsoIgnored => {} _ => {} } } remain-0.2.6/tests/ui/enum.rs000064400000000000000000000001621046102023000141740ustar 00000000000000use remain::sorted; #[sorted] enum E { Aaa, Ccc(u8), Ddd { u: u8 }, Bbb(u8, u8), } fn main() {} remain-0.2.6/tests/ui/enum.stderr000064400000000000000000000001411046102023000150500ustar 00000000000000error: Bbb should sort before Ccc --> tests/ui/enum.rs:8:5 | 8 | Bbb(u8, u8), | ^^^ remain-0.2.6/tests/ui/let-stable.rs000064400000000000000000000004231046102023000152640ustar 00000000000000enum E { Aaa, Bbb(u8, u8), Ccc(u8), Ddd { u: u8 }, } #[remain::check] fn main() { let value = E::Aaa; #[sorted] let _ = match value { E::Aaa => {} E::Ccc(_) => {} E::Ddd { u: _ } => {} E::Bbb(_, _) => {} }; } remain-0.2.6/tests/ui/let-stable.stderr000064400000000000000000000002031046102023000161370ustar 00000000000000error: E::Bbb should sort before E::Ccc --> tests/ui/let-stable.rs:17:9 | 17 | E::Bbb(_, _) => {} | ^^^^^^ remain-0.2.6/tests/ui/let-unstable.rs000064400000000000000000000005161046102023000156320ustar 00000000000000#![feature(proc_macro_hygiene, stmt_expr_attributes)] use remain::sorted; enum E { Aaa, Bbb(u8, u8), Ccc(u8), Ddd { u: u8 }, } fn main() { let value = E::Aaa; #[sorted] let _ = match value { E::Aaa => {} E::Ccc(_) => {} E::Ddd { u: _ } => {} E::Bbb(_, _) => {} }; } remain-0.2.6/tests/ui/let-unstable.stderr000064400000000000000000000002051046102023000165040ustar 00000000000000error: E::Bbb should sort before E::Ccc --> tests/ui/let-unstable.rs:20:9 | 20 | E::Bbb(_, _) => {} | ^^^^^^ remain-0.2.6/tests/ui/match-stable.rs000064400000000000000000000004121046102023000155720ustar 00000000000000enum E { Aaa, Bbb(u8, u8), Ccc(u8), Ddd { u: u8 }, } #[remain::check] fn main() { let value = E::Aaa; #[sorted] match value { E::Aaa => {} E::Ccc(_) => {} E::Ddd { u: _ } => {} E::Bbb(_, _) => {} } } remain-0.2.6/tests/ui/match-stable.stderr000064400000000000000000000002051046102023000164510ustar 00000000000000error: E::Bbb should sort before E::Ccc --> tests/ui/match-stable.rs:17:9 | 17 | E::Bbb(_, _) => {} | ^^^^^^ remain-0.2.6/tests/ui/match-unstable.rs000064400000000000000000000005051046102023000161400ustar 00000000000000#![feature(proc_macro_hygiene, stmt_expr_attributes)] use remain::sorted; enum E { Aaa, Bbb(u8, u8), Ccc(u8), Ddd { u: u8 }, } fn main() { let value = E::Aaa; #[sorted] match value { E::Aaa => {} E::Ccc(_) => {} E::Ddd { u: _ } => {} E::Bbb(_, _) => {} } } remain-0.2.6/tests/ui/match-unstable.stderr000064400000000000000000000002071046102023000170160ustar 00000000000000error: E::Bbb should sort before E::Ccc --> tests/ui/match-unstable.rs:20:9 | 20 | E::Bbb(_, _) => {} | ^^^^^^ remain-0.2.6/tests/ui/repeat.rs000064400000000000000000000002551046102023000145130ustar 00000000000000enum E { Aaa(u8), Bbb, } #[remain::check] fn main() { #[sorted] match E::Bbb { E::Aaa(0) => {} E::Bbb => {} E::Aaa(_) => {} } } remain-0.2.6/tests/ui/repeat.stderr000064400000000000000000000001741046102023000153720ustar 00000000000000error: E::Aaa should sort before E::Bbb --> tests/ui/repeat.rs:12:9 | 12 | E::Aaa(_) => {} | ^^^^^^ remain-0.2.6/tests/ui/struct.rs000064400000000000000000000001731046102023000145560ustar 00000000000000use remain::sorted; #[sorted] struct TestStruct { d: usize, c: usize, a: usize, b: usize, } fn main() {} remain-0.2.6/tests/ui/struct.stderr000064400000000000000000000001321046102023000154300ustar 00000000000000error: c should sort before d --> tests/ui/struct.rs:6:5 | 6 | c: usize, | ^ remain-0.2.6/tests/ui/unnamed-fields.rs000064400000000000000000000001571046102023000161270ustar 00000000000000#[remain::sorted] struct TupleStruct(usize, usize, usize); #[remain::sorted] struct UnitStruct; fn main() {} remain-0.2.6/tests/ui/unnamed-fields.stderr000064400000000000000000000010431046102023000170010ustar 00000000000000error: expected enum, struct, or match expression --> tests/ui/unnamed-fields.rs:1:1 | 1 | #[remain::sorted] | ^^^^^^^^^^^^^^^^^ | = note: this error originates in the attribute macro `remain::sorted` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected enum, struct, or match expression --> tests/ui/unnamed-fields.rs:4:1 | 4 | #[remain::sorted] | ^^^^^^^^^^^^^^^^^ | = note: this error originates in the attribute macro `remain::sorted` (in Nightly builds, run with -Z macro-backtrace for more info) remain-0.2.6/tests/ui/unsorted-enum.rs000064400000000000000000000002021046102023000160300ustar 00000000000000use remain::sorted; #[sorted] enum E { Aaa, Ccc(u8), #[unsorted] Ddd { u: u8 }, Bbb(u8, u8), } fn main() {} remain-0.2.6/tests/ui/unsorted-enum.stderr000064400000000000000000000001521046102023000167130ustar 00000000000000error: Bbb should sort before Ccc --> tests/ui/unsorted-enum.rs:9:5 | 9 | Bbb(u8, u8), | ^^^ remain-0.2.6/tests/ui/unsorted-match-stable.rs000064400000000000000000000004361046102023000174410ustar 00000000000000enum E { Aaa, Bbb(u8, u8), Ccc(u8), Ddd { u: u8 }, } #[remain::check] fn main() { let value = E::Aaa; #[sorted] match value { E::Aaa => {} E::Ccc(_) => {} #[unsorted] E::Ddd { u: _ } => {} E::Bbb(_, _) => {} } } remain-0.2.6/tests/ui/unsorted-match-stable.stderr000064400000000000000000000002161046102023000203140ustar 00000000000000error: E::Bbb should sort before E::Ccc --> tests/ui/unsorted-match-stable.rs:18:9 | 18 | E::Bbb(_, _) => {} | ^^^^^^ remain-0.2.6/tests/ui/unsorted-match-unstable.rs000064400000000000000000000005311046102023000200000ustar 00000000000000#![feature(proc_macro_hygiene, stmt_expr_attributes)] use remain::sorted; enum E { Aaa, Bbb(u8, u8), Ccc(u8), Ddd { u: u8 }, } fn main() { let value = E::Aaa; #[sorted] match value { E::Aaa => {} #[unsorted] E::Ccc(_) => {} E::Ddd { u: _ } => {} E::Bbb(_, _) => {} } } remain-0.2.6/tests/ui/unsorted-match-unstable.stderr000064400000000000000000000002201046102023000206520ustar 00000000000000error: E::Bbb should sort before E::Ddd --> tests/ui/unsorted-match-unstable.rs:21:9 | 21 | E::Bbb(_, _) => {} | ^^^^^^ remain-0.2.6/tests/ui/unsorted-struct.rs000064400000000000000000000002131046102023000164120ustar 00000000000000use remain::sorted; #[sorted] struct TestStruct { d: usize, #[unsorted] c: usize, a: usize, b: usize, } fn main() {} remain-0.2.6/tests/ui/unsorted-struct.stderr000064400000000000000000000001431046102023000172730ustar 00000000000000error: a should sort before d --> tests/ui/unsorted-struct.rs:8:5 | 8 | a: usize, | ^ remain-0.2.6/tests/ui/unsupported.rs000064400000000000000000000001761046102023000156250ustar 00000000000000#[remain::check] fn main() { let value = 0; #[sorted] match value { 0..=20 => {} _ => {} } } remain-0.2.6/tests/ui/unsupported.stderr000064400000000000000000000001711046102023000164770ustar 00000000000000error: unsupported by #[remain::sorted] --> tests/ui/unsupported.rs:7:9 | 7 | 0..=20 => {} | ^^^^^^ remain-0.2.6/tests/unstable.rs000064400000000000000000000022451046102023000144340ustar 00000000000000#![allow(dead_code)] #![cfg(not(remain_stable_testing))] #![feature(proc_macro_hygiene, stmt_expr_attributes)] #![allow(clippy::derive_partial_eq_without_eq, clippy::match_same_arms)] #[remain::sorted] #[derive(PartialEq)] pub enum TestEnum { A, #[remain::unsorted] Ignored, B, C, D, __Nonexhaustive, } #[remain::sorted] #[derive(PartialEq)] pub struct TestStruct { a: usize, b: usize, c: usize, #[unsorted] ignored: usize, d: usize, } #[test] fn test_attrs() { fn is_partial_eq() -> bool { true } assert!(is_partial_eq::()); assert!(is_partial_eq::()); } #[test] fn test_let() { let value = TestEnum::A; #[remain::sorted] let _ = match value { TestEnum::A => {} #[remain::unsorted] TestEnum::Ignored => {} TestEnum::B => {} TestEnum::C => {} _ => {} }; } #[test] fn test_match() { let value = TestEnum::A; #[remain::sorted] match value { TestEnum::A => {} TestEnum::B => {} #[unsorted] TestEnum::Ignored => {} TestEnum::C => {} _ => {} } }