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