Backed out 6 changesets (bug 1787306) for causing Toolchains bustages. CLOSED TREE

Backed out changeset bcee96aa7df1 (bug 1787306)
Backed out changeset b5be37b86b21 (bug 1787306)
Backed out changeset 7e518de15dbb (bug 1787306)
Backed out changeset 07d938340e27 (bug 1787306)
Backed out changeset 9b8971442df5 (bug 1787306)
Backed out changeset 4d719c2b2711 (bug 1787306)
This commit is contained in:
criss 2022-08-26 02:25:46 +03:00
Родитель 34fe6c3121
Коммит 055a8632de
54 изменённых файлов: 269 добавлений и 2607 удалений

16
Cargo.lock сгенерированный
Просмотреть файл

@ -4574,12 +4574,6 @@ dependencies = [
"semver",
]
[[package]]
name = "rustversion"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8"
[[package]]
name = "ryu"
version = "1.0.11"
@ -4768,9 +4762,9 @@ dependencies = [
[[package]]
name = "serial_test"
version = "0.6.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5bcc41d18f7a1d50525d080fd3e953be87c4f9f1a974f3c21798ca00d54ec15"
checksum = "e0bccbcf40c8938196944a3da0e133e031a33f4d6b72db3bda3cc556e361905d"
dependencies = [
"lazy_static",
"parking_lot 0.11.2",
@ -4779,14 +4773,12 @@ dependencies = [
[[package]]
name = "serial_test_derive"
version = "0.6.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2881bccd7d60fb32dfa3d7b3136385312f8ad75e2674aab2852867a09790cae8"
checksum = "b2acd6defeddb41eb60bb468f8825d0cfd0c2a76bc03bfd235b6a1dc4f6a1ad5"
dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"rustversion",
"syn",
]

Просмотреть файл

@ -19,7 +19,7 @@ unic-langid = "0.9"
[dev-dependencies]
unic-langid = { version = "0.9", features = ["macros"] }
serial_test = "0.6"
serial_test = "0.5"
# The mozilla-central vendoring process unfortunately always pulls in
# dev-dependencies. The criterion package pulls in duplicated versions of
# other crates as well as large data files that the vendoring process is

Просмотреть файл

@ -29,12 +29,6 @@ who = "Mike Hommey <mh+mozilla@glandium.org>"
criteria = "safe-to-deploy"
delta = "1.0.57 -> 1.0.61"
[[audits.anyhow]]
who = "Bobby Holley <bobbyholley@gmail.com>"
criteria = "safe-to-deploy"
delta = "1.0.58 -> 1.0.57"
notes = "No functional differences, just CI config and docs."
[[audits.anyhow]]
who = "Mike Hommey <mh+mozilla@glandium.org>"
criteria = "safe-to-deploy"
@ -118,16 +112,6 @@ who = "Jeff Muizelaar <jmuizelaar@mozilla.com>"
criteria = "safe-to-deploy"
version = "0.1.2"
[[audits.bumpalo]]
who = "Bobby Holley <bobbyholley@gmail.com>"
criteria = "safe-to-run"
delta = "3.9.1 -> 3.10.0"
notes = """
Some nontrivial functional changes but certainly meets the no-malware bar of
safe-to-run. If we needed safe-to-deploy for this in m-c I'd ask Nick to re-
certify this version, but we don't, so this is fine for now.
"""
[[audits.bytes]]
who = "Mike Hommey <mh+mozilla@glandium.org>"
criteria = "safe-to-deploy"
@ -658,17 +642,6 @@ criteria = "safe-to-deploy"
version = "1.1.0"
notes = "Straightforward crate with no unsafe code, does what it says on the tin."
[[audits.rustversion]]
who = "Bobby Holley <bobbyholley@gmail.com>"
criteria = "safe-to-deploy"
version = "1.0.9"
notes = """
This crate has a build-time component and procedural macro logic, which I looked
at enough to convince myself it wasn't going to do anything dramatically wrong.
I don't think logic bugs in the version parsing etc can realistically introduce
a security vulnerability.
"""
[[audits.ryu]]
who = "Mike Hommey <mh+mozilla@glandium.org>"
criteria = "safe-to-deploy"

Просмотреть файл

@ -1,12 +1,6 @@
# cargo-vet config file
[imports.bytecodealliance]
url = "https://raw.githubusercontent.com/bytecodealliance/wasmtime/main/supply-chain/audits.toml"
[imports.embark]
url = "https://raw.githubusercontent.com/EmbarkStudios/rust-ecosystem/main/audits.toml"
[policy.async-task]
audit-as-crates-io = true
notes = "This is the upstream code plus an extra fix that hasn't been released yet, see bug 1746533."
@ -187,6 +181,10 @@ criteria = "safe-to-deploy"
version = "0.2.0"
criteria = "safe-to-deploy"
[[exemptions.anyhow]]
version = "1.0.57"
criteria = "safe-to-deploy"
[[exemptions.arbitrary]]
version = "1.1.0"
criteria = "safe-to-run"
@ -195,6 +193,10 @@ criteria = "safe-to-run"
version = "0.3.6"
criteria = "safe-to-deploy"
[[exemptions.arrayvec]]
version = "0.7.2"
criteria = "safe-to-deploy"
[[exemptions.ash]]
version = "0.37.0+1.3.209"
criteria = "safe-to-deploy"
@ -279,6 +281,10 @@ criteria = "safe-to-deploy"
version = "0.10.2"
criteria = "safe-to-deploy"
[[exemptions.bumpalo]]
version = "3.10.0"
criteria = "safe-to-run"
[[exemptions.byteorder]]
version = "1.4.3"
criteria = "safe-to-deploy"
@ -303,10 +309,18 @@ criteria = "safe-to-deploy"
version = "0.14.2"
criteria = "safe-to-deploy"
[[exemptions.cc]]
version = "1.0.73"
criteria = "safe-to-deploy"
[[exemptions.cexpr]]
version = "0.6.0"
criteria = "safe-to-deploy"
[[exemptions.cfg-if]]
version = "1.0.0"
criteria = "safe-to-deploy"
[[exemptions.cfg_aliases]]
version = "0.1.1"
criteria = "safe-to-deploy"
@ -427,6 +441,10 @@ criteria = "safe-to-deploy"
version = "0.6.0"
criteria = "safe-to-deploy"
[[exemptions.cty]]
version = "0.2.2"
criteria = "safe-to-deploy"
[[exemptions.cubeb]]
version = "0.10.0"
criteria = "safe-to-deploy"
@ -1239,6 +1257,10 @@ criteria = "safe-to-deploy"
version = "1.24.0"
criteria = "safe-to-deploy"
[[exemptions.rustc-demangle]]
version = "0.1.21"
criteria = "safe-to-deploy"
[[exemptions.rustc_version]]
version = "0.4.0"
criteria = "safe-to-deploy"
@ -1319,6 +1341,14 @@ criteria = "safe-to-deploy"
version = "0.8.24"
criteria = "safe-to-run"
[[exemptions.serial_test]]
version = "0.5.1"
criteria = "safe-to-run"
[[exemptions.serial_test_derive]]
version = "0.5.1"
criteria = "safe-to-run"
[[exemptions.servo_arc]]
version = "0.1.1"
criteria = "safe-to-deploy"

Просмотреть файл

@ -1,141 +1,5 @@
# cargo-vet imports lock
[[audits.bytecodealliance.audits.arrayvec]]
who = "Nick Fitzgerald <fitzgen@gmail.com>"
criteria = "safe-to-deploy"
version = "0.7.2"
notes = """
Well documented invariants, good assertions for those invariants in unsafe code,
and tested with MIRI to boot. LGTM.
"""
[[audits.bytecodealliance.audits.bumpalo]]
who = "Nick Fitzgerald <fitzgen@gmail.com>"
criteria = "safe-to-deploy"
version = "3.9.1"
notes = "I am the author of this crate."
[[audits.bytecodealliance.audits.cc]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "1.0.73"
notes = "I am the author of this crate."
[[audits.bytecodealliance.audits.cfg-if]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "1.0.0"
notes = "I am the author of this crate."
[[audits.bytecodealliance.audits.rustc-demangle]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.1.21"
notes = "I am the author of this crate."
[[audits.bytecodealliance.audits.wasm-encoder]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.14.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasm-encoder]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.15.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasm-encoder]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.16.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasm-smith]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.11.2"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasm-smith]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.11.3"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasm-smith]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.11.4"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasmparser]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.87.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasmparser]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.88.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasmparser]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.89.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wasmparser]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "0.89.1"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wast]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "35.0.2"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.bytecodealliance.audits.wast]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "44.0.0"
notes = "The Bytecode Alliance is the author of this crate"
[[audits.bytecodealliance.audits.wast]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "45.0.0"
notes = "The Bytecode Alliance is the author of this crate"
[[audits.bytecodealliance.audits.wast]]
who = "Alex Crichton <alex@alexcrichton.com>"
criteria = "safe-to-deploy"
version = "46.0.0"
notes = "The Bytecode Alliance is the author of this crate."
[[audits.embark.audits.anyhow]]
who = "Johan Andersson <johan@embark-studios.com>"
criteria = "safe-to-deploy"
version = "1.0.58"
[[audits.embark.audits.cty]]
who = "Johan Andersson <johan@embark-studios.com>"
criteria = "safe-to-deploy"
version = "0.2.2"
notes = "Inspected it and is a tiny crate with just type definitions"
[[audits.embark.audits.serial_test]]
who = "Johan Andersson <johan@embark-studios.com>"
criteria = "safe-to-run"
version = "0.6.0"
[[audits.embark.audits.serial_test_derive]]
who = "Johan Andersson <johan@embark-studios.com>"
criteria = "safe-to-run"
version = "0.6.0"
[audits]

Просмотреть файл

@ -607,7 +607,7 @@ cargo-vet:
fetch:
type: git
repo: https://github.com/mozilla/cargo-vet
revision: e68d6189e2759307495bc2c1c9b5284111cb6060
revision: 16e5c986f3204889910720b647a2ef25dd417f13
symbol-scrapers:
description: Linux distribution symbol scraper source

Просмотреть файл

@ -1 +0,0 @@
{"files":{"Cargo.toml":"3202b894e27f099c5ff334d76e1c587704e7f4e4aa60fe1eb2f9135738b72aa8","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"2741e29db14c0f91aefa4ec9293ea03734b3ab052faf7dce93114ace54e995ef","build/build.rs":"2570716746a6607a37d3a54ae80e11767d69942eac6b37cb5b45244d1d229bd6","build/rustc.rs":"0de80a0590facf36d76fa89c566789c774f5bfc3b787fe8d5b61f668deaed3f9","src/attr.rs":"9301cd4aff5a9648c057d5d8de9eb66921f0c3a715c51ada4459576bd49c8b19","src/bound.rs":"44bda74d3aacfeeeac9dae2f7eef3acc844d4c3c7eaa9d3e6288e5aeff269dff","src/constfn.rs":"613b8f53b21cc06b4f619fce9000993d3e7873b650701ca01cef1e53bed5b40a","src/date.rs":"454c749a60db8144a706a813e06fe3ae39c981920ba9832ef82f3f9debe1f052","src/error.rs":"cb37102f03ebbaca313d80f9714fe08dfef92fe956789ee87d93eb6121705f4f","src/expand.rs":"cfd1772b1af090532de1f318e1b61cc79c8004941a8c56a1a7f4962324b81c9d","src/expr.rs":"8e8ca76f4f5838436d9d7273f499c698bb41f6c15bc07d32ec5c1cb8bd3dd731","src/iter.rs":"8d4b817b9abc4e817105b673e15f29ef9bb8284a010ce01ac2d83387fe136947","src/lib.rs":"126c0c7c3305b1afd4995507f0b8f82f4ea2583cb89f3c6354a05b80434c090a","src/release.rs":"abb8ddd877c39a023bf5e7bd67063d6e4144e79758a8bafa338167f9d15b89f1","src/time.rs":"bdd05a743b07a6bbfa0dbc9d4e415e051aba4a51a430c3be1e23447eae298c8b","src/token.rs":"824ce765f692db73afa02d3ebb0281c750748035efc98fa547be29d3072665ce","src/version.rs":"afdb048bba95bbb885945eba5527b6bf0eca0105642bfc304c2f82a8b7d556df","tests/compiletest.rs":"022a8e400ef813d7ea1875b944549cee5125f6a995dc33e93b48cba3e1b57bd1","tests/test_const.rs":"44d72ea92a81544692ccabe7e93f5d560d29828e79835e9f9839fbb40acc499a","tests/test_eval.rs":"6f0ee3f49c9a0d0c374a4d0e9a9dce753cd9fc2ca7725e000a435dbd5f4a9ce3","tests/test_parse.rs":"a9d262ea18109f792da719c29f3434a2f6a5e5723286385a099359795495b6fb","tests/ui/bad-bound.rs":"25bde278fcaabf62868417148a5e5f2006bf589d7ebd7bf6004fb8d78e47594f","tests/ui/bad-bound.stderr":"96b5549a312cd64d503c560026a6f0e97ac2173fe7c136a14425f19dcb5968e3","tests/ui/bad-date.rs":"6e23714dae8b6346fefe50dacd4abba3265248bbadfdd60c739138aa8a0037ba","tests/ui/bad-date.stderr":"3cc6d10572b80d397954737340d444c541d2c0e54e7d26495861d6189b6b2a55","tests/ui/bad-not.rs":"f003df8bd245e9dd8edc3a6d94078ee5162fac7a98db881271f0f5b6db98d45d","tests/ui/bad-not.stderr":"1aebb3121d067d432a32dd95ff380ceac15a0531c34f90cee950582558841c56","tests/ui/bad-version.rs":"f4ea2cd038e6c63deb9c2e3ceffce93dbf179d9ce18c16d88f3b6cd7138a8c8e","tests/ui/bad-version.stderr":"e9421586d59cb9135123bd97710655014f95cc5f55b0f9611e1d2e8ce9e29a5d","tests/ui/const-not-fn.rs":"10bbe38f0d89391fff0698756e4cfd4e72a41090360393a0c951b67df14d1c35","tests/ui/const-not-fn.stderr":"1180662fd3b8c4426d46923918a2e58dd9b6259f1a364469ae13d5fc3d69ce6c"},"package":"97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8"}

37
third_party/rust/rustversion/Cargo.toml поставляемый
Просмотреть файл

@ -1,37 +0,0 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.31"
name = "rustversion"
version = "1.0.9"
authors = ["David Tolnay <dtolnay@gmail.com>"]
build = "build/build.rs"
description = "Conditional compilation according to rustc compiler version"
documentation = "https://docs.rs/rustversion"
readme = "README.md"
categories = [
"development-tools::build-utils",
"no-std",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/rustversion"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[lib]
proc-macro = true
[dev-dependencies.trybuild]
version = "1.0.49"
features = ["diff"]

201
third_party/rust/rustversion/LICENSE-APACHE поставляемый
Просмотреть файл

@ -1,201 +0,0 @@
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.

23
third_party/rust/rustversion/LICENSE-MIT поставляемый
Просмотреть файл

@ -1,23 +0,0 @@
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.

139
third_party/rust/rustversion/README.md поставляемый
Просмотреть файл

@ -1,139 +0,0 @@
Compiler version cfg
====================
[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/rustversion-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/rustversion)
[<img alt="crates.io" src="https://img.shields.io/crates/v/rustversion.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/rustversion)
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-rustversion-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/rustversion)
[<img alt="build status" src="https://img.shields.io/github/workflow/status/dtolnay/rustversion/CI/master?style=for-the-badge" height="20">](https://github.com/dtolnay/rustversion/actions?query=branch%3Amaster)
This crate provides macros for conditional compilation according to rustc
compiler version, analogous to [`#[cfg(...)]`][cfg] and
[`#[cfg_attr(...)]`][cfg_attr].
[cfg]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute
[cfg_attr]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute
```toml
[dependencies]
rustversion = "1.0"
```
<br>
## Selectors
- <b>`#[rustversion::stable]`</b>
<br>
True on any stable compiler.
- <b>`#[rustversion::stable(1.34)]`</b>
<br>
True on exactly the specified stable compiler.
- <b>`#[rustversion::beta]`</b>
<br>
True on any beta compiler.
- <b>`#[rustversion::nightly]`</b>
<br>
True on any nightly compiler or dev build.
- <b>`#[rustversion::nightly(2019-01-01)]`</b>
<br>
True on exactly one nightly.
- <b>`#[rustversion::since(1.34)]`</b>
<br>
True on that stable release and any later compiler, including beta and
nightly.
- <b>`#[rustversion::since(2019-01-01)]`</b>
<br>
True on that nightly and all newer ones.
- <b>`#[rustversion::before(`</b><i>version or date</i><b>`)]`</b>
<br>
Negative of *#[rustversion::since(...)]*.
- <b>`#[rustversion::not(`</b><i>selector</i><b>`)]`</b>
<br>
Negative of any selector; for example *#[rustversion::not(nightly)]*.
- <b>`#[rustversion::any(`</b><i>selectors...</i><b>`)]`</b>
<br>
True if any of the comma-separated selectors is true; for example
*#[rustversion::any(stable, beta)]*.
- <b>`#[rustversion::all(`</b><i>selectors...</i><b>`)]`</b>
<br>
True if all of the comma-separated selectors are true; for example
*#[rustversion::all(since(1.31), before(1.34))]*.
- <b>`#[rustversion::attr(`</b><i>selector</i><b>`, `</b><i>attribute</i><b>`)]`</b>
<br>
For conditional inclusion of attributes; analogous to `cfg_attr`.
<br>
## Use cases
Providing additional trait impls as types are stabilized in the standard library
without breaking compatibility with older compilers; in this case Pin\<P\>
stabilized in [Rust 1.33][pin]:
[pin]: https://blog.rust-lang.org/2019/02/28/Rust-1.33.0.html#pinning
```rust
#[rustversion::since(1.33)]
use std::pin::Pin;
#[rustversion::since(1.33)]
impl<P: MyTrait> MyTrait for Pin<P> {
/* ... */
}
```
Similar but for language features; the ability to control alignment greater than
1 of packed structs was stabilized in [Rust 1.33][packed].
[packed]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1330-2019-02-28
```rust
#[rustversion::attr(before(1.33), repr(packed))]
#[rustversion::attr(since(1.33), repr(packed(2)))]
struct Six(i16, i32);
fn main() {
println!("{}", std::mem::align_of::<Six>());
}
```
Augmenting code with `const` as const impls are stabilized in the standard
library. This use of `const` as an attribute is recognized as a special case by
the rustversion::attr macro.
```rust
use std::time::Duration;
#[rustversion::attr(since(1.32), const)]
fn duration_as_days(dur: Duration) -> u64 {
dur.as_secs() / 60 / 60 / 24
}
```
<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>

73
third_party/rust/rustversion/build/build.rs поставляемый
Просмотреть файл

@ -1,73 +0,0 @@
#![allow(
clippy::enum_glob_use,
clippy::must_use_candidate,
clippy::single_match_else
)]
mod rustc;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process::{self, Command};
fn main() {
let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc"));
let mut is_clippy_driver = false;
let version = loop {
let mut command = Command::new(&rustc);
if is_clippy_driver {
command.arg("--rustc");
}
command.arg("--version");
let output = match command.output() {
Ok(output) => output,
Err(e) => {
let rustc = rustc.to_string_lossy();
eprintln!("Error: failed to run `{} --version`: {}", rustc, e);
process::exit(1);
}
};
let string = match String::from_utf8(output.stdout) {
Ok(string) => string,
Err(e) => {
let rustc = rustc.to_string_lossy();
eprintln!(
"Error: failed to parse output of `{} --version`: {}",
rustc, e,
);
process::exit(1);
}
};
break match rustc::parse(&string) {
rustc::ParseResult::Success(version) => version,
rustc::ParseResult::OopsClippy if !is_clippy_driver => {
is_clippy_driver = true;
continue;
}
rustc::ParseResult::Unrecognized | rustc::ParseResult::OopsClippy => {
eprintln!(
"Error: unexpected output from `rustc --version`: {:?}\n\n\
Please file an issue in https://github.com/dtolnay/rustversion",
string
);
process::exit(1);
}
};
};
if version.minor < 38 {
// Prior to 1.38, a #[proc_macro] is not allowed to be named `cfg`.
println!("cargo:rustc-cfg=cfg_macro_not_allowed");
}
let version = format!("{:#?}\n", version);
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not set");
let out_file = Path::new(&out_dir).join("version.expr");
fs::write(out_file, version).expect("failed to write version.expr");
}

124
third_party/rust/rustversion/build/rustc.rs поставляемый
Просмотреть файл

@ -1,124 +0,0 @@
use self::Channel::*;
use std::fmt::{self, Debug};
pub enum ParseResult {
Success(Version),
OopsClippy,
Unrecognized,
}
#[cfg_attr(test, derive(PartialEq))]
pub struct Version {
pub minor: u16,
pub patch: u16,
pub channel: Channel,
}
#[cfg_attr(test, derive(PartialEq))]
pub enum Channel {
Stable,
Beta,
Nightly(Date),
Dev,
}
#[cfg_attr(test, derive(PartialEq))]
pub struct Date {
pub year: u16,
pub month: u8,
pub day: u8,
}
pub fn parse(string: &str) -> ParseResult {
let last_line = string.lines().last().unwrap_or(string);
let mut words = last_line.trim().split(' ');
match words.next() {
Some("rustc") => {}
Some(word) if word.starts_with("clippy") => return ParseResult::OopsClippy,
Some(_) | None => return ParseResult::Unrecognized,
}
parse_words(&mut words).map_or(ParseResult::Unrecognized, ParseResult::Success)
}
fn parse_words(words: &mut dyn Iterator<Item = &str>) -> Option<Version> {
let mut version_channel = words.next()?.split('-');
let version = version_channel.next()?;
let channel = version_channel.next();
let mut digits = version.split('.');
let major = digits.next()?;
if major != "1" {
return None;
}
let minor = digits.next()?.parse().ok()?;
let patch = digits.next().unwrap_or("0").parse().ok()?;
let channel = match channel {
None => Stable,
Some(channel) if channel == "dev" => Dev,
Some(channel) if channel.starts_with("beta") => Beta,
Some(channel) if channel == "nightly" => match words.next() {
Some(hash) if hash.starts_with('(') => match words.next() {
None if hash.ends_with(')') => Dev,
Some(date) if date.ends_with(')') => {
let mut date = date[..date.len() - 1].split('-');
let year = date.next()?.parse().ok()?;
let month = date.next()?.parse().ok()?;
let day = date.next()?.parse().ok()?;
match date.next() {
None => Nightly(Date { year, month, day }),
Some(_) => return None,
}
}
None | Some(_) => return None,
},
Some(_) => return None,
None => Dev,
},
Some(_) => return None,
};
Some(Version {
minor,
patch,
channel,
})
}
impl Debug for Version {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_struct("crate::version::Version")
.field("minor", &self.minor)
.field("patch", &self.patch)
.field("channel", &self.channel)
.finish()
}
}
impl Debug for Channel {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self {
Channel::Stable => formatter.write_str("crate::version::Channel::Stable"),
Channel::Beta => formatter.write_str("crate::version::Channel::Beta"),
Channel::Nightly(date) => formatter
.debug_tuple("crate::version::Channel::Nightly")
.field(date)
.finish(),
Channel::Dev => formatter.write_str("crate::version::Channel::Dev"),
}
}
}
impl Debug for Date {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
.debug_struct("crate::date::Date")
.field("year", &self.year)
.field("month", &self.month)
.field("day", &self.day)
.finish()
}
}

35
third_party/rust/rustversion/src/attr.rs поставляемый
Просмотреть файл

@ -1,35 +0,0 @@
use crate::error::{Error, Result};
use crate::expr::{self, Expr};
use crate::{iter, token};
use proc_macro::{Span, TokenStream};
pub struct Args {
pub condition: Expr,
pub then: Then,
}
pub enum Then {
Const(Span),
Attribute(TokenStream),
}
pub fn parse(input: TokenStream) -> Result<Args> {
let ref mut input = iter::new(input);
let condition = expr::parse(input)?;
token::parse_punct(input, ',')?;
if input.peek().is_none() {
return Err(Error::new(Span::call_site(), "expected one or more attrs"));
}
let const_span = token::parse_optional_keyword(input, "const");
let then = if let Some(const_span) = const_span {
token::parse_optional_punct(input, ',');
token::parse_end(input)?;
Then::Const(const_span)
} else {
Then::Attribute(input.collect())
};
Ok(Args { condition, then })
}

63
third_party/rust/rustversion/src/bound.rs поставляемый
Просмотреть файл

@ -1,63 +0,0 @@
use crate::date::{self, Date};
use crate::error::{Error, Result};
use crate::iter::Iter;
use crate::release::{self, Release};
use crate::time;
use crate::version::{Channel::*, Version};
use proc_macro::{Group, TokenTree};
use std::cmp::Ordering;
pub enum Bound {
Nightly(Date),
Stable(Release),
}
pub fn parse(paren: Group, iter: Iter) -> Result<Bound> {
if let Some(TokenTree::Literal(literal)) = iter.peek() {
let repr = literal.to_string();
if repr.starts_with(|ch: char| ch.is_ascii_digit()) {
if repr.contains('.') {
return release::parse(paren, iter).map(Bound::Stable);
} else {
return date::parse(paren, iter).map(Bound::Nightly);
}
}
}
let msg = format!(
"expected rustc release number like 1.31, or nightly date like {}",
time::today(),
);
Err(Error::group(paren, msg))
}
impl PartialEq<Bound> for Version {
fn eq(&self, rhs: &Bound) -> bool {
match rhs {
Bound::Nightly(date) => match self.channel {
Stable | Beta | Dev => false,
Nightly(nightly) => nightly == *date,
},
Bound::Stable(release) => {
self.minor == release.minor
&& release.patch.map_or(true, |patch| self.patch == patch)
}
}
}
}
impl PartialOrd<Bound> for Version {
fn partial_cmp(&self, rhs: &Bound) -> Option<Ordering> {
match rhs {
Bound::Nightly(date) => match self.channel {
Stable | Beta => Some(Ordering::Less),
Nightly(nightly) => Some(nightly.cmp(date)),
Dev => Some(Ordering::Greater),
},
Bound::Stable(release) => {
let version = (self.minor, self.patch);
let bound = (release.minor, release.patch.unwrap_or(0));
Some(version.cmp(&bound))
}
}
}
}

58
third_party/rust/rustversion/src/constfn.rs поставляемый
Просмотреть файл

@ -1,58 +0,0 @@
use crate::error::{Error, Result};
use proc_macro::{Ident, Span, TokenStream, TokenTree};
use std::iter;
#[derive(PartialOrd, PartialEq)]
enum Qualifiers {
None,
Async,
Unsafe,
Extern,
Abi,
}
impl Qualifiers {
fn from_ident(ident: &Ident) -> Self {
match ident.to_string().as_str() {
"async" => Qualifiers::Async,
"unsafe" => Qualifiers::Unsafe,
"extern" => Qualifiers::Extern,
_ => Qualifiers::None,
}
}
}
pub(crate) fn insert_const(input: TokenStream, const_span: Span) -> Result<TokenStream> {
let ref mut input = crate::iter::new(input);
let mut out = TokenStream::new();
let mut qualifiers = Qualifiers::None;
let mut pending = Vec::new();
while let Some(token) = input.next() {
match token {
TokenTree::Ident(ref ident) if ident.to_string() == "fn" => {
let const_ident = Ident::new("const", const_span);
out.extend(iter::once(TokenTree::Ident(const_ident)));
out.extend(pending);
out.extend(iter::once(token));
out.extend(input);
return Ok(out);
}
TokenTree::Ident(ref ident) if Qualifiers::from_ident(ident) > qualifiers => {
qualifiers = Qualifiers::from_ident(ident);
pending.push(token);
}
TokenTree::Literal(_) if qualifiers == Qualifiers::Extern => {
qualifiers = Qualifiers::Abi;
pending.push(token);
}
_ => {
qualifiers = Qualifiers::None;
out.extend(pending.drain(..));
out.extend(iter::once(token));
}
}
}
Err(Error::new(const_span, "only allowed on a fn item"))
}

50
third_party/rust/rustversion/src/date.rs поставляемый
Просмотреть файл

@ -1,50 +0,0 @@
use crate::error::{Error, Result};
use crate::iter::Iter;
use crate::{time, token};
use proc_macro::Group;
use std::fmt::{self, Display};
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Date {
pub year: u16,
pub month: u8,
pub day: u8,
}
impl Display for Date {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"{:04}-{:02}-{:02}",
self.year, self.month, self.day,
)
}
}
pub fn parse(paren: Group, iter: Iter) -> Result<Date> {
try_parse(iter).map_err(|_| {
let msg = format!("expected nightly date, like {}", time::today());
Error::group(paren, msg)
})
}
fn try_parse(iter: Iter) -> Result<Date, ()> {
let year = token::parse_literal(iter).map_err(drop)?;
token::parse_punct(iter, '-').map_err(drop)?;
let month = token::parse_literal(iter).map_err(drop)?;
token::parse_punct(iter, '-').map_err(drop)?;
let day = token::parse_literal(iter).map_err(drop)?;
let year = year.to_string().parse::<u64>().map_err(drop)?;
let month = month.to_string().parse::<u64>().map_err(drop)?;
let day = day.to_string().parse::<u64>().map_err(drop)?;
if year >= 3000 || month > 12 || day > 31 {
return Err(());
}
Ok(Date {
year: year as u16,
month: month as u8,
day: day as u8,
})
}

