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