rust-lang / rust-lang/rust

rustdoc: support #![cfg(feature)] that disables doc tests

Open
#133,886 4 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-cfg A-doctests C-feature-request T-rustdoc
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code in doc comments may require specific Cargo features or platforms, but currently the syntax for disabling doctests is non-obvious, verbose, and by mixing languages and syntaxes, it doesn't play well with Markdown syntax highlighting:

#![cfg_attr(feature = "alloc", doc = " ```")]
#![cfg_attr(not(feature = "alloc"), doc = " ```ignore")]
//! code
//! ```

I suggest supporting #![cfg(…)] inside doctests, injected into the test code in a way that disables a block of code containing the test. Currently #![cfg(feature = …)] doesn't work at all in doctests, because it gets hoisted to be a real crate attribute, and ends up disabling entire the test module.

//! ```rust
//! #![cfg(feature = "alloc")] // proposed syntax
//! code
//! ```

In the implementation I think it would require wrapping "everything_else" code in extra { }, and keeping #![cfg(feature = …)] attrs in the code, instead of extracting them and hoisting them to the top level of the doctest crate.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing rustdoc's doctest generation and the handling of crate-level cfg attributes. Verify how the proposed in-doctest cfg syntax should preserve Markdown highlighting while disabling only the intended code block, and confirm that existing feature-gated doctests do not disable the entire test module.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.