Skip to content

Commit 472bbb9

Browse files
authored
Rollup merge of #128780 - GuillaumeGomez:rustflags-doctests, r=rustdoc
Add `--doctest-compilation-args` option to add compilation flags to doctest compilation Fixes #67533. Tracking issue: #134172 It's been something I meant to take a look at for a long time and actually completely forgot... The idea is to allow to give more control over how doctests are compiled to users. To do so, this PR adds a new `--doctest-compilation-args` option which provides extra compilation flags. r? `@notriddle`
2 parents 758ad53 + 2d914be commit 472bbb9

File tree

10 files changed

+220
-21
lines changed

10 files changed

+220
-21
lines changed

src/doc/rustdoc/src/unstable-features.md

+95-18
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ Markdown file, the URL given to `--markdown-playground-url` will take precedence
315315
`--playground-url` and `#![doc(html_playground_url = "url")]` are present when rendering crate docs,
316316
the attribute will take precedence.
317317

318-
### `--sort-modules-by-appearance`: control how items on module pages are sorted
318+
## `--sort-modules-by-appearance`: control how items on module pages are sorted
319319

320320
Using this flag looks like this:
321321

@@ -328,7 +328,7 @@ some consideration for their stability, and names that end in a number). Giving
328328
`rustdoc` will disable this sorting and instead make it print the items in the order they appear in
329329
the source.
330330

331-
### `--show-type-layout`: add a section to each type's docs describing its memory layout
331+
## `--show-type-layout`: add a section to each type's docs describing its memory layout
332332

