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