diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
commit | 698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch) | |
tree | 173a775858bd501c378080a10dca74132f05bc50 /vendor/rustfix | |
parent | Initial commit. (diff) | |
download | rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip |
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/rustfix')
-rw-r--r-- | vendor/rustfix/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | vendor/rustfix/Cargo.toml | 60 | ||||
-rw-r--r-- | vendor/rustfix/Changelog.md | 79 | ||||
-rw-r--r-- | vendor/rustfix/LICENSE-APACHE | 202 | ||||
-rw-r--r-- | vendor/rustfix/LICENSE-MIT | 21 | ||||
-rw-r--r-- | vendor/rustfix/Readme.md | 41 | ||||
-rw-r--r-- | vendor/rustfix/proptest-regressions/replace.txt | 8 | ||||
-rw-r--r-- | vendor/rustfix/src/diagnostics.rs | 89 | ||||
-rw-r--r-- | vendor/rustfix/src/lib.rs | 263 | ||||
-rw-r--r-- | vendor/rustfix/src/replace.rs | 323 |
10 files changed, 1087 insertions, 0 deletions
diff --git a/vendor/rustfix/.cargo-checksum.json b/vendor/rustfix/.cargo-checksum.json new file mode 100644 index 000000000..001cb08d5 --- /dev/null +++ b/vendor/rustfix/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"2dd7ae4c38e488cc4b65c5c5c5bc2b2b84f9ac662e5300a5eba4d4b701219426","Changelog.md":"78b0b218038a68313eaf853aea4dd704efaea95d8c5b9a4590aeecd39564bc3b","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"06a5d0a2bfba711b0c19fa86c481bf08b38a84bd31a86648d9e207287d941e36","Readme.md":"f6b9395fb6554cc43fd182e89eef700c7ac11eef5d17b99cb0d4778ed76206b4","proptest-regressions/replace.txt":"9335379703ca7f8aa978c88d40c966cad42a592fed3e0b56513e9686f661232d","src/diagnostics.rs":"de3ec2eea7e01724dd859e76e3a7876f752bd581cd07dc54170543dacf01101a","src/lib.rs":"ab977e131a2ac0b8935f97152947019e01f0b5a76e2bb18d6bb5a2c07e71a306","src/replace.rs":"0be71a8ef286398fdc956dab1f98af0d61a2ef95303caa284c3f9e9bbfa07c33"},"package":"ecd2853d9e26988467753bd9912c3a126f642d05d229a4b53f5752ee36c56481"}
\ No newline at end of file diff --git a/vendor/rustfix/Cargo.toml b/vendor/rustfix/Cargo.toml new file mode 100644 index 000000000..782dc7b55 --- /dev/null +++ b/vendor/rustfix/Cargo.toml @@ -0,0 +1,60 @@ +# 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" +name = "rustfix" +version = "0.6.1" +authors = [ + "Pascal Hertleif <killercup@gmail.com>", + "Oliver Schneider <oli-obk@users.noreply.github.com>", +] +exclude = [ + "etc/*", + "examples/*", + "tests/*", +] +description = "Automatically apply the suggestions made by rustc" +documentation = "https://docs.rs/rustfix" +readme = "Readme.md" +license = "Apache-2.0/MIT" +repository = "https://github.com/rust-lang-nursery/rustfix" + +[dependencies.anyhow] +version = "1.0.6" + +[dependencies.log] +version = "0.4.1" + +[dependencies.serde] +version = "1.0" +features = ["derive"] + +[dependencies.serde_json] +version = "1.0" + +[dev-dependencies.duct] +version = "0.9" + +[dev-dependencies.env_logger] +version = "0.5.0-rc.1" + +[dev-dependencies.log] +version = "0.4.1" + +[dev-dependencies.proptest] +version = "0.7.0" + +[dev-dependencies.similar] +version = "0.4.0" + +[dev-dependencies.tempfile] +version = "3" diff --git a/vendor/rustfix/Changelog.md b/vendor/rustfix/Changelog.md new file mode 100644 index 000000000..1b57320e6 --- /dev/null +++ b/vendor/rustfix/Changelog.md @@ -0,0 +1,79 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.4.6] - 2019-07-16 + +### Changed + +Internal changes: + +- Change example to automatically determine filename +- Migrate to Rust 2018 +- use `derive` feature over `serde_derive` crate + +## [0.4.5] - 2019-03-26 + +### Added + +- Implement common traits for Diagnostic and related types + +### Fixed + +- Fix out of bounds access in parse_snippet + +## [0.4.4] - 2018-12-13 + +### Added + +- Make Diagnostic::rendered public. + +### Changed + +- Revert faulty "Allow multiple solutions in a suggestion" + +## [0.4.3] - 2018-12-09 - *yanked!* + +### Added + +- Allow multiple solutions in a suggestion + +### Changed + +- use `RUSTC` environment var if present + +## [0.4.2] - 2018-07-31 + +### Added + +- Expose an interface to apply fixes on-by-one + +### Changed + +- Handle invalid snippets instead of panicking + +## [0.4.1] - 2018-07-26 + +### Changed + +- Ignore duplicate replacements + +## [0.4.0] - 2018-05-23 + +### Changed + +- Filter by machine applicability by default + +[Unreleased]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.6...HEAD +[0.4.6]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.5...rustfix-0.4.6 +[0.4.5]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.4...rustfix-0.4.5 +[0.4.4]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.3...rustfix-0.4.4 +[0.4.3]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.2...rustfix-0.4.3 +[0.4.2]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.1...rustfix-0.4.2 +[0.4.1]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.0...rustfix-0.4.1 +[0.4.0]: https://github.com/rust-lang-nursery/rustfix/compare/rustfix-0.4.0 diff --git a/vendor/rustfix/LICENSE-APACHE b/vendor/rustfix/LICENSE-APACHE new file mode 100644 index 000000000..8f71f43fe --- /dev/null +++ b/vendor/rustfix/LICENSE-APACHE @@ -0,0 +1,202 @@ + 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. + diff --git a/vendor/rustfix/LICENSE-MIT b/vendor/rustfix/LICENSE-MIT new file mode 100644 index 000000000..458e9c6ce --- /dev/null +++ b/vendor/rustfix/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Pascal Hertleif + +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. diff --git a/vendor/rustfix/Readme.md b/vendor/rustfix/Readme.md new file mode 100644 index 000000000..541b9d4da --- /dev/null +++ b/vendor/rustfix/Readme.md @@ -0,0 +1,41 @@ +# rustfix + +The goal of this tool is to read and apply the suggestions made by rustc. + +## Current status + +Currently, rustfix is split into two crates: + +- `rustfix`, a library for consuming and applying suggestions in the format that `rustc` outputs +- and `cargo-fix`, a binary that works as cargo subcommand and that end users will use to fix their code. + +The magic of rustfix is entirely dependent on the diagnostics implemented in the Rust compiler (and external lints, like [clippy]). + +[clippy]: https://github.com/rust-lang-nursery/rust-clippy + +## Installation + +To use the rustfix library, add it to your `Cargo.toml`. + +To get the tool to automatically fix warnings in, run `cargo install cargo-fix`. This will give you `cargo fix`. + +## Using `cargo fix --edition` to transition to Rust 2021 + +Instructions on how to use this tool to transition a crate to Rust 2021 can be +found [in the Rust Edition Guide.](https://rust-lang-nursery.github.io/edition-guide/editions/transitioning-an-existing-project-to-a-new-edition.html) + +## License + +Licensed under either of + +- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally +submitted for inclusion in the work by you, as defined in the Apache-2.0 +license, shall be dual licensed as above, without any additional terms or +conditions. diff --git a/vendor/rustfix/proptest-regressions/replace.txt b/vendor/rustfix/proptest-regressions/replace.txt new file mode 100644 index 000000000..fc5bd1a8b --- /dev/null +++ b/vendor/rustfix/proptest-regressions/replace.txt @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +xs 358148376 3634975642 2528447681 3675516813 # shrinks to ref s = "" +xs 3127423015 3362740891 2605681441 2390162043 # shrinks to ref data = "", ref replacements = [(0..0, [])] diff --git a/vendor/rustfix/src/diagnostics.rs b/vendor/rustfix/src/diagnostics.rs new file mode 100644 index 000000000..f745b0b2a --- /dev/null +++ b/vendor/rustfix/src/diagnostics.rs @@ -0,0 +1,89 @@ +//! Rustc Diagnostic JSON Output +//! +//! The following data types are copied from [rust-lang/rust](https://github.com/rust-lang/rust/blob/de78655bca47cac8e783dbb563e7e5c25c1fae40/src/libsyntax/json.rs) + +use serde::Deserialize; + +#[derive(Clone, Deserialize, Debug, Hash, Eq, PartialEq)] +pub struct Diagnostic { + /// The primary error message. + pub message: String, + pub code: Option<DiagnosticCode>, + /// "error: internal compiler error", "error", "warning", "note", "help". + level: String, + pub spans: Vec<DiagnosticSpan>, + /// Associated diagnostic messages. + pub children: Vec<Diagnostic>, + /// The message as rustc would render it. Currently this is only + /// `Some` for "suggestions", but eventually it will include all + /// snippets. + pub rendered: Option<String>, +} + +#[derive(Clone, Deserialize, Debug, Hash, Eq, PartialEq)] +pub struct DiagnosticSpan { + pub file_name: String, + pub byte_start: u32, + pub byte_end: u32, + /// 1-based. + pub line_start: usize, + pub line_end: usize, + /// 1-based, character offset. + pub column_start: usize, + pub column_end: usize, + /// Is this a "primary" span -- meaning the point, or one of the points, + /// where the error occurred? + pub is_primary: bool, + /// Source text from the start of line_start to the end of line_end. + pub text: Vec<DiagnosticSpanLine>, + /// Label that should be placed at this location (if any) + label: Option<String>, + /// If we are suggesting a replacement, this will contain text + /// that should be sliced in atop this span. You may prefer to + /// load the fully rendered version from the parent `Diagnostic`, + /// however. + pub suggested_replacement: Option<String>, + pub suggestion_applicability: Option<Applicability>, + /// Macro invocations that created the code at this span, if any. + expansion: Option<Box<DiagnosticSpanMacroExpansion>>, +} + +#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Hash, Eq)] +pub enum Applicability { + MachineApplicable, + HasPlaceholders, + MaybeIncorrect, + Unspecified, +} + +#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)] +pub struct DiagnosticSpanLine { + pub text: String, + + /// 1-based, character offset in self.text. + pub highlight_start: usize, + + pub highlight_end: usize, +} + +#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)] +struct DiagnosticSpanMacroExpansion { + /// span where macro was applied to generate this code; note that + /// this may itself derive from a macro (if + /// `span.expansion.is_some()`) + span: DiagnosticSpan, + + /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]") + macro_decl_name: String, + + /// span where macro was defined (if known) + def_site_span: Option<DiagnosticSpan>, +} + +#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)] +pub struct DiagnosticCode { + /// The code itself. + pub code: String, + /// An explanation for the code. + explanation: Option<String>, +} diff --git a/vendor/rustfix/src/lib.rs b/vendor/rustfix/src/lib.rs new file mode 100644 index 000000000..f83223306 --- /dev/null +++ b/vendor/rustfix/src/lib.rs @@ -0,0 +1,263 @@ +#![warn(rust_2018_idioms)] + +#[macro_use] +extern crate log; +#[cfg(test)] +#[macro_use] +extern crate proptest; + +use std::collections::HashSet; +use std::ops::Range; + +use anyhow::Error; + +pub mod diagnostics; +use crate::diagnostics::{Diagnostic, DiagnosticSpan}; +mod replace; + +#[derive(Debug, Clone, Copy)] +pub enum Filter { + MachineApplicableOnly, + Everything, +} + +pub fn get_suggestions_from_json<S: ::std::hash::BuildHasher>( + input: &str, + only: &HashSet<String, S>, + filter: Filter, +) -> serde_json::error::Result<Vec<Suggestion>> { + let mut result = Vec::new(); + for cargo_msg in serde_json::Deserializer::from_str(input).into_iter::<Diagnostic>() { + // One diagnostic line might have multiple suggestions + result.extend(collect_suggestions(&cargo_msg?, only, filter)); + } + Ok(result) +} + +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub struct LinePosition { + pub line: usize, + pub column: usize, +} + +impl std::fmt::Display for LinePosition { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}", self.line, self.column) + } +} + +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub struct LineRange { + pub start: LinePosition, + pub end: LinePosition, +} + +impl std::fmt::Display for LineRange { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}-{}", self.start, self.end) + } +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +/// An error/warning and possible solutions for fixing it +pub struct Suggestion { + pub message: String, + pub snippets: Vec<Snippet>, + pub solutions: Vec<Solution>, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct Solution { + pub message: String, + pub replacements: Vec<Replacement>, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct Snippet { + pub file_name: String, + pub line_range: LineRange, + pub range: Range<usize>, + /// leading surrounding text, text to replace, trailing surrounding text + /// + /// This split is useful for higlighting the part that gets replaced + pub text: (String, String, String), +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct Replacement { + pub snippet: Snippet, + pub replacement: String, +} + +fn parse_snippet(span: &DiagnosticSpan) -> Option<Snippet> { + // unindent the snippet + let indent = span + .text + .iter() + .map(|line| { + let indent = line + .text + .chars() + .take_while(|&c| char::is_whitespace(c)) + .count(); + std::cmp::min(indent, line.highlight_start - 1) + }) + .min()?; + + let text_slice = span.text[0].text.chars().collect::<Vec<char>>(); + + // We subtract `1` because these highlights are 1-based + // Check the `min` so that it doesn't attempt to index out-of-bounds when + // the span points to the "end" of the line. For example, a line of + // "foo\n" with a highlight_start of 5 is intended to highlight *after* + // the line. This needs to compensate since the newline has been removed + // from the text slice. + let start = (span.text[0].highlight_start - 1).min(text_slice.len()); + let end = (span.text[0].highlight_end - 1).min(text_slice.len()); + let lead = text_slice[indent..start].iter().collect(); + let mut body: String = text_slice[start..end].iter().collect(); + + for line in span.text.iter().take(span.text.len() - 1).skip(1) { + body.push('\n'); + body.push_str(&line.text[indent..]); + } + let mut tail = String::new(); + let last = &span.text[span.text.len() - 1]; + + // If we get a DiagnosticSpanLine where highlight_end > text.len(), we prevent an 'out of + // bounds' access by making sure the index is within the array bounds. + // `saturating_sub` is used in case of an empty file + let last_tail_index = last.highlight_end.min(last.text.len()).saturating_sub(1); + let last_slice = last.text.chars().collect::<Vec<char>>(); + + if span.text.len() > 1 { + body.push('\n'); + body.push_str( + &last_slice[indent..last_tail_index] + .iter() + .collect::<String>(), + ); + } + tail.push_str(&last_slice[last_tail_index..].iter().collect::<String>()); + Some(Snippet { + file_name: span.file_name.clone(), + line_range: LineRange { + start: LinePosition { + line: span.line_start, + column: span.column_start, + }, + end: LinePosition { + line: span.line_end, + column: span.column_end, + }, + }, + range: (span.byte_start as usize)..(span.byte_end as usize), + text: (lead, body, tail), + }) +} + +fn collect_span(span: &DiagnosticSpan) -> Option<Replacement> { + let snippet = parse_snippet(span)?; + let replacement = span.suggested_replacement.clone()?; + Some(Replacement { + snippet, + replacement, + }) +} + +pub fn collect_suggestions<S: ::std::hash::BuildHasher>( + diagnostic: &Diagnostic, + only: &HashSet<String, S>, + filter: Filter, +) -> Option<Suggestion> { + if !only.is_empty() { + if let Some(ref code) = diagnostic.code { + if !only.contains(&code.code) { + // This is not the code we are looking for + return None; + } + } else { + // No code, probably a weird builtin warning/error + return None; + } + } + + let snippets = diagnostic.spans.iter().filter_map(parse_snippet).collect(); + + let solutions: Vec<_> = diagnostic + .children + .iter() + .filter_map(|child| { + let replacements: Vec<_> = child + .spans + .iter() + .filter(|span| { + use crate::diagnostics::Applicability::*; + use crate::Filter::*; + + match (filter, &span.suggestion_applicability) { + (MachineApplicableOnly, Some(MachineApplicable)) => true, + (MachineApplicableOnly, _) => false, + (Everything, _) => true, + } + }) + .filter_map(collect_span) + .collect(); + if !replacements.is_empty() { + Some(Solution { + message: child.message.clone(), + replacements, + }) + } else { + None + } + }) + .collect(); + + if solutions.is_empty() { + None + } else { + Some(Suggestion { + message: diagnostic.message.clone(), + snippets, + solutions, + }) + } +} + +pub struct CodeFix { + data: replace::Data, +} + +impl CodeFix { + pub fn new(s: &str) -> CodeFix { + CodeFix { + data: replace::Data::new(s.as_bytes()), + } + } + + pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> { + for sol in &suggestion.solutions { + for r in &sol.replacements { + self.data.replace_range( + r.snippet.range.start, + r.snippet.range.end.saturating_sub(1), + r.replacement.as_bytes(), + )?; + } + } + Ok(()) + } + + pub fn finish(&self) -> Result<String, Error> { + Ok(String::from_utf8(self.data.to_vec())?) + } +} + +pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result<String, Error> { + let mut fix = CodeFix::new(code); + for suggestion in suggestions.iter().rev() { + fix.apply(suggestion)?; + } + fix.finish() +} diff --git a/vendor/rustfix/src/replace.rs b/vendor/rustfix/src/replace.rs new file mode 100644 index 000000000..8deba5e9f --- /dev/null +++ b/vendor/rustfix/src/replace.rs @@ -0,0 +1,323 @@ +//! A small module giving you a simple container that allows easy and cheap +//! replacement of parts of its content, with the ability to prevent changing +//! the same parts multiple times. + +use anyhow::{anyhow, ensure, Error}; +use std::rc::Rc; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum State { + Initial, + Replaced(Rc<[u8]>), + Inserted(Rc<[u8]>), +} + +impl State { + fn is_inserted(&self) -> bool { + matches!(*self, State::Inserted(..)) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Span { + /// Start of this span in parent data + start: usize, + /// up to end including + end: usize, + data: State, +} + +/// A container that allows easily replacing chunks of its data +#[derive(Debug, Clone, Default)] +pub struct Data { + original: Vec<u8>, + parts: Vec<Span>, +} + +impl Data { + /// Create a new data container from a slice of bytes + pub fn new(data: &[u8]) -> Self { + Data { + original: data.into(), + parts: vec![Span { + data: State::Initial, + start: 0, + end: data.len().saturating_sub(1), + }], + } + } + + /// Render this data as a vector of bytes + pub fn to_vec(&self) -> Vec<u8> { + if self.original.is_empty() { + return Vec::new(); + } + + self.parts.iter().fold(Vec::new(), |mut acc, d| { + match d.data { + State::Initial => acc.extend_from_slice(&self.original[d.start..=d.end]), + State::Replaced(ref d) | State::Inserted(ref d) => acc.extend_from_slice(d), + }; + acc + }) + } + + /// Replace a chunk of data with the given slice, erroring when this part + /// was already changed previously. + pub fn replace_range( + &mut self, + from: usize, + up_to_and_including: usize, + data: &[u8], + ) -> Result<(), Error> { + let exclusive_end = up_to_and_including + 1; + + ensure!( + from <= exclusive_end, + "Invalid range {}...{}, start is larger than end", + from, + up_to_and_including + ); + + ensure!( + up_to_and_including <= self.original.len(), + "Invalid range {}...{} given, original data is only {} byte long", + from, + up_to_and_including, + self.original.len() + ); + + let insert_only = from == exclusive_end; + + // Since we error out when replacing an already replaced chunk of data, + // we can take some shortcuts here. For example, there can be no + // overlapping replacements -- we _always_ split a chunk of 'initial' + // data into three[^empty] parts, and there can't ever be two 'initial' + // parts touching. + // + // [^empty]: Leading and trailing ones might be empty if we replace + // the whole chunk. As an optimization and without loss of generality we + // don't add empty parts. + let new_parts = { + let index_of_part_to_split = self + .parts + .iter() + .position(|p| { + !p.data.is_inserted() && p.start <= from && p.end >= up_to_and_including + }) + .ok_or_else(|| { + use log::Level::Debug; + if log_enabled!(Debug) { + let slices = self + .parts + .iter() + .map(|p| { + ( + p.start, + p.end, + match p.data { + State::Initial => "initial", + State::Replaced(..) => "replaced", + State::Inserted(..) => "inserted", + }, + ) + }) + .collect::<Vec<_>>(); + debug!( + "no single slice covering {}...{}, current slices: {:?}", + from, up_to_and_including, slices, + ); + } + + anyhow!( + "Could not replace range {}...{} in file \ + -- maybe parts of it were already replaced?", + from, + up_to_and_including + ) + })?; + + let part_to_split = &self.parts[index_of_part_to_split]; + + // If this replacement matches exactly the part that we would + // otherwise split then we ignore this for now. This means that you + // can replace the exact same range with the exact same content + // multiple times and we'll process and allow it. + // + // This is currently done to alleviate issues like + // rust-lang/rust#51211 although this clause likely wants to be + // removed if that's fixed deeper in the compiler. + if part_to_split.start == from && part_to_split.end == up_to_and_including { + if let State::Replaced(ref replacement) = part_to_split.data { + if &**replacement == data { + return Ok(()); + } + } + } + + ensure!( + part_to_split.data == State::Initial, + "Cannot replace slice of data that was already replaced" + ); + + let mut new_parts = Vec::with_capacity(self.parts.len() + 2); + + // Previous parts + if let Some(ps) = self.parts.get(..index_of_part_to_split) { + new_parts.extend_from_slice(ps); + } + + // Keep initial data on left side of part + if from > part_to_split.start { + new_parts.push(Span { + start: part_to_split.start, + end: from.saturating_sub(1), + data: State::Initial, + }); + } + + // New part + new_parts.push(Span { + start: from, + end: up_to_and_including, + data: if insert_only { + State::Inserted(data.into()) + } else { + State::Replaced(data.into()) + }, + }); + + // Keep initial data on right side of part + if up_to_and_including < part_to_split.end { + new_parts.push(Span { + start: up_to_and_including + 1, + end: part_to_split.end, + data: State::Initial, + }); + } + + // Following parts + if let Some(ps) = self.parts.get(index_of_part_to_split + 1..) { + new_parts.extend_from_slice(ps); + } + + new_parts + }; + + self.parts = new_parts; + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + fn str(i: &[u8]) -> &str { + ::std::str::from_utf8(i).unwrap() + } + + #[test] + fn replace_some_stuff() { + let mut d = Data::new(b"foo bar baz"); + d.replace_range(4, 6, b"lol").unwrap(); + assert_eq!("foo lol baz", str(&d.to_vec())); + } + + #[test] + fn replace_a_single_char() { + let mut d = Data::new(b"let y = true;"); + d.replace_range(4, 4, b"mut y").unwrap(); + assert_eq!("let mut y = true;", str(&d.to_vec())); + } + + #[test] + fn replace_multiple_lines() { + let mut d = Data::new(b"lorem\nipsum\ndolor"); + + d.replace_range(6, 10, b"lol").unwrap(); + assert_eq!("lorem\nlol\ndolor", str(&d.to_vec())); + + d.replace_range(12, 16, b"lol").unwrap(); + assert_eq!("lorem\nlol\nlol", str(&d.to_vec())); + } + + #[test] + fn replace_multiple_lines_with_insert_only() { + let mut d = Data::new(b"foo!"); + + d.replace_range(3, 2, b"bar").unwrap(); + assert_eq!("foobar!", str(&d.to_vec())); + + d.replace_range(0, 2, b"baz").unwrap(); + assert_eq!("bazbar!", str(&d.to_vec())); + + d.replace_range(3, 3, b"?").unwrap(); + assert_eq!("bazbar?", str(&d.to_vec())); + } + + #[test] + fn replace_invalid_range() { + let mut d = Data::new(b"foo!"); + + assert!(d.replace_range(2, 0, b"bar").is_err()); + assert!(d.replace_range(0, 2, b"bar").is_ok()); + } + + #[test] + fn empty_to_vec_roundtrip() { + let s = ""; + assert_eq!(s.as_bytes(), Data::new(s.as_bytes()).to_vec().as_slice()); + } + + #[test] + #[should_panic(expected = "Cannot replace slice of data that was already replaced")] + fn replace_overlapping_stuff_errs() { + let mut d = Data::new(b"foo bar baz"); + + d.replace_range(4, 6, b"lol").unwrap(); + assert_eq!("foo lol baz", str(&d.to_vec())); + + d.replace_range(4, 6, b"lol2").unwrap(); + } + + #[test] + #[should_panic(expected = "original data is only 3 byte long")] + fn broken_replacements() { + let mut d = Data::new(b"foo"); + d.replace_range(4, 7, b"lol").unwrap(); + } + + #[test] + fn replace_same_twice() { + let mut d = Data::new(b"foo"); + d.replace_range(0, 0, b"b").unwrap(); + d.replace_range(0, 0, b"b").unwrap(); + assert_eq!("boo", str(&d.to_vec())); + } + + proptest! { + #[test] + #[ignore] + fn new_to_vec_roundtrip(ref s in "\\PC*") { + assert_eq!(s.as_bytes(), Data::new(s.as_bytes()).to_vec().as_slice()); + } + + #[test] + #[ignore] + fn replace_random_chunks( + ref data in "\\PC*", + ref replacements in prop::collection::vec( + (any::<::std::ops::Range<usize>>(), any::<Vec<u8>>()), + 1..1337, + ) + ) { + let mut d = Data::new(data.as_bytes()); + for &(ref range, ref bytes) in replacements { + let _ = d.replace_range(range.start, range.end, bytes); + } + } + } +} |