56
third_party/rust/rustversion/src/error.rs поставляемый
Просмотреть файл

@ -1,56 +0,0 @@
use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
use std::fmt::Display;
use std::iter::FromIterator;
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub struct Error {
begin: Span,
end: Span,
msg: String,
}
impl Error {
pub fn new(span: Span, msg: impl Display) -> Self {
Self::new2(span, span, msg)
}
pub fn new2(begin: Span, end: Span, msg: impl Display) -> Self {
Error {
begin,
end,
msg: msg.to_string(),
}
}
pub fn group(group: Group, msg: impl Display) -> Self {
let mut iter = group.stream().into_iter();
let delimiter = group.span();
let begin = iter.next().map_or(delimiter, |t| t.span());
let end = iter.last().map_or(begin, |t| t.span());
Self::new2(begin, end, msg)
}
pub fn into_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
}),
])
}
}

72
third_party/rust/rustversion/src/expand.rs поставляемый
Просмотреть файл

@ -1,72 +0,0 @@
use crate::attr::{self, Then};
use crate::error::{Error, Result};
use crate::{constfn, expr, iter, token};
use proc_macro::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
pub fn cfg(introducer: &str, args: TokenStream, input: TokenStream) -> TokenStream {
try_cfg(introducer, args, input).unwrap_or_else(Error::into_compile_error)
}
fn try_cfg(introducer: &str, args: TokenStream, input: TokenStream) -> Result<TokenStream> {
let introducer = Ident::new(introducer, Span::call_site());
let mut full_args = TokenStream::from(TokenTree::Ident(introducer));
if !args.is_empty() {
full_args.extend(std::iter::once(TokenTree::Group(Group::new(
Delimiter::Parenthesis,
args,
))));
}
let ref mut full_args = iter::new(full_args);
let expr = expr::parse(full_args)?;
token::parse_end(full_args)?;
if expr.eval(crate::RUSTVERSION) {
Ok(input)
} else {
Ok(TokenStream::new())
}
}
pub fn try_attr(args: attr::Args, input: TokenStream) -> Result<TokenStream> {
if !args.condition.eval(crate::RUSTVERSION) {
return Ok(input);
}
match args.then {
Then::Const(const_token) => constfn::insert_const(input, const_token),
Then::Attribute(then) => {
// #[cfg_attr(all(), #then)]
Ok(TokenStream::from_iter(
vec![
TokenTree::Punct(Punct::new('#', Spacing::Alone)),
TokenTree::Group(Group::new(
Delimiter::Bracket,
TokenStream::from_iter(vec![
TokenTree::Ident(Ident::new("cfg_attr", Span::call_site())),
TokenTree::Group(Group::new(
Delimiter::Parenthesis,
TokenStream::from_iter(
vec![
TokenTree::Ident(Ident::new("all", Span::call_site())),
TokenTree::Group(Group::new(
Delimiter::Parenthesis,
TokenStream::new(),
)),
TokenTree::Punct(Punct::new(',', Spacing::Alone)),
]
.into_iter()
.chain(then),
),
)),
]),
)),
]
.into_iter()
.chain(input),
))
}
}
}

