]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/check_code_block_syntax.rs
Auto merge of #90583 - willcrichton:example-analyzer, r=jyn514
[rust.git] / src / librustdoc / passes / check_code_block_syntax.rs
1 use rustc_data_structures::sync::{Lock, Lrc};
2 use rustc_errors::{emitter::Emitter, Applicability, Diagnostic, Handler};
3 use rustc_middle::lint::LintDiagnosticBuilder;
4 use rustc_parse::parse_stream_from_source_str;
5 use rustc_session::parse::ParseSess;
6 use rustc_span::source_map::{FilePathMapping, SourceMap};
7 use rustc_span::{hygiene::AstPass, ExpnData, ExpnKind, FileName, InnerSpan, DUMMY_SP};
8
9 use crate::clean;
10 use crate::core::DocContext;
11 use crate::html::markdown::{self, RustCodeBlock};
12 use crate::passes::Pass;
13 use crate::visit::DocVisitor;
14
15 crate const CHECK_CODE_BLOCK_SYNTAX: Pass = Pass {
16     name: "check-code-block-syntax",
17     run: check_code_block_syntax,
18     description: "validates syntax inside Rust code blocks",
19 };
20
21 crate fn check_code_block_syntax(krate: clean::Crate, cx: &mut DocContext<'_>) -> clean::Crate {
22     SyntaxChecker { cx }.visit_crate(&krate);
23     krate
24 }
25
26 struct SyntaxChecker<'a, 'tcx> {
27     cx: &'a DocContext<'tcx>,
28 }
29
30 impl<'a, 'tcx> SyntaxChecker<'a, 'tcx> {
31     fn check_rust_syntax(&self, item: &clean::Item, dox: &str, code_block: RustCodeBlock) {
32         let buffer = Lrc::new(Lock::new(Buffer::default()));
33         let emitter = BufferEmitter { buffer: Lrc::clone(&buffer) };
34
35         let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
36         let handler = Handler::with_emitter(false, None, Box::new(emitter));
37         let source = dox[code_block.code].to_owned();
38         let sess = ParseSess::with_span_handler(handler, sm);
39
40         let edition = code_block.lang_string.edition.unwrap_or_else(|| self.cx.tcx.sess.edition());
41         let expn_data = ExpnData::default(
42             ExpnKind::AstPass(AstPass::TestHarness),
43             DUMMY_SP,
44             edition,
45             None,
46             None,
47         );
48         let span = DUMMY_SP.fresh_expansion(expn_data, self.cx.tcx.create_stable_hashing_context());
49
50         let is_empty = rustc_driver::catch_fatal_errors(|| {
51             parse_stream_from_source_str(
52                 FileName::Custom(String::from("doctest")),
53                 source,
54                 &sess,
55                 Some(span),
56             )
57             .is_empty()
58         })
59         .unwrap_or(false);
60         let buffer = buffer.borrow();
61
62         if !buffer.has_errors && !is_empty {
63             // No errors in a non-empty program.
64             return;
65         }
66
67         let local_id = match item.def_id.as_def_id().and_then(|x| x.as_local()) {
68             Some(id) => id,
69             // We don't need to check the syntax for other crates so returning
70             // without doing anything should not be a problem.
71             None => return,
72         };
73
74         let hir_id = self.cx.tcx.hir().local_def_id_to_hir_id(local_id);
75         let empty_block = code_block.lang_string == Default::default() && code_block.is_fenced;
76         let is_ignore = code_block.lang_string.ignore != markdown::Ignore::None;
77
78         // The span and whether it is precise or not.
79         let (sp, precise_span) = match super::source_span_for_markdown_range(
80             self.cx.tcx,
81             dox,
82             &code_block.range,
83             &item.attrs,
84         ) {
85             Some(sp) => (sp, true),
86             None => (item.attr_span(self.cx.tcx), false),
87         };
88
89         // lambda that will use the lint to start a new diagnostic and add
90         // a suggestion to it when needed.
91         let diag_builder = |lint: LintDiagnosticBuilder<'_>| {
92             let explanation = if is_ignore {
93                 "`ignore` code blocks require valid Rust code for syntax highlighting; \
94                     mark blocks that do not contain Rust code as text"
95             } else {
96                 "mark blocks that do not contain Rust code as text"
97             };
98             let msg = if buffer.has_errors {
99                 "could not parse code block as Rust code"
100             } else {
101                 "Rust code block is empty"
102             };
103             let mut diag = lint.build(msg);
104
105             if precise_span {
106                 if is_ignore {
107                     // giving an accurate suggestion is hard because `ignore` might not have come first in the list.
108                     // just give a `help` instead.
109                     diag.span_help(
110                         sp.from_inner(InnerSpan::new(0, 3)),
111                         &format!("{}: ```text", explanation),
112                     );
113                 } else if empty_block {
114                     diag.span_suggestion(
115                         sp.from_inner(InnerSpan::new(0, 3)).shrink_to_hi(),
116                         explanation,
117                         String::from("text"),
118                         Applicability::MachineApplicable,
119                     );
120                 }
121             } else if empty_block || is_ignore {
122                 diag.help(&format!("{}: ```text", explanation));
123             }
124
125             // FIXME(#67563): Provide more context for these errors by displaying the spans inline.
126             for message in buffer.messages.iter() {
127                 diag.note(message);
128             }
129
130             diag.emit();
131         };
132
133         // Finally build and emit the completed diagnostic.
134         // All points of divergence have been handled earlier so this can be
135         // done the same way whether the span is precise or not.
136         self.cx.tcx.struct_span_lint_hir(
137             crate::lint::INVALID_RUST_CODEBLOCKS,
138             hir_id,
139             sp,
140             diag_builder,
141         );
142     }
143 }
144
145 impl<'a, 'tcx> DocVisitor for SyntaxChecker<'a, 'tcx> {
146     fn visit_item(&mut self, item: &clean::Item) {
147         if let Some(dox) = &item.attrs.collapsed_doc_value() {
148             let sp = item.attr_span(self.cx.tcx);
149             let extra = crate::html::markdown::ExtraInfo::new_did(
150                 self.cx.tcx,
151                 item.def_id.expect_def_id(),
152                 sp,
153             );
154             for code_block in markdown::rust_code_blocks(dox, &extra) {
155                 self.check_rust_syntax(&item, dox, code_block);
156             }
157         }
158
159         self.visit_item_recur(item)
160     }
161 }
162
163 #[derive(Default)]
164 struct Buffer {
165     messages: Vec<String>,
166     has_errors: bool,
167 }
168
169 struct BufferEmitter {
170     buffer: Lrc<Lock<Buffer>>,
171 }
172
173 impl Emitter for BufferEmitter {
174     fn emit_diagnostic(&mut self, diag: &Diagnostic) {
175         let mut buffer = self.buffer.borrow_mut();
176         buffer.messages.push(format!("error from rustc: {}", diag.message[0].0));
177         if diag.is_error() {
178             buffer.has_errors = true;
179         }
180     }
181
182     fn source_map(&self) -> Option<&Lrc<SourceMap>> {
183         None
184     }
185 }