1use cargo_util_terminal::report::{AnnotationKind, Group, Level, Snippet};
2use std::borrow::Cow;
3use std::cell::OnceCell;
4use std::collections::{BTreeMap, BTreeSet, HashMap};
5use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7use std::rc::Rc;
8use std::str::{self, FromStr};
9
10use crate::AlreadyPrintedError;
11use crate::core::summary::MissingDependencyError;
12use anyhow::{Context as _, anyhow, bail};
13use cargo_platform::Platform;
14use cargo_util::paths;
15use cargo_util_schemas::manifest::{
16 self, PackageName, PathBaseName, TomlDependency, TomlDetailedDependency, TomlManifest,
17 TomlPackageBuild, TomlWorkspace,
18};
19use cargo_util_schemas::manifest::{RustVersion, StringOrBool};
20use itertools::Itertools;
21use pathdiff::diff_paths;
22use url::Url;
23
24use crate::core::compiler::{CompileKind, CompileTarget};
25use crate::core::dependency::{Artifact, ArtifactTarget, DepKind};
26use crate::core::manifest::{ManifestMetadata, TargetSourcePath};
27use crate::core::resolver::ResolveBehavior;
28use crate::core::{
29 CliUnstable, FeatureValue, Patch, PatchLocation, find_workspace_root, resolve_relative_path,
30};
31use crate::core::{Dependency, Manifest, Package, PackageId, Summary, Target};
32use crate::core::{Edition, EitherManifest, Feature, Features, VirtualManifest, Workspace};
33use crate::core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, WorkspaceRootConfig};
34use crate::lints::get_key_value_span;
35use crate::lints::rel_cwd_manifest_path;
36use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
37use crate::util::errors::{CargoResult, ManifestError};
38use crate::util::interning::InternedString;
39use crate::util::{
40 self, GlobalContext, IntoUrl, OnceExt, OptVersionReq, context::ConfigRelativePath,
41 context::TOP_LEVEL_CONFIG_KEYS,
42};
43
44mod embedded;
45mod targets;
46
47use self::targets::to_targets;
48
49pub fn is_embedded(path: &Path) -> bool {
51 let ext = path.extension();
52 ext == Some(OsStr::new("rs")) || ext.is_none()
53}
54
55#[tracing::instrument(skip(gctx))]
64pub fn read_manifest(
65 path: &Path,
66 source_id: SourceId,
67 gctx: &GlobalContext,
68) -> CargoResult<EitherManifest> {
69 let mut warnings = Default::default();
70 let mut errors = Default::default();
71
72 let is_embedded = is_embedded(path);
73 let contents = read_toml_string(path, is_embedded, gctx)?;
74 let document = parse_document(&contents)
75 .map_err(|e| emit_toml_diagnostic(e.into(), &contents, path, gctx))?;
76 let original_toml = deserialize_toml(&document)
77 .map_err(|e| emit_toml_diagnostic(e.into(), &contents, path, gctx))?;
78
79 let mut manifest = (|| {
80 let empty = Vec::new();
81 let cargo_features = original_toml.cargo_features.as_ref().unwrap_or(&empty);
82 let features = Features::new(cargo_features, gctx, &mut warnings, source_id.is_path())?;
83 let workspace_config =
84 to_workspace_config(&original_toml, path, is_embedded, gctx, &mut warnings)?;
85 if let WorkspaceConfig::Root(ws_root_config) = &workspace_config {
86 let package_root = path.parent().unwrap();
87 gctx.ws_roots()
88 .insert(package_root.to_owned(), ws_root_config.clone());
89 }
90 let normalized_toml = normalize_toml(
91 &original_toml,
92 &features,
93 &workspace_config,
94 path,
95 is_embedded,
96 gctx,
97 &mut warnings,
98 &mut errors,
99 )?;
100
101 if normalized_toml.package().is_some() {
102 to_real_manifest(
103 Some(contents),
104 Some(document),
105 original_toml,
106 normalized_toml,
107 features,
108 workspace_config,
109 source_id,
110 path,
111 is_embedded,
112 gctx,
113 &mut warnings,
114 &mut errors,
115 )
116 .map(EitherManifest::Real)
117 } else if normalized_toml.workspace.is_some() {
118 assert!(!is_embedded);
119 to_virtual_manifest(
120 Some(contents),
121 Some(document),
122 original_toml,
123 normalized_toml,
124 features,
125 workspace_config,
126 source_id,
127 path,
128 gctx,
129 &mut warnings,
130 &mut errors,
131 )
132 .map(EitherManifest::Virtual)
133 } else {
134 anyhow::bail!("manifest is missing either a `[package]` or a `[workspace]`")
135 }
136 })()
137 .map_err(|err| {
138 ManifestError::new(
139 err.context(format!("failed to parse manifest at `{}`", path.display())),
140 path.into(),
141 )
142 })?;
143
144 for warning in warnings {
145 manifest.warnings_mut().add_warning(warning);
146 }
147 for error in errors {
148 manifest.warnings_mut().add_critical_warning(error);
149 }
150
151 Ok(manifest)
152}
153
154#[tracing::instrument(skip_all)]
155fn read_toml_string(path: &Path, is_embedded: bool, gctx: &GlobalContext) -> CargoResult<String> {
156 let mut contents = paths::read(path).map_err(|err| ManifestError::new(err, path.into()))?;
157 if is_embedded {
158 if !gctx.cli_unstable().script {
159 anyhow::bail!("parsing `{}` requires `-Zscript`", path.display());
160 }
161 contents = embedded::expand_manifest(&contents)
162 .map_err(|e| emit_frontmatter_diagnostic(e, &contents, path, gctx))?;
163 }
164 Ok(contents)
165}
166
167#[tracing::instrument(skip_all)]
168fn parse_document(
169 contents: &str,
170) -> Result<toml::Spanned<toml::de::DeTable<'static>>, toml::de::Error> {
171 let mut table = toml::de::DeTable::parse(contents)?;
172 table.get_mut().make_owned();
173 let table = unsafe {
176 std::mem::transmute::<
177 toml::Spanned<toml::de::DeTable<'_>>,
178 toml::Spanned<toml::de::DeTable<'static>>,
179 >(table)
180 };
181 Ok(table)
182}
183
184#[tracing::instrument(skip_all)]
185fn deserialize_toml(
186 document: &toml::Spanned<toml::de::DeTable<'static>>,
187) -> Result<manifest::TomlManifest, toml::de::Error> {
188 let mut unused = BTreeSet::new();
189 let deserializer = toml::de::Deserializer::from(document.clone());
190 let mut document: manifest::TomlManifest = serde_ignored::deserialize(deserializer, |path| {
191 let mut key = String::new();
192 stringify(&mut key, &path);
193 unused.insert(key);
194 })?;
195 document._unused_keys = unused;
196 Ok(document)
197}
198
199fn stringify(dst: &mut String, path: &serde_ignored::Path<'_>) {
200 use serde_ignored::Path;
201
202 match *path {
203 Path::Root => {}
204 Path::Seq { parent, index } => {
205 stringify(dst, parent);
206 if !dst.is_empty() {
207 dst.push('.');
208 }
209 dst.push_str(&index.to_string());
210 }
211 Path::Map { parent, ref key } => {
212 stringify(dst, parent);
213 if !dst.is_empty() {
214 dst.push('.');
215 }
216 dst.push_str(key);
217 }
218 Path::Some { parent }
219 | Path::NewtypeVariant { parent }
220 | Path::NewtypeStruct { parent } => stringify(dst, parent),
221 }
222}
223
224fn to_workspace_config(
225 original_toml: &manifest::TomlManifest,
226 manifest_file: &Path,
227 is_embedded: bool,
228 gctx: &GlobalContext,
229 warnings: &mut Vec<String>,
230) -> CargoResult<WorkspaceConfig> {
231 if is_embedded {
232 let ws_root_config = to_workspace_root_config(&TomlWorkspace::default(), manifest_file);
233 return Ok(WorkspaceConfig::Root(ws_root_config));
234 }
235 let workspace_config = match (
236 original_toml.workspace.as_ref(),
237 original_toml.package().and_then(|p| p.workspace.as_ref()),
238 ) {
239 (Some(toml_config), None) => {
240 verify_lints(toml_config.lints.as_ref(), gctx, warnings)?;
241 if let Some(ws_deps) = &toml_config.dependencies {
242 for (name, dep) in ws_deps {
243 if dep.is_optional() {
244 bail!("{name} is optional, but workspace dependencies cannot be optional",);
245 }
246 if dep.is_public() {
247 bail!("{name} is public, but workspace dependencies cannot be public",);
248 }
249 }
250
251 for (name, dep) in ws_deps {
252 unused_dep_keys(name, "workspace.dependencies", dep.unused_keys(), warnings);
253 }
254 }
255 let ws_root_config = to_workspace_root_config(toml_config, manifest_file);
256 WorkspaceConfig::Root(ws_root_config)
257 }
258 (None, root) => WorkspaceConfig::Member {
259 root: root.cloned(),
260 },
261 (Some(..), Some(..)) => bail!(
262 "cannot configure both `package.workspace` and \
263 `[workspace]`, only one can be specified"
264 ),
265 };
266 Ok(workspace_config)
267}
268
269fn to_workspace_root_config(
270 normalized_toml: &manifest::TomlWorkspace,
271 manifest_file: &Path,
272) -> WorkspaceRootConfig {
273 let package_root = manifest_file.parent().unwrap();
274 let inheritable = InheritableFields {
275 package: normalized_toml.package.clone(),
276 dependencies: normalized_toml.dependencies.clone(),
277 lints: normalized_toml.lints.clone(),
278 _ws_root: package_root.to_owned(),
279 };
280 let ws_root_config = WorkspaceRootConfig::new(
281 package_root,
282 &normalized_toml.members,
283 &normalized_toml.default_members,
284 &normalized_toml.exclude,
285 &Some(inheritable),
286 &normalized_toml.metadata,
287 );
288 ws_root_config
289}
290
291#[tracing::instrument(skip_all)]
293fn normalize_toml(
294 original_toml: &manifest::TomlManifest,
295 features: &Features,
296 workspace_config: &WorkspaceConfig,
297 manifest_file: &Path,
298 is_embedded: bool,
299 gctx: &GlobalContext,
300 warnings: &mut Vec<String>,
301 errors: &mut Vec<String>,
302) -> CargoResult<manifest::TomlManifest> {
303 let package_root = manifest_file.parent().unwrap();
304
305 let inherit_cell: OnceCell<InheritableFields> = OnceCell::new();
306 let inherit = || {
307 inherit_cell
308 .try_borrow_with(|| load_inheritable_fields(gctx, manifest_file, &workspace_config))
309 };
310 let workspace_root = || inherit().map(|fields| fields.ws_root().as_path());
311
312 let mut normalized_toml = manifest::TomlManifest {
313 cargo_features: original_toml.cargo_features.clone(),
314 package: None,
315 project: None,
316 badges: None,
317 features: None,
318 lib: None,
319 bin: None,
320 example: None,
321 test: None,
322 bench: None,
323 dependencies: None,
324 dev_dependencies: None,
325 dev_dependencies2: None,
326 build_dependencies: None,
327 build_dependencies2: None,
328 target: None,
329 lints: None,
330 hints: None,
331 workspace: original_toml.workspace.clone().or_else(|| {
332 is_embedded.then(manifest::TomlWorkspace::default)
334 }),
335 profile: original_toml.profile.clone(),
336 patch: normalize_patch(
337 gctx,
338 original_toml.patch.as_ref(),
339 &workspace_root,
340 features,
341 )?,
342 replace: original_toml.replace.clone(),
343 _unused_keys: Default::default(),
344 };
345
346 if let Some(original_package) = original_toml.package().map(Cow::Borrowed).or_else(|| {
347 if is_embedded {
348 Some(Cow::Owned(Box::new(manifest::TomlPackage::default())))
349 } else {
350 None
351 }
352 }) {
353 let normalized_package = normalize_package_toml(
354 &original_package,
355 manifest_file,
356 is_embedded,
357 gctx,
358 &inherit,
359 features,
360 )?;
361 let package_name = &normalized_package
362 .normalized_name()
363 .expect("previously normalized")
364 .clone();
365 let edition = normalized_package
366 .normalized_edition()
367 .expect("previously normalized")
368 .map_or(Edition::default(), |e| {
369 Edition::from_str(&e).unwrap_or_default()
370 });
371 normalized_toml.package = Some(normalized_package);
372
373 normalized_toml.features = normalize_features(original_toml.features.as_ref())?;
374
375 let auto_embedded = is_embedded.then_some(false);
376 normalized_toml.lib = targets::normalize_lib(
377 original_toml.lib.as_ref(),
378 package_root,
379 package_name,
380 edition,
381 original_package.autolib.or(auto_embedded),
382 warnings,
383 )?;
384 let original_toml_bin = if is_embedded {
385 let name = package_name.as_ref().to_owned();
386 let manifest_file_name = manifest_file
387 .file_name()
388 .expect("file name enforced previously");
389 let path = PathBuf::from(manifest_file_name);
390 Cow::Owned(Some(vec![manifest::TomlBinTarget {
391 name: Some(name),
392 crate_type: None,
393 crate_type2: None,
394 path: Some(manifest::PathValue(path)),
395 filename: None,
396 test: None,
397 doctest: None,
398 bench: None,
399 doc: None,
400 doc_scrape_examples: None,
401 proc_macro: None,
402 proc_macro2: None,
403 harness: None,
404 required_features: None,
405 edition: None,
406 }]))
407 } else {
408 Cow::Borrowed(&original_toml.bin)
409 };
410 normalized_toml.bin = Some(targets::normalize_bins(
411 original_toml_bin.as_ref().as_ref(),
412 package_root,
413 package_name,
414 edition,
415 original_package.autobins.or(auto_embedded),
416 warnings,
417 errors,
418 normalized_toml.lib.is_some(),
419 )?);
420 normalized_toml.example = Some(targets::normalize_examples(
421 original_toml.example.as_ref(),
422 package_root,
423 edition,
424 original_package.autoexamples.or(auto_embedded),
425 warnings,
426 errors,
427 )?);
428 normalized_toml.test = Some(targets::normalize_tests(
429 original_toml.test.as_ref(),
430 package_root,
431 edition,
432 original_package.autotests.or(auto_embedded),
433 warnings,
434 errors,
435 )?);
436 normalized_toml.bench = Some(targets::normalize_benches(
437 original_toml.bench.as_ref(),
438 package_root,
439 edition,
440 original_package.autobenches.or(auto_embedded),
441 warnings,
442 errors,
443 )?);
444
445 normalized_toml.dependencies = normalize_dependencies(
446 gctx,
447 edition,
448 &features,
449 original_toml.dependencies.as_ref(),
450 DepKind::Normal,
451 &inherit,
452 &workspace_root,
453 package_root,
454 warnings,
455 )?;
456 deprecated_underscore(
457 &original_toml.dev_dependencies2,
458 &original_toml.dev_dependencies,
459 "dev-dependencies",
460 package_name,
461 "package",
462 edition,
463 warnings,
464 )?;
465 normalized_toml.dev_dependencies = normalize_dependencies(
466 gctx,
467 edition,
468 &features,
469 original_toml.dev_dependencies(),
470 DepKind::Development,
471 &inherit,
472 &workspace_root,
473 package_root,
474 warnings,
475 )?;
476 deprecated_underscore(
477 &original_toml.build_dependencies2,
478 &original_toml.build_dependencies,
479 "build-dependencies",
480 package_name,
481 "package",
482 edition,
483 warnings,
484 )?;
485 normalized_toml.build_dependencies = normalize_dependencies(
486 gctx,
487 edition,
488 &features,
489 original_toml.build_dependencies(),
490 DepKind::Build,
491 &inherit,
492 &workspace_root,
493 package_root,
494 warnings,
495 )?;
496 let mut normalized_target = BTreeMap::new();
497 for (name, platform) in original_toml.target.iter().flatten() {
498 let normalized_dependencies = normalize_dependencies(
499 gctx,
500 edition,
501 &features,
502 platform.dependencies.as_ref(),
503 DepKind::Normal,
504 &inherit,
505 &workspace_root,
506 package_root,
507 warnings,
508 )?;
509 deprecated_underscore(
510 &platform.dev_dependencies2,
511 &platform.dev_dependencies,
512 "dev-dependencies",
513 name,
514 "platform target",
515 edition,
516 warnings,
517 )?;
518 let normalized_dev_dependencies = normalize_dependencies(
519 gctx,
520 edition,
521 &features,
522 platform.dev_dependencies(),
523 DepKind::Development,
524 &inherit,
525 &workspace_root,
526 package_root,
527 warnings,
528 )?;
529 deprecated_underscore(
530 &platform.build_dependencies2,
531 &platform.build_dependencies,
532 "build-dependencies",
533 name,
534 "platform target",
535 edition,
536 warnings,
537 )?;
538 let normalized_build_dependencies = normalize_dependencies(
539 gctx,
540 edition,
541 &features,
542 platform.build_dependencies(),
543 DepKind::Build,
544 &inherit,
545 &workspace_root,
546 package_root,
547 warnings,
548 )?;
549 normalized_target.insert(
550 name.clone(),
551 manifest::TomlPlatform {
552 dependencies: normalized_dependencies,
553 build_dependencies: normalized_build_dependencies,
554 build_dependencies2: None,
555 dev_dependencies: normalized_dev_dependencies,
556 dev_dependencies2: None,
557 },
558 );
559 }
560 normalized_toml.target = (!normalized_target.is_empty()).then_some(normalized_target);
561
562 let normalized_lints = original_toml
563 .lints
564 .clone()
565 .map(|value| lints_inherit_with(value, || inherit()?.lints()))
566 .transpose()?;
567 normalized_toml.lints = normalized_lints.map(|lints| manifest::InheritableLints {
568 workspace: false,
569 lints,
570 });
571
572 normalized_toml.hints = original_toml.hints.clone();
573
574 normalized_toml.badges = original_toml.badges.clone();
575 } else {
576 if let Some(field) = original_toml.requires_package().next() {
577 bail!("this virtual manifest specifies a `{field}` section, which is not allowed");
578 }
579 }
580
581 Ok(normalized_toml)
582}
583
584fn normalize_patch<'a>(
585 gctx: &GlobalContext,
586 original_patch: Option<&BTreeMap<String, BTreeMap<PackageName, TomlDependency>>>,
587 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
588 features: &Features,
589) -> CargoResult<Option<BTreeMap<String, BTreeMap<PackageName, TomlDependency>>>> {
590 if let Some(patch) = original_patch {
591 let mut normalized_patch = BTreeMap::new();
592 for (name, packages) in patch {
593 let mut normalized_packages = BTreeMap::new();
594 for (pkg, dep) in packages {
595 let dep = if let TomlDependency::Detailed(dep) = dep {
596 let mut dep = dep.clone();
597 normalize_path_dependency(gctx, &mut dep, workspace_root, features)
598 .with_context(|| {
599 format!("resolving path for patch of ({pkg}) for source ({name})")
600 })?;
601 TomlDependency::Detailed(dep)
602 } else {
603 dep.clone()
604 };
605 normalized_packages.insert(pkg.clone(), dep);
606 }
607 normalized_patch.insert(name.clone(), normalized_packages);
608 }
609 Ok(Some(normalized_patch))
610 } else {
611 Ok(None)
612 }
613}
614
615#[tracing::instrument(skip_all)]
616fn normalize_package_toml<'a>(
617 original_package: &manifest::TomlPackage,
618 manifest_file: &Path,
619 is_embedded: bool,
620 gctx: &GlobalContext,
621 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
622 features: &Features,
623) -> CargoResult<Box<manifest::TomlPackage>> {
624 let package_root = manifest_file.parent().unwrap();
625
626 let edition = original_package
627 .edition
628 .clone()
629 .map(|value| field_inherit_with(value, "edition", || inherit()?.edition()))
630 .transpose()?
631 .map(manifest::InheritableField::Value)
632 .or_else(|| {
633 if is_embedded {
634 const DEFAULT_EDITION: crate::core::features::Edition =
635 crate::core::features::Edition::LATEST_STABLE;
636 let report = [Group::with_title(Level::WARNING.secondary_title(format!(
637 "`package.edition` is unspecified, defaulting to the latest edition (currently `{DEFAULT_EDITION}`)"
638 )))];
639 let _ = gctx.shell().print_report(&report, true);
640 Some(manifest::InheritableField::Value(
641 DEFAULT_EDITION.to_string(),
642 ))
643 } else {
644 None
645 }
646 });
647 let rust_version = original_package
648 .rust_version
649 .clone()
650 .map(|value| field_inherit_with(value, "rust-version", || inherit()?.rust_version()))
651 .transpose()?
652 .map(manifest::InheritableField::Value);
653 let name = Some(
654 original_package
655 .name
656 .clone()
657 .or_else(|| {
658 if is_embedded {
659 let file_stem = manifest_file
660 .file_stem()
661 .expect("file name enforced previously")
662 .to_string_lossy();
663 let name = embedded::sanitize_name(file_stem.as_ref());
664 let name =
665 manifest::PackageName::new(name).expect("sanitize made the name valid");
666 Some(name)
667 } else {
668 None
669 }
670 })
671 .ok_or_else(|| anyhow::format_err!("missing field `package.name`"))?,
672 );
673 let version = original_package
674 .version
675 .clone()
676 .map(|value| field_inherit_with(value, "version", || inherit()?.version()))
677 .transpose()?
678 .map(manifest::InheritableField::Value);
679 let authors = original_package
680 .authors
681 .clone()
682 .map(|value| field_inherit_with(value, "authors", || inherit()?.authors()))
683 .transpose()?
684 .map(manifest::InheritableField::Value);
685 let build = if is_embedded {
686 Some(TomlPackageBuild::Auto(false))
687 } else {
688 if let Some(TomlPackageBuild::MultipleScript(_)) = original_package.build {
689 features.require(Feature::multiple_build_scripts())?;
690 }
691 targets::normalize_build(original_package.build.as_ref(), package_root)?
692 };
693 let metabuild = original_package.metabuild.clone();
694 let default_target = original_package.default_target.clone();
695 let forced_target = original_package.forced_target.clone();
696 let links = original_package.links.clone();
697 let exclude = original_package
698 .exclude
699 .clone()
700 .map(|value| field_inherit_with(value, "exclude", || inherit()?.exclude()))
701 .transpose()?
702 .map(manifest::InheritableField::Value);
703 let include = original_package
704 .include
705 .clone()
706 .map(|value| field_inherit_with(value, "include", || inherit()?.include()))
707 .transpose()?
708 .map(manifest::InheritableField::Value);
709 let publish = original_package
710 .publish
711 .clone()
712 .map(|value| field_inherit_with(value, "publish", || inherit()?.publish()))
713 .transpose()?
714 .map(manifest::InheritableField::Value);
715 let workspace = original_package.workspace.clone();
716 let im_a_teapot = original_package.im_a_teapot.clone();
717 let autolib = Some(false);
718 let autobins = Some(false);
719 let autoexamples = Some(false);
720 let autotests = Some(false);
721 let autobenches = Some(false);
722 let default_run = original_package.default_run.clone();
723 let description = original_package
724 .description
725 .clone()
726 .map(|value| field_inherit_with(value, "description", || inherit()?.description()))
727 .transpose()?
728 .map(manifest::InheritableField::Value);
729 let homepage = original_package
730 .homepage
731 .clone()
732 .map(|value| field_inherit_with(value, "homepage", || inherit()?.homepage()))
733 .transpose()?
734 .map(manifest::InheritableField::Value);
735 let documentation = original_package
736 .documentation
737 .clone()
738 .map(|value| field_inherit_with(value, "documentation", || inherit()?.documentation()))
739 .transpose()?
740 .map(manifest::InheritableField::Value);
741 let readme = normalize_package_readme(
742 package_root,
743 original_package
744 .readme
745 .clone()
746 .map(|value| field_inherit_with(value, "readme", || inherit()?.readme(package_root)))
747 .transpose()?
748 .as_ref(),
749 )
750 .map(|s| manifest::InheritableField::Value(StringOrBool::String(s)))
751 .or(Some(manifest::InheritableField::Value(StringOrBool::Bool(
752 false,
753 ))));
754 let keywords = original_package
755 .keywords
756 .clone()
757 .map(|value| field_inherit_with(value, "keywords", || inherit()?.keywords()))
758 .transpose()?
759 .map(manifest::InheritableField::Value);
760 let categories = original_package
761 .categories
762 .clone()
763 .map(|value| field_inherit_with(value, "categories", || inherit()?.categories()))
764 .transpose()?
765 .map(manifest::InheritableField::Value);
766 let license = original_package
767 .license
768 .clone()
769 .map(|value| field_inherit_with(value, "license", || inherit()?.license()))
770 .transpose()?
771 .map(manifest::InheritableField::Value);
772 let license_file = original_package
773 .license_file
774 .clone()
775 .map(|value| {
776 field_inherit_with(value, "license-file", || {
777 inherit()?.license_file(package_root)
778 })
779 })
780 .transpose()?
781 .map(manifest::InheritableField::Value);
782 let repository = original_package
783 .repository
784 .clone()
785 .map(|value| field_inherit_with(value, "repository", || inherit()?.repository()))
786 .transpose()?
787 .map(manifest::InheritableField::Value);
788 let resolver = original_package.resolver.clone();
789 let metadata = original_package.metadata.clone();
790
791 let normalized_package = manifest::TomlPackage {
792 edition,
793 rust_version,
794 name,
795 version,
796 authors,
797 build,
798 metabuild,
799 default_target,
800 forced_target,
801 links,
802 exclude,
803 include,
804 publish,
805 workspace,
806 im_a_teapot,
807 autolib,
808 autobins,
809 autoexamples,
810 autotests,
811 autobenches,
812 default_run,
813 description,
814 homepage,
815 documentation,
816 readme,
817 keywords,
818 categories,
819 license,
820 license_file,
821 repository,
822 resolver,
823 metadata,
824 _invalid_cargo_features: Default::default(),
825 };
826
827 Ok(Box::new(normalized_package))
828}
829
830fn normalize_package_readme(
832 package_root: &Path,
833 readme: Option<&manifest::StringOrBool>,
834) -> Option<String> {
835 match &readme {
836 None => default_readme_from_package_root(package_root),
837 Some(value) => match value {
838 manifest::StringOrBool::Bool(false) => None,
839 manifest::StringOrBool::Bool(true) => Some("README.md".to_string()),
840 manifest::StringOrBool::String(v) => Some(v.clone()),
841 },
842 }
843}
844
845pub const DEFAULT_README_FILES: [&str; 3] = ["README.md", "README.txt", "README"];
846
847fn default_readme_from_package_root(package_root: &Path) -> Option<String> {
850 for &readme_filename in DEFAULT_README_FILES.iter() {
851 if package_root.join(readme_filename).is_file() {
852 return Some(readme_filename.to_string());
853 }
854 }
855
856 None
857}
858
859#[tracing::instrument(skip_all)]
860fn normalize_features(
861 original_features: Option<&BTreeMap<manifest::FeatureName, Vec<String>>>,
862) -> CargoResult<Option<BTreeMap<manifest::FeatureName, Vec<String>>>> {
863 let Some(normalized_features) = original_features.cloned() else {
864 return Ok(None);
865 };
866
867 Ok(Some(normalized_features))
868}
869
870#[tracing::instrument(skip_all)]
871fn normalize_dependencies<'a>(
872 gctx: &GlobalContext,
873 edition: Edition,
874 features: &Features,
875 orig_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
876 kind: DepKind,
877 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
878 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
879 package_root: &Path,
880 warnings: &mut Vec<String>,
881) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
882 let Some(dependencies) = orig_deps else {
883 return Ok(None);
884 };
885
886 let mut deps = BTreeMap::new();
887 for (name_in_toml, v) in dependencies.iter() {
888 let mut resolved = dependency_inherit_with(
889 v.clone(),
890 name_in_toml,
891 inherit,
892 package_root,
893 edition,
894 warnings,
895 )?;
896 if let manifest::TomlDependency::Detailed(ref mut d) = resolved {
897 deprecated_underscore(
898 &d.default_features2,
899 &d.default_features,
900 "default-features",
901 name_in_toml,
902 "dependency",
903 edition,
904 warnings,
905 )?;
906 if d.public.is_some() {
907 let with_public_feature = features.require(Feature::public_dependency()).is_ok();
908 let with_z_public = gctx.cli_unstable().public_dependency;
909 match kind {
910 DepKind::Normal => {
911 if !with_public_feature && !with_z_public {
912 d.public = None;
913 warnings.push(format!(
914 "ignoring `public` on dependency {name_in_toml}, pass `-Zpublic-dependency` to enable support for it"
915 ));
916 }
917 }
918 DepKind::Development | DepKind::Build => {
919 let kind_name = kind.kind_table();
920 let hint = format!(
921 "'public' specifier can only be used on regular dependencies, not {kind_name}",
922 );
923 if with_public_feature || with_z_public {
924 bail!(hint)
925 } else {
926 warnings.push(hint);
928 d.public = None;
929 }
930 }
931 }
932 }
933 normalize_path_dependency(gctx, d, workspace_root, features)
934 .with_context(|| format!("resolving path dependency {name_in_toml}"))?;
935 }
936
937 deps.insert(
938 name_in_toml.clone(),
939 manifest::InheritableDependency::Value(resolved.clone()),
940 );
941 }
942 Ok(Some(deps))
943}
944
945fn normalize_path_dependency<'a>(
946 gctx: &GlobalContext,
947 detailed_dep: &mut TomlDetailedDependency,
948 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
949 features: &Features,
950) -> CargoResult<()> {
951 if let Some(base) = detailed_dep.base.take() {
952 if let Some(path) = detailed_dep.path.as_mut() {
953 let new_path = lookup_path_base(&base, gctx, workspace_root, features)?.join(&path);
954 *path = new_path.to_str().unwrap().to_string();
955 } else {
956 bail!("`base` can only be used with path dependencies");
957 }
958 }
959 Ok(())
960}
961
962fn load_inheritable_fields(
963 gctx: &GlobalContext,
964 normalized_path: &Path,
965 workspace_config: &WorkspaceConfig,
966) -> CargoResult<InheritableFields> {
967 match workspace_config {
968 WorkspaceConfig::Root(root) => Ok(root.inheritable().clone()),
969 WorkspaceConfig::Member {
970 root: Some(path_to_root),
971 } => {
972 let path = normalized_path
973 .parent()
974 .unwrap()
975 .join(path_to_root)
976 .join("Cargo.toml");
977 let root_path = paths::normalize_path(&path);
978 inheritable_from_path(gctx, root_path)
979 }
980 WorkspaceConfig::Member { root: None } => {
981 match find_workspace_root(&normalized_path, gctx)? {
982 Some(path_to_root) => inheritable_from_path(gctx, path_to_root),
983 None => Err(anyhow!("failed to find a workspace root")),
984 }
985 }
986 }
987}
988
989fn inheritable_from_path(
990 gctx: &GlobalContext,
991 workspace_path: PathBuf,
992) -> CargoResult<InheritableFields> {
993 let workspace_path_root = workspace_path.parent().unwrap();
995
996 if let Some(ws_root) = gctx.ws_roots().get(workspace_path_root) {
999 return Ok(ws_root.inheritable().clone());
1000 };
1001
1002 let source_id = SourceId::for_manifest_path(&workspace_path)?;
1003 let man = read_manifest(&workspace_path, source_id, gctx)?;
1004 match man.workspace_config() {
1005 WorkspaceConfig::Root(root) => {
1006 gctx.ws_roots().insert(workspace_path, root.clone());
1007 Ok(root.inheritable().clone())
1008 }
1009 _ => bail!(
1010 "root of a workspace inferred but wasn't a root: {}",
1011 workspace_path.display()
1012 ),
1013 }
1014}
1015
1016macro_rules! package_field_getter {
1018 ( $(($key:literal, $field:ident -> $ret:ty),)* ) => (
1019 $(
1020 #[doc = concat!("Gets the field `workspace.package.", $key, "`.")]
1021 fn $field(&self) -> CargoResult<$ret> {
1022 let Some(val) = self.package.as_ref().and_then(|p| p.$field.as_ref()) else {
1023 bail!("`workspace.package.{}` was not defined", $key);
1024 };
1025 Ok(val.clone())
1026 }
1027 )*
1028 )
1029}
1030
1031#[derive(Clone, Debug, Default)]
1033pub struct InheritableFields {
1034 package: Option<manifest::InheritablePackage>,
1035 dependencies: Option<BTreeMap<manifest::PackageName, manifest::TomlDependency>>,
1036 lints: Option<manifest::TomlLints>,
1037
1038 _ws_root: PathBuf,
1040}
1041
1042impl InheritableFields {
1043 package_field_getter! {
1044 ("authors", authors -> Vec<String>),
1046 ("categories", categories -> Vec<String>),
1047 ("description", description -> String),
1048 ("documentation", documentation -> String),
1049 ("edition", edition -> String),
1050 ("exclude", exclude -> Vec<String>),
1051 ("homepage", homepage -> String),
1052 ("include", include -> Vec<String>),
1053 ("keywords", keywords -> Vec<String>),
1054 ("license", license -> String),
1055 ("publish", publish -> manifest::VecStringOrBool),
1056 ("repository", repository -> String),
1057 ("rust-version", rust_version -> RustVersion),
1058 ("version", version -> semver::Version),
1059 }
1060
1061 fn get_dependency(
1063 &self,
1064 name: &str,
1065 package_root: &Path,
1066 ) -> CargoResult<manifest::TomlDependency> {
1067 let Some(deps) = &self.dependencies else {
1068 bail!("`workspace.dependencies` was not defined");
1069 };
1070 let Some(dep) = deps.get(name) else {
1071 bail!("`dependency.{name}` was not found in `workspace.dependencies`");
1072 };
1073 let mut dep = dep.clone();
1074 if let manifest::TomlDependency::Detailed(detailed) = &mut dep {
1075 if detailed.base.is_none() {
1076 if let Some(rel_path) = &detailed.path {
1079 detailed.path = Some(resolve_relative_path(
1080 name,
1081 self.ws_root(),
1082 package_root,
1083 rel_path,
1084 )?);
1085 }
1086 }
1087 }
1088 Ok(dep)
1089 }
1090
1091 pub fn lints(&self) -> CargoResult<manifest::TomlLints> {
1093 let Some(val) = &self.lints else {
1094 bail!("`workspace.lints` was not defined");
1095 };
1096 Ok(val.clone())
1097 }
1098
1099 fn license_file(&self, package_root: &Path) -> CargoResult<String> {
1101 let Some(license_file) = self.package.as_ref().and_then(|p| p.license_file.as_ref()) else {
1102 bail!("`workspace.package.license-file` was not defined");
1103 };
1104 resolve_relative_path("license-file", &self._ws_root, package_root, license_file)
1105 }
1106
1107 fn readme(&self, package_root: &Path) -> CargoResult<manifest::StringOrBool> {
1109 let Some(readme) = normalize_package_readme(
1110 self._ws_root.as_path(),
1111 self.package.as_ref().and_then(|p| p.readme.as_ref()),
1112 ) else {
1113 bail!("`workspace.package.readme` was not defined");
1114 };
1115 resolve_relative_path("readme", &self._ws_root, package_root, &readme)
1116 .map(manifest::StringOrBool::String)
1117 }
1118
1119 fn ws_root(&self) -> &PathBuf {
1120 &self._ws_root
1121 }
1122}
1123
1124fn field_inherit_with<'a, T>(
1125 field: manifest::InheritableField<T>,
1126 label: &str,
1127 get_ws_inheritable: impl FnOnce() -> CargoResult<T>,
1128) -> CargoResult<T> {
1129 match field {
1130 manifest::InheritableField::Value(value) => Ok(value),
1131 manifest::InheritableField::Inherit(_) => get_ws_inheritable().with_context(|| {
1132 format!(
1133 "error inheriting `{label}` from workspace root manifest's `workspace.package.{label}`",
1134 )
1135 }),
1136 }
1137}
1138
1139fn lints_inherit_with(
1140 lints: manifest::InheritableLints,
1141 get_ws_inheritable: impl FnOnce() -> CargoResult<manifest::TomlLints>,
1142) -> CargoResult<manifest::TomlLints> {
1143 if lints.workspace {
1144 if !lints.lints.is_empty() {
1145 anyhow::bail!(
1146 "cannot override `workspace.lints` in `lints`, either remove the overrides or `lints.workspace = true` and manually specify the lints"
1147 );
1148 }
1149 get_ws_inheritable().with_context(
1150 || "error inheriting `lints` from workspace root manifest's `workspace.lints`",
1151 )
1152 } else {
1153 Ok(lints.lints)
1154 }
1155}
1156
1157fn dependency_inherit_with<'a>(
1158 dependency: manifest::InheritableDependency,
1159 name: &str,
1160 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
1161 package_root: &Path,
1162 edition: Edition,
1163 warnings: &mut Vec<String>,
1164) -> CargoResult<manifest::TomlDependency> {
1165 match dependency {
1166 manifest::InheritableDependency::Value(value) => Ok(value),
1167 manifest::InheritableDependency::Inherit(w) => {
1168 inner_dependency_inherit_with(w, name, inherit, package_root, edition, warnings).with_context(|| {
1169 format!(
1170 "error inheriting `{name}` from workspace root manifest's `workspace.dependencies.{name}`",
1171 )
1172 })
1173 }
1174 }
1175}
1176
1177fn inner_dependency_inherit_with<'a>(
1178 pkg_dep: manifest::TomlInheritedDependency,
1179 name: &str,
1180 inherit: &dyn Fn() -> CargoResult<&'a InheritableFields>,
1181 package_root: &Path,
1182 edition: Edition,
1183 warnings: &mut Vec<String>,
1184) -> CargoResult<manifest::TomlDependency> {
1185 let ws_dep = inherit()?.get_dependency(name, package_root)?;
1186 let mut merged_dep = match ws_dep {
1187 manifest::TomlDependency::Simple(ws_version) => manifest::TomlDetailedDependency {
1188 version: Some(ws_version),
1189 ..Default::default()
1190 },
1191 manifest::TomlDependency::Detailed(ws_dep) => ws_dep.clone(),
1192 };
1193 let manifest::TomlInheritedDependency {
1194 workspace: _,
1195
1196 features,
1197 optional,
1198 default_features,
1199 default_features2,
1200 public,
1201
1202 _unused_keys: _,
1203 } = &pkg_dep;
1204 let default_features = default_features.or(*default_features2);
1205
1206 match (default_features, merged_dep.default_features()) {
1207 (Some(true), Some(false)) => {
1211 merged_dep.default_features = Some(true);
1212 }
1213 (Some(false), Some(true)) => {
1217 deprecated_ws_default_features(name, Some(true), edition, warnings)?;
1218 }
1219 (Some(false), None) => {
1222 deprecated_ws_default_features(name, None, edition, warnings)?;
1223 }
1224 _ => {}
1225 }
1226 merged_dep.features = match (merged_dep.features.clone(), features.clone()) {
1227 (Some(dep_feat), Some(inherit_feat)) => Some(
1228 dep_feat
1229 .into_iter()
1230 .chain(inherit_feat)
1231 .collect::<Vec<String>>(),
1232 ),
1233 (Some(dep_fet), None) => Some(dep_fet),
1234 (None, Some(inherit_feat)) => Some(inherit_feat),
1235 (None, None) => None,
1236 };
1237 merged_dep.optional = *optional;
1238 merged_dep.public = *public;
1239 Ok(manifest::TomlDependency::Detailed(merged_dep))
1240}
1241
1242fn deprecated_ws_default_features(
1243 label: &str,
1244 ws_def_feat: Option<bool>,
1245 edition: Edition,
1246 warnings: &mut Vec<String>,
1247) -> CargoResult<()> {
1248 let ws_def_feat = match ws_def_feat {
1249 Some(true) => "true",
1250 Some(false) => "false",
1251 None => "not specified",
1252 };
1253 if Edition::Edition2024 <= edition {
1254 anyhow::bail!("`default-features = false` cannot override workspace's `default-features`");
1255 } else {
1256 warnings.push(format!(
1257 "`default-features` is ignored for {label}, since `default-features` was \
1258 {ws_def_feat} for `workspace.dependencies.{label}`, \
1259 this could become a hard error in the future"
1260 ));
1261 }
1262 Ok(())
1263}
1264
1265#[tracing::instrument(skip_all)]
1266pub fn to_real_manifest(
1267 contents: Option<String>,
1268 document: Option<toml::Spanned<toml::de::DeTable<'static>>>,
1269 original_toml: manifest::TomlManifest,
1270 normalized_toml: manifest::TomlManifest,
1271 features: Features,
1272 workspace_config: WorkspaceConfig,
1273 source_id: SourceId,
1274 manifest_file: &Path,
1275 is_embedded: bool,
1276 gctx: &GlobalContext,
1277 warnings: &mut Vec<String>,
1278 _errors: &mut Vec<String>,
1279) -> CargoResult<Manifest> {
1280 let package_root = manifest_file.parent().unwrap();
1281 if !package_root.is_dir() {
1282 bail!(
1283 "package root '{}' is not a directory",
1284 package_root.display()
1285 );
1286 };
1287
1288 let normalized_package = normalized_toml
1289 .package()
1290 .expect("previously verified to have a `[package]`");
1291 let package_name = normalized_package
1292 .normalized_name()
1293 .expect("previously normalized");
1294 if package_name.contains(':') {
1295 features.require(Feature::open_namespaces())?;
1296 }
1297 let rust_version = normalized_package
1298 .normalized_rust_version()
1299 .expect("previously normalized")
1300 .cloned();
1301
1302 let edition = if let Some(edition) = normalized_package
1303 .normalized_edition()
1304 .expect("previously normalized")
1305 {
1306 let edition: Edition = edition
1307 .parse()
1308 .context("failed to parse the `edition` key")?;
1309 if let Some(pkg_msrv) = &rust_version {
1310 if let Some(edition_msrv) = edition.first_version() {
1311 let edition_msrv = RustVersion::try_from(edition_msrv).unwrap();
1312 if !edition_msrv.is_compatible_with(&pkg_msrv.to_partial()) {
1313 bail!(
1314 "rust-version {} is incompatible with the version ({}) required by \
1315 the specified edition ({})",
1316 pkg_msrv,
1317 edition_msrv,
1318 edition,
1319 )
1320 }
1321 }
1322 }
1323 edition
1324 } else {
1325 let msrv_edition = if let Some(pkg_msrv) = &rust_version {
1326 Edition::ALL
1327 .iter()
1328 .filter(|e| {
1329 e.first_version()
1330 .map(|e| {
1331 let e = RustVersion::try_from(e).unwrap();
1332 e.is_compatible_with(&pkg_msrv.to_partial())
1333 })
1334 .unwrap_or_default()
1335 })
1336 .max()
1337 .copied()
1338 } else {
1339 None
1340 }
1341 .unwrap_or_default();
1342 let default_edition = Edition::default();
1343 let latest_edition = Edition::LATEST_STABLE;
1344
1345 if msrv_edition != default_edition || rust_version.is_none() {
1350 let tip = if msrv_edition == latest_edition || rust_version.is_none() {
1351 format!(" while the latest is `{latest_edition}`")
1352 } else {
1353 format!(" while {msrv_edition} is compatible with `rust-version`")
1354 };
1355 warnings.push(format!(
1356 "`package.edition` is unspecified, defaulting to `{default_edition}`{tip}"
1357 ));
1358 }
1359 default_edition
1360 };
1361 if !edition.is_stable() {
1362 let version = normalized_package
1363 .normalized_version()
1364 .expect("previously normalized")
1365 .map(|v| format!("@{v}"))
1366 .unwrap_or_default();
1367 let hint = rust_version
1368 .as_ref()
1369 .map(|rv| format!("help: {package_name}{version} requires rust {rv}"));
1370 features.require_with_hint(Feature::unstable_editions(), hint.as_deref())?;
1371 }
1372
1373 if original_toml.project.is_some() {
1374 if Edition::Edition2024 <= edition {
1375 anyhow::bail!(
1376 "`[project]` is not supported as of the 2024 Edition, please use `[package]`"
1377 );
1378 } else {
1379 warnings.push(format!("`[project]` is deprecated in favor of `[package]`"));
1380 }
1381 }
1382
1383 if normalized_package.metabuild.is_some() {
1384 features.require(Feature::metabuild())?;
1385 }
1386
1387 if is_embedded {
1388 let manifest::TomlManifest {
1389 cargo_features: _,
1390 package: _,
1391 project: _,
1392 badges: _,
1393 features: _,
1394 lib,
1395 bin,
1396 example,
1397 test,
1398 bench,
1399 dependencies: _,
1400 dev_dependencies: _,
1401 dev_dependencies2: _,
1402 build_dependencies,
1403 build_dependencies2,
1404 target: _,
1405 lints: _,
1406 hints: _,
1407 workspace,
1408 profile: _,
1409 patch: _,
1410 replace: _,
1411 _unused_keys: _,
1412 } = &original_toml;
1413 let mut invalid_fields = vec![
1414 ("`workspace`", workspace.is_some()),
1415 ("`lib`", lib.is_some()),
1416 ("`bin`", bin.is_some()),
1417 ("`example`", example.is_some()),
1418 ("`test`", test.is_some()),
1419 ("`bench`", bench.is_some()),
1420 ("`build-dependencies`", build_dependencies.is_some()),
1421 ("`build_dependencies`", build_dependencies2.is_some()),
1422 ];
1423 if let Some(package) = original_toml.package() {
1424 let manifest::TomlPackage {
1425 edition: _,
1426 rust_version: _,
1427 name: _,
1428 version: _,
1429 authors: _,
1430 build,
1431 metabuild,
1432 default_target: _,
1433 forced_target: _,
1434 links,
1435 exclude: _,
1436 include: _,
1437 publish: _,
1438 workspace,
1439 im_a_teapot: _,
1440 autolib,
1441 autobins,
1442 autoexamples,
1443 autotests,
1444 autobenches,
1445 default_run,
1446 description: _,
1447 homepage: _,
1448 documentation: _,
1449 readme: _,
1450 keywords: _,
1451 categories: _,
1452 license: _,
1453 license_file: _,
1454 repository: _,
1455 resolver: _,
1456 metadata: _,
1457 _invalid_cargo_features: _,
1458 } = package.as_ref();
1459 invalid_fields.extend([
1460 ("`package.workspace`", workspace.is_some()),
1461 ("`package.build`", build.is_some()),
1462 ("`package.metabuild`", metabuild.is_some()),
1463 ("`package.links`", links.is_some()),
1464 ("`package.autolib`", autolib.is_some()),
1465 ("`package.autobins`", autobins.is_some()),
1466 ("`package.autoexamples`", autoexamples.is_some()),
1467 ("`package.autotests`", autotests.is_some()),
1468 ("`package.autobenches`", autobenches.is_some()),
1469 ("`package.default-run`", default_run.is_some()),
1470 ]);
1471 }
1472 let invalid_fields = invalid_fields
1473 .into_iter()
1474 .filter_map(|(name, invalid)| invalid.then_some(name))
1475 .collect::<Vec<_>>();
1476 if !invalid_fields.is_empty() {
1477 let fields = invalid_fields.join(", ");
1478 let are = if invalid_fields.len() == 1 {
1479 "is"
1480 } else {
1481 "are"
1482 };
1483 anyhow::bail!("{fields} {are} not allowed in embedded manifests")
1484 }
1485 }
1486
1487 let resolve_behavior = match (
1488 normalized_package.resolver.as_ref(),
1489 normalized_toml
1490 .workspace
1491 .as_ref()
1492 .and_then(|ws| ws.resolver.as_ref()),
1493 ) {
1494 (None, None) => None,
1495 (Some(s), None) | (None, Some(s)) => Some(ResolveBehavior::from_manifest(s)?),
1496 (Some(_), Some(_)) => {
1497 bail!("cannot specify `resolver` field in both `[workspace]` and `[package]`")
1498 }
1499 };
1500
1501 let targets = to_targets(
1505 &features,
1506 &original_toml,
1507 &normalized_toml,
1508 package_root,
1509 edition,
1510 &normalized_package.metabuild,
1511 warnings,
1512 )?;
1513
1514 if targets.iter().all(|t| t.is_custom_build()) {
1515 bail!(
1516 "no targets specified in the manifest\n\
1517 either src/lib.rs, src/main.rs, a [lib] section, or \
1518 [[bin]] section must be present"
1519 )
1520 }
1521
1522 if let Err(conflict_targets) = unique_build_targets(&targets, package_root) {
1523 conflict_targets
1524 .iter()
1525 .for_each(|(target_path, conflicts)| {
1526 warnings.push(format!(
1527 "file `{}` found to be present in multiple \
1528 build targets:\n{}",
1529 target_path.display(),
1530 conflicts
1531 .iter()
1532 .map(|t| format!(" * `{}` target `{}`", t.kind().description(), t.name(),))
1533 .join("\n")
1534 ));
1535 })
1536 }
1537
1538 if let Some(links) = &normalized_package.links {
1539 if !targets.iter().any(|t| t.is_custom_build()) {
1540 bail!(
1541 "package specifies that it links to `{links}` but does not have a custom build script"
1542 )
1543 }
1544 }
1545
1546 validate_dependencies(original_toml.dependencies.as_ref(), None, None, warnings)?;
1547 validate_dependencies(
1548 original_toml.dev_dependencies(),
1549 None,
1550 Some(DepKind::Development),
1551 warnings,
1552 )?;
1553 validate_dependencies(
1554 original_toml.build_dependencies(),
1555 None,
1556 Some(DepKind::Build),
1557 warnings,
1558 )?;
1559 for (name, platform) in original_toml.target.iter().flatten() {
1560 let platform_kind: Platform = name.parse()?;
1561 platform_kind.check_cfg_attributes(warnings);
1562 platform_kind.check_cfg_keywords(warnings, manifest_file);
1563 let platform_kind = Some(platform_kind);
1564 validate_dependencies(
1565 platform.dependencies.as_ref(),
1566 platform_kind.as_ref(),
1567 None,
1568 warnings,
1569 )?;
1570 validate_dependencies(
1571 platform.build_dependencies(),
1572 platform_kind.as_ref(),
1573 Some(DepKind::Build),
1574 warnings,
1575 )?;
1576 validate_dependencies(
1577 platform.dev_dependencies(),
1578 platform_kind.as_ref(),
1579 Some(DepKind::Development),
1580 warnings,
1581 )?;
1582 }
1583
1584 let mut deps = Vec::new();
1586 let mut manifest_ctx = ManifestContext {
1587 deps: &mut deps,
1588 source_id,
1589 gctx,
1590 warnings,
1591 platform: None,
1592 file: manifest_file,
1593 };
1594 gather_dependencies(
1595 &mut manifest_ctx,
1596 normalized_toml.dependencies.as_ref(),
1597 None,
1598 )?;
1599 gather_dependencies(
1600 &mut manifest_ctx,
1601 normalized_toml.dev_dependencies(),
1602 Some(DepKind::Development),
1603 )?;
1604 gather_dependencies(
1605 &mut manifest_ctx,
1606 normalized_toml.build_dependencies(),
1607 Some(DepKind::Build),
1608 )?;
1609 for (name, platform) in normalized_toml.target.iter().flatten() {
1610 manifest_ctx.platform = Some(name.parse()?);
1611 gather_dependencies(&mut manifest_ctx, platform.dependencies.as_ref(), None)?;
1612 gather_dependencies(
1613 &mut manifest_ctx,
1614 platform.build_dependencies(),
1615 Some(DepKind::Build),
1616 )?;
1617 gather_dependencies(
1618 &mut manifest_ctx,
1619 platform.dev_dependencies(),
1620 Some(DepKind::Development),
1621 )?;
1622 }
1623 let replace = replace(&normalized_toml, &mut manifest_ctx)?;
1624 let patch = patch(&normalized_toml, &mut manifest_ctx)?;
1625
1626 {
1627 let mut names_sources = BTreeMap::new();
1628 for dep in &deps {
1629 let name = dep.name_in_toml();
1630 let prev = names_sources.insert(name, dep.source_id());
1631 if prev.is_some() && prev != Some(dep.source_id()) {
1632 bail!(
1633 "Dependency '{}' has different source paths depending on the build \
1634 target. Each dependency must have a single canonical source path \
1635 irrespective of build target.",
1636 name
1637 );
1638 }
1639 }
1640 }
1641
1642 verify_lints(
1643 normalized_toml
1644 .normalized_lints()
1645 .expect("previously normalized"),
1646 gctx,
1647 warnings,
1648 )?;
1649 let default = manifest::TomlLints::default();
1650 let rustflags = lints_to_rustflags(
1651 normalized_toml
1652 .normalized_lints()
1653 .expect("previously normalized")
1654 .unwrap_or(&default),
1655 )?;
1656
1657 let hints = normalized_toml.hints.clone();
1658
1659 let metadata = ManifestMetadata {
1660 description: normalized_package
1661 .normalized_description()
1662 .expect("previously normalized")
1663 .cloned(),
1664 homepage: normalized_package
1665 .normalized_homepage()
1666 .expect("previously normalized")
1667 .cloned(),
1668 documentation: normalized_package
1669 .normalized_documentation()
1670 .expect("previously normalized")
1671 .cloned(),
1672 readme: normalized_package
1673 .normalized_readme()
1674 .expect("previously normalized")
1675 .cloned(),
1676 authors: normalized_package
1677 .normalized_authors()
1678 .expect("previously normalized")
1679 .cloned()
1680 .unwrap_or_default(),
1681 license: normalized_package
1682 .normalized_license()
1683 .expect("previously normalized")
1684 .cloned(),
1685 license_file: normalized_package
1686 .normalized_license_file()
1687 .expect("previously normalized")
1688 .cloned(),
1689 repository: normalized_package
1690 .normalized_repository()
1691 .expect("previously normalized")
1692 .cloned(),
1693 keywords: normalized_package
1694 .normalized_keywords()
1695 .expect("previously normalized")
1696 .cloned()
1697 .unwrap_or_default(),
1698 categories: normalized_package
1699 .normalized_categories()
1700 .expect("previously normalized")
1701 .cloned()
1702 .unwrap_or_default(),
1703 badges: normalized_toml.badges.clone().unwrap_or_default(),
1704 links: normalized_package.links.clone(),
1705 rust_version: rust_version.clone(),
1706 };
1707
1708 if let Some(profiles) = &normalized_toml.profile {
1709 let cli_unstable = gctx.cli_unstable();
1710 validate_profiles(profiles, cli_unstable, &features, warnings)?;
1711 }
1712
1713 let version = normalized_package
1714 .normalized_version()
1715 .expect("previously normalized");
1716 let publish = match normalized_package
1717 .normalized_publish()
1718 .expect("previously normalized")
1719 {
1720 Some(manifest::VecStringOrBool::VecString(vecstring)) => Some(vecstring.clone()),
1721 Some(manifest::VecStringOrBool::Bool(false)) => Some(vec![]),
1722 Some(manifest::VecStringOrBool::Bool(true)) => None,
1723 None => version.is_none().then_some(vec![]),
1724 };
1725
1726 if version.is_none() && publish != Some(vec![]) {
1727 bail!("`package.publish` requires `package.version` be specified");
1728 }
1729
1730 let pkgid = PackageId::new(
1731 package_name.as_str().into(),
1732 version
1733 .cloned()
1734 .unwrap_or_else(|| semver::Version::new(0, 0, 0)),
1735 source_id,
1736 );
1737 let summary = {
1738 let summary = Summary::new(
1739 pkgid,
1740 deps,
1741 &normalized_toml
1742 .features
1743 .as_ref()
1744 .unwrap_or(&Default::default())
1745 .iter()
1746 .map(|(k, v)| {
1747 (
1748 k.to_string().into(),
1749 v.iter().map(InternedString::from).collect(),
1750 )
1751 })
1752 .collect(),
1753 normalized_package.links.as_deref(),
1754 rust_version.clone(),
1755 );
1756 if let Err(ref err) = summary {
1759 if let Some(missing_dep) = err.downcast_ref::<MissingDependencyError>() {
1760 missing_dep_diagnostic(
1761 missing_dep,
1762 &original_toml,
1763 document.as_ref(),
1764 contents.as_deref(),
1765 manifest_file,
1766 gctx,
1767 )?;
1768 }
1769 }
1770 summary?
1771 };
1772
1773 if summary.features().contains_key("default-features") {
1774 warnings.push(
1775 "`[features]` defines a feature named `default-features`
1776note: only a feature named `default` will be enabled by default"
1777 .to_string(),
1778 )
1779 }
1780
1781 if let Some(run) = &normalized_package.default_run {
1782 if !targets
1783 .iter()
1784 .filter(|t| t.is_bin())
1785 .any(|t| t.name() == run)
1786 {
1787 let suggestion = util::closest_msg(
1788 run,
1789 targets.iter().filter(|t| t.is_bin()),
1790 |t| t.name(),
1791 "target",
1792 );
1793 bail!("default-run target `{}` not found{}", run, suggestion);
1794 }
1795 }
1796
1797 let default_kind = normalized_package
1798 .default_target
1799 .as_ref()
1800 .map(|t| CompileTarget::new(&*t, gctx.cli_unstable().json_target_spec))
1801 .transpose()?
1802 .map(CompileKind::Target);
1803 let forced_kind = normalized_package
1804 .forced_target
1805 .as_ref()
1806 .map(|t| CompileTarget::new(&*t, gctx.cli_unstable().json_target_spec))
1807 .transpose()?
1808 .map(CompileKind::Target);
1809 let include = normalized_package
1810 .normalized_include()
1811 .expect("previously normalized")
1812 .cloned()
1813 .unwrap_or_default();
1814 let exclude = normalized_package
1815 .normalized_exclude()
1816 .expect("previously normalized")
1817 .cloned()
1818 .unwrap_or_default();
1819 let links = normalized_package.links.clone();
1820 let custom_metadata = normalized_package.metadata.clone();
1821 let im_a_teapot = normalized_package.im_a_teapot;
1822 let default_run = normalized_package.default_run.clone();
1823 let metabuild = normalized_package.metabuild.clone().map(|sov| sov.0);
1824 let manifest = Manifest::new(
1825 contents.map(Rc::new),
1826 document.map(Rc::new),
1827 Some(Rc::new(original_toml)),
1828 Rc::new(normalized_toml),
1829 summary,
1830 default_kind,
1831 forced_kind,
1832 targets,
1833 exclude,
1834 include,
1835 links,
1836 metadata,
1837 custom_metadata,
1838 publish,
1839 replace,
1840 patch,
1841 workspace_config,
1842 features,
1843 edition,
1844 rust_version,
1845 im_a_teapot,
1846 default_run,
1847 metabuild,
1848 resolve_behavior,
1849 rustflags,
1850 hints,
1851 is_embedded,
1852 );
1853 if manifest
1854 .normalized_toml()
1855 .package()
1856 .unwrap()
1857 .license_file
1858 .is_some()
1859 && manifest
1860 .normalized_toml()
1861 .package()
1862 .unwrap()
1863 .license
1864 .is_some()
1865 {
1866 warnings.push(
1867 "only one of `license` or `license-file` is necessary\n\
1868 `license` should be used if the package license can be expressed \
1869 with a standard SPDX expression.\n\
1870 `license-file` should be used if the package uses a non-standard license.\n\
1871 See https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields \
1872 for more information."
1873 .to_owned(),
1874 );
1875 }
1876 if let Some(original_toml) = manifest.original_toml() {
1877 warn_on_unused(&original_toml._unused_keys, warnings);
1878 }
1879
1880 manifest.feature_gate()?;
1881
1882 Ok(manifest)
1883}
1884
1885fn missing_dep_diagnostic(
1886 missing_dep: &MissingDependencyError,
1887 orig_toml: &TomlManifest,
1888 document: Option<&toml::Spanned<toml::de::DeTable<'static>>>,
1889 contents: Option<&str>,
1890 manifest_file: &Path,
1891 gctx: &GlobalContext,
1892) -> CargoResult<()> {
1893 let dep_name = missing_dep.dep_name;
1894 let manifest_path = rel_cwd_manifest_path(manifest_file, gctx);
1895
1896 let title = format!(
1897 "feature `{}` includes `{}`, but `{}` is not a dependency",
1898 missing_dep.feature, missing_dep.feature_value, &dep_name
1899 );
1900 let help = format!("enable the dependency with `dep:{dep_name}`");
1901 let info_label = format!(
1902 "`{}` is an unused optional dependency since no feature enables it",
1903 &dep_name
1904 );
1905 let group = Group::with_title(Level::ERROR.primary_title(&title));
1906 let group =
1907 if let Some(contents) = contents
1908 && let Some(document) = document
1909 {
1910 let feature_span =
1911 get_key_value_span(&document, &["features", missing_dep.feature.as_str()]).unwrap();
1912
1913 let snippet = Snippet::source(contents)
1914 .path(manifest_path)
1915 .annotation(AnnotationKind::Primary.span(feature_span.value));
1916
1917 if missing_dep.weak_optional {
1918 let mut orig_deps = vec![
1919 (
1920 orig_toml.dependencies.as_ref(),
1921 vec![DepKind::Normal.kind_table()],
1922 ),
1923 (
1924 orig_toml.build_dependencies.as_ref(),
1925 vec![DepKind::Build.kind_table()],
1926 ),
1927 ];
1928 for (name, platform) in orig_toml.target.iter().flatten() {
1929 orig_deps.push((
1930 platform.dependencies.as_ref(),
1931 vec!["target", name, DepKind::Normal.kind_table()],
1932 ));
1933 orig_deps.push((
1934 platform.build_dependencies.as_ref(),
1935 vec!["target", name, DepKind::Normal.kind_table()],
1936 ));
1937 }
1938
1939 if let Some((_, toml_path)) = orig_deps.iter().find(|(deps, _)| {
1940 if let Some(deps) = deps {
1941 deps.keys().any(|p| *p.as_str() == *dep_name)
1942 } else {
1943 false
1944 }
1945 }) {
1946 let toml_path = toml_path
1947 .iter()
1948 .map(|s| *s)
1949 .chain(std::iter::once(dep_name.as_str()))
1950 .collect::<Vec<_>>();
1951 let dep_span = get_key_value_span(&document, &toml_path).unwrap();
1952
1953 group
1954 .element(snippet.annotation(
1955 AnnotationKind::Context.span(dep_span.key).label(info_label),
1956 ))
1957 .element(Level::HELP.message(help))
1958 } else {
1959 group.element(snippet)
1960 }
1961 } else {
1962 group.element(snippet)
1963 }
1964 } else {
1965 group
1966 };
1967
1968 if let Err(err) = gctx.shell().print_report(&[group], true) {
1969 return Err(err.into());
1970 }
1971 Err(AlreadyPrintedError::new(anyhow!("").into()).into())
1972}
1973
1974fn to_virtual_manifest(
1975 contents: Option<String>,
1976 document: Option<toml::Spanned<toml::de::DeTable<'static>>>,
1977 original_toml: manifest::TomlManifest,
1978 normalized_toml: manifest::TomlManifest,
1979 features: Features,
1980 workspace_config: WorkspaceConfig,
1981 source_id: SourceId,
1982 manifest_file: &Path,
1983 gctx: &GlobalContext,
1984 warnings: &mut Vec<String>,
1985 _errors: &mut Vec<String>,
1986) -> CargoResult<VirtualManifest> {
1987 let mut deps = Vec::new();
1988 let (replace, patch) = {
1989 let mut manifest_ctx = ManifestContext {
1990 deps: &mut deps,
1991 source_id,
1992 gctx,
1993 warnings,
1994 platform: None,
1995 file: manifest_file,
1996 };
1997 (
1998 replace(&normalized_toml, &mut manifest_ctx)?,
1999 patch(&normalized_toml, &mut manifest_ctx)?,
2000 )
2001 };
2002 if let Some(profiles) = &normalized_toml.profile {
2003 validate_profiles(profiles, gctx.cli_unstable(), &features, warnings)?;
2004 }
2005 let resolve_behavior = normalized_toml
2006 .workspace
2007 .as_ref()
2008 .and_then(|ws| ws.resolver.as_deref())
2009 .map(|r| ResolveBehavior::from_manifest(r))
2010 .transpose()?;
2011 if let WorkspaceConfig::Member { .. } = &workspace_config {
2012 bail!("virtual manifests must be configured with [workspace]");
2013 }
2014 let manifest = VirtualManifest::new(
2015 contents.map(Rc::new),
2016 document.map(Rc::new),
2017 Some(Rc::new(original_toml)),
2018 Rc::new(normalized_toml),
2019 replace,
2020 patch,
2021 workspace_config,
2022 features,
2023 resolve_behavior,
2024 );
2025
2026 if let Some(original_toml) = manifest.original_toml() {
2027 warn_on_unused(&original_toml._unused_keys, warnings);
2028 }
2029
2030 Ok(manifest)
2031}
2032
2033#[tracing::instrument(skip_all)]
2034fn validate_dependencies(
2035 original_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
2036 platform: Option<&Platform>,
2037 kind: Option<DepKind>,
2038 warnings: &mut Vec<String>,
2039) -> CargoResult<()> {
2040 let Some(dependencies) = original_deps else {
2041 return Ok(());
2042 };
2043
2044 for (name_in_toml, v) in dependencies.iter() {
2045 let kind_name = match kind {
2046 Some(k) => k.kind_table(),
2047 None => "dependencies",
2048 };
2049 let table_in_toml = if let Some(platform) = platform {
2050 format!("target.{platform}.{kind_name}")
2051 } else {
2052 kind_name.to_string()
2053 };
2054 unused_dep_keys(name_in_toml, &table_in_toml, v.unused_keys(), warnings);
2055 }
2056 Ok(())
2057}
2058
2059struct ManifestContext<'a, 'b> {
2060 deps: &'a mut Vec<Dependency>,
2061 source_id: SourceId,
2062 gctx: &'b GlobalContext,
2063 warnings: &'a mut Vec<String>,
2064 platform: Option<Platform>,
2065 file: &'a Path,
2066}
2067
2068#[tracing::instrument(skip_all)]
2069fn gather_dependencies(
2070 manifest_ctx: &mut ManifestContext<'_, '_>,
2071 normalized_deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
2072 kind: Option<DepKind>,
2073) -> CargoResult<()> {
2074 let Some(dependencies) = normalized_deps else {
2075 return Ok(());
2076 };
2077
2078 for (n, v) in dependencies.iter() {
2079 let resolved = v.normalized().expect("previously normalized");
2080 let dep = dep_to_dependency(&resolved, n, manifest_ctx, kind)?;
2081 manifest_ctx.deps.push(dep);
2082 }
2083 Ok(())
2084}
2085
2086fn replace(
2087 me: &manifest::TomlManifest,
2088 manifest_ctx: &mut ManifestContext<'_, '_>,
2089) -> CargoResult<Vec<(PackageIdSpec, Dependency)>> {
2090 if me.patch.is_some() && me.replace.is_some() {
2091 bail!("cannot specify both [replace] and [patch]");
2092 }
2093 let mut replace = Vec::new();
2094 for (spec, replacement) in me.replace.iter().flatten() {
2095 let mut spec = PackageIdSpec::parse(spec).with_context(|| {
2096 format!(
2097 "replacements must specify a valid semver \
2098 version to replace, but `{}` does not",
2099 spec
2100 )
2101 })?;
2102 if spec.url().is_none() {
2103 spec.set_url(CRATES_IO_INDEX.parse().unwrap());
2104 }
2105
2106 if replacement.is_version_specified() {
2107 bail!(
2108 "replacements cannot specify a version \
2109 requirement, but found one for `{}`",
2110 spec
2111 );
2112 }
2113
2114 let mut dep = dep_to_dependency(replacement, spec.name(), manifest_ctx, None)?;
2115 let version = spec.version().ok_or_else(|| {
2116 anyhow!(
2117 "replacements must specify a version \
2118 to replace, but `{}` does not",
2119 spec
2120 )
2121 })?;
2122 unused_dep_keys(
2123 dep.name_in_toml().as_str(),
2124 "replace",
2125 replacement.unused_keys(),
2126 &mut manifest_ctx.warnings,
2127 );
2128 dep.set_version_req(OptVersionReq::exact(&version));
2129 replace.push((spec, dep));
2130 }
2131 Ok(replace)
2132}
2133
2134fn patch(
2135 me: &TomlManifest,
2136 manifest_ctx: &mut ManifestContext<'_, '_>,
2137) -> CargoResult<HashMap<Url, Vec<Patch>>> {
2138 let mut patch = HashMap::new();
2139 for (toml_url, deps) in me.patch.iter().flatten() {
2140 let url = match &toml_url[..] {
2141 CRATES_IO_REGISTRY => CRATES_IO_INDEX.parse().unwrap(),
2142 _ => manifest_ctx
2143 .gctx
2144 .get_registry_index(toml_url)
2145 .or_else(|_| toml_url.into_url())
2146 .with_context(|| {
2147 format!(
2148 "[patch] entry `{}` should be a URL or registry name{}",
2149 toml_url,
2150 if toml_url == "crates" {
2151 "\nFor crates.io, use [patch.crates-io] (with a dash)"
2152 } else {
2153 ""
2154 }
2155 )
2156 })?,
2157 };
2158 patch.insert(
2159 url,
2160 deps.iter()
2161 .map(|(name, dep)| {
2162 unused_dep_keys(
2163 name,
2164 &format!("patch.{toml_url}",),
2165 dep.unused_keys(),
2166 &mut manifest_ctx.warnings,
2167 );
2168
2169 let dep = dep_to_dependency(dep, name, manifest_ctx, None)?;
2170 let loc = PatchLocation::Manifest(manifest_ctx.file.to_path_buf());
2171 Ok(Patch { dep, loc })
2172 })
2173 .collect::<CargoResult<Vec<_>>>()?,
2174 );
2175 }
2176 Ok(patch)
2177}
2178
2179pub(crate) fn config_patch_to_dependency<P: ResolveToPath + Clone>(
2181 config_patch: &manifest::TomlDependency<P>,
2182 name: &str,
2183 source_id: SourceId,
2184 gctx: &GlobalContext,
2185 warnings: &mut Vec<String>,
2186) -> CargoResult<Dependency> {
2187 let manifest_ctx = &mut ManifestContext {
2188 deps: &mut Vec::new(),
2189 source_id,
2190 gctx,
2191 warnings,
2192 platform: None,
2193 file: Path::new("unused"),
2195 };
2196 dep_to_dependency(config_patch, name, manifest_ctx, None)
2197}
2198
2199fn dep_to_dependency<P: ResolveToPath + Clone>(
2200 orig: &manifest::TomlDependency<P>,
2201 name_in_toml: &str,
2202 manifest_ctx: &mut ManifestContext<'_, '_>,
2203 kind: Option<DepKind>,
2204) -> CargoResult<Dependency> {
2205 let orig = match orig {
2206 manifest::TomlDependency::Simple(version) => &manifest::TomlDetailedDependency::<P> {
2207 version: Some(version.clone()),
2208 ..Default::default()
2209 },
2210 manifest::TomlDependency::Detailed(details) => details,
2211 };
2212
2213 if orig.version.is_none() && orig.path.is_none() && orig.git.is_none() {
2214 anyhow::bail!(
2215 "dependency ({name_in_toml}) specified without \
2216 providing a local path, Git repository, version, or \
2217 workspace dependency to use"
2218 );
2219 }
2220
2221 if let Some(version) = &orig.version {
2222 if version.contains('+') {
2223 manifest_ctx.warnings.push(format!(
2224 "version requirement `{}` for dependency `{}` \
2225 includes semver metadata which will be ignored, removing the \
2226 metadata is recommended to avoid confusion",
2227 version, name_in_toml
2228 ));
2229 }
2230 }
2231
2232 if orig.git.is_none() {
2233 let git_only_keys = [
2234 (&orig.branch, "branch"),
2235 (&orig.tag, "tag"),
2236 (&orig.rev, "rev"),
2237 ];
2238
2239 for &(key, key_name) in &git_only_keys {
2240 if key.is_some() {
2241 bail!(
2242 "key `{}` is ignored for dependency ({}).",
2243 key_name,
2244 name_in_toml
2245 );
2246 }
2247 }
2248 }
2249
2250 if let Some(features) = &orig.features {
2253 for feature in features {
2254 if feature.contains('/') {
2255 bail!(
2256 "feature `{}` in dependency `{}` is not allowed to contain slashes\n\
2257 If you want to enable features of a transitive dependency, \
2258 the direct dependency needs to re-export those features from \
2259 the `[features]` table.",
2260 feature,
2261 name_in_toml
2262 );
2263 }
2264 if feature.starts_with("dep:") {
2265 bail!(
2266 "feature `{}` in dependency `{}` is not allowed to use explicit \
2267 `dep:` syntax\n\
2268 If you want to enable an optional dependency, specify the name \
2269 of the optional dependency without the `dep:` prefix, or specify \
2270 a feature from the dependency's `[features]` table that enables \
2271 the optional dependency.",
2272 feature,
2273 name_in_toml
2274 );
2275 }
2276 }
2277 }
2278
2279 let new_source_id = to_dependency_source_id(orig, name_in_toml, manifest_ctx)?;
2280
2281 let (pkg_name, explicit_name_in_toml) = match orig.package {
2282 Some(ref s) => (&s[..], Some(name_in_toml)),
2283 None => (name_in_toml, None),
2284 };
2285
2286 let version = orig.version.as_deref();
2287 let mut dep = Dependency::parse(pkg_name, version, new_source_id)?;
2288 dep.set_features(orig.features.iter().flatten())
2289 .set_default_features(orig.default_features().unwrap_or(true))
2290 .set_optional(orig.optional.unwrap_or(false))
2291 .set_platform(manifest_ctx.platform.clone());
2292 if let Some(registry) = &orig.registry {
2293 let registry_id = SourceId::alt_registry(manifest_ctx.gctx, registry)?;
2294 dep.set_registry_id(registry_id);
2295 }
2296 if let Some(registry_index) = &orig.registry_index {
2297 let url = registry_index.into_url()?;
2298 let registry_id = SourceId::for_registry(&url)?;
2299 dep.set_registry_id(registry_id);
2300 }
2301
2302 if let Some(kind) = kind {
2303 dep.set_kind(kind);
2304 }
2305 if let Some(name_in_toml) = explicit_name_in_toml {
2306 dep.set_explicit_name_in_toml(name_in_toml);
2307 }
2308
2309 if let Some(p) = orig.public {
2310 dep.set_public(p);
2311 }
2312
2313 if let (Some(artifact), is_lib, target) = (
2314 orig.artifact.as_ref(),
2315 orig.lib.unwrap_or(false),
2316 orig.target.as_deref(),
2317 ) {
2318 if manifest_ctx.gctx.cli_unstable().bindeps {
2319 let artifact = Artifact::parse(
2320 &artifact.0,
2321 is_lib,
2322 target,
2323 manifest_ctx.gctx.cli_unstable().json_target_spec,
2324 )?;
2325 if dep.kind() != DepKind::Build
2326 && artifact.target() == Some(ArtifactTarget::BuildDependencyAssumeTarget)
2327 {
2328 bail!(
2329 r#"`target = "target"` in normal- or dev-dependencies has no effect ({})"#,
2330 name_in_toml
2331 );
2332 }
2333 dep.set_artifact(artifact)
2334 } else {
2335 bail!("`artifact = …` requires `-Z bindeps` ({})", name_in_toml);
2336 }
2337 } else if orig.lib.is_some() || orig.target.is_some() {
2338 for (is_set, specifier) in [
2339 (orig.lib.is_some(), "lib"),
2340 (orig.target.is_some(), "target"),
2341 ] {
2342 if !is_set {
2343 continue;
2344 }
2345 bail!(
2346 "'{}' specifier cannot be used without an 'artifact = …' value ({})",
2347 specifier,
2348 name_in_toml
2349 )
2350 }
2351 }
2352 Ok(dep)
2353}
2354
2355fn to_dependency_source_id<P: ResolveToPath + Clone>(
2356 orig: &manifest::TomlDetailedDependency<P>,
2357 name_in_toml: &str,
2358 manifest_ctx: &mut ManifestContext<'_, '_>,
2359) -> CargoResult<SourceId> {
2360 match (
2361 orig.git.as_ref(),
2362 orig.path.as_ref(),
2363 orig.registry.as_deref(),
2364 orig.registry_index.as_ref(),
2365 ) {
2366 (Some(_git), Some(_path), _, _) => {
2367 bail!(
2368 "dependency ({name_in_toml}) specification is ambiguous. \
2369 Only one of `git` or `path` is allowed.",
2370 );
2371 }
2372 (_, _, Some(_registry), Some(_registry_index)) => bail!(
2373 "dependency ({name_in_toml}) specification is ambiguous. \
2374 Only one of `registry` or `registry-index` is allowed.",
2375 ),
2376 (Some(git), None, _, _) => {
2377 let n_details = [&orig.branch, &orig.tag, &orig.rev]
2378 .iter()
2379 .filter(|d| d.is_some())
2380 .count();
2381
2382 if n_details > 1 {
2383 bail!(
2384 "dependency ({name_in_toml}) specification is ambiguous. \
2385 Only one of `branch`, `tag` or `rev` is allowed.",
2386 );
2387 }
2388
2389 let reference = orig
2390 .branch
2391 .clone()
2392 .map(GitReference::Branch)
2393 .or_else(|| orig.tag.clone().map(GitReference::Tag))
2394 .or_else(|| orig.rev.clone().map(GitReference::Rev))
2395 .unwrap_or(GitReference::DefaultBranch);
2396 let loc = git.into_url()?;
2397
2398 if let Some(fragment) = loc.fragment() {
2399 let msg = format!(
2400 "URL fragment `#{fragment}` in git URL is ignored for dependency ({name_in_toml}). \
2401 If you were trying to specify a specific git revision, \
2402 use `rev = \"{fragment}\"` in the dependency declaration.",
2403 );
2404 manifest_ctx.warnings.push(msg);
2405 }
2406
2407 SourceId::for_git(&loc, reference)
2408 }
2409 (None, Some(path), _, _) => {
2410 let path = path.resolve(manifest_ctx.gctx);
2411 if manifest_ctx.source_id.is_path() {
2420 let path = manifest_ctx.file.parent().unwrap().join(path);
2421 let path = paths::normalize_path(&path);
2422 SourceId::for_path(&path)
2423 } else {
2424 Ok(manifest_ctx.source_id)
2425 }
2426 }
2427 (None, None, Some(registry), None) => SourceId::alt_registry(manifest_ctx.gctx, registry),
2428 (None, None, None, Some(registry_index)) => {
2429 let url = registry_index.into_url()?;
2430 SourceId::for_registry(&url)
2431 }
2432 (None, None, None, None) => SourceId::crates_io(manifest_ctx.gctx),
2433 }
2434}
2435
2436pub(crate) fn lookup_path_base<'a>(
2437 base: &PathBaseName,
2438 gctx: &GlobalContext,
2439 workspace_root: &dyn Fn() -> CargoResult<&'a Path>,
2440 features: &Features,
2441) -> CargoResult<PathBuf> {
2442 features.require(Feature::path_bases())?;
2443
2444 let base_key = format!("path-bases.{base}");
2447
2448 if let Some(path_bases) = gctx.get::<Option<ConfigRelativePath>>(&base_key)? {
2450 Ok(path_bases.resolve_path(gctx))
2451 } else {
2452 match base.as_str() {
2454 "workspace" => Ok(workspace_root()?.to_path_buf()),
2455 _ => bail!(
2456 "path base `{base}` is undefined. \
2457 You must add an entry for `{base}` in the Cargo configuration [path-bases] table."
2458 ),
2459 }
2460 }
2461}
2462
2463pub trait ResolveToPath {
2464 fn resolve(&self, gctx: &GlobalContext) -> PathBuf;
2465}
2466
2467impl ResolveToPath for String {
2468 fn resolve(&self, _: &GlobalContext) -> PathBuf {
2469 self.into()
2470 }
2471}
2472
2473impl ResolveToPath for ConfigRelativePath {
2474 fn resolve(&self, gctx: &GlobalContext) -> PathBuf {
2475 self.resolve_path(gctx)
2476 }
2477}
2478
2479#[tracing::instrument(skip_all)]
2482fn unique_build_targets(
2483 targets: &[Target],
2484 package_root: &Path,
2485) -> Result<(), HashMap<PathBuf, Vec<Target>>> {
2486 let mut source_targets = HashMap::<_, Vec<_>>::new();
2487 for target in targets {
2488 if let TargetSourcePath::Path(path) = target.src_path() {
2489 let full = package_root.join(path);
2490 source_targets.entry(full).or_default().push(target.clone());
2491 }
2492 }
2493
2494 let conflict_targets = source_targets
2495 .into_iter()
2496 .filter(|(_, targets)| targets.len() > 1)
2497 .collect::<HashMap<_, _>>();
2498
2499 if !conflict_targets.is_empty() {
2500 return Err(conflict_targets);
2501 }
2502
2503 Ok(())
2504}
2505
2506fn validate_profiles(
2511 profiles: &manifest::TomlProfiles,
2512 cli_unstable: &CliUnstable,
2513 features: &Features,
2514 warnings: &mut Vec<String>,
2515) -> CargoResult<()> {
2516 for (name, profile) in &profiles.0 {
2517 validate_profile(profile, name, cli_unstable, features, warnings)?;
2518 }
2519 Ok(())
2520}
2521
2522pub fn validate_profile(
2524 root: &manifest::TomlProfile,
2525 name: &str,
2526 cli_unstable: &CliUnstable,
2527 features: &Features,
2528 warnings: &mut Vec<String>,
2529) -> CargoResult<()> {
2530 validate_profile_layer(root, cli_unstable, features)?;
2531 if let Some(ref profile) = root.build_override {
2532 validate_profile_override(profile, "build-override")?;
2533 validate_profile_layer(profile, cli_unstable, features)?;
2534 }
2535 if let Some(ref packages) = root.package {
2536 for profile in packages.values() {
2537 validate_profile_override(profile, "package")?;
2538 validate_profile_layer(profile, cli_unstable, features)?;
2539 }
2540 }
2541
2542 if let Some(dir_name) = &root.dir_name {
2543 bail!(
2547 "dir-name=\"{}\" in profile `{}` is not currently allowed, \
2548 directory names are tied to the profile name for custom profiles",
2549 dir_name,
2550 name
2551 );
2552 }
2553
2554 if matches!(root.inherits.as_deref(), Some("debug")) {
2556 bail!(
2557 "profile.{}.inherits=\"debug\" should be profile.{}.inherits=\"dev\"",
2558 name,
2559 name
2560 );
2561 }
2562
2563 match name {
2564 "doc" => {
2565 warnings.push("profile `doc` is deprecated and has no effect".to_string());
2566 }
2567 "test" | "bench" => {
2568 if root.panic.is_some() {
2569 warnings.push(format!("`panic` setting is ignored for `{}` profile", name))
2570 }
2571 }
2572 _ => {}
2573 }
2574
2575 if let Some(panic) = &root.panic {
2576 if panic != "unwind" && panic != "abort" && panic != "immediate-abort" {
2577 bail!(
2578 "`panic` setting of `{}` is not a valid setting, \
2579 must be `unwind`, `abort`, or `immediate-abort`.",
2580 panic
2581 );
2582 }
2583 }
2584
2585 if let Some(manifest::StringOrBool::String(arg)) = &root.lto {
2586 if arg == "true" || arg == "false" {
2587 bail!(
2588 "`lto` setting of string `\"{arg}\"` for `{name}` profile is not \
2589 a valid setting, must be a boolean (`true`/`false`) or a string \
2590 (`\"thin\"`/`\"fat\"`/`\"off\"`) or omitted.",
2591 );
2592 }
2593 }
2594
2595 if let Some(frame_pointers) = &root.frame_pointers {
2596 if frame_pointers != "force-on"
2597 && frame_pointers != "force-off"
2598 && frame_pointers != "default"
2599 {
2600 bail!(
2601 "`frame-pointers` setting of `{frame_pointers}` is not a valid setting, \
2602 must be `\"force-on\"`, `\"force-off\"`, or `\"default\"`.",
2603 );
2604 }
2605 }
2606
2607 Ok(())
2608}
2609
2610fn validate_profile_layer(
2614 profile: &manifest::TomlProfile,
2615 cli_unstable: &CliUnstable,
2616 features: &Features,
2617) -> CargoResult<()> {
2618 if profile.codegen_backend.is_some() {
2619 match (
2620 features.require(Feature::codegen_backend()),
2621 cli_unstable.codegen_backend,
2622 ) {
2623 (Err(e), false) => return Err(e),
2624 _ => {}
2625 }
2626 }
2627 if profile.rustflags.is_some() {
2628 match (
2629 features.require(Feature::profile_rustflags()),
2630 cli_unstable.profile_rustflags,
2631 ) {
2632 (Err(e), false) => return Err(e),
2633 _ => {}
2634 }
2635 }
2636 if profile.trim_paths.is_some() {
2637 match (
2638 features.require(Feature::trim_paths()),
2639 cli_unstable.trim_paths,
2640 ) {
2641 (Err(e), false) => return Err(e),
2642 _ => {}
2643 }
2644 }
2645 if profile.panic.as_deref() == Some("immediate-abort") {
2646 match (
2647 features.require(Feature::panic_immediate_abort()),
2648 cli_unstable.panic_immediate_abort,
2649 ) {
2650 (Err(e), false) => return Err(e),
2651 _ => {}
2652 }
2653 }
2654 Ok(())
2655}
2656
2657fn validate_profile_override(profile: &manifest::TomlProfile, which: &str) -> CargoResult<()> {
2659 if profile.package.is_some() {
2660 bail!("package-specific profiles cannot be nested");
2661 }
2662 if profile.build_override.is_some() {
2663 bail!("build-override profiles cannot be nested");
2664 }
2665 if profile.panic.is_some() {
2666 bail!("`panic` may not be specified in a `{}` profile", which)
2667 }
2668 if profile.lto.is_some() {
2669 bail!("`lto` may not be specified in a `{}` profile", which)
2670 }
2671 if profile.rpath.is_some() {
2672 bail!("`rpath` may not be specified in a `{}` profile", which)
2673 }
2674 Ok(())
2675}
2676
2677fn verify_lints(
2678 lints: Option<&manifest::TomlLints>,
2679 gctx: &GlobalContext,
2680 warnings: &mut Vec<String>,
2681) -> CargoResult<()> {
2682 let Some(lints) = lints else {
2683 return Ok(());
2684 };
2685
2686 for (tool, lints) in lints {
2687 let supported = ["cargo", "clippy", "rust", "rustdoc"];
2688 if !supported.contains(&tool.as_str()) {
2689 let message = format!(
2690 "unrecognized lint tool `lints.{tool}`, specifying unrecognized tools may break in the future.
2691supported tools: {}",
2692 supported.join(", "),
2693 );
2694 warnings.push(message);
2695 continue;
2696 }
2697 if tool == "cargo" && !gctx.cli_unstable().cargo_lints {
2698 warn_for_cargo_lint_feature(gctx, warnings);
2699 }
2700 for (name, config) in lints {
2701 if let Some((prefix, suffix)) = name.split_once("::") {
2702 if tool == prefix {
2703 anyhow::bail!(
2704 "`lints.{tool}.{name}` is not valid lint name; try `lints.{prefix}.{suffix}`"
2705 )
2706 } else if tool == "rust" && supported.contains(&prefix) {
2707 anyhow::bail!(
2708 "`lints.{tool}.{name}` is not valid lint name; try `lints.{prefix}.{suffix}`"
2709 )
2710 } else {
2711 anyhow::bail!("`lints.{tool}.{name}` is not a valid lint name")
2712 }
2713 } else if let Some(config) = config.config() {
2714 for config_name in config.keys() {
2715 let expected = EXPECTED_LINT_CONFIG.contains(&(tool, name, config_name));
2718 if !expected {
2719 let message =
2720 format!("unused manifest key: `lints.{tool}.{name}.{config_name}`");
2721 warnings.push(message);
2722 }
2723 }
2724 }
2725 }
2726 }
2727
2728 Ok(())
2729}
2730
2731static EXPECTED_LINT_CONFIG: &[(&str, &str, &str)] = &[
2732 ("cargo", "unused_dependencies", "ignore"),
2733 ("rust", "unexpected_cfgs", "check-cfg"),
2735];
2736
2737fn warn_for_cargo_lint_feature(gctx: &GlobalContext, warnings: &mut Vec<String>) {
2738 use std::fmt::Write as _;
2739
2740 let key_name = "lints.cargo";
2741 let feature_name = "cargo-lints";
2742
2743 let mut message = String::new();
2744
2745 let _ = write!(
2746 message,
2747 "unused manifest key `{key_name}` (may be supported in a future version)"
2748 );
2749 if gctx.nightly_features_allowed {
2750 let _ = write!(
2751 message,
2752 "
2753
2754consider passing `-Z{feature_name}` to enable this feature."
2755 );
2756 } else {
2757 let _ = write!(
2758 message,
2759 "
2760
2761this Cargo does not support nightly features, but if you
2762switch to nightly channel you can pass
2763`-Z{feature_name}` to enable this feature.",
2764 );
2765 }
2766 warnings.push(message);
2767}
2768
2769fn lints_to_rustflags(lints: &manifest::TomlLints) -> CargoResult<Vec<String>> {
2770 let mut rustflags = lints
2771 .iter()
2772 .filter(|(tool, _)| tool != &"cargo")
2774 .flat_map(|(tool, lints)| {
2775 lints.iter().map(move |(name, config)| {
2776 let flag = match config.level() {
2777 manifest::TomlLintLevel::Forbid => "--forbid",
2778 manifest::TomlLintLevel::Deny => "--deny",
2779 manifest::TomlLintLevel::Warn => "--warn",
2780 manifest::TomlLintLevel::Allow => "--allow",
2781 };
2782
2783 let option = if tool == "rust" {
2784 format!("{flag}={name}")
2785 } else {
2786 format!("{flag}={tool}::{name}")
2787 };
2788 (
2789 config.priority(),
2790 std::cmp::Reverse(name),
2793 option,
2794 )
2795 })
2796 })
2797 .collect::<Vec<_>>();
2798 rustflags.sort();
2799
2800 let mut rustflags: Vec<_> = rustflags.into_iter().map(|(_, _, option)| option).collect();
2801
2802 if let Some(rust_lints) = lints.get("rust") {
2804 if let Some(unexpected_cfgs) = rust_lints.get("unexpected_cfgs") {
2805 if let Some(config) = unexpected_cfgs.config() {
2806 if let Some(check_cfg) = config.get("check-cfg") {
2807 if let Ok(check_cfgs) = toml::Value::try_into::<Vec<String>>(check_cfg.clone())
2808 {
2809 for check_cfg in check_cfgs {
2810 rustflags.push("--check-cfg".to_string());
2811 rustflags.push(check_cfg);
2812 }
2813 } else {
2815 bail!("`lints.rust.unexpected_cfgs.check-cfg` must be a list of string");
2816 }
2817 }
2818 }
2819 }
2820 }
2821
2822 Ok(rustflags)
2823}
2824
2825fn emit_frontmatter_diagnostic(
2826 e: crate::util::frontmatter::FrontmatterError,
2827 contents: &str,
2828 manifest_file: &Path,
2829 gctx: &GlobalContext,
2830) -> anyhow::Error {
2831 let primary_span = e.primary_span();
2832
2833 let manifest_path = diff_paths(manifest_file, gctx.cwd())
2835 .unwrap_or_else(|| manifest_file.to_path_buf())
2836 .display()
2837 .to_string();
2838 let group = Group::with_title(Level::ERROR.primary_title(e.message())).element(
2839 Snippet::source(contents)
2840 .path(manifest_path)
2841 .annotation(AnnotationKind::Primary.span(primary_span))
2842 .annotations(
2843 e.visible_spans()
2844 .iter()
2845 .map(|s| AnnotationKind::Visible.span(s.clone())),
2846 ),
2847 );
2848
2849 if let Err(err) = gctx.shell().print_report(&[group], true) {
2850 return err.into();
2851 }
2852 return AlreadyPrintedError::new(e.into()).into();
2853}
2854
2855fn emit_toml_diagnostic(
2856 e: toml::de::Error,
2857 contents: &str,
2858 manifest_file: &Path,
2859 gctx: &GlobalContext,
2860) -> anyhow::Error {
2861 let Some(span) = e.span() else {
2862 return e.into();
2863 };
2864
2865 let manifest_path = diff_paths(manifest_file, gctx.cwd())
2867 .unwrap_or_else(|| manifest_file.to_path_buf())
2868 .display()
2869 .to_string();
2870 let group = Group::with_title(Level::ERROR.primary_title(e.message())).element(
2871 Snippet::source(contents)
2872 .path(manifest_path)
2873 .annotation(AnnotationKind::Primary.span(span)),
2874 );
2875
2876 if let Err(err) = gctx.shell().print_report(&[group], true) {
2877 return err.into();
2878 }
2879 return AlreadyPrintedError::new(e.into()).into();
2880}
2881
2882fn deprecated_underscore<T>(
2884 old: &Option<T>,
2885 new: &Option<T>,
2886 new_path: &str,
2887 name: &str,
2888 kind: &str,
2889 edition: Edition,
2890 warnings: &mut Vec<String>,
2891) -> CargoResult<()> {
2892 let old_path = new_path.replace("-", "_");
2893 if old.is_some() && Edition::Edition2024 <= edition {
2894 anyhow::bail!(
2895 "`{old_path}` is unsupported as of the 2024 edition; instead use `{new_path}`\n(in the `{name}` {kind})"
2896 );
2897 } else if old.is_some() && new.is_some() {
2898 warnings.push(format!(
2899 "`{old_path}` is redundant with `{new_path}`, preferring `{new_path}` in the `{name}` {kind}"
2900 ))
2901 } else if old.is_some() {
2902 warnings.push(format!(
2903 "`{old_path}` is deprecated in favor of `{new_path}` and will not work in the 2024 edition\n(in the `{name}` {kind})"
2904 ))
2905 }
2906 Ok(())
2907}
2908
2909fn warn_on_unused(unused: &BTreeSet<String>, warnings: &mut Vec<String>) {
2910 use std::fmt::Write as _;
2911
2912 for key in unused {
2913 let mut message = format!("unused manifest key: {}", key);
2914 if TOP_LEVEL_CONFIG_KEYS.iter().any(|c| c == key) {
2915 write!(
2916 &mut message,
2917 "\nhelp: {key} is a valid .cargo/config.toml key"
2918 )
2919 .unwrap();
2920 }
2921 warnings.push(message);
2922 }
2923}
2924
2925fn unused_dep_keys(
2926 dep_name: &str,
2927 kind: &str,
2928 unused_keys: Vec<String>,
2929 warnings: &mut Vec<String>,
2930) {
2931 for unused in unused_keys {
2932 let key = format!("unused manifest key: {kind}.{dep_name}.{unused}");
2933 warnings.push(key);
2934 }
2935}
2936
2937pub fn prepare_for_publish(
2939 me: &Package,
2940 ws: &Workspace<'_>,
2941 packaged_files: Option<&[PathBuf]>,
2942) -> CargoResult<Package> {
2943 let contents = me.manifest().contents();
2944 let document = me.manifest().document();
2945 let original_toml = prepare_toml_for_publish(
2946 me.manifest().normalized_toml(),
2947 ws,
2948 me.root(),
2949 packaged_files,
2950 )?;
2951 let normalized_toml = original_toml.clone();
2952 let features = me.manifest().unstable_features().clone();
2953 let workspace_config = me.manifest().workspace_config().clone();
2954 let source_id = me.package_id().source_id();
2955 let mut warnings = Default::default();
2956 let mut errors = Default::default();
2957 let gctx = ws.gctx();
2958 let manifest = to_real_manifest(
2959 contents.map(|c| c.to_owned()),
2960 document.cloned(),
2961 original_toml,
2962 normalized_toml,
2963 features,
2964 workspace_config,
2965 source_id,
2966 me.manifest_path(),
2967 me.manifest().is_embedded(),
2968 gctx,
2969 &mut warnings,
2970 &mut errors,
2971 )?;
2972 let new_pkg = Package::new(manifest, me.manifest_path());
2973 Ok(new_pkg)
2974}
2975
2976fn prepare_toml_for_publish(
2980 me: &manifest::TomlManifest,
2981 ws: &Workspace<'_>,
2982 package_root: &Path,
2983 packaged_files: Option<&[PathBuf]>,
2984) -> CargoResult<manifest::TomlManifest> {
2985 let gctx = ws.gctx();
2986
2987 if me
2988 .cargo_features
2989 .iter()
2990 .flat_map(|f| f.iter())
2991 .any(|f| f == "open-namespaces")
2992 {
2993 anyhow::bail!("cannot publish with `open-namespaces`")
2994 }
2995
2996 let mut package = me.package().unwrap().clone();
2997 package.workspace = None;
2998 if let Some(custom_build_scripts) = package.normalized_build().expect("previously normalized") {
3000 let mut included_scripts = Vec::new();
3001 for script in custom_build_scripts {
3002 let path = Path::new(script).to_path_buf();
3003 let included = packaged_files.map(|i| i.contains(&path)).unwrap_or(true);
3004 if included {
3005 let path = path
3006 .into_os_string()
3007 .into_string()
3008 .map_err(|_err| anyhow::format_err!("non-UTF8 `package.build`"))?;
3009 let path = normalize_path_string_sep(path);
3010 included_scripts.push(path);
3011 } else {
3012 ws.gctx().shell().warn(format!(
3013 "ignoring `package.build` entry `{}` as it is not included in the published package",
3014 path.display()
3015 ))?;
3016 }
3017 }
3018
3019 package.build = Some(match included_scripts.len() {
3020 0 => TomlPackageBuild::Auto(false),
3021 1 => TomlPackageBuild::SingleScript(included_scripts[0].clone()),
3022 _ => TomlPackageBuild::MultipleScript(included_scripts),
3023 });
3024 }
3025 let current_resolver = package
3026 .resolver
3027 .as_ref()
3028 .map(|r| ResolveBehavior::from_manifest(r))
3029 .unwrap_or_else(|| {
3030 package
3031 .edition
3032 .as_ref()
3033 .and_then(|e| e.as_value())
3034 .map(|e| Edition::from_str(e))
3035 .unwrap_or(Ok(Edition::Edition2015))
3036 .map(|e| e.default_resolve_behavior())
3037 })?;
3038 if ws.resolve_behavior() != current_resolver {
3039 package.resolver = Some(ws.resolve_behavior().to_manifest());
3044 }
3045 if let Some(license_file) = &package.license_file {
3046 let license_file = license_file
3047 .as_value()
3048 .context("license file should have been resolved before `prepare_for_publish()`")?;
3049 let license_path = Path::new(&license_file);
3050 let abs_license_path = paths::normalize_path(&package_root.join(license_path));
3051 if let Ok(license_file) = abs_license_path.strip_prefix(package_root) {
3052 package.license_file = Some(manifest::InheritableField::Value(
3053 normalize_path_string_sep(
3054 license_file
3055 .to_str()
3056 .ok_or_else(|| anyhow::format_err!("non-UTF8 `package.license-file`"))?
3057 .to_owned(),
3058 ),
3059 ));
3060 } else {
3061 package.license_file = Some(manifest::InheritableField::Value(
3064 license_path
3065 .file_name()
3066 .unwrap()
3067 .to_str()
3068 .unwrap()
3069 .to_string(),
3070 ));
3071 }
3072 }
3073
3074 if let Some(readme) = &package.readme {
3075 let readme = readme
3076 .as_value()
3077 .context("readme should have been resolved before `prepare_for_publish()`")?;
3078 match readme {
3079 manifest::StringOrBool::String(readme) => {
3080 let readme_path = Path::new(&readme);
3081 let abs_readme_path = paths::normalize_path(&package_root.join(readme_path));
3082 if let Ok(readme_path) = abs_readme_path.strip_prefix(package_root) {
3083 package.readme = Some(manifest::InheritableField::Value(StringOrBool::String(
3084 normalize_path_string_sep(
3085 readme_path
3086 .to_str()
3087 .ok_or_else(|| {
3088 anyhow::format_err!("non-UTF8 `package.license-file`")
3089 })?
3090 .to_owned(),
3091 ),
3092 )));
3093 } else {
3094 package.readme = Some(manifest::InheritableField::Value(
3097 manifest::StringOrBool::String(
3098 readme_path
3099 .file_name()
3100 .unwrap()
3101 .to_str()
3102 .unwrap()
3103 .to_string(),
3104 ),
3105 ));
3106 }
3107 }
3108 manifest::StringOrBool::Bool(_) => {}
3109 }
3110 }
3111
3112 let lib = if let Some(target) = &me.lib {
3113 prepare_target_for_publish(target, packaged_files, "library", ws.gctx())?
3114 } else {
3115 None
3116 };
3117 let bin = prepare_targets_for_publish(me.bin.as_ref(), packaged_files, "binary", ws.gctx())?;
3118 let example =
3119 prepare_targets_for_publish(me.example.as_ref(), packaged_files, "example", ws.gctx())?;
3120 let test = prepare_targets_for_publish(me.test.as_ref(), packaged_files, "test", ws.gctx())?;
3121 let bench =
3122 prepare_targets_for_publish(me.bench.as_ref(), packaged_files, "benchmark", ws.gctx())?;
3123
3124 let all = |_d: &manifest::TomlDependency| true;
3125 let mut manifest = manifest::TomlManifest {
3126 cargo_features: me.cargo_features.clone(),
3127 package: Some(package),
3128 project: None,
3129 badges: me.badges.clone(),
3130 features: me.features.clone(),
3131 lib,
3132 bin,
3133 example,
3134 test,
3135 bench,
3136 dependencies: map_deps(gctx, me.dependencies.as_ref(), all)?,
3137 dev_dependencies: map_deps(
3138 gctx,
3139 me.dev_dependencies(),
3140 manifest::TomlDependency::is_version_specified,
3141 )?,
3142 dev_dependencies2: None,
3143 build_dependencies: map_deps(gctx, me.build_dependencies(), all)?,
3144 build_dependencies2: None,
3145 target: match me.target.as_ref().map(|target_map| {
3146 target_map
3147 .iter()
3148 .map(|(k, v)| {
3149 Ok((
3150 k.clone(),
3151 manifest::TomlPlatform {
3152 dependencies: map_deps(gctx, v.dependencies.as_ref(), all)?,
3153 dev_dependencies: map_deps(
3154 gctx,
3155 v.dev_dependencies(),
3156 manifest::TomlDependency::is_version_specified,
3157 )?,
3158 dev_dependencies2: None,
3159 build_dependencies: map_deps(gctx, v.build_dependencies(), all)?,
3160 build_dependencies2: None,
3161 },
3162 ))
3163 })
3164 .collect()
3165 }) {
3166 Some(Ok(v)) => Some(v),
3167 Some(Err(e)) => return Err(e),
3168 None => None,
3169 },
3170 lints: me.lints.clone(),
3171 hints: me.hints.clone(),
3172 workspace: None,
3173 profile: me.profile.clone(),
3174 patch: None,
3175 replace: None,
3176 _unused_keys: Default::default(),
3177 };
3178 strip_features(&mut manifest);
3179 return Ok(manifest);
3180
3181 fn strip_features(manifest: &mut TomlManifest) {
3182 fn insert_dep_name(
3183 dep_name_set: &mut BTreeSet<manifest::PackageName>,
3184 deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
3185 ) {
3186 let Some(deps) = deps else {
3187 return;
3188 };
3189 deps.iter().for_each(|(k, _v)| {
3190 dep_name_set.insert(k.clone());
3191 });
3192 }
3193 let mut dep_name_set = BTreeSet::new();
3194 insert_dep_name(&mut dep_name_set, manifest.dependencies.as_ref());
3195 insert_dep_name(&mut dep_name_set, manifest.dev_dependencies());
3196 insert_dep_name(&mut dep_name_set, manifest.build_dependencies());
3197 if let Some(target_map) = manifest.target.as_ref() {
3198 target_map.iter().for_each(|(_k, v)| {
3199 insert_dep_name(&mut dep_name_set, v.dependencies.as_ref());
3200 insert_dep_name(&mut dep_name_set, v.dev_dependencies());
3201 insert_dep_name(&mut dep_name_set, v.build_dependencies());
3202 });
3203 }
3204 let features = manifest.features.as_mut();
3205
3206 let Some(features) = features else {
3207 return;
3208 };
3209
3210 features.values_mut().for_each(|feature_deps| {
3211 feature_deps.retain(|feature_dep| {
3212 let feature_value = FeatureValue::new(feature_dep.into());
3213 match feature_value {
3214 FeatureValue::Dep { dep_name } | FeatureValue::DepFeature { dep_name, .. } => {
3215 let k = &manifest::PackageName::new(dep_name.to_string()).unwrap();
3216 dep_name_set.contains(k)
3217 }
3218 _ => true,
3219 }
3220 });
3221 });
3222 }
3223
3224 fn map_deps(
3225 gctx: &GlobalContext,
3226 deps: Option<&BTreeMap<manifest::PackageName, manifest::InheritableDependency>>,
3227 filter: impl Fn(&manifest::TomlDependency) -> bool,
3228 ) -> CargoResult<Option<BTreeMap<manifest::PackageName, manifest::InheritableDependency>>> {
3229 let Some(deps) = deps else {
3230 return Ok(None);
3231 };
3232 let deps = deps
3233 .iter()
3234 .filter(|(_k, v)| {
3235 if let manifest::InheritableDependency::Value(def) = v {
3236 filter(def)
3237 } else {
3238 false
3239 }
3240 })
3241 .map(|(k, v)| Ok((k.clone(), map_dependency(gctx, v)?)))
3242 .collect::<CargoResult<BTreeMap<_, _>>>()?;
3243 Ok(Some(deps))
3244 }
3245
3246 fn map_dependency(
3247 gctx: &GlobalContext,
3248 dep: &manifest::InheritableDependency,
3249 ) -> CargoResult<manifest::InheritableDependency> {
3250 let dep = match dep {
3251 manifest::InheritableDependency::Value(manifest::TomlDependency::Detailed(d)) => {
3252 let mut d = d.clone();
3253 d.path.take();
3255 d.base.take();
3256 d.git.take();
3258 d.branch.take();
3259 d.tag.take();
3260 d.rev.take();
3261 if let Some(registry) = d.registry.take() {
3263 d.registry_index = Some(gctx.get_registry_index(®istry)?.to_string());
3264 }
3265 Ok(d)
3266 }
3267 manifest::InheritableDependency::Value(manifest::TomlDependency::Simple(s)) => {
3268 Ok(manifest::TomlDetailedDependency {
3269 version: Some(s.clone()),
3270 ..Default::default()
3271 })
3272 }
3273 _ => unreachable!(),
3274 };
3275 dep.map(manifest::TomlDependency::Detailed)
3276 .map(manifest::InheritableDependency::Value)
3277 }
3278}
3279
3280pub fn prepare_targets_for_publish(
3281 targets: Option<&Vec<manifest::TomlTarget>>,
3282 packaged_files: Option<&[PathBuf]>,
3283 context: &str,
3284 gctx: &GlobalContext,
3285) -> CargoResult<Option<Vec<manifest::TomlTarget>>> {
3286 let Some(targets) = targets else {
3287 return Ok(None);
3288 };
3289
3290 let mut prepared = Vec::with_capacity(targets.len());
3291 for target in targets {
3292 let Some(target) = prepare_target_for_publish(target, packaged_files, context, gctx)?
3293 else {
3294 continue;
3295 };
3296 prepared.push(target);
3297 }
3298
3299 if prepared.is_empty() {
3300 Ok(None)
3301 } else {
3302 Ok(Some(prepared))
3303 }
3304}
3305
3306pub fn prepare_target_for_publish(
3307 target: &manifest::TomlTarget,
3308 packaged_files: Option<&[PathBuf]>,
3309 context: &str,
3310 gctx: &GlobalContext,
3311) -> CargoResult<Option<manifest::TomlTarget>> {
3312 let path = target.path.as_ref().expect("previously normalized");
3313 let path = &path.0;
3314 if let Some(packaged_files) = packaged_files {
3315 if !packaged_files.contains(&path) {
3316 let name = target.name.as_ref().expect("previously normalized");
3317 gctx.shell().warn(format!(
3318 "ignoring {context} `{name}` as `{}` is not included in the published package",
3319 path.display()
3320 ))?;
3321 return Ok(None);
3322 }
3323 }
3324
3325 let mut target = target.clone();
3326 let path = normalize_path_sep(path.to_path_buf(), context)?;
3327 target.path = Some(manifest::PathValue(path.into()));
3328
3329 Ok(Some(target))
3330}
3331
3332fn normalize_path_sep(path: PathBuf, context: &str) -> CargoResult<PathBuf> {
3333 let path = path
3334 .into_os_string()
3335 .into_string()
3336 .map_err(|_err| anyhow::format_err!("non-UTF8 path for {context}"))?;
3337 let path = normalize_path_string_sep(path);
3338 Ok(path.into())
3339}
3340
3341pub fn normalize_path_string_sep(path: String) -> String {
3342 if std::path::MAIN_SEPARATOR != '/' {
3343 path.replace(std::path::MAIN_SEPARATOR, "/")
3344 } else {
3345 path
3346 }
3347}