]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/html_tags.rs
Don't warn if the tag is nested inside a <script> or inside a <style>
[rust.git] / src / librustdoc / passes / html_tags.rs
1 use super::{span_of_attrs, Pass};
2 use crate::clean::*;
3 use crate::core::DocContext;
4 use crate::fold::DocFolder;
5 use crate::html::markdown::opts;
6 use core::ops::Range;
7 use pulldown_cmark::{Event, Parser};
8 use rustc_feature::UnstableFeatures;
9 use rustc_session::lint;
10
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",
15 };
16
17 struct InvalidHtmlTagsLinter<'a, 'tcx> {
18     cx: &'a DocContext<'tcx>,
19 }
20
21 impl<'a, 'tcx> InvalidHtmlTagsLinter<'a, 'tcx> {
22     fn new(cx: &'a DocContext<'tcx>) -> Self {
23         InvalidHtmlTagsLinter { cx }
24     }
25 }
26
27 pub fn check_invalid_html_tags(krate: Crate, cx: &DocContext<'_>) -> Crate {
28     if !UnstableFeatures::from_environment().is_nightly_build() {
29         krate
30     } else {
31         let mut coll = InvalidHtmlTagsLinter::new(cx);
32
33         coll.fold_crate(krate)
34     }
35 }
36
37 const ALLOWED_UNCLOSED: &[&str] = &[
38     "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
39     "source", "track", "wbr",
40 ];
41
42 fn drop_tag(
43     tags: &mut Vec<(String, Range<usize>)>,
44     tag_name: String,
45     range: Range<usize>,
46     f: &impl Fn(&str, &Range<usize>),
47 ) {
48     if let Some(pos) = tags.iter().rev().position(|(t, _)| *t == tag_name) {
49         // Because this is from a `rev` iterator, the position is reversed as well!
50         let pos = tags.len() - 1 - pos;
51         // If the tag is nested inside a "<script>", not warning should be emitted.
52         let should_not_warn =
53             tags.iter().take(pos + 1).any(|(at, _)| at == "script" || at == "style");
54         for (last_tag_name, last_tag_span) in tags.drain(pos + 1..) {
55             if should_not_warn || ALLOWED_UNCLOSED.iter().any(|&at| at == &last_tag_name) {
56                 continue;
57             }
58             // `tags` is used as a queue, meaning that everything after `pos` is included inside it.
59             // So `<h2><h3></h2>` will look like `["h2", "h3"]`. So when closing `h2`, we will still
60             // have `h3`, meaning the tag wasn't closed as it should have.
61             f(&format!("unclosed HTML tag `{}`", last_tag_name), &last_tag_span);
62         }
63         // Remove the `tag_name` that was originally closed
64         tags.pop();
65     } else {
66         // It can happen for example in this case: `<h2></script></h2>` (the `h2` tag isn't required
67         // but it helps for the visualization).
68         f(&format!("unopened HTML tag `{}`", tag_name), &range);
69     }
70 }
71
72 fn extract_tag(
73     tags: &mut Vec<(String, Range<usize>)>,
74     text: &str,
75     range: Range<usize>,
76     f: &impl Fn(&str, &Range<usize>),
77 ) {
78     let mut iter = text.chars().enumerate().peekable();
79
80     while let Some((start_pos, c)) = iter.next() {
81         if c == '<' {
82             let mut tag_name = String::new();
83             let mut is_closing = false;
84             while let Some((pos, c)) = iter.peek() {
85                 // Checking if this is a closing tag (like `</a>` for `<a>`).
86                 if *c == '/' && tag_name.is_empty() {
87                     is_closing = true;
88                 } else if c.is_ascii_alphanumeric() && !c.is_ascii_uppercase() {
89                     tag_name.push(*c);
90                 } else {
91                     if !tag_name.is_empty() {
92                         let mut r =
93                             Range { start: range.start + start_pos, end: range.start + pos };
94                         if *c == '>' {
95                             // In case we have a tag without attribute, we can consider the span to
96                             // refer to it fully.
97                             r.end += 1;
98                         }
99                         if is_closing {
100                             drop_tag(tags, tag_name, r, f);
101                         } else {
102                             tags.push((tag_name, r));
103                         }
104                     }
105                     break;
106                 }
107                 iter.next();
108             }
109         }
110     }
111 }
112
113 impl<'a, 'tcx> DocFolder for InvalidHtmlTagsLinter<'a, 'tcx> {
114     fn fold_item(&mut self, item: Item) -> Option<Item> {
115         let hir_id = match self.cx.as_local_hir_id(item.def_id) {
116             Some(hir_id) => hir_id,
117             None => {
118                 // If non-local, no need to check anything.
119                 return self.fold_item_recur(item);
120             }
121         };
122         let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
123         if !dox.is_empty() {
124             let cx = &self.cx;
125             let report_diag = |msg: &str, range: &Range<usize>| {
126                 let sp = match super::source_span_for_markdown_range(cx, &dox, range, &item.attrs) {
127                     Some(sp) => sp,
128                     None => span_of_attrs(&item.attrs).unwrap_or(item.source.span()),
129                 };
130                 cx.tcx.struct_span_lint_hir(lint::builtin::INVALID_HTML_TAGS, hir_id, sp, |lint| {
131                     lint.build(msg).emit()
132                 });
133             };
134
135             let mut tags = Vec::new();
136
137             let p = Parser::new_ext(&dox, opts()).into_offset_iter();
138
139             for (event, range) in p {
140                 match event {
141                     Event::Html(text) => extract_tag(&mut tags, &text, range, &report_diag),
142                     _ => {}
143                 }
144             }
145
146             for (tag, range) in
147                 tags.iter().filter(|(t, _)| ALLOWED_UNCLOSED.iter().find(|&at| at == t).is_none())
148             {
149                 report_diag(&format!("unclosed HTML tag `{}`", tag), range);
150             }
151         }
152
153         self.fold_item_recur(item)
154     }
155 }