163
third_party/rust/rustversion/src/expr.rs поставляемый
Просмотреть файл

@ -1,163 +0,0 @@
use crate::bound::{self, Bound};
use crate::date::{self, Date};
use crate::error::{Error, Result};
use crate::iter::{self, Iter};
use crate::release::{self, Release};
use crate::token;
use crate::version::{Channel, Version};
use proc_macro::{Ident, Span, TokenTree};
pub enum Expr {
Stable,
Beta,
Nightly,
Date(Date),
Since(Bound),
Before(Bound),
Release(Release),
Not(Box<Expr>),
Any(Vec<Expr>),
All(Vec<Expr>),
}
impl Expr {
pub fn eval(&self, rustc: Version) -> bool {
use self::Expr::*;
match self {
Stable => rustc.channel == Channel::Stable,
Beta => rustc.channel == Channel::Beta,
Nightly => match rustc.channel {
Channel::Nightly(_) | Channel::Dev => true,
Channel::Stable | Channel::Beta => false,
},
Date(date) => match rustc.channel {
Channel::Nightly(rustc) => rustc == *date,
Channel::Stable | Channel::Beta | Channel::Dev => false,
},
Since(bound) => rustc >= *bound,
Before(bound) => rustc < *bound,
Release(release) => {
rustc.channel == Channel::Stable
&& rustc.minor == release.minor
&& release.patch.map_or(true, |patch| rustc.patch == patch)
}
Not(expr) => !expr.eval(rustc),
Any(exprs) => exprs.iter().any(|e| e.eval(rustc)),
All(exprs) => exprs.iter().all(|e| e.eval(rustc)),
}
}
}
pub fn parse(iter: Iter) -> Result<Expr> {
match &iter.next() {
Some(TokenTree::Ident(i)) if i.to_string() == "stable" => parse_stable(iter),
Some(TokenTree::Ident(i)) if i.to_string() == "beta" => Ok(Expr::Beta),
Some(TokenTree::Ident(i)) if i.to_string() == "nightly" => parse_nightly(iter),
Some(TokenTree::Ident(i)) if i.to_string() == "since" => parse_since(i, iter),
Some(TokenTree::Ident(i)) if i.to_string() == "before" => parse_before(i, iter),
Some(TokenTree::Ident(i)) if i.to_string() == "not" => parse_not(i, iter),
Some(TokenTree::Ident(i)) if i.to_string() == "any" => parse_any(i, iter),
Some(TokenTree::Ident(i)) if i.to_string() == "all" => parse_all(i, iter),
unexpected => {
let span = unexpected
.as_ref()
.map_or_else(Span::call_site, TokenTree::span);
Err(Error::new(span, "expected one of `stable`, `beta`, `nightly`, `since`, `before`, `not`, `any`, `all`"))
}
}
}
fn parse_nightly(iter: Iter) -> Result<Expr> {
let paren = match token::parse_optional_paren(iter) {
Some(group) => group,
None => return Ok(Expr::Nightly),
};
let ref mut inner = iter::new(paren.stream());
let date = date::parse(paren, inner)?;
token::parse_optional_punct(inner, ',');
token::parse_end(inner)?;
Ok(Expr::Date(date))
}
fn parse_stable(iter: Iter) -> Result<Expr> {
let paren = match token::parse_optional_paren(iter) {
Some(group) => group,
None => return Ok(Expr::Stable),
};
let ref mut inner = iter::new(paren.stream());
let release = release::parse(paren, inner)?;
token::parse_optional_punct(inner, ',');
token::parse_end(inner)?;
Ok(Expr::Release(release))
}
fn parse_since(introducer: &Ident, iter: Iter) -> Result<Expr> {
let paren = token::parse_paren(introducer, iter)?;
let ref mut inner = iter::new(paren.stream());
let bound = bound::parse(paren, inner)?;
token::parse_optional_punct(inner, ',');
token::parse_end(inner)?;
Ok(Expr::Since(bound))
}
fn parse_before(introducer: &Ident, iter: Iter) -> Result<Expr> {
let paren = token::parse_paren(introducer, iter)?;
let ref mut inner = iter::new(paren.stream());
let bound = bound::parse(paren, inner)?;
token::parse_optional_punct(inner, ',');
token::parse_end(inner)?;
Ok(Expr::Before(bound))
}
fn parse_not(introducer: &Ident, iter: Iter) -> Result<Expr> {
let paren = token::parse_paren(introducer, iter)?;
let ref mut inner = iter::new(paren.stream());
let expr = self::parse(inner)?;
token::parse_optional_punct(inner, ',');
token::parse_end(inner)?;
Ok(Expr::Not(Box::new(expr)))
}
fn parse_any(introducer: &Ident, iter: Iter) -> Result<Expr> {
let paren = token::parse_paren(introducer, iter)?;
let ref mut inner = iter::new(paren.stream());
let exprs = parse_comma_separated(inner)?;
Ok(Expr::Any(exprs.into_iter().collect()))
}
fn parse_all(introducer: &Ident, iter: Iter) -> Result<Expr> {
let paren = token::parse_paren(introducer, iter)?;
let ref mut inner = iter::new(paren.stream());
let exprs = parse_comma_separated(inner)?;
Ok(Expr::All(exprs.into_iter().collect()))
}
fn parse_comma_separated(iter: Iter) -> Result<Vec<Expr>> {
let mut exprs = Vec::new();
while iter.peek().is_some() {
let expr = self::parse(iter)?;
exprs.push(expr);
if iter.peek().is_none() {
break;
}
token::parse_punct(iter, ',')?;
}
Ok(exprs)
}

