trybuild-1.0.50/.cargo_vcs_info.json0000644000000001360000000000100127550ustar { "git": { "sha1": "df0dcc70d4f8b3bdcea4a9422fcee09be5ead8c7" }, "path_in_vcs": "" }trybuild-1.0.50/.clippy.toml000064400000000000000000000000200072674642500140400ustar 00000000000000msrv = "1.31.0" trybuild-1.0.50/.github/FUNDING.yml000064400000000000000000000000200072674642500147420ustar 00000000000000github: dtolnay trybuild-1.0.50/.github/workflows/ci.yml000064400000000000000000000031040072674642500163060ustar 00000000000000name: CI on: push: pull_request: schedule: [cron: "40 1 * * *"] jobs: test: name: Rust ${{matrix.rust}} runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.36.0] steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - run: cargo test xplat: name: ${{matrix.name}} runs-on: ${{matrix.os}}-latest strategy: fail-fast: false matrix: include: - name: macOS os: macos - name: Windows os: windows steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@nightly - run: cargo test msrv: name: Rust 1.34.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@1.34.0 - run: cargo check minimal: name: Minimal versions runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@nightly - run: cargo update -Z minimal-versions - run: cargo check clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' steps: - uses: actions/checkout@v2 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' steps: - uses: actions/checkout@v2 - run: cargo outdated --exit-code 1 trybuild-1.0.50/.gitignore000064400000000000000000000000350072674642500135630ustar 00000000000000target **/*.rs.bk Cargo.lock trybuild-1.0.50/Cargo.toml0000644000000023640000000000100107600ustar # 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.34" name = "trybuild" version = "1.0.50" authors = ["David Tolnay "] exclude = ["screenshots/*"] description = "Test harness for ui tests of compiler diagnostics" documentation = "https://docs.rs/trybuild" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/trybuild" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies.dissimilar] version = "1.0" optional = true [dependencies.glob] version = "0.3" [dependencies.lazy_static] version = "1.3" [dependencies.serde] version = "1.0.103" features = ["derive"] [dependencies.serde_json] version = "1.0" [dependencies.termcolor] version = "1.0.4" [dependencies.toml] version = "0.5.2" [features] diff = ["dissimilar"] trybuild-1.0.50/Cargo.toml.orig000064400000000000000000000015720072674642500144710ustar 00000000000000[package] name = "trybuild" version = "1.0.50" authors = ["David Tolnay "] edition = "2018" rust-version = "1.34" license = "MIT OR Apache-2.0" description = "Test harness for ui tests of compiler diagnostics" repository = "https://github.com/dtolnay/trybuild" documentation = "https://docs.rs/trybuild" exclude = ["screenshots/*"] readme = "README.md" [features] # Experimental: highlight the diff between the expected and actual compiler # output. Currently unix-only. If you test this out, please provide any feedback # in https://github.com/dtolnay/trybuild/issues/41. diff = ["dissimilar"] [dependencies] dissimilar = { version = "1.0", optional = true } glob = "0.3" lazy_static = "1.3" serde = { version = "1.0.103", features = ["derive"] } serde_json = "1.0" termcolor = "1.0.4" toml = "0.5.2" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] trybuild-1.0.50/LICENSE-APACHE000064400000000000000000000251370072674642500135310ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. trybuild-1.0.50/LICENSE-MIT000064400000000000000000000017770072674642500132450ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. trybuild-1.0.50/README.md000064400000000000000000000232430072674642500130600ustar 00000000000000Trybuild ======== [github](https://github.com/dtolnay/trybuild) [crates.io](https://crates.io/crates/trybuild) [docs.rs](https://docs.rs/trybuild) [build status](https://github.com/dtolnay/trybuild/actions?query=branch%3Amaster) Trybuild is a test harness for invoking rustc on a set of test cases and asserting that any resulting error messages are the ones intended.

Such tests are commonly useful for testing error reporting involving procedural macros. We would write test cases triggering either errors detected by the macro or errors detected by the Rust compiler in the resulting expanded code, and compare against the expected errors to ensure that they remain user-friendly. This style of testing is sometimes called *ui tests* because they test aspects of the user's interaction with a library outside of what would be covered by ordinary API tests. Nothing here is specific to macros; trybuild would work equally well for testing misuse of non-macro APIs. ```toml [dev-dependencies] trybuild = "1.0" ``` *Compiler support: requires rustc 1.36+*
## Compile-fail tests A minimal trybuild setup looks like this: ```rust #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } ``` The test can be run with `cargo test`. It will individually compile each of the source files matching the glob pattern, expect them to fail to compile, and assert that the compiler's error message matches an adjacently named _*.stderr_ file containing the expected output (same file name as the test except with a different extension). If it matches, the test case is considered to succeed. Dependencies listed under `[dev-dependencies]` in the project's Cargo.toml are accessible from within the test cases. Failing tests display the expected vs actual compiler output inline.

A compile\_fail test that fails to fail to compile is also a failure.

To test just one source file, use: ``` cargo test -- ui trybuild=example.rs ``` where `ui` is the name of the `#[test]` funtion that invokes `trybuild`, and `example.rs` is the name of the file to test.
## Pass tests The same test harness is able to run tests that are expected to pass, too. Ordinarily you would just have Cargo run such tests directly, but being able to combine modes like this could be useful for workshops in which participants work through test cases enabling one at a time. Trybuild was originally developed for my [procedural macros workshop at Rust Latam][workshop]. [workshop]: https://github.com/dtolnay/proc-macro-workshop ```rust #[test] fn ui() { let t = trybuild::TestCases::new(); t.pass("tests/01-parse-header.rs"); t.pass("tests/02-parse-body.rs"); t.compile_fail("tests/03-expand-four-errors.rs"); t.pass("tests/04-paste-ident.rs"); t.pass("tests/05-repeat-section.rs"); //t.pass("tests/06-make-work-in-function.rs"); //t.pass("tests/07-init-array.rs"); //t.compile_fail("tests/08-ident-span.rs"); } ``` Pass tests are considered to succeed if they compile successfully and have a `main` function that does not panic when the compiled binary is executed.


## Details That's the entire API.
## Workflow There are two ways to update the _*.stderr_ files as you iterate on your test cases or your library; handwriting them is not recommended. First, if a test case is being run as compile\_fail but a corresponding _*.stderr_ file does not exist, the test runner will save the actual compiler output with the right filename into a directory called *wip* within the directory containing Cargo.toml. So you can update these files by deleting them, running `cargo test`, and moving all the files from *wip* into your testcase directory.

Alternatively, run `cargo test` with the environment variable `TRYBUILD=overwrite` to skip the *wip* directory and write all compiler output directly in place. You'll want to check `git diff` afterward to be sure the compiler's output is what you had in mind.
## What to test When it comes to compile-fail tests, write tests for anything for which you care to find out when there are changes in the user-facing compiler output. As a negative example, please don't write compile-fail tests simply calling all of your public APIs with arguments of the wrong type; there would be no benefit. A common use would be for testing specific targeted error messages emitted by a procedural macro. For example the derive macro from the [`ref-cast`] crate is required to be placed on a type that has either `#[repr(C)]` or `#[repr(transparent)]` in order for the expansion to be free of undefined behavior, which it enforces at compile time: [`ref-cast`]: https://github.com/dtolnay/ref-cast ```console error: RefCast trait requires #[repr(C)] or #[repr(transparent)] --> $DIR/missing-repr.rs:3:10 | 3 | #[derive(RefCast)] | ^^^^^^^ ``` Macros that consume helper attributes will want to check that unrecognized content within those attributes is properly indicated to the caller. Is the error message correctly placed under the erroneous tokens, not on a useless call\_site span? ```console error: unknown serde field attribute `qqq` --> $DIR/unknown-attribute.rs:5:13 | 5 | #[serde(qqq = "...")] | ^^^ ``` Declarative macros can benefit from compile-fail tests too. The [`json!`] macro from serde\_json is just a great big macro\_rules macro but makes an effort to have error messages from broken JSON in the input always appear on the most appropriate token: [`json!`]: https://docs.rs/serde_json/1.0/serde_json/macro.json.html ```console error: no rules expected the token `,` --> $DIR/double-comma.rs:4:38 | 4 | println!("{}", json!({ "k": null,, })); | ^ no rules expected this token in macro call ``` Sometimes we may have a macro that expands successfully but we count on it to trigger particular compiler errors at some point beyond macro expansion. For example the [`readonly`] crate introduces struct fields that are public but readable only, even if the caller has a &mut reference to the surrounding struct. If someone writes to a readonly field, we need to be sure that it wouldn't compile: [`readonly`]: https://github.com/dtolnay/readonly ```console error[E0594]: cannot assign to data in a `&` reference --> $DIR/write-a-readonly.rs:17:26 | 17 | println!("{}", s.n); s.n += 1; | ^^^^^^^^ cannot assign ``` In all of these cases, the compiler's output can change because our crate or one of our dependencies broke something, or as a consequence of changes in the Rust compiler. Both are good reasons to have well conceived compile-fail tests. If we refactor and mistakenly cause an error that used to be correct to now no longer be emitted or be emitted in the wrong place, that is important for a test suite to catch. If the compiler changes something that makes error messages that we care about substantially worse, it is also important to catch and report as a compiler issue.
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
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. trybuild-1.0.50/build.rs000064400000000000000000000006330072674642500132440ustar 00000000000000use std::env; use std::fs; use std::io; use std::path::Path; fn main() -> io::Result<()> { let out_dir = env::var_os("OUT_DIR").unwrap(); let target = env::var("TARGET").ok(); let path = Path::new(&out_dir).join("target"); let value = match target { Some(target) => format!(r#"Some("{}")"#, target.escape_debug()), None => "None".to_owned(), }; fs::write(path, value) } trybuild-1.0.50/src/cargo.rs000064400000000000000000000077420072674642500140370ustar 00000000000000use crate::directory::Directory; use crate::error::{Error, Result}; use crate::manifest::Name; use crate::run::Project; use crate::rustflags; use serde::Deserialize; use std::process::{Command, Output, Stdio}; use std::{env, fs}; #[derive(Deserialize)] pub struct Metadata { pub target_directory: Directory, pub workspace_root: Directory, pub packages: Vec, } #[derive(Deserialize)] pub struct Package { pub name: String, } fn raw_cargo() -> Command { match env::var_os("CARGO") { Some(cargo) => Command::new(cargo), None => Command::new("cargo"), } } fn cargo(project: &Project) -> Command { let mut cmd = raw_cargo(); cmd.current_dir(&project.dir); cmd.env( "CARGO_TARGET_DIR", path!(project.target_dir / "tests" / "target"), ); cmd.arg("--offline"); rustflags::set_env(&mut cmd); cmd } pub fn build_dependencies(project: &Project) -> Result<()> { let workspace_cargo_lock = path!(project.workspace / "Cargo.lock"); if workspace_cargo_lock.exists() { let _ = fs::copy(workspace_cargo_lock, path!(project.dir / "Cargo.lock")); } else { let _ = cargo(project).arg("generate-lockfile").status(); } let status = cargo(project) .arg(if project.has_pass { "build" } else { "check" }) .args(target()) .arg("--bin") .arg(&project.name) .args(features(project)) .status() .map_err(Error::Cargo)?; if status.success() { Ok(()) } else { Err(Error::CargoFail) } } pub fn build_test(project: &Project, name: &Name) -> Result { let _ = cargo(project) .arg("clean") .arg("--package") .arg(&project.name) .arg("--color=never") .stdout(Stdio::null()) .stderr(Stdio::null()) .status(); cargo(project) .arg(if project.has_pass { "build" } else { "check" }) .args(target()) .arg("--bin") .arg(name) .args(features(project)) .arg("--quiet") .arg("--color=never") .output() .map_err(Error::Cargo) } pub fn run_test(project: &Project, name: &Name) -> Result { cargo(project) .arg("run") .args(target()) .arg("--bin") .arg(name) .args(features(project)) .arg("--quiet") .arg("--color=never") .output() .map_err(Error::Cargo) } pub fn metadata() -> Result { let output = raw_cargo() .arg("metadata") .arg("--no-deps") .arg("--format-version=1") .output() .map_err(Error::Cargo)?; serde_json::from_slice(&output.stdout).map_err(|err| { print!("{}", String::from_utf8_lossy(&output.stderr)); Error::Metadata(err) }) } fn features(project: &Project) -> Vec { match &project.features { Some(features) => vec![ "--no-default-features".to_owned(), "--features".to_owned(), features.join(","), ], None => vec![], } } fn target() -> Vec<&'static str> { const TARGET: Option<&str> = include!(concat!(env!("OUT_DIR"), "/target")); // When --target flag is passed, cargo does not pass RUSTFLAGS to rustc when // building proc-macro and build script even if the host and target triples // are the same. Therefore, if we always pass --target to cargo, tools such // as coverage that require RUSTFLAGS do not work for tests run by trybuild. // // To avoid that problem, do not pass --target to cargo if we know that it // has not been passed. // // Currently, cargo does not have a way to tell the build script whether // --target has been passed or not, and there is no heuristic that can // handle this well. // // Therefore, expose a cfg to always treat the target as host. if cfg!(trybuild_no_target) { vec![] } else if let Some(target) = TARGET { vec!["--target", target] } else { vec![] } } trybuild-1.0.50/src/dependencies.rs000064400000000000000000000152320072674642500153630ustar 00000000000000use crate::directory::Directory; use crate::error::Error; use crate::manifest::Edition; use serde::de::value::MapAccessDeserializer; use serde::de::{self, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::collections::BTreeMap as Map; use std::fmt; use std::fs; use std::path::PathBuf; use toml::Value; pub fn get_manifest(manifest_dir: &Directory) -> Manifest { try_get_manifest(manifest_dir).unwrap_or_default() } fn try_get_manifest(manifest_dir: &Directory) -> Result { let cargo_toml_path = manifest_dir.join("Cargo.toml"); let manifest_str = fs::read_to_string(cargo_toml_path)?; let mut manifest: Manifest = toml::from_str(&manifest_str)?; fix_dependencies(&mut manifest.dependencies, manifest_dir); fix_dependencies(&mut manifest.dev_dependencies, manifest_dir); for target in manifest.target.values_mut() { fix_dependencies(&mut target.dependencies, manifest_dir); fix_dependencies(&mut target.dev_dependencies, manifest_dir); } Ok(manifest) } pub fn get_workspace_manifest(manifest_dir: &Directory) -> WorkspaceManifest { try_get_workspace_manifest(manifest_dir).unwrap_or_default() } pub fn try_get_workspace_manifest(manifest_dir: &Directory) -> Result { let cargo_toml_path = manifest_dir.join("Cargo.toml"); let manifest_str = fs::read_to_string(cargo_toml_path)?; let mut manifest: WorkspaceManifest = toml::from_str(&manifest_str)?; fix_patches(&mut manifest.patch, manifest_dir); fix_replacements(&mut manifest.replace, manifest_dir); Ok(manifest) } fn fix_dependencies(dependencies: &mut Map, dir: &Directory) { dependencies.remove("trybuild"); for dep in dependencies.values_mut() { dep.path = dep.path.as_ref().map(|path| Directory::new(dir.join(path))); } } fn fix_patches(patches: &mut Map, dir: &Directory) { for registry in patches.values_mut() { registry.crates.remove("trybuild"); for patch in registry.crates.values_mut() { patch.path = patch.path.as_ref().map(|path| dir.join(path)); } } } fn fix_replacements(replacements: &mut Map, dir: &Directory) { replacements.remove("trybuild"); for replacement in replacements.values_mut() { replacement.path = replacement.path.as_ref().map(|path| dir.join(path)); } } #[derive(Deserialize, Default, Debug)] pub struct WorkspaceManifest { #[serde(default)] pub patch: Map, #[serde(default)] pub replace: Map, } #[derive(Deserialize, Default, Debug)] pub struct Manifest { #[serde(default)] pub package: Package, #[serde(default)] pub features: Map>, #[serde(default)] pub dependencies: Map, #[serde(default, alias = "dev-dependencies")] pub dev_dependencies: Map, #[serde(default)] pub target: Map, } #[derive(Deserialize, Default, Debug)] pub struct Package { #[serde(default)] pub edition: Edition, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(remote = "Self")] pub struct Dependency { #[serde(skip_serializing_if = "Option::is_none")] pub version: Option, #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, #[serde( rename = "default-features", default = "get_true", skip_serializing_if = "is_true" )] pub default_features: bool, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub features: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub git: Option, #[serde(skip_serializing_if = "Option::is_none")] pub branch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub tag: Option, #[serde(skip_serializing_if = "Option::is_none")] pub rev: Option, #[serde(flatten)] pub rest: Map, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TargetDependencies { #[serde(default, skip_serializing_if = "Map::is_empty")] pub dependencies: Map, #[serde( default, alias = "dev-dependencies", skip_serializing_if = "Map::is_empty" )] pub dev_dependencies: Map, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(transparent)] pub struct RegistryPatch { crates: Map, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Patch { #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, #[serde(skip_serializing_if = "Option::is_none")] pub git: Option, #[serde(skip_serializing_if = "Option::is_none")] pub branch: Option, #[serde(skip_serializing_if = "Option::is_none")] pub tag: Option, #[serde(skip_serializing_if = "Option::is_none")] pub rev: Option, #[serde(flatten)] pub rest: Map, } fn get_true() -> bool { true } fn is_true(boolean: &bool) -> bool { *boolean } impl Serialize for Dependency { fn serialize(&self, serializer: S) -> Result where S: Serializer, { Dependency::serialize(self, serializer) } } impl<'de> Deserialize<'de> for Dependency { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct DependencyVisitor; impl<'de> Visitor<'de> for DependencyVisitor { type Value = Dependency; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str( "a version string like \"0.9.8\" or a \ dependency like { version = \"0.9.8\" }", ) } fn visit_str(self, s: &str) -> Result where E: de::Error, { Ok(Dependency { version: Some(s.to_owned()), path: None, default_features: true, features: Vec::new(), git: None, branch: None, tag: None, rev: None, rest: Map::new(), }) } fn visit_map(self, map: M) -> Result where M: de::MapAccess<'de>, { Dependency::deserialize(MapAccessDeserializer::new(map)) } } deserializer.deserialize_any(DependencyVisitor) } } trybuild-1.0.50/src/diff.rs000064400000000000000000000043730072674642500136510ustar 00000000000000pub use self::r#impl::Diff; pub enum Render<'a> { Common(&'a str), Unique(&'a str), } #[cfg(all(feature = "diff", not(windows)))] mod r#impl { use super::Render; use dissimilar::Chunk; use std::cmp; use std::panic; pub struct Diff<'a> { expected: &'a str, actual: &'a str, diff: Vec>, } impl<'a> Diff<'a> { pub fn compute(expected: &'a str, actual: &'a str) -> Option { if expected.len() + actual.len() > 2048 { // We don't yet trust the dissimilar crate to work well on large // inputs. return None; } // Nor on non-ascii inputs. let diff = panic::catch_unwind(|| dissimilar::diff(expected, actual)).ok()?; let mut common_len = 0; for chunk in &diff { if let Chunk::Equal(common) = chunk { common_len += common.len(); } } let bigger_len = cmp::max(expected.len(), actual.len()); let worth_printing = 5 * common_len >= 4 * bigger_len; if !worth_printing { return None; } Some(Diff { expected, actual, diff, }) } pub fn iter<'i>(&'i self, input: &str) -> impl Iterator> + 'i { let expected = input == self.expected; let actual = input == self.actual; self.diff.iter().filter_map(move |chunk| match chunk { Chunk::Equal(common) => Some(Render::Common(common)), Chunk::Delete(unique) if expected => Some(Render::Unique(unique)), Chunk::Insert(unique) if actual => Some(Render::Unique(unique)), _ => None, }) } } } #[cfg(any(not(feature = "diff"), windows))] mod r#impl { use super::Render; pub enum Diff {} impl Diff { pub fn compute(_expected: &str, _actual: &str) -> Option { None } pub fn iter(&self, _input: &str) -> Box> { let _ = Render::Common; let _ = Render::Unique; match *self {} } } } trybuild-1.0.50/src/directory.rs000064400000000000000000000022150072674642500147360ustar 00000000000000use serde::{Deserialize, Deserializer, Serialize}; use std::borrow::Cow; use std::ffi::OsString; use std::io; use std::path::{Path, PathBuf}; #[derive(Clone, Debug, Serialize)] #[serde(transparent)] pub struct Directory { path: PathBuf, } impl Directory { pub fn new>(path: P) -> Self { let mut path = path.into(); path.push(""); Directory { path } } pub fn to_string_lossy(&self) -> Cow { self.path.to_string_lossy() } pub fn join>(&self, tail: P) -> PathBuf { self.path.join(tail) } pub fn canonicalize(&self) -> io::Result { self.path.canonicalize().map(Directory::new) } } impl From for Directory { fn from(os_string: OsString) -> Self { Directory::new(PathBuf::from(os_string)) } } impl AsRef for Directory { fn as_ref(&self) -> &Path { &self.path } } impl<'de> Deserialize<'de> for Directory { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { PathBuf::deserialize(deserializer).map(Directory::new) } } trybuild-1.0.50/src/env.rs000064400000000000000000000011300072674642500135150ustar 00000000000000use crate::error::{Error, Result}; use std::env; #[derive(PartialEq, Debug)] pub enum Update { Wip, Overwrite, } impl Default for Update { fn default() -> Self { Update::Wip } } impl Update { pub fn env() -> Result { let var = match env::var_os("TRYBUILD") { Some(var) => var, None => return Ok(Update::default()), }; match var.as_os_str().to_str() { Some("wip") => Ok(Update::Wip), Some("overwrite") => Ok(Update::Overwrite), _ => Err(Error::UpdateVar(var)), } } } trybuild-1.0.50/src/error.rs000064400000000000000000000054660072674642500140760ustar 00000000000000use glob::{GlobError, PatternError}; use std::env; use std::ffi::OsString; use std::fmt::{self, Display}; use std::io; use std::path::PathBuf; #[derive(Debug)] pub enum Error { Cargo(io::Error), CargoFail, Glob(GlobError), Io(io::Error), Metadata(serde_json::Error), Mismatch, Open(PathBuf, io::Error), Pattern(PatternError), PkgName(env::VarError), ProjectDir, ReadStderr(io::Error), RunFailed, ShouldNotHaveCompiled, TomlDe(toml::de::Error), TomlSer(toml::ser::Error), UpdateVar(OsString), WriteStderr(io::Error), } pub type Result = std::result::Result; impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { Cargo(e) => write!(f, "failed to execute cargo: {}", e), CargoFail => write!(f, "cargo reported an error"), Glob(e) => write!(f, "{}", e), Io(e) => write!(f, "{}", e), Metadata(e) => write!(f, "failed to read cargo metadata: {}", e), Mismatch => write!(f, "compiler error does not match expected error"), Open(path, e) => write!(f, "{}: {}", path.display(), e), Pattern(e) => write!(f, "{}", e), PkgName(e) => write!(f, "failed to detect CARGO_PKG_NAME: {}", e), ProjectDir => write!(f, "failed to determine name of project dir"), ReadStderr(e) => write!(f, "failed to read stderr file: {}", e), RunFailed => write!(f, "execution of the test case was unsuccessful"), ShouldNotHaveCompiled => { write!(f, "expected test case to fail to compile, but it succeeded") } TomlDe(e) => write!(f, "{}", e), TomlSer(e) => write!(f, "{}", e), UpdateVar(var) => write!( f, "unrecognized value of TRYBUILD: {:?}", var.to_string_lossy(), ), WriteStderr(e) => write!(f, "failed to write stderr file: {}", e), } } } impl Error { pub fn already_printed(&self) -> bool { use self::Error::*; match self { CargoFail | Mismatch | RunFailed | ShouldNotHaveCompiled => true, _ => false, } } } impl From for Error { fn from(err: GlobError) -> Self { Error::Glob(err) } } impl From for Error { fn from(err: PatternError) -> Self { Error::Pattern(err) } } impl From for Error { fn from(err: io::Error) -> Self { Error::Io(err) } } impl From for Error { fn from(err: toml::de::Error) -> Self { Error::TomlDe(err) } } impl From for Error { fn from(err: toml::ser::Error) -> Self { Error::TomlSer(err) } } trybuild-1.0.50/src/features.rs000064400000000000000000000056100072674642500145520ustar 00000000000000use serde::de::DeserializeOwned; use serde::{de, Deserialize, Deserializer}; use std::env; use std::error::Error; use std::ffi::OsStr; use std::fs; use std::path::PathBuf; pub fn find() -> Option> { try_find().ok() } struct Ignored; impl From for Ignored { fn from(_error: E) -> Self { Ignored } } #[derive(Deserialize)] struct Build { #[serde(deserialize_with = "from_json")] features: Vec, } fn try_find() -> Result, Ignored> { // This will look something like: // /path/to/crate_name/target/debug/deps/test_name-HASH let test_binary = env::args_os().next().ok_or(Ignored)?; // The hash at the end is ascii so not lossy, rest of conversion doesn't // matter. let test_binary_lossy = test_binary.to_string_lossy(); let hash_range = if cfg!(windows) { // Trim ".exe" from the binary name for windows. test_binary_lossy.len() - 21..test_binary_lossy.len() - 4 } else { test_binary_lossy.len() - 17..test_binary_lossy.len() }; let hash = test_binary_lossy.get(hash_range).ok_or(Ignored)?; if !hash.starts_with('-') || !hash[1..].bytes().all(is_lower_hex_digit) { return Err(Ignored); } let binary_path = PathBuf::from(&test_binary); // Feature selection is saved in: // /path/to/crate_name/target/debug/.fingerprint/*-HASH/*-HASH.json let up = binary_path .parent() .ok_or(Ignored)? .parent() .ok_or(Ignored)?; let fingerprint_dir = up.join(".fingerprint"); if !fingerprint_dir.is_dir() { return Err(Ignored); } let mut hash_matches = Vec::new(); for entry in fingerprint_dir.read_dir()? { let entry = entry?; let is_dir = entry.file_type()?.is_dir(); let matching_hash = entry.file_name().to_string_lossy().ends_with(hash); if is_dir && matching_hash { hash_matches.push(entry.path()); } } if hash_matches.len() != 1 { return Err(Ignored); } let mut json_matches = Vec::new(); for entry in hash_matches[0].read_dir()? { let entry = entry?; let is_file = entry.file_type()?.is_file(); let is_json = entry.path().extension() == Some(OsStr::new("json")); if is_file && is_json { json_matches.push(entry.path()); } } if json_matches.len() != 1 { return Err(Ignored); } let build_json = fs::read_to_string(&json_matches[0])?; let build: Build = serde_json::from_str(&build_json)?; Ok(build.features) } fn is_lower_hex_digit(byte: u8) -> bool { byte >= b'0' && byte <= b'9' || byte >= b'a' && byte <= b'f' } fn from_json<'de, T, D>(deserializer: D) -> Result where T: DeserializeOwned, D: Deserializer<'de>, { let json = String::deserialize(deserializer)?; serde_json::from_str(&json).map_err(de::Error::custom) } trybuild-1.0.50/src/flock.rs000064400000000000000000000074360072674642500140420ustar 00000000000000use lazy_static::lazy_static; use std::fs::{self, File, OpenOptions}; use std::io; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::thread; use std::time::{Duration, SystemTime}; lazy_static! { static ref LOCK: Mutex<()> = Mutex::new(()); } pub struct Lock { intraprocess_guard: Guard, lockfile: FileLock, } // High-quality lock to coordinate different #[test] functions within the *same* // integration test crate. enum Guard { NotLocked, Locked(MutexGuard<'static, ()>), } // Best-effort filesystem lock to coordinate different #[test] functions across // *different* integration tests. enum FileLock { NotLocked, Locked { path: PathBuf, done: Arc, }, } impl Lock { pub fn acquire(path: impl AsRef) -> Self { Lock { intraprocess_guard: Guard::acquire(), lockfile: FileLock::acquire(path), } } } impl Guard { fn acquire() -> Self { Guard::Locked(LOCK.lock().unwrap_or_else(PoisonError::into_inner)) } } impl FileLock { fn acquire(path: impl AsRef) -> Self { let path = path.as_ref().to_owned(); let lockfile = match create(&path) { None => return FileLock::NotLocked, Some(lockfile) => lockfile, }; let done = Arc::new(AtomicBool::new(false)); thread::spawn({ let done = Arc::clone(&done); move || poll(lockfile, done) }); FileLock::Locked { path, done } } } impl Drop for Lock { fn drop(&mut self) { let Lock { intraprocess_guard, lockfile, } = self; // Unlock file lock first. *lockfile = FileLock::NotLocked; *intraprocess_guard = Guard::NotLocked; } } impl Drop for FileLock { fn drop(&mut self) { match self { FileLock::NotLocked => {} FileLock::Locked { path, done } => { done.store(true, Ordering::Release); let _ = fs::remove_file(path); } } } } fn create(path: &Path) -> Option { loop { match OpenOptions::new().write(true).create_new(true).open(path) { // Acquired lock by creating lockfile. Ok(lockfile) => return Some(lockfile), Err(io_error) => match io_error.kind() { // Lock is already held by another test. io::ErrorKind::AlreadyExists => {} // File based locking isn't going to work for some reason. _ => return None, }, } // Check whether it's okay to bust the lock. let metadata = match fs::metadata(path) { Ok(metadata) => metadata, Err(io_error) => match io_error.kind() { // Other holder of the lock finished. Retry. io::ErrorKind::NotFound => continue, _ => return None, }, }; let modified = match metadata.modified() { Ok(modified) => modified, Err(_) => return None, }; let now = SystemTime::now(); let considered_stale = now - Duration::from_millis(1500); let considered_future = now + Duration::from_millis(1500); if modified < considered_stale || considered_future < modified { return File::create(path).ok(); } // Try again shortly. thread::sleep(Duration::from_millis(500)); } } // Bump mtime periodically while test directory is in use. fn poll(lockfile: File, done: Arc) { loop { thread::sleep(Duration::from_millis(500)); if done.load(Ordering::Acquire) || lockfile.set_len(0).is_err() { return; } } } trybuild-1.0.50/src/lib.rs000064400000000000000000000263640072674642500135130ustar 00000000000000//! [![github]](https://github.com/dtolnay/trybuild) [![crates-io]](https://crates.io/crates/trybuild) [![docs-rs]](https://docs.rs/trybuild) //! //! [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&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K //! //!
//! //! ####  A compiler diagnostics testing library in just 3 functions. //! //! Trybuild is a test harness for invoking rustc on a set of test cases and //! asserting that any resulting error messages are the ones intended. //! //! Such tests are commonly useful for testing error reporting involving //! procedural macros. We would write test cases triggering either errors //! detected by the macro or errors detected by the Rust compiler in the //! resulting expanded code, and compare against the expected errors to ensure //! that they remain user-friendly. //! //! This style of testing is sometimes called *ui tests* because they test //! aspects of the user's interaction with a library outside of what would be //! covered by ordinary API tests. //! //! Nothing here is specific to macros; trybuild would work equally well for //! testing misuse of non-macro APIs. //! //!
//! //! # Compile-fail tests //! //! A minimal trybuild setup looks like this: //! //! ``` //! #[test] //! fn ui() { //! let t = trybuild::TestCases::new(); //! t.compile_fail("tests/ui/*.rs"); //! } //! ``` //! //! The test can be run with `cargo test`. It will individually compile each of //! the source files matching the glob pattern, expect them to fail to compile, //! and assert that the compiler's error message matches an adjacently named //! _*.stderr_ file containing the expected output (same file name as the test //! except with a different extension). If it matches, the test case is //! considered to succeed. //! //! Dependencies listed under `[dev-dependencies]` in the project's Cargo.toml //! are accessible from within the test cases. //! //!

//! //!

//! //! Failing tests display the expected vs actual compiler output inline. //! //!

//! //!

//! //! A compile_fail test that fails to fail to compile is also a failure. //! //!

//! //!

//! //!
//! //! # Pass tests //! //! The same test harness is able to run tests that are expected to pass, too. //! Ordinarily you would just have Cargo run such tests directly, but being able //! to combine modes like this could be useful for workshops in which //! participants work through test cases enabling one at a time. Trybuild was //! originally developed for my [procedural macros workshop at Rust //! Latam][workshop]. //! //! [workshop]: https://github.com/dtolnay/proc-macro-workshop //! //! ``` //! #[test] //! fn ui() { //! let t = trybuild::TestCases::new(); //! t.pass("tests/01-parse-header.rs"); //! t.pass("tests/02-parse-body.rs"); //! t.compile_fail("tests/03-expand-four-errors.rs"); //! t.pass("tests/04-paste-ident.rs"); //! t.pass("tests/05-repeat-section.rs"); //! //t.pass("tests/06-make-work-in-function.rs"); //! //t.pass("tests/07-init-array.rs"); //! //t.compile_fail("tests/08-ident-span.rs"); //! } //! ``` //! //! Pass tests are considered to succeed if they compile successfully and have a //! `main` function that does not panic when the compiled binary is executed. //! //!

//! //!

//! //!
//! //! # Details //! //! That's the entire API. //! //!
//! //! # Workflow //! //! There are two ways to update the _*.stderr_ files as you iterate on your //! test cases or your library; handwriting them is not recommended. //! //! First, if a test case is being run as compile_fail but a corresponding //! _*.stderr_ file does not exist, the test runner will save the actual //! compiler output with the right filename into a directory called *wip* within //! the directory containing Cargo.toml. So you can update these files by //! deleting them, running `cargo test`, and moving all the files from *wip* //! into your testcase directory. //! //!

//! //!

//! //! Alternatively, run `cargo test` with the environment variable //! `TRYBUILD=overwrite` to skip the *wip* directory and write all compiler //! output directly in place. You'll want to check `git diff` afterward to be //! sure the compiler's output is what you had in mind. //! //!
//! //! # What to test //! //! When it comes to compile-fail tests, write tests for anything for which you //! care to find out when there are changes in the user-facing compiler output. //! As a negative example, please don't write compile-fail tests simply calling //! all of your public APIs with arguments of the wrong type; there would be no //! benefit. //! //! A common use would be for testing specific targeted error messages emitted //! by a procedural macro. For example the derive macro from the [`ref-cast`] //! crate is required to be placed on a type that has either `#[repr(C)]` or //! `#[repr(transparent)]` in order for the expansion to be free of undefined //! behavior, which it enforces at compile time: //! //! [`ref-cast`]: https://github.com/dtolnay/ref-cast //! //! ```console //! error: RefCast trait requires #[repr(C)] or #[repr(transparent)] //! --> $DIR/missing-repr.rs:3:10 //! | //! 3 | #[derive(RefCast)] //! | ^^^^^^^ //! ``` //! //! Macros that consume helper attributes will want to check that unrecognized //! content within those attributes is properly indicated to the caller. Is the //! error message correctly placed under the erroneous tokens, not on a useless //! call\_site span? //! //! ```console //! error: unknown serde field attribute `qqq` //! --> $DIR/unknown-attribute.rs:5:13 //! | //! 5 | #[serde(qqq = "...")] //! | ^^^ //! ``` //! //! Declarative macros can benefit from compile-fail tests too. The [`json!`] //! macro from serde\_json is just a great big macro\_rules macro but makes an //! effort to have error messages from broken JSON in the input always appear on //! the most appropriate token: //! //! [`json!`]: https://docs.rs/serde_json/1.0/serde_json/macro.json.html //! //! ```console //! error: no rules expected the token `,` //! --> $DIR/double-comma.rs:4:38 //! | //! 4 | println!("{}", json!({ "k": null,, })); //! | ^ no rules expected this token in macro call //! ``` //! //! Sometimes we may have a macro that expands successfully but we count on it //! to trigger particular compiler errors at some point beyond macro expansion. //! For example the [`readonly`] crate introduces struct fields that are public //! but readable only, even if the caller has a &mut reference to the //! surrounding struct. If someone writes to a readonly field, we need to be //! sure that it wouldn't compile: //! //! [`readonly`]: https://github.com/dtolnay/readonly //! //! ```console //! error[E0594]: cannot assign to data in a `&` reference //! --> $DIR/write-a-readonly.rs:17:26 //! | //! 17 | println!("{}", s.n); s.n += 1; //! | ^^^^^^^^ cannot assign //! ``` //! //! In all of these cases, the compiler's output can change because our crate or //! one of our dependencies broke something, or as a consequence of changes in //! the Rust compiler. Both are good reasons to have well conceived compile-fail //! tests. If we refactor and mistakenly cause an error that used to be correct //! to now no longer be emitted or be emitted in the wrong place, that is //! important for a test suite to catch. If the compiler changes something that //! makes error messages that we care about substantially worse, it is also //! important to catch and report as a compiler issue. #![allow( clippy::collapsible_if, clippy::default_trait_access, clippy::doc_markdown, clippy::enum_glob_use, clippy::if_then_panic, clippy::let_underscore_drop, clippy::module_name_repetitions, clippy::must_use_candidate, clippy::needless_pass_by_value, clippy::non_ascii_literal, clippy::range_plus_one, clippy::single_match_else, clippy::too_many_lines, clippy::trivially_copy_pass_by_ref, clippy::unused_self )] #![deny(clippy::clone_on_ref_ptr)] #[macro_use] mod term; #[macro_use] mod path; mod cargo; mod dependencies; mod diff; mod directory; mod env; mod error; mod features; mod flock; mod manifest; mod message; mod normalize; mod run; mod rustflags; use std::cell::RefCell; use std::panic::RefUnwindSafe; use std::path::{Path, PathBuf}; use std::thread; #[derive(Debug)] pub struct TestCases { runner: RefCell, } #[derive(Debug)] struct Runner { tests: Vec, } #[derive(Clone, Debug)] struct Test { path: PathBuf, expected: Expected, } #[derive(Copy, Clone, Debug)] enum Expected { Pass, CompileFail, } impl TestCases { #[allow(clippy::new_without_default)] pub fn new() -> Self { TestCases { runner: RefCell::new(Runner { tests: Vec::new() }), } } pub fn pass>(&self, path: P) { self.runner.borrow_mut().tests.push(Test { path: path.as_ref().to_owned(), expected: Expected::Pass, }); } pub fn compile_fail>(&self, path: P) { self.runner.borrow_mut().tests.push(Test { path: path.as_ref().to_owned(), expected: Expected::CompileFail, }); } } impl RefUnwindSafe for TestCases {} #[doc(hidden)] impl Drop for TestCases { fn drop(&mut self) { if !thread::panicking() { self.runner.borrow_mut().run(); } } } trybuild-1.0.50/src/manifest.rs000064400000000000000000000033130072674642500145400ustar 00000000000000use crate::dependencies::{Dependency, Patch, RegistryPatch, TargetDependencies}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap as Map; use std::ffi::OsStr; use std::path::PathBuf; #[derive(Serialize, Debug)] pub struct Manifest { pub package: Package, #[serde(skip_serializing_if = "Map::is_empty")] pub features: Map>, pub dependencies: Map, #[serde(skip_serializing_if = "Map::is_empty")] pub target: Map, #[serde(rename = "bin")] pub bins: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub workspace: Option, #[serde(skip_serializing_if = "Map::is_empty")] pub patch: Map, #[serde(skip_serializing_if = "Map::is_empty")] pub replace: Map, } #[derive(Serialize, Debug)] pub struct Package { pub name: String, pub version: String, pub edition: Edition, pub publish: bool, } #[derive(Serialize, Deserialize, Debug)] pub enum Edition { #[serde(rename = "2015")] E2015, #[serde(rename = "2018")] E2018, #[serde(rename = "2021")] E2021, } #[derive(Serialize, Debug)] pub struct Bin { pub name: Name, pub path: PathBuf, } #[derive(Serialize, Clone, Debug)] pub struct Name(pub String); #[derive(Serialize, Debug)] pub struct Config { pub build: Build, } #[derive(Serialize, Debug)] pub struct Build { pub rustflags: Vec<&'static str>, } #[derive(Serialize, Debug)] pub struct Workspace {} impl Default for Edition { fn default() -> Self { Edition::E2018 } } impl AsRef for Name { fn as_ref(&self) -> &OsStr { self.0.as_ref() } } trybuild-1.0.50/src/message.rs000064400000000000000000000136540072674642500143670ustar 00000000000000use crate::diff::{Diff, Render}; use crate::error::Error; use crate::{normalize, term, Expected, Test}; use std::env; use std::path::Path; use std::process::Output; use termcolor::Color::{self, *}; pub(crate) enum Level { Fail, Warn, } pub(crate) use self::Level::*; pub(crate) fn prepare_fail(err: Error) { if err.already_printed() { return; } term::bold_color(Red); print!("ERROR"); term::reset(); println!(": {}", err); println!(); } pub(crate) fn test_fail(err: Error) { if err.already_printed() { return; } term::bold_color(Red); println!("error"); term::color(Red); println!("{}", err); term::reset(); println!(); } pub(crate) fn no_tests_enabled() { term::color(Yellow); println!("There are no trybuild tests enabled yet."); term::reset(); } pub(crate) fn ok() { term::color(Green); println!("ok"); term::reset(); } pub(crate) fn begin_test(test: &Test, show_expected: bool) { let display_name = if show_expected { test.path .file_name() .unwrap_or_else(|| test.path.as_os_str()) .to_string_lossy() } else { test.path.as_os_str().to_string_lossy() }; print!("test "); term::bold(); print!("{}", display_name); term::reset(); if show_expected { match test.expected { Expected::Pass => print!(" [should pass]"), Expected::CompileFail => print!(" [should fail to compile]"), } } print!(" ... "); } pub(crate) fn failed_to_build(stderr: &str) { term::bold_color(Red); println!("error"); snippet(Red, stderr); println!(); } pub(crate) fn should_not_have_compiled() { term::bold_color(Red); println!("error"); term::color(Red); println!("Expected test case to fail to compile, but it succeeded."); term::reset(); println!(); } pub(crate) fn write_stderr_wip(wip_path: &Path, stderr_path: &Path, stderr: &str) { let wip_path = wip_path.to_string_lossy(); let stderr_path = stderr_path.to_string_lossy(); term::bold_color(Yellow); println!("wip"); println!(); print!("NOTE"); term::reset(); println!(": writing the following output to `{}`.", wip_path); println!( "Move this file to `{}` to accept it as correct.", stderr_path, ); snippet(Yellow, stderr); println!(); } pub(crate) fn overwrite_stderr(stderr_path: &Path, stderr: &str) { let stderr_path = stderr_path.to_string_lossy(); term::bold_color(Yellow); println!("wip"); println!(); print!("NOTE"); term::reset(); println!(": writing the following output to `{}`.", stderr_path); snippet(Yellow, stderr); println!(); } pub(crate) fn mismatch(expected: &str, actual: &str) { term::bold_color(Red); println!("mismatch"); term::reset(); println!(); let diff = if env::var_os("TERM").map_or(true, |term| term == "dumb") { // No diff in dumb terminal or when TERM is unset. None } else { Diff::compute(expected, actual) }; term::bold_color(Blue); println!("EXPECTED:"); snippet_diff(Blue, expected, diff.as_ref()); println!(); term::bold_color(Red); println!("ACTUAL OUTPUT:"); snippet_diff(Red, actual, diff.as_ref()); print!("note: If the "); term::color(Red); print!("actual output"); term::reset(); println!(" is the correct output you can bless it by rerunning"); println!(" your test with the environment variable TRYBUILD=overwrite"); println!(); } pub(crate) fn output(warnings: &str, output: &Output) { let success = output.status.success(); let stdout = normalize::trim(&output.stdout); let stderr = normalize::trim(&output.stderr); let has_output = !stdout.is_empty() || !stderr.is_empty(); if success { ok(); if has_output || !warnings.is_empty() { println!(); } } else { term::bold_color(Red); println!("error"); term::color(Red); if has_output { println!("Test case failed at runtime."); } else { println!("Execution of the test case was unsuccessful but there was no output."); } term::reset(); println!(); } self::warnings(warnings); let color = if success { Yellow } else { Red }; for (name, content) in &[("STDOUT", stdout), ("STDERR", stderr)] { if !content.is_empty() { term::bold_color(color); println!("{}:", name); snippet(color, &normalize::trim(content)); println!(); } } } pub(crate) fn fail_output(level: Level, stdout: &[u8]) { let color = match level { Fail => Red, Warn => Yellow, }; if !stdout.is_empty() { term::bold_color(color); println!("STDOUT:"); snippet(color, &normalize::trim(stdout)); println!(); } } pub(crate) fn warnings(warnings: &str) { if warnings.is_empty() { return; } term::bold_color(Yellow); println!("WARNINGS:"); snippet(Yellow, warnings); println!(); } fn snippet(color: Color, content: &str) { snippet_diff(color, content, None); } fn snippet_diff(color: Color, content: &str, diff: Option<&Diff>) { fn dotted_line() { println!("{}", "┈".repeat(60)); } term::color(color); dotted_line(); match diff { Some(diff) => { for chunk in diff.iter(content) { match chunk { Render::Common(s) => { term::color(color); print!("{}", s); } Render::Unique(s) => { term::bold_color(color); print!("\x1B[7m{}", s); } } } } None => print!("{}", content), } term::color(color); dotted_line(); term::reset(); } trybuild-1.0.50/src/normalize.rs000064400000000000000000000265050072674642500147420ustar 00000000000000#[cfg(test)] #[path = "tests.rs"] mod tests; use crate::directory::Directory; use crate::run::PathDependency; #[derive(Copy, Clone)] pub struct Context<'a> { pub krate: &'a str, pub source_dir: &'a Directory, pub workspace: &'a Directory, pub path_dependencies: &'a [PathDependency], } pub fn trim>(output: S) -> String { let bytes = output.as_ref(); let mut normalized = String::from_utf8_lossy(bytes).to_string(); let len = normalized.trim_end().len(); normalized.truncate(len); if !normalized.is_empty() { normalized.push('\n'); } normalized } /// For a given compiler output, produces the set of saved outputs against which /// the compiler's output would be considered correct. If the test's saved /// stderr file is identical to any one of these variations, the test will pass. /// /// This is a set rather than just one normalized output in order to avoid /// breaking existing tests when introducing new normalization steps. Someone /// may have saved stderr snapshots with an older version of trybuild, and those /// tests need to continue to pass with newer versions of trybuild. /// /// There is one "preferred" variation which is what we print when the stderr /// file is absent or not a match. pub fn diagnostics(output: Vec, context: Context) -> Variations { let mut from_bytes = String::from_utf8_lossy(&output).to_string(); from_bytes = from_bytes.replace("\r\n", "\n"); let variations = [ Basic, StripCouldNotCompile, StripCouldNotCompile2, StripForMoreInformation, StripForMoreInformation2, TrimEnd, RustLib, TypeDirBackslash, WorkspaceLines, PathDependencies, CargoRegistry, ArrowOtherCrate, RelativeToDir, ] .iter() .map(|normalization| apply(&from_bytes, *normalization, context)) .collect(); Variations { variations } } pub struct Variations { variations: Vec, } impl Variations { pub fn preferred(&self) -> &str { self.variations.last().unwrap() } pub fn any bool>(&self, mut f: F) -> bool { self.variations.iter().any(|stderr| f(stderr)) } } #[derive(PartialOrd, PartialEq, Copy, Clone)] enum Normalization { Basic, StripCouldNotCompile, StripCouldNotCompile2, StripForMoreInformation, StripForMoreInformation2, TrimEnd, RustLib, TypeDirBackslash, WorkspaceLines, PathDependencies, CargoRegistry, ArrowOtherCrate, RelativeToDir, // New normalization steps are to be inserted here at the end so that any // snapshots saved before your normalization change remain passing. } use self::Normalization::*; fn apply(original: &str, normalization: Normalization, context: Context) -> String { let mut normalized = String::new(); let lines: Vec<&str> = original.lines().collect(); let mut filter = Filter { all_lines: &lines, normalization, context, hide_numbers: 0, }; for i in 0..lines.len() { if let Some(line) = filter.apply(i) { normalized += &line; if !normalized.ends_with("\n\n") { normalized.push('\n'); } } } trim(normalized) } struct Filter<'a> { all_lines: &'a [&'a str], normalization: Normalization, context: Context<'a>, hide_numbers: usize, } impl<'a> Filter<'a> { fn apply(&mut self, index: usize) -> Option { let mut line = self.all_lines[index].to_owned(); if self.hide_numbers > 0 { hide_leading_numbers(&mut line); self.hide_numbers -= 1; } let trim_start = line.trim_start(); let indent = line.len() - trim_start.len(); let prefix = if trim_start.starts_with("--> ") { Some("--> ") } else if trim_start.starts_with("::: ") { Some("::: ") } else { None }; if prefix == Some("--> ") && self.normalization < ArrowOtherCrate { if let Some(cut_end) = line.rfind(&['/', '\\'][..]) { let cut_start = line.find('>').unwrap() + 2; line.replace_range(cut_start..cut_end + 1, "$DIR/"); return Some(line); } } if let Some(prefix) = prefix { line = line.replace('\\', "/"); let line_lower = line.to_ascii_lowercase(); let source_dir_pat = self .context .source_dir .to_string_lossy() .to_ascii_lowercase() .replace('\\', "/"); if let Some(i) = line_lower.find(&source_dir_pat) { if self.normalization >= RelativeToDir && i == indent + 4 { line.replace_range(i..i + source_dir_pat.len(), ""); } else { line.replace_range(i..i + source_dir_pat.len() - 1, "$DIR"); } return Some(line); } let mut other_crate = false; let workspace_pat = self .context .workspace .to_string_lossy() .to_ascii_lowercase() .replace('\\', "/"); if let Some(i) = line_lower.find(&workspace_pat) { line.replace_range(i..i + workspace_pat.len() - 1, "$WORKSPACE"); other_crate = true; } if self.normalization >= PathDependencies && !other_crate { for path_dep in self.context.path_dependencies { let path_dep_pat = path_dep .normalized_path .to_string_lossy() .to_ascii_lowercase() .replace('\\', "/"); if let Some(i) = line_lower.find(&path_dep_pat) { let var = format!("${}", path_dep.name.to_uppercase().replace('-', "_")); line.replace_range(i..i + path_dep_pat.len() - 1, &var); other_crate = true; break; } } } if self.normalization >= RustLib && !other_crate { if let Some(pos) = line.find("/rustlib/src/rust/src/") { // ::: $RUST/src/libstd/net/ip.rs:83:1 line.replace_range(line.find(prefix).unwrap() + 4..pos + 17, "$RUST"); other_crate = true; } else if let Some(pos) = line.find("/rustlib/src/rust/library/") { // ::: $RUST/std/src/net/ip.rs:83:1 line.replace_range(line.find(prefix).unwrap() + 4..pos + 25, "$RUST"); other_crate = true; } } if self.normalization >= CargoRegistry && !other_crate { if let Some(pos) = line.find("/registry/src/github.com-") { // ::: $CARGO/github.com-1ecc6299db9ec823/serde_json-1.0.64/src/de.rs:2584:8 line.replace_range(line.find(prefix).unwrap() + 4..pos + 41, "$CARGO"); other_crate = true; } } if other_crate && self.normalization >= WorkspaceLines { // Blank out line numbers for this particular error since rustc // tends to reach into code from outside of the test case. The // test stderr shouldn't need to be updated every time we touch // those files. hide_trailing_numbers(&mut line); self.hide_numbers = 1; while let Some(next_line) = self.all_lines.get(index + self.hide_numbers) { match next_line.trim_start().chars().next().unwrap_or_default() { '0'..='9' | '|' | '.' => self.hide_numbers += 1, _ => break, } } } return Some(line); } if line.starts_with("error: aborting due to ") { return None; } if line == "To learn more, run the command again with --verbose." { return None; } if self.normalization >= StripCouldNotCompile { if line.starts_with("error: Could not compile `") { return None; } } if self.normalization >= StripCouldNotCompile2 { if line.starts_with("error: could not compile `") { return None; } } if self.normalization >= StripForMoreInformation { if line.starts_with("For more information about this error, try `rustc --explain") { return None; } } if self.normalization >= StripForMoreInformation2 { if line.starts_with("Some errors have detailed explanations:") { return None; } if line.starts_with("For more information about an error, try `rustc --explain") { return None; } } if self.normalization >= TrimEnd { line.truncate(line.trim_end().len()); } if self.normalization >= TypeDirBackslash { if line .trim_start() .starts_with("= note: required because it appears within the type") { line = line.replace('\\', "/"); } } line = line.replace(self.context.krate, "$CRATE"); line = replace_case_insensitive(&line, &self.context.source_dir.to_string_lossy(), "$DIR/"); line = replace_case_insensitive( &line, &self.context.workspace.to_string_lossy(), "$WORKSPACE/", ); Some(line) } } // "10 | T: Send," -> " | T: Send," fn hide_leading_numbers(line: &mut String) { let n = line.bytes().take_while(u8::is_ascii_digit).count(); for i in 0..n { line.replace_range(i..i + 1, " "); } } // "main.rs:22:29" -> "main.rs" fn hide_trailing_numbers(line: &mut String) { for _ in 0..2 { let digits = line.bytes().rev().take_while(u8::is_ascii_digit).count(); if digits == 0 || !line[..line.len() - digits].ends_with(':') { return; } line.truncate(line.len() - digits - 1); } } fn replace_case_insensitive(line: &str, pattern: &str, replacement: &str) -> String { let line_lower = line.to_ascii_lowercase().replace('\\', "/"); let pattern_lower = pattern.to_ascii_lowercase().replace('\\', "/"); let mut replaced = String::with_capacity(line.len()); let line_lower = line_lower.as_str(); let mut split = line_lower.split(&pattern_lower); let mut pos = 0; let mut insert_replacement = false; while let Some(keep) = split.next() { if insert_replacement { replaced.push_str(replacement); pos += pattern.len(); } let keep = &line[pos..pos + keep.len()]; replaced.push_str(keep); pos += keep.len(); insert_replacement = true; if replaced.ends_with(|ch: char| ch.is_ascii_alphanumeric()) { if let Some(ch) = line[pos..].chars().next() { replaced.push(ch); pos += ch.len_utf8(); split = line_lower[pos..].split(&pattern_lower); insert_replacement = false; } } } replaced } trybuild-1.0.50/src/path.rs000064400000000000000000000023250072674642500136700ustar 00000000000000macro_rules! path { ($($tt:tt)+) => { tokenize_path!([] [] $($tt)+) }; } // Private implementation detail. macro_rules! tokenize_path { ([$(($($component:tt)+))*] [$($cur:tt)+] /) => { crate::directory::Directory::new(tokenize_path!([$(($($component)+))*] [$($cur)+])) }; ([$(($($component:tt)+))*] [$($cur:tt)+] / $($rest:tt)+) => { tokenize_path!([$(($($component)+))* ($($cur)+)] [] $($rest)+) }; ([$(($($component:tt)+))*] [$($cur:tt)*] $first:tt $($rest:tt)*) => { tokenize_path!([$(($($component)+))*] [$($cur)* $first] $($rest)*) }; ([$(($($component:tt)+))*] [$($cur:tt)+]) => { tokenize_path!([$(($($component)+))* ($($cur)+)]) }; ([$(($($component:tt)+))*]) => {{ let mut path = std::path::PathBuf::new(); $( path.push(&($($component)+)); )* path }}; } #[test] fn test_path_macro() { use std::path::{Path, PathBuf}; struct Project { dir: PathBuf, } let project = Project { dir: PathBuf::from("../target/tests"), }; let cargo_dir = path!(project.dir / ".cargo" / "config"); assert_eq!(cargo_dir, Path::new("../target/tests/.cargo/config")); } trybuild-1.0.50/src/run.rs000064400000000000000000000345400072674642500135440ustar 00000000000000use crate::cargo::{self, Metadata}; use crate::dependencies::{self, Dependency}; use crate::directory::Directory; use crate::env::Update; use crate::error::{Error, Result}; use crate::flock::Lock; use crate::manifest::{Bin, Build, Config, Manifest, Name, Package, Workspace}; use crate::message::{self, Fail, Warn}; use crate::normalize::{self, Context, Variations}; use crate::{features, rustflags, Expected, Runner, Test}; use std::collections::BTreeMap as Map; use std::env; use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::mem; use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct Project { pub dir: Directory, source_dir: Directory, pub target_dir: Directory, pub name: String, update: Update, pub has_pass: bool, has_compile_fail: bool, pub features: Option>, pub workspace: Directory, pub path_dependencies: Vec, manifest: Manifest, } #[derive(Debug)] pub struct PathDependency { pub name: String, pub normalized_path: Directory, } impl Runner { pub fn run(&mut self) { let mut tests = expand_globs(&self.tests); filter(&mut tests); let (project, _lock) = (|| { let project = self.prepare(&tests)?; let lock = Lock::acquire(path!(project.dir / ".lock")); self.write(&project)?; Ok((project, lock)) })() .unwrap_or_else(|err| { message::prepare_fail(err); panic!("tests failed"); }); print!("\n\n"); let len = tests.len(); let mut failures = 0; if tests.is_empty() { message::no_tests_enabled(); } else { for test in tests { if let Err(err) = test.run(&project) { failures += 1; message::test_fail(err); } } } print!("\n\n"); if failures > 0 && project.name != "trybuild-tests" { panic!("{} of {} tests failed", failures, len); } } fn prepare(&self, tests: &[ExpandedTest]) -> Result { let Metadata { target_directory: target_dir, workspace_root: workspace, packages, } = cargo::metadata()?; let crate_name = env::var("CARGO_PKG_NAME").map_err(Error::PkgName)?; let mut has_pass = false; let mut has_compile_fail = false; for e in tests { match e.test.expected { Expected::Pass => has_pass = true, Expected::CompileFail => has_compile_fail = true, } } let source_dir = env::var_os("CARGO_MANIFEST_DIR") .map(Directory::from) .ok_or(Error::ProjectDir)?; let source_manifest = dependencies::get_manifest(&source_dir); let mut features = features::find(); let path_dependencies = source_manifest .dependencies .iter() .filter_map(|(name, dep)| { let path = dep.path.as_ref()?; if packages.iter().any(|p| &p.name == name) { // Skip path dependencies coming from the workspace itself None } else { Some(PathDependency { name: name.clone(), normalized_path: path.canonicalize().ok()?, }) } }) .collect(); let project_dir = path!(target_dir / "tests" / crate_name /); fs::create_dir_all(&project_dir)?; let project_name = format!("{}-tests", crate_name); let manifest = self.make_manifest( crate_name, &workspace, &project_name, &source_dir, tests, source_manifest, ); if let Some(enabled_features) = &mut features { enabled_features.retain(|feature| manifest.features.contains_key(feature)); } Ok(Project { dir: project_dir, source_dir, target_dir, name: project_name, update: Update::env()?, has_pass, has_compile_fail, features, workspace, path_dependencies, manifest, }) } fn write(&self, project: &Project) -> Result<()> { let manifest_toml = toml::to_string(&project.manifest)?; let config = self.make_config(); let config_toml = toml::to_string(&config)?; fs::create_dir_all(path!(project.dir / ".cargo"))?; fs::write(path!(project.dir / ".cargo" / "config"), config_toml)?; fs::write(path!(project.dir / "Cargo.toml"), manifest_toml)?; fs::write(path!(project.dir / "main.rs"), b"fn main() {}\n")?; cargo::build_dependencies(project)?; Ok(()) } fn make_manifest( &self, crate_name: String, workspace: &Directory, project_name: &str, source_dir: &Directory, tests: &[ExpandedTest], source_manifest: dependencies::Manifest, ) -> Manifest { let workspace_manifest = dependencies::get_workspace_manifest(workspace); let features = source_manifest .features .keys() .map(|feature| { let enable = format!("{}/{}", crate_name, feature); (feature.clone(), vec![enable]) }) .collect(); let mut manifest = Manifest { package: Package { name: project_name.to_owned(), version: "0.0.0".to_owned(), edition: source_manifest.package.edition, publish: false, }, features, dependencies: Map::new(), target: source_manifest.target, bins: Vec::new(), workspace: Some(Workspace {}), // Within a workspace, only the [patch] and [replace] sections in // the workspace root's Cargo.toml are applied by Cargo. patch: workspace_manifest.patch, replace: workspace_manifest.replace, }; manifest.dependencies.extend(source_manifest.dependencies); manifest .dependencies .extend(source_manifest.dev_dependencies); for target in manifest.target.values_mut() { let dev_dependencies = mem::replace(&mut target.dev_dependencies, Map::new()); target.dependencies.extend(dev_dependencies); } manifest.dependencies.insert( crate_name, Dependency { version: None, path: Some(source_dir.clone()), default_features: false, features: Vec::new(), git: None, branch: None, tag: None, rev: None, rest: Map::new(), }, ); manifest.bins.push(Bin { name: Name(project_name.to_owned()), path: Path::new("main.rs").to_owned(), }); for expanded in tests { if expanded.error.is_none() { manifest.bins.push(Bin { name: expanded.name.clone(), path: source_dir.join(&expanded.test.path), }); } } manifest } fn make_config(&self) -> Config { Config { build: Build { rustflags: rustflags::make_vec(), }, } } } impl Test { fn run(&self, project: &Project, name: &Name) -> Result<()> { let show_expected = project.has_pass && project.has_compile_fail; message::begin_test(self, show_expected); check_exists(&self.path)?; let output = cargo::build_test(project, name)?; let success = output.status.success(); let stdout = output.stdout; let stderr = normalize::diagnostics( output.stderr, Context { krate: &name.0, source_dir: &project.source_dir, workspace: &project.workspace, path_dependencies: &project.path_dependencies, }, ); let check = match self.expected { Expected::Pass => Test::check_pass, Expected::CompileFail => Test::check_compile_fail, }; check(self, project, name, success, stdout, stderr) } fn check_pass( &self, project: &Project, name: &Name, success: bool, build_stdout: Vec, variations: Variations, ) -> Result<()> { let preferred = variations.preferred(); if !success { message::failed_to_build(preferred); return Err(Error::CargoFail); } let mut output = cargo::run_test(project, name)?; output.stdout.splice(..0, build_stdout); message::output(preferred, &output); if output.status.success() { Ok(()) } else { Err(Error::RunFailed) } } fn check_compile_fail( &self, project: &Project, _name: &Name, success: bool, build_stdout: Vec, variations: Variations, ) -> Result<()> { let preferred = variations.preferred(); if success { message::should_not_have_compiled(); message::fail_output(Fail, &build_stdout); message::warnings(preferred); return Err(Error::ShouldNotHaveCompiled); } let stderr_path = self.path.with_extension("stderr"); if !stderr_path.exists() { match project.update { Update::Wip => { let wip_dir = Path::new("wip"); fs::create_dir_all(wip_dir)?; let gitignore_path = wip_dir.join(".gitignore"); fs::write(gitignore_path, "*\n")?; let stderr_name = stderr_path .file_name() .unwrap_or_else(|| OsStr::new("test.stderr")); let wip_path = wip_dir.join(stderr_name); message::write_stderr_wip(&wip_path, &stderr_path, preferred); fs::write(wip_path, preferred).map_err(Error::WriteStderr)?; } Update::Overwrite => { message::overwrite_stderr(&stderr_path, preferred); fs::write(stderr_path, preferred).map_err(Error::WriteStderr)?; } } message::fail_output(Warn, &build_stdout); return Ok(()); } let expected = fs::read_to_string(&stderr_path) .map_err(Error::ReadStderr)? .replace("\r\n", "\n"); if variations.any(|stderr| expected == stderr) { message::ok(); return Ok(()); } match project.update { Update::Wip => { message::mismatch(&expected, preferred); Err(Error::Mismatch) } Update::Overwrite => { message::overwrite_stderr(&stderr_path, preferred); fs::write(stderr_path, preferred).map_err(Error::WriteStderr)?; Ok(()) } } } } fn check_exists(path: &Path) -> Result<()> { if path.exists() { return Ok(()); } match File::open(path) { Ok(_) => Ok(()), Err(err) => Err(Error::Open(path.to_owned(), err)), } } #[derive(Debug)] struct ExpandedTest { name: Name, test: Test, error: Option, } fn expand_globs(tests: &[Test]) -> Vec { fn glob(pattern: &str) -> Result> { let mut paths = glob::glob(pattern)? .map(|entry| entry.map_err(Error::from)) .collect::>>()?; paths.sort(); Ok(paths) } fn bin_name(i: usize) -> Name { Name(format!("trybuild{:03}", i)) } let mut vec = Vec::new(); for test in tests { let mut expanded = ExpandedTest { name: bin_name(vec.len()), test: test.clone(), error: None, }; if let Some(utf8) = test.path.to_str() { if utf8.contains('*') { match glob(utf8) { Ok(paths) => { for path in paths { vec.push(ExpandedTest { name: bin_name(vec.len()), test: Test { path, expected: expanded.test.expected, }, error: None, }); } continue; } Err(error) => expanded.error = Some(error), } } } vec.push(expanded); } vec } impl ExpandedTest { fn run(self, project: &Project) -> Result<()> { match self.error { None => self.test.run(project, &self.name), Some(error) => { let show_expected = false; message::begin_test(&self.test, show_expected); Err(error) } } } } // Filter which test cases are run by trybuild. // // $ cargo test -- ui trybuild=tuple_structs.rs // // The first argument after `--` must be the trybuild test name i.e. the name of // the function that has the #[test] attribute and calls trybuild. That's to get // Cargo to run the test at all. The next argument starting with `trybuild=` // provides a filename filter. Only test cases whose filename contains the // filter string will be run. #[allow(clippy::needless_collect)] // false positive https://github.com/rust-lang/rust-clippy/issues/5991 fn filter(tests: &mut Vec) { let filters = env::args_os() .flat_map(OsString::into_string) .filter_map(|mut arg| { const PREFIX: &str = "trybuild="; if arg.starts_with(PREFIX) && arg != PREFIX { Some(arg.split_off(PREFIX.len())) } else { None } }) .collect::>(); if filters.is_empty() { return; } tests.retain(|t| { filters .iter() .any(|f| t.test.path.to_string_lossy().contains(f)) }); } trybuild-1.0.50/src/rustflags.rs000064400000000000000000000011660072674642500147500ustar 00000000000000use std::env; use std::process::Command; const RUSTFLAGS: &str = "RUSTFLAGS"; const IGNORED_LINTS: &[&str] = &["dead_code"]; pub fn make_vec() -> Vec<&'static str> { let mut rustflags = vec!["--cfg", "trybuild"]; for &lint in IGNORED_LINTS { rustflags.push("-A"); rustflags.push(lint); } rustflags } pub fn set_env(cmd: &mut Command) { let mut rustflags = match env::var_os(RUSTFLAGS) { Some(rustflags) => rustflags, None => return, }; for flag in make_vec() { rustflags.push(" "); rustflags.push(flag); } cmd.env(RUSTFLAGS, rustflags); } trybuild-1.0.50/src/term.rs000064400000000000000000000050700072674642500137030ustar 00000000000000use lazy_static::lazy_static; use std::io::{Result, Write}; use std::sync::{Mutex, MutexGuard, PoisonError}; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream as Stream, WriteColor}; lazy_static! { static ref TERM: Mutex = Mutex::new(Term::new()); } pub fn lock() -> MutexGuard<'static, Term> { TERM.lock().unwrap_or_else(PoisonError::into_inner) } pub fn bold() { lock().set_color(ColorSpec::new().set_bold(true)); } pub fn color(color: Color) { lock().set_color(ColorSpec::new().set_fg(Some(color))); } pub fn bold_color(color: Color) { lock().set_color(ColorSpec::new().set_bold(true).set_fg(Some(color))); } pub fn reset() { lock().reset(); } #[deny(unused_macros)] macro_rules! print { ($($args:tt)*) => {{ use std::io::Write; let _ = std::write!($crate::term::lock(), $($args)*); }}; } #[deny(unused_macros)] macro_rules! println { ($($args:tt)*) => {{ use std::io::Write; let _ = std::writeln!($crate::term::lock(), $($args)*); }}; } pub struct Term { spec: ColorSpec, stream: Stream, start_of_line: bool, } impl Term { fn new() -> Self { Term { spec: ColorSpec::new(), stream: Stream::stderr(ColorChoice::Auto), start_of_line: true, } } fn set_color(&mut self, spec: &ColorSpec) { if self.spec != *spec { self.spec = spec.clone(); self.start_of_line = true; } } fn reset(&mut self) { self.spec = ColorSpec::new(); let _ = self.stream.reset(); } } impl Write for Term { // Color one line at a time because Travis does not preserve color setting // across output lines. fn write(&mut self, mut buf: &[u8]) -> Result { if self.spec.is_none() { return self.stream.write(buf); } let len = buf.len(); while !buf.is_empty() { if self.start_of_line { let _ = self.stream.set_color(&self.spec); } match buf.iter().position(|byte| *byte == b'\n') { Some(line_len) => { self.stream.write_all(&buf[..line_len + 1])?; self.start_of_line = true; buf = &buf[line_len + 1..]; } None => { self.stream.write_all(buf)?; self.start_of_line = false; break; } } } Ok(len) } fn flush(&mut self) -> Result<()> { self.stream.flush() } } trybuild-1.0.50/src/tests.rs000064400000000000000000000312250072674642500140770ustar 00000000000000use crate::directory::Directory; use crate::run::PathDependency; macro_rules! test_normalize { ($name:ident $(DIR=$dir:literal)? $(WORKSPACE=$workspace:literal)? $original:literal $expected:literal) => { #[test] fn $name() { let context = super::Context { krate: "trybuild000", source_dir: &Directory::new({ "/git/trybuild/test_suite" $(; $dir)? }), workspace: &Directory::new({ "/git/trybuild" $(; $workspace)? }), path_dependencies: &[PathDependency { name: String::from("diesel"), normalized_path: Directory::new("/home/user/documents/rust/diesel/diesel"), }], }; let original = $original.to_owned().into_bytes(); let variations = super::diagnostics(original, context); let preferred = variations.preferred(); let expected = $expected; if preferred != expected { panic!("\nACTUAL: \"{}\"\nEXPECTED: \"{}\"", preferred, expected); } } }; } test_normalize! {test_basic " error: `self` parameter is only allowed in associated functions --> /git/trybuild/test_suite/tests/ui/error.rs:11:23 | 11 | async fn bad_endpoint(self) -> Result, HttpError> { | ^^^^ not semantically valid as function parameter error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0401`. error: could not compile `trybuild-tests`. To learn more, run the command again with --verbose. " " error: `self` parameter is only allowed in associated functions --> tests/ui/error.rs:11:23 | 11 | async fn bad_endpoint(self) -> Result, HttpError> { | ^^^^ not semantically valid as function parameter "} test_normalize! {test_dir_backslash " error[E0277]: the trait bound `QueryParams: serde::de::Deserialize<'de>` is not satisfied --> \\git\\trybuild\\test_suite\\tests\\ui\\error.rs:22:61 " " error[E0277]: the trait bound `QueryParams: serde::de::Deserialize<'de>` is not satisfied --> tests/ui/error.rs:22:61 "} test_normalize! {test_rust_lib " error[E0599]: no method named `quote_into_iter` found for struct `std::net::Ipv4Addr` in the current scope --> /git/trybuild/test_suite/tests/ui/not-repeatable.rs:6:13 | 6 | let _ = quote! { #(#ip)* }; | ^^^^^^^^^^^^^^^^^^ method not found in `std::net::Ipv4Addr` | ::: /rustlib/src/rust/src/libstd/net/ip.rs:83:1 ::: /rustlib/src/rust/library/std/src/net/ip.rs:83:1 | 83 | pub struct Ipv4Addr { | ------------------- | | | doesn't satisfy `std::net::Ipv4Addr: quote::to_tokens::ToTokens` " " error[E0599]: no method named `quote_into_iter` found for struct `std::net::Ipv4Addr` in the current scope --> tests/ui/not-repeatable.rs:6:13 | 6 | let _ = quote! { #(#ip)* }; | ^^^^^^^^^^^^^^^^^^ method not found in `std::net::Ipv4Addr` | ::: $RUST/src/libstd/net/ip.rs ::: $RUST/std/src/net/ip.rs | | pub struct Ipv4Addr { | ------------------- | | | doesn't satisfy `std::net::Ipv4Addr: quote::to_tokens::ToTokens` "} test_normalize! {test_type_dir_backslash " error[E0277]: `*mut _` cannot be shared between threads safely --> /git/trybuild/test_suite/tests/ui/compile-fail-3.rs:7:5 | 7 | thread::spawn(|| { | ^^^^^^^^^^^^^ `*mut _` cannot be shared between threads safely | = help: the trait `std::marker::Sync` is not implemented for `*mut _` = note: required because of the requirements on the impl of `std::marker::Send` for `&*mut _` = note: required because it appears within the type `[closure@/git/trybuild/test_suite/ui/compile-fail-3.rs:7:19: 9:6 x:&*mut _]` " " error[E0277]: `*mut _` cannot be shared between threads safely --> tests/ui/compile-fail-3.rs:7:5 | 7 | thread::spawn(|| { | ^^^^^^^^^^^^^ `*mut _` cannot be shared between threads safely | = help: the trait `std::marker::Sync` is not implemented for `*mut _` = note: required because of the requirements on the impl of `std::marker::Send` for `&*mut _` = note: required because it appears within the type `[closure@$DIR/ui/compile-fail-3.rs:7:19: 9:6 x:&*mut _]` "} test_normalize! {test_strip_path_dependencies " error[E0277]: the trait bound `diesel::query_builder::SelectStatement>>>>: diesel::query_builder::IntoUpdateTarget` is not satisfied --> $DIR/update_requires_valid_where_clause.rs:21:12 | 21 | update(users::table.filter(posts::id.eq(1))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `diesel::query_builder::IntoUpdateTarget` is not implemented for `diesel::query_builder::SelectStatement>>>>` | ::: /home/user/documents/rust/diesel/diesel/src/query_builder/functions.rs:78:18 | 78 | pub fn update(source: T) -> UpdateStatement { | ---------------- required by this bound in `diesel::update` | = help: the following implementations were found: as diesel::query_builder::IntoUpdateTarget> " " error[E0277]: the trait bound `diesel::query_builder::SelectStatement>>>>: diesel::query_builder::IntoUpdateTarget` is not satisfied --> $DIR/update_requires_valid_where_clause.rs:21:12 | 21 | update(users::table.filter(posts::id.eq(1))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `diesel::query_builder::IntoUpdateTarget` is not implemented for `diesel::query_builder::SelectStatement>>>>` | ::: $DIESEL/src/query_builder/functions.rs | | pub fn update(source: T) -> UpdateStatement { | ---------------- required by this bound in `diesel::update` | = help: the following implementations were found: as diesel::query_builder::IntoUpdateTarget> "} test_normalize! {test_cargo_registry " error[E0277]: the trait bound `Thread: serde::de::Deserialize<'_>` is not satisfied --> src/main.rs:2:36 | 2 | let _ = serde_json::from_str::(\"???\"); | ^^^^^^^^^^^^^^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `Thread` | ::: /home/ferris/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.64/src/de.rs:2584:8 | 2584 | T: de::Deserialize<'a>, | ------------------- required by this bound in `serde_json::from_str` For more information about this error, try `rustc --explain E0277`. error: could not compile `testing` due to previous error " " error[E0277]: the trait bound `Thread: serde::de::Deserialize<'_>` is not satisfied --> src/main.rs:2:36 | 2 | let _ = serde_json::from_str::(\"???\"); | ^^^^^^^^^^^^^^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `Thread` | ::: $CARGO/serde_json-1.0.64/src/de.rs | | T: de::Deserialize<'a>, | ------------------- required by this bound in `serde_json::from_str` "} test_normalize! {test_traits_must_be_implemented " error[E0599]: the method `anyhow_kind` exists for reference `&Error`, but its trait bounds were not satisfied --> src/main.rs:7:13 | 4 | struct Error; | ------------- | | | doesn't satisfy `Error: Into` | doesn't satisfy `Error: anyhow::private::kind::TraitKind` | doesn't satisfy `Error: std::fmt::Display` ... 7 | let _ = anyhow!(Error); | ^^^^^^^^^^^^^^ method cannot be called on `&Error` due to unsatisfied trait bounds | = note: the following trait bounds were not satisfied: `Error: Into` which is required by `Error: anyhow::private::kind::TraitKind` `Error: std::fmt::Display` which is required by `&Error: anyhow::private::kind::AdhocKind` `&Error: Into` which is required by `&Error: anyhow::private::kind::TraitKind` note: the following traits must be implemented --> /rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/convert/mod.rs:274:1 | 274 | / pub trait Into: Sized { 275 | | /// Performs the conversion. 276 | | #[stable(feature = \"rust1\", since = \"1.0.0\")] 277 | | fn into(self) -> T; 278 | | } | |_^ | ::: /rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/fmt/mod.rs:715:1 | 715 | / pub trait Display { 716 | | /// Formats the value using the given formatter. 717 | | /// 718 | | /// # Examples ... | 738 | | fn fmt(&self, f: &mut Formatter<'_>) -> Result; 739 | | } | |_^ = note: this error originates in the macro `anyhow` (in Nightly builds, run with -Z macro-backtrace for more info) " " error[E0599]: the method `anyhow_kind` exists for reference `&Error`, but its trait bounds were not satisfied --> src/main.rs:7:13 | 4 | struct Error; | ------------- | | | doesn't satisfy `Error: Into` | doesn't satisfy `Error: anyhow::private::kind::TraitKind` | doesn't satisfy `Error: std::fmt::Display` ... 7 | let _ = anyhow!(Error); | ^^^^^^^^^^^^^^ method cannot be called on `&Error` due to unsatisfied trait bounds | = note: the following trait bounds were not satisfied: `Error: Into` which is required by `Error: anyhow::private::kind::TraitKind` `Error: std::fmt::Display` which is required by `&Error: anyhow::private::kind::AdhocKind` `&Error: Into` which is required by `&Error: anyhow::private::kind::TraitKind` note: the following traits must be implemented --> $RUST/core/src/convert/mod.rs | | / pub trait Into: Sized { | | /// Performs the conversion. | | #[stable(feature = \"rust1\", since = \"1.0.0\")] | | fn into(self) -> T; | | } | |_^ | ::: $RUST/core/src/fmt/mod.rs | | / pub trait Display { | | /// Formats the value using the given formatter. | | /// | | /// # Examples ... | | | fn fmt(&self, f: &mut Formatter<'_>) -> Result; | | } | |_^ = note: this error originates in the macro `anyhow` (in Nightly builds, run with -Z macro-backtrace for more info) "} test_normalize! {test_pyo3_url DIR="/pyo3" WORKSPACE="/pyo3" " error: `async fn` is not yet supported for Python functions. Additional crates such as `pyo3-asyncio` can be used to integrate async Rust and Python. For more information, see https://github.com/PyO3/pyo3/issues/1632 --> tests/ui/invalid_pyfunctions.rs:10:1 | 10 | async fn async_function() {} | ^^^^^ " " error: `async fn` is not yet supported for Python functions. Additional crates such as `pyo3-asyncio` can be used to integrate async Rust and Python. For more information, see https://github.com/PyO3/pyo3/issues/1632 --> tests/ui/invalid_pyfunctions.rs:10:1 | 10 | async fn async_function() {} | ^^^^^ "} trybuild-1.0.50/tests/test.rs000064400000000000000000000014340072674642500142660ustar 00000000000000#[test] fn test() { let t = trybuild::TestCases::new(); t.pass("tests/ui/run-pass-0.rs"); t.pass("tests/ui/print-stdout.rs"); t.pass("tests/ui/run-pass-1.rs"); t.pass("tests/ui/print-stderr.rs"); t.pass("tests/ui/run-pass-2.rs"); t.pass("tests/ui/print-both.rs"); t.pass("tests/ui/run-pass-4.rs"); t.compile_fail("tests/ui/run-pass-3.rs"); t.pass("tests/ui/run-pass-5.rs"); t.pass("tests/ui/compile-fail-0.rs"); t.pass("tests/ui/run-pass-6.rs"); t.pass("tests/ui/run-pass-7.rs"); t.pass("tests/ui/run-pass-8.rs"); t.compile_fail("tests/ui/compile-fail-1.rs"); t.pass("tests/ui/run-fail.rs"); t.pass("tests/ui/run-pass-9.rs"); t.compile_fail("tests/ui/compile-fail-2.rs"); t.compile_fail("tests/ui/compile-fail-3.rs"); } trybuild-1.0.50/tests/ui/compile-fail-0.rs000064400000000000000000000000470072674642500164210ustar 00000000000000compile_error!("ERROR"); fn main() {} trybuild-1.0.50/tests/ui/compile-fail-1.rs000064400000000000000000000000470072674642500164220ustar 00000000000000compile_error!("ERROR"); fn main() {} trybuild-1.0.50/tests/ui/compile-fail-2.rs000064400000000000000000000000470072674642500164230ustar 00000000000000compile_error!("ERROR"); fn main() {} trybuild-1.0.50/tests/ui/compile-fail-2.stderr000064400000000000000000000001530072674642500173000ustar 00000000000000error: ERROR --> $DIR/compile-fail-2.rs:1:1 | 1 | compile_error!("ERROR"); | ^^^^^^^^^^^^^^^^^^^^^^^^ trybuild-1.0.50/tests/ui/compile-fail-3.rs000064400000000000000000000002070072674642500164220ustar 00000000000000use std::ptr; use std::thread; fn main() { let x = ptr::null_mut(); thread::spawn(|| { println!("{:?}", x) }); } trybuild-1.0.50/tests/ui/compile-fail-3.stderr000064400000000000000000000007230072674642500173040ustar 00000000000000error[E0277]: `*mut _` cannot be shared between threads safely --> $DIR/compile-fail-3.rs:7:5 | 7 | thread::spawn(|| { | ^^^^^^^^^^^^^ `*mut _` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `*mut _` = note: required because of the requirements on the impl of `Send` for `&*mut _` = note: required because it appears within the type `[closure@$DIR/tests/ui/compile-fail-3.rs:7:19: 9:6]` trybuild-1.0.50/tests/ui/print-both.rs000064400000000000000000000001370072674642500160110ustar 00000000000000fn main() { println!("{:?}", "STDOUT".chars()); eprintln!("{:?}", "STDERR".chars()); } trybuild-1.0.50/tests/ui/print-stderr.rs000064400000000000000000000000670072674642500163620ustar 00000000000000fn main() { eprintln!("{:?}", "STDERR".chars()); } trybuild-1.0.50/tests/ui/print-stdout.rs000064400000000000000000000000660072674642500164000ustar 00000000000000fn main() { println!("{:?}", "STDOUT".chars()); } trybuild-1.0.50/tests/ui/run-fail.rs000064400000000000000000000000420072674642500154330ustar 00000000000000fn main() { assert!(false); } trybuild-1.0.50/tests/ui/run-pass-0.rs000064400000000000000000000000150072674642500156230ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-1.rs000064400000000000000000000000150072674642500156240ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-2.rs000064400000000000000000000000150072674642500156250ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-3.rs000064400000000000000000000000150072674642500156260ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-4.rs000064400000000000000000000000150072674642500156270ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-5.rs000064400000000000000000000000150072674642500156300ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-6.rs000064400000000000000000000000150072674642500156310ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-7.rs000064400000000000000000000000150072674642500156320ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-8.rs000064400000000000000000000000150072674642500156330ustar 00000000000000fn main() {} trybuild-1.0.50/tests/ui/run-pass-9.rs000064400000000000000000000000150072674642500156340ustar 00000000000000fn main() {}