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