42
third_party/rust/rustversion/src/iter.rs поставляемый
Просмотреть файл

@ -1,42 +0,0 @@
use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree};
pub type Iter<'a> = &'a mut IterImpl;
pub struct IterImpl {
stack: Vec<token_stream::IntoIter>,
peeked: Option<TokenTree>,
}
pub fn new(tokens: TokenStream) -> IterImpl {
IterImpl {
stack: vec![tokens.into_iter()],
peeked: None,
}
}
impl IterImpl {
pub fn peek(&mut self) -> Option<&TokenTree> {
self.peeked = self.next();
self.peeked.as_ref()
}
}
impl Iterator for IterImpl {
type Item = TokenTree;
fn next(&mut self) -> Option<Self::Item> {
if let Some(tt) = self.peeked.take() {
return Some(tt);
}
loop {
let top = self.stack.last_mut()?;
match top.next() {
None => drop(self.stack.pop()),
Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::None => {
self.stack.push(group.stream().into_iter());
}
Some(tt) => return Some(tt),
}
}
}
}

247
third_party/rust/rustversion/src/lib.rs поставляемый
Просмотреть файл

@ -1,247 +0,0 @@
//! [![github]](https://github.com/dtolnay/rustversion)&ensp;[![crates-io]](https://crates.io/crates/rustversion)&ensp;[![docs-rs]](https://docs.rs/rustversion)
//!
//! [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 macros for conditional compilation according to rustc
//! compiler version, analogous to [`#[cfg(...)]`][cfg] and
//! [`#[cfg_attr(...)]`][cfg_attr].
//!
//! [cfg]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute
//! [cfg_attr]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute
//!
//! <br>
//!
//! # Selectors
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::stable]</code></b>
//! —<br>
//! True on any stable compiler.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::stable(1.34)]</code></b>
//! —<br>
//! True on exactly the specified stable compiler.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::beta]</code></b>
//! —<br>
//! True on any beta compiler.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::nightly]</code></b>
//! —<br>
//! True on any nightly compiler or dev build.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::nightly(2019-01-01)]</code></b>
//! —<br>
//! True on exactly one nightly.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::since(1.34)]</code></b>
//! —<br>
//! True on that stable release and any later compiler, including beta and
//! nightly.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::since(2019-01-01)]</code></b>
//! —<br>
//! True on that nightly and all newer ones.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::before(</code></b><i>version or date</i><b><code>)]</code></b>
//! —<br>
//! Negative of <i>#[rustversion::since(...)]</i>.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::not(</code></b><i>selector</i><b><code>)]</code></b>
//! —<br>
//! Negative of any selector; for example <i>#[rustversion::not(nightly)]</i>.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::any(</code></b><i>selectors...</i><b><code>)]</code></b>
//! —<br>
//! True if any of the comma-separated selectors is true; for example
//! <i>#[rustversion::any(stable, beta)]</i>.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::all(</code></b><i>selectors...</i><b><code>)]</code></b>
//! —<br>
//! True if all of the comma-separated selectors are true; for example
//! <i>#[rustversion::all(since(1.31), before(1.34))]</i>.
//! </p>
//!
//! - <p style="margin-left:50px;text-indent:-50px">
//! <b><code>#[rustversion::attr(</code></b><i>selector</i><b><code>, </code></b><i>attribute</i><b><code>)]</code></b>
//! —<br>
//! For conditional inclusion of attributes; analogous to
//! <code>cfg_attr</code>.
//! </p>
//!
//! <br>
//!
//! # Use cases
//!
//! Providing additional trait impls as types are stabilized in the standard library
//! without breaking compatibility with older compilers; in this case Pin\<P\>
//! stabilized in [Rust 1.33][pin]:
//!
//! [pin]: https://blog.rust-lang.org/2019/02/28/Rust-1.33.0.html#pinning
//!
//! ```
//! # trait MyTrait {}
//! #
//! #[rustversion::since(1.33)]
//! use std::pin::Pin;
//!
//! #[rustversion::since(1.33)]
//! impl<P: MyTrait> MyTrait for Pin<P> {
//! /* ... */
//! }
//! ```
//!
//! Similar but for language features; the ability to control alignment greater than
//! 1 of packed structs was stabilized in [Rust 1.33][packed].
//!
//! [packed]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1330-2019-02-28
//!
//! ```
//! #[rustversion::attr(before(1.33), repr(packed))]
//! #[rustversion::attr(since(1.33), repr(packed(2)))]
//! struct Six(i16, i32);
//!
//! fn main() {
//! println!("{}", std::mem::align_of::<Six>());
//! }
//! ```
//!
//! Augmenting code with `const` as const impls are stabilized in the standard
//! library. This use of `const` as an attribute is recognized as a special case
//! by the rustversion::attr macro.
//!
//! ```
//! use std::time::Duration;
//!
//! #[rustversion::attr(since(1.32), const)]
//! fn duration_as_days(dur: Duration) -> u64 {
//! dur.as_secs() / 60 / 60 / 24
//! }
//! ```
//!
//! <br>
#![allow(
clippy::cast_lossless,
clippy::cast_possible_truncation,
clippy::derive_partial_eq_without_eq,
clippy::doc_markdown,
clippy::enum_glob_use,
clippy::from_iter_instead_of_collect,
// https://github.com/rust-lang/rust-clippy/issues/8539
clippy::iter_with_drain,
clippy::module_name_repetitions,
clippy::must_use_candidate,
clippy::needless_doctest_main,
clippy::needless_pass_by_value,
clippy::redundant_else,
clippy::toplevel_ref_arg,
clippy::unreadable_literal
)]
extern crate proc_macro;
mod attr;
mod bound;
mod constfn;
mod date;
mod error;
mod expand;
mod expr;
mod iter;
mod release;
mod time;
mod token;
mod version;
use crate::error::Error;
use crate::version::Version;
use proc_macro::TokenStream;
const RUSTVERSION: Version = include!(concat!(env!("OUT_DIR"), "/version.expr"));
#[proc_macro_attribute]
pub fn stable(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("stable", args, input)
}
#[proc_macro_attribute]
pub fn beta(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("beta", args, input)
}
#[proc_macro_attribute]
pub fn nightly(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("nightly", args, input)
}
#[proc_macro_attribute]
pub fn since(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("since", args, input)
}
#[proc_macro_attribute]
pub fn before(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("before", args, input)
}
#[proc_macro_attribute]
pub fn not(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("not", args, input)
}
#[proc_macro_attribute]
pub fn any(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("any", args, input)
}
#[proc_macro_attribute]
pub fn all(args: TokenStream, input: TokenStream) -> TokenStream {
expand::cfg("all", args, input)
}
#[proc_macro_attribute]
pub fn attr(args: TokenStream, input: TokenStream) -> TokenStream {
attr::parse(args)
.and_then(|args| expand::try_attr(args, input))
.unwrap_or_else(Error::into_compile_error)
}
#[cfg(not(cfg_macro_not_allowed))]
#[proc_macro]
pub fn cfg(input: TokenStream) -> TokenStream {
use proc_macro::{Ident, Span, TokenTree};
(|| {
let ref mut args = iter::new(input);
let expr = expr::parse(args)?;
token::parse_end(args)?;
let boolean = expr.eval(RUSTVERSION);
let ident = Ident::new(&boolean.to_string(), Span::call_site());
Ok(TokenStream::from(TokenTree::Ident(ident)))
})()
.unwrap_or_else(Error::into_compile_error)
}

