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