Skip to content

Commit

Permalink
Lower MSRV to 1.57
Browse files Browse the repository at this point in the history
Makes progress on #554
  • Loading branch information
joshlf committed Feb 8, 2024
1 parent 2d2eb71 commit 0cc020e
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 41 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ authors = ["Joshua Liebow-Feeser <[email protected]>"]
description = "Utilities for zero-copy parsing and serialization"
license = "BSD-2-Clause OR Apache-2.0 OR MIT"
repository = "https://github.com/google/zerocopy"
rust-version = "1.58.0"
rust-version = "1.57.0"

exclude = [".*"]

Expand Down
54 changes: 52 additions & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,56 @@
// This file may not be copied, modified, or distributed except according to
// those terms.

// Sometimes we want to use lints which were added after our MSRV.
// `unknown_lints` is `warn` by default and we deny warnings in CI, so without
// this attribute, any unknown lint would cause a CI failure when testing with
// our MSRV.
#![allow(unknown_lints)]
#![deny(renamed_and_removed_lints)]
#![deny(
anonymous_parameters,
deprecated_in_future,
late_bound_lifetime_arguments,
missing_copy_implementations,
missing_debug_implementations,
path_statements,
patterns_in_fns_without_body,
rust_2018_idioms,
trivial_numeric_casts,
unreachable_pub,
unsafe_op_in_unsafe_fn,
unused_extern_crates,
unused_qualifications,
variant_size_differences
)]
#![deny(
clippy::all,
clippy::alloc_instead_of_core,
clippy::arithmetic_side_effects,
clippy::as_underscore,
clippy::assertions_on_result_states,
clippy::as_conversions,
clippy::correctness,
clippy::dbg_macro,
clippy::decimal_literal_representation,
clippy::get_unwrap,
clippy::indexing_slicing,
clippy::missing_inline_in_public_items,
clippy::missing_safety_doc,
clippy::obfuscated_if_else,
clippy::perf,
clippy::print_stdout,
clippy::std_instead_of_core,
clippy::style,
clippy::suspicious,
clippy::todo,
clippy::undocumented_unsafe_blocks,
clippy::unimplemented,
clippy::unnested_or_patterns,
clippy::unwrap_used,
clippy::use_debug
)]

use std::{env, fs, process::Command, str};

