1 //! Detects invalid HTML (like an unclosed `<span>`) in doc comments.
4 use crate::core::DocContext;
5 use crate::html::markdown::main_body_opts;
6 use crate::visit::DocVisitor;
8 use pulldown_cmark::{BrokenLink, Event, LinkType, Parser, Tag};
10 use std::iter::Peekable;
12 use std::str::CharIndices;
14 pub(crate) const CHECK_INVALID_HTML_TAGS: Pass = Pass {
15 name: "check-invalid-html-tags",
16 run: check_invalid_html_tags,
17 description: "detects invalid HTML tags in doc comments",
20 struct InvalidHtmlTagsLinter<'a, 'tcx> {
21 cx: &'a mut DocContext<'tcx>,
24 pub(crate) fn check_invalid_html_tags(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
25 if cx.tcx.sess.is_nightly_build() {
26 let mut coll = InvalidHtmlTagsLinter { cx };
27 coll.visit_crate(&krate);
32 const ALLOWED_UNCLOSED: &[&str] = &[
33 "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
34 "source", "track", "wbr",
38 tags: &mut Vec<(String, Range<usize>)>,
41 f: &impl Fn(&str, &Range<usize>, bool),
43 let tag_name_low = tag_name.to_lowercase();
44 if let Some(pos) = tags.iter().rposition(|(t, _)| t.to_lowercase() == tag_name_low) {
45 // If the tag is nested inside a "<script>" or a "<style>" tag, no warning should
47 let should_not_warn = tags.iter().take(pos + 1).any(|(at, _)| {
48 let at = at.to_lowercase();
49 at == "script" || at == "style"
51 for (last_tag_name, last_tag_span) in tags.drain(pos + 1..) {
55 let last_tag_name_low = last_tag_name.to_lowercase();
56 if ALLOWED_UNCLOSED.contains(&last_tag_name_low.as_str()) {
59 // `tags` is used as a queue, meaning that everything after `pos` is included inside it.
60 // So `<h2><h3></h2>` will look like `["h2", "h3"]`. So when closing `h2`, we will still
61 // have `h3`, meaning the tag wasn't closed as it should have.
62 f(&format!("unclosed HTML tag `{}`", last_tag_name), &last_tag_span, true);
64 // Remove the `tag_name` that was originally closed
67 // It can happen for example in this case: `<h2></script></h2>` (the `h2` tag isn't required
68 // but it helps for the visualization).
69 f(&format!("unopened HTML tag `{}`", tag_name), &range, false);
73 fn extract_path_backwards(text: &str, end_pos: usize) -> Option<usize> {
74 use rustc_lexer::{is_id_continue, is_id_start};
75 let mut current_pos = end_pos;
77 if current_pos >= 2 && text[..current_pos].ends_with("::") {
80 let new_pos = text[..current_pos]
83 .take_while(|(_, c)| is_id_start(*c) || is_id_continue(*c))
84 .reduce(|_accum, item| item)
85 .and_then(|(new_pos, c)| is_id_start(c).then_some(new_pos));
86 if let Some(new_pos) = new_pos {
87 if current_pos != new_pos {
88 current_pos = new_pos;
94 if current_pos == end_pos { None } else { Some(current_pos) }
97 fn is_valid_for_html_tag_name(c: char, is_empty: bool) -> bool {
98 // https://spec.commonmark.org/0.30/#raw-html
100 // > A tag name consists of an ASCII letter followed by zero or more ASCII letters, digits, or
102 c.is_ascii_alphabetic() || !is_empty && (c == '-' || c.is_ascii_digit())
106 tags: &mut Vec<(String, Range<usize>)>,
108 range: &Range<usize>,
110 iter: &mut Peekable<CharIndices<'_>>,
111 f: &impl Fn(&str, &Range<usize>, bool),
113 let mut tag_name = String::new();
114 let mut is_closing = false;
115 let mut prev_pos = start_pos;
118 let (pos, c) = match iter.peek() {
119 Some((pos, c)) => (*pos, *c),
120 // In case we reached the of the doc comment, we want to check that it's an
121 // unclosed HTML tag. For example "/// <h3".
122 None => (prev_pos, '\0'),
125 // Checking if this is a closing tag (like `</a>` for `<a>`).
126 if c == '/' && tag_name.is_empty() {
128 } else if is_valid_for_html_tag_name(c, tag_name.is_empty()) {
131 if !tag_name.is_empty() {
132 let mut r = Range { start: range.start + start_pos, end: range.start + pos };
134 // In case we have a tag without attribute, we can consider the span to
135 // refer to it fully.
139 // In case we have "</div >" or even "</div >".
141 if !c.is_whitespace() {
142 // It seems like it's not a valid HTML tag.
145 let mut found = false;
146 for (new_pos, c) in text[pos..].char_indices() {
147 if !c.is_whitespace() {
149 r.end = range.start + new_pos + 1;
159 drop_tag(tags, tag_name, r, f);
161 tags.push((tag_name, r));
171 tags: &mut Vec<(String, Range<usize>)>,
174 is_in_comment: &mut Option<Range<usize>>,
175 f: &impl Fn(&str, &Range<usize>, bool),
177 let mut iter = text.char_indices().peekable();
179 while let Some((start_pos, c)) = iter.next() {
180 if is_in_comment.is_some() {
181 if text[start_pos..].starts_with("-->") {
182 *is_in_comment = None;
185 if text[start_pos..].starts_with("<!--") {
186 // We skip the "!--" part. (Once `advance_by` is stable, might be nice to use it!)
190 *is_in_comment = Some(Range {
191 start: range.start + start_pos,
192 end: range.start + start_pos + 3,
195 extract_html_tag(tags, text, &range, start_pos, &mut iter, f);
201 impl<'a, 'tcx> DocVisitor for InvalidHtmlTagsLinter<'a, 'tcx> {
202 fn visit_item(&mut self, item: &Item) {
203 let tcx = self.cx.tcx;
204 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id)
205 // If non-local, no need to check anything.
207 let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
209 let report_diag = |msg: &str, range: &Range<usize>, is_open_tag: bool| {
210 let sp = match super::source_span_for_markdown_range(tcx, &dox, range, &item.attrs)
213 None => item.attr_span(tcx),
215 tcx.struct_span_lint_hir(crate::lint::INVALID_HTML_TAGS, hir_id, sp, |lint| {
216 use rustc_lint_defs::Applicability;
217 let mut diag = lint.build(msg);
218 // If a tag looks like `<this>`, it might actually be a generic.
219 // We don't try to detect stuff `<like, this>` because that's not valid HTML,
220 // and we don't try to detect stuff `<like this>` because that's not valid Rust.
221 if let Some(Some(generics_start)) = (is_open_tag
222 && dox[..range.end].ends_with('>'))
223 .then(|| extract_path_backwards(&dox, range.start))
225 let generics_sp = match super::source_span_for_markdown_range(
228 &(generics_start..range.end),
232 None => item.attr_span(tcx),
234 // multipart form is chosen here because ``Vec<i32>`` would be confusing.
235 diag.multipart_suggestion(
236 "try marking as source code",
238 (generics_sp.shrink_to_lo(), String::from("`")),
239 (generics_sp.shrink_to_hi(), String::from("`")),
241 Applicability::MaybeIncorrect,
248 let mut tags = Vec::new();
249 let mut is_in_comment = None;
250 let mut in_code_block = false;
252 let link_names = item.link_names(&self.cx.cache);
254 let mut replacer = |broken_link: BrokenLink<'_>| {
256 link_names.iter().find(|link| *link.original_text == *broken_link.reference)
258 Some((link.href.as_str().into(), link.new_text.as_str().into()))
260 &broken_link.link_type,
261 LinkType::Reference | LinkType::ReferenceUnknown
263 // If the link is shaped [like][this], suppress any broken HTML in the [this] part.
264 // The `broken_intra_doc_links` will report typos in there anyway.
266 broken_link.reference.to_string().into(),
267 broken_link.reference.to_string().into(),
275 Parser::new_with_broken_link_callback(&dox, main_body_opts(), Some(&mut replacer))
278 for (event, range) in p {
280 Event::Start(Tag::CodeBlock(_)) => in_code_block = true,
281 Event::Html(text) | Event::Text(text) if !in_code_block => {
282 extract_tags(&mut tags, &text, range, &mut is_in_comment, &report_diag)
284 Event::End(Tag::CodeBlock(_)) => in_code_block = false,
289 for (tag, range) in tags.iter().filter(|(t, _)| {
290 let t = t.to_lowercase();
291 !ALLOWED_UNCLOSED.contains(&t.as_str())
293 report_diag(&format!("unclosed HTML tag `{}`", tag), range, true);
296 if let Some(range) = is_in_comment {
297 report_diag("Unclosed HTML comment", &range, false);
301 self.visit_item_recur(item)