rustfix-0.6.0/.cargo_vcs_info.json0000644000000001120000000000000125340ustar { "git": { "sha1": "e6dabf15236e0a1bb05fc54718cb5f83b0e82da5" } } rustfix-0.6.0/.editorconfig000064400000000000000000000006370000000000000137730ustar 00000000000000# EditorConfig helps developers define and maintain consistent # coding styles between different editors and IDEs # editorconfig.org root = true [*] end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 4 [*.rs] indent_style = space indent_size = 4 [*.toml] indent_style = space indent_size = 4 [*.md] trim_trailing_whitespace = false rustfix-0.6.0/.github/workflows/main.yml000064400000000000000000000012240000000000000163530ustar 00000000000000name: CI on: [push, pull_request] jobs: test: name: Test runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest] steps: - uses: actions/checkout@master - name: Install Rust (rustup) run: rustup update nightly --no-self-update && rustup default nightly shell: bash - run: cargo test --all - run: cargo test --all -- --ignored rustfmt: name: Rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@master - name: Install Rust run: rustup update stable && rustup default stable && rustup component add rustfmt - run: cargo fmt -- --check rustfix-0.6.0/.gitignore000064400000000000000000000002250000000000000132770ustar 00000000000000target Cargo.lock tests/crates/**/output.txt # Editor and IDE-specific ignores ## VSCode .vscode ## Eclipse .project ## All JetBrains IDE's *.iml rustfix-0.6.0/.gitmodules000064400000000000000000000000000000000000000134530ustar 00000000000000rustfix-0.6.0/Cargo.lock0000644000000371400000000000000105220ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "0.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5" dependencies = [ "memchr", ] [[package]] name = "anyhow" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28b2cd92db5cbd74e8e5028f7e27dd7aa3090e89e4f2a197cc7c8dfb69c7063b" [[package]] name = "atty" version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652" dependencies = [ "libc", "termion", "winapi", ] [[package]] name = "autocfg" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6d640bee2da49f60a4068a7fae53acde8982514ab7bae8b8cea9e88cbcfd799" [[package]] name = "bit-set" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e84c238982c4b1e1ee668d136c510c67a13465279c0cb367ea6baf6310620a80" dependencies = [ "bit-vec", ] [[package]] name = "bit-vec" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f59bbe95d4e52a6398ec21238d31577f2b28a9d86807f06ca59d191d8440d0bb" [[package]] name = "bitflags" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" [[package]] name = "cc" version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9ce8bb087aacff865633f0bd5aeaed910fe2fe55b55f4739527f2e023a2e53d" [[package]] name = "cfg-if" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4" [[package]] name = "cloudabi" version = "0.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" dependencies = [ "bitflags", ] [[package]] name = "duct" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c553d79f40e74f7f611e49bf3429b6760cff79596b61818291c27cc0b18549d" dependencies = [ "lazycell", "libc", "os_pipe", "shared_child", ] [[package]] name = "env_logger" version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38" dependencies = [ "atty", "humantime", "log", "regex", "termcolor", ] [[package]] name = "fnv" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" [[package]] name = "fuchsia-cprng" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" [[package]] name = "humantime" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ca7e5f2e110db35f93b837c81797f3714500b81d517bf20c431b16d3ca4f114" dependencies = [ "quick-error", ] [[package]] name = "itoa" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" [[package]] name = "lazy_static" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14" [[package]] name = "lazycell" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b585b7a6811fb03aa10e74b278a0f00f8dd9b45dc681f148bb29fa5cb61859b" [[package]] name = "libc" version = "0.2.50" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1" [[package]] name = "log" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" dependencies = [ "cfg-if", ] [[package]] name = "memchr" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2efc7bc57c883d4a4d6e3246905283d8dae951bb3bd32f49d6ef297f546e1c39" [[package]] name = "nix" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d37e713a259ff641624b6cb20e3b12b2952313ba36b6823c0f16e6cfd9e5de17" dependencies = [ "bitflags", "cc", "cfg-if", "libc", "void", ] [[package]] name = "num-traits" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1" [[package]] name = "os_pipe" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe033225d563042c3eeb22ffd1d2ea1aefcc48e7e37151a064c9e0bae64b253f" dependencies = [ "nix", "winapi", ] [[package]] name = "proc-macro2" version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d317f9caece796be1980837fd5cb3dfec5613ebdb04ad0956deea83ce168915" dependencies = [ "unicode-xid", ] [[package]] name = "proptest" version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f275a76b824714046ce0b1e00323e06437e027f2d31b2b6272cae30afaf18d" dependencies = [ "bit-set", "bitflags", "lazy_static", "num-traits", "quick-error", "rand 0.4.6", "regex-syntax 0.4.2", "rusty-fork", "tempfile", ] [[package]] name = "quick-error" version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" [[package]] name = "quote" version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdd8e04bd9c52e0342b406469d494fcb033be4bdbe5c606016defbb1681411e1" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" dependencies = [ "fuchsia-cprng", "libc", "rand_core 0.3.1", "rdrand", "winapi", ] [[package]] name = "rand" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" dependencies = [ "autocfg", "libc", "rand_chacha", "rand_core 0.4.0", "rand_hc", "rand_isaac", "rand_jitter", "rand_os", "rand_pcg", "rand_xorshift", "winapi", ] [[package]] name = "rand_chacha" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" dependencies = [ "autocfg", "rand_core 0.3.1", ] [[package]] name = "rand_core" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" dependencies = [ "rand_core 0.4.0", ] [[package]] name = "rand_core" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" [[package]] name = "rand_hc" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "rand_isaac" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "rand_jitter" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b9ea758282efe12823e0d952ddb269d2e1897227e464919a554f2a03ef1b832" dependencies = [ "libc", "rand_core 0.4.0", "winapi", ] [[package]] name = "rand_os" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" dependencies = [ "cloudabi", "fuchsia-cprng", "libc", "rand_core 0.4.0", "rdrand", "winapi", ] [[package]] name = "rand_pcg" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" dependencies = [ "autocfg", "rand_core 0.4.0", ] [[package]] name = "rand_xorshift" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "rdrand" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" dependencies = [ "rand_core 0.3.1", ] [[package]] name = "redox_syscall" version = "0.1.51" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "423e376fffca3dfa06c9e9790a9ccd282fafb3cc6e6397d01dbf64f9bacc6b85" [[package]] name = "redox_termios" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76" dependencies = [ "redox_syscall", ] [[package]] name = "regex" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53ee8cfdddb2e0291adfb9f13d31d3bbe0a03c9a402c01b1e24188d86c35b24f" dependencies = [ "aho-corasick", "memchr", "regex-syntax 0.6.5", "thread_local", "utf8-ranges", ] [[package]] name = "regex-syntax" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e931c58b93d86f080c734bfd2bce7dd0079ae2331235818133c8be7f422e20e" [[package]] name = "regex-syntax" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c2f35eedad5295fdf00a63d7d4b238135723f92b434ec06774dad15c7ab0861" dependencies = [ "ucd-util", ] [[package]] name = "remove_dir_all" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5" dependencies = [ "winapi", ] [[package]] name = "rustfix" version = "0.6.0" dependencies = [ "anyhow", "duct", "env_logger", "log", "proptest", "serde", "serde_json", "similar", "tempdir", ] [[package]] name = "rusty-fork" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9591f190d2852720b679c21f66ad929f9f1d7bb09d1193c26167586029d8489c" dependencies = [ "fnv", "quick-error", "tempfile", "wait-timeout", ] [[package]] name = "ryu" version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb9e9b8cde282a9fe6a42dd4681319bfb63f121b8a8ee9439c6f4107e58a46f7" [[package]] name = "serde" version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92514fb95f900c9b5126e32d020f5c6d40564c27a5ea6d1d7d9f157a96623560" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb6eabf4b5914e88e24eea240bb7c9f9a2cbc1bbbe8d961d381975ec3c6b806c" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a23aa71d4a4d43fdbfaac00eff68ba8a06a51759a89ac3304323e800c4dd40d" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "shared_child" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e254d79655b3a1cb86b4079fc080c91664af57d0a81facb59fc828503cd4f48" dependencies = [ "libc", "winapi", ] [[package]] name = "similar" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "823f59ff8efe59c4cf706349651b0e19dd6f501fdf3521666fbe498e8d18d0ec" [[package]] name = "syn" version = "0.15.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1825685f977249735d510a242a6727b46efe914bb67e38d30c071b1b72b1d5c2" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "tempdir" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" dependencies = [ "rand 0.4.6", "remove_dir_all", ] [[package]] name = "tempfile" version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b86c784c88d98c801132806dadd3819ed29d8600836c4088e855cdf3e178ed8a" dependencies = [ "cfg-if", "libc", "rand 0.6.5", "redox_syscall", "remove_dir_all", "winapi", ] [[package]] name = "termcolor" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4096add70612622289f2fdcdbd5086dc81c1e2675e6ae58d6c4f62a16c6d7f2f" dependencies = [ "wincolor", ] [[package]] name = "termion" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096" dependencies = [ "libc", "redox_syscall", "redox_termios", ] [[package]] name = "thread_local" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" dependencies = [ "lazy_static", ] [[package]] name = "ucd-util" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "535c204ee4d8434478593480b8f86ab45ec9aae0e83c568ca81abf0fd0e88f86" [[package]] name = "unicode-xid" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" [[package]] name = "utf8-ranges" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "796f7e48bef87609f7ade7e06495a87d5cd06c7866e6a5cbfceffc558a243737" [[package]] name = "void" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" [[package]] name = "wait-timeout" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9f3bf741a801531993db6478b95682117471f76916f5e690dd8d45395b09349" dependencies = [ "libc", ] [[package]] name = "winapi" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" 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-util" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9" dependencies = [ "winapi", ] [[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 = "wincolor" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "561ed901ae465d6185fa7864d63fbd5720d0ef718366c9a4dc83cf6170d7e9ba" dependencies = [ "winapi", "winapi-util", ] rustfix-0.6.0/Cargo.toml0000644000000026030000000000000105410ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "rustfix" version = "0.6.0" authors = ["Pascal Hertleif ", "Oliver Schneider "] 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.0" [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.tempdir] version = "0.3.5" rustfix-0.6.0/Cargo.toml.orig000064400000000000000000000013120000000000000141740ustar 00000000000000[package] authors = [ "Pascal Hertleif ", "Oliver Schneider ", ] license = "Apache-2.0/MIT" name = "rustfix" description = "Automatically apply the suggestions made by rustc" repository = "https://github.com/rust-lang-nursery/rustfix" documentation = "https://docs.rs/rustfix" edition = "2018" readme = "Readme.md" version = "0.6.0" exclude = [ "etc/*", "examples/*", "tests/*", ] [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" anyhow = "1.0.0" log = "0.4.1" [dev-dependencies] duct = "0.9" env_logger = "0.5.0-rc.1" log = "0.4.1" tempdir = "0.3.5" proptest = "0.7.0" similar = "0.4.0" [workspace] rustfix-0.6.0/Changelog.md000064400000000000000000000035720000000000000135300ustar 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.6.0/LICENSE-APACHE000064400000000000000000000261360000000000000132440ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. rustfix-0.6.0/LICENSE-MIT000064400000000000000000000020720000000000000127450ustar 00000000000000The 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. rustfix-0.6.0/Readme.md000064400000000000000000000027550000000000000130400ustar 00000000000000# 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` to transition to Rust 2018 Instructions on how to use this tool to transition a crate to Rust 2018 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 ) - 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.6.0/proptest-regressions/replace.txt000064400000000000000000000007300000000000000177050ustar 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.6.0/src/diagnostics.rs000064400000000000000000000056670000000000000147720ustar 00000000000000//! 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, /// "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. Currently this is only /// `Some` for "suggestions", but eventually it will include all /// snippets. pub rendered: Option, } #[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? 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. You may prefer to /// load the fully rendered version from the parent `Diagnostic`, /// however. pub suggested_replacement: Option, pub suggestion_applicability: Option, /// Macro invocations that created the code at this span, if any. expansion: Option>, } #[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, } #[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.6.0/src/lib.rs000064400000000000000000000171200000000000000132140ustar 00000000000000#![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( 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) } } #[derive(Debug, Clone, Hash, PartialEq, Eq)] /// An error/warning and possible solutions for fixing it pub struct Suggestion { pub message: String, pub snippets: Vec, pub solutions: Vec, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Solution { pub message: String, pub replacements: Vec, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct Snippet { pub file_name: String, pub line_range: LineRange, pub range: Range, /// 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 { // 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) }) .min()?; let text_slice = span.text[0].text.chars().collect::>(); // 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::>(); if span.text.len() > 1 { body.push('\n'); body.push_str( &last_slice[indent..last_tail_index] .iter() .collect::(), ); } tail.push_str(&last_slice[last_tail_index..].iter().collect::()); 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 { let snippet = parse_snippet(span)?; let replacement = span.suggested_replacement.clone()?; Some(Replacement { snippet, replacement, }) } 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 snippets = diagnostic .spans .iter() .filter_map(|span| parse_snippet(span)) .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.len() >= 1 { 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 { Ok(String::from_utf8(self.data.to_vec())?) } } pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result { let mut fix = CodeFix::new(code); for suggestion in suggestions.iter().rev() { fix.apply(suggestion)?; } fix.finish() } rustfix-0.6.0/src/replace.rs000064400000000000000000000237200000000000000140640ustar 00000000000000//! 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, 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![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 { 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::>(); 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>(), any::>()), 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); } } } }