Skip to content

Commit b574c67

Browse files
poliorceticsjyn514
authored andcommitted
New rustdoc lint to respect -Dwarnings correctly
This adds a new lint to `rustc` that is used in rustdoc when a code block is empty or cannot be parsed as valid Rust code. Previously this was unconditionally a warning. As such some documentation comments were (unknowingly) abusing this to pass despite the `-Dwarnings` used when compiling `rustc`, this should not be the case anymore.
1 parent 3e99439 commit b574c67

File tree

8 files changed

+115
-40
lines changed

8 files changed

+115
-40
lines changed

Diff for: compiler/rustc_mir/src/borrow_check/region_infer/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1241,7 +1241,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
12411241
/// it. However, it works pretty well in practice. In particular,
12421242
/// this is needed to deal with projection outlives bounds like
12431243
///
1244-
/// ```ignore (internal compiler representation so lifetime syntax is invalid)
1244+
/// ```text (internal compiler representation so lifetime syntax is invalid)
12451245
/// <T as Foo<'0>>::Item: '1
12461246
/// ```
12471247
///

Diff for: compiler/rustc_trait_selection/src/opaque_types.rs

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ pub struct OpaqueTypeDecl<'tcx> {
4646
/// type Foo = impl Baz;
4747
/// fn bar() -> Foo {
4848
/// // ^^^ This is the span we are looking for!
49+
/// }
4950
/// ```
5051
///
5152
/// In cases where the fn returns `(impl Trait, impl Trait)` or

Diff for: compiler/rustc_typeck/src/check/upvar.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
323323
///
324324
/// InferBorrowKind results in a structure like this:
325325
///
326-
/// ```
326+
/// ```text
327327
/// {
328328
/// Place(base: hir_id_s, projections: [], ....) -> {
329329
/// capture_kind_expr: hir_id_L5,
@@ -348,7 +348,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
348348
/// ```
349349
///
350350
/// After the min capture analysis, we get:
351-
/// ```
351+
/// ```text
352352
/// {
353353
/// hir_id_s -> [
354354
/// Place(base: hir_id_s, projections: [], ....) -> {

Diff for: src/doc/rustdoc/src/lints.md

+37
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,43 @@ warning: unclosed HTML tag `h1`
294294
warning: 2 warnings emitted
295295
```
296296

297+
## invalid_rust_codeblock
298+
299+
This lint **warns by default**. It detects Rust code blocks in documentation
300+
examples that are invalid (e.g. empty, not parsable as Rust). For example:
301+
302+
```rust
303+
/// Empty code blocks (with and without the `rust` marker):
304+
///
305+
/// ```rust
306+
/// ```
307+
///
308+
/// Unclosed code blocks (with and without the `rust` marker):
309+
///
310+
/// ```rust
311+
fn main() {}
312+
```
313+
314+
Which will give:
315+
316+
```text
317+
warning: Rust code block is empty
318+
--> src/lib.rs:3:5
319+
|
320+
3 | /// ```rust
321+
| _____^
322+
4 | | /// ```
323+
| |_______^
324+
|
325+
= note: `#[warn(rustdoc::invalid_rust_codeblock)]` on by default
326+
327+
warning: Rust code block is empty
328+
--> src/lib.rs:8:5
329+
|
330+
8 | /// ```rust
331+
| ^^^^^^^
332+
```
333+
297334
## bare_urls
298335

299336
This lint is **warn-by-default**. It detects URLs which are not links.

Diff for: src/librustdoc/lint.rs

+13
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,26 @@ declare_rustdoc_lint! {
157157
"detects URLs that are not hyperlinks"
158158
}
159159

160+
declare_rustdoc_lint! {
161+
/// The `invalid_rust_codeblock` lint detects Rust code blocks in
162+
/// documentation examples that are invalid (e.g. empty, not parsable as
163+
/// Rust code). This is a `rustdoc` only lint, see the documentation in the
164+
/// [rustdoc book].
165+
///
166+
/// [rustdoc book]: ../../../rustdoc/lints.html#invalid_rust_codeblock
167+
INVALID_RUST_CODEBLOCK,
168+
Warn,
169+
"codeblock could not be parsed as valid Rust or is empty"
170+
}
171+
160172
crate static RUSTDOC_LINTS: Lazy<Vec<&'static Lint>> = Lazy::new(|| {
161173
vec![
162174
BROKEN_INTRA_DOC_LINKS,
163175
PRIVATE_INTRA_DOC_LINKS,
164176
MISSING_DOC_CODE_EXAMPLES,
165177
PRIVATE_DOC_TESTS,
166178
INVALID_CODEBLOCK_ATTRIBUTES,
179+
INVALID_RUST_CODEBLOCK,
167180
INVALID_HTML_TAGS,
168181
BARE_URLS,
169182
MISSING_CRATE_LEVEL_DOCS,

Diff for: src/librustdoc/passes/check_code_block_syntax.rs

+59-33
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use rustc_data_structures::sync::{Lock, Lrc};
22
use rustc_errors::{emitter::Emitter, Applicability, Diagnostic, Handler};
3+
use rustc_middle::lint::LintDiagnosticBuilder;
34
use rustc_parse::parse_stream_from_source_str;
45
use rustc_session::parse::ParseSess;
56
use rustc_span::source_map::{FilePathMapping, SourceMap};
@@ -47,50 +48,65 @@ impl<'a, 'tcx> SyntaxChecker<'a, 'tcx> {
4748
.unwrap_or(false);
4849
let buffer = buffer.borrow();
4950

50-
if buffer.has_errors || is_empty {
51-
let mut diag = if let Some(sp) = super::source_span_for_markdown_range(
52-
self.cx.tcx,
53-
&dox,
54-
&code_block.range,
55-
&item.attrs,
56-
) {
57-
let (warning_message, suggest_using_text) = if buffer.has_errors {
58-
("could not parse code block as Rust code", true)
51+
if !(buffer.has_errors || is_empty) {
52+
// No errors in a non-empty program.
53+
return;
54+
}
55+
56+
let local_id = match item.def_id.as_local() {
57+
Some(id) => id,
58+
// We don't need to check the syntax for other crates so returning
59+
// without doing anything should not be a problem.
60+
None => return,
61+
};
62+
63+
let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_id);
64+
let suggest_using_text = code_block.syntax.is_none() && code_block.is_fenced;
65+
let is_ignore = code_block.is_ignore;
66+
67+
// The span and whether it is precise or not.
68+
let (sp, precise_span) = match super::source_span_for_markdown_range(
69+
self.cx.tcx,
70+
&dox,
71+
&code_block.range,
72+
&item.attrs,
73+
) {
74+
Some(sp) => (sp, true),
75+
None => (item.attr_span(self.cx.tcx), false),
76+
};
77+
78+
// lambda that will use the lint to start a new diagnostic and add
79+
// a suggestion to it when needed.
80+
let diag_builder = |lint: LintDiagnosticBuilder<'_>| {
81+
let mut diag = if precise_span {
82+
let msg = if buffer.has_errors {
83+
"could not parse code block as Rust code"
5984
} else {
60-
("Rust code block is empty", false)
85+
"Rust code block is empty"
6186
};
6287

63-
let mut diag = self.cx.sess().struct_span_warn(sp, warning_message);
88+
let mut diag = lint.build(msg);
89+
90+
if suggest_using_text {
91+
let extended_msg = if is_ignore {
92+
"`ignore` code blocks require valid Rust code for syntax highlighting. \
93+
Mark blocks that do not contain Rust code as text"
94+
} else {
95+
"mark blocks that do not contain Rust code as text"
96+
};
6497

65-
if code_block.syntax.is_none() && code_block.is_fenced {
66-
let sp = sp.from_inner(InnerSpan::new(0, 3));
6798
diag.span_suggestion(
68-
sp,
69-
"mark blocks that do not contain Rust code as text",
99+
sp.from_inner(InnerSpan::new(0, 3)),
100+
extended_msg,
70101
String::from("```text"),
71102
Applicability::MachineApplicable,
72103
);
73-
} else if suggest_using_text && code_block.is_ignore {
74-
let sp = sp.from_inner(InnerSpan::new(0, 3));
75-
diag.span_suggestion(
76-
sp,
77-
"`ignore` code blocks require valid Rust code for syntax highlighting. \
78-
Mark blocks that do not contain Rust code as text",
79-
String::from("```text,"),
80-
Applicability::MachineApplicable,
81-
);
82104
}
83105

