Skip to main content

subcrate_core/
lib.rs

1//! Shared logic between the `subcrate` build helper and the `subcrate-macros`
2//! procedural macro.
3//!
4//! The two sides never talk to each other. They only have to agree, on their own,
5//! about one thing: the **internal crate name** a given `#[subcrate]` module
6//! compiles to. The build helper uses it to name the `rustc` output; the
7//! procedural macro uses it in the `extern crate` binding that loads that output.
8//! Both derive the name from the module's identifier and body alone, so they
9//! always reach the same answer with no coordination.
10
11use proc_macro2::{Delimiter, TokenStream, TokenTree};
12use syn::parse::{Parse, ParseStream};
13use syn::punctuated::Punctuated;
14use syn::{
15    AttrStyle, Attribute, Expr, ExprLit, ExprPath, Item, Lit, Meta, MetaNameValue, PathArguments,
16    Token,
17};
18use template_quote::quote;
19
20/// The prefix of every generated internal crate name.
21///
22/// It is deliberately unlikely to collide with a real crate name and makes the
23/// generated artifacts easy to recognise in a `target` directory. It uses a
24/// single trailing underscore (not `__`) so the full name stays snake-case and
25/// never trips the `non_snake_case` lint — which would otherwise become an error
26/// whenever the owner builds with `-D warnings`.
27pub const INTERNAL_PREFIX: &str = "__subcrate_";
28
29/// Arguments accepted by the `#[subcrate]` attribute, e.g.
30/// `#[subcrate(proc_macro, edition = "2018", other_subcrate)]`.
31///
32/// The attribute takes a flat, comma-separated list. Each argument is one of:
33///
34/// * `proc_macro` (or `proc_macro = true`) — compile as a `proc-macro` crate.
35/// * `edition = "2018"` — compile with this edition.
36/// * `path::to::dep` — depend on the sibling subcrate at that module path,
37///   visible inside this subcrate under the path's last segment.
38/// * `alias = path::to::dep` — the same, visible under `alias`.
39/// * `::name` (or `alias = ::name`) — an *external* crate: one the owning
40///   package depends on, or — if `name` is the package's own library — the owner
41///   crate itself. The build helper has Cargo build it for the subcrate. It is
42///   visible inside the subcrate under `name` (or `alias`).
43///
44/// The remaining arguments turn the subcrate into a **UI test** — a build-time
45/// assertion about the diagnostics `rustc` produces for it. Each may be given more
46/// than once, and every one must hold (they are combined with AND — e.g. two
47/// `should_error = "…"` require a matching error for *each* string):
48///
49/// * `should_error` — the subcrate must *fail* to compile. Any `should_error`
50///   makes it expected to fail, so it produces no artifact and its module expands
51///   to an empty stand-in. With `= "…"` an error's rendered text must also contain
52///   that string.
53/// * `should_warn` — the subcrate must emit at least one warning. With `= "…"` a
54///   warning's rendered text must contain that string.
55/// * `should_spanned = "…"` — some diagnostic must underline source code equal to
56///   this string once whitespace is removed from both sides. (A value is required.)
57#[derive(Debug, Clone, Default, PartialEq, Eq)]
58pub struct Args {
59    /// Compile the module as a `proc-macro` crate rather than an ordinary
60    /// library crate.
61    pub proc_macro: bool,
62    /// Compile the subcrate with this edition instead of the owning package's.
63    pub edition: Option<String>,
64    /// The crates this subcrate links against, in the order written.
65    pub deps: Vec<Dependency>,
66    /// The UI-test expectations (`should_error`/`should_warn`/`should_spanned`).
67    pub ui: UiExpectations,
68}
69
70impl Args {
71    /// Whether these arguments make the subcrate a UI test (any `should_*`).
72    pub fn is_ui_test(&self) -> bool {
73        self.ui.is_ui_test()
74    }
75
76    /// Whether the subcrate is expected to fail to compile (any `should_error`),
77    /// so it produces no artifact.
78    pub fn expects_error(&self) -> bool {
79        self.ui.expects_error()
80    }
81}
82
83/// A subcrate's UI-test expectations: assertions about the diagnostics `rustc`
84/// produces for it, from `#[subcrate(should_error/should_warn/should_spanned …)]`.
85///
86/// Any non-empty field makes the subcrate a UI test. Every expectation must hold
87/// — they are combined with AND.
88#[derive(Debug, Clone, Default, PartialEq, Eq)]
89pub struct UiExpectations {
90    /// One entry per `should_error`: `Some(s)` requires an error whose rendered
91    /// text contains `s`, `None` (bare `should_error`) only that compilation
92    /// fails. A non-empty list makes the subcrate a UI test expected to fail.
93    pub should_errors: Vec<Option<String>>,
94    /// One entry per `should_warn`: `Some(s)` requires a warning whose rendered
95    /// text contains `s`, `None` (bare `should_warn`) only that some warning is
96    /// emitted.
97    pub should_warns: Vec<Option<String>>,
98    /// Code a diagnostic must underline, compared with whitespace removed.
99    pub should_spanned: Vec<String>,
100}
101
102impl UiExpectations {
103    /// Whether any expectation is set, so the subcrate is a UI test.
104    pub fn is_ui_test(&self) -> bool {
105        !self.should_errors.is_empty()
106            || !self.should_warns.is_empty()
107            || !self.should_spanned.is_empty()
108    }
109
110    /// Whether the subcrate is expected to fail to compile (any `should_error`),
111    /// so it produces no artifact.
112    pub fn expects_error(&self) -> bool {
113        !self.should_errors.is_empty()
114    }
115
116    /// A stable textual form folded into the internal crate name (see
117    /// [`Args::fingerprint`]): `S<text>` for a `Some`, `N` for a bare (`None`)
118    /// occurrence.
119    fn fingerprint(&self) -> String {
120        format!(
121            "e:{}|w:{}|s:{}",
122            fingerprint_opts(&self.should_errors),
123            fingerprint_opts(&self.should_warns),
124            self.should_spanned.join("\u{1f}"),
125        )
126    }
127}
128
129/// One dependency of a subcrate, as written in `#[subcrate(...)]`.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Dependency {
132    /// The name the dependency is visible under inside the subcrate: the explicit
133    /// `alias = …`, or else the last segment of `path`. (The build helper imports
134    /// the dependency's crate under this name at the subcrate's crate root.)
135    pub alias: String,
136    /// The module path of the depended-on subcrate, from its crate root, with
137    /// any leading `crate` removed (e.g. `["nested", "inner"]`). For an
138    /// external crate this is the crate's path after the leading `::`.
139    pub path: Vec<String>,
140    /// `true` for a leading-`::` path naming an external crate: one the owning
141    /// package depends on, or the owner crate itself. (The build helper accepts
142    /// just the crate's name, not a path into it.)
143    pub external: bool,
144}
145
146impl Dependency {
147    /// The dependency's path as written, e.g. `nested::inner` or `::serde`.
148    pub fn path_display(&self) -> String {
149        format!(
150            "{}{}",
151            if self.external { "::" } else { "" },
152            self.path.join("::")
153        )
154    }
155}
156
157impl Args {
158    /// A stable textual form of the arguments, folded into the internal crate
159    /// name so that two otherwise-identical module bodies compiled with
160    /// different arguments (e.g. different editions or dependencies) get
161    /// distinct crates.
162    ///
163    /// Dependencies are sorted, so reordering them does not change the name. Only
164    /// their *paths* are folded in, not the depended-on crate's content: the
165    /// build helper recompiles a subcrate whenever a dependency's crate name
166    /// (which embeds that dependency's content hash) changes.
167    ///
168    /// The UI-test expectations are folded in too, so editing a `should_error`
169    /// (or sibling) gives a fresh crate name and re-runs the check. They do not
170    /// change what is compiled, only what the build helper asserts about the
171    /// result, but a UI test has no downstream users to churn.
172    fn fingerprint(&self) -> String {
173        let mut deps: Vec<String> = self
174            .deps
175            .iter()
176            .map(|dep| format!("{}={}", dep.alias, dep.path_display()))
177            .collect();
178        deps.sort();
179        format!(
180            "{}|{}|{}|{}",
181            self.proc_macro,
182            self.edition.as_deref().unwrap_or(""),
183            deps.join(","),
184            self.ui.fingerprint(),
185        )
186    }
187}
188
189/// A stable textual form of a `should_error`/`should_warn` list for the
190/// fingerprint: `S<text>` for `Some`, `N` for a bare (`None`) occurrence.
191fn fingerprint_opts(opts: &[Option<String>]) -> String {
192    opts.iter()
193        .map(|opt| match opt {
194            Some(text) => format!("S{}", text),
195            None => "N".to_string(),
196        })
197        .collect::<Vec<_>>()
198        .join("\u{1f}")
199}
200
201impl Parse for Args {
202    fn parse(input: ParseStream) -> syn::Result<Self> {
203        let mut args = Args::default();
204        let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
205        for meta in metas {
206            match &meta {
207                // A bare path: the `proc_macro` flag, a bare UI-test assertion, or
208                // a dependency.
209                Meta::Path(path) => {
210                    if path.is_ident("proc_macro") {
211                        args.proc_macro = true;
212                    } else if path.is_ident("should_error") {
213                        args.ui.should_errors.push(None);
214                    } else if path.is_ident("should_warn") {
215                        args.ui.should_warns.push(None);
216                    } else if path.is_ident("should_spanned") {
217                        return Err(syn::Error::new_spanned(
218                            path,
219                            "`should_spanned` needs the code to match: \
220                             `should_spanned = \"…\"`",
221                        ));
222                    } else {
223                        args.deps.push(parse_dependency(None, path)?);
224                    }
225                }
226                Meta::NameValue(MetaNameValue { path, value, .. }) => {
227                    let key = match path.get_ident() {
228                        Some(ident) => ident.to_string(),
229                        None => return Err(unknown_argument(path)),
230                    };
231                    // The value's kind picks the meaning: a path renames a
232                    // dependency, a literal sets a known key.
233                    match value {
234                        Expr::Path(ExprPath {
235                            qself: None,
236                            path: target,
237                            ..
238                        }) => {
239                            if key == "proc_macro" {
240                                return Err(syn::Error::new_spanned(
241                                    path,
242                                    "`proc_macro` is reserved and cannot name a dependency",
243                                ));
244                            }
245                            args.deps.push(parse_dependency(Some(key), target)?);
246                        }
247                        _ if key == "proc_macro" => args.proc_macro = parse_bool(value)?,
248                        _ if key == "edition" => args.edition = Some(parse_string(value)?),
249                        _ if key == "should_error" => {
250                            args.ui.should_errors.push(Some(parse_string(value)?))
251                        }
252                        _ if key == "should_warn" => {
253                            args.ui.should_warns.push(Some(parse_string(value)?))
254                        }
255                        _ if key == "should_spanned" => {
256                            args.ui.should_spanned.push(parse_string(value)?)
257                        }
258                        _ => return Err(unknown_argument(path)),
259                    }
260                }
261                Meta::List(list) => return Err(unknown_argument(&list.path)),
262            }
263        }
264        Ok(args)
265    }
266}
267
268fn unknown_argument(path: &syn::Path) -> syn::Error {
269    syn::Error::new_spanned(
270        path,
271        "unknown `#[subcrate]` argument (expected `proc_macro`, `edition = \"…\"`, a \
272         dependency: `path::to::subcrate`, `::crate_name`, or either with an `alias = `, or a \
273         UI-test assertion: `should_error`, `should_warn` (each optionally `= \"…\"`), or \
274         `should_spanned = \"…\"`)",
275    )
276}
277
278/// Parses one dependency path, optionally renamed to `alias`.
279///
280/// A single leading `crate` is dropped (module paths are relative to the crate
281/// root); `self`/`super`/`Self` and generic arguments are rejected, since a
282/// subcrate has no meaningful position to resolve them against.
283fn parse_dependency(alias: Option<String>, path: &syn::Path) -> syn::Result<Dependency> {
284    let external = path.leading_colon.is_some();
285    let mut segments = Vec::new();
286    for segment in &path.segments {
287        if !matches!(segment.arguments, PathArguments::None) {
288            return Err(syn::Error::new_spanned(
289                segment,
290                "a subcrate dependency path cannot have generic arguments",
291            ));
292        }
293        segments.push(segment.ident.to_string());
294    }
295    if !external && segments.first().map(String::as_str) == Some("crate") {
296        segments.remove(0);
297    }
298    if segments
299        .iter()
300        .any(|s| matches!(s.as_str(), "crate" | "self" | "super" | "Self"))
301    {
302        return Err(syn::Error::new_spanned(
303            path,
304            "a subcrate dependency path must name a module from the crate root, \
305             like `outer::inner` (`self`, `super` and `Self` are not allowed)",
306        ));
307    }
308    let last = match segments.last() {
309        Some(last) => last.clone(),
310        None => {
311            return Err(syn::Error::new_spanned(
312                path,
313                "expected the path of a subcrate",
314            ))
315        }
316    };
317    Ok(Dependency {
318        alias: alias.unwrap_or(last),
319        path: segments,
320        external,
321    })
322}
323
324fn parse_bool(expr: &Expr) -> syn::Result<bool> {
325    if let Expr::Lit(ExprLit {
326        lit: Lit::Bool(b), ..
327    }) = expr
328    {
329        Ok(b.value)
330    } else {
331        Err(syn::Error::new_spanned(expr, "expected a boolean literal"))
332    }
333}
334
335fn parse_string(expr: &Expr) -> syn::Result<String> {
336    if let Expr::Lit(ExprLit {
337        lit: Lit::Str(s), ..
338    }) = expr
339    {
340        Ok(s.value())
341    } else {
342        Err(syn::Error::new_spanned(expr, "expected a string literal"))
343    }
344}
345
346/// Returns the crate-level inner attributes (`#![…]`) of a module body — the
347/// ones that belong on the subcrate's crate root, such as `#![no_std]` or
348/// `#![allow(…)]`.
349pub fn inner_attrs(attrs: &[Attribute]) -> Vec<Attribute> {
350    attrs
351        .iter()
352        .filter(|attr| matches!(attr.style, AttrStyle::Inner(_)))
353        .cloned()
354        .collect()
355}
356
357/// Returns `true` if `attr` is the `#[subcrate]` attribute.
358///
359/// Matches both the imported form (`#[subcrate]`, via `use subcrate::subcrate;`)
360/// and the fully qualified form (`#[subcrate::subcrate]`) by comparing only the
361/// final path segment.
362pub fn is_subcrate_attr(attr: &Attribute) -> bool {
363    attr.path()
364        .segments
365        .last()
366        .map(|seg| seg.ident == "subcrate")
367        .unwrap_or(false)
368}
369
370/// Parses the [`Args`] carried by a `#[subcrate(...)]` attribute as it appears
371/// in parsed source (used by the build helper).
372pub fn parse_attr_args(attr: &Attribute) -> syn::Result<Args> {
373    match &attr.meta {
374        Meta::Path(_) => Ok(Args::default()),
375        Meta::List(list) => syn::parse2::<Args>(list.tokens.clone()),
376        Meta::NameValue(nv) => Err(syn::Error::new_spanned(
377            nv,
378            "`#[subcrate]` does not take a `= value` form",
379        )),
380    }
381}
382
383/// A sibling dependency of a subcrate that the build helper resolved *under the
384/// same crate root*, as recorded in the manifest: the name it is visible under
385/// (the alias) and its module path from that root.
386pub type ResolvedDep = (String, Vec<String>);
387
388/// The reserved first field marking a manifest line as a skipped subcrate (one
389/// whose `#[rustversion]` gate kept it from building on the current toolchain).
390/// A real dependency field is always `alias=path`, and an alias is an identifier,
391/// so this `!`-prefixed token can never collide with one.
392pub const SKIPPED_MARKER: &str = "!skipped";
393
394/// What the build helper recorded for a subcrate in its manifest.
395pub enum ManifestEntry {
396    /// The subcrate was compiled; these are its resolved dependencies (used to
397    /// give its `cfg(doc)` stand-in the same names the real crate gets).
398    Built(Vec<ResolvedDep>),
399    /// The subcrate carries a `#[rustversion]` gate and did not build on the
400    /// current toolchain, so no artifact exists. The macro expands it away. See
401    /// `subcrate::build::compile`'s handling of rustversion-gated subcrates.
402    Skipped,
403}
404
405/// Renders one line of the build helper's manifest: the subcrate's internal name,
406/// then one tab-separated `alias=path::to::dep` per resolved dependency.
407///
408/// The macro reads the dependencies back to give a subcrate's `cfg(doc)`
409/// stand-in the same names in scope that the real crate gets from `--extern`.
410pub fn manifest_line(internal: &str, deps: &[ResolvedDep]) -> String {
411    let mut line = internal.to_string();
412    for (alias, path) in deps {
413        line.push('\t');
414        line.push_str(alias);
415        line.push('=');
416        line.push_str(&path.join("::"));
417    }
418    line
419}
420
421/// Renders the manifest line for a subcrate the helper skipped because its
422/// `#[rustversion]` gate did not build on the current toolchain (see
423/// [`ManifestEntry::Skipped`]).
424pub fn skipped_manifest_line(internal: &str) -> String {
425    format!("{}\t{}", internal, SKIPPED_MARKER)
426}
427
428/// Finds the manifest line for `internal` (see [`manifest_line`]) and returns what
429/// the helper recorded for it, or `None` if the subcrate is not listed.
430pub fn manifest_lookup(manifest: &str, internal: &str) -> Option<ManifestEntry> {
431    manifest.lines().find_map(|line| {
432        let mut fields = line.trim().split('\t');
433        if fields.next()? != internal {
434            return None;
435        }
436        let rest = fields.collect::<Vec<&str>>();
437        if rest.first() == Some(&SKIPPED_MARKER) {
438            return Some(ManifestEntry::Skipped);
439        }
440        Some(ManifestEntry::Built(
441            rest.into_iter()
442                .filter_map(|field| {
443                    let (alias, path) = field.split_once('=')?;
444                    let path = path.split("::").map(str::to_string).collect();
445                    Some((alias.to_string(), path))
446                })
447                .collect(),
448        ))
449    })
450}
451
452/// Produces a canonical text form of a module body.
453///
454/// The macro and the build helper each start from the same `Vec<Item>` — one from
455/// the tokens handed to the attribute macro, the other from re-parsing the source
456/// file — and render it the same way.
457///
458/// We do **not** hash `TokenStream::to_string()`. That text differs between the
459/// real proc-macro backend (used in the macro) and `proc_macro2`'s fallback
460/// backend (used in the build script) — in whitespace, and in how a string
461/// literal is spelled (raw vs escaped). Instead we walk the token tree and write a
462/// form that depends only on each token's kind and, for literals, decoded value —
463/// not its spacing or spelling — so both backends produce the same bytes.
464pub fn canonical_body(attrs: &[Attribute], items: &[Item]) -> String {
465    let tokens: TokenStream = quote! { #(#attrs)* #(#items)* };
466    let mut out = String::new();
467    write_canonical(&tokens, &mut out);
468    out
469}
470
471fn write_canonical(tokens: &TokenStream, out: &mut String) {
472    for tt in tokens.clone() {
473        match tt {
474            TokenTree::Group(group) => {
475                let (open, close) = match group.delimiter() {
476                    Delimiter::Parenthesis => ('(', ')'),
477                    Delimiter::Brace => ('{', '}'),
478                    Delimiter::Bracket => ('[', ']'),
479                    // Invisible groups: use markers that cannot appear in source.
480                    Delimiter::None => ('\u{2039}', '\u{203a}'),
481                };
482                out.push(open);
483                write_canonical(&group.stream(), out);
484                out.push(close);
485            }
486            // Idents are space-delimited so `a b` never collapses into `ab`.
487            TokenTree::Ident(ident) => {
488                out.push(' ');
489                out.push_str(&ident.to_string());
490                out.push(' ');
491            }
492            // Punct characters are concatenated verbatim; multi-character
493            // operators arrive as separate joint puncts and reassemble exactly.
494            TokenTree::Punct(punct) => out.push(punct.as_char()),
495            // Literals are wrapped in markers so their boundaries are explicit,
496            // and reduced to their value (see `canonical_literal`).
497            TokenTree::Literal(lit) => {
498                out.push('\u{2045}');
499                out.push_str(&canonical_literal(&lit.to_string()));
500                out.push('\u{2046}');
501            }
502        }
503    }
504}
505
506/// Reduces a literal to a backend-independent form. A string, byte-string, char
507/// or byte literal becomes its decoded value, so the raw and escaped spellings of
508/// one value agree: the two proc-macro backends spell the same value differently
509/// (a raw `r"a\b"` on one, an escaped `"a\\b"` on the other — notably for a doc
510/// comment carrying `"` or `\`), and hashing the spelling would make the macro and
511/// the build helper disagree on a module's name. Numeric literals render the same
512/// on both backends, and anything that does not parse as a literal is left as is.
513fn canonical_literal(text: &str) -> String {
514    match syn::parse_str::<Lit>(text) {
515        Ok(Lit::Str(s)) => format!("s\u{1f}{}", s.value()),
516        Ok(Lit::ByteStr(s)) => format!("b\u{1f}{:?}", s.value()),
517        Ok(Lit::Char(c)) => format!("c\u{1f}{}", c.value()),
518        Ok(Lit::Byte(b)) => format!("y\u{1f}{}", b.value()),
519        _ => text.to_string(),
520    }
521}
522
523/// Computes the internal crate name for a `#[subcrate]` module.
524///
525/// The name is content-addressed: it embeds a hash of the module identifier and
526/// its body. This has two useful consequences:
527///
528/// * The macro and the build helper compute the same name with no shared state.
529/// * When the body (its items, crate-level inner attributes, or arguments)
530///   changes, the name changes, so stale artifacts are never reused — and when
531///   it does not change, the existing artifact is reused as-is (incremental
532///   rebuilds).
533///
534/// `inner_attrs` are the subcrate's crate-root `#![…]` attributes; `args` are
535/// the `#[subcrate(...)]` arguments. Both the macro and the build helper pass
536/// the same values, so they agree.
537pub fn internal_crate_name(
538    ident: &str,
539    args: &Args,
540    inner_attrs: &[Attribute],
541    items: &[Item],
542) -> String {
543    let body = canonical_body(inner_attrs, items);
544    let mut hasher = Fnv1a::new();
545    // Hash the original identifier for uniqueness; the name only *displays* a
546    // sanitized form of it.
547    hasher.write(ident.as_bytes());
548    hasher.write(&[0x1f]);
549    hasher.write(args.fingerprint().as_bytes());
550    hasher.write(&[0x1f]);
551    hasher.write(body.as_bytes());
552    format!(
553        "{}{}_{:016x}",
554        INTERNAL_PREFIX,
555        sanitize_ident(ident),
556        hasher.finish()
557    )
558}
559
560/// Reduces an identifier to a lowercase, single-underscore-separated token so the
561/// generated crate name is valid snake case regardless of the original casing.
562/// Uniqueness does not rely on this (the hash covers the exact identifier).
563fn sanitize_ident(ident: &str) -> String {
564    let mut result = String::new();
565    let mut gap = false;
566    for ch in ident.chars() {
567        if ch.is_ascii_alphanumeric() {
568            // A single underscore joins alphanumeric runs; leading/trailing runs
569            // of non-alphanumerics are dropped, so no `__` can appear.
570            if gap && !result.is_empty() {
571                result.push('_');
572            }
573            result.push(ch.to_ascii_lowercase());
574            gap = false;
575        } else {
576            gap = true;
577        }
578    }
579    if result.is_empty() {
580        "anon".to_string()
581    } else {
582        result
583    }
584}
585
586/// A tiny, dependency-free FNV-1a (64-bit) hasher.
587///
588/// `std`'s `DefaultHasher` is deterministic today, but its output is explicitly
589/// not guaranteed stable. We need a value that is identical across two separate
590/// compilations (the build script and the proc-macro host), so we spell the
591/// algorithm out here.
592struct Fnv1a(u64);
593
594impl Fnv1a {
595    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
596    const PRIME: u64 = 0x0000_0100_0000_01b3;
597
598    fn new() -> Self {
599        Fnv1a(Self::OFFSET)
600    }
601
602    fn write(&mut self, bytes: &[u8]) {
603        for &b in bytes {
604            self.0 ^= u64::from(b);
605            self.0 = self.0.wrapping_mul(Self::PRIME);
606        }
607    }
608
609    fn finish(&self) -> u64 {
610        self.0
611    }
612}
613
614#[cfg(test)]
615mod tests {
616    use super::*;
617
618    // A raw and an escaped spelling of one string value must canonicalize the
619    // same, so the macro and the build helper (whose proc-macro backends spell
620    // literals differently) agree on the internal name. Regression test for the
621    // "a doc comment with `\"` or `\\` breaks discovery" bug.
622    #[test]
623    fn literals_canonicalize_by_value_not_spelling() {
624        let raw: Item = syn::parse_str(r##"fn f() -> &'static str { r"a\b" }"##).unwrap();
625        let escaped: Item = syn::parse_str(r#"fn f() -> &'static str { "a\\b" }"#).unwrap();
626        assert_eq!(
627            canonical_body(&[], std::slice::from_ref(&raw)),
628            canonical_body(&[], std::slice::from_ref(&escaped)),
629        );
630        assert_eq!(
631            internal_crate_name("m", &Args::default(), &[], std::slice::from_ref(&raw)),
632            internal_crate_name("m", &Args::default(), &[], std::slice::from_ref(&escaped)),
633        );
634    }
635
636    // A skipped subcrate (its `#[rustversion]` gate kept it from building on this
637    // toolchain) is recorded distinctly from a built one, and the marker can never
638    // be confused with a dependency field (which is always `alias=path`).
639    #[test]
640    fn a_skipped_subcrate_round_trips_through_the_manifest() {
641        let built = manifest_line(
642            "__subcrate_a",
643            &[("dep".into(), vec!["x".into(), "y".into()])],
644        );
645        let skipped = skipped_manifest_line("__subcrate_b");
646        let manifest = format!("{}\n{}\n", built, skipped);
647
648        match manifest_lookup(&manifest, "__subcrate_a") {
649            Some(ManifestEntry::Built(deps)) => {
650                assert_eq!(
651                    deps,
652                    vec![("dep".to_string(), vec!["x".to_string(), "y".to_string()])]
653                );
654            }
655            _ => panic!("expected a built entry"),
656        }
657        assert!(matches!(
658            manifest_lookup(&manifest, "__subcrate_b"),
659            Some(ManifestEntry::Skipped)
660        ));
661        assert!(manifest_lookup(&manifest, "__subcrate_missing").is_none());
662    }
663}