fix-getters-rules-0.3.2/.cargo_vcs_info.json0000644000000001120000000000000144200ustar { "git": { "sha1": "b9a196f151ac910c496bc016a77741623316ffdc" } } fix-getters-rules-0.3.2/Cargo.toml0000644000000020020000000000000124160ustar # 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] edition = "2018" name = "fix-getters-rules" version = "0.3.2" authors = ["François Laignel "] description = "Fix get functions name by removing the get prefix when applicable" readme = "README.md" keywords = ["rust", "code", "getter", "programming", "migration"] categories = ["development-tools"] license = "MIT/Apache-2.0" repository = "https://github.com/fengalin/fix-getters" [dependencies.once_cell] version = "1.5" [features] default = ["dir-entry"] dir-entry = [] fix-getters-rules-0.3.2/Cargo.toml.orig000064400000000000000000000010030000000000000160550ustar 00000000000000[package] name = "fix-getters-rules" version = "0.3.2" authors = ["François Laignel "] description = "Fix get functions name by removing the get prefix when applicable" categories = ["development-tools"] keywords = ["rust", "code", "getter", "programming", "migration"] license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/fengalin/fix-getters" edition = "2018" [dependencies] once_cell = "1.5" [features] default = ["dir-entry"] # dir_entry module. dir-entry = [] fix-getters-rules-0.3.2/LICENSE-APACHE000064400000000000000000000251370000000000000151300ustar 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. fix-getters-rules-0.3.2/LICENSE-MIT000064400000000000000000000017770000000000000146440ustar 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. fix-getters-rules-0.3.2/README.md000064400000000000000000000114630000000000000144600ustar 00000000000000# fix-getters-rules This package contains rules definitions for the `fix-getters` tools. See the [workspace documentation](https://github.com/fengalin/fix-getters/blob/0.3.2/README.md) for more details on `fix-getters`. ## Rules The `rules` apply to: * file system directory entries to decide if a file should be processed or if a directory branch should be skipped. This requires `feature` **`dir-entry`** (enabled by default). * functions name. ## Feature * **`dir-entry`** — directory entry filtering rules. This features is enabled by default. Use `default-features = false` if your use case differs. ## Function name rules The initial intent is to comply with Rust [naming conventions for getter methods](https://doc.rust-lang.org/1.0.0/style/style/naming/README.html#getter/setter-methods-%5Brfc-344%5D): > A method `foo(&self) -> &T` for getting the current value of the field. ### General rules These rules are based on the function name and knowledge of the return type. See next chapter for `get` functions returning exactly one `bool`. A `get` function is considered eligible for `get` prefix removal if: * The function starts with `get_`. * The suffix is not a Rust keyword, which would result in invalid code. E.g.: `get_as`, `get_false`, ... are kept as is. * The method would result inconsistent with other similar methods. E.g.: a `struct` `Value` with a `get_mut` method to get the underlying value as a mutable reference, `get_optional` to get the underlying value of a type in the form `Option` and `get_some` to get the underlying value of a type for which the value is always defined. See `RESERVED` in [`function.rs`](https://github.com/fengalin/fix-getters/blob/0.3.2/rules/src/function.rs). * The suffix is not part of a subsitution list. This includes some Rust keywords. E.g.: `get_type` is replaced with `type_`. See `EXACT_SUFFIX_SUBSTITUTES` in [`function.rs`](https://github.com/fengalin/fix-getters/blob/0.3.2/rules/src/function.rs). Another rule is applied to homogenize functions names in the form `get_something_mut`. This rule renames both `get_something_mut` and `get_mut_something` as `something_mut`. The `fix-getters` tools also apply selective rules based on on the function signature. See the dedicated chapter in [this `README`](https://github.com/fengalin/fix-getters/blob/0.3.2/README.md#get-functions-selection). ### Functions returning exactly one `bool` Get functions returning `bool` should usually use the form `is_suffix`, which reads natural when used in a condition. E.g.: ```rust if event.is_serialized() { ... } ``` The following additional rules are implemented. #### First token substitutions When the suffix starts with a verb, it's common to conjugate. E.g. * `get_emit_eos` -> `if element.emits_eos()`. `BOOL_FIRST_TOKEN_SUBSTITUTES` in [`function.rs`](https://github.com/fengalin/fix-getters/blob/0.3.2/rules/src/function.rs) lists a set of verbs and the matching substitutions and also includes other cases such as: * `get_always_...` -> `must_always_...`. * `get_focus` -> `gets_focus`. #### Special first tokens Modal verbs should be kept unchanged and no `is` prefix should be used. E.g.: * `get_can_focus` -> `can_focus`. * `get_must_...` -> `must_...`. This is also the case for already conjugated verbs. E.g.: * `get_has_...` -> `has_...`. See `BOOL_FIRST_TOKEN_NO_PREFIX` in [`function.rs`](https://github.com/fengalin/fix-getters/blob/0.3.2/rules/src/function.rs). #### Exact suffix substitutions In some cases, the semantic requires substitutions only if the whole suffix matches a value. E.g.: * `get_result` -> `result`. Neither `if a.is_result()` nor `if a.results()` would be suitable. * `get_visibility` -> `is_visible` Neither `if a.is_visibility()` nor `if a.visibility()`) would be suitable. See `BOOL_EXACT_SUBSTITUTES` in [`function.rs`](https://github.com/fengalin/fix-getters/blob/0.3.2/rules/src/function.rs). #### get_is prefix Finally, the `is` prefix shouldn't be repeated when already present: * `get_is_active` -> `is_active`. ### Detecting functions returning exactly one `bool` The return type of Rust functions is usually not explicit. When renaming the `get` functions call sites (see [`fix-getters-calls`](https://github.com/fengalin/fix-getters/tree/0.3.2/fix-calls)), the returned type must be inferred. The rules described in previous chapter are reversed when possible and an additional heuristic is used: when the first token of the `get` function suffix ends in `able`, the function is considered to be returning a `bool`. E.g.: * `get_seekable` -> `is_seekable`. ## LICENSE This crate is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. fix-getters-rules-0.3.2/src/dir_entry.rs000064400000000000000000000037370000000000000163420ustar 00000000000000//! Directory entry filtering. use once_cell::sync::Lazy; use std::{ collections::HashSet, error::Error, fmt::{self, Display}, fs::DirEntry, io, path::PathBuf, }; /// Directories to exclude from the fix process. pub static EXCLUDED: Lazy> = Lazy::new(|| { let mut excluded = HashSet::new(); excluded.insert(".git"); excluded.insert("auto"); excluded.insert("ci"); excluded.insert("docs"); excluded.insert("gir"); excluded.insert("gir-files"); excluded.insert("target"); excluded.insert("sys"); excluded }); /// Checks the given directory entry. #[inline] pub fn check(entry: &DirEntry) -> Result { let entry_type = entry .file_type() .map_err(|err| CheckError::DirEntry(entry.path(), err))?; let entry_name = entry.file_name(); let entry_name = match entry_name.to_str() { Some(entry_name) => entry_name, None => return Err(CheckError::Name(entry.path(), entry_name)), }; if entry_type.is_file() { if entry_name.ends_with(".rs") { return Ok(CheckOk::RustFile); } } else if entry_type.is_dir() { if !EXCLUDED.contains(entry_name) { return Ok(CheckOk::Directory); } } else { return Ok(CheckOk::SkipUnspecified); } Ok(CheckOk::Skip(entry_name.to_string())) } #[derive(Debug)] pub enum CheckOk { Directory, RustFile, Skip(String), SkipUnspecified, } #[derive(Debug)] pub enum CheckError { Name(PathBuf, std::ffi::OsString), DirEntry(PathBuf, io::Error), } impl Display for CheckError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use CheckError::*; match self { Name(path, name) => write!(f, "error converting dir entry name {:?} {:?}", path, name), DirEntry(path, err) => write!(f, "error checking dir entry {:?}: {}", path, err), } } } impl Error for CheckError {} fix-getters-rules-0.3.2/src/function.rs000064400000000000000000000570000000000000000161600ustar 00000000000000//! Would-be-getter renaming rules definition. use once_cell::sync::Lazy; use std::{ collections::{HashMap, HashSet}, error::Error, fmt::{self, Display}, }; use crate::{NewName, NewNameRule, ReturnsBool}; /// Getters reserved suffix list. /// /// Getter that we don't want to rename because /// they are Rust keywords or would result confusing. pub static RESERVED: Lazy> = Lazy::new(|| { let mut reserved = HashSet::new(); reserved.insert(""); reserved.insert("as"); reserved.insert("const"); // keep `get_const` similar to `get` reserved.insert("else"); reserved.insert("false"); reserved.insert("for"); reserved.insert("if"); reserved.insert("in"); reserved.insert("mut"); // keep `get_mut` similar to `get` reserved.insert("optional"); // keep `get_optional` similar to `get` reserved.insert("or_init"); // keep `get_or_init` reserved.insert("owned"); // keep `get_owned` similar to `get` reserved.insert("ref"); // keep `get_ref` similar to `get` reserved.insert("some"); // keep `get_some` similar to `get` reserved.insert("true"); reserved.insert("unchecked"); reserved.insert("unchecked_mut"); reserved.insert("where"); reserved.insert("while"); reserved }); /// Substitutes to be used when the suffix matches exactly. /// /// The convention is to rename getters `get_suffix` as `suffix`, /// but there are cases for which a better name should be used: /// /// - `get_type` -> `type_`. pub static EXACT_SUFFIX_SUBSTITUTES: Lazy> = Lazy::new(|| { let mut exact_subs = HashMap::new(); exact_subs.insert("async", "async_"); exact_subs.insert("await", "await_"); exact_subs.insert("break", "break_"); exact_subs.insert("crate", "crate_"); exact_subs.insert("continue", "continue_"); exact_subs.insert("dyn", "dyn_"); exact_subs.insert("enum", "enum_"); exact_subs.insert("extern", "extern_"); exact_subs.insert("fn", "fn_"); exact_subs.insert("impl", "impl_"); exact_subs.insert("loop", "loop_"); exact_subs.insert("match", "match_"); exact_subs.insert("mod", "mod_"); exact_subs.insert("move", "move_"); exact_subs.insert("pub", "pub_"); exact_subs.insert("return", "return_"); exact_subs.insert("self", "self_"); exact_subs.insert("static", "static_"); exact_subs.insert("struct", "struct_"); exact_subs.insert("super", "super_"); exact_subs.insert("trait", "trait_"); exact_subs.insert("type", "type_"); exact_subs.insert("union", "union_"); exact_subs.insert("unsafe", "unsafe_"); exact_subs.insert("use", "use_"); exact_subs }); /// Substitutes for tokens of `bool` getters. /// /// The convention is to rename `bool` getters `get_suffix` as `is_suffix`, /// but there are cases for which we want a better name: /// /// - `get_mute` -> `is_muted`. /// - `get_emit_eos` -> `emits_eos`. pub static BOOL_FIRST_TOKEN_SUBSTITUTES: Lazy> = Lazy::new(|| { let mut first_token_subs = HashMap::new(); first_token_subs.insert("activate", "activates"); first_token_subs.insert("accept", "accepts"); first_token_subs.insert("allow", "allows"); // Ex.: `get_always_show_image` -> `must_always_show_image`. first_token_subs.insert("always", "must_always"); first_token_subs.insert("close", "closes"); first_token_subs.insert("create", "creates"); // Ex.: `get_destroy_with_parent` -> `must_destroy_with_parent`. first_token_subs.insert("destroy", "must_destroy"); first_token_subs.insert("do", "does"); first_token_subs.insert("draw", "draws"); first_token_subs.insert("embed", "embeds"); first_token_subs.insert("emit", "emits"); first_token_subs.insert("enable", "enables"); first_token_subs.insert("exit", "exits"); first_token_subs.insert("expand", "expands"); first_token_subs.insert("fill", "fills"); first_token_subs.insert("fit", "fits"); // Ex.: `get_focus_on_map` -> `gets_focus_on_map`. first_token_subs.insert("focus", "gets_focus"); first_token_subs.insert("follow", "follows"); first_token_subs.insert("hide", "hides"); first_token_subs.insert("ignore", "ignores"); first_token_subs.insert("invert", "inverts"); first_token_subs.insert("mute", "is_muted"); first_token_subs.insert("need", "needs"); first_token_subs.insert("propagate", "propagates"); first_token_subs.insert("populate", "populates"); first_token_subs.insert("receive", "receives"); first_token_subs.insert("reset", "resets"); first_token_subs.insert("require", "requires"); // Ex.: `get_reserve_indicator` -> `must_reserve_indicator`. first_token_subs.insert("reserve", "must_reserve"); first_token_subs.insert("resize", "resizes"); first_token_subs.insert("restrict", "restricts"); first_token_subs.insert("reveal", "reveals"); first_token_subs.insert("select", "selects"); first_token_subs.insert("show", "shows"); first_token_subs.insert("shrink", "shrinks"); first_token_subs.insert("skip", "skips"); first_token_subs.insert("snap", "snaps"); first_token_subs.insert("support", "supports"); first_token_subs.insert("take", "takes"); first_token_subs.insert("track", "tracks"); // Ex.: `get_truncate_multiline` -> `must_truncate_multiline`. first_token_subs.insert("truncate", "must_truncate"); first_token_subs.insert("use", "uses"); first_token_subs.insert("wrap", "wraps"); first_token_subs }); /// Set of `bool` getter suffix first tokens for which no be prefix should be applied. /// /// The convention is to rename `bool` getters `get_suffix` as `is_suffix`, /// but there are cases for which the meaning makes it useless to add the `is` prefix: /// /// - `get_has_entry` -> `has_entry`. pub static BOOL_FIRST_TOKEN_NO_PREFIX: Lazy> = Lazy::new(|| { let mut first_tokens = HashSet::new(); first_tokens.insert("can"); first_tokens.insert("has"); first_tokens.insert("must"); first_tokens.insert("should"); first_tokens.insert("state"); // Also add all the prefix substitutes (e.g. accepts, skips, ...) for bool_substitute in BOOL_FIRST_TOKEN_SUBSTITUTES.values() { first_tokens.insert(bool_substitute); } first_tokens }); /// Substitutes of `bool` getter to be used when the suffix matches exactly. /// /// The convention is to rename `bool` getters `get_suffix` as `is_suffix`, /// but there are cases for which it would be confusing to add the `is` prefix: /// /// - `get_result` -> `result`. /// - `get_overwrite` -> `overwrites`. Note that if the getter suffix doesn't match /// exactly, this rule doesn't apply. Ex. `get_overwrite_mode` -> `is_overwrites_mode` pub static BOOL_EXACT_SUBSTITUTES: Lazy> = Lazy::new(|| { let mut exact_subs = HashMap::new(); exact_subs.insert("result", "result"); exact_subs.insert("overwrite", "overwrites"); exact_subs.insert("visibility", "is_visible"); exact_subs }); /// Special suffix to detect getters returning a `bool`. /// /// Ex.: `get_seekable`. pub const BOOL_ABLE_PREFIX: &str = "able"; /// Getters prefix to move to the end. /// /// The convention is to use the form: /// - `get_structure_mut`. /// /// but we can run into this one too: /// - `get_mut_structure`. pub static PREFIX_TO_POSTFIX: Lazy> = Lazy::new(|| { let mut prefix_to_postfix = HashSet::new(); prefix_to_postfix.insert("mut"); prefix_to_postfix }); /// Attempts to apply getter name rules to this would-be-getter function. /// /// The argument `returns_bool` hints the renaming process when /// the getter returns a unique `bool` value. Use [`ReturnsBool::Maybe`] /// if the return value is not known. pub fn try_rename_would_be_getter( name: &str, returns_bool: impl Into, ) -> Result { let suffix = match name.strip_prefix("get_") { Some(suffix) => suffix, None => return Err(RenameError::NotGetFn), }; try_rename_getter_suffix(suffix, returns_bool) } /// Attempts to apply getter name rules to this getter suffix. /// /// The argument `returns_bool` hints the renaming process when /// the getter returns a unique `bool` value. Use [`ReturnsBool::Maybe`] /// if the return value is not known. pub fn try_rename_getter_suffix( suffix: &str, returns_bool: impl Into, ) -> Result { use ReturnsBool::*; let returns_bool = match returns_bool.into() { False => ReturnsBool::False, True => return Ok(rename_bool_getter(suffix)), Maybe => { if let Some(rename) = guesstimate_boolness_then_rename(suffix) { return Ok(rename); } ReturnsBool::Maybe } }; if let Some(substitute) = EXACT_SUFFIX_SUBSTITUTES.get(suffix) { return Ok(NewName { new_name: substitute.to_string(), returns_bool, rule: NewNameRule::Substituted, }); } let splits: Vec<&str> = suffix.splitn(2, '_').collect(); if splits.len() > 1 && PREFIX_TO_POSTFIX.contains(splits[0]) { Ok(NewName { new_name: format!("{}_{}", splits[1], splits[0]), returns_bool, rule: NewNameRule::Fixed, }) } else if RESERVED.contains(suffix) { Err(RenameError::Reserved) } else { Ok(NewName { new_name: suffix.to_string(), returns_bool, rule: NewNameRule::Regular, }) } } /// Applies `bool` getter name rules. #[inline] pub fn rename_bool_getter(suffix: &str) -> NewName { if let Some(substitute) = BOOL_EXACT_SUBSTITUTES.get(suffix) { return NewName { new_name: substitute.to_string(), returns_bool: true.into(), rule: NewNameRule::Substituted, }; } if let Some(new_name) = try_rename_bool_getter(suffix) { new_name } else { NewName { new_name: format!("is_{}", suffix), returns_bool: true.into(), rule: NewNameRule::Regular, } } } /// Attempts to apply special rules to the `bool` getter. /// /// The substitutions are defined in [`BOOL_FIRST_TOKEN_SUBSTITUTES`] /// and [`BOOL_FIRST_TOKEN_NO_PREFIX`]. #[inline] fn try_rename_bool_getter(suffix: &str) -> Option { let mut working_suffix = suffix; let mut has_is_prefix = false; if let Some(suffix_without_is) = suffix.strip_prefix("is_") { working_suffix = suffix_without_is; has_is_prefix = true; } let splits: Vec<&str> = working_suffix.splitn(2, '_').collect(); BOOL_FIRST_TOKEN_SUBSTITUTES .get(splits[0]) .map(|substitute| { if splits.len() == 1 { NewName { new_name: substitute.to_string(), returns_bool: true.into(), rule: NewNameRule::Substituted, } } else { NewName { new_name: format!("{}_{}", substitute, splits[1]), returns_bool: true.into(), rule: NewNameRule::Substituted, } } }) .or_else(|| { BOOL_FIRST_TOKEN_NO_PREFIX.get(splits[0]).map(|_| { if splits.len() == 1 { NewName { new_name: splits[0].to_string(), returns_bool: true.into(), rule: NewNameRule::NoPrefix, } } else { NewName { new_name: format!("{}_{}", splits[0], splits[1]), returns_bool: true.into(), rule: NewNameRule::NoPrefix, } } }) }) .or_else(|| { // No bool rules applied to the working suffix if has_is_prefix { // but the suffix was already `is` prefixed Some(NewName { new_name: suffix.to_string(), returns_bool: true.into(), rule: NewNameRule::Regular, }) } else { None } }) } /// Attempts to determine whether the getter returns a `bool` from its name. /// /// Uses [`BOOL_FIRST_TOKEN_SUBSTITUTES`], [`BOOL_FIRST_TOKEN_NO_PREFIX`] and /// [`BOOL_ABLE_PREFIX`] as a best effort estimation. /// /// Returns the name substitute if `self` seems to be returning a `bool`. #[inline] pub fn guesstimate_boolness_then_rename(suffix: &str) -> Option { if let Some(new_name) = try_rename_bool_getter(suffix) { return Some(new_name); } let splits: Vec<&str> = suffix.splitn(2, '_').collect(); if splits[0].ends_with(BOOL_ABLE_PREFIX) { Some(NewName { new_name: format!("is_{}", suffix), returns_bool: true.into(), rule: NewNameRule::Regular, }) } else { None } } /// Would-be-getter rename attempt failure result. /// /// Holds details about the reason of the failure. #[derive(Debug, Copy, Clone, PartialEq)] #[non_exhaustive] pub enum RenameError { /// The function doesn't start with `get_`. NotGetFn, /// The function uses a reserved name and can't be renamed. Reserved, } impl RenameError { pub fn is_not_get_fn(&self) -> bool { matches!(self, RenameError::NotGetFn) } pub fn is_reserved(&self) -> bool { matches!(self, RenameError::Reserved) } } impl Display for RenameError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use RenameError::*; match self { NotGetFn => write!(f, "not a get function"), Reserved => write!(f, "name is reserved"), } } } impl Error for RenameError {} #[cfg(test)] mod tests { use super::*; #[test] fn bool_getter_rename_attempt() { let new_name = try_rename_bool_getter(&"mute").unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_muted"); let new_name = try_rename_bool_getter(&"emit_eos").unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_bool_getter(&"has_entry").unwrap(); assert!(new_name.is_no_prefix()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "has_entry"); let new_name = try_rename_bool_getter(&"is_emit_eos").unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_bool_getter(&"is_activated").unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activated"); assert!(try_rename_bool_getter(&"name").is_none()); } #[test] fn bool_getter_suffix() { let new_name = rename_bool_getter(&"result"); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "result"); let new_name = rename_bool_getter(&"activable"); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activable"); let new_name = rename_bool_getter(&"mute"); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_muted"); let new_name = rename_bool_getter(&"emit_eos"); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = rename_bool_getter(&"can_acquire"); assert!(new_name.is_no_prefix()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "can_acquire"); } #[test] fn boolness_guestimation() { assert!(guesstimate_boolness_then_rename(&"result").is_none()); assert!(guesstimate_boolness_then_rename(&"name").is_none()); let new_name = guesstimate_boolness_then_rename(&"mute").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_muted"); let new_name = guesstimate_boolness_then_rename(&"does_ts").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "does_ts"); let new_name = guesstimate_boolness_then_rename(&"emit_eos").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = guesstimate_boolness_then_rename(&"emits_eos").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = guesstimate_boolness_then_rename(&"is_emits_eos").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = guesstimate_boolness_then_rename(&"is_activated").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activated"); let new_name = guesstimate_boolness_then_rename(&"activable").unwrap(); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activable"); } #[test] fn rename_getter_non_bool() { let new_name = try_rename_would_be_getter(&"get_structure", false).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_false()); assert_eq!(new_name, "structure"); let new_name = try_rename_would_be_getter(&"get_type", false).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_false()); assert_eq!(new_name, "type_"); // Bool-alike, but not a bool let new_name = try_rename_would_be_getter(&"get_activable", false).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_false()); assert_eq!(new_name, "activable"); // Prefix to postfix let new_name = try_rename_would_be_getter(&"get_mut_structure", false).unwrap(); assert!(new_name.is_fixed()); assert!(new_name.returns_bool().is_false()); assert_eq!(new_name, "structure_mut"); assert!(try_rename_would_be_getter(&"get_mut", false) .unwrap_err() .is_reserved()); assert!(try_rename_would_be_getter(&"not_a_getter", false) .unwrap_err() .is_not_get_fn()); } #[test] fn rename_getter_bool() { let new_name = try_rename_would_be_getter(&"get_structure", true).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_structure"); let new_name = try_rename_would_be_getter(&"get_type", true).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_type"); let new_name = try_rename_would_be_getter(&"get_mute", true).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_muted"); let new_name = try_rename_would_be_getter(&"get_emit_eos", true).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_would_be_getter(&"get_emits_eos", true).unwrap(); assert!(new_name.is_no_prefix()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_would_be_getter(&"get_is_emit_eos", true).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_would_be_getter(&"get_is_activated", true).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activated"); let new_name = try_rename_would_be_getter(&"get_activable", true).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activable"); let new_name = try_rename_would_be_getter(&"get_mut", true).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_mut"); let new_name = try_rename_would_be_getter(&"get_overwrite", true).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "overwrites"); let new_name = try_rename_would_be_getter(&"get_overwrite_mode", true).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_overwrite_mode"); assert!(try_rename_would_be_getter(&"not_a_getter", true) .unwrap_err() .is_not_get_fn()); } #[test] fn rename_getter_maybe_bool() { let new_name = try_rename_would_be_getter(&"get_structure", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_maybe()); assert_eq!(new_name, "structure"); let new_name = try_rename_would_be_getter(&"get_type", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_maybe()); assert_eq!(new_name, "type_"); let new_name = try_rename_would_be_getter(&"get_mute", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_muted"); let new_name = try_rename_would_be_getter(&"get_emit_eos", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_would_be_getter(&"get_emits_eos", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_no_prefix()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_would_be_getter(&"get_is_emit_eos", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_substituted()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "emits_eos"); let new_name = try_rename_would_be_getter(&"get_is_activated", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activated"); let new_name = try_rename_would_be_getter(&"get_activable", ReturnsBool::Maybe).unwrap(); assert!(new_name.is_regular()); assert!(new_name.returns_bool().is_true()); assert_eq!(new_name, "is_activable"); assert!(try_rename_would_be_getter(&"get_mut", ReturnsBool::Maybe) .unwrap_err() .is_reserved()); assert!( try_rename_would_be_getter(&"not_a_getter", ReturnsBool::Maybe) .unwrap_err() .is_not_get_fn() ); } } fix-getters-rules-0.3.2/src/lib.rs000064400000000000000000000006420000000000000151010ustar 00000000000000//! Rules definition for getter renaming and Rust crate / workspace directory filtering. //! //! # Features //! //! - **`dir-entry`** *(enabled by default)* — Directory entry filtering. #[cfg(feature = "dir-entry")] pub mod dir_entry; pub mod function; pub use function::{try_rename_getter_suffix, try_rename_would_be_getter, RenameError}; pub mod new_name; pub use new_name::{NewName, NewNameRule, ReturnsBool}; fix-getters-rules-0.3.2/src/new_name.rs000064400000000000000000000114370000000000000161300ustar 00000000000000//! Would-be-getter rename attempt sucessful result and details. use std::fmt::{self, Display}; /// Would-be-getter rename attempt sucessful result and details. /// /// Holds details about what happened and assumptions on the return type. #[derive(Debug, PartialEq)] #[non_exhaustive] pub struct NewName { pub(crate) new_name: String, pub(crate) returns_bool: ReturnsBool, pub(crate) rule: NewNameRule, } impl NewName { /// Returns the new name. pub fn as_str(&self) -> &str { self.new_name.as_str() } /// Consumes the [`NewName`] and returns the inner new name [`String`]. pub fn unwrap(self) -> String { self.new_name } /// Returns current knowledge about the getter returning exactly one `bool`. pub fn returns_bool(&self) -> ReturnsBool { self.returns_bool } /// Returns the renaming rule that was used to rename the getter. pub fn rule(&self) -> NewNameRule { self.rule } /// Returns whether renaming required fixing the name to comply with rules. /// /// Ex. `get_mut_structure` -> `structure_mut`. pub fn is_fixed(&self) -> bool { self.rule.is_fixed() } /// Returns whether renaming required substituing (part) of the name. /// /// Ex. `get_mute` -> `is_muted`. pub fn is_substituted(&self) -> bool { self.rule.is_substituted() } /// Returns whether renaming used the regular strategy. /// /// Ex.: /// * `get_name` -> `name`. /// * `get_active` -> `is_active`. pub fn is_regular(&self) -> bool { self.rule.is_regular() } /// Returns whether renaming didn't use the `is` prefix for `bool` getter. /// /// Ex.: /// * `get_has_entry` -> `has_entry`. pub fn is_no_prefix(&self) -> bool { self.rule.is_no_prefix() } } impl Display for NewName { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}{} {}", self.returns_bool, self.rule, self.new_name) } } impl> PartialEq for NewName { fn eq(&self, other: &T) -> bool { self.as_str() == other.as_ref() } } /// Rule that applied to get the [`NewName`]. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub enum NewNameRule { /// Fixed name to comply to rules. Ex. `get_mut_structure` -> `structure_mut`. Fixed, /// Regular rule: removal of the prefix or replacement with `is`. Regular, /// No prefix for `bool` getter. Ex. `get_has_entry` -> `has_entry`. NoPrefix, /// Applied substitution. Ex. `get_mute` -> `is_muted`. Substituted, } impl NewNameRule { /// Returns whether renaming required fixing the name to comply with rules. /// /// Ex. `get_mut_structure` -> `structure_mut`. pub fn is_fixed(&self) -> bool { matches!(self, NewNameRule::Fixed) } /// Returns whether renaming required substituing (part) of the name. /// /// Ex. `get_mute` -> `is_muted`. pub fn is_substituted(&self) -> bool { matches!(self, NewNameRule::Substituted) } /// Returns whether renaming used the regular strategy. /// /// Ex.: /// * `get_name` -> `name`. /// * `get_active` -> `is_active`. pub fn is_regular(&self) -> bool { matches!(self, NewNameRule::Regular) } /// Returns whether renaming didn't use the `is` prefix for `bool` getter. /// /// Ex.: /// * `get_has_entry` -> `has_entry`. pub fn is_no_prefix(&self) -> bool { matches!(self, NewNameRule::NoPrefix) } } impl Display for NewNameRule { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use NewNameRule::*; match self { Fixed => f.write_str("fixed as"), Substituted => f.write_str("substituted with"), NoPrefix => f.write_str("kept as"), Regular => f.write_str("renamed as"), } } } /// Indicates current knowledge about the getter returning exaclty one `bool`. #[derive(Debug, Copy, Clone, PartialEq)] pub enum ReturnsBool { True, False, Maybe, } impl ReturnsBool { pub fn is_true(&self) -> bool { matches!(self, ReturnsBool::True) } pub fn is_false(&self) -> bool { matches!(self, ReturnsBool::False) } pub fn is_maybe(&self) -> bool { matches!(self, ReturnsBool::Maybe) } } impl From for ReturnsBool { fn from(returns_bool: bool) -> Self { if returns_bool { ReturnsBool::True } else { ReturnsBool::False } } } impl Display for ReturnsBool { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { use ReturnsBool::*; match self { False => Ok(()), True => f.write_str("-> bool "), Maybe => f.write_str("-> ? "), } } }