Skip to content

Commit c2c636a

Browse files
authored
fix(toml): Remove workaround for rustc frontmatter support (#15570)
### What does this PR try to resolve? With rust-lang/rust#140035 now merged, we can rely on that rather than dirty hacks This is part of #12207 ### How should we test and review this PR? ### Additional information
2 parents 4b3f952 + f49d2fd commit c2c636a

File tree

7 files changed

+131
-172
lines changed

7 files changed

+131
-172
lines changed

src/cargo/core/compiler/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,15 @@ fn prepare_rustc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResult
735735
.compilation
736736
.rustc_process(unit, is_primary, is_workspace)?;
737737
build_base_args(build_runner, &mut base, unit)?;
738+
if unit.pkg.manifest().is_embedded() {
739+
if !gctx.cli_unstable().script {
740+
anyhow::bail!(
741+
"parsing `{}` requires `-Zscript`",
742+
unit.pkg.manifest_path().display()
743+
);
744+
}
745+
base.arg("-Z").arg("crate-attr=feature(frontmatter)");
746+
}
738747

739748
base.inherit_jobserver(&build_runner.jobserver);
740749
build_deps_args(&mut base, build_runner, unit)?;
@@ -774,6 +783,15 @@ fn prepare_rustdoc(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> CargoResu
774783
let bcx = build_runner.bcx;
775784
// script_metadata is not needed here, it is only for tests.
776785
let mut rustdoc = build_runner.compilation.rustdoc_process(unit, None)?;
786+
if unit.pkg.manifest().is_embedded() {
787+
if !bcx.gctx.cli_unstable().script {
788+
anyhow::bail!(
789+
"parsing `{}` requires `-Zscript`",
790+
unit.pkg.manifest_path().display()
791+
);
792+
}
793+
rustdoc.arg("-Z").arg("crate-attr=feature(frontmatter)");
794+
}
777795
rustdoc.inherit_jobserver(&build_runner.jobserver);
778796
let crate_name = unit.target.crate_name();
779797
rustdoc.arg("--crate-name").arg(&crate_name);

src/cargo/util/toml/embedded.rs

Lines changed: 6 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
1-
use anyhow::Context as _;
2-
31
use cargo_util_schemas::manifest::PackageName;
42

53
use crate::util::restricted_names;
64
use crate::CargoResult;
7-
use crate::GlobalContext;
85

9-
pub(super) fn expand_manifest(
10-
content: &str,
11-
path: &std::path::Path,
12-
gctx: &GlobalContext,
13-
) -> CargoResult<String> {
6+
pub(super) fn expand_manifest(content: &str) -> CargoResult<String> {
147
let source = ScriptSource::parse(content)?;
158
if let Some(frontmatter) = source.frontmatter() {
169
match source.info() {
@@ -24,74 +17,13 @@ pub(super) fn expand_manifest(
2417
}
2518
}
2619

27-
// HACK: until rustc has native support for this syntax, we have to remove it from the
28-
// source file
29-
use std::fmt::Write as _;
30-
let hash = crate::util::hex::short_hash(&path.to_string_lossy());
31-
let mut rel_path = std::path::PathBuf::new();
32-
rel_path.push("target");
33-
rel_path.push(&hash[0..2]);
34-
rel_path.push(&hash[2..]);
35-
let target_dir = gctx.home().join(rel_path);
36-
let hacked_path = target_dir
37-
.join(
38-
path.file_name()
39-
.expect("always a name for embedded manifests"),
40-
)
41-
.into_path_unlocked();
42-
let mut hacked_source = String::new();
43-
if let Some(shebang) = source.shebang() {
44-
writeln!(hacked_source, "{shebang}")?;
45-
}
46-
writeln!(hacked_source)?; // open
47-
for _ in 0..frontmatter.lines().count() {
48-
writeln!(hacked_source)?;
49-
}
50-
writeln!(hacked_source)?; // close
51-
writeln!(hacked_source, "{}", source.content())?;
52-
if let Some(parent) = hacked_path.parent() {
53-
cargo_util::paths::create_dir_all(parent)?;
54-
}
55-
cargo_util::paths::write_if_changed(&hacked_path, hacked_source)?;
56-
57-
let manifest = inject_bin_path(&frontmatter, &hacked_path)
58-
.with_context(|| format!("failed to parse manifest at `{}`", path.display()))?;
59-
let manifest = toml::to_string_pretty(&manifest)?;
60-
Ok(manifest)
20+
Ok(frontmatter.to_owned())
6121
} else {
6222
let frontmatter = "";
63-
let manifest = inject_bin_path(frontmatter, path)
64-
.with_context(|| format!("failed to parse manifest at `{}`", path.display()))?;
65-
let manifest = toml::to_string_pretty(&manifest)?;
66-
Ok(manifest)
23+
Ok(frontmatter.to_owned())
6724
}
6825
}
6926

70-
/// HACK: Add a `[[bin]]` table to the `original_toml`
71-
fn inject_bin_path(manifest: &str, path: &std::path::Path) -> CargoResult<toml::Table> {
72-
let mut manifest: toml::Table = toml::from_str(&manifest)?;
73-
74-
let bin_path = path.to_string_lossy().into_owned();
75-
let file_stem = path
76-
.file_stem()
77-
.ok_or_else(|| anyhow::format_err!("no file name"))?
78-
.to_string_lossy();
79-
let name = sanitize_name(file_stem.as_ref());
80-
let bin_name = name.clone();
81-
82-
let mut bin = toml::Table::new();
83-
bin.insert("name".to_owned(), toml::Value::String(bin_name));
84-
bin.insert("path".to_owned(), toml::Value::String(bin_path));
85-
manifest
86-
.entry("bin")
87-
.or_insert_with(|| Vec::<toml::Value>::new().into())
88-
.as_array_mut()
89-
.ok_or_else(|| anyhow::format_err!("`bin` must be an array"))?
90-
.push(toml::Value::Table(bin));
91-
92-
Ok(manifest)
93-
}
94-
9527
/// Ensure the package name matches the validation from `ops::cargo_new::check_name`
9628
pub fn sanitize_name(name: &str) -> String {
9729
let placeholder = if name.contains('_') {
@@ -584,25 +516,12 @@ fn main() {}
584516

585517
#[track_caller]
586518
fn expand(source: &str) -> String {
587-
let shell = crate::Shell::from_write(Box::new(Vec::new()));
588-
let cwd = std::env::current_dir().unwrap();
589-
let home = home::cargo_home_with_cwd(&cwd).unwrap();
590-
let gctx = GlobalContext::new(shell, cwd, home);
591-
expand_manifest(source, std::path::Path::new("/home/me/test.rs"), &gctx)
592-
.unwrap_or_else(|err| panic!("{}", err))
519+
expand_manifest(source).unwrap_or_else(|err| panic!("{}", err))
593520
}
594521

595522
#[test]
596523
fn expand_default() {
597-
assert_data_eq!(
598-
expand(r#"fn main() {}"#),
599-
str![[r#"
600-
[[bin]]
601-
name = "test-"
602-
path = "/home/me/test.rs"
603-
604-
"#]]
605-
);
524+
assert_data_eq!(expand(r#"fn main() {}"#), str![""]);
606525
}
607526

608527
#[test]
@@ -617,12 +536,8 @@ fn main() {}
617536
"#
618537
),
619538
str![[r#"
620-
[[bin]]
621-
name = "test-"
622-
path = [..]
623-
624539
[dependencies]
625-
time = "0.1.25"
540+
time="0.1.25"
626541
627542
"#]]
628543
);

src/cargo/util/toml/mod.rs

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ fn read_toml_string(path: &Path, is_embedded: bool, gctx: &GlobalContext) -> Car
160160
if !gctx.cli_unstable().script {
161161
anyhow::bail!("parsing `{}` requires `-Zscript`", path.display());
162162
}
163-
contents = embedded::expand_manifest(&contents, path, gctx)?;
163+
contents = embedded::expand_manifest(&contents)?;
164164
}
165165
Ok(contents)
166166
}
@@ -368,8 +368,37 @@ fn normalize_toml(
368368
original_package.autolib.or(auto_embedded),
369369
warnings,
370370
)?;
371+
let original_toml_bin = if is_embedded {
372+
let manifest_file_stem = manifest_file
373+
.file_stem()
374+
.expect("file name enforced previously");
375+
let name = embedded::sanitize_name(manifest_file_stem.to_string_lossy().as_ref());
376+
let manifest_file_name = manifest_file
377+
.file_name()
378+
.expect("file name enforced previously");
379+
let path = PathBuf::from(manifest_file_name);
380+
Cow::Owned(Some(vec![manifest::TomlBinTarget {
381+
name: Some(name),
382+
crate_type: None,
383+
crate_type2: None,
384+
path: Some(manifest::PathValue(path)),
385+
filename: None,
386+
test: None,
387+
doctest: None,
388+
bench: None,
389+
doc: None,
390+
doc_scrape_examples: None,
391+
proc_macro: None,
392+
proc_macro2: None,
393+
harness: None,
394+
required_features: None,
395+
edition: None,
396+
}]))
397+
} else {
398+
Cow::Borrowed(&original_toml.bin)
399+
};
371400
normalized_toml.bin = Some(targets::normalize_bins(
372-
original_toml.bin.as_ref(),
401+
original_toml_bin.as_ref().as_ref(),
373402
package_root,
374403
package_name,
375404
edition,
@@ -1345,10 +1374,7 @@ pub fn to_real_manifest(
13451374
let invalid_fields = [
13461375
("`workspace`", original_toml.workspace.is_some()),
13471376
("`lib`", original_toml.lib.is_some()),
1348-
(
1349-
"`bin`",
1350-
original_toml.bin.as_ref().map(|b| b.len()).unwrap_or(0) != 1,
1351-
),
1377+
("`bin`", original_toml.bin.is_some()),
13521378
("`example`", original_toml.example.is_some()),
13531379
("`test`", original_toml.test.is_some()),
13541380
("`bench`", original_toml.bench.is_some()),

tests/testsuite/fix.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2542,7 +2542,7 @@ edition = "2021"
25422542
);
25432543
}
25442544

2545-
#[cargo_test]
2545+
#[cargo_test(nightly, reason = "-Zscript is unstable")]
25462546
fn migrate_removes_project_for_script() {
25472547
let p = project()
25482548
.file(
@@ -2576,7 +2576,7 @@ fn main() {
25762576
[MIGRATING] foo.rs from 2021 edition to 2024
25772577
[FIXED] foo.rs (1 fix)
25782578
[CHECKING] foo v0.0.0 ([ROOT]/foo/foo.rs)
2579-
[MIGRATING] [ROOT]/home/.cargo/target/[HASH]/foo.rs from 2021 edition to 2024
2579+
[MIGRATING] foo.rs from 2021 edition to 2024
25802580
[FINISHED] `dev` profile [unoptimized + debuginfo] target(s) in [ELAPSED]s
25812581
25822582
"#]])

tests/testsuite/lockfile_path.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ fn install_lock_file_path_must_present() {
494494
.run();
495495
}
496496

497-
#[cargo_test]
497+
#[cargo_test(nightly, reason = "-Zscript is unstable")]
498498
fn run_embed() {
499499
let lockfile_path = "mylockfile/Cargo.lock";
500500
let invalid_lockfile = "Cargo.lock";

tests/testsuite/open_namespaces.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ fn explicit_bin_within_namespace() {
259259
.run();
260260
}
261261

262-
#[cargo_test]
262+
#[cargo_test(nightly, reason = "-Zscript is unstable")]
263263
#[cfg(unix)]
264264
fn namespaced_script_name() {
265265
let p = cargo_test_support::project()
@@ -314,7 +314,7 @@ fn main() {}
314314
"bin"
315315
],
316316
"name": "foo::bar",
317-
"src_path": "[ROOT]/home/.cargo/target/[HASH]/foo::bar.rs",
317+
"src_path": "[ROOT]/foo/foo::bar.rs",
318318
"test": true
319319
}
320320
],

0 commit comments

Comments
 (0)