Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"ed3503c6dbc1fe873288e50cd14176e49e292ed2396bc2fb53b9cfcec6bd9dae",".github/FUNDING.yml":"b017158736b3c9751a2d21edfce7fe61c8954e2fced8da8dd3013c2f3e295bd9",".github/workflows/ci.yml":"c819e525ab46aec2d2ab413d9a30e7b8b01e55468e890e34d9e2c722fe984f28","Cargo.lock":"9ba75446429d67d4c794ea8d64a56789a1cf4f8cdf26e08490aefcee2b2162c3","Cargo.toml":"407a03f19cc6a83ec09e5b184c41ce1345b44e13d6865ea5f74046e8d0934916","Cargo.toml.orig":"53bef9400e8ecabbd281e7aef59a946e31bb215b7ff935296f32f19e51f57a30","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"1a19bb1c39c3cbf5348446e5ba5f7d145679168c9ed944415a01752f2ebbd36a","src/error.rs":"1791b9ed045f84cd7365d917418dbdd1e8d614e441a0def0f52c74a979b24ba8","src/expr.rs":"ea811c5c8f7aa699f8b96f5655e2921225aad9373a2355906702ca978935cb84","src/lib.rs":"c0269bb55514d268eb12c0d618edbf44db95d3e128179cfe2310fb19a44728f5","src/unindent.rs":"20bdda8d470c93b6b48e3fc30f6ae22c061f8f1ae066a28dd1cd64373338b37b","tests/compiletest.rs":"4e381aa8ca3eabb7ac14d1e0c3700b3223e47640547a6988cfa13ad68255f60f","tests/test_concat.rs":"8065592ad2fc58c51855af3f6213fed426e508963de24e6b48319906fc901ee1","tests/test_cstr/mod.rs":"d568524a7c5f6eb90211e513868b298595b493b0cf24a2f5b2b33b3d4cf9e50c","tests/test_formatdoc.rs":"538586016cf601451b582604908f7ab594ce642bbbd7a458ba2dff1d300f297d","tests/test_indoc.rs":"0951faf33256e3b5c834b80d87ba6878b3571ff811972ad00736f13b1b7d9f6a","tests/test_unindent.rs":"57ce28df0e6055b661097cb4dca3efa949e15535aa28d1bc8da6932d4cc1ed15","tests/test_writedoc.rs":"e313e4f49faec67b4b2cb3a69b468bd95e7d941f3686ee2193a8d6626cf48c49","tests/ui/capture-var-nested.rs":"01597020d34975817a627c213e1e35e58bd1809f3174a26d9c2795efba677297","tests/ui/capture-var-nested.stderr":"99d385c115680bb6d923e9dc30c9e2fcaa346fa0679931e1df20b998a5fb6682","tests/ui/no-arguments.rs":"d544b1a510efbef42a1fb7b7b40009da2d9be815a55ef76dd2362c8c7754734e","tests/ui/no-arguments.stderr":"50adb9ca3a1b1661ef7dbd9e9a74804353d18c294d2a28498f50ef91676f13d6","tests/ui/non-lit.rs":"3e7d7b4b5e141b5eb4c76d64b47f7a5f60325091a8e4d8cc2d97b7d590dd2857","tests/ui/non-lit.stderr":"f7ea54b55db14f756254e013150a3a45d3045cef4419e8a512cfd70ec29b858e","tests/ui/non-string.rs":"0b56f281761edaee1c7341c9ba231371c86752456179d84777c62f03f52ce173","tests/ui/non-string.stderr":"6a65eb94f57ef6733da6a1d855194708e124dd8dac424d3eebde6e79b966f9ad","tests/ui/printdoc-binary.rs":"0122fd6b783cb9c25c8aede8f0cc69c1c3ffcef656bf7d9ee476e8e0ff49e59f","tests/ui/printdoc-binary.stderr":"4b745df236fbca6ac1f314e6b1c26c069fc4d108edad84a8a69b7dcc2e6ca4ea","tests/ui/printdoc-extra-arg.rs":"fa31182019534b5b258f8335799c8ba53a7715c1d9e6fc9d25fbc0952d28bd7a","tests/ui/printdoc-extra-arg.stderr":"c613f1118d1ce268ed6570940b70057ce90083060a0227d3cc1d8aa545c98692","tests/ui/printdoc-no-arg.rs":"087d8e5295f7809abf596a076743401f6ba019fd5b3b2e290bfd6551b4bdcdf3","tests/ui/printdoc-no-arg.stderr":"a5e5d79415ef3fc357403c38b486acbb6ba3e5e565c358265694902afd476b9d","tests/ui/printdoc-no-display.rs":"afeafb1f41a6f7aa68bd5da14c2057e54f2756c1726098ac8be9ab0517a85879","tests/ui/printdoc-no-display.stderr":"0ebc764fb295853609123d118b3584da9a137a04a5f0bf3da6672b493329bf1d","tests/ui/printdoc-no-named-arg.rs":"beeb8447ab95a0e0a21aec78872be79ad1b2a8fe1be4a276fe191f47f3b8082b","tests/ui/printdoc-no-named-arg.stderr":"c5e2f35a4c960e0ae86c2c3481645da90bf86b8f8ae8b6f8c8954d8c9917a44d","tests/ui/three-arguments.rs":"47b74a9918de87bad00cdd94dc7091a499a586edcfbc05035ef79ce0d52dbe27","tests/ui/three-arguments.stderr":"f3649c03bf13c18b863f0ee0986154c4530601138c574e30cf05f7916eb85c39","tests/ui/two-arguments.rs":"1607e7c149cc0ed5e3fb5984ac1d39d8dff0bd8325911518b02d05daa95b06b0","tests/ui/two-arguments.stderr":"a446346d0cb74e791174b22eed874130387d21038cfdb809b80eb068b4f24b92"},"package":"79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "8d78216b3f127f523d198475ea44090f8f6894d5"
},
"path_in_vcs": ""
}
+1
View File
@@ -0,0 +1 @@
github: dtolnay
+95
View File
@@ -0,0 +1,95 @@
name: CI
on:
push:
pull_request:
workflow_dispatch:
schedule: [cron: "40 1 * * *"]
permissions:
contents: read
env:
RUSTFLAGS: -Dwarnings
jobs:
pre_ci:
uses: dtolnay/.github/.github/workflows/pre_ci.yml@master
test:
name: Rust ${{matrix.rust}}
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
rust: [nightly, beta, stable, 1.77.0, 1.76.0, 1.60.0]
timeout-minutes: 45
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{matrix.rust}}
- name: Enable type layout randomization
run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV
if: matrix.rust == 'nightly'
- run: cargo check --workspace
- run: cargo test --workspace
if: matrix.rust != '1.60.0'
- uses: actions/upload-artifact@v4
if: matrix.rust == 'nightly' && always()
with:
name: Cargo.lock
path: Cargo.lock
continue-on-error: true
doc:
name: Documentation
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
timeout-minutes: 45
env:
RUSTDOCFLAGS: -Dwarnings
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@nightly
- uses: dtolnay/install@cargo-docs-rs
- run: cargo docs-rs
- run: cargo docs-rs -p unindent
clippy:
name: Clippy
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
timeout-minutes: 45
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@clippy
- run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic
miri:
name: Miri
needs: pre_ci
if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@miri
- run: cargo miri setup
- run: cargo miri test
env:
MIRIFLAGS: -Zmiri-strict-provenance
outdated:
name: Outdated
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
timeout-minutes: 45
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/install@cargo-outdated
- run: cargo outdated --workspace --exit-code 1
+262
View File
@@ -0,0 +1,262 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "dissimilar"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8975ffdaa0ef3661bfe02dbdcc06c9f829dfafe6a3c474de366a8d5e44276921"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "hashbrown"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
[[package]]
name = "indexmap"
version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "indoc"
version = "2.0.7"
dependencies = [
"rustversion",
"trybuild",
"unindent",
]
[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "memchr"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
[[package]]
name = "proc-macro2"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.145"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
"serde_core",
]
[[package]]
name = "serde_spanned"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392"
dependencies = [
"serde_core",
]
[[package]]
name = "syn"
version = "2.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a26dbd934e5451d21ef060c018dae56fc073894c5a7896f882928a76e6d081b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "target-triple"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ac9aa371f599d22256307c24a9d748c041e548cbf599f35d890f9d365361790"
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "toml"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2"
[[package]]
name = "trybuild"
version = "1.0.112"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d66678374d835fe847e0dc8348fde2ceb5be4a7ec204437d8367f0d8df266a5"
dependencies = [
"dissimilar",
"glob",
"serde",
"serde_derive",
"serde_json",
"target-triple",
"termcolor",
"toml",
]
[[package]]
name = "unicode-ident"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "462eeb75aeb73aea900253ce739c8e18a67423fadf006037cd3ff27e82748a06"
[[package]]
name = "unindent"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"
+95
View File
@@ -0,0 +1,95 @@
# 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.60"
name = "indoc"
version = "2.0.7"
authors = ["David Tolnay <dtolnay@gmail.com>"]
build = false
exclude = ["build.rs"]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Indented document literals"
documentation = "https://docs.rs/indoc"
readme = "README.md"
keywords = [
"heredoc",
"nowdoc",
"multiline",
"string",
"literal",
]
categories = [
"rust-patterns",
"text-processing",
"no-std",
"no-std::no-alloc",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/indoc"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--extern-html-root-url=core=https://doc.rust-lang.org",
"--extern-html-root-url=alloc=https://doc.rust-lang.org",
"--extern-html-root-url=std=https://doc.rust-lang.org",
"--extern-html-root-url=proc_macro=https://doc.rust-lang.org",
]
[lib]
name = "indoc"
path = "src/lib.rs"
proc-macro = true
[[test]]
name = "compiletest"
path = "tests/compiletest.rs"
[[test]]
name = "test_concat"
path = "tests/test_concat.rs"
[[test]]
name = "test_formatdoc"
path = "tests/test_formatdoc.rs"
[[test]]
name = "test_indoc"
path = "tests/test_indoc.rs"
[[test]]
name = "test_unindent"
path = "tests/test_unindent.rs"
[[test]]
name = "test_writedoc"
path = "tests/test_writedoc.rs"
[dev-dependencies.rustversion]
version = "1.0"
[dev-dependencies.trybuild]
version = "1.0.108"
features = ["diff"]
[dev-dependencies.unindent]
version = "0.2.3"
[build-dependencies.rustversion]
version = "1.0"
+38
View File
@@ -0,0 +1,38 @@
[package]
name = "indoc"
version = "2.0.7"
authors = ["David Tolnay <dtolnay@gmail.com>"]
categories = ["rust-patterns", "text-processing", "no-std", "no-std::no-alloc"]
description = "Indented document literals"
documentation = "https://docs.rs/indoc"
edition = "2021"
exclude = ["build.rs"]
keywords = ["heredoc", "nowdoc", "multiline", "string", "literal"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/indoc"
rust-version = "1.60"
[lib]
proc-macro = true
[dev-dependencies]
rustversion = "1.0"
trybuild = { version = "1.0.108", features = ["diff"] }
unindent = { version = "0.2.3", path = "unindent" }
[build-dependencies]
rustversion = "1.0"
[workspace]
members = ["unindent"]
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--extern-html-root-url=core=https://doc.rust-lang.org",
"--extern-html-root-url=alloc=https://doc.rust-lang.org",
"--extern-html-root-url=std=https://doc.rust-lang.org",
"--extern-html-root-url=proc_macro=https://doc.rust-lang.org",
]
+176
View File
@@ -0,0 +1,176 @@
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
+23
View File
@@ -0,0 +1,23 @@
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.
+158
View File
@@ -0,0 +1,158 @@
Indented Documents (indoc)
==========================
[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/indoc-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/indoc)
[<img alt="crates.io" src="https://img.shields.io/crates/v/indoc.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/indoc)
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-indoc-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/indoc)
[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/indoc/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/indoc/actions?query=branch%3Amaster)
This crate provides a procedural macro for indented string literals. The
`indoc!()` macro takes a multiline string literal and un-indents it at compile
time so the leftmost non-space character is in the first column.
```toml
[dependencies]
indoc = "2"
```
*Compiler requirement: rustc 1.60 or greater.*
<br>
## Using indoc
```rust
use indoc::indoc;
fn main() {
let testing = indoc! {"
def hello():
print('Hello, world!')
hello()
"};
let expected = "def hello():\n print('Hello, world!')\n\nhello()\n";
assert_eq!(testing, expected);
}
```
Indoc also works with raw string literals:
```rust
use indoc::indoc;
fn main() {
let testing = indoc! {r#"
def hello():
print("Hello, world!")
hello()
"#};
let expected = "def hello():\n print(\"Hello, world!\")\n\nhello()\n";
assert_eq!(testing, expected);
}
```
And byte string literals:
```rust
use indoc::indoc;
fn main() {
let testing = indoc! {b"
def hello():
print('Hello, world!')
hello()
"};
let expected = b"def hello():\n print('Hello, world!')\n\nhello()\n";
assert_eq!(testing[..], expected[..]);
}
```
<br>
## Formatting macros
The indoc crate exports five additional macros to substitute conveniently for
the standard library's formatting macros:
- `formatdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `format!(indoc!($fmt), ...)`
- `printdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `print!(indoc!($fmt), ...)`
- `eprintdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `eprint!(indoc!($fmt), ...)`
- `writedoc!($dest, $fmt, ...)`&ensp;&mdash;&ensp;equivalent to `write!($dest, indoc!($fmt), ...)`
- `concatdoc!(...)`&ensp;&mdash;&ensp;equivalent to `concat!(...)` with each string literal wrapped in `indoc!`
```rust
use indoc::{concatdoc, printdoc};
const HELP: &str = concatdoc! {"
Usage: ", env!("CARGO_BIN_NAME"), " [options]
Options:
-h, --help
"};
fn main() {
printdoc! {"
GET {url}
Accept: {mime}
",
url = "http://localhost:8080",
mime = "application/json",
}
}
```
<br>
## Explanation
The following rules characterize the behavior of the `indoc!()` macro:
1. Count the leading spaces of each line, ignoring the first line and any lines
that are empty or contain spaces only.
2. Take the minimum.
3. If the first line is empty i.e. the string begins with a newline, remove the
first line.
4. Remove the computed number of spaces from the beginning of each line.
<br>
## Unindent
Indoc's indentation logic is available in the `unindent` crate. This may be
useful for processing strings that are not statically known at compile time.
The crate exposes two functions:
- `unindent(&str) -> String`
- `unindent_bytes(&[u8]) -> Vec<u8>`
```rust
use unindent::unindent;
fn main() {
let indented = "
line one
line two";
assert_eq!("line one\nline two", unindent(indented));
}
```
<br>
#### License
<sup>
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
</sup>
<br>
<sub>
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.
</sub>
+46
View File
@@ -0,0 +1,46 @@
use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
pub type Result<T> = std::result::Result<T, Error>;
pub struct Error {
begin: Span,
end: Span,
msg: String,
}
impl Error {
pub fn new(span: Span, msg: impl Into<String>) -> Self {
Self::new2(span, span, msg)
}
pub fn new2(begin: Span, end: Span, msg: impl Into<String>) -> Self {
Error {
begin,
end,
msg: msg.into(),
}
}
pub fn to_compile_error(&self) -> TokenStream {
// compile_error! { $msg }
TokenStream::from_iter(vec![
TokenTree::Ident(Ident::new("compile_error", self.begin)),
TokenTree::Punct({
let mut punct = Punct::new('!', Spacing::Alone);
punct.set_span(self.begin);
punct
}),
TokenTree::Group({
let mut group = Group::new(Delimiter::Brace, {
TokenStream::from_iter(vec![TokenTree::Literal({
let mut string = Literal::string(&self.msg);
string.set_span(self.end);
string
})])
});
group.set_span(self.end);
group
}),
])
}
}
+61
View File
@@ -0,0 +1,61 @@
use crate::error::{Error, Result};
use proc_macro::token_stream::IntoIter as TokenIter;
use proc_macro::{Spacing, Span, TokenStream, TokenTree};
use std::iter::{self, Peekable};
pub fn parse(input: &mut Peekable<TokenIter>, require_comma: bool) -> Result<TokenStream> {
#[derive(PartialEq)]
enum Lookbehind {
JointColon,
DoubleColon,
JointHyphen,
Other,
}
let mut expr = TokenStream::new();
let mut lookbehind = Lookbehind::Other;
let mut angle_bracket_depth = 0;
loop {
if angle_bracket_depth == 0 {
match input.peek() {
Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => {
return Ok(expr);
}
_ => {}
}
}
match input.next() {
Some(TokenTree::Punct(punct)) => {
let ch = punct.as_char();
let spacing = punct.spacing();
expr.extend(iter::once(TokenTree::Punct(punct)));
lookbehind = match ch {
':' if lookbehind == Lookbehind::JointColon => Lookbehind::DoubleColon,
':' if spacing == Spacing::Joint => Lookbehind::JointColon,
'<' if lookbehind == Lookbehind::DoubleColon => {
angle_bracket_depth += 1;
Lookbehind::Other
}
'>' if angle_bracket_depth > 0 && lookbehind != Lookbehind::JointHyphen => {
angle_bracket_depth -= 1;
Lookbehind::Other
}
'-' if spacing == Spacing::Joint => Lookbehind::JointHyphen,
_ => Lookbehind::Other,
};
}
Some(token) => expr.extend(iter::once(token)),
None => {
return if require_comma {
Err(Error::new(
Span::call_site(),
"unexpected end of macro input",
))
} else {
Ok(expr)
};
}
}
}
}
+509
View File
@@ -0,0 +1,509 @@
//! [![github]](https://github.com/dtolnay/indoc)&ensp;[![crates-io]](https://crates.io/crates/indoc)&ensp;[![docs-rs]](https://docs.rs/indoc)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! This crate provides a procedural macro for indented string literals. The
//! `indoc!()` macro takes a multiline string literal and un-indents it at
//! compile time so the leftmost non-space character is in the first column.
//!
//! ```toml
//! [dependencies]
//! indoc = "2"
//! ```
//!
//! <br>
//!
//! # Using indoc
//!
//! ```
//! use indoc::indoc;
//!
//! fn main() {
//! let testing = indoc! {"
//! def hello():
//! print('Hello, world!')
//!
//! hello()
//! "};
//! let expected = "def hello():\n print('Hello, world!')\n\nhello()\n";
//! assert_eq!(testing, expected);
//! }
//! ```
//!
//! Indoc also works with raw string literals:
//!
//! ```
//! use indoc::indoc;
//!
//! fn main() {
//! let testing = indoc! {r#"
//! def hello():
//! print("Hello, world!")
//!
//! hello()
//! "#};
//! let expected = "def hello():\n print(\"Hello, world!\")\n\nhello()\n";
//! assert_eq!(testing, expected);
//! }
//! ```
//!
//! And byte string literals:
//!
//! ```
//! use indoc::indoc;
//!
//! fn main() {
//! let testing = indoc! {b"
//! def hello():
//! print('Hello, world!')
//!
//! hello()
//! "};
//! let expected = b"def hello():\n print('Hello, world!')\n\nhello()\n";
//! assert_eq!(testing[..], expected[..]);
//! }
//! ```
//!
//! <br><br>
//!
//! # Formatting macros
//!
//! The indoc crate exports five additional macros to substitute conveniently
//! for the standard library's formatting macros:
//!
//! - `formatdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `format!(indoc!($fmt), ...)`
//! - `printdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `print!(indoc!($fmt), ...)`
//! - `eprintdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `eprint!(indoc!($fmt), ...)`
//! - `writedoc!($dest, $fmt, ...)`&ensp;&mdash;&ensp;equivalent to `write!($dest, indoc!($fmt), ...)`
//! - `concatdoc!(...)`&ensp;&mdash;&ensp;equivalent to `concat!(...)` with each string literal wrapped in `indoc!`
//!
//! ```
//! # macro_rules! env {
//! # ($var:literal) => {
//! # "example"
//! # };
//! # }
//! #
//! use indoc::{concatdoc, printdoc};
//!
//! const HELP: &str = concatdoc! {"
//! Usage: ", env!("CARGO_BIN_NAME"), " [options]
//!
//! Options:
//! -h, --help
//! "};
//!
//! fn main() {
//! printdoc! {"
//! GET {url}
//! Accept: {mime}
//! ",
//! url = "http://localhost:8080",
//! mime = "application/json",
//! }
//! }
//! ```
//!
//! <br><br>
//!
//! # Explanation
//!
//! The following rules characterize the behavior of the `indoc!()` macro:
//!
//! 1. Count the leading spaces of each line, ignoring the first line and any
//! lines that are empty or contain spaces only.
//! 2. Take the minimum.
//! 3. If the first line is empty i.e. the string begins with a newline, remove
//! the first line.
//! 4. Remove the computed number of spaces from the beginning of each line.
#![doc(html_root_url = "https://docs.rs/indoc/2.0.7")]
#![allow(
clippy::derive_partial_eq_without_eq,
clippy::from_iter_instead_of_collect,
clippy::module_name_repetitions,
clippy::needless_doctest_main,
clippy::needless_pass_by_value,
clippy::trivially_copy_pass_by_ref,
clippy::type_complexity
)]
mod error;
mod expr;
#[allow(dead_code)]
mod unindent;
use crate::error::{Error, Result};
use crate::unindent::do_unindent;
use proc_macro::token_stream::IntoIter as TokenIter;
use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
use std::iter::{self, Peekable};
use std::str::FromStr;
#[derive(Copy, Clone, PartialEq)]
enum Macro {
Indoc,
Format,
Print,
Eprint,
Write,
Concat,
}
/// Unindent and produce `&'static str` or `&'static [u8]`.
///
/// Supports normal strings, raw strings, bytestrings, and raw bytestrings.
///
/// # Example
///
/// ```
/// # use indoc::indoc;
/// #
/// // The type of `program` is &'static str
/// let program = indoc! {"
/// def hello():
/// print('Hello, world!')
///
/// hello()
/// "};
/// print!("{}", program);
/// ```
///
/// ```text
/// def hello():
/// print('Hello, world!')
///
/// hello()
/// ```
#[proc_macro]
pub fn indoc(input: TokenStream) -> TokenStream {
expand(input, Macro::Indoc)
}
/// Unindent and call `format!`.
///
/// Argument syntax is the same as for [`std::format!`].
///
/// # Example
///
/// ```
/// # use indoc::formatdoc;
/// #
/// let request = formatdoc! {"
/// GET {url}
/// Accept: {mime}
/// ",
/// url = "http://localhost:8080",
/// mime = "application/json",
/// };
/// println!("{}", request);
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn formatdoc(input: TokenStream) -> TokenStream {
expand(input, Macro::Format)
}
/// Unindent and call `print!`.
///
/// Argument syntax is the same as for [`std::print!`].
///
/// # Example
///
/// ```
/// # use indoc::printdoc;
/// #
/// printdoc! {"
/// GET {url}
/// Accept: {mime}
/// ",
/// url = "http://localhost:8080",
/// mime = "application/json",
/// }
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn printdoc(input: TokenStream) -> TokenStream {
expand(input, Macro::Print)
}
/// Unindent and call `eprint!`.
///
/// Argument syntax is the same as for [`std::eprint!`].
///
/// # Example
///
/// ```
/// # use indoc::eprintdoc;
/// #
/// eprintdoc! {"
/// GET {url}
/// Accept: {mime}
/// ",
/// url = "http://localhost:8080",
/// mime = "application/json",
/// }
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn eprintdoc(input: TokenStream) -> TokenStream {
expand(input, Macro::Eprint)
}
/// Unindent and call `write!`.
///
/// Argument syntax is the same as for [`std::write!`].
///
/// # Example
///
/// ```
/// # use indoc::writedoc;
/// # use std::io::Write;
/// #
/// let _ = writedoc!(
/// std::io::stdout(),
/// "
/// GET {url}
/// Accept: {mime}
/// ",
/// url = "http://localhost:8080",
/// mime = "application/json",
/// );
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn writedoc(input: TokenStream) -> TokenStream {
expand(input, Macro::Write)
}
/// Unindent and call `concat!`.
///
/// Argument syntax is the same as for [`std::concat!`].
///
/// # Example
///
/// ```
/// # use indoc::concatdoc;
/// #
/// # macro_rules! env {
/// # ($var:literal) => {
/// # "example"
/// # };
/// # }
/// #
/// const HELP: &str = concatdoc! {"
/// Usage: ", env!("CARGO_BIN_NAME"), " [options]
///
/// Options:
/// -h, --help
/// "};
///
/// print!("{}", HELP);
/// ```
///
/// ```text
/// Usage: example [options]
///
/// Options:
/// -h, --help
/// ```
#[proc_macro]
pub fn concatdoc(input: TokenStream) -> TokenStream {
expand(input, Macro::Concat)
}
fn expand(input: TokenStream, mode: Macro) -> TokenStream {
match try_expand(input, mode) {
Ok(tokens) => tokens,
Err(err) => err.to_compile_error(),
}
}
fn try_expand(input: TokenStream, mode: Macro) -> Result<TokenStream> {
let mut input = input.into_iter().peekable();
let prefix = match mode {
Macro::Indoc | Macro::Format | Macro::Print | Macro::Eprint => None,
Macro::Write => {
let require_comma = true;
let mut expr = expr::parse(&mut input, require_comma)?;
expr.extend(iter::once(input.next().unwrap())); // add comma
Some(expr)
}
Macro::Concat => return do_concat(input),
};
let first = input.next().ok_or_else(|| {
Error::new(
Span::call_site(),
"unexpected end of macro invocation, expected format string",
)
})?;
let preserve_empty_first_line = false;
let unindented_lit = lit_indoc(first, mode, preserve_empty_first_line)?;
let macro_name = match mode {
Macro::Indoc => {
require_empty_or_trailing_comma(&mut input)?;
return Ok(TokenStream::from(TokenTree::Literal(unindented_lit)));
}
Macro::Format => "format",
Macro::Print => "print",
Macro::Eprint => "eprint",
Macro::Write => "write",
Macro::Concat => unreachable!(),
};
// #macro_name! { #unindented_lit #args }
Ok(TokenStream::from_iter(vec![
TokenTree::Ident(Ident::new(macro_name, Span::call_site())),
TokenTree::Punct(Punct::new('!', Spacing::Alone)),
TokenTree::Group(Group::new(
Delimiter::Brace,
prefix
.unwrap_or_else(TokenStream::new)
.into_iter()
.chain(iter::once(TokenTree::Literal(unindented_lit)))
.chain(input)
.collect(),
)),
]))
}
fn do_concat(mut input: Peekable<TokenIter>) -> Result<TokenStream> {
let mut result = TokenStream::new();
let mut first = true;
while input.peek().is_some() {
let require_comma = false;
let mut expr = expr::parse(&mut input, require_comma)?;
let mut expr_tokens = expr.clone().into_iter();
if let Some(token) = expr_tokens.next() {
if expr_tokens.next().is_none() {
let preserve_empty_first_line = !first;
if let Ok(literal) = lit_indoc(token, Macro::Concat, preserve_empty_first_line) {
result.extend(iter::once(TokenTree::Literal(literal)));
expr = TokenStream::new();
}
}
}
result.extend(expr);
if let Some(comma) = input.next() {
result.extend(iter::once(comma));
} else {
break;
}
first = false;
}
// concat! { #result }
Ok(TokenStream::from_iter(vec![
TokenTree::Ident(Ident::new("concat", Span::call_site())),
TokenTree::Punct(Punct::new('!', Spacing::Alone)),
TokenTree::Group(Group::new(Delimiter::Brace, result)),
]))
}
fn lit_indoc(token: TokenTree, mode: Macro, preserve_empty_first_line: bool) -> Result<Literal> {
let span = token.span();
let mut single_token = Some(token);
while let Some(TokenTree::Group(group)) = single_token {
single_token = if group.delimiter() == Delimiter::None {
let mut token_iter = group.stream().into_iter();
token_iter.next().xor(token_iter.next())
} else {
None
};
}
let single_token =
single_token.ok_or_else(|| Error::new(span, "argument must be a single string literal"))?;
let repr = single_token.to_string();
let is_string = repr.starts_with('"') || repr.starts_with('r');
let is_byte_string = repr.starts_with("b\"") || repr.starts_with("br");
let is_c_string = repr.starts_with("c\"") || repr.starts_with("cr");
if !is_string && !is_byte_string && !is_c_string {
return Err(Error::new(span, "argument must be a single string literal"));
}
if let Some(restricted_kind) = if is_byte_string {
Some("byte strings")
} else if is_c_string {
Some("C-strings")
} else {
None
} {
match mode {
Macro::Indoc => {}
Macro::Format | Macro::Print | Macro::Eprint | Macro::Write => {
return Err(Error::new(
span,
format!("{restricted_kind} are not supported in formatting macros"),
));
}
Macro::Concat => {
return Err(Error::new(
span,
format!("{restricted_kind} are not supported in concat macro"),
));
}
}
}
let begin = repr.find('"').unwrap() + 1;
let end = repr.rfind('"').unwrap();
let repr = format!(
"{open}{content}{close}",
open = &repr[..begin],
content = do_unindent(&repr[begin..end], preserve_empty_first_line),
close = &repr[end..],
);
let mut lit = Literal::from_str(&repr).unwrap();
lit.set_span(span);
Ok(lit)
}
fn require_empty_or_trailing_comma(input: &mut Peekable<TokenIter>) -> Result<()> {
let first = match input.next() {
Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => match input.next() {
Some(second) => second,
None => return Ok(()),
},
Some(first) => first,
None => return Ok(()),
};
let last = input.last();
let begin_span = first.span();
let end_span = last.as_ref().map_or(begin_span, TokenTree::span);
let msg = format!(
"unexpected {token} in macro invocation; indoc argument must be a single string literal",
token = if last.is_some() { "tokens" } else { "token" }
);
Err(Error::new2(begin_span, end_span, &msg))
}
+120
View File
@@ -0,0 +1,120 @@
#![allow(unknown_lints, mismatched_lifetime_syntaxes)]
use std::slice::Split;
pub fn unindent(s: &str) -> String {
let preserve_empty_first_line = false;
do_unindent(s, preserve_empty_first_line)
}
// Compute the maximal number of spaces that can be removed from every line, and
// remove them.
pub fn unindent_bytes(s: &[u8]) -> Vec<u8> {
let preserve_empty_first_line = false;
do_unindent_bytes(s, preserve_empty_first_line)
}
pub(crate) fn do_unindent(s: &str, preserve_empty_first_line: bool) -> String {
let bytes = s.as_bytes();
let unindented = do_unindent_bytes(bytes, preserve_empty_first_line);
String::from_utf8(unindented).unwrap()
}
fn do_unindent_bytes(s: &[u8], preserve_empty_first_line: bool) -> Vec<u8> {
// Document may start either on the same line as opening quote or
// on the next line
let ignore_first_line =
!preserve_empty_first_line && (s.starts_with(b"\n") || s.starts_with(b"\r\n"));
// Largest number of spaces that can be removed from every
// non-whitespace-only line after the first
let spaces = s
.lines()
.skip(1)
.filter_map(count_spaces)
.min()
.unwrap_or(0);
let mut result = Vec::with_capacity(s.len());
for (i, line) in s.lines().enumerate() {
if i > 1 || (i == 1 && !ignore_first_line) {
result.push(b'\n');
}
if i == 0 {
// Do not un-indent anything on same line as opening quote
result.extend_from_slice(line);
} else if line.len() > spaces {
// Whitespace-only lines may have fewer than the number of spaces
// being removed
result.extend_from_slice(&line[spaces..]);
}
}
result
}
pub trait Unindent {
type Output;
fn unindent(&self) -> Self::Output;
}
impl Unindent for str {
type Output = String;
fn unindent(&self) -> Self::Output {
unindent(self)
}
}
impl Unindent for String {
type Output = String;
fn unindent(&self) -> Self::Output {
unindent(self)
}
}
impl Unindent for [u8] {
type Output = Vec<u8>;
fn unindent(&self) -> Self::Output {
unindent_bytes(self)
}
}
impl<T: ?Sized + Unindent> Unindent for &T {
type Output = T::Output;
fn unindent(&self) -> Self::Output {
(**self).unindent()
}
}
// Number of leading spaces in the line, or None if the line is entirely spaces.
fn count_spaces(line: &[u8]) -> Option<usize> {
for (i, ch) in line.iter().enumerate() {
if *ch != b' ' && *ch != b'\t' {
return Some(i);
}
}
None
}
// Based on core::str::StrExt.
trait BytesExt {
fn lines(&self) -> Split<u8, fn(&u8) -> bool>;
}
impl BytesExt for [u8] {
fn lines(&self) -> Split<u8, fn(&u8) -> bool> {
fn is_newline(b: &u8) -> bool {
*b == b'\n'
}
let bytestring = if self.starts_with(b"\r\n") {
&self[1..]
} else {
self
};
bytestring.split(is_newline as fn(&u8) -> bool)
}
}
+7
View File
@@ -0,0 +1,7 @@
#[rustversion::attr(not(nightly), ignore = "requires nightly")]
#[cfg_attr(miri, ignore = "incompatible with miri")]
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs");
}
+20
View File
@@ -0,0 +1,20 @@
use indoc::concatdoc;
macro_rules! env {
($var:literal) => {
"test"
};
}
static HELP: &str = concatdoc! {"
Usage: ", env!("CARGO_BIN_NAME"), " [options]
Options:
-h, --help
"};
#[test]
fn test_help() {
let expected = "Usage: test [options]\n\nOptions:\n -h, --help\n";
assert_eq!(HELP, expected);
}
+25
View File
@@ -0,0 +1,25 @@
use indoc::indoc;
#[test]
fn c_string() {
let indoc = indoc! {c"
a
\\b
c"
};
let expected = c"a\n\n \\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn raw_c_string() {
let indoc = indoc! {cr#"
"a"
\\b
c"#
};
let expected = c"\"a\"\n\n \\\\b\nc";
assert_eq!(indoc, expected);
}
+117
View File
@@ -0,0 +1,117 @@
use indoc::formatdoc;
#[test]
fn carriage_return() {
// Every line in the string ends with \r\n
let indoc = formatdoc! {"
{}
\\{}
{}",
'a', 'b', 'c'
};
let expected = "a\n\n \\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn empty_string() {
let indoc = formatdoc! {""};
let expected = "";
assert_eq!(indoc, expected);
}
#[test]
fn joined_first_line() {
let indoc = formatdoc! {"\
{}", 'a'
};
let expected = "a";
assert_eq!(indoc, expected);
}
#[test]
fn joined_lines() {
let indoc = formatdoc! {"
{}\
{}
{}\
{}
{}",
'a', 'b', 'c', 'd', 'e'
};
let expected = "ab\ncd\ne";
assert_eq!(indoc, expected);
}
#[test]
fn no_leading_newline() {
let indoc = formatdoc! {"{}
{}
{}", 'a', 'b', 'c'};
let expected = "a\nb\nc";
assert_eq!(indoc, expected);
}
#[test]
fn one_line() {
let indoc = formatdoc! {"a"};
let expected = "a";
assert_eq!(indoc, expected);
}
#[test]
fn raw_string() {
let indoc = formatdoc! {r#"
{:?}"
\\{}
{}"#,
"a", 'b', 'c'
};
let expected = "\"a\"\"\n\n \\\\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn string() {
let indoc = formatdoc! {"
{}
\\{}
{}",
'a', 'b', 'c'
};
let expected = "a\n\n \\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn string_trailing_newline() {
let indoc = formatdoc! {"
{}
\\{}
{}
",
'a', 'b', 'c'
};
let expected = "a\n\n \\b\nc\n";
assert_eq!(indoc, expected);
}
#[test]
fn trailing_whitespace() {
let indoc = formatdoc! {"
{} {below}
{} {below}
{} {below}
end",
2, 0, -2, below = "below"
};
let expected = "2 below\n \n0 below\n\n-2 below\n\nend";
assert_eq!(indoc, expected);
}
+179
View File
@@ -0,0 +1,179 @@
#[cfg(indoc_test_cstr)]
mod test_cstr;
use indoc::indoc;
const HELP: &str = indoc! {"
Usage: ./foo
"};
#[test]
fn byte_string() {
let indoc = indoc! {b"
a
\\b
c"
};
let expected = b"a\n\n \\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn carriage_return() {
// Every line in the string ends with \r\n
let indoc = indoc! {"
a
\\b
c"
};
let expected = "a\n\n \\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn empty_string() {
let indoc = indoc! {""};
let expected = "";
assert_eq!(indoc, expected);
}
#[test]
fn global() {
let expected = "Usage: ./foo\n";
assert_eq!(HELP, expected);
}
#[test]
fn indoc_as_format_string() {
let s = format!(indoc! {"{}"}, true);
assert_eq!(s, "true");
}
#[test]
fn joined_first_line() {
let indoc = indoc! {"\
a"
};
let expected = "a";
assert_eq!(indoc, expected);
}
#[test]
fn joined_lines() {
let indoc = indoc! {"
a\
b
c\
d
e"
};
let expected = "ab\ncd\ne";
assert_eq!(indoc, expected);
}
#[test]
fn metavariable() {
macro_rules! indoc_wrapper {
($e:expr) => {
indoc!($e)
};
}
let indoc = indoc_wrapper! {"
macros, how do they work
"};
let expected = "macros, how do they work\n";
assert_eq!(indoc, expected);
}
#[test]
fn no_leading_newline() {
let indoc = indoc! {"a
b
c"};
let expected = "a\nb\nc";
assert_eq!(indoc, expected);
}
#[test]
fn one_line() {
let indoc = indoc! {"a"};
let expected = "a";
assert_eq!(indoc, expected);
}
#[test]
fn raw_byte_string() {
let indoc = indoc! {br#"
"a"
\\b
c"#
};
let expected = b"\"a\"\n\n \\\\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn raw_string() {
let indoc = indoc! {r#"
"a"
\\b
c"#
};
let expected = "\"a\"\n\n \\\\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn string() {
let indoc = indoc! {"
a
\\b
c"
};
let expected = "a\n\n \\b\nc";
assert_eq!(indoc, expected);
}
#[test]
fn string_trailing_newline() {
let indoc = indoc! {"
a
\\b
c
"};
let expected = "a\n\n \\b\nc\n";
assert_eq!(indoc, expected);
}
#[test]
fn trailing_comma() {
let indoc = indoc! {
"
test
",
};
let expected = "test\n";
assert_eq!(indoc, expected);
}
#[test]
fn trailing_whitespace() {
let indoc = indoc! {"
2 below
0 below
-2 below
end"
};
let expected = "2 below\n \n0 below\n\n-2 below\n\nend";
assert_eq!(indoc, expected);
}
+53
View File
@@ -0,0 +1,53 @@
#![allow(clippy::shadow_unrelated)]
use unindent::{unindent, unindent_bytes, Unindent};
#[test]
fn fn_unindent_str() {
let s = "
line one
line two";
assert_eq!(unindent(s), "line one\nline two");
let s = "\n\t\t\tline one\n\t\t\tline two";
assert_eq!(unindent(s), "line one\nline two");
}
#[test]
fn fn_unindent_bytes() {
let b = b"
line one
line two";
assert_eq!(unindent_bytes(b), b"line one\nline two");
let b = b"\n\t\t\tline one\n\t\t\tline two";
assert_eq!(unindent_bytes(b), b"line one\nline two");
}
#[test]
fn trait_unindent_str() {
let s = "
line one
line two";
assert_eq!(s.unindent(), "line one\nline two");
let s = "\n\t\t\tline one\n\t\t\tline two";
assert_eq!(s.unindent(), "line one\nline two");
}
#[test]
fn trait_unindent_bytes() {
let b = b"
line one
line two";
assert_eq!(b.unindent(), b"line one\nline two");
let b = b"\n\t\t\tline one\n\t\t\tline two";
assert_eq!(b.unindent(), b"line one\nline two");
}
#[test]
fn carriage_returns() {
let s = "\r\n\tline one\r\n\tline two";
assert_eq!(unindent(s), "line one\r\nline two");
}
+57
View File
@@ -0,0 +1,57 @@
#![allow(clippy::if_same_then_else, clippy::let_underscore_untyped)]
use indoc::writedoc;
use std::fmt::Write as _;
#[test]
fn test_write_to_string() {
let mut s = String::new();
writedoc!(
s,
"
one
two
",
)
.unwrap();
let expected = "one\ntwo\n";
assert_eq!(s, expected);
}
#[test]
fn test_format_args() {
let mut s = String::new();
writedoc!(
s,
"
{}
{}
",
0,
0,
)
.unwrap();
let expected = "0\n0\n";
assert_eq!(s, expected);
}
#[test]
fn test_angle_bracket_parsing() {
const ZERO: usize = 0;
struct Pair<A, B>(A, B);
impl<A, B> Pair<A, B> {
const ONE: usize = 1;
}
let mut s = String::new();
let _ = writedoc! {
if ZERO < Pair::<fn() -> (), ()>::ONE { &mut s } else { &mut s },
"writedoc",
};
let expected = "writedoc";
assert_eq!(s, expected);
}
@@ -0,0 +1,6 @@
use indoc::indoc;
fn main() {
let world = "world";
println!(indoc!("Hello {world}"));
}
@@ -0,0 +1,8 @@
error: there is no argument named `world`
--> tests/ui/capture-var-nested.rs:5:21
|
5 | println!(indoc!("Hello {world}"));
| ^^^^^^^^^^^^^^^
|
= note: did you intend to capture a variable `world` from the surrounding scope?
= note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro
+5
View File
@@ -0,0 +1,5 @@
use indoc::indoc;
fn main() {
indoc!();
}
@@ -0,0 +1,7 @@
error: unexpected end of macro invocation, expected format string
--> tests/ui/no-arguments.rs:4:5
|
4 | indoc!();
| ^^^^^^^^
|
= note: this error originates in the macro `indoc` (in Nightly builds, run with -Z macro-backtrace for more info)
+5
View File
@@ -0,0 +1,5 @@
use indoc::indoc;
fn main() {
indoc!(fail);
}
+5
View File
@@ -0,0 +1,5 @@
error: argument must be a single string literal
--> tests/ui/non-lit.rs:4:12
|
4 | indoc!(fail);
| ^^^^
+5
View File
@@ -0,0 +1,5 @@
use indoc::indoc;
fn main() {
indoc!(64);
}
+5
View File
@@ -0,0 +1,5 @@
error: argument must be a single string literal
--> tests/ui/non-string.rs:4:12
|
4 | indoc!(64);
| ^^
@@ -0,0 +1,5 @@
use indoc::printdoc;
fn main() {
printdoc!(b"");
}
@@ -0,0 +1,5 @@
error: byte strings are not supported in formatting macros
--> tests/ui/printdoc-binary.rs:4:15
|
4 | printdoc!(b"");
| ^^^
@@ -0,0 +1,5 @@
use indoc::printdoc;
fn main() {
printdoc!("", 0);
}
@@ -0,0 +1,12 @@
error: argument never used
--> tests/ui/printdoc-extra-arg.rs:4:19
|
4 | printdoc!("", 0);
| -- ^ argument never used
| |
| formatting specifier missing
|
help: format specifiers use curly braces, consider adding a format specifier
|
4 | printdoc!("{}", 0);
| ++
@@ -0,0 +1,5 @@
use indoc::printdoc;
fn main() {
printdoc!("{}");
}
@@ -0,0 +1,5 @@
error: 1 positional argument in format string, but no arguments were given
--> tests/ui/printdoc-no-arg.rs:4:16
|
4 | printdoc!("{}");
| ^^
@@ -0,0 +1,7 @@
use indoc::printdoc;
struct NoDisplay;
fn main() {
printdoc!("{}", NoDisplay);
}
@@ -0,0 +1,15 @@
error[E0277]: `NoDisplay` doesn't implement `std::fmt::Display`
--> tests/ui/printdoc-no-display.rs:6:21
|
6 | printdoc!("{}", NoDisplay);
| -- ^^^^^^^^^ `NoDisplay` cannot be formatted with the default formatter
| |
| required by this formatting parameter
|
help: the trait `std::fmt::Display` is not implemented for `NoDisplay`
--> tests/ui/printdoc-no-display.rs:3:1
|
3 | struct NoDisplay;
| ^^^^^^^^^^^^^^^^
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: this error originates in the macro `$crate::format_args` which comes from the expansion of the macro `printdoc` (in Nightly builds, run with -Z macro-backtrace for more info)
@@ -0,0 +1,5 @@
use indoc::printdoc;
fn main() {
printdoc!("{named}");
}
@@ -0,0 +1,5 @@
error[E0425]: cannot find value `named` in this scope
--> tests/ui/printdoc-no-named-arg.rs:4:17
|
4 | printdoc!("{named}");
| ^^^^^ not found in this scope
@@ -0,0 +1,9 @@
use indoc::indoc;
fn main() {
indoc!("
a
b
c
" 64 128);
}
@@ -0,0 +1,5 @@
error: unexpected tokens in macro invocation; indoc argument must be a single string literal
--> tests/ui/three-arguments.rs:8:11
|
8 | " 64 128);
| ^^^^^^
+9
View File
@@ -0,0 +1,9 @@
use indoc::indoc;
fn main() {
indoc!("
a
b
c
" 64);
}
@@ -0,0 +1,5 @@
error: unexpected token in macro invocation; indoc argument must be a single string literal
--> tests/ui/two-arguments.rs:8:11
|
8 | " 64);
| ^^