rustdoc/passes/lint/
check_code_block_syntax.rs1use std::borrow::Cow;
4use std::sync::Arc;
5
6use rustc_data_structures::sync::Lock;
7use rustc_errors::emitter::Emitter;
8use rustc_errors::registry::Registry;
9use rustc_errors::translation::{Translator, to_fluent_args};
10use rustc_errors::{Applicability, DiagCtxt, DiagInner};
11use rustc_parse::{source_str_to_stream, unwrap_or_emit_fatal};
12use rustc_resolve::rustdoc::source_span_for_markdown_range;
13use rustc_session::parse::ParseSess;
14use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, Transparency};
15use rustc_span::source_map::{FilePathMapping, SourceMap};
16use rustc_span::{DUMMY_SP, FileName, InnerSpan};
17
18use crate::clean;
19use crate::core::DocContext;
20use crate::html::markdown::{self, RustCodeBlock};
21
22pub(crate) fn visit_item(cx: &DocContext<'_>, item: &clean::Item, dox: &str) {
23 if let Some(def_id) = item.item_id.as_local_def_id() {
24 let sp = item.attr_span(cx.tcx);
25 let extra = crate::html::markdown::ExtraInfo::new(cx.tcx, def_id, sp);
26 for code_block in markdown::rust_code_blocks(dox, &extra) {
27 check_rust_syntax(cx, item, dox, code_block);
28 }
29 }
30}
31
32fn check_rust_syntax(
33 cx: &DocContext<'_>,
34 item: &clean::Item,
35 dox: &str,
36 code_block: RustCodeBlock,
37) {
38 let buffer = Arc::new(Lock::new(Buffer::default()));
39 let translator = rustc_driver::default_translator();
40 let emitter = BufferEmitter { buffer: Arc::clone(&buffer), translator };
41
42 let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
43 let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings();
44 let source = dox[code_block.code]
45 .lines()
46 .map(|line| crate::html::markdown::map_line(line).for_code())
47 .intersperse(Cow::Borrowed("\n"))
48 .collect::<String>();
49 let psess = ParseSess::with_dcx(dcx, sm);
50
51 let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition());
52 let expn_data =
53 ExpnData::default(ExpnKind::AstPass(AstPass::TestHarness), DUMMY_SP, edition, None, None);
54 let expn_id = cx.tcx.with_stable_hashing_context(|hcx| LocalExpnId::fresh(expn_data, hcx));
55 let span = DUMMY_SP.apply_mark(expn_id.to_expn_id(), Transparency::Transparent);
56
57 let is_empty = rustc_driver::catch_fatal_errors(|| {
58 unwrap_or_emit_fatal(source_str_to_stream(
59 &psess,
60 FileName::Custom(String::from("doctest")),
61 source,
62 Some(span),
63 ))
64 .is_empty()
65 })
66 .unwrap_or(false);
67 let buffer = buffer.borrow();
68
69 if !buffer.has_errors && !is_empty {
70 return;
72 }
73
74 let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local()) else {
75 return;
78 };
79
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 let (sp, precise_span) = match source_span_for_markdown_range(
85 cx.tcx,
86 dox,
87 &code_block.range,
88 &item.attrs.doc_strings,
89 ) {
90 Some((sp, _)) => (sp, true),
91 None => (item.attr_span(cx.tcx), false),
92 };
93
94 let msg = if buffer.has_errors {
95 "could not parse code block as Rust code"
96 } else {
97 "Rust code block is empty"
98 };
99
100 let hir_id = cx.tcx.local_def_id_to_hir_id(local_id);
104 cx.tcx.node_span_lint(crate::lint::INVALID_RUST_CODEBLOCKS, hir_id, sp, |lint| {
105 lint.primary_message(msg);
106
107 let explanation = if is_ignore {
108 "`ignore` code blocks require valid Rust code for syntax highlighting; \
109 mark blocks that do not contain Rust code as text"
110 } else {
111 "mark blocks that do not contain Rust code as text"
112 };
113
114 if precise_span {
115 if is_ignore {
116 lint.span_help(
119 sp.from_inner(InnerSpan::new(0, 3)),
120 format!("{explanation}: ```text"),
121 );
122 } else if empty_block {
123 lint.span_suggestion(
124 sp.from_inner(InnerSpan::new(0, 3)).shrink_to_hi(),
125 explanation,
126 "text",
127 Applicability::MachineApplicable,
128 );
129 }
130 } else if empty_block || is_ignore {
131 lint.help(format!("{explanation}: ```text"));
132 }
133
134 for message in buffer.messages.iter() {
136 lint.note(message.clone());
137 }
138 });
139}
140
141#[derive(Default)]
142struct Buffer {
143 messages: Vec<String>,
144 has_errors: bool,
145}
146
147struct BufferEmitter {
148 buffer: Arc<Lock<Buffer>>,
149 translator: Translator,
150}
151
152impl Emitter for BufferEmitter {
153 fn emit_diagnostic(&mut self, diag: DiagInner, _registry: &Registry) {
154 let mut buffer = self.buffer.borrow_mut();
155
156 let fluent_args = to_fluent_args(diag.args.iter());
157 let translated_main_message = self
158 .translator
159 .translate_message(&diag.messages[0].0, &fluent_args)
160 .unwrap_or_else(|e| panic!("{e}"));
161
162 buffer.messages.push(format!("error from rustc: {translated_main_message}"));
163 if diag.is_error() {
164 buffer.has_errors = true;
165 }
166 }
167
168 fn source_map(&self) -> Option<&SourceMap> {
169 None
170 }
171
172 fn translator(&self) -> &Translator {
173 &self.translator
174 }
175}