]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/html_tags.rs
Rollup merge of #93219 - cr1901:msp430-asm-squashed, r=Amanieu
[rust.git] / src / librustdoc / passes / html_tags.rs
1 //! Detects invalid HTML (like an unclosed `<span>`) in doc comments.
2 use super::Pass;
3 use crate::clean::*;
4 use crate::core::DocContext;
5 use crate::html::markdown::main_body_opts;
6 use crate::visit::DocVisitor;
7
8 use pulldown_cmark::{Event, Parser, Tag};
9
10 use std::iter::Peekable;
11 use std::ops::Range;
12 use std::str::CharIndices;
13
14 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",
18 };
19
20 struct InvalidHtmlTagsLinter<'a, 'tcx> {
21     cx: &'a mut DocContext<'tcx>,
22 }
23
24 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);
28     }
29     krate
30 }
31
32 const ALLOWED_UNCLOSED: &[&str] = &[
33     "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
34     "source", "track", "wbr",
35 ];
36
37 fn drop_tag(
38     tags: &mut Vec<(String, Range<usize>)>,
39     tag_name: String,
40     range: Range<usize>,
41     f: &impl Fn(&str, &Range<usize>),
42 ) {
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
46         // be emitted.
47         let should_not_warn = tags.iter().take(pos + 1).any(|(at, _)| {
48             let at = at.to_lowercase();
49             at == "script" || at == "style"
50         });
51         for (last_tag_name, last_tag_span) in tags.drain(pos + 1..) {
52             if should_not_warn {
53                 continue;
54             }
55             let last_tag_name_low = last_tag_name.to_lowercase();
56             if ALLOWED_UNCLOSED.contains(&last_tag_name_low.as_str()) {
57                 continue;
58             }
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);
63         }
64         // Remove the `tag_name` that was originally closed
65         tags.pop();
66     } else {
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);
70     }
71 }
72
73 fn extract_html_tag(
74     tags: &mut Vec<(String, Range<usize>)>,
75     text: &str,
76     range: &Range<usize>,
77     start_pos: usize,
78     iter: &mut Peekable<CharIndices<'_>>,
79     f: &impl Fn(&str, &Range<usize>),
80 ) {
81     let mut tag_name = String::new();
82     let mut is_closing = false;
83     let mut prev_pos = start_pos;
84
85     loop {
86         let (pos, c) = match iter.peek() {
87             Some((pos, c)) => (*pos, *c),
88             // In case we reached the of the doc comment, we want to check that it's an
89             // unclosed HTML tag. For example "/// <h3".
90             None => (prev_pos, '\0'),
91         };
92         prev_pos = pos;
93         // Checking if this is a closing tag (like `</a>` for `<a>`).
94         if c == '/' && tag_name.is_empty() {
95             is_closing = true;
96         } else if c.is_ascii_alphanumeric() {
97             tag_name.push(c);
98         } else {
99             if !tag_name.is_empty() {
100                 let mut r = Range { start: range.start + start_pos, end: range.start + pos };
101                 if c == '>' {
102                     // In case we have a tag without attribute, we can consider the span to
103                     // refer to it fully.
104                     r.end += 1;
105                 }
106                 if is_closing {
107                     // In case we have "</div >" or even "</div         >".
108                     if c != '>' {
109                         if !c.is_whitespace() {
110                             // It seems like it's not a valid HTML tag.
111                             break;
112                         }
113                         let mut found = false;
114                         for (new_pos, c) in text[pos..].char_indices() {
115                             if !c.is_whitespace() {
116                                 if c == '>' {
117                                     r.end = range.start + new_pos + 1;
118                                     found = true;
119                                 }
120                                 break;
121                             }
122                         }
123                         if !found {
124                             break;
125                         }
126                     }
127                     drop_tag(tags, tag_name, r, f);
128                 } else {
129                     tags.push((tag_name, r));
130                 }
131             }
132             break;
133         }
134         iter.next();
135     }
136 }
137
138 fn extract_tags(
139     tags: &mut Vec<(String, Range<usize>)>,
140     text: &str,
141     range: Range<usize>,
142     is_in_comment: &mut Option<Range<usize>>,
143     f: &impl Fn(&str, &Range<usize>),
144 ) {
145     let mut iter = text.char_indices().peekable();
146
147     while let Some((start_pos, c)) = iter.next() {
148         if is_in_comment.is_some() {
149             if text[start_pos..].starts_with("-->") {
150                 *is_in_comment = None;
151             }
152         } else if c == '<' {
153             if text[start_pos..].starts_with("<!--") {
154                 // We skip the "!--" part. (Once `advance_by` is stable, might be nice to use it!)
155                 iter.next();
156                 iter.next();
157                 iter.next();
158                 *is_in_comment = Some(Range {
159                     start: range.start + start_pos,
160                     end: range.start + start_pos + 3,
161                 });
162             } else {
163                 extract_html_tag(tags, text, &range, start_pos, &mut iter, f);
164             }
165         }
166     }
167 }
168
169 impl<'a, 'tcx> DocVisitor for InvalidHtmlTagsLinter<'a, 'tcx> {
170     fn visit_item(&mut self, item: &Item) {
171         let tcx = self.cx.tcx;
172         let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
173             Some(hir_id) => hir_id,
174             None => {
175                 // If non-local, no need to check anything.
176                 return;
177             }
178         };
179         let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
180         if !dox.is_empty() {
181             let report_diag = |msg: &str, range: &Range<usize>| {
182                 let sp = match super::source_span_for_markdown_range(tcx, &dox, range, &item.attrs)
183                 {
184                     Some(sp) => sp,
185                     None => item.attr_span(tcx),
186                 };
187                 tcx.struct_span_lint_hir(crate::lint::INVALID_HTML_TAGS, hir_id, sp, |lint| {
188                     lint.build(msg).emit()
189                 });
190             };
191
192             let mut tags = Vec::new();
193             let mut is_in_comment = None;
194             let mut in_code_block = false;
195
196             let p = Parser::new_ext(&dox, main_body_opts()).into_offset_iter();
197
198             for (event, range) in p {
199                 match event {
200                     Event::Start(Tag::CodeBlock(_)) => in_code_block = true,
201                     Event::Html(text) | Event::Text(text) if !in_code_block => {
202                         extract_tags(&mut tags, &text, range, &mut is_in_comment, &report_diag)
203                     }
204                     Event::End(Tag::CodeBlock(_)) => in_code_block = false,
205                     _ => {}
206                 }
207             }
208
209             for (tag, range) in tags.iter().filter(|(t, _)| {
210                 let t = t.to_lowercase();
211                 !ALLOWED_UNCLOSED.contains(&t.as_str())
212             }) {
213                 report_diag(&format!("unclosed HTML tag `{}`", tag), range);
214             }
215
216             if let Some(range) = is_in_comment {
217                 report_diag("Unclosed HTML comment", &range);
218             }
219         }
220
221         self.visit_item_recur(item)
222     }
223 }