fn main() {
Expand Down Expand Up @@ -96,7 +146,7 @@ fn parse_version_cfgs_from_cargo_toml() -> Vec<VersionCfg> {
// comment (which can happen if it's inside a string) since we authored
// `Cargo.toml` and, in this section, we only put Rust version numbers
// in strings.
let before_comment = line.split("#").next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
let before_comment = line.split('#').next().expect(ITER_FIRST_NEXT_EXPECT_MSG);
let before_comment_without_whitespace = before_comment.trim_start();
if before_comment_without_whitespace.is_empty() {
return None;
Expand All @@ -121,7 +171,7 @@ fn parse_version_cfgs_from_cargo_toml() -> Vec<VersionCfg> {
assert_eq!(equals_sign, "=", "{}", EXPECT_MSG);

// Replace dashes with underscores.
let name = name.replace("-", "_");
let name = name.replace('-', "_");

// Strip the quotation marks.
let value = value.trim_start_matches('"').trim_end_matches('"');
Expand Down
11 changes: 6 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5886,7 +5886,7 @@ mod tests {

assert_matches::assert_matches!(
actual, $expect,
"layout({size_info:?}, {align}).validate_cast_and_convert_metadata({addr}, {bytes_len}, {cast_type:?})",
"layout({:?}, {}).validate_cast_and_convert_metadata({}, {}, {:?})" ,size_info, align, addr, bytes_len, cast_type
);
});
};
Expand Down Expand Up @@ -5981,7 +5981,8 @@ mod tests {
{
let (size_info, align) = (layout.size_info, layout.align);
let debug_str = format!(
"layout({size_info:?}, {align}).validate_cast_and_convert_metadata({addr}, {bytes_len}, {cast_type:?}) => ({elems}, {split_at})",
"layout({:?}, {}).validate_cast_and_convert_metadata({}, {}, {:?}) => ({}, {})",
size_info, align, addr, bytes_len, cast_type, elems, split_at
);

// If this is a sized type (no trailing slice), then `elems` is
Expand Down Expand Up @@ -6130,7 +6131,7 @@ mod tests {

// Avoid expensive allocation when running under Miri.
let assert_msg = if !cfg!(miri) {
format!("\n{args:?}\nsize:{size}, align:{align}")
format!("\n{:?}\nsize:{}, align:{}", args, size, align)
} else {
String::new()
};
Expand Down Expand Up @@ -6168,8 +6169,8 @@ mod tests {
// Avoid expensive allocation when running under Miri.
let assert_msg = if !cfg!(miri) {
format!(
"{}\nvalidate_cast_and_convert_metadata({addr}, {size})",
assert_msg
"{}\nvalidate_cast_and_convert_metadata({}, {})",
assert_msg, addr, size,
)
} else {
String::new()
Expand Down
7 changes: 6 additions & 1 deletion src/macro_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,12 @@ pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>(
// - The caller has guaranteed that alignment is not increased.
// - We know that the returned lifetime will not outlive the input lifetime
// thanks to the lifetime bounds on this function.
unsafe { &*dst }
//
// TODO(#67): Once our MSRV is 1.58, replace this `transmute` with `&*dst`.
#[allow(clippy::transmute_ptr_to_ref)]
unsafe {
core::mem::transmute(dst)
}
}

/// Transmutes a mutable reference of one type to a mutable reference of another
Expand Down
6 changes: 3 additions & 3 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ mod tests {
let align = NonZeroUsize::new(align).unwrap();
let want = alt_impl(n, align);
let got = round_down_to_next_multiple_of_alignment(n, align);
assert_eq!(got, want, "round_down_to_next_multiple_of_alignment({n}, {align})");
assert_eq!(got, want, "round_down_to_next_multiple_of_alignment({}, {})", n, align);
}
}
}
Expand All @@ -295,7 +295,7 @@ mod proofs {

let expected = model_impl(n, align);
let actual = round_down_to_next_multiple_of_alignment(n, align);
assert_eq!(expected, actual, "round_down_to_next_multiple_of_alignment({n}, {align})");
assert_eq!(expected, actual, "round_down_to_next_multiple_of_alignment({}, {})", n, align);
}

// Restricted to nightly since we use the unstable `usize::next_multiple_of`
Expand All @@ -319,7 +319,7 @@ mod proofs {

let expected = model_impl(len, align);
let actual = padding_needed_for(len, align);
assert_eq!(expected, actual, "padding_needed_for({len}, {align})");
assert_eq!(expected, actual, "padding_needed_for({}, {})", len, align);

let padded_len = actual + len;
assert_eq!(padded_len % align, 0);
Expand Down
4 changes: 2 additions & 2 deletions tests/trybuild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn ui() {
let source_files_dirname = version.get_ui_source_files_dirname_and_maybe_print_warning();

let t = trybuild::TestCases::new();
t.compile_fail(format!("tests/{source_files_dirname}/*.rs"));
t.compile_fail(format!("tests/{}/*.rs", source_files_dirname));
}

// The file `invalid-impls.rs` directly includes `src/macros.rs` in order to
Expand All @@ -37,5 +37,5 @@ fn ui_invalid_impls() {
let source_files_dirname = version.get_ui_source_files_dirname_and_maybe_print_warning();

let t = trybuild::TestCases::new();
t.compile_fail(format!("tests/{source_files_dirname}/invalid-impls/*.rs"));
t.compile_fail(format!("tests/{}/invalid-impls/*.rs", source_files_dirname));
}
1 change: 1 addition & 0 deletions testutil/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ rustc_version = "0.4.0"
# Pin to 0.3.0 because more recent versions require a Rust version more recent
# than our MSRV.
time = { version = "=0.3.0", default-features = false, features = ["formatting", "macros", "parsing"] }
toml = "0.5.11"
56 changes: 30 additions & 26 deletions testutil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
// This file may not be copied, modified, or distributed except according to
// those terms.

use cargo_metadata::MetadataCommand;
use rustc_version::{Channel, Version};
use std::error::Error;
use std::{env, error::Error, fs};

struct PinnedVersions {
msrv: String,
Expand All @@ -24,29 +23,33 @@ impl PinnedVersions {
/// child of a Cargo workspace. It extracts the pinned versions from the
/// metadata of the root package.
fn extract_from_pwd() -> Result<PinnedVersions, Box<dyn Error>> {
let meta = MetadataCommand::new().exec()?;
// NOTE(joshlf): In theory `meta.root_package()` should work instead of
// this manual search, but for some reason it breaks when called from
// zerocopy-derive's tests. This works as a workaround, and it's just
// test code, so I didn't bother investigating.
let pkg = meta
.workspace_packages()
.into_iter()
.find(|pkg| pkg.name == "zerocopy")
.ok_or("no `zerocopy` package found; are we in a workspace?")?;
let msrv = pkg
.rust_version
.as_ref()
.ok_or("failed to find msrv: no `rust-version` key present")?
.to_string();
let extract = |version_name, key| -> Result<String, String> {
let value = pkg.metadata.pointer(&format!("/ci/{key}")).ok_or_else(|| {
format!("failed to find {version_name}: no `metadata.ci.{key}` key present")
})?;
value.as_str().map(str::to_string).ok_or_else(|| format!("failed to find {version_name}: key `metadata.ci.{key}` (contents: {value:?}) failed to parse as JSON string"))
let manifest_dir = env::var_os("CARGO_MANIFEST_DIR")
.ok_or("CARGO_MANIFEST_DIR environment variable not set")?;
let manifest = fs::read_to_string(
manifest_dir
.into_string()
.map_err(|_| "could not parse $CARGO_MANIFEST_DIR as UTF-8")?
+ "/Cargo.toml",
)?;
let manifest: toml::map::Map<String, toml::Value> = toml::from_str(&manifest)?;
let manifest = toml::Value::Table(manifest);

let extract = |keys: &[&str]| -> Result<String, String> {
let mut val = &manifest;
for k in keys {
val = val
.get(k)
.ok_or(format!("failed to look up path in Cargo.toml: {:?}", keys))?;
}

val.as_str()
.map(|s| s.to_string())
.ok_or(format!("expected string value for path in Cargo.toml: {:?}", keys))
};
let stable = extract("stable", "pinned-stable")?;
let nightly = extract("nightly", "pinned-nightly")?;

let msrv = extract(&["package", "rust-version"])?;
let stable = extract(&["package", "metadata", "ci", "pinned-stable"])?;
let nightly = extract(&["package", "metadata", "ci", "pinned-nightly"])?;
Ok(PinnedVersions { msrv, stable, nightly })
}
}
Expand Down Expand Up @@ -85,7 +88,7 @@ impl ToolchainVersion {
}
Channel::Stable => {
let Version { major, minor, patch, .. } = current.semver;
format!("{major}.{minor}.{patch}")
format!("{}.{}.{}", major, minor, patch)
}
};

Expand Down Expand Up @@ -116,7 +119,8 @@ impl ToolchainVersion {
_ if current.channel == Channel::Nightly => ToolchainVersion::OtherNightly,
_ => {
return Err(format!(
"current toolchain ({current:?}) doesn't match any known version"
"current toolchain ({:?}) doesn't match any known version",
current
)
.into())
}
Expand Down
2 changes: 1 addition & 1 deletion zerocopy-derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ authors = ["Joshua Liebow-Feeser <[email protected]>"]
description = "Custom derive for traits from the zerocopy crate"
license = "BSD-2-Clause OR Apache-2.0 OR MIT"
repository = "https://github.com/google/zerocopy"
rust-version = "1.58.0"
rust-version = "1.57.0"

# We prefer to include tests when publishing to crates.io so that Crater [1] can
# detect regressions in our test suite. These two tests are excessively large,
Expand Down

0 comments on commit 0cc020e

Please sign in to comment.