34
third_party/rust/rustversion/src/release.rs поставляемый
Просмотреть файл

@ -1,34 +0,0 @@
use crate::error::{Error, Result};
use crate::iter::Iter;
use crate::token;
use proc_macro::Group;
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Release {
pub minor: u16,
pub patch: Option<u16>,
}
pub fn parse(paren: Group, iter: Iter) -> Result<Release> {
try_parse(iter).map_err(|_| Error::group(paren, "expected rustc release number, like 1.31"))
}
fn try_parse(iter: Iter) -> Result<Release, ()> {
let major_minor = token::parse_literal(iter).map_err(drop)?;
let string = major_minor.to_string();
if !string.starts_with("1.") {
return Err(());
}
let minor: u16 = string[2..].parse().map_err(drop)?;
let patch = if token::parse_optional_punct(iter, '.').is_some() {
let int = token::parse_literal(iter).map_err(drop)?;
Some(int.to_string().parse().map_err(drop)?)
} else {
None
};
Ok(Release { minor, patch })
}

51
third_party/rust/rustversion/src/time.rs поставляемый
Просмотреть файл

@ -1,51 +0,0 @@
use crate::date::Date;
use std::env;
use std::time::{SystemTime, UNIX_EPOCH};
// Timestamp of 2016-03-01 00:00:00 in UTC.
const BASE: u64 = 1456790400;
const BASE_YEAR: u16 = 2016;
const BASE_MONTH: u8 = 3;
// Days between leap days.
const CYCLE: u64 = 365 * 4 + 1;
const DAYS_BY_MONTH: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
pub fn today() -> Date {
let default = Date {
year: 2020,
month: 2,
day: 25,
};
try_today().unwrap_or(default)
}
fn try_today() -> Option<Date> {
if let Some(pkg_name) = env::var_os("CARGO_PKG_NAME") {
if pkg_name.to_str() == Some("rustversion-tests") {
return None; // Stable date for ui testing.
}
}
let now = SystemTime::now();
let since_epoch = now.duration_since(UNIX_EPOCH).ok()?;
let secs = since_epoch.as_secs();
let approx_days = secs.checked_sub(BASE)? / 60 / 60 / 24;
let cycle = approx_days / CYCLE;
let mut rem = approx_days % CYCLE;
let mut year = BASE_YEAR + cycle as u16 * 4;
let mut month = BASE_MONTH;
loop {
let days_in_month = DAYS_BY_MONTH[month as usize - 1];
if rem < days_in_month as u64 {
let day = rem as u8 + 1;
return Some(Date { year, month, day });
}
rem -= days_in_month as u64;
year += (month == 12) as u16;
month = month % 12 + 1;
}
}

78
third_party/rust/rustversion/src/token.rs поставляемый
Просмотреть файл

@ -1,78 +0,0 @@
use crate::error::{Error, Result};
use crate::iter::Iter;
use proc_macro::{Delimiter, Group, Ident, Literal, Span, TokenTree};
pub fn parse_punct(iter: Iter, ch: char) -> Result<()> {
match iter.next() {
Some(TokenTree::Punct(ref punct)) if punct.as_char() == ch => Ok(()),
unexpected => {
let span = unexpected
.as_ref()
.map_or_else(Span::call_site, TokenTree::span);
Err(Error::new(span, format!("expected `{}`", ch)))
}
}
}
pub fn parse_optional_punct(iter: Iter, ch: char) -> Option<()> {
match iter.peek() {
Some(TokenTree::Punct(punct)) if punct.as_char() == ch => iter.next().map(drop),
_ => None,
}
}
pub fn parse_optional_keyword(iter: Iter, keyword: &str) -> Option<Span> {
match iter.peek() {
Some(TokenTree::Ident(ident)) if ident.to_string() == keyword => {
Some(iter.next().unwrap().span())
}
_ => None,
}
}
pub fn parse_literal(iter: Iter) -> Result<Literal> {
match iter.next() {
Some(TokenTree::Literal(literal)) => Ok(literal),
unexpected => {
let span = unexpected
.as_ref()
.map_or_else(Span::call_site, TokenTree::span);
Err(Error::new(span, "expected literal"))
}
}
}
pub fn parse_paren(introducer: &Ident, iter: Iter) -> Result<Group> {
match iter.peek() {
Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Parenthesis => {
match iter.next() {
Some(TokenTree::Group(group)) => Ok(group),
_ => unreachable!(),
}
}
Some(unexpected) => Err(Error::new(unexpected.span(), "expected `(`")),
None => Err(Error::new(
introducer.span(),
format!("expected `(` after `{}`", introducer),
)),
}
}
pub fn parse_optional_paren(iter: Iter) -> Option<Group> {
match iter.peek() {
Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Parenthesis => {
match iter.next() {
Some(TokenTree::Group(group)) => Some(group),
_ => unreachable!(),
}
}
_ => None,
}
}
pub fn parse_end(iter: Iter) -> Result<()> {
match iter.next() {
None => Ok(()),
Some(unexpected) => Err(Error::new(unexpected.span(), "unexpected token")),
}
}

18
third_party/rust/rustversion/src/version.rs поставляемый
Просмотреть файл

@ -1,18 +0,0 @@
#![allow(dead_code)]
use crate::date::Date;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Version {
pub minor: u16,
pub patch: u16,
pub channel: Channel,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Channel {
Stable,
Beta,
Nightly(Date),
Dev,
}

Просмотреть файл

@ -1,7 +0,0 @@
#[rustversion::attr(not(nightly), ignore)]
#[cfg_attr(miri, ignore)]
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs");
}

Просмотреть файл

@ -1,39 +0,0 @@
#![allow(clippy::semicolon_if_nothing_returned)] // https://github.com/rust-lang/rust-clippy/issues/7324
#[rustversion::attr(all(), const)]
fn _basic() {}
const _BASIC: () = _basic();
#[rustversion::attr(all(), const)]
unsafe fn _unsafe() {}
const _UNSAFE: () = unsafe { _unsafe() };
macro_rules! item {
($i:item) => {
#[rustversion::attr(all(), const)]
$i
};
}
item! {fn _item() {}}
const _ITEM: () = _item();
macro_rules! ident {
($fn:ident) => {
#[rustversion::attr(all(), const)]
$fn _ident() {}
};
}
ident! {fn}
const _IDENT: () = _ident();
#[rustversion::attr(all(), const)]
/// doc
fn _doc_below() {}
const _DOC_BELOW: () = _doc_below();
/// doc
#[rustversion::attr(all(), const)]
fn _doc_above() {}
const _DOC_ABOVE: () = _doc_above();

Просмотреть файл

@ -1,20 +0,0 @@
#[rustversion::any(
stable,
stable(1.34),
stable(1.34.0),
beta,
nightly,
nightly(2020-02-25),
since(1.34),
since(2020-02-25),
before(1.34),
before(2020-02-25),
not(nightly),
all(stable, beta, nightly),
)]
fn success() {}
#[test]
fn test() {
success();
}

Просмотреть файл

@ -1,103 +0,0 @@
#![allow(
clippy::derive_partial_eq_without_eq,
clippy::enum_glob_use,
clippy::must_use_candidate
)]
include!("../build/rustc.rs");
#[test]
fn test_parse() {
let cases = &[
(
"rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)",
Version {
minor: 0,
patch: 0,
channel: Stable,
},
),
(
"rustc 1.18.0",
Version {
minor: 18,
patch: 0,
channel: Stable,
},
),
(
"rustc 1.24.1 (d3ae9a9e0 2018-02-27)",
Version {
minor: 24,
patch: 1,
channel: Stable,
},
),
(
"rustc 1.35.0-beta.3 (c13114dc8 2019-04-27)",
Version {
minor: 35,
patch: 0,
channel: Beta,
},
),
(
"rustc 1.36.0-nightly (938d4ffe1 2019-04-27)",
Version {
minor: 36,
patch: 0,
channel: Nightly(Date {
year: 2019,
month: 4,
day: 27,
}),
},
),
(
"rustc 1.36.0-dev",
Version {
minor: 36,
patch: 0,
channel: Dev,
},
),
(
"rustc 1.36.0-nightly",
Version {
minor: 36,
patch: 0,
channel: Dev,
},
),
(
"warning: invalid logging spec 'warning', ignoring it
rustc 1.30.0-nightly (3bc2ca7e4 2018-09-20)",
Version {
minor: 30,
patch: 0,
channel: Nightly(Date {
year: 2018,
month: 9,
day: 20,
}),
},
),
(
"rustc 1.52.1-nightly (gentoo)",
Version {
minor: 52,
patch: 1,
channel: Dev,
},
),
];
for (string, expected) in cases {
match parse(string) {
ParseResult::Success(version) => assert_eq!(version, *expected),
ParseResult::OopsClippy | ParseResult::Unrecognized => {
panic!("unrecognized: {:?}", string);
}
}
}
}

Просмотреть файл

@ -1,7 +0,0 @@
#[rustversion::since(stable)]
struct S;
#[rustversion::any(since(stable))]
struct S;
fn main() {}

Просмотреть файл

@ -1,11 +0,0 @@
error: expected rustc release number like 1.31, or nightly date like 2020-02-25
--> tests/ui/bad-bound.rs:1:22
|
1 | #[rustversion::since(stable)]
| ^^^^^^
error: expected rustc release number like 1.31, or nightly date like 2020-02-25
--> tests/ui/bad-bound.rs:4:26
|
4 | #[rustversion::any(since(stable))]
| ^^^^^^

