1 //! Validates syntax inside Rust code blocks (\`\`\`rust).
2 use rustc_data_structures::sync::{Lock, Lrc};
5 translation::{to_fluent_args, Translate},
6 Applicability, Diagnostic, Handler, LazyFallbackBundle,
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};
15 use crate::core::DocContext;
16 use crate::html::markdown::{self, RustCodeBlock};
17 use crate::passes::source_span_for_markdown_range;
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);
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);
34 code_block: RustCodeBlock,
36 let buffer = Lrc::new(Lock::new(Buffer::default()));
38 rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
39 let emitter = BufferEmitter { buffer: Lrc::clone(&buffer), fallback_bundle };
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);
46 let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition());
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);
52 let is_empty = rustc_driver::catch_fatal_errors(|| {
53 parse_stream_from_source_str(
54 FileName::Custom(String::from("doctest")),
62 let buffer = buffer.borrow();
64 if !buffer.has_errors && !is_empty {
65 // No errors in a non-empty program.
69 let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local())
71 // We don't need to check the syntax for other crates so returning
72 // without doing anything should not be a problem.
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;
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),
87 let msg = if buffer.has_errors {
88 "could not parse code block as Rust code"
90 "Rust code block is empty"
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"
101 "mark blocks that do not contain Rust code as text"
106 // giving an accurate suggestion is hard because `ignore` might not have come first in the list.
107 // just give a `help` instead.
109 sp.from_inner(InnerSpan::new(0, 3)),
110 &format!("{}: ```text", explanation),
112 } else if empty_block {
113 lint.span_suggestion(
114 sp.from_inner(InnerSpan::new(0, 3)).shrink_to_hi(),
117 Applicability::MachineApplicable,
120 } else if empty_block || is_ignore {
121 lint.help(&format!("{}: ```text", explanation));
124 // FIXME(#67563): Provide more context for these errors by displaying the spans inline.
125 for message in buffer.messages.iter() {
135 messages: Vec<String>,
139 struct BufferEmitter {
140 buffer: Lrc<Lock<Buffer>>,
141 fallback_bundle: LazyFallbackBundle,
144 impl Translate for BufferEmitter {
145 fn fluent_bundle(&self) -> Option<&Lrc<rustc_errors::FluentBundle>> {
149 fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
150 &**self.fallback_bundle
154 impl Emitter for BufferEmitter {
155 fn emit_diagnostic(&mut self, diag: &Diagnostic) {
156 let mut buffer = self.buffer.borrow_mut();
158 let fluent_args = to_fluent_args(diag.args());
159 let translated_main_message = self.translate_message(&diag.message[0].0, &fluent_args);
161 buffer.messages.push(format!("error from rustc: {}", translated_main_message));
163 buffer.has_errors = true;
167 fn source_map(&self) -> Option<&Lrc<SourceMap>> {