rustfix-0.9.0/.cargo_vcs_info.json0000644000000001540000000000100125460ustar { "git": { "sha1": "66221abdeca2002d318fde6efff516aab091df0e" }, "path_in_vcs": "crates/rustfix" }rustfix-0.9.0/CHANGELOG.md000064400000000000000000000035721046102023000131560ustar 00000000000000# 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 rustfix-0.9.0/Cargo.lock0000644000000411220000000000100105210ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "anyhow" version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "autocfg" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "bit-set" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" dependencies = [ "bit-vec", ] [[package]] name = "bit-vec" version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "errno" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" [[package]] name = "libm" version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "matchers" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" dependencies = [ "regex-automata 0.1.10", ] [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "nu-ansi-term" version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" dependencies = [ "overload", "winapi", ] [[package]] name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", "libm", ] [[package]] name = "once_cell" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "overload" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "pin-project-lite" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "ppv-lite86" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "proptest" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c2511913b88df1637da85cc8d96ec8e43a3f8bb8ccb71ee1ac240d6f3df58d" dependencies = [ "bit-set", "bit-vec", "bitflags", "lazy_static", "num-traits", "rand", "rand_chacha", "rand_xorshift", "regex-syntax 0.8.4", "rusty-fork", "tempfile", "unarray", ] [[package]] name = "quick-error" version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", "rand_chacha", "rand_core", ] [[package]] name = "rand_chacha" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "rand_xorshift" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" dependencies = [ "rand_core", ] [[package]] name = "regex" version = "1.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" dependencies = [ "aho-corasick", "memchr", "regex-automata 0.4.7", "regex-syntax 0.8.4", ] [[package]] name = "regex-automata" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" dependencies = [ "regex-syntax 0.6.29", ] [[package]] name = "regex-automata" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" dependencies = [ "aho-corasick", "memchr", "regex-syntax 0.8.4", ] [[package]] name = "regex-syntax" version = "0.6.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" [[package]] name = "rustfix" version = "0.9.0" dependencies = [ "anyhow", "proptest", "serde", "serde_json", "similar", "tempfile", "thiserror", "tracing", "tracing-subscriber", ] [[package]] name = "rustix" version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "rusty-fork" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f" dependencies = [ "fnv", "quick-error", "tempfile", "wait-timeout", ] [[package]] name = "ryu" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "serde" version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.121" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ab380d7d9f22ef3f21ad3e6c1ebe8e4fc7a2000ccba2e4d71fc96f15b2cb609" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "sharded-slab" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" dependencies = [ "lazy_static", ] [[package]] name = "similar" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" [[package]] name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "syn" version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", "rustix", "windows-sys", ] [[package]] name = "thiserror" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "thread_local" version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ "cfg-if", "once_cell", ] [[package]] name = "tracing" version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "pin-project-lite", "tracing-core", ] [[package]] name = "tracing-core" version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", "valuable", ] [[package]] name = "tracing-log" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" dependencies = [ "log", "once_cell", "tracing-core", ] [[package]] name = "tracing-subscriber" version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" dependencies = [ "matchers", "nu-ansi-term", "once_cell", "regex", "sharded-slab", "smallvec", "thread_local", "tracing", "tracing-core", "tracing-log", ] [[package]] name = "unarray" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" [[package]] name = "unicode-ident" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "valuable" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" [[package]] name = "wait-timeout" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" dependencies = [ "libc", ] [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" rustfix-0.9.0/Cargo.toml0000644000000036670000000000100105600ustar # 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 = "2021" rust-version = "1.79" name = "rustfix" version = "0.9.0" authors = [ "Pascal Hertleif ", "Oliver Schneider ", ] build = false exclude = [ "examples/*", "tests/*", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Automatically apply the suggestions made by rustc" homepage = "https://github.com/rust-lang/cargo" documentation = "https://docs.rs/rustfix" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/cargo" [lib] name = "rustfix" path = "src/lib.rs" [dependencies.serde] version = "1.0.204" features = ["derive"] [dependencies.serde_json] version = "1.0.120" [dependencies.thiserror] version = "1.0.63" [dependencies.tracing] version = "0.1.40" features = ["std"] default-features = false [dev-dependencies.anyhow] version = "1.0.86" [dev-dependencies.proptest] version = "1.5.0" [dev-dependencies.similar] version = "2.6.0" [dev-dependencies.tempfile] version = "3.10.1" [dev-dependencies.tracing-subscriber] version = "0.3.18" features = ["env-filter"] [lints.clippy] dbg_macro = "warn" disallowed_methods = "warn" print_stderr = "warn" print_stdout = "warn" self_named_module_files = "warn" [lints.clippy.all] level = "allow" priority = -2 [lints.clippy.correctness] level = "warn" priority = -1 [lints.rust] rust_2018_idioms = "warn" [lints.rustdoc] private_intra_doc_links = "allow" rustfix-0.9.0/Cargo.toml.orig000064400000000000000000000014171046102023000142300ustar 00000000000000[package] name = "rustfix" version = "0.9.0" authors = [ "Pascal Hertleif ", "Oliver Schneider ", ] rust-version.workspace = true edition.workspace = true license.workspace = true homepage.workspace = true repository.workspace = true description = "Automatically apply the suggestions made by rustc" documentation = "https://docs.rs/rustfix" exclude = [ "examples/*", "tests/*", ] [dependencies] serde = { workspace = true, features = ["derive"] } serde_json.workspace = true thiserror.workspace = true tracing.workspace = true [dev-dependencies] anyhow.workspace = true proptest.workspace = true similar.workspace = true tempfile.workspace = true tracing-subscriber.workspace = true [lints] workspace = true rustfix-0.9.0/LICENSE-APACHE000064400000000000000000000251541046102023000132710ustar 00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/LICENSE-2.0 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 https://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. rustfix-0.9.0/LICENSE-MIT000064400000000000000000000017771046102023000130060ustar 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. rustfix-0.9.0/README.md000064400000000000000000000027721046102023000126250ustar 00000000000000# rustfix [![Latest Version](https://img.shields.io/crates/v/rustfix.svg)](https://crates.io/crates/rustfix) [![Rust Documentation](https://docs.rs/rustfix/badge.svg)](https://docs.rs/rustfix) Rustfix is a library defining useful structures that represent fix suggestions from rustc. This is a low-level library. You pass it the JSON output from `rustc`, and you can then use it to apply suggestions to in-memory strings. This library doesn't execute commands, or read or write from the filesystem. If you are looking for the [`cargo fix`] implementation, the core of it is located in [`cargo::ops::fix`]. > This crate is maintained by the Cargo team, primarily for use by Cargo and Rust compiler test suite > and not intended for external use (except as a transitive dependency). This > crate may make major changes to its APIs or be deprecated without warning. [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html [`cargo::ops::fix`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/ops/fix.rs ## License Licensed under either of - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 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. rustfix-0.9.0/proptest-regressions/replace.txt000064400000000000000000000007301046102023000177330ustar 00000000000000# 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, [])] rustfix-0.9.0/src/diagnostics.rs000064400000000000000000000104411046102023000150020ustar 00000000000000//! Rustc Diagnostic JSON Output. //! //! The following data types are copied from [rust-lang/rust](https://github.com/rust-lang/rust/blob/4fd68eb47bad1c121417ac4450b2f0456150db86/compiler/rustc_errors/src/json.rs). //! //! For examples of the JSON output, see JSON fixture files under `tests/` directory. use serde::Deserialize; /// The root diagnostic JSON output emitted by the compiler. #[derive(Clone, Deserialize, Debug, Hash, Eq, PartialEq)] pub struct Diagnostic { /// The primary error message. pub message: String, pub code: Option, /// "error: internal compiler error", "error", "warning", "note", "help". level: String, pub spans: Vec, /// Associated diagnostic messages. pub children: Vec, /// The message as rustc would render it. pub rendered: Option, } /// Span information of a diagnostic item. #[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, /// Label that should be placed at this location (if any) label: Option, /// If we are suggesting a replacement, this will contain text /// that should be sliced in atop this span. pub suggested_replacement: Option, /// If the suggestion is approximate pub suggestion_applicability: Option, /// Macro invocations that created the code at this span, if any. expansion: Option>, } /// Indicates the confidence in the correctness of a suggestion. /// /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion /// to determine whether it should be automatically applied or if the user should be consulted /// before applying the suggestion. #[derive(Copy, Clone, Debug, PartialEq, Deserialize, Hash, Eq)] pub enum Applicability { /// The suggestion is definitely what the user intended, or maintains the exact meaning of the code. /// This suggestion should be automatically applied. /// /// In case of multiple `MachineApplicable` suggestions (whether as part of /// the same `multipart_suggestion` or not), all of them should be /// automatically applied. MachineApplicable, /// The suggestion may be what the user intended, but it is uncertain. The suggestion should /// result in valid Rust code if it is applied. MaybeIncorrect, /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion /// cannot be applied automatically because it will not result in valid Rust code. The user /// will need to fill in the placeholders. HasPlaceholders, /// The applicability of the suggestion is unknown. Unspecified, } /// Span information of a single line. #[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, } /// Span information for macro expansions. #[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, } /// The error code emitted by the compiler. See [Rust error codes index]. /// /// [Rust error codes index]: https://doc.rust-lang.org/error_codes/error-index.html #[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)] pub struct DiagnosticCode { /// The code itself. pub code: String, /// An explanation for the code. explanation: Option, } rustfix-0.9.0/src/error.rs000064400000000000000000000014411046102023000136240ustar 00000000000000//! Error types. use std::ops::Range; #[non_exhaustive] #[derive(Debug, thiserror::Error)] pub enum Error { #[error("invalid range {0:?}, start is larger than end")] InvalidRange(Range), #[error("invalid range {0:?}, original data is only {1} byte long")] DataLengthExceeded(Range, usize), #[non_exhaustive] #[error("cannot replace slice of data that was already replaced")] AlreadyReplaced { /// The location of the intended replacement. range: Range, /// Whether the modification exactly matches (both range and data) the one it conflicts with. /// Some clients may wish to simply ignore this condition. is_identical: bool, }, #[error(transparent)] Utf8(#[from] std::string::FromUtf8Error), } rustfix-0.9.0/src/lib.rs000064400000000000000000000226551046102023000132530ustar 00000000000000//! Library for applying diagnostic suggestions to source code. //! //! This is a low-level library. You pass it the [JSON output] from `rustc`, //! and you can then use it to apply suggestions to in-memory strings. //! This library doesn't execute commands, or read or write from the filesystem. //! //! If you are looking for the [`cargo fix`] implementation, the core of it is //! located in [`cargo::ops::fix`]. //! //! [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html //! [`cargo::ops::fix`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/ops/fix.rs //! [JSON output]: diagnostics //! //! The general outline of how to use this library is: //! //! 1. Call `rustc` and collect the JSON data. //! 2. Pass the json data to [`get_suggestions_from_json`]. //! 3. Create a [`CodeFix`] with the source of a file to modify. //! 4. Call [`CodeFix::apply`] to apply a change. //! 5. Call [`CodeFix::finish`] to get the result and write it back to disk. //! //! > This crate is maintained by the Cargo team, primarily for use by Cargo and Rust compiler test suite //! > and not intended for external use (except as a transitive dependency). This //! > crate may make major changes to its APIs or be deprecated without warning. use std::collections::HashSet; use std::ops::Range; pub mod diagnostics; mod error; mod replace; use diagnostics::Diagnostic; use diagnostics::DiagnosticSpan; pub use error::Error; /// A filter to control which suggestion should be applied. #[derive(Debug, Clone, Copy)] pub enum Filter { /// For [`diagnostics::Applicability::MachineApplicable`] only. MachineApplicableOnly, /// Everything is included. YOLO! Everything, } /// Collects code [`Suggestion`]s from one or more compiler diagnostic lines. /// /// Fails if any of diagnostic line `input` is not a valid [`Diagnostic`] JSON. /// /// * `only` --- only diagnostics with code in a set of error codes would be collected. pub fn get_suggestions_from_json( input: &str, only: &HashSet, filter: Filter, ) -> serde_json::error::Result> { let mut result = Vec::new(); for cargo_msg in serde_json::Deserializer::from_str(input).into_iter::() { // 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) } } /// An error/warning and possible solutions for fixing it #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Suggestion { pub message: String, pub snippets: Vec, pub solutions: Vec, } /// Solution to a diagnostic item. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Solution { /// The error message of the diagnostic item. pub message: String, /// Possible solutions to fix the error. pub replacements: Vec, } /// Represents code that will get replaced. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Snippet { pub file_name: String, pub line_range: LineRange, pub range: Range, } /// Represents a replacement of a `snippet`. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Replacement { /// Code snippet that gets replaced. pub snippet: Snippet, /// The replacement of the snippet. pub replacement: String, } /// Converts a [`DiagnosticSpan`] to a [`Snippet`]. fn span_to_snippet(span: &DiagnosticSpan) -> Snippet { 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), } } /// Converts a [`DiagnosticSpan`] into a [`Replacement`]. fn collect_span(span: &DiagnosticSpan) -> Option { let snippet = span_to_snippet(span); let replacement = span.suggested_replacement.clone()?; Some(Replacement { snippet, replacement, }) } /// Collects code [`Suggestion`]s from a single compiler diagnostic line. /// /// * `only` --- only diagnostics with code in a set of error codes would be collected. pub fn collect_suggestions( diagnostic: &Diagnostic, only: &HashSet, filter: Filter, ) -> Option { 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 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: diagnostic.spans.iter().map(span_to_snippet).collect(), solutions, }) } } /// Represents a code fix. This doesn't write to disks but is only in memory. /// /// The general way to use this is: /// /// 1. Feeds the source of a file to [`CodeFix::new`]. /// 2. Calls [`CodeFix::apply`] to apply suggestions to the source code. /// 3. Calls [`CodeFix::finish`] to get the "fixed" code. #[derive(Clone)] pub struct CodeFix { data: replace::Data, /// Whether or not the data has been modified. modified: bool, } impl CodeFix { /// Creates a `CodeFix` with the source of a file to modify. pub fn new(s: &str) -> CodeFix { CodeFix { data: replace::Data::new(s.as_bytes()), modified: false, } } /// Applies a suggestion to the code. pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> { for solution in &suggestion.solutions { for r in &solution.replacements { self.data .replace_range(r.snippet.range.clone(), r.replacement.as_bytes()) .inspect_err(|_| self.data.restore())?; } } self.data.commit(); self.modified = true; Ok(()) } /// Applies an individual solution from a [`Suggestion`]. pub fn apply_solution(&mut self, solution: &Solution) -> Result<(), Error> { for r in &solution.replacements { self.data .replace_range(r.snippet.range.clone(), r.replacement.as_bytes()) .inspect_err(|_| self.data.restore())?; } self.data.commit(); self.modified = true; Ok(()) } /// Gets the result of the "fixed" code. pub fn finish(&self) -> Result { Ok(String::from_utf8(self.data.to_vec())?) } /// Returns whether or not the data has been modified. pub fn modified(&self) -> bool { self.modified } } /// Applies multiple `suggestions` to the given `code`, handling certain conflicts automatically. /// /// If a replacement in a suggestion exactly matches a replacement of a previously applied solution, /// that entire suggestion will be skipped without generating an error. /// This is currently done to alleviate issues like rust-lang/rust#51211, /// although it may be removed if that's fixed deeper in the compiler. /// /// The intent of this design is that the overall application process /// should repeatedly apply non-conflicting suggestions then rëevaluate the result, /// looping until either there are no more suggestions to apply or some budget is exhausted. pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result { let mut fix = CodeFix::new(code); for suggestion in suggestions.iter().rev() { fix.apply(suggestion).or_else(|err| match err { Error::AlreadyReplaced { is_identical: true, .. } => Ok(()), _ => Err(err), })?; } fix.finish() } rustfix-0.9.0/src/replace.rs000064400000000000000000000276061046102023000141210ustar 00000000000000//! A small module giving you a simple container that allows //! easy and cheap replacement of parts of its content, //! with the ability to commit or rollback pending changes. //! //! Create a new [`Data`] struct with some initial set of code, //! then record changes with [`Data::replace_range`], //! which will validate that the changes do not conflict with one another. //! At any time, you can "checkpoint" the current changes with [`Data::commit`] //! or roll them back (perhaps due to a conflict) with [`Data::restore`]. //! When you're done, use [`Data::to_vec`] //! to merge the original data with the changes. //! //! # Notes //! //! The [`Data::to_vec`] method includes uncommitted changes, if present. //! The reason for including uncommitted changes is that typically, once you're calling those, //! you're done with edits and will be dropping the [`Data`] struct in a moment. //! In this case, requiring an extra call to `commit` would be unnecessary work. //! Of course, there's no harm in calling `commit`---it's just not strictly necessary. //! //! Put another way, the main point of `commit` is to checkpoint a set of known-good changes //! before applying additional sets of as-of-yet unvalidated changes. //! If no future changes are expected, you aren't _required_ to pay the cost of `commit`. //! If you want to discard uncommitted changes, simply call [`Data::restore`] first. use std::ops::Range; use std::rc::Rc; use crate::error::Error; /// Data that should replace a particular range of the original. #[derive(Clone)] struct Span { /// Span of the parent data to be replaced, inclusive of the start, exclusive of the end. range: Range, /// New data to insert at the `start` position of the `original` data. data: Rc<[u8]>, /// Whether this data is committed or provisional. committed: bool, } impl std::fmt::Debug for Span { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let state = if self.is_insert() { "inserted" } else { "replaced" }; let committed = if self.committed { "committed" } else { "uncommitted" }; write!( f, "({}, {}: {state}, {committed})", self.range.start, self.range.end ) } } impl Span { fn new(range: Range, data: &[u8]) -> Self { Self { range, data: data.into(), committed: false, } } /// Returns `true` if and only if this is a "pure" insertion, /// i.e. does not remove any existing data. /// /// The insertion point is the `start` position of the range. fn is_insert(&self) -> bool { self.range.start == self.range.end } } impl PartialEq for Span { /// Returns `true` if and only if this `Span` and `other` have the same range and data, /// regardless of `committed` status. fn eq(&self, other: &Self) -> bool { self.range == other.range && self.data == other.data } } /// A container that allows easily replacing chunks of its data. #[derive(Debug, Clone, Default)] pub struct Data { /// Original data. original: Vec, /// [`Span`]s covering the full range of the original data. /// Important: it's expected that the underlying implementation maintains this in order, /// sorted ascending by start position. parts: Vec, } impl Data { /// Create a new data container from a slice of bytes pub fn new(data: &[u8]) -> Self { Data { original: data.into(), parts: vec![], } } /// Commit the current changes. pub fn commit(&mut self) { self.parts.iter_mut().for_each(|span| span.committed = true); } /// Discard uncommitted changes. pub fn restore(&mut self) { self.parts.retain(|parts| parts.committed); } /// Merge the original data with changes, **including** uncommitted changes. /// /// See the module-level documentation for more information on why uncommitted changes are included. pub fn to_vec(&self) -> Vec { let mut prev_end = 0; let mut s = self.parts.iter().fold(Vec::new(), |mut acc, span| { // Hedge against potential implementation errors. debug_assert!( prev_end <= span.range.start, "expected parts in sorted order" ); acc.extend_from_slice(&self.original[prev_end..span.range.start]); acc.extend_from_slice(&span.data); prev_end = span.range.end; acc }); // Append remaining data, if any. s.extend_from_slice(&self.original[prev_end..]); s } /// Record a provisional change. /// /// If committed, the original data in the given `range` will be replaced by the given data. /// If there already exist changes for data in the given range (committed or not), /// this method will return an error. /// It will also return an error if the beginning of the range comes before its end, /// or if the range is outside that of the original data. pub fn replace_range(&mut self, range: Range, data: &[u8]) -> Result<(), Error> { if range.start > range.end { return Err(Error::InvalidRange(range)); } if range.end > self.original.len() { return Err(Error::DataLengthExceeded(range, self.original.len())); } // Keep sorted by start position, or by end position if the start position is the same, // which has the effect of keeping a pure insertion ahead of a replacement. // That limits the kinds of conflicts that can happen, simplifying the checks below. let ins_point = self.parts.partition_point(|span| { span.range.start < range.start || (span.range.start == range.start && span.range.end < range.end) }); let incoming = Span::new(range, data.as_ref()); // Reject if the change starts before the previous one ends. if let Some(before) = ins_point.checked_sub(1).and_then(|i| self.parts.get(i)) { if incoming.range.start < before.range.end { return Err(Error::AlreadyReplaced { is_identical: incoming == *before, range: incoming.range, }); } } // Reject if the change ends after the next one starts, // or if this is an insert and there's already an insert there. if let Some(after) = self.parts.get(ins_point) { if incoming.range.end > after.range.start || incoming.range == after.range { return Err(Error::AlreadyReplaced { is_identical: incoming == *after, range: incoming.range, }); } } self.parts.insert(ins_point, incoming); Ok(()) } } #[cfg(test)] mod tests { use super::*; use proptest::prelude::*; fn str(i: &[u8]) -> &str { ::std::str::from_utf8(i).unwrap() } #[test] fn insert_at_beginning() { let mut d = Data::new(b"foo bar baz"); d.replace_range(0..0, b"oh no ").unwrap(); assert_eq!("oh no foo bar baz", str(&d.to_vec())); } #[test] fn insert_at_end() { let mut d = Data::new(b"foo bar baz"); d.replace_range(11..11, b" oh no").unwrap(); assert_eq!("foo bar baz oh no", str(&d.to_vec())); } #[test] fn replace_some_stuff() { let mut d = Data::new(b"foo bar baz"); d.replace_range(4..7, 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..5, 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..11, b"lol").unwrap(); assert_eq!("lorem\nlol\ndolor", str(&d.to_vec())); d.replace_range(12..17, 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..3, b"bar").unwrap(); assert_eq!("foobar!", str(&d.to_vec())); d.replace_range(0..3, b"baz").unwrap(); assert_eq!("bazbar!", str(&d.to_vec())); d.replace_range(3..4, b"?").unwrap(); assert_eq!("bazbar?", str(&d.to_vec())); } #[test] #[allow(clippy::reversed_empty_ranges)] fn replace_invalid_range() { let mut d = Data::new(b"foo!"); assert!(d.replace_range(2..1, b"bar").is_err()); assert!(d.replace_range(0..3, 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] fn replace_same_range_diff_data() { let mut d = Data::new(b"foo bar baz"); d.replace_range(4..7, b"lol").unwrap(); assert_eq!("foo lol baz", str(&d.to_vec())); assert!(matches!( d.replace_range(4..7, b"lol2").unwrap_err(), Error::AlreadyReplaced { is_identical: false, .. }, )); } #[test] fn replace_same_range_same_data() { let mut d = Data::new(b"foo bar baz"); d.replace_range(4..7, b"lol").unwrap(); assert_eq!("foo lol baz", str(&d.to_vec())); assert!(matches!( d.replace_range(4..7, b"lol").unwrap_err(), Error::AlreadyReplaced { is_identical: true, .. }, )); } #[test] fn broken_replacements() { let mut d = Data::new(b"foo"); assert!(matches!( d.replace_range(4..8, b"lol").unwrap_err(), Error::DataLengthExceeded(std::ops::Range { start: 4, end: 8 }, 3), )); } #[test] fn insert_same_twice() { let mut d = Data::new(b"foo"); d.replace_range(1..1, b"b").unwrap(); assert_eq!("fboo", str(&d.to_vec())); assert!(matches!( d.replace_range(1..1, b"b").unwrap_err(), Error::AlreadyReplaced { is_identical: true, .. }, )); assert_eq!("fboo", str(&d.to_vec())); } #[test] fn commit_restore() { let mut d = Data::new(b", "); assert_eq!(", ", str(&d.to_vec())); d.replace_range(2..2, b"world").unwrap(); d.replace_range(0..0, b"hello").unwrap(); assert_eq!("hello, world", str(&d.to_vec())); d.restore(); assert_eq!(", ", str(&d.to_vec())); d.commit(); assert_eq!(", ", str(&d.to_vec())); d.replace_range(2..2, b"world").unwrap(); assert_eq!(", world", str(&d.to_vec())); d.commit(); assert_eq!(", world", str(&d.to_vec())); d.restore(); assert_eq!(", world", str(&d.to_vec())); d.replace_range(0..0, b"hello").unwrap(); assert_eq!("hello, world", str(&d.to_vec())); d.commit(); assert_eq!("hello, world", str(&d.to_vec())); d.restore(); assert_eq!("hello, world", str(&d.to_vec())); } proptest! { #[test] fn new_to_vec_roundtrip(ref s in "\\PC*") { assert_eq!(s.as_bytes(), Data::new(s.as_bytes()).to_vec().as_slice()); } #[test] fn replace_random_chunks( ref data in "\\PC*", ref replacements in prop::collection::vec( (any::<::std::ops::Range>(), any::>()), 1..100, ) ) { let mut d = Data::new(data.as_bytes()); for &(ref range, ref bytes) in replacements { let _ = d.replace_range(range.clone(), bytes); } } } }