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