Просмотреть файл

@ -1,7 +0,0 @@
#[rustversion::nightly(stable)]
struct S;
#[rustversion::any(nightly(stable))]
struct S;
fn main() {}

Просмотреть файл

@ -1,11 +0,0 @@
error: expected nightly date, like 2020-02-25
--> tests/ui/bad-date.rs:1:24
|
1 | #[rustversion::nightly(stable)]
| ^^^^^^
error: expected nightly date, like 2020-02-25
--> tests/ui/bad-date.rs:4:28
|
4 | #[rustversion::any(nightly(stable))]
| ^^^^^^

Просмотреть файл

@ -1,7 +0,0 @@
#[rustversion::any(not)]
struct S;
#[rustversion::any(not, not)]
struct S;
fn main() {}

Просмотреть файл

@ -1,11 +0,0 @@
error: expected `(` after `not`
--> tests/ui/bad-not.rs:1:20
|
1 | #[rustversion::any(not)]
| ^^^
error: expected `(`
--> tests/ui/bad-not.rs:4:23
|
4 | #[rustversion::any(not, not)]
| ^

Просмотреть файл

@ -1,7 +0,0 @@
#[rustversion::stable(nightly)]
struct S;
#[rustversion::any(stable(nightly))]
struct S;
fn main() {}

Просмотреть файл

@ -1,11 +0,0 @@
error: expected rustc release number, like 1.31
--> tests/ui/bad-version.rs:1:23
|
1 | #[rustversion::stable(nightly)]
| ^^^^^^^
error: expected rustc release number, like 1.31
--> tests/ui/bad-version.rs:4:27
|
4 | #[rustversion::any(stable(nightly))]
| ^^^^^^^

Просмотреть файл

@ -1,4 +0,0 @@
#[rustversion::attr(all(), const)]
pub struct S;
fn main() {}

Просмотреть файл

@ -1,5 +0,0 @@
error: only allowed on a fn item
--> tests/ui/const-not-fn.rs:1:28
|
1 | #[rustversion::attr(all(), const)]
| ^^^^^

Просмотреть файл

@ -1 +1 @@
{"files":{"Cargo.toml":"3eaed30d780757b28e3db22c8dc2ae302f94b8ef7be4c3452c171a3fa1f66c0b","LICENSE":"ac7e05bd11cc1cfc3f9452c1b9986a9b1d54e180fa88e44e69caf955f95dc8a6","README.md":"b6df6928aece5915ef3469e8384c3716a4fe58820fd1e8ab758c061bd5a499f0","src/code_lock.rs":"775bc592dc9f09aaef90d6455b0ed584fc571224611de4497f5ab0136abc4e78","src/file_lock.rs":"e4c954278a467674648ee43c1b10d0013201358d7c4bbc8cc3678b5af17b9848","src/lib.rs":"6462996f756ee44b47562462a1c5148672c90a6dfc1c093319e583b08b1d251a","src/rwlock.rs":"51c99268a9bb86c601373dbb84f549cd7694ffab151b72ee789d73c149bbf5c7","tests/tests.rs":"242fd98c91c8c42e39a0795a40f44fc11451be54b3196dc4487796f929322bc8"},"package":"e5bcc41d18f7a1d50525d080fd3e953be87c4f9f1a974f3c21798ca00d54ec15"}
{"files":{"Cargo.toml":"4933f04c433404ad954e1ee4ca679662790b4ec63968b4ff07b0a5741b4239b5","LICENSE":"ac7e05bd11cc1cfc3f9452c1b9986a9b1d54e180fa88e44e69caf955f95dc8a6","README.md":"6d27f48fdd3c5425843288902a2c54ec82890011e5d27c814e0fab1d9f9e21ed","src/lib.rs":"f5e43243d8a1fa55ee7acceb4d47be7956c7dee638e7816a411eb7efd72adba7","tests/tests.rs":"73df3c5b4e0ca15adc63689cba82bcc1553165bc09f034ab34b17e4b09cde5a8"},"package":"e0bccbcf40c8938196944a3da0e133e031a33f4d6b72db3bda3cc556e361905d"}

30
third_party/rust/serial_test/Cargo.toml поставляемый
Просмотреть файл

@ -3,34 +3,23 @@
# 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.
# 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.
# 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 = "serial_test"
version = "0.6.0"
version = "0.5.1"
authors = ["Tom Parker-Shemilt <palfrey@tevp.net>"]
description = "Allows for the creation of serialised Rust tests"
readme = "README.md"
keywords = ["sequential"]
categories = ["development-tools::testing"]
license = "MIT"
repository = "https://github.com/palfrey/serial_test/"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies.document-features]
version = "0.2"
optional = true
[dependencies.fslock]
version = "0.2"
optional = true
[dependencies.lazy_static]
version = "1.2"
@ -38,9 +27,4 @@ version = "1.2"
version = ">= 0.10, < 0.12"
[dependencies.serial_test_derive]
version = "~0.6.0"
[features]
default = []
docsrs = ["document-features"]
file_locks = ["fslock"]
version = "~0.5.1"

6
third_party/rust/serial_test/README.md поставляемый
Просмотреть файл

