### Implement TestCases::new Source: https://docs.rs/trybuild/latest/trybuild/struct.TestCases.html Constructor for creating a new instance of TestCases. No specific setup is required. ```rust pub fn new() -> Self> ``` -------------------------------- ### Directory Initialization and Current Directory Source: https://docs.rs/trybuild/latest/src/trybuild/directory.rs.html Provides methods to create a new Directory instance from a path and to get the current working directory. The `new` method appends an empty string, ensuring it's treated as a directory. ```rust impl Directory { pub fn new>(path: P) -> Self { let mut path = path.into(); path.push(""); Directory { path } } pub fn current() -> io::Result { env::current_dir().map(Directory::new) } // ... other methods ``` -------------------------------- ### Verify Post-Expansion Compiler Errors Source: https://docs.rs/trybuild Example of a compile-fail test output for errors triggered after successful macro expansion. ```text 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 ``` -------------------------------- ### Basic Compile-Fail Test Setup Source: https://docs.rs/trybuild Set up a basic compile-fail test using trybuild. This test will individually compile each source file matching the glob pattern, expect them to fail, and assert that the compiler's error message matches an adjacent .stderr file. ```rust #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } ``` -------------------------------- ### Verify Declarative Macro Error Placement Source: https://docs.rs/trybuild Example of a compile-fail test output for a declarative macro ensuring errors appear on the appropriate token. ```text 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 ``` -------------------------------- ### Locate Project Manifest Source: https://docs.rs/trybuild/latest/src/trybuild/cargo.rs.html Finds the project root directory by searching for Cargo.toml starting from the current directory. ```rust pub(crate) fn manifest_dir() -> Result { if let Some(manifest_dir) = env::var_os("CARGO_MANIFEST_DIR") { return Ok(Directory::from(manifest_dir)); } let mut dir = Directory::current()?; loop { if dir.join("Cargo.toml").exists() { return Ok(dir); } dir = dir.parent().ok_or(Error::ProjectDir)?; } } ``` -------------------------------- ### Verify Macro Helper Attribute Errors Source: https://docs.rs/trybuild Example of a compile-fail test output ensuring error messages are placed on the correct tokens within helper attributes. ```text error: unknown serde field attribute `qqq` --> $DIR/unknown-attribute.rs:5:13 | 5 | #[serde(qqq = "...")] | ^^^ ``` -------------------------------- ### Try Get Workspace Manifest Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Attempts to read and parse the workspace Cargo.toml, fixing dependencies, patches, and replacements. ```rust pub(crate) 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_dependencies(&mut manifest.workspace.dependencies, manifest_dir); fix_patches(&mut manifest.patch, manifest_dir); fix_replacements(&mut manifest.replace, manifest_dir); Ok(manifest) } ``` -------------------------------- ### Normalize Rust Standard Library Paths Source: https://docs.rs/trybuild/latest/src/trybuild/normalize.rs.html Replaces standard library paths with a placeholder to normalize compiler output. Handles different Rust installation structures. ```Rust line.replace_range(indent + 4..pos + 17, "$RUST"); ``` ```Rust line.replace_range(indent + 4..pos + 25, "$RUST"); ``` ```Rust line.replace_range(indent + 4..indent + 59, "$RUST"); ``` -------------------------------- ### Verify Procedural Macro Error Messages Source: https://docs.rs/trybuild Example of a compile-fail test output for a derive macro enforcing specific type attributes. ```text error: RefCast trait requires #[repr(C)] or #[repr(transparent)] --> $DIR/missing-repr.rs:3:10 | 3 | #[derive(RefCast)] | ^^^^^^^ ``` -------------------------------- ### Build Project Dependencies Source: https://docs.rs/trybuild/latest/src/trybuild/cargo.rs.html Prepares the project environment by copying or generating a lockfile and running the build or check command. ```rust pub(crate) fn build_dependencies(project: &mut Project) -> Result<()> { // Try copying or generating lockfile. match File::open({ let mut path = std::path::PathBuf::new(); path.push(&(project.workspace)); path.push(&("Cargo.lock")); path }path!(project.workspace / "Cargo.lock")) { Ok(mut workspace_cargo_lock) => { if let Ok(mut new_cargo_lock) = File::create({ let mut path = std::path::PathBuf::new(); path.push(&(project.dir)); path.push(&("Cargo.lock")); path }path!(project.dir / "Cargo.lock")) { // Not fs::copy in order to avoid producing a read-only destination // file if the source file happens to be read-only. let _ = io::copy(&mut workspace_cargo_lock, &mut new_cargo_lock); } } Err(err) => { if err.kind() == io::ErrorKind::NotFound { let _ = cargo(project).arg("generate-lockfile").status(); } } } let mut command = cargo(project); command .arg(if project.has_pass { "build" } else { "check" }) .args(target()) .arg("--bin") .arg(&project.name) .args(features(project)); let status = command.status().map_err(Error::Cargo)?; if !status.success() { return Err(Error::CargoFail); } // Check if this Cargo contains https://github.com/rust-lang/cargo/pull/10383 project.keep_going = command .arg("--keep-going") .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .is_ok_and(|status| status.success()); Ok(()) } ``` -------------------------------- ### Get Workspace Manifest Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Retrieves the workspace manifest, falling back to a default if an error occurs. ```rust pub(crate) fn get_workspace_manifest(manifest_dir: &Directory) -> WorkspaceManifest { try_get_workspace_manifest(manifest_dir).unwrap_or_default() } ``` -------------------------------- ### Get Cargo Manifest Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Reads and parses the Cargo.toml file for a given directory, fixing dependency paths. ```rust use crate::directory::Directory; use crate::error::Error; use crate::inherit::InheritEdition; use crate::manifest::Edition; use serde::de::value::MapAccessDeserializer; use serde::de::value::StrDeserializer; use serde::de::{self, Deserialize, Deserializer, Visitor}; use serde::ser::{Serialize, Serializer}; use serde_derive::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap as Map; use std::fmt; use std::fs; use std::path::PathBuf; pub(crate) fn get_manifest(manifest_dir: &Directory) -> Result { let cargo_toml_path = manifest_dir.join("Cargo.toml"); let mut manifest = (|| { let manifest_str = fs::read_to_string(&cargo_toml_path)?; let manifest: Manifest = toml::from_str(&manifest_str)?; Ok(manifest) })() .map_err(|err| Error::GetManifest(cargo_toml_path, Box::new(err)))?; 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) } ``` -------------------------------- ### Create Project Directory Path Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Constructs the path for the test project directory, including the target directory, 'tests', 'trybuild', and the crate name. ```rust let mut path = std::path::PathBuf::new(); path.push(&(target_dir)); path.push(&("tests")); path.push(&("trybuild")); path.push(&(crate_name)); path ``` -------------------------------- ### Format Project Name Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Creates a project name by appending '-tests' to the crate name. ```rust ::alloc::fmt::format(format_args!({"}-tests", crate_name)) ``` -------------------------------- ### Begin Test Message Source: https://docs.rs/trybuild/latest/src/trybuild/message.rs.html Prints the beginning of a test, including its display name and optional status (should pass/fail). ```rust pub(crate) fn begin_test(test: &Test, show_expected: bool) { let display_name = test.path.as_os_str().to_string_lossy(); { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!("test ")); }; term::bold(); { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!("{0}", display_name)); }; term::reset(); if show_expected { match test.expected { Expected::Pass => { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!(" [should pass]")); } Expected::CompileFail => { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!(" [should fail to compile]")); } } } { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!(" ... ")); }; } ``` -------------------------------- ### Path Macro for Constructing Paths Source: https://docs.rs/trybuild/latest/src/trybuild/path.rs.html Use the `path!` macro to conveniently construct `PathBuf` instances by concatenating path components with the `/` operator. It simplifies path creation, especially within tests. ```rust use std::path::{Path, PathBuf}; macro_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 }}; } ``` -------------------------------- ### Implement Visitor for i64 Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting i64 values within a visitor pattern, converting them to an `_serde::__private228::de::Content::I64` variant. ```rust fn visit_i64<__E>(self, __value: i64) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::I64(__value))) } ``` -------------------------------- ### Implement Visitor for bytes Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting byte slices within a visitor pattern, mapping specific byte slices to fields and others to `_serde::__private228::de::Content::ByteBuf`. ```rust fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::__private228::Result where __E: _serde::de::Error { match __value { b"path" => _serde::__private228::Ok(__Field::__field0), b"git" => _serde::__private228::Ok(__Field::__field1), b"branch" => _serde::__private228::Ok(__Field::__field2), b"tag" => _serde::__private228::Ok(__Field::__field3), b"rev" => _serde::__private228::Ok(__Field::__field4), _ => { let __value = _serde::__private228::de::Content::ByteBuf(__value.to_vec()); _serde::__private228::Ok(__Field::__other(__value)) } } } ``` -------------------------------- ### Write Main RS File Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Writes a minimal main.rs file to the project directory, typically used for integration tests. ```rust let mut path = std::path::PathBuf::new(); path.push(&(project.dir)); path.push(&("main.rs")); path ``` -------------------------------- ### Feature and Target Configuration Helpers Source: https://docs.rs/trybuild/latest/src/trybuild/cargo.rs.html Utilities to generate feature flag arguments and determine the target triple for Cargo commands. ```rust fn features(project: &Project) -> Vec { match &project.features { Some(features) => <[_]>::into_vec(::alloc::boxed::box_new(["--no-default-features".to_owned(), "--features".to_owned(), features.join(",")]))vec![ "--no-default-features".to_owned(), "--features".to_owned(), features.join(","), ], None => ::alloc::vec::Vec::new()vec![], } } ``` ```rust fn target() -> Vec<&'static str> { if falsecfg!(trybuild_no_target) { ::alloc::vec::Vec::new()vec![] } else { <[_]>::into_vec(::alloc::boxed::box_new(["--target", TARGET]))vec!["--target", TARGET] } } ``` -------------------------------- ### Find and Parse Build Features JSON Source: https://docs.rs/trybuild/latest/src/trybuild/features.rs.html This function `try_find` locates the build fingerprint JSON file for the current test binary and parses it to extract the enabled features. It requires the `serde` and `serde_json` crates. Ensure the execution environment has access to the target directory. ```rust 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 falsecfg!(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) } ``` -------------------------------- ### Implement Visitor for str Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting string slices within a visitor pattern, mapping specific strings to fields and others to `_serde::__private228::de::Content::String`. ```rust fn visit_str<__E>(self, __value: &str) -> _serde::__private228::Result where __E: _serde::de::Error { match __value { "path" => _serde::__private228::Ok(__Field::__field0), "git" => _serde::__private228::Ok(__Field::__field1), "branch" => _serde::__private228::Ok(__Field::__field2), "tag" => _serde::__private228::Ok(__Field::__field3), "rev" => _serde::__private228::Ok(__Field::__field4), _ => { let __value = _serde::__private228::de::Content::String(_serde::__private228::ToString::to_string(__value)); _serde::__private228::Ok(__Field::__other(__value)) } } } ``` -------------------------------- ### Build and Test Execution Helpers Source: https://docs.rs/trybuild/latest/src/trybuild/cargo.rs.html Functions to execute build and test commands via Cargo, including specific configurations for diagnostic output and feature flags. ```rust pub(crate) fn build_all_tests(project: &Project) -> Result { let _ = cargo(project) .arg("clean") .arg("--package") .arg(&project.name) .arg("--color=never") .stdout(Stdio::null()) .stderr(Stdio::null()) .status(); cargo_with_rustflags(project, &["--diagnostic-width=140"]) .arg(if project.has_pass { "build" } else { "check" }) .args(target()) .arg("--bins") .args(features(project)) .arg("--quiet") .arg("--color=never") .arg("--message-format=json") .arg("--keep-going") .output() .map_err(Error::Cargo) } ``` ```rust pub(crate) 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) } ``` -------------------------------- ### Implement Visitor for f64 Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting f64 values within a visitor pattern, converting them to an `_serde::__private228::de::Content::F64` variant. ```rust fn visit_f64<__E>(self, __value: f64) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::F64(__value))) } ``` -------------------------------- ### Implement Visitor for u64 Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting u64 values within a visitor pattern, converting them to an `_serde::__private228::de::Content::U64` variant. ```rust fn visit_u64<__E>(self, __value: u64) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::U64(__value))) } ``` -------------------------------- ### Execute Test Logic Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Core method to run a test, build the project, and initiate the validation check. ```rust 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 mut path_map = Map::new(); let src_path = CanonicalPath::new(&project.source_dir.join(&self.path)); path_map.insert(src_path.clone(), (name, self)); let output = cargo::build_test(project, name)?; let parsed = parse_cargo_json(project, &output.stdout, &path_map); let fallback = Stderr::default(); let this_test = parsed.stderrs.get(&src_path).unwrap_or(&fallback); self.check(project, name, this_test, &parsed.stdout) } ``` -------------------------------- ### Implement Visitor for i32 Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting i32 values within a visitor pattern, converting them to an `_serde::__private228::de::Content::I32` variant. ```rust fn visit_i32<__E>(self, __value: i32) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::I32(__value))) } ``` -------------------------------- ### Configure rust-src for Consistent Diagnostics Source: https://docs.rs/trybuild Add this configuration to rust-toolchain.toml to ensure the compiler can render standard library source snippets in diagnostics. ```toml [toolchain] components = ["rust-src"] ``` -------------------------------- ### Write Project Manifest Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Writes the generated manifest TOML string to the Cargo.toml file within the project directory. ```rust let mut path = std::path::PathBuf::new(); path.push(&(project.dir)); path.push(&("Cargo.toml")); path ``` -------------------------------- ### Construct Manifest Object Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Assembles the final `Manifest` struct using data from the source manifest, workspace, and processed features and dependencies. Includes package details and bins. ```rust let mut manifest = Manifest { cargo_features: source_manifest.cargo_features, package: Package { name: project_name.to_owned(), version: "0.0.0".to_owned(), edition, resolver: source_manifest.package.resolver, publish: false, }, features, dependencies, target: targets, bins: Vec::new(), workspace: Some(Workspace { dependencies: workspace_manifest.workspace.dependencies, }), // 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, }; ``` -------------------------------- ### Check File Existence Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Verifies if a file exists at the given path or can be opened, returning an error if access fails. ```rust 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)), } } ``` -------------------------------- ### Directory Conversion from OsString Source: https://docs.rs/trybuild/latest/src/trybuild/directory.rs.html Implements the From trait to allow conversion of an OsString directly into a Directory instance. This is useful when working with environment variables or other OS-level string representations of paths. ```rust impl From for Directory { fn from(os_string: OsString) -> Self { Directory::new(PathBuf::from(os_string)) } } ``` -------------------------------- ### Directory Path Manipulation Methods Source: https://docs.rs/trybuild/latest/src/trybuild/directory.rs.html Offers utility methods for path manipulation, including converting the path to a lossy string, joining path components, and retrieving the parent directory. ```rust 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 parent(&self) -> Option { self.path.parent().map(Directory::new) } // ... other methods ``` -------------------------------- ### Default Implementation for Package Struct Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Provides a default implementation for the Package struct, initializing all fields to their default values. ```rust impl ::core::default::Default for Package { #[inline] fn default() -> Package { Package { name: ::core::default::Default::default(), edition: ::core::default::Default::default(), resolver: ::core::default::Default::default(), } } } ``` -------------------------------- ### Implement Serde Visitor Methods Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html These methods handle the deserialization of various primitive types into a custom field enum. Use these within a Visitor implementation to map incoming data to specific struct fields. ```rust __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::U16(__value))) } fn visit_u32<__E>(self, __value: u32) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::U32(__value))) } fn visit_u64<__E>(self, __value: u64) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::U64(__value))) } fn visit_f32<__E>(self, __value: f32) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::F32(__value))) } fn visit_f64<__E>(self, __value: f64) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::F64(__value))) } fn visit_char<__E>(self, __value: char) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::Char(__value))) } fn visit_unit<__E>(self) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::Unit)) } ``` ```rust fn visit_str<__E>(self, __value: &str) -> _serde::__private228::Result where __E: _serde::de::Error { match __value { "version" => _serde::__private228::Ok(__Field::__field0), "path" => _serde::__private228::Ok(__Field::__field1), "optional" => _serde::__private228::Ok(__Field::__field2), "default-features" => _serde::__private228::Ok(__Field::__field3), "features" => _serde::__private228::Ok(__Field::__field4), "git" => _serde::__private228::Ok(__Field::__field5), "branch" => _serde::__private228::Ok(__Field::__field6), "tag" => _serde::__private228::Ok(__Field::__field7), "rev" => _serde::__private228::Ok(__Field::__field8), "workspace" => _serde::__private228::Ok(__Field::__field9), _ => { let __value = _serde::__private228::de::Content::String(_serde::__private228::ToString::to_string(__value)); _serde::__private228::Ok(__Field::__other(__value)) } } } ``` ```rust fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::__private228::Result where __E: _serde::de::Error { match __value { b"version" => _serde::__private228::Ok(__Field::__field0), b"path" => _serde::__private228::Ok(__Field::__field1), b"optional" => _serde::__private228::Ok(__Field::__field2), b"default-features" => _serde::__private228::Ok(__Field::__field3), b"features" => _serde::__private228::Ok(__Field::__field4), b"git" => _serde::__private228::Ok(__Field::__field5), b"branch" => _serde::__private228::Ok(__Field::__field6), b"tag" => _serde::__private228::Ok(__Field::__field7), b"rev" => _serde::__private228::Ok(__Field::__field8), b"workspace" => _serde::__private228::Ok(__Field::__field9), _ => { let __value = _serde::__private228::de::Content::ByteBuf(__value.to_vec()); ``` -------------------------------- ### Implement TestCases::pass Source: https://docs.rs/trybuild/latest/trybuild/struct.TestCases.html Adds a test case that is expected to compile successfully. Accepts a path to the test file. ```rust pub fn pass>(&self, path: P)> ``` -------------------------------- ### Runner Execution Logic Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Core logic for initializing the project environment, acquiring locks, and executing tests. ```rust impl Runner { pub(crate) fn run(&mut self) { let mut tests = expand_globs(&self.tests); filter(&mut tests); let (project, _lock) = (|| { let mut project = self.prepare(&tests)?; let lock = Lock::acquire({ let mut path = std::path::PathBuf::new(); path.push(&(project.dir)); path.push(&(".lock")); path }path!(project.dir / ".lock"))?; self.write(&mut project)?; Ok((project, lock)) })() .unwrap_or_else(|err| { message::prepare_fail(err); { ::core::panicking::panic_fmt(format_args!("tests failed")); };panic!("tests failed"); }); { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!("\n\n")); };print!("\n\n"); let len = tests.len(); let mut report = Report { failures: 0, created_wip: 0, }; if tests.is_empty() { message::no_tests_enabled(); } else if project.keep_going && !project.has_pass { report = match self.run_all(&project, tests) { Ok(failures) => failures, Err(err) => { message::test_fail(err); Report { failures: len, created_wip: 0, } } } } else { for test in tests { match test.run(&project) { Ok(Outcome::Passed) => {} Ok(Outcome::CreatedWip) => report.created_wip += 1, Err(err) => { report.failures += 1; message::test_fail(err); } } } } { use std::io::Write; let _ = crate::term::lock().write_fmt(format_args!("\n\n")); };print!("\n\n"); if report.failures > 0 && project.name != "trybuild-tests" { { ::core::panicking::panic_fmt(format_args!("{0} of {1} tests failed", report.failures, len)); };panic!("{} of {} tests failed", report.failures, len); } if report.created_wip > 0 && project.name != "trybuild-tests" { ``` -------------------------------- ### Project and PathDependency Data Structures Source: https://docs.rs/trybuild/latest/src/trybuild/run.rs.html Internal structs representing the test project configuration and its path dependencies. ```rust pub(crate) 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, pub keep_going: bool, } ``` ```rust pub(crate) struct PathDependency { pub name: String, pub normalized_path: Directory, } ``` -------------------------------- ### Initialize Cargo Command Source: https://docs.rs/trybuild/latest/src/trybuild/cargo.rs.html Creates a base Command object for Cargo, respecting the CARGO environment variable if set. ```rust fn raw_cargo() -> Command { match env::var_os("CARGO") { Some(cargo) => Command::new(cargo), None => Command::new("cargo"), } } ``` -------------------------------- ### TestCases API Source: https://docs.rs/trybuild/latest/trybuild/struct.TestCases.html Methods for initializing and running test cases using the TestCases struct. ```APIDOC ## TestCases API ### Description The TestCases struct is the primary entry point for trybuild tests. It allows users to register files that should compile successfully or fail to compile. ### Methods - **new() -> Self**: Creates a new instance of TestCases. - **pass>(&self, path: P)**: Registers a test case that is expected to compile successfully. - **compile_fail>(&self, path: P)**: Registers a test case that is expected to fail compilation. ``` -------------------------------- ### Package Deserialization Logic Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Shows the deserialization implementation for the Package struct using serde. It defines fields like 'name', 'edition', and handles potential errors during the process. ```rust impl<'de> _serde::Deserialize<'de> for Package { fn deserialize<__D>(__deserializer: __D) -> _serde::__private228::Result where __D: _serde::Deserializer<'de> { #[allow(non_camel_case_types)] #[doc(hidden)] enum __Field { __field0, __field1, __field2, __ignore, } #[doc(hidden)] struct __FieldVisitor; #[automatically_derived] impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { type Value = __Field; fn expecting(&self, __formatter: &mut _serde::__private228::Formatter) -> _serde::__private228::fmt::Result { _serde::__private228::Formatter::write_str(__formatter, "field identifier") } fn visit_u64<__E>(self, __value: u64) -> _serde::__private228::Result where __E: _serde::de::Error { match __value { 0u64 => _serde::__private228::Ok(__Field::__field0), 1u64 => _serde::__private228::Ok(__Field::__field1), 2u64 => _serde::__private228::Ok(__Field::__field2), _ => _serde::__private228::Ok(__Field::__ignore), } } fn visit_str<__E>(self, __value: &str) -> _serde::__private228::Result where __E: _serde::de::Error { match __value { "name" => _serde::__private228::Ok(__Field::__field0), "edition" => _serde::__private228::Ok(__Field::__field1), ``` -------------------------------- ### Manifest Deserialization Logic Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Illustrates the deserialization process for the Manifest struct, including handling of various fields like 'cargo-features', 'package', 'features', 'dependencies', 'dev-dependencies', and 'target'. It uses a visitor pattern to parse the input. ```rust _serde::Deserializer::deserialize_struct(__deserializer, "Manifest", FIELDS, __Visitor { marker: _serde::__private228::PhantomData::, lifetime: _serde::__private228::PhantomData, }) } } }; #[doc(hidden)] const FIELDS: &'static [&'static str] = &["cargo-features", "package", "features", "dependencies", "dev-dependencies", "dev_dependencies", "target"]; _serde::Deserializer::deserialize_struct(__deserializer, "Manifest", FIELDS, __Visitor { marker: _serde::__private228::PhantomData::, lifetime: _serde::__private228::PhantomData, }) } ``` -------------------------------- ### Implement Visitor for f32 Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting f32 values within a visitor pattern, converting them to an `_serde::__private228::de::Content::F32` variant. ```rust fn visit_f32<__E>(self, __value: f32) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::F32(__value))) } ``` -------------------------------- ### Implement Visitor for char Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting char values within a visitor pattern, converting them to an `_serde::__private228::de::Content::Char` variant. ```rust fn visit_char<__E>(self, __value: char) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::Char(__value))) } ``` -------------------------------- ### Implement Visitor for u32 Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Handles visiting u32 values within a visitor pattern, converting them to an `_serde::__private228::de::Content::U32` variant. ```rust fn visit_u32<__E>(self, __value: u32) -> _serde::__private228::Result where __E: _serde::de::Error { _serde::__private228::Ok(__Field::__other(_serde::__private228::de::Content::U32(__value))) } ``` -------------------------------- ### Visitor for TargetDependencies Struct (SeqAccess) Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Implements the Visitor pattern for deserializing a sequence into the TargetDependencies struct. Handles missing fields by defaulting them. ```rust #[inline] fn visit_seq<__A>(self, mut __seq: __A) -> _serde::__private228::Result where __A: _serde::de::SeqAccess<'de> { let __field0 = match _serde::de::SeqAccess::next_element::>(&mut __seq)? { _serde::__private228::Some(__value) => __value, _serde::__private228::None => _serde::__private228::Default::default(), }; let __field1 = match _serde::de::SeqAccess::next_element::>(&mut __seq)? { _serde::__private228::Some(__value) => __value, _serde::__private228::None => _serde::__private228::Default::default(), }; _serde::__private228::Ok(TargetDependencies { dependencies: __field0, dev_dependencies: __field1, }) ``` -------------------------------- ### Default Implementation for WorkspacePackage Source: https://docs.rs/trybuild/latest/src/trybuild/dependencies.rs.html Provides a default value for the WorkspacePackage struct, initializing the edition field to its default. ```rust impl ::core::default::Default for WorkspacePackage { #[inline] fn default() -> WorkspacePackage { WorkspacePackage { edition: ::core::default::Default::default() } } } ```