Skip to main content

raf_source/
manifest.rs

1// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! The parts of a `Cargo.toml` that package discovery reads.
5//!
6//! The supplied native TOML arena honours comments, single-quoted strings,
7//! dotted keys and inline tables. Explicit model and depth admission turns
8//! excessive nesting into an error and not a crash. Every wrong value
9//! is an error that names its key.
10
11use std::collections::BTreeMap;
12
13pub(crate) mod native;
14use native::field as get;
15use purrdf_toml::{Document, Kind, Node, Scalar};
16
17/// A manifest problem: what is wrong, and the key when one is at fault.
18#[derive(Debug)]
19pub(crate) struct ManifestError {
20    pub(crate) message: String,
21    pub(crate) key: Option<String>,
22    pub(crate) source: Option<Box<purrdf_toml::TomlError>>,
23}
24
25/// The most entries `workspace.members` may have.
26pub(crate) const MAX_MEMBERS: usize = 4096;
27
28/// The most entries `workspace.exclude` may have.
29pub(crate) const MAX_EXCLUDES: usize = 4096;
30
31fn at_key(key: &str, message: impl Into<String>) -> ManifestError {
32    ManifestError {
33        message: message.into(),
34        key: Some(key.to_owned()),
35        source: None,
36    }
37}
38
39/// How `package.build` names the build script.
40#[derive(Debug, PartialEq, Eq)]
41pub(crate) enum Build {
42    /// `build.rs` when it exists.
43    Default,
44    /// `build = false`.
45    Disabled,
46    /// `build = "path"`.
47    Path(String),
48}
49
50/// Where a package gets its edition.
51#[derive(Debug, PartialEq, Eq)]
52pub(crate) enum EditionDecl {
53    /// `edition = "2021"`.
54    Explicit(u16),
55    /// `edition.workspace = true`.
56    Inherited,
57    /// No `edition` key, which cargo reads as 2015.
58    Unset,
59}
60
61/// Package version evidence, without synthesizing a missing identity.
62#[derive(Debug, PartialEq, Eq)]
63pub(crate) enum VersionDecl {
64    Explicit(String),
65    Inherited,
66    Unset,
67}
68
69/// The table a dependency is declared in.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum DependencyKind {
72    /// `[dependencies]`.
73    Normal,
74    /// `[dev-dependencies]`.
75    Dev,
76    /// `[build-dependencies]`.
77    Build,
78}
79
80/// One dependency of a package, from any of its tables, the `[target.*]`
81/// ones included.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub(crate) struct Dependency {
84    /// The table and name, such as `dependencies.helper`, for messages.
85    pub(crate) key: String,
86    /// The table it is declared in.
87    pub(crate) kind: DependencyKind,
88    /// The name it is declared under.
89    pub(crate) name: String,
90    /// `package = ".."`: the package the entry renames, when it renames one.
91    pub(crate) package: Option<String>,
92    /// Where the dependency gets its directory, when it names one.
93    pub(crate) path: Option<PathSource>,
94    pub(crate) declaration: DependencyDeclaration,
95}
96
97/// Written dependency constraints, not evidence of activation or source provenance.
98///
99/// Optional flags retain the distinction between omission and an explicit value.
100/// Cargo version requirements are validated without allocation and retain their
101/// written spelling. Git selectors remain declarations, not resolved commits.
102#[derive(Debug, Clone, Default, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct DependencySpec {
105    /// Renamed package, when explicitly declared.
106    pub package: Option<String>,
107    /// Written version requirement.
108    pub version: Option<String>,
109    /// Path relative to the declaring manifest.
110    pub path: Option<String>,
111    /// Named registry; resolving Cargo configuration is a separate operation.
112    pub registry: Option<String>,
113    /// Explicit registry index, when supplied.
114    pub registry_index: Option<String>,
115    /// Git repository spelling.
116    pub git: Option<String>,
117    /// Git revision selector, which need not be a complete commit hash.
118    pub rev: Option<String>,
119    /// Git branch selector.
120    pub branch: Option<String>,
121    /// Git tag selector.
122    pub tag: Option<String>,
123    /// Explicit optional-dependency setting.
124    pub optional: Option<bool>,
125    /// Explicit default-feature setting.
126    pub default_features: Option<bool>,
127    /// Requested features, without computing feature unification.
128    pub features: Vec<String>,
129    /// Whether this entry inherits from `workspace.dependencies`.
130    pub workspace: bool,
131}
132
133impl DependencySpec {
134    pub(crate) fn heap_bytes(&self) -> usize {
135        [
136            &self.package,
137            &self.version,
138            &self.path,
139            &self.registry,
140            &self.registry_index,
141            &self.git,
142            &self.rev,
143            &self.branch,
144            &self.tag,
145        ]
146        .into_iter()
147        .flatten()
148        .map(String::len)
149        .fold(
150            self.features.len().saturating_mul(size_of::<String>()),
151            usize::saturating_add,
152        )
153        .saturating_add(self.features.iter().map(String::len).sum::<usize>())
154    }
155}
156
157/// The workspace entry inherited by a dependency, retaining its declaring base.
158#[derive(Debug, Clone, PartialEq, Eq)]
159#[non_exhaustive]
160pub struct InheritedDependency {
161    /// Manifest whose `workspace.dependencies` supplies the constraints and path base.
162    pub manifest: crate::RelPath,
163    /// The workspace entry, before combining local features or flags.
164    pub specification: DependencySpec,
165}
166
167/// One package dependency declaration, including its unevaluated target condition.
168#[derive(Debug, Clone, PartialEq, Eq)]
169#[non_exhaustive]
170pub struct DependencyDeclaration {
171    /// Original manifest key, useful for diagnostics.
172    pub key: String,
173    /// Dependency table kind.
174    pub kind: DependencyKind,
175    /// Written dependency alias, before Rust's hyphen normalization.
176    pub name: String,
177    /// Written target triple or `cfg(...)` table key; not an activation decision.
178    pub condition: Option<String>,
179    /// Constraints written in the package manifest.
180    pub specification: DependencySpec,
181    /// Resolved workspace declaration, when inheritance was requested.
182    pub inherited: Option<InheritedDependency>,
183}
184
185/// Where a path dependency gets its directory.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub(crate) enum PathSource {
188    /// `path = ".."`, relative to the manifest's directory.
189    Own(String),
190    /// `workspace = true`: the dependency of that name in
191    /// `[workspace.dependencies]`, relative to the workspace manifest.
192    Workspace(String),
193}
194
195/// An entry of `[workspace.dependencies]`.
196#[derive(Debug, Clone, Default, PartialEq, Eq)]
197pub(crate) struct WorkspaceDependency {
198    /// Its `path`, relative to the workspace manifest.
199    pub(crate) path: Option<String>,
200    /// `package = ".."`, when it renames a package.
201    pub(crate) package: Option<String>,
202    pub(crate) specification: DependencySpec,
203}
204
205/// The test settings of a target table, each `None` (or empty) when the
206/// table leaves it to cargo's default.
207#[derive(Debug, Default)]
208pub(crate) struct TargetSettings {
209    /// `harness`.
210    pub(crate) harness: Option<bool>,
211    /// `required-features`.
212    pub(crate) required_features: Vec<String>,
213    /// `test`.
214    pub(crate) test: Option<bool>,
215    /// `doctest`.
216    pub(crate) doctest: Option<bool>,
217}
218
219/// A `[lib]` table.
220#[derive(Debug, Default)]
221pub(crate) struct LibDecl {
222    pub(crate) name: Option<String>,
223    pub(crate) path: Option<String>,
224    pub(crate) settings: TargetSettings,
225}
226
227/// One `[[bin]]`, `[[test]]`, `[[bench]]` or `[[example]]` table.
228#[derive(Debug)]
229pub(crate) struct TargetDecl {
230    pub(crate) name: Option<String>,
231    pub(crate) path: Option<String>,
232    pub(crate) settings: TargetSettings,
233}
234
235/// The `[package]` table.
236#[derive(Debug)]
237pub(crate) struct PackageDecl {
238    pub(crate) name: String,
239    pub(crate) version: VersionDecl,
240    /// The tables (`bin`, `test`, `bench`, `example`) whose automatic
241    /// discovery `autobins = false` and its siblings, `autolib` included, turned off.
242    pub(crate) auto_off: Vec<&'static str>,
243    pub(crate) build: Build,
244    pub(crate) edition: EditionDecl,
245}
246
247impl PackageDecl {
248    /// True unless `auto<table>s = false` turned discovery off.
249    pub(crate) fn auto(&self, table: &str) -> bool {
250        !self.auto_off.contains(&table)
251    }
252}
253
254/// A parsed manifest.
255#[derive(Debug)]
256pub(crate) struct Manifest {
257    /// Complete local Cargo feature declarations, before activation.
258    pub(crate) features: BTreeMap<String, Vec<String>>,
259    pub(crate) package: Option<PackageDecl>,
260    pub(crate) has_workspace: bool,
261    pub(crate) package_workspace: Option<String>,
262    /// `[workspace.package] edition`, for the packages that inherit it.
263    pub(crate) workspace_edition: Option<u16>,
264    pub(crate) workspace_version: Option<String>,
265    /// `workspace.members`, when the manifest has a `[workspace]` table.
266    pub(crate) members: Vec<String>,
267    /// The dependencies of the package, in all dependency tables.
268    pub(crate) dependencies: Vec<Dependency>,
269    /// The `[workspace.dependencies]` entries, by name.
270    pub(crate) workspace_dependencies: BTreeMap<String, WorkspaceDependency>,
271    /// `workspace.exclude`.
272    pub(crate) exclude: Vec<String>,
273    pub(crate) lib: Option<LibDecl>,
274    pub(crate) bins: Vec<TargetDecl>,
275    pub(crate) tests: Vec<TargetDecl>,
276    pub(crate) benches: Vec<TargetDecl>,
277    pub(crate) examples: Vec<TargetDecl>,
278}
279
280/// An edition such as `2021` as its year.
281fn year(text: &str, key: &str) -> Result<u16, ManifestError> {
282    text.parse()
283        .map_err(|_| at_key(key, "must be a year such as \"2021\""))
284}
285
286fn string(
287    document: &Document<'_>,
288    table: &Node,
289    section: &str,
290    key: &str,
291) -> Result<Option<String>, ManifestError> {
292    match get(document, table, key) {
293        None => Ok(None),
294        Some(Node {
295            kind: Kind::Scalar(Scalar::String(text)),
296            ..
297        }) => Ok(Some(text.clone())),
298        Some(_) => Err(at_key(&format!("{section}.{key}"), "must be a string")),
299    }
300}
301
302fn flag(
303    document: &Document<'_>,
304    table: &Node,
305    section: &str,
306    key: &str,
307) -> Result<bool, ManifestError> {
308    match get(document, table, key) {
309        None => Ok(true),
310        Some(Node {
311            kind: Kind::Scalar(Scalar::Boolean(value)),
312            ..
313        }) => Ok(*value),
314        Some(_) => Err(at_key(&format!("{section}.{key}"), "must be a boolean")),
315    }
316}
317
318fn optional_flag(
319    document: &Document<'_>,
320    table: &Node,
321    section: &str,
322    key: &str,
323) -> Result<Option<bool>, ManifestError> {
324    match get(document, table, key) {
325        None => Ok(None),
326        Some(Node {
327            kind: Kind::Scalar(Scalar::Boolean(value)),
328            ..
329        }) => Ok(Some(*value)),
330        Some(_) => Err(at_key(&format!("{section}.{key}"), "must be a boolean")),
331    }
332}
333
334/// The test settings of the target table `table` of `section`.
335fn settings(
336    document: &Document<'_>,
337    table: &Node,
338    section: &str,
339) -> Result<TargetSettings, ManifestError> {
340    if section == "lib" && get(document, table, "required-features").is_some() {
341        // Cargo refuses the key for a library.
342        return Err(at_key(
343            "lib.required-features",
344            "is not allowed for a library target",
345        ));
346    }
347    let required_features = match get(document, table, "required-features") {
348        None => Vec::new(),
349        Some(Node {
350            kind: Kind::Array | Kind::ArrayOfTables,
351            children: features,
352            ..
353        }) => features
354            .iter()
355            .map(|feature| match &document.nodes()[*feature] {
356                Node {
357                    kind: Kind::Scalar(Scalar::String(name)),
358                    ..
359                } => Ok(name.clone()),
360                _ => Err(at_key(
361                    &format!("{section}.required-features"),
362                    "must be an array of strings",
363                )),
364            })
365            .collect::<Result<_, _>>()?,
366        Some(_) => {
367            return Err(at_key(
368                &format!("{section}.required-features"),
369                "must be an array of strings",
370            ));
371        }
372    };
373    Ok(TargetSettings {
374        harness: optional_flag(document, table, section, "harness")?,
375        required_features,
376        test: optional_flag(document, table, section, "test")?,
377        doctest: optional_flag(document, table, section, "doctest")?,
378    })
379}
380
381fn table_of<'a>(value: &'a Node, key: &str) -> Result<&'a Node, ManifestError> {
382    native::table(value).ok_or_else(|| at_key(key, "must be a table"))
383}
384
385/// The value of `package` in a dependency table at `key`, if it has one.
386fn renamed(
387    document: &Document<'_>,
388    details: &Node,
389    key: &str,
390) -> Result<Option<String>, ManifestError> {
391    match get(document, details, "package") {
392        None => Ok(None),
393        Some(Node {
394            kind: Kind::Scalar(Scalar::String(package)),
395            ..
396        }) => Ok(Some(package.clone())),
397        Some(_) => Err(at_key(key, "`package` must be a string")),
398    }
399}
400
401fn dependency_spec(
402    document: &Document<'_>,
403    value: &Node,
404    key: &str,
405) -> Result<DependencySpec, ManifestError> {
406    let spec = match value {
407        Node {
408            kind: Kind::Scalar(Scalar::String(version)),
409            ..
410        } => DependencySpec {
411            version: Some(version.clone()),
412            ..DependencySpec::default()
413        },
414        table @ Node {
415            kind: Kind::Table(_),
416            ..
417        } => {
418            let features = match get(document, table, "features") {
419                None => Vec::new(),
420                Some(Node {
421                    kind: Kind::Array | Kind::ArrayOfTables,
422                    children: values,
423                    ..
424                }) => values
425                    .iter()
426                    .map(|value| {
427                        native::string(&document.nodes()[*value])
428                            .map(str::to_owned)
429                            .ok_or_else(|| {
430                                at_key(&format!("{key}.features"), "must contain only strings")
431                            })
432                    })
433                    .collect::<Result<Vec<_>, _>>()?,
434                Some(_) => {
435                    return Err(at_key(
436                        &format!("{key}.features"),
437                        "must be an array of strings",
438                    ));
439                }
440            };
441            let workspace = optional_flag(document, table, key, "workspace")?;
442            if workspace == Some(false) {
443                return Err(at_key(
444                    &format!("{key}.workspace"),
445                    "must be true when present",
446                ));
447            }
448            DependencySpec {
449                package: renamed(document, table, key)?,
450                version: string(document, table, key, "version")?,
451                path: string(document, table, key, "path").map_err(|mut error| {
452                    // Path declarations retain their established owning-entry origin.
453                    error.key = Some(key.to_owned());
454                    error.message = format!("`path` {}", error.message);
455                    error
456                })?,
457                registry: string(document, table, key, "registry")?,
458                registry_index: string(document, table, key, "registry-index")?,
459                git: string(document, table, key, "git")?,
460                rev: string(document, table, key, "rev")?,
461                branch: string(document, table, key, "branch")?,
462                tag: string(document, table, key, "tag")?,
463                optional: optional_flag(document, table, key, "optional")?,
464                default_features: optional_flag(document, table, key, "default-features")?,
465                features,
466                workspace: workspace == Some(true),
467            }
468        }
469        _ => return Err(at_key(key, "dependency must be a version string or table")),
470    };
471    validate_dependency_spec(&spec, key)?;
472    Ok(spec)
473}
474
475pub(crate) fn validate_dependency_spec(
476    spec: &DependencySpec,
477    key: &str,
478) -> Result<(), ManifestError> {
479    if let Some(version) = &spec.version {
480        crate::cargo_version::Requirement::parse(version).map_err(|error| {
481            at_key(
482                &format!("{key}.version"),
483                format!("invalid version requirement: {error}"),
484            )
485        })?;
486    }
487    let selectors = [&spec.rev, &spec.branch, &spec.tag]
488        .into_iter()
489        .flatten()
490        .count();
491    if selectors > 1 || (selectors != 0 && spec.git.is_none()) {
492        return Err(at_key(
493            key,
494            "a Git dependency requires `git` and at most one of `rev`, `branch`, or `tag`",
495        ));
496    }
497    if spec.git.is_some()
498        && (spec.path.is_some() || spec.registry.is_some() || spec.registry_index.is_some())
499    {
500        return Err(at_key(
501            key,
502            "`git` cannot be combined with a path or registry",
503        ));
504    }
505    if spec.workspace
506        && [
507            &spec.package,
508            &spec.version,
509            &spec.path,
510            &spec.registry,
511            &spec.registry_index,
512            &spec.git,
513            &spec.rev,
514            &spec.branch,
515            &spec.tag,
516        ]
517        .into_iter()
518        .any(Option::is_some)
519    {
520        return Err(at_key(
521            key,
522            "an inherited dependency cannot override its package or source constraints",
523        ));
524    }
525    Ok(())
526}
527
528/// The dependencies of the three tables of `table`, whose keys start with
529/// `prefix` in messages.
530fn dependency_entries(
531    document: &Document<'_>,
532    table: &Node,
533    prefix: &str,
534    condition: Option<&str>,
535    out: &mut Vec<Dependency>,
536) -> Result<(), ManifestError> {
537    for (section, kind) in [
538        ("dependencies", DependencyKind::Normal),
539        ("dev-dependencies", DependencyKind::Dev),
540        ("build-dependencies", DependencyKind::Build),
541    ] {
542        let Some(value) = get(document, table, section) else {
543            continue;
544        };
545        for (name, entry) in
546            native::entries(document, table_of(value, &format!("{prefix}{section}"))?)
547        {
548            let key = format!("{prefix}{section}.{name}");
549            let specification = dependency_spec(document, entry, &key)?;
550            let path = if specification.workspace {
551                Some(PathSource::Workspace(name.to_owned()))
552            } else {
553                specification.path.clone().map(PathSource::Own)
554            };
555            out.push(Dependency {
556                declaration: DependencyDeclaration {
557                    key: key.clone(),
558                    kind,
559                    name: name.to_owned(),
560                    condition: condition.map(str::to_owned),
561                    specification: specification.clone(),
562                    inherited: None,
563                },
564                key,
565                kind,
566                name: name.to_owned(),
567                package: specification.package,
568                path,
569            });
570        }
571    }
572    Ok(())
573}
574
575/// The dependencies of a manifest: the three tables at the top and the same
576/// three under each `[target.<platform>]`.
577fn dependencies(document: &Document<'_>, root: &Node) -> Result<Vec<Dependency>, ManifestError> {
578    let mut found = Vec::new();
579    dependency_entries(document, root, "", None, &mut found)?;
580    if let Some(targets) = get(document, root, "target") {
581        for (platform, value) in native::entries(document, table_of(targets, "target")?) {
582            let table = table_of(value, &format!("target.{platform}"))?;
583            dependency_entries(
584                document,
585                table,
586                &format!("target.{platform}."),
587                Some(platform),
588                &mut found,
589            )?;
590        }
591    }
592    Ok(found)
593}
594
595fn declarations(
596    document: &Document<'_>,
597    root: &Node,
598    section: &str,
599) -> Result<Vec<TargetDecl>, ManifestError> {
600    let Some(value) = get(document, root, section) else {
601        return Ok(Vec::new());
602    };
603    let rows = native::array(value).ok_or_else(|| at_key(section, "must be an array of tables"))?;
604    rows.iter()
605        .map(|row| {
606            let table = table_of(&document.nodes()[*row], section)?;
607            Ok(TargetDecl {
608                name: string(document, table, section, "name")?,
609                path: string(document, table, section, "path")?,
610                settings: settings(document, table, section)?,
611            })
612        })
613        .collect()
614}
615
616fn workspace_version(
617    document: &Document<'_>,
618    workspace: Option<&Node>,
619) -> Result<Option<String>, ManifestError> {
620    let version = workspace
621        .and_then(|table| get(document, table, "package"))
622        .map(|value| table_of(value, "workspace.package"))
623        .transpose()?
624        .map(|table| string(document, table, "workspace.package", "version"))
625        .transpose()?
626        .flatten();
627    if let Some(version) = &version {
628        validate_version(version, "workspace.package.version")?;
629    }
630    Ok(version)
631}
632
633fn validate_version(version: &str, key: &str) -> Result<(), ManifestError> {
634    crate::cargo_version::Version::parse(version)
635        .map(|_| ())
636        .map_err(|error| at_key(key, format!("invalid package version: {error}")))
637}
638
639fn package(document: &Document<'_>, root: &Node) -> Result<Option<PackageDecl>, ManifestError> {
640    let Some(value) = get(document, root, "package") else {
641        return Ok(None);
642    };
643    let table = table_of(value, "package")?;
644    let name = string(document, table, "package", "name")?
645        .ok_or_else(|| at_key("package.name", "is missing"))?;
646    let version = match get(document, table, "version") {
647        None => VersionDecl::Unset,
648        Some(Node {
649            kind: Kind::Scalar(Scalar::String(version)),
650            ..
651        }) => {
652            validate_version(version, "package.version")?;
653            VersionDecl::Explicit(version.clone())
654        }
655        Some(
656            inherited @ Node {
657                kind: Kind::Table(_),
658                ..
659            },
660        ) if inherited.children.len() == 1
661            && get(document, inherited, "workspace").and_then(native::boolean) == Some(true) =>
662        {
663            VersionDecl::Inherited
664        }
665        Some(_) => {
666            return Err(at_key(
667                "package.version",
668                "must be a version string or `{ workspace = true }`",
669            ));
670        }
671    };
672    let build = match get(document, table, "build") {
673        None => Build::Default,
674        Some(Node {
675            kind: Kind::Scalar(Scalar::Boolean(false)),
676            ..
677        }) => Build::Disabled,
678        Some(Node {
679            kind: Kind::Scalar(Scalar::String(path)),
680            ..
681        }) => Build::Path(path.clone()),
682        Some(_) => {
683            return Err(at_key("package.build", "must be a path or false"));
684        }
685    };
686    let mut auto_off = Vec::new();
687    for (key, group) in [
688        ("autobins", "bin"),
689        ("autotests", "test"),
690        ("autobenches", "bench"),
691        ("autoexamples", "example"),
692        ("autolib", "lib"),
693    ] {
694        if !flag(document, table, "package", key)? {
695            auto_off.push(group);
696        }
697    }
698    let edition = match get(document, table, "edition") {
699        None => EditionDecl::Unset,
700        Some(Node {
701            kind: Kind::Scalar(Scalar::String(edition)),
702            ..
703        }) => EditionDecl::Explicit(year(edition, "package.edition")?),
704        Some(
705            inherit @ Node {
706                kind: Kind::Table(_),
707                ..
708            },
709        ) if get(document, inherit, "workspace").and_then(native::boolean) == Some(true) => {
710            EditionDecl::Inherited
711        }
712        Some(_) => {
713            return Err(at_key(
714                "package.edition",
715                "must be a string or `workspace = true`",
716            ));
717        }
718    };
719    Ok(Some(PackageDecl {
720        name,
721        version,
722        auto_off,
723        build,
724        edition,
725    }))
726}
727
728fn workspace_edition(document: &Document<'_>, root: &Node) -> Result<Option<u16>, ManifestError> {
729    match get(document, root, "workspace")
730        .and_then(native::table)
731        .and_then(|workspace| get(document, workspace, "package"))
732        .and_then(native::table)
733        .and_then(|package| get(document, package, "edition"))
734    {
735        None => Ok(None),
736        Some(Node {
737            kind: Kind::Scalar(Scalar::String(edition)),
738            ..
739        }) => Ok(Some(year(edition, "workspace.package.edition")?)),
740        Some(_) => Err(at_key("workspace.package.edition", "must be a string")),
741    }
742}
743
744/// Read a manifest from its text.
745///
746/// # Errors
747///
748/// Returns a [`ManifestError`] when the text is not TOML, is nested deeper than
749/// the parser allows, has neither a `[package]` nor a `[workspace]` table, or
750/// holds a value of the wrong type.
751pub(crate) fn parse(text: &str) -> Result<Manifest, ManifestError> {
752    let parsed = native::read(text).map_err(|error| ManifestError {
753        message: error.to_string(),
754        key: None,
755        source: Some(Box::new(error)),
756    })?;
757    let document = &parsed;
758    let root = &document.nodes()[0];
759    let package = package(document, root)?;
760    let has_workspace = get(document, root, "workspace").is_some();
761    if let Some(value) = get(document, root, "workspace") {
762        table_of(value, "workspace")?;
763    }
764    let package_workspace = get(document, root, "package")
765        .and_then(native::table)
766        .map(|table| string(document, table, "package", "workspace"))
767        .transpose()?
768        .flatten();
769    let workspace = get(document, root, "workspace").and_then(native::table);
770    let strings = |key: &str, cap: usize| -> Result<Vec<String>, ManifestError> {
771        let Some(value) = workspace.and_then(|table| get(document, table, key)) else {
772            return Ok(Vec::new());
773        };
774        let full = format!("workspace.{key}");
775        let array =
776            native::array(value).ok_or_else(|| at_key(&full, "must be an array of strings"))?;
777        if array.len() > cap {
778            return Err(at_key(
779                &full,
780                format!("has {} entries; at most {cap} are allowed", array.len()),
781            ));
782        }
783        array
784            .iter()
785            .map(|entry| {
786                native::string(&document.nodes()[*entry])
787                    .map(str::to_owned)
788                    .ok_or_else(|| at_key(&full, "must be an array of strings"))
789            })
790            .collect()
791    };
792    let mut workspace_dependencies = BTreeMap::new();
793    if let Some(value) = workspace.and_then(|table| get(document, table, "dependencies")) {
794        for (name, entry) in native::entries(document, table_of(value, "workspace.dependencies")?) {
795            let key = format!("workspace.dependencies.{name}");
796            let specification = dependency_spec(document, entry, &key)?;
797            if specification.workspace || specification.optional.is_some() {
798                return Err(at_key(
799                    &key,
800                    "workspace dependencies cannot inherit or set `optional`",
801                ));
802            }
803            workspace_dependencies.insert(
804                name.to_owned(),
805                WorkspaceDependency {
806                    path: specification.path.clone(),
807                    package: specification.package.clone(),
808                    specification,
809                },
810            );
811        }
812    }
813    let members = strings("members", MAX_MEMBERS)?;
814    let exclude = strings("exclude", MAX_EXCLUDES)?;
815    let workspace_edition = workspace_edition(document, root)?;
816    let workspace_version = workspace_version(document, workspace)?;
817    if package.is_none() && !has_workspace {
818        return Err(ManifestError {
819            message: "has neither a [package] nor a [workspace] table".to_owned(),
820            key: None,
821            source: None,
822        });
823    }
824    Ok(Manifest {
825        features: feature_declarations(document, root)?,
826        package,
827        has_workspace,
828        package_workspace,
829        workspace_edition,
830        workspace_version,
831        members,
832        exclude,
833        dependencies: dependencies(document, root)?,
834        workspace_dependencies,
835        lib: library_declaration(document, root)?,
836        bins: declarations(document, root, "bin")?,
837        tests: declarations(document, root, "test")?,
838        benches: declarations(document, root, "bench")?,
839        examples: declarations(document, root, "example")?,
840    })
841}
842
843fn feature_declarations(
844    document: &Document<'_>,
845    root: &Node,
846) -> Result<BTreeMap<String, Vec<String>>, ManifestError> {
847    let mut features = BTreeMap::new();
848    if let Some(value) = get(document, root, "features") {
849        for (name, value) in native::entries(document, table_of(value, "features")?) {
850            let key = format!("features.{name}");
851            let values = native::array(value)
852                .ok_or_else(|| at_key(&key, "must be an array of feature references"))?;
853            let mut references = Vec::new();
854            for value in values {
855                references.push(
856                    native::string(&document.nodes()[*value])
857                        .ok_or_else(|| at_key(&key, "must contain only strings"))?
858                        .to_owned(),
859                );
860            }
861            features.insert(name.to_owned(), references);
862        }
863    }
864    Ok(features)
865}
866
867fn library_declaration(
868    document: &Document<'_>,
869    root: &Node,
870) -> Result<Option<LibDecl>, ManifestError> {
871    let Some(value) = get(document, root, "lib") else {
872        return Ok(None);
873    };
874    let table = table_of(value, "lib")?;
875    Ok(Some(LibDecl {
876        name: string(document, table, "lib", "name")?,
877        path: string(document, table, "lib", "path")?,
878        settings: settings(document, table, "lib")?,
879    }))
880}
881
882/// The name of the library target that the root manifest of `tree` declares,
883/// which a locked configuration must name to select that target.
884///
885/// A `[lib]` table names the library itself, or takes the package name; a
886/// package without one has a library only when `src/lib.rs` exists. Nothing
887/// but the root manifest is parsed, so a package whose other targets are
888/// absent from `tree`, as in a registry archive, is not loaded.
889///
890/// # Errors
891/// Refuses an unreadable, oversized or malformed manifest, and one that is not
892/// a package manifest.
893pub fn library_target_name(
894    tree: &dyn crate::Tree,
895    options: &crate::LoadOptions,
896) -> Result<Option<String>, crate::LoadError> {
897    let path = crate::RelPath::new("Cargo.toml").map_err(|error| {
898        crate::LoadError::new(
899            &crate::RelPath::root(),
900            None,
901            crate::LoadErrorKind::Manifest {
902                message: error.to_string(),
903                source: None,
904            },
905        )
906    })?;
907    let origin = crate::Origin::Discovery;
908    let text = tree
909        .read(&path, options.max_file_bytes)
910        .map_err(|error| crate::LoadError::tree(&path, None, &origin, error))?;
911    let parsed = parse(&text).map_err(|problem| {
912        crate::LoadError::new(
913            &path,
914            None,
915            crate::LoadErrorKind::Manifest {
916                message: problem.message,
917                source: problem.source,
918            },
919        )
920    })?;
921    let Some(package) = parsed.package else {
922        return Err(crate::LoadError::new(
923            &path,
924            None,
925            crate::LoadErrorKind::Manifest {
926                message: "the root manifest declares no package".to_owned(),
927                source: None,
928            },
929        ));
930    };
931    if let Some(lib) = parsed.lib {
932        return Ok(Some(lib.name.unwrap_or(package.name)));
933    }
934    if !package.auto("lib") {
935        return Ok(None);
936    }
937    let default = crate::RelPath::new("src/lib.rs")
938        .map_err(|error| crate::LoadError::tree(&path, None, &origin, error.into()))?;
939    let present = tree
940        .entry(&default)
941        .map_err(|error| crate::LoadError::tree(&path, None, &origin, error))?;
942    Ok(present.map(|_| package.name))
943}