2022-11-22 19:42:49 -08:00
|
|
|
//! Validates syntax inside Rust code blocks (\`\`\`rust).
|
|
|
|
use rustc_data_structures::sync::{Lock, Lrc};
|
|
|
|
use rustc_errors::{
|
|
|
|
emitter::Emitter,
|
|
|
|
translation::{to_fluent_args, Translate},
|
2024-02-22 18:32:06 +11:00
|
|
|
Applicability, DiagCtxt, DiagInner, LazyFallbackBundle,
|
2022-11-22 19:42:49 -08:00
|
|
|
};
|
|
|
|
use rustc_parse::parse_stream_from_source_str;
|
2023-09-08 22:39:20 +00:00
|
|
|
use rustc_resolve::rustdoc::source_span_for_markdown_range;
|
2022-11-22 19:42:49 -08:00
|
|
|
use rustc_session::parse::ParseSess;
|
2024-01-05 17:11:25 +03:00
|
|
|
use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, Transparency};
|
2022-11-22 19:42:49 -08:00
|
|
|
use rustc_span::source_map::{FilePathMapping, SourceMap};
|
|
|
|
use rustc_span::{FileName, InnerSpan, DUMMY_SP};
|
|
|
|
|
|
|
|
use crate::clean;
|
|
|
|
use crate::core::DocContext;
|
|
|
|
use crate::html::markdown::{self, RustCodeBlock};
|
|
|
|
|
|
|
|
pub(crate) fn visit_item(cx: &DocContext<'_>, item: &clean::Item) {
|
2023-05-12 20:34:24 +03:00
|
|
|
if let Some(dox) = &item.opt_doc_value() {
|
2022-11-22 19:42:49 -08:00
|
|
|
let sp = item.attr_span(cx.tcx);
|
2023-01-26 14:30:28 +04:00
|
|
|
let extra = crate::html::markdown::ExtraInfo::new(cx.tcx, item.item_id.expect_def_id(), sp);
|
2023-09-17 14:52:45 +02:00
|
|
|
for code_block in
|
|
|
|
markdown::rust_code_blocks(dox, &extra, cx.tcx.features().custom_code_classes_in_docs)
|
|
|
|
{
|
2022-11-22 19:42:49 -08:00
|
|
|
check_rust_syntax(cx, item, dox, code_block);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_rust_syntax(
|
|
|
|
cx: &DocContext<'_>,
|
|
|
|
item: &clean::Item,
|
|
|
|
dox: &str,
|
|
|
|
code_block: RustCodeBlock,
|
|
|
|
) {
|
|
|
|
let buffer = Lrc::new(Lock::new(Buffer::default()));
|
2022-10-17 14:11:26 +01:00
|
|
|
let fallback_bundle = rustc_errors::fallback_fluent_bundle(
|
|
|
|
rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
|
|
|
|
false,
|
|
|
|
);
|
2022-11-22 19:42:49 -08:00
|
|
|
let emitter = BufferEmitter { buffer: Lrc::clone(&buffer), fallback_bundle };
|
|
|
|
|
|
|
|
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
|
2024-02-29 11:50:32 +11:00
|
|
|
let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings();
|
2022-11-22 19:42:49 -08:00
|
|
|
let source = dox[code_block.code].to_owned();
|
2023-12-18 11:15:13 +11:00
|
|
|
let sess = ParseSess::with_dcx(dcx, sm);
|
2022-11-22 19:42:49 -08:00
|
|
|
|
|
|
|
let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition());
|
|
|
|
let expn_data =
|
|
|
|
ExpnData::default(ExpnKind::AstPass(AstPass::TestHarness), DUMMY_SP, edition, None, None);
|
|
|
|
let expn_id = cx.tcx.with_stable_hashing_context(|hcx| LocalExpnId::fresh(expn_data, hcx));
|
2024-01-05 17:11:25 +03:00
|
|
|
let span = DUMMY_SP.apply_mark(expn_id.to_expn_id(), Transparency::Transparent);
|
2022-11-22 19:42:49 -08:00
|
|
|
|
|
|
|
let is_empty = rustc_driver::catch_fatal_errors(|| {
|
|
|
|
parse_stream_from_source_str(
|
|
|
|
FileName::Custom(String::from("doctest")),
|
|
|
|
source,
|
|
|
|
&sess,
|
|
|
|
Some(span),
|
|
|
|
)
|
|
|
|
.is_empty()
|
|
|
|
})
|
|
|
|
.unwrap_or(false);
|
|
|
|
let buffer = buffer.borrow();
|
|
|
|
|
|
|
|
if !buffer.has_errors && !is_empty {
|
|
|
|
// No errors in a non-empty program.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local()) else {
|
|
|
|
// We don't need to check the syntax for other crates so returning
|
|
|
|
// without doing anything should not be a problem.
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
|
|
|
let empty_block = code_block.lang_string == Default::default() && code_block.is_fenced;
|
|
|
|
let is_ignore = code_block.lang_string.ignore != markdown::Ignore::None;
|
|
|
|
|
|
|
|
// The span and whether it is precise or not.
|
2023-09-08 22:39:20 +00:00
|
|
|
let (sp, precise_span) = match source_span_for_markdown_range(
|
|
|
|
cx.tcx,
|
|
|
|
dox,
|
|
|
|
&code_block.range,
|
|
|
|
&item.attrs.doc_strings,
|
|
|
|
) {
|
|
|
|
Some(sp) => (sp, true),
|
|
|
|
None => (item.attr_span(cx.tcx), false),
|
|
|
|
};
|
2022-11-22 19:42:49 -08:00
|
|
|
|
|
|
|
let msg = if buffer.has_errors {
|
|
|
|
"could not parse code block as Rust code"
|
|
|
|
} else {
|
|
|
|
"Rust code block is empty"
|
|
|
|
};
|
|
|
|
|
|
|
|
// Finally build and emit the completed diagnostic.
|
|
|
|
// All points of divergence have been handled earlier so this can be
|
|
|
|
// done the same way whether the span is precise or not.
|
2023-11-24 19:28:19 +03:00
|
|
|
let hir_id = cx.tcx.local_def_id_to_hir_id(local_id);
|
2024-01-16 16:14:33 +11:00
|
|
|
cx.tcx.node_span_lint(crate::lint::INVALID_RUST_CODEBLOCKS, hir_id, sp, msg, |lint| {
|
2022-11-22 19:42:49 -08:00
|
|
|
let explanation = if is_ignore {
|
|
|
|
"`ignore` code blocks require valid Rust code for syntax highlighting; \
|
|
|
|
mark blocks that do not contain Rust code as text"
|
|
|
|
} else {
|
|
|
|
"mark blocks that do not contain Rust code as text"
|
|
|
|
};
|
|
|
|
|
|
|
|
if precise_span {
|
|
|
|
if is_ignore {
|
|
|
|
// giving an accurate suggestion is hard because `ignore` might not have come first in the list.
|
|
|
|
// just give a `help` instead.
|
|
|
|
lint.span_help(
|
|
|
|
sp.from_inner(InnerSpan::new(0, 3)),
|
2023-08-14 22:25:32 +02:00
|
|
|
format!("{explanation}: ```text"),
|
2022-11-22 19:42:49 -08:00
|
|
|
);
|
|
|
|
} else if empty_block {
|
|
|
|
lint.span_suggestion(
|
|
|
|
sp.from_inner(InnerSpan::new(0, 3)).shrink_to_hi(),
|
|
|
|
explanation,
|
|
|
|
"text",
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else if empty_block || is_ignore {
|
2023-08-14 22:25:32 +02:00
|
|
|
lint.help(format!("{explanation}: ```text"));
|
2022-11-22 19:42:49 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME(#67563): Provide more context for these errors by displaying the spans inline.
|
|
|
|
for message in buffer.messages.iter() {
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
lint.note(message.clone());
|
2022-11-22 19:42:49 -08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
struct Buffer {
|
|
|
|
messages: Vec<String>,
|
|
|
|
has_errors: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct BufferEmitter {
|
|
|
|
buffer: Lrc<Lock<Buffer>>,
|
|
|
|
fallback_bundle: LazyFallbackBundle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Translate for BufferEmitter {
|
|
|
|
fn fluent_bundle(&self) -> Option<&Lrc<rustc_errors::FluentBundle>> {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
|
|
|
|
&**self.fallback_bundle
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Emitter for BufferEmitter {
|
2024-02-22 18:32:06 +11:00
|
|
|
fn emit_diagnostic(&mut self, diag: DiagInner) {
|
2022-11-22 19:42:49 -08:00
|
|
|
let mut buffer = self.buffer.borrow_mut();
|
|
|
|
|
2024-02-16 06:07:49 +11:00
|
|
|
let fluent_args = to_fluent_args(diag.args.iter());
|
2023-01-08 23:35:43 +01:00
|
|
|
let translated_main_message = self
|
2023-12-20 17:12:17 +11:00
|
|
|
.translate_message(&diag.messages[0].0, &fluent_args)
|
2023-01-08 23:35:43 +01:00
|
|
|
.unwrap_or_else(|e| panic!("{e}"));
|
2022-11-22 19:42:49 -08:00
|
|
|
|
2023-08-14 22:25:32 +02:00
|
|
|
buffer.messages.push(format!("error from rustc: {translated_main_message}"));
|
2022-11-22 19:42:49 -08:00
|
|
|
if diag.is_error() {
|
|
|
|
buffer.has_errors = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn source_map(&self) -> Option<&Lrc<SourceMap>> {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|