rustdoc/passes/lint/
check_code_block_syntax.rs

1//! Validates syntax inside Rust code blocks (\`\`\`rust).
2
3use 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::{Translate, to_fluent_args};
10use rustc_errors::{Applicability, DiagCtxt, DiagInner, LazyFallbackBundle};
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 fallback_bundle = rustc_errors::fallback_fluent_bundle(
40        rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
41        false,
42    );
43    let emitter = BufferEmitter { buffer: Arc::clone(&buffer), fallback_bundle };
44
45    let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
46    let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings();
47    let source = dox[code_block.code]
48        .lines()
49        .map(|line| crate::html::markdown::map_line(line).for_code())
50        .intersperse(Cow::Borrowed("\n"))
51        .collect::<String>();
52    let psess = ParseSess::with_dcx(dcx, sm);
53
54    let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition());
55    let expn_data =
56        ExpnData::default(ExpnKind::AstPass(AstPass::TestHarness), DUMMY_SP, edition, None, None);
57    let expn_id = cx.tcx.with_stable_hashing_context(|hcx| LocalExpnId::fresh(expn_data, hcx));
58    let span = DUMMY_SP.apply_mark(expn_id.to_expn_id(), Transparency::Transparent);
59
60    let is_empty = rustc_driver::catch_fatal_errors(|| {
61        unwrap_or_emit_fatal(source_str_to_stream(
62            &psess,
63            FileName::Custom(String::from("doctest")),
64            source,
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()) else {
78        // We don't need to check the syntax for other crates so returning
79        // without doing anything should not be a problem.
80        return;
81    };
82
83    let empty_block = code_block.lang_string == Default::default() && code_block.is_fenced;
84    let is_ignore = code_block.lang_string.ignore != markdown::Ignore::None;
85
86    // The span and whether it is precise or not.
87    let (sp, precise_span) = match source_span_for_markdown_range(
88        cx.tcx,
89        dox,
90        &code_block.range,
91        &item.attrs.doc_strings,
92    ) {
93        Some(sp) => (sp, true),
94        None => (item.attr_span(cx.tcx), false),
95    };
96
97    let msg = if buffer.has_errors {
98        "could not parse code block as Rust code"
99    } else {
100        "Rust code block is empty"
101    };
102
103    // Finally build and emit the completed diagnostic.
104    // All points of divergence have been handled earlier so this can be
105    // done the same way whether the span is precise or not.
106    let hir_id = cx.tcx.local_def_id_to_hir_id(local_id);
107    cx.tcx.node_span_lint(crate::lint::INVALID_RUST_CODEBLOCKS, hir_id, sp, |lint| {
108        lint.primary_message(msg);
109
110        let explanation = if is_ignore {
111            "`ignore` code blocks require valid Rust code for syntax highlighting; \
112                    mark blocks that do not contain Rust code as text"
113        } else {
114            "mark blocks that do not contain Rust code as text"
115        };
116
117        if precise_span {
118            if is_ignore {
119                // giving an accurate suggestion is hard because `ignore` might not have come first in the list.
120                // just give a `help` instead.
121                lint.span_help(
122                    sp.from_inner(InnerSpan::new(0, 3)),
123                    format!("{explanation}: ```text"),
124                );
125            } else if empty_block {
126                lint.span_suggestion(
127                    sp.from_inner(InnerSpan::new(0, 3)).shrink_to_hi(),
128                    explanation,
129                    "text",
130                    Applicability::MachineApplicable,
131                );
132            }
133        } else if empty_block || is_ignore {
134            lint.help(format!("{explanation}: ```text"));
135        }
136
137        // FIXME(#67563): Provide more context for these errors by displaying the spans inline.
138        for message in buffer.messages.iter() {
139            lint.note(message.clone());
140        }
141    });
142}
143
144#[derive(Default)]
145struct Buffer {
146    messages: Vec<String>,
147    has_errors: bool,
148}
149
150struct BufferEmitter {
151    buffer: Arc<Lock<Buffer>>,
152    fallback_bundle: LazyFallbackBundle,
153}
154
155impl Translate for BufferEmitter {
156    fn fluent_bundle(&self) -> Option<&rustc_errors::FluentBundle> {
157        None
158    }
159
160    fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
161        &self.fallback_bundle
162    }
163}
164
165impl Emitter for BufferEmitter {
166    fn emit_diagnostic(&mut self, diag: DiagInner, _registry: &Registry) {
167        let mut buffer = self.buffer.borrow_mut();
168
169        let fluent_args = to_fluent_args(diag.args.iter());
170        let translated_main_message = self
171            .translate_message(&diag.messages[0].0, &fluent_args)
172            .unwrap_or_else(|e| panic!("{e}"));
173
174        buffer.messages.push(format!("error from rustc: {translated_main_message}"));
175        if diag.is_error() {
176            buffer.has_errors = true;
177        }
178    }
179
180    fn source_map(&self) -> Option<&SourceMap> {
181        None
182    }
183}