333333
* Tracking issue: [#113248](https://github.com/rust-lang/rust/issues/113248)
334334

@@ -346,7 +346,7 @@ of that type will take in memory.
346346
Note that most layout information is **completely unstable** and may even differ
347347
between compilations.
348348

349-
### `--resource-suffix`: modifying the name of CSS/JavaScript in crate docs
349+
## `--resource-suffix`: modifying the name of CSS/JavaScript in crate docs
350350

351351
* Tracking issue: [#54765](https://github.com/rust-lang/rust/issues/54765)
352352

@@ -361,7 +361,7 @@ all these files are linked from every page, changing where they are can be cumbe
361361
specially cache them. This flag will rename all these files in the output to include the suffix in
362362
the filename. For example, `light.css` would become `light-suf.css` with the above command.
363363

364-
### `--extern-html-root-url`: control how rustdoc links to non-local crates
364+
## `--extern-html-root-url`: control how rustdoc links to non-local crates
365365

366366
Using this flag looks like this:
367367

@@ -376,7 +376,7 @@ flags to control that behavior. When the `--extern-html-root-url` flag is given
376376
one of your dependencies, rustdoc use that URL for those docs. Keep in mind that if those docs exist
377377
in the output directory, those local docs will still override this flag.
378378

379-
### `-Z force-unstable-if-unmarked`
379+
## `-Z force-unstable-if-unmarked`
380380

381381
Using this flag looks like this:
382382

@@ -389,7 +389,7 @@ This is an internal flag intended for the standard library and compiler that app
389389
allows `rustdoc` to be able to generate documentation for the compiler crates and the standard
390390
library, as an equivalent command-line argument is provided to `rustc` when building those crates.
391391

392-
### `--index-page`: provide a top-level landing page for docs
392+
## `--index-page`: provide a top-level landing page for docs
393393

394394
This feature allows you to generate an index-page with a given markdown file. A good example of it
395395
is the [rust documentation index](https://doc.rust-lang.org/nightly/index.html).
@@ -398,18 +398,18 @@ With this, you'll have a page which you can customize as much as you want at the
398398

399399
Using `index-page` option enables `enable-index-page` option as well.
400400

401-
### `--enable-index-page`: generate a default index page for docs
401+
## `--enable-index-page`: generate a default index page for docs
402402

403403
This feature allows the generation of a default index-page which lists the generated crates.
404404

405-
### `--nocapture`: disable output capture for test
405+
## `--nocapture`: disable output capture for test
406406

407407
When this flag is used with `--test`, the output (stdout and stderr) of your tests won't be
408408
captured by rustdoc. Instead, the output will be directed to your terminal,
409409
as if you had run the test executable manually. This is especially useful
410410
for debugging your tests!
411411

412-
### `--check`: only checks the documentation
412+
## `--check`: only checks the documentation
413413

414414
When this flag is supplied, rustdoc will type check and lint your code, but will not generate any
415415
documentation or run your doctests.
@@ -420,7 +420,7 @@ Using this flag looks like:
420420
rustdoc -Z unstable-options --check src/lib.rs
421421
```
422422

423-
### `--static-root-path`: control how static files are loaded in HTML output
423+
## `--static-root-path`: control how static files are loaded in HTML output
424424

425425
Using this flag looks like this:
426426

@@ -435,7 +435,7 @@ JavaScript, and font files in a single location, rather than duplicating it once
435435
files like the search index will still load from the documentation root, but anything that gets
436436
renamed with `--resource-suffix` will load from the given path.
437437

438-
### `--persist-doctests`: persist doctest executables after running
438+
## `--persist-doctests`: persist doctest executables after running
439439

440440
* Tracking issue: [#56925](https://github.com/rust-lang/rust/issues/56925)
441441

@@ -449,7 +449,7 @@ This flag allows you to keep doctest executables around after they're compiled o
449449
Usually, rustdoc will immediately discard a compiled doctest after it's been tested, but
450450
with this option, you can keep those binaries around for farther testing.
451451

452-
### `--show-coverage`: calculate the percentage of items with documentation
452+
## `--show-coverage`: calculate the percentage of items with documentation
453453

454454
* Tracking issue: [#58154](https://github.com/rust-lang/rust/issues/58154)
455455

@@ -500,7 +500,7 @@ Calculating code examples follows these rules:
500500
* typedef
501501
2. If one of the previously listed items has a code example, then it'll be counted.
502502

503-
#### JSON output
503+
### JSON output
504504

505505
When using `--output-format json` with this option, it will display the coverage information in
506506
JSON format. For example, here is the JSON for a file with one documented item and one
@@ -522,7 +522,7 @@ Note that the third item is the crate root, which in this case is undocumented.
522522
If you want the JSON output to be displayed on `stdout` instead of having a file generated, you can
523523
use `-o -`.
524524

525-
### `-w`/`--output-format`: output format
525+
## `-w`/`--output-format`: output format
526526

527527
`--output-format json` emits documentation in the experimental
528528
[JSON format](https://doc.rust-lang.org/nightly/nightly-rustc/rustdoc_json_types/). `--output-format html` has no effect,
@@ -542,7 +542,7 @@ It can also be used with `--show-coverage`. Take a look at its
542542
[documentation](#--show-coverage-calculate-the-percentage-of-items-with-documentation) for more
543543
information.
544544

545-
### `--enable-per-target-ignores`: allow `ignore-foo` style filters for doctests
545+
## `--enable-per-target-ignores`: allow `ignore-foo` style filters for doctests
546546

547547
* Tracking issue: [#64245](https://github.com/rust-lang/rust/issues/64245)
548548

@@ -577,7 +577,7 @@ struct Foo;
577577
In older versions, this will be ignored on all targets, but on newer versions `ignore-gnu` will
578578
override `ignore`.
579579

580-
### `--runtool`, `--runtool-arg`: program to run tests with; args to pass to it
580+
## `--runtool`, `--runtool-arg`: program to run tests with; args to pass to it
581581

582582
* Tracking issue: [#64245](https://github.com/rust-lang/rust/issues/64245)
583583

@@ -596,7 +596,7 @@ $ rustdoc src/lib.rs -Z unstable-options --runtool valgrind
596596

597597
Another use case would be to run a test inside an emulator, or through a Virtual Machine.
598598

599-
### `--with-examples`: include examples of uses of items as documentation
599+
## `--with-examples`: include examples of uses of items as documentation
600600

601601
* Tracking issue: [#88791](https://github.com/rust-lang/rust/issues/88791)
602602

@@ -625,7 +625,7 @@ crate being documented (`foobar`) and a path to output the calls
625625
To scrape examples from test code, e.g. functions marked `#[test]`, then
626626
add the `--scrape-tests` flag.
627627

628-
### `--generate-link-to-definition`: Generate links on types in source code
628+
## `--generate-link-to-definition`: Generate links on types in source code
629629

630630
* Tracking issue: [#89095](https://github.com/rust-lang/rust/issues/89095)
631631

@@ -664,3 +664,80 @@ Similar to cargo `build.rustc-wrapper` option, this flag takes a `rustc` wrapper
664664
The first argument to the program will be the test builder program.
665665

666666
This flag can be passed multiple times to nest wrappers.
667+
668+
## Passing arguments to rustc when compiling doctests
669+
670+
You can use the `--doctest-compilation-args` flag if you want to add options when compiling the
671+
doctest. For example if you have:
672+
673+
```rust,no_run
674+
/// ```
675+
/// #![deny(warnings)]
676+
/// #![feature(async_await)]
677+
///
678+
/// let x = 12;
679+
/// ```
680+
pub struct Bar;
681+
```
682+
683+
And you run `rustdoc --test` on it, you will get:
684+
685+
```console
686+
running 1 test
687+
test foo.rs - Bar (line 1) ... FAILED
688+
689+
failures:
690+
691+
---- foo.rs - Bar (line 1) stdout ----
692+
error: the feature `async_await` has been stable since 1.39.0 and no longer requires an attribute to enable
693+
--> foo.rs:2:12
694+
|
695+
3 | #![feature(async_await)]
696+
| ^^^^^^^^^^^
697+
|
698+
note: the lint level is defined here
699+
--> foo.rs:1:9
700+
|
701+
2 | #![deny(warnings)]
702+
| ^^^^^^^^
703+
= note: `#[deny(stable_features)]` implied by `#[deny(warnings)]`
704+
705+
error: aborting due to 1 previous error
706+
707+
Couldn't compile the test.
708+
709+
failures:
710+
foo.rs - Bar (line 1)
711+
712+
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
713+
```
714+
715+
But if you can limit the lint level to warning by using `--doctest_compilation_args=--cap-lints=warn`:
716+
717+
```console
718+
$ rustdoc --test --doctest_compilation_args=--cap-lints=warn file.rs
719+
720+
running 1 test
721+
test tests/rustdoc-ui/doctest/rustflags.rs - Bar (line 5) ... ok
722+
723+
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s
724+
```
725+
726+
The parsing of arguments works as follows: if it encounters a `"` or a `'`, it will continue
727+
until it finds the character unescaped (without a prepending `\`). If not inside a string, a
728+
whitespace character will also split arguments. Example:
729+
730+
```text
731+
"hello 'a'\" ok" how are 'you today?'
732+
```
733+
734+
will be split as follows:
735+
736+
```text
737+
[
738+
"hello 'a'\" ok",
739+
"how",
740+
"are",
741+
"you today?",
742+
]
743+
```

src/librustdoc/config.rs

+5
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,9 @@ pub(crate) struct Options {
172172
/// This is mainly useful for other tools that reads that debuginfo to figure out
173173
/// how to call the compiler with the same arguments.
174174
pub(crate) expanded_args: Vec<String>,
175+
176+
/// Arguments to be used when compiling doctests.
177+
pub(crate) doctest_compilation_args: Vec<String>,
175178
}
176179

177180
impl fmt::Debug for Options {
@@ -774,6 +777,7 @@ impl Options {
774777
let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
775778
let with_examples = matches.opt_strs("with-examples");
776779
let call_locations = crate::scrape_examples::load_call_locations(with_examples, dcx);
780+
let doctest_compilation_args = matches.opt_strs("doctest-compilation-args");
777781

778782
let unstable_features =
779783
rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
@@ -819,6 +823,7 @@ impl Options {
819823
scrape_examples_options,
820824
unstable_features,
821825
expanded_args: args,
826+
doctest_compilation_args,
822827
};
823828
let render_options = RenderOptions {
824829
output,

src/librustdoc/doctest.rs

+44
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,46 @@ pub(crate) struct GlobalTestOptions {
5050
pub(crate) args_file: PathBuf,
5151
}
5252

53+
/// Function used to split command line arguments just like a shell would.
54+
fn split_args(args: &str) -> Vec<String> {
55+
let mut out = Vec::new();
56+
let mut iter = args.chars();
57+
let mut current = String::new();
58+
59+
while let Some(c) = iter.next() {
60+
if c == '\\' {
61+
if let Some(c) = iter.next() {
62+
// If it's escaped, even a quote or a whitespace will be ignored.
63+
current.push(c);
64+
}
65+
} else if c == '"' || c == '\'' {
66+
while let Some(new_c) = iter.next() {
67+
if new_c == c {
68+
break;
69+
} else if new_c == '\\' {
70+
if let Some(c) = iter.next() {
71+
// If it's escaped, even a quote will be ignored.
72+
current.push(c);
73+
}
74+
} else {
75+
current.push(new_c);
76+
}
77+
}
78+
} else if " \n\t\r".contains(c) {
79+
if !current.is_empty() {
80+
out.push(current.clone());
81+
current.clear();
82+
}
83+
} else {
84+
current.push(c);
85+
}
86+
}
87+
if !current.is_empty() {
88+
out.push(current);
89+
}
90+
out
91+
}
92+
5393
pub(crate) fn generate_args_file(file_path: &Path, options: &RustdocOptions) -> Result<(), String> {
5494
let mut file = File::create(file_path)
5595
.map_err(|error| format!("failed to create args file: {error:?}"))?;
@@ -78,6 +118,10 @@ pub(crate) fn generate_args_file(file_path: &Path, options: &RustdocOptions) ->
78118
content.push(format!("-Z{unstable_option_str}"));
79119
}
80120

121+
for compilation_args in &options.doctest_compilation_args {
122+
content.extend(split_args(compilation_args));
123+
}
124+
81125
let content = content.join("\n");
82126

83127
file.write_all(content.as_bytes())

src/librustdoc/doctest/tests.rs

+22
Original file line numberDiff line numberDiff line change
@@ -379,3 +379,25 @@ fn main() {
379379
let (output, len) = make_test(input, None, false, &opts, None);
380380
assert_eq!((output, len), (expected, 1));
381381
}
382+
383+
#[test]
384+
fn check_split_args() {
385+
fn compare(input: &str, expected: &[&str]) {
386+
let output = super::split_args(input);
387+
let expected = expected.iter().map(|s| s.to_string()).collect::<Vec<_>>();
388+
assert_eq!(expected, output, "test failed for {input:?}");
389+
}
390+
391+
compare("'a' \"b\"c", &["a", "bc"]);
392+
compare("'a' \"b \"c d", &["a", "b c", "d"]);
393+
compare("'a' \"b\\\"c\"", &["a", "b\"c"]);
394+
compare("'a\"'", &["a\""]);
395+
compare("\"a'\"", &["a'"]);
396+
compare("\\ a", &[" a"]);
397+
compare("\\\\", &["\\"]);
398+
compare("a'", &["a"]);
399+
compare("a ", &["a"]);
400+
compare("a b", &["a", "b"]);
401+
compare("a\n\t \rb", &["a", "b"]);
402+
compare("a\n\t1 \rb", &["a", "1", "b"]);
403+
}

src/librustdoc/lib.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,15 @@ fn opts() -> Vec<RustcOptGroup> {
642642
"Includes trait implementations and other crate info from provided path. Only use with --merge=finalize",
643643
"path/to/doc.parts/<crate-name>",
644644
),
645+
opt(Unstable, Flag, "", "html-no-source", "Disable HTML source code pages generation", ""),
646+
opt(
647+
Unstable,
648+
Multi,
649+
"",
650+
"doctest-compilation-args",
651+
"",
652+
"add arguments to be used when compiling doctests",
653+
),
645654
// deprecated / removed options
646655
opt(Unstable, FlagMulti, "", "disable-minification", "removed", ""),
647656
opt(
@@ -684,7 +693,6 @@ fn opts() -> Vec<RustcOptGroup> {
684693
"removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information",
685694
"[rust]",
686695
),
687-
opt(Unstable, Flag, "", "html-no-source", "Disable HTML source code pages generation", ""),
688696
]
689697
}
690698

tests/run-make/rustdoc-default-output/output-default.stdout

+4-2
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ Options:
189189
--include-parts-dir path/to/doc.parts/<crate-name>
190190
Includes trait implementations and other crate info
191191
from provided path. Only use with --merge=finalize
192+
--html-no-source
193+
Disable HTML source code pages generation
194+
--doctest-compilation-args add arguments to be used when compiling doctests
195+
192196
--disable-minification
193197
removed
194198
--plugin-path DIR
@@ -209,8 +213,6 @@ Options:
209213
removed, see issue #44136
210214
<https://github.com/rust-lang/rust/issues/44136> for
211215
more information
212-
--html-no-source
213-
Disable HTML source code pages generation
214216

215217
@path Read newline separated options from `path`
216218

0 commit comments

Comments
 (0)