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