1 use super::{span_of_attrs, Pass};
3 use crate::core::DocContext;
4 use crate::fold::DocFolder;
5 use crate::html::markdown::opts;
7 use pulldown_cmark::{Event, Parser};
8 use rustc_feature::UnstableFeatures;
9 use rustc_session::lint;
11 pub const CHECK_INVALID_HTML_TAGS: Pass = Pass {
12 name: "check-invalid-html-tags",
13 run: check_invalid_html_tags,
14 description: "detects invalid HTML tags in doc comments",
17 struct InvalidHtmlTagsLinter<'a, 'tcx> {
18 cx: &'a DocContext<'tcx>,
21 impl<'a, 'tcx> InvalidHtmlTagsLinter<'a, 'tcx> {
22 fn new(cx: &'a DocContext<'tcx>) -> Self {
23 InvalidHtmlTagsLinter { cx }
27 pub fn check_invalid_html_tags(krate: Crate, cx: &DocContext<'_>) -> Crate {
28 if !UnstableFeatures::from_environment().is_nightly_build() {
31 let mut coll = InvalidHtmlTagsLinter::new(cx);
33 coll.fold_crate(krate)
37 const ALLOWED_UNCLOSED: &[&str] = &[
38 "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
39 "source", "track", "wbr",
43 tags: &mut Vec<(String, Range<usize>)>,
46 f: &impl Fn(&str, &Range<usize>),
48 let tag_name_low = tag_name.to_lowercase();
49 if let Some(pos) = tags.iter().rposition(|(t, _)| t.to_lowercase() == tag_name_low) {
50 // If the tag is nested inside a "<script>" or a "<style>" tag, no warning should
52 let should_not_warn = tags.iter().take(pos + 1).any(|(at, _)| {
53 let at = at.to_lowercase();
54 at == "script" || at == "style"
56 for (last_tag_name, last_tag_span) in tags.drain(pos + 1..) {
60 let last_tag_name_low = last_tag_name.to_lowercase();
61 if ALLOWED_UNCLOSED.iter().any(|&at| at == &last_tag_name_low) {
64 // `tags` is used as a queue, meaning that everything after `pos` is included inside it.
65 // So `<h2><h3></h2>` will look like `["h2", "h3"]`. So when closing `h2`, we will still
66 // have `h3`, meaning the tag wasn't closed as it should have.
67 f(&format!("unclosed HTML tag `{}`", last_tag_name), &last_tag_span);
69 // Remove the `tag_name` that was originally closed
72 // It can happen for example in this case: `<h2></script></h2>` (the `h2` tag isn't required
73 // but it helps for the visualization).
74 f(&format!("unopened HTML tag `{}`", tag_name), &range);
79 tags: &mut Vec<(String, Range<usize>)>,
82 f: &impl Fn(&str, &Range<usize>),
84 let mut iter = text.char_indices().peekable();
86 while let Some((start_pos, c)) = iter.next() {
88 let mut tag_name = String::new();
89 let mut is_closing = false;
90 let mut prev_pos = start_pos;
92 let (pos, c) = match iter.peek() {
93 Some((pos, c)) => (*pos, *c),
94 // In case we reached the of the doc comment, we want to check that it's an
95 // unclosed HTML tag. For example "/// <h3".
96 None => (prev_pos, '\0'),
99 // Checking if this is a closing tag (like `</a>` for `<a>`).
100 if c == '/' && tag_name.is_empty() {
102 } else if c.is_ascii_alphanumeric() {
105 if !tag_name.is_empty() {
107 Range { start: range.start + start_pos, end: range.start + pos };
109 // In case we have a tag without attribute, we can consider the span to
110 // refer to it fully.
114 // In case we have "</div >" or even "</div >".
116 if !c.is_whitespace() {
117 // It seems like it's not a valid HTML tag.
120 let mut found = false;
121 for (new_pos, c) in text[pos..].char_indices() {
122 if !c.is_whitespace() {
124 r.end = range.start + new_pos + 1;
134 drop_tag(tags, tag_name, r, f);
136 tags.push((tag_name, r));
147 impl<'a, 'tcx> DocFolder for InvalidHtmlTagsLinter<'a, 'tcx> {
148 fn fold_item(&mut self, item: Item) -> Option<Item> {
149 let hir_id = match self.cx.as_local_hir_id(item.def_id) {
150 Some(hir_id) => hir_id,
152 // If non-local, no need to check anything.
153 return self.fold_item_recur(item);
156 let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
159 let report_diag = |msg: &str, range: &Range<usize>| {
160 let sp = match super::source_span_for_markdown_range(cx, &dox, range, &item.attrs) {
162 None => span_of_attrs(&item.attrs).unwrap_or(item.source.span()),
164 cx.tcx.struct_span_lint_hir(lint::builtin::INVALID_HTML_TAGS, hir_id, sp, |lint| {
165 lint.build(msg).emit()
169 let mut tags = Vec::new();
171 let p = Parser::new_ext(&dox, opts()).into_offset_iter();
173 for (event, range) in p {
175 Event::Html(text) => extract_tag(&mut tags, &text, range, &report_diag),
180 for (tag, range) in tags.iter().filter(|(t, _)| {
181 let t = t.to_lowercase();
182 ALLOWED_UNCLOSED.iter().find(|&&at| at == t).is_none()
184 report_diag(&format!("unclosed HTML tag `{}`", tag), range);
188 self.fold_item_recur(item)