84106
diag
85107
} else {
86-
// We couldn't calculate the span of the markdown block that had the error, so our
87-
// diagnostics are going to be a bit lacking.
88-
let mut diag = self.cx.sess().struct_span_warn(
89-
item.attr_span(self.cx.tcx),
90-
"doc comment contains an invalid Rust code block",
91-
);
92-
93-
if code_block.syntax.is_none() && code_block.is_fenced {
108+
let mut diag = lint.build("doc comment contains an invalid Rust code block");
109+
if suggest_using_text {
94110
diag.help("mark blocks that do not contain Rust code as text: ```text");
95111
}
96112

@@ -103,7 +119,17 @@ impl<'a, 'tcx> SyntaxChecker<'a, 'tcx> {
103119
}
104120

105121
diag.emit();
106-
}
122+
};
123+
124+
// Finally build and emit the completed diagnostic.
125+
// All points of divergence have been handled earlier so this can be
126+
// done the same way whether the span is precise or not.
127+
self.cx.tcx.struct_span_lint_hir(
128+
crate::lint::INVALID_RUST_CODEBLOCK,
129+
hir_id,
130+
sp,
131+
diag_builder,
132+
);
107133
}
108134
}
109135

Diff for: src/test/rustdoc-ui/ignore-block-help.stderr

+1-4
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,8 @@ LL | | /// let heart = '❤️';
77
LL | | /// ```
88
| |_______^
99
|
10+
= note: `#[warn(invalid_rust_codeblock)]` on by default
1011
= note: error from rustc: character literal may only contain one codepoint
11-
help: `ignore` code blocks require valid Rust code for syntax highlighting. Mark blocks that do not contain Rust code as text
12-
|
13-
LL | /// ```text,ignore (to-prevent-tidy-error)
14-
| ^^^^^^^^
1512

1613
warning: 1 warning emitted
1714

Diff for: src/test/rustdoc-ui/invalid-syntax.stderr

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ LL | | /// \__________pkt->size___________/ \_result->size_/ \__pkt->si
77
LL | | /// ```
88
| |_______^
99
|
10+
= note: `#[warn(invalid_rust_codeblock)]` on by default
1011
= note: error from rustc: unknown start of token: \
1112
= note: error from rustc: unknown start of token: \
1213
= note: error from rustc: unknown start of token: \

0 commit comments

Comments
 (0)