@ -3,8 +3,9 @@
[![Downloads](https://img.shields.io/crates/d/serial_test)](https://crates.io/crates/serial_test)
[![Docs](https://docs.rs/serial_test/badge.svg)](https://docs.rs/serial_test/)
[![MIT license](https://img.shields.io/crates/l/serial_test.svg)](./LICENSE)
[![Build Status](https://github.com/palfrey/serial_test/workflows/Continuous%20integration/badge.svg?branch=main)](https://github.com/palfrey/serial_test/actions)
[![Build Status](https://travis-ci.com/palfrey/serial_test.svg?branch=main)](https://travis-ci.com/palfrey/serial_test)
[![MSRV: 1.39.0](https://flat.badgen.net/badge/MSRV/1.39.0/purple)](https://blog.rust-lang.org/2019/11/07/Rust-1.39.0.html)
[![dependency status](https://deps.rs/repo/github/palfrey/serial_test/status.svg)](https://deps.rs/repo/github/palfrey/serial_test)
`serial_test` allows for the creation of serialised Rust tests using the `serial` attribute
e.g.
@ -28,9 +29,6 @@ async fn test_serial_another() {
}
```
Multiple tests with the `serial` attribute are guaranteed to be executed in serial. Ordering of the tests is not guaranteed however.
Tests without the `serial` attribute may run at any time, including in parallel to tests marked as `serial`. Note that if you're using
an async test reactor attribute (e.g. `tokio::test` or `actix_rt::test`) then they should be listed *before* `serial`, otherwise we
don't get an async function and things break. There's now an error for this case to improve debugging.
## Usage
We require at least Rust 1.39 for [async/await](https://blog.rust-lang.org/2019/11/07/Async-await-stable.html) support

72
third_party/rust/serial_test/src/code_lock.rs поставляемый
Просмотреть файл

@ -1,72 +0,0 @@
use lazy_static::lazy_static;
use parking_lot::ReentrantMutex;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, RwLock};
lazy_static! {
static ref LOCKS: Arc<RwLock<HashMap<String, ReentrantMutex<()>>>> =
Arc::new(RwLock::new(HashMap::new()));
}
fn check_new_key(name: &str) {
// Check if a new key is needed. Just need a read lock, which can be done in sync with everyone else
let new_key = {
let unlock = LOCKS.read().unwrap();
!unlock.deref().contains_key(name)
};
if new_key {
// This is the rare path, which avoids the multi-writer situation mostly
LOCKS
.write()
.unwrap()
.deref_mut()
.insert(name.to_string(), ReentrantMutex::new(()));
}
}
#[doc(hidden)]
pub fn local_serial_core_with_return<E>(
name: &str,
function: fn() -> Result<(), E>,
) -> Result<(), E> {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
function()
}
#[doc(hidden)]
pub fn local_serial_core(name: &str, function: fn()) {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
function();
}
#[doc(hidden)]
pub async fn local_async_serial_core_with_return<E>(
name: &str,
fut: impl std::future::Future<Output = Result<(), E>>,
) -> Result<(), E> {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
fut.await
}
#[doc(hidden)]
pub async fn local_async_serial_core(name: &str, fut: impl std::future::Future<Output = ()>) {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
fut.await;
}

86
third_party/rust/serial_test/src/file_lock.rs поставляемый
Просмотреть файл

@ -1,86 +0,0 @@
use fslock::LockFile;
use std::{env, fs, path::Path};
struct Lock {
lockfile: LockFile,
}
impl Lock {
fn unlock(self: &mut Lock) {
self.lockfile.unlock().unwrap();
println!("Unlock");
}
}
fn do_lock(path: &str) -> Lock {
if !Path::new(path).exists() {
fs::write(path, "").unwrap_or_else(|_| panic!("Lock file path was {:?}", path))
}
let mut lockfile = LockFile::open(path).unwrap();
println!("Waiting on {:?}", path);
lockfile.lock().unwrap();
println!("Locked for {:?}", path);
Lock { lockfile }
}
fn path_for_name(name: &str) -> String {
let mut pathbuf = env::temp_dir();
pathbuf.push(format!("serial-test-{}", name));
pathbuf.into_os_string().into_string().unwrap()
}
fn make_lock_for_name_and_path(name: &str, path: Option<&str>) -> Lock {
if let Some(opt_path) = path {
do_lock(opt_path)
} else {
let default_path = path_for_name(name);
do_lock(&default_path)
}
}
#[doc(hidden)]
pub fn fs_serial_core(name: &str, path: Option<&str>, function: fn()) {
let mut lock = make_lock_for_name_and_path(name, path);
function();
lock.unlock();
}
#[doc(hidden)]
pub fn fs_serial_core_with_return<E>(
name: &str,
path: Option<&str>,
function: fn() -> Result<(), E>,
) -> Result<(), E> {
let mut lock = make_lock_for_name_and_path(name, path);
let ret = function();
lock.unlock();
ret
}
#[doc(hidden)]
pub async fn fs_async_serial_core_with_return<E>(
name: &str,
path: Option<&str>,
fut: impl std::future::Future<Output = Result<(), E>>,
) -> Result<(), E> {
let mut lock = make_lock_for_name_and_path(name, path);
let ret = fut.await;
lock.unlock();
ret
}
#[doc(hidden)]
pub async fn fs_async_serial_core(
name: &str,
path: Option<&str>,
fut: impl std::future::Future<Output = ()>,
) {
let mut lock = make_lock_for_name_and_path(name, path);
fut.await;
lock.unlock();
}
#[test]
fn test_serial() {
fs_serial_core("test", None, || {});
}

108
third_party/rust/serial_test/src/lib.rs поставляемый
Просмотреть файл

@ -1,7 +1,5 @@
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
//! # serial_test
//! `serial_test` allows for the creation of serialised Rust tests using the [serial](macro@serial) attribute
//! `serial_test` allows for the creation of serialised Rust tests using the [serial](attr.serial.html) attribute
//! e.g.
//! ````
//! #[test]
@ -16,45 +14,79 @@
//! // Do things
//! }
//! ````
//! Multiple tests with the [serial](macro@serial) attribute are guaranteed to be executed in serial. Ordering
//! Multiple tests with the [serial](attr.serial.html) attribute are guaranteed to be executed in serial. Ordering
//! of the tests is not guaranteed however.
//!
//! For cases like doctests and integration tests where the tests are run as separate processes, we also support
//! [file_serial](macro@file_serial), with similar properties but based off file locking. Note that there are no
//! guarantees about one test with [serial](macro@serial) and another with [file_serial](macro@file_serial)
//! as they lock using different methods.
//! ````
//! #[test]
//! #[file_serial]
//! fn test_serial_three() {
//! // Do things
//! }
//! ````
//!
//! ## Feature flags
#![cfg_attr(
feature = "docsrs",
cfg_attr(doc, doc = ::document_features::document_features!())
)]
mod code_lock;
#[cfg(feature = "file_locks")]
mod file_lock;
use lazy_static::lazy_static;
use parking_lot::ReentrantMutex;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, RwLock};
pub use code_lock::{
local_async_serial_core, local_async_serial_core_with_return, local_serial_core,
local_serial_core_with_return,
};
lazy_static! {
static ref LOCKS: Arc<RwLock<HashMap<String, ReentrantMutex<()>>>> =
Arc::new(RwLock::new(HashMap::new()));
}
#[cfg(feature = "file_locks")]
pub use file_lock::{
fs_async_serial_core, fs_async_serial_core_with_return, fs_serial_core,
fs_serial_core_with_return,
};
fn check_new_key(name: &str) {
// Check if a new key is needed. Just need a read lock, which can be done in sync with everyone else
let new_key = {
let unlock = LOCKS.read().unwrap();
!unlock.deref().contains_key(name)
};
if new_key {
// This is the rare path, which avoids the multi-writer situation mostly
LOCKS
.write()
.unwrap()
.deref_mut()
.insert(name.to_string(), ReentrantMutex::new(()));
}
}
// Re-export #[serial/file_serial].
#[doc(hidden)]
pub fn serial_core_with_return<E>(name: &str, function: fn() -> Result<(), E>) -> Result<(), E> {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
function()
}
#[doc(hidden)]
pub fn serial_core(name: &str, function: fn()) {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
function();
}
#[doc(hidden)]
pub async fn async_serial_core_with_return<E>(
name: &str,
fut: impl std::future::Future<Output = Result<(), E>>,
) -> Result<(), E> {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
fut.await
}
#[doc(hidden)]
pub async fn async_serial_core(name: &str, fut: impl std::future::Future<Output = ()>) {
check_new_key(name);
let unlock = LOCKS.read().unwrap();
// _guard needs to be named to avoid being instant dropped
let _guard = unlock.deref()[name].lock();
fut.await
}
// Re-export #[serial].
#[allow(unused_imports)]
pub use serial_test_derive::serial;
#[cfg(feature = "file_locks")]
pub use serial_test_derive::file_serial;

30
third_party/rust/serial_test/src/rwlock.rs поставляемый
Просмотреть файл

@ -1,30 +0,0 @@
use std::sync::{ Arc, Mutex, Condvar};
// LockState can be in several possible states:
// 1. 0 readers, false upgradeable_reader, false writer. No-one has any locks, anyone can acquire anything (initial state)
// 2. 1+ readers, false upgradeable_reader, false writer - readers. writer cannot be acquired, but upgradeable_reader can be
// 3. 1+ readers, true upgradeable_reader, false writer - bunch of readers, and one thread that could upgrade to writer, but not yet
// 4. 0 readers, true upgradeable_reader, false writer - upgradeable_reader thread can upgrade to writer
// 5. 0 readers, false upgradeable_reader, true writer - writer only. Nothing else can be acquired.
struct LockState {
readers: u32,
upgradeable_reader: bool,
writer: bool
}
struct Locks(Arc<(Mutex<LockState>, Condvar)>);
impl Locks {
pub fn new() -> Locks {
Locks(Arc::new((Mutex::new(
LockState {
readers: 0,
upgradeable_reader: false,
writer: false
}), Condvar::new())))
}
pub fn read() ->
}

4
third_party/rust/serial_test/tests/tests.rs поставляемый
Просмотреть файл

@ -1,8 +1,8 @@
use serial_test::local_serial_core;
use serial_test::serial_core;
#[test]
fn test_empty_serial_call() {
local_serial_core("beta", || {
serial_core("beta", || {
println!("Bar");
});
}

Просмотреть файл

@ -1 +1 @@
{"files":{"Cargo.toml":"a02b6139f1d683aff6731643e41aaf0ffb5d8ea7e186f9e2bbdbcba5a4837f7d","LICENSE":"ac7e05bd11cc1cfc3f9452c1b9986a9b1d54e180fa88e44e69caf955f95dc8a6","README.md":"b6df6928aece5915ef3469e8384c3716a4fe58820fd1e8ab758c061bd5a499f0","src/lib.rs":"0881974b990368dd1fabcbb97b5f75e861f1acbf150f0fe740abf8a4576c80db","tests/broken/test_serial_async_before_wrapper.rs":"fc61e416a5ec885af93e2e846323ca5bc6ca7c2e7e315c26e1f7f035b029b96e","tests/broken/test_serial_async_before_wrapper.stderr":"139864bee445d9ef9d554d4c261c657dda8c864b402e1d6dd66bdde3037c3fe8"},"package":"2881bccd7d60fb32dfa3d7b3136385312f8ad75e2674aab2852867a09790cae8"}
{"files":{"Cargo.toml":"62afdeeab5dd5a9cd82fa8a1382229d46e4149f0f467509b878833801324dcf2","LICENSE":"ac7e05bd11cc1cfc3f9452c1b9986a9b1d54e180fa88e44e69caf955f95dc8a6","README.md":"6d27f48fdd3c5425843288902a2c54ec82890011e5d27c814e0fab1d9f9e21ed","src/lib.rs":"5a3625477edec06083dc18587d3b908e29ec15ff8410e2c57df10d2c2e9414b0"},"package":"b2acd6defeddb41eb60bb468f8825d0cfd0c2a76bc03bfd235b6a1dc4f6a1ad5"}

Просмотреть файл

@ -3,16 +3,17 @@
# 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.
# 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.
# 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 = "serial_test_derive"
version = "0.6.0"
version = "0.5.1"
authors = ["Tom Parker-Shemilt <palfrey@tevp.net>"]
description = "Helper crate for serial_test"
readme = "README.md"
@ -22,23 +23,14 @@ repository = "https://github.com/palfrey/serial_test/"
[lib]
proc-macro = true
[dependencies.proc-macro-error]
version = "1"
[dependencies.proc-macro2]
version = "1.0"
[dependencies.quote]
version = "1.0"
[dependencies.rustversion]
version = "1.0"
[dependencies.syn]
version = "1.0"
features = ["full"]
[dev-dependencies.env_logger]
version = ">= 0.7, <0.9"
[dev-dependencies.trybuild]
version = "1"

Просмотреть файл

@ -3,8 +3,9 @@
[![Downloads](https://img.shields.io/crates/d/serial_test)](https://crates.io/crates/serial_test)
[![Docs](https://docs.rs/serial_test/badge.svg)](https://docs.rs/serial_test/)
[![MIT license](https://img.shields.io/crates/l/serial_test.svg)](./LICENSE)
[![Build Status](https://github.com/palfrey/serial_test/workflows/Continuous%20integration/badge.svg?branch=main)](https://github.com/palfrey/serial_test/actions)
[![Build Status](https://travis-ci.com/palfrey/serial_test.svg?branch=main)](https://travis-ci.com/palfrey/serial_test)
[![MSRV: 1.39.0](https://flat.badgen.net/badge/MSRV/1.39.0/purple)](https://blog.rust-lang.org/2019/11/07/Rust-1.39.0.html)
[![dependency status](https://deps.rs/repo/github/palfrey/serial_test/status.svg)](https://deps.rs/repo/github/palfrey/serial_test)
`serial_test` allows for the creation of serialised Rust tests using the `serial` attribute
e.g.
@ -28,9 +29,6 @@ async fn test_serial_another() {
}
```
Multiple tests with the `serial` attribute are guaranteed to be executed in serial. Ordering of the tests is not guaranteed however.
Tests without the `serial` attribute may run at any time, including in parallel to tests marked as `serial`. Note that if you're using
an async test reactor attribute (e.g. `tokio::test` or `actix_rt::test`) then they should be listed *before* `serial`, otherwise we
don't get an async function and things break. There's now an error for this case to improve debugging.
## Usage
We require at least Rust 1.39 for [async/await](https://blog.rust-lang.org/2019/11/07/Async-await-stable.html) support

454
third_party/rust/serial_test_derive/src/lib.rs поставляемый
Просмотреть файл

@ -1,15 +1,13 @@
//! # serial_test_derive
//! Helper crate for [serial_test](../serial_test/index.html)
#![cfg_attr(docsrs, feature(doc_cfg))]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::TokenTree;
use proc_macro_error::{abort_call_site, proc_macro_error};
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use quote::quote;
use std::ops::Deref;
use syn;
/// Allows for the creation of serialised Rust tests
/// ````
@ -25,9 +23,9 @@ use std::ops::Deref;
/// // Do things
/// }
/// ````
/// Multiple tests with the [serial](macro@serial) attribute are guaranteed to be executed in serial. Ordering
/// Multiple tests with the [serial](attr.serial.html) attribute are guaranteed to be executed in serial. Ordering
/// of the tests is not guaranteed however. If you want different subsets of tests to be serialised with each
/// other, but not depend on other subsets, you can add an argument to [serial](macro@serial), and all calls
/// other, but not depend on other subsets, you can add an argument to [serial](attr.serial.html), and all calls
/// with identical arguments will be called in serial. e.g.
/// ````
/// #[test]
@ -56,155 +54,29 @@ use std::ops::Deref;
/// ````
/// `test_serial_one` and `test_serial_another` will be executed in serial, as will `test_serial_third` and `test_serial_fourth`
/// but neither sequence will be blocked by the other
///
/// Nested serialised tests (i.e. a [serial](macro@serial) tagged test calling another) is supported
#[proc_macro_attribute]
#[proc_macro_error]
pub fn serial(attr: TokenStream, input: TokenStream) -> TokenStream {
local_serial_core(attr.into(), input.into()).into()
return serial_core(attr.into(), input.into()).into();
}
/// Allows for the creation of file-serialised Rust tests
/// ````
/// #[test]
/// #[file_serial]
/// fn test_serial_one() {
/// // Do things
/// }
///
/// #[test]
/// #[file_serial]
/// fn test_serial_another() {
/// // Do things
/// }
/// ````
///
/// Multiple tests with the [file_serial](macro@file_serial) attribute are guaranteed to run in serial, as per the [serial](macro@serial)
/// attribute. Note that there are no guarantees about one test with [serial](macro@serial) and another with [file_serial](macro@file_serial)
/// as they lock using different methods, and [file_serial](macro@file_serial) does not support nested serialised tests, but otherwise acts
/// like [serial](macro@serial).
///
/// It also supports an optional `path` arg e.g
/// ````
/// #[test]
/// #[file_serial(key, "/tmp/foo")]
/// fn test_serial_one() {
/// // Do things
/// }
///
/// #[test]
/// #[file_serial(key, "/tmp/foo")]
/// fn test_serial_another() {
/// // Do things
/// }
/// ````
/// Note that in this case you need to specify the `name` arg as well (as per [serial](macro@serial)). The path defaults to a reasonable temp directory for the OS if not specified.
#[proc_macro_attribute]
#[proc_macro_error]
#[cfg_attr(docsrs, doc(cfg(feature = "file_locks")))]
pub fn file_serial(attr: TokenStream, input: TokenStream) -> TokenStream {
fs_serial_core(attr.into(), input.into()).into()
}
// Based off of https://github.com/dtolnay/quote/issues/20#issuecomment-437341743
struct QuoteOption<T>(Option<T>);
impl<T: ToTokens> ToTokens for QuoteOption<T> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.append_all(match self.0 {
Some(ref t) => quote! { ::std::option::Option::Some(#t) },
None => quote! { ::std::option::Option::None },
});
}
}
fn get_raw_args(attr: proc_macro2::TokenStream) -> Vec<String> {
let mut attrs = attr.into_iter().collect::<Vec<TokenTree>>();
let mut raw_args: Vec<String> = Vec::new();
while !attrs.is_empty() {
match attrs.remove(0) {
TokenTree::Ident(id) => {
raw_args.push(id.to_string());
}
TokenTree::Literal(literal) => {
let string_literal = literal.to_string();
if !string_literal.starts_with('\"') || !string_literal.ends_with('\"') {
panic!("Expected a string literal, got '{}'", string_literal);
}
// Hacky way of getting a string without the enclosing quotes
raw_args.push(string_literal[1..string_literal.len() - 1].to_string());
}
x => {
panic!("Expected either strings or literals as args, not {}", x);
}
}
if !attrs.is_empty() {
match attrs.remove(0) {
TokenTree::Punct(p) if p.as_char() == ',' => {}
x => {
panic!("Expected , between args, not {}", x);
}
}
}
}
raw_args
}
fn local_serial_core(
fn serial_core(
attr: proc_macro2::TokenStream,
input: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let mut raw_args = get_raw_args(attr);
let key = match raw_args.len() {
let attrs = attr.into_iter().collect::<Vec<TokenTree>>();
let key = match attrs.len() {
0 => "".to_string(),
1 => raw_args.pop().unwrap(),
1 => {
if let TokenTree::Ident(id) = &attrs[0] {
id.to_string()
} else {
panic!("Expected a single name as argument, got {:?}", attrs);
}
}
n => {
panic!(
"Expected either 0 or 1 arguments, got {}: {:?}",
n, raw_args
);
panic!("Expected either 0 or 1 arguments, got {}: {:?}", n, attrs);
}
};
serial_setup(input, vec![Box::new(key)], "local")
}
fn fs_serial_core(
attr: proc_macro2::TokenStream,
input: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let none_ident = Box::new(format_ident!("None"));
let mut args: Vec<Box<dyn quote::ToTokens>> = Vec::new();
let mut raw_args = get_raw_args(attr);
match raw_args.len() {
0 => {
args.push(Box::new("".to_string()));
args.push(none_ident);
}
1 => {
args.push(Box::new(raw_args.pop().unwrap()));
args.push(none_ident);
}
2 => {
let key = raw_args.remove(0);
let path = raw_args.remove(0);
args.push(Box::new(key));
args.push(Box::new(QuoteOption(Some(path))));
}
n => {
panic!("Expected 0-2 arguments, got {}: {:?}", n, raw_args);
}
}
serial_setup(input, args, "fs")
}
fn serial_setup<T>(
input: proc_macro2::TokenStream,
args: Vec<Box<T>>,
prefix: &str,
) -> proc_macro2::TokenStream
where
T: quote::ToTokens + ?Sized,
{
let ast: syn::ItemFn = syn::parse2(input).unwrap();
let asyncness = ast.sig.asyncness;
let name = ast.sig.ident;
@ -219,196 +91,140 @@ where
.filter(|at| {
if let Ok(m) = at.parse_meta() {
let path = m.path();
if asyncness.is_some()
&& path.segments.len() == 2
&& path.segments[1].ident == "test"
{
// We assume that any 2-part attribute with the second part as "test" on an async function
// is the "do this test with reactor" wrapper. This is true for actix, tokio and async_std.
abort_call_site!("Found async test attribute after serial, which will break");
if path.is_ident("ignore") || path.is_ident("should_panic") {
// we skip ignore/should_panic because the test framework already deals with it
false
} else {
true
}
// we skip ignore/should_panic because the test framework already deals with it
!(path.is_ident("ignore") || path.is_ident("should_panic"))
} else {
true
}
})
.collect();
if let Some(ret) = return_type {
let gen = if let Some(ret) = return_type {
match asyncness {
Some(_) => {
let fnname = format_ident!("{}_async_serial_core_with_return", prefix);
quote! {
#(#attrs)
*
async fn #name () -> #ret {
serial_test::#fnname(#(#args ),*, || async #block ).await;
}
Some(_) => quote! {
#(#attrs)
*
async fn #name () -> #ret {
serial_test::async_serial_core_with_return(#key, || async {
#block
}).await;
}
}
None => {
let fnname = format_ident!("{}_serial_core_with_return", prefix);
quote! {
#(#attrs)
*
fn #name () -> #ret {
serial_test::#fnname(#(#args ),*, || #block )
}
},
None => quote! {
#(#attrs)
*
fn #name () -> #ret {
serial_test::serial_core_with_return(#key, || {
#block
})
}
}
},
}
} else {
match asyncness {
Some(_) => {
let fnname = format_ident!("{}_async_serial_core", prefix);
quote! {
#(#attrs)
*
async fn #name () {
serial_test::#fnname(#(#args ),*, || async #block ).await;
}
Some(_) => quote! {
#(#attrs)
*
async fn #name () {
serial_test::async_serial_core(#key, || async {
#block
}).await;
}
}
None => {
let fnname = format_ident!("{}_serial_core", prefix);
quote! {
#(#attrs)
*
fn #name () {
serial_test::#fnname(#(#args ),*, || #block );
}
},
None => quote! {
#(#attrs)
*
fn #name () {
serial_test::serial_core(#key, || {
#block
});
}
}
},
}
}
};
return gen.into();
}
#[cfg(test)]
mod tests {
use proc_macro2::{Literal, Punct, Spacing};
use super::{format_ident, fs_serial_core, local_serial_core, quote, TokenTree};
use std::iter::FromIterator;
#[test]
fn test_serial() {
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
#[test]
fn foo() {}
};
let stream = local_serial_core(attrs.into(), input);
let compare = quote! {
#[test]
fn foo () {
serial_test::local_serial_core("", || {} );
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_stripped_attributes() {
let _ = env_logger::builder().is_test(true).try_init();
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
#[test]
#[ignore]
#[should_panic(expected = "Testing panic")]
#[something_else]
fn foo() {}
};
let stream = local_serial_core(attrs.into(), input);
let compare = quote! {
#[test]
#[something_else]
fn foo () {
serial_test::local_serial_core("", || {} );
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_serial_async() {
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
async fn foo() {}
};
let stream = local_serial_core(attrs.into(), input);
let compare = quote! {
async fn foo () {
serial_test::local_async_serial_core("", || async {} ).await;
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_serial_async_return() {
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
async fn foo() -> Result<(), ()> { Ok(()) }
};
let stream = local_serial_core(attrs.into(), input);
let compare = quote! {
async fn foo () -> Result<(), ()> {
serial_test::local_async_serial_core_with_return("", || async { Ok(()) } ).await;
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
// 1.54 needed for https://github.com/rust-lang/rust/commit/9daf546b77dbeab7754a80d7336cd8d00c6746e4 change in note message
#[rustversion::since(1.54)]
#[test]
fn test_serial_async_before_wrapper() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/broken/test_serial_async_before_wrapper.rs");
}
#[test]
fn test_file_serial() {
let attrs = vec![TokenTree::Ident(format_ident!("foo"))];
let input = quote! {
#[test]
fn foo() {}
};
let stream = fs_serial_core(
proc_macro2::TokenStream::from_iter(attrs.into_iter()),
input,
);
let compare = quote! {
#[test]
fn foo () {
serial_test::fs_serial_core("foo", None, || {} );
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_file_serial_with_path() {
let attrs = vec![
TokenTree::Ident(format_ident!("foo")),
TokenTree::Punct(Punct::new(',', Spacing::Alone)),
TokenTree::Literal(Literal::string("bar_path")),
];
let input = quote! {
#[test]
fn foo() {}
};
let stream = fs_serial_core(
proc_macro2::TokenStream::from_iter(attrs.into_iter()),
input,
);
let compare = quote! {
#[test]
fn foo () {
serial_test::fs_serial_core("foo", ::std::option::Option::Some("bar_path"), || {} );
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_serial() {
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
#[test]
fn foo() {}
};
let stream = serial_core(attrs.into(), input);
let compare = quote! {
#[test]
fn foo () {
serial_test::serial_core("", || {
{}
});
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_stripped_attributes() {
let _ = env_logger::builder().is_test(true).try_init();
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
#[test]
#[ignore]
#[should_panic(expected = "Testing panic")]
#[something_else]
fn foo() {}
};
let stream = serial_core(attrs.into(), input);
let compare = quote! {
#[test]
#[something_else]
fn foo () {
serial_test::serial_core("", || {
{}
});
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_serial_async() {
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
#[tokio::test]
async fn foo() {}
};
let stream = serial_core(attrs.into(), input);
let compare = quote! {
#[tokio::test]
async fn foo () {
serial_test::async_serial_core("", || async {
{}
}).await;
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}
#[test]
fn test_serial_async_return() {
let attrs = proc_macro2::TokenStream::new();
let input = quote! {
#[tokio::test]
async fn foo() -> Result<(), ()> { Ok(()) }
};
let stream = serial_core(attrs.into(), input);
let compare = quote! {
#[tokio::test]
async fn foo () -> Result<(), ()> {
serial_test::async_serial_core_with_return("", || async {
{ Ok(()) }
}).await;
}
};
assert_eq!(format!("{}", compare), format!("{}", stream));
}

Просмотреть файл

@ -1,7 +0,0 @@
use serial_test_derive::serial;
#[serial]
#[actix_rt::test]
async fn test_async_serial_no_arg_actix() {}
fn main() {}

Просмотреть файл

@ -1,7 +0,0 @@
error: Found async test attribute after serial, which will break
--> tests/broken/test_serial_async_before_wrapper.rs:3:1
|
3 | #[serial]
| ^^^^^^^^^
|
= note: this error originates in the attribute macro `serial` (in Nightly builds, run with -Z macro-backtrace for more info)