rustdoc/passes/lint/
html_tags.rs

1//! Detects invalid HTML (like an unclosed `<span>`) in doc comments.
2
3use std::borrow::Cow;
4use std::iter::Peekable;
5use std::ops::Range;
6use std::str::CharIndices;
7
8use itertools::Itertools as _;
9use rustc_hir::HirId;
10use rustc_resolve::rustdoc::pulldown_cmark::{BrokenLink, Event, LinkType, Parser, Tag, TagEnd};
11use rustc_resolve::rustdoc::source_span_for_markdown_range;
12
13use crate::clean::*;
14use crate::core::DocContext;
15use crate::html::markdown::main_body_opts;
16
17pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item, hir_id: HirId, dox: &str) {
18    let tcx = cx.tcx;
19    let report_diag = |msg: String, range: &Range<usize>, is_open_tag: bool| {
20        let sp = match source_span_for_markdown_range(tcx, dox, range, &item.attrs.doc_strings) {
21            Some((sp, _)) => sp,
22            None => item.attr_span(tcx),
23        };
24        tcx.node_span_lint(crate::lint::INVALID_HTML_TAGS, hir_id, sp, |lint| {
25            use rustc_lint_defs::Applicability;
26
27            lint.primary_message(msg);
28
29            // If a tag looks like `<this>`, it might actually be a generic.
30            // We don't try to detect stuff `<like, this>` because that's not valid HTML,
31            // and we don't try to detect stuff `<like this>` because that's not valid Rust.
32            let mut generics_end = range.end;
33            if is_open_tag
34                && dox[..generics_end].ends_with('>')
35                && let Some(mut generics_start) = extract_path_backwards(dox, range.start)
36            {
37                while generics_start != 0
38                    && generics_end < dox.len()
39                    && dox.as_bytes()[generics_start - 1] == b'<'
40                    && dox.as_bytes()[generics_end] == b'>'
41                {
42                    generics_end += 1;
43                    generics_start -= 1;
44                    if let Some(new_start) = extract_path_backwards(dox, generics_start) {
45                        generics_start = new_start;
46                    }
47                    if let Some(new_end) = extract_path_forward(dox, generics_end) {
48                        generics_end = new_end;
49                    }
50                }
51                if let Some(new_end) = extract_path_forward(dox, generics_end) {
52                    generics_end = new_end;
53                }
54                let generics_sp = match source_span_for_markdown_range(
55                    tcx,
56                    dox,
57                    &(generics_start..generics_end),
58                    &item.attrs.doc_strings,
59                ) {
60                    Some((sp, _)) => sp,
61                    None => item.attr_span(tcx),
62                };
63                // Sometimes, we only extract part of a path. For example, consider this:
64                //
65                //     <[u32] as IntoIter<u32>>::Item
66                //                       ^^^^^ unclosed HTML tag `u32`
67                //
68                // We don't have any code for parsing fully-qualified trait paths.
69                // In theory, we could add it, but doing it correctly would require
70                // parsing the entire path grammar, which is problematic because of
71                // overlap between the path grammar and Markdown.
72                //
73                // The example above shows that ambiguity. Is `[u32]` intended to be an
74                // intra-doc link to the u32 primitive, or is it intended to be a slice?
75                //
76                // If the below conditional were removed, we would suggest this, which is
77                // not what the user probably wants.
78                //
79                //     <[u32] as `IntoIter<u32>`>::Item
80                //
81                // We know that the user actually wants to wrap the whole thing in a code
82                // block, but the only reason we know that is because `u32` does not, in
83                // fact, implement IntoIter. If the example looks like this:
84                //
85                //     <[Vec<i32>] as IntoIter<i32>::Item
86                //
87                // The ideal fix would be significantly different.
88                if (generics_start > 0 && dox.as_bytes()[generics_start - 1] == b'<')
89                    || (generics_end < dox.len() && dox.as_bytes()[generics_end] == b'>')
90                {
91                    return;
92                }
93                // multipart form is chosen here because ``Vec<i32>`` would be confusing.
94                lint.multipart_suggestion(
95                    "try marking as source code",
96                    vec![
97                        (generics_sp.shrink_to_lo(), String::from("`")),
98                        (generics_sp.shrink_to_hi(), String::from("`")),
99                    ],
100                    Applicability::MaybeIncorrect,
101                );
102            }
103        });
104    };
105
106    let mut tagp = TagParser::new();
107    let mut is_in_comment = None;
108    let mut in_code_block = false;
109
110    let link_names = item.link_names(&cx.cache);
111
112    let mut replacer = |broken_link: BrokenLink<'_>| {
113        if let Some(link) =
114            link_names.iter().find(|link| *link.original_text == *broken_link.reference)
115        {
116            Some((link.href.as_str().into(), link.new_text.to_string().into()))
117        } else if matches!(&broken_link.link_type, LinkType::Reference | LinkType::ReferenceUnknown)
118        {
119            // If the link is shaped [like][this], suppress any broken HTML in the [this] part.
120            // The `broken_intra_doc_links` will report typos in there anyway.
121            Some((
122                broken_link.reference.to_string().into(),
123                broken_link.reference.to_string().into(),
124            ))
125        } else {
126            None
127        }
128    };
129
130    let p = Parser::new_with_broken_link_callback(dox, main_body_opts(), Some(&mut replacer))
131        .into_offset_iter()
132        .coalesce(|a, b| {
133            // for some reason, pulldown-cmark splits html blocks into separate events for each line.
134            // we undo this, in order to handle multi-line tags.
135            match (a, b) {
136                ((Event::Html(_), ra), (Event::Html(_), rb)) if ra.end == rb.start => {
137                    let merged = ra.start..rb.end;
138                    Ok((Event::Html(Cow::Borrowed(&dox[merged.clone()]).into()), merged))
139                }
140                x => Err(x),
141            }
142        });
143
144    for (event, range) in p {
145        match event {
146            Event::Start(Tag::CodeBlock(_)) => in_code_block = true,
147            Event::Html(text) | Event::InlineHtml(text) if !in_code_block => {
148                tagp.extract_tags(&text, range, &mut is_in_comment, &report_diag)
149            }
150            Event::End(TagEnd::CodeBlock) => in_code_block = false,
151            _ => {}
152        }
153    }
154
155    if let Some(range) = is_in_comment {
156        report_diag("Unclosed HTML comment".to_string(), &range, false);
157    } else if let &Some(quote_pos) = &tagp.quote_pos {
158        let qr = Range { start: quote_pos, end: quote_pos };
159        report_diag(
160            format!("unclosed quoted HTML attribute on tag `{}`", &tagp.tag_name),
161            &qr,
162            false,
163        );
164    } else {
165        if !tagp.tag_name.is_empty() {
166            report_diag(
167                format!("incomplete HTML tag `{}`", &tagp.tag_name),
168                &(tagp.tag_start_pos..dox.len()),
169                false,
170            );
171        }
172        for (tag, range) in tagp.tags.iter().filter(|(t, _)| {
173            let t = t.to_lowercase();
174            !is_implicitly_self_closing(&t)
175        }) {
176            report_diag(format!("unclosed HTML tag `{tag}`"), range, true);
177        }
178    }
179}
180
181/// These tags are interpreted as self-closing if they lack an explicit closing tag.
182const ALLOWED_UNCLOSED: &[&str] = &[
183    "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
184    "source", "track", "wbr",
185];
186
187/// Allows constructs like `<img>`, but not `<img`.
188fn is_implicitly_self_closing(tag_name: &str) -> bool {
189    ALLOWED_UNCLOSED.contains(&tag_name)
190}
191
192fn extract_path_backwards(text: &str, end_pos: usize) -> Option<usize> {
193    use rustc_lexer::{is_id_continue, is_id_start};
194    let mut current_pos = end_pos;
195    loop {
196        if current_pos >= 2 && text[..current_pos].ends_with("::") {
197            current_pos -= 2;
198        }
199        let new_pos = text[..current_pos]
200            .char_indices()
201            .rev()
202            .take_while(|(_, c)| is_id_start(*c) || is_id_continue(*c))
203            .reduce(|_accum, item| item)
204            .and_then(|(new_pos, c)| is_id_start(c).then_some(new_pos));
205        if let Some(new_pos) = new_pos
206            && current_pos != new_pos
207        {
208            current_pos = new_pos;
209            continue;
210        }
211        break;
212    }
213    if current_pos == end_pos { None } else { Some(current_pos) }
214}
215
216fn extract_path_forward(text: &str, start_pos: usize) -> Option<usize> {
217    use rustc_lexer::{is_id_continue, is_id_start};
218    let mut current_pos = start_pos;
219    loop {
220        if current_pos < text.len() && text[current_pos..].starts_with("::") {
221            current_pos += 2;
222        } else {
223            break;
224        }
225        let mut chars = text[current_pos..].chars();
226        if let Some(c) = chars.next() {
227            if is_id_start(c) {
228                current_pos += c.len_utf8();
229            } else {
230                break;
231            }
232        }
233        for c in chars {
234            if is_id_continue(c) {
235                current_pos += c.len_utf8();
236            } else {
237                break;
238            }
239        }
240    }
241    if current_pos == start_pos { None } else { Some(current_pos) }
242}
243
244fn is_valid_for_html_tag_name(c: char, is_empty: bool) -> bool {
245    // https://spec.commonmark.org/0.30/#raw-html
246    //
247    // > A tag name consists of an ASCII letter followed by zero or more ASCII letters, digits, or
248    // > hyphens (-).
249    c.is_ascii_alphabetic() || !is_empty && (c == '-' || c.is_ascii_digit())
250}
251
252/// Parse html tags to ensure they are well-formed
253#[derive(Debug, Clone)]
254struct TagParser {
255    tags: Vec<(String, Range<usize>)>,
256    /// Name of the tag that is being parsed, if we are within a tag.
257    ///
258    /// Since the `<` and name of a tag must appear on the same line with no whitespace,
259    /// if this is the empty string, we are not in a tag.
260    tag_name: String,
261    tag_start_pos: usize,
262    is_closing: bool,
263    /// `true` if we are within a tag, but not within its name.
264    in_attrs: bool,
265    /// If we are in a quoted attribute, what quote char does it use?
266    ///
267    /// This needs to be stored in the struct since HTML5 allows newlines in quoted attrs.
268    quote: Option<char>,
269    quote_pos: Option<usize>,
270    after_eq: bool,
271}
272
273impl TagParser {
274    fn new() -> Self {
275        Self {
276            tags: Vec::new(),
277            tag_name: String::with_capacity(8),
278            tag_start_pos: 0,
279            is_closing: false,
280            in_attrs: false,
281            quote: None,
282            quote_pos: None,
283            after_eq: false,
284        }
285    }
286
287    fn drop_tag(&mut self, range: Range<usize>, f: &impl Fn(String, &Range<usize>, bool)) {
288        let tag_name_low = self.tag_name.to_lowercase();
289        if let Some(pos) = self.tags.iter().rposition(|(t, _)| t.to_lowercase() == tag_name_low) {
290            // If the tag is nested inside a "<script>" or a "<style>" tag, no warning should
291            // be emitted.
292            let should_not_warn = self.tags.iter().take(pos + 1).any(|(at, _)| {
293                let at = at.to_lowercase();
294                at == "script" || at == "style"
295            });
296            for (last_tag_name, last_tag_span) in self.tags.drain(pos + 1..) {
297                if should_not_warn {
298                    continue;
299                }
300                let last_tag_name_low = last_tag_name.to_lowercase();
301                if is_implicitly_self_closing(&last_tag_name_low) {
302                    continue;
303                }
304                // `tags` is used as a queue, meaning that everything after `pos` is included inside it.
305                // So `<h2><h3></h2>` will look like `["h2", "h3"]`. So when closing `h2`, we will still
306                // have `h3`, meaning the tag wasn't closed as it should have.
307                f(format!("unclosed HTML tag `{last_tag_name}`"), &last_tag_span, true);
308            }
309            // Remove the `tag_name` that was originally closed
310            self.tags.pop();
311        } else {
312            // It can happen for example in this case: `<h2></script></h2>` (the `h2` tag isn't required
313            // but it helps for the visualization).
314            f(format!("unopened HTML tag `{}`", &self.tag_name), &range, false);
315        }
316    }
317
318    /// Handle a `<` that appeared while parsing a tag.
319    fn handle_lt_in_tag(
320        &mut self,
321        range: Range<usize>,
322        lt_pos: usize,
323        f: &impl Fn(String, &Range<usize>, bool),
324    ) {
325        let global_pos = range.start + lt_pos;
326        // is this check needed?
327        if global_pos == self.tag_start_pos {
328            // `<` is in the tag because it is the start.
329            return;
330        }
331        // tried to start a new tag while in a tag
332        f(
333            format!("incomplete HTML tag `{}`", &self.tag_name),
334            &(self.tag_start_pos..global_pos),
335            false,
336        );
337        self.tag_parsed();
338    }
339
340    fn extract_html_tag(
341        &mut self,
342        text: &str,
343        range: &Range<usize>,
344        start_pos: usize,
345        iter: &mut Peekable<CharIndices<'_>>,
346        f: &impl Fn(String, &Range<usize>, bool),
347    ) {
348        let mut prev_pos = start_pos;
349
350        'outer_loop: loop {
351            let (pos, c) = match iter.peek() {
352                Some((pos, c)) => (*pos, *c),
353                // In case we reached the of the doc comment, we want to check that it's an
354                // unclosed HTML tag. For example "/// <h3".
355                None if self.tag_name.is_empty() => (prev_pos, '\0'),
356                None => break,
357            };
358            prev_pos = pos;
359            if c == '/' && self.tag_name.is_empty() {
360                // Checking if this is a closing tag (like `</a>` for `<a>`).
361                self.is_closing = true;
362            } else if !self.in_attrs && is_valid_for_html_tag_name(c, self.tag_name.is_empty()) {
363                self.tag_name.push(c);
364            } else {
365                if !self.tag_name.is_empty() {
366                    self.in_attrs = true;
367                    // range of the entire tag within dox
368                    let mut r = Range { start: range.start + start_pos, end: range.start + pos };
369                    if c == '>' {
370                        // In case we have a tag without attribute, we can consider the span to
371                        // refer to it fully.
372                        r.end += 1;
373                    }
374                    if self.is_closing {
375                        // In case we have "</div >" or even "</div         >".
376                        if c != '>' {
377                            if !c.is_whitespace() {
378                                // It seems like it's not a valid HTML tag.
379                                break;
380                            }
381                            let mut found = false;
382                            for (new_pos, c) in text[pos..].char_indices() {
383                                if !c.is_whitespace() {
384                                    if c == '>' {
385                                        r.end = range.start + pos + new_pos + 1;
386                                        found = true;
387                                    } else if c == '<' {
388                                        self.handle_lt_in_tag(range.clone(), pos + new_pos, f);
389                                    }
390                                    break;
391                                }
392                            }
393                            if !found {
394                                break 'outer_loop;
395                            }
396                        }
397                        self.drop_tag(r, f);
398                        self.tag_parsed();
399                    } else {
400                        self.extract_opening_tag(text, range, r, pos, c, iter, f)
401                    }
402                }
403                break;
404            }
405            iter.next();
406        }
407    }
408
409    fn extract_opening_tag(
410        &mut self,
411        text: &str,
412        range: &Range<usize>,
413        r: Range<usize>,
414        pos: usize,
415        c: char,
416        iter: &mut Peekable<CharIndices<'_>>,
417        f: &impl Fn(String, &Range<usize>, bool),
418    ) {
419        // we can store this as a local, since html5 does require the `/` and `>`
420        // to not be separated by whitespace.
421        let mut is_self_closing = false;
422        if c != '>' {
423            'parse_til_gt: {
424                for (i, c) in text[pos..].char_indices() {
425                    if !c.is_whitespace() {
426                        debug_assert_eq!(self.quote_pos.is_some(), self.quote.is_some());
427                        if let Some(q) = self.quote {
428                            if c == q {
429                                self.quote = None;
430                                self.quote_pos = None;
431                                self.after_eq = false;
432                            }
433                        } else if c == '>' {
434                            break 'parse_til_gt;
435                        } else if c == '<' {
436                            self.handle_lt_in_tag(range.clone(), pos + i, f);
437                        } else if c == '/' && !self.after_eq {
438                            is_self_closing = true;
439                        } else {
440                            if is_self_closing {
441                                is_self_closing = false;
442                            }
443                            if (c == '"' || c == '\'') && self.after_eq {
444                                self.quote = Some(c);
445                                self.quote_pos = Some(pos + i);
446                            } else if c == '=' {
447                                self.after_eq = true;
448                            }
449                        }
450                    } else if self.quote.is_none() {
451                        self.after_eq = false;
452                    }
453                    if !is_self_closing && !self.tag_name.is_empty() {
454                        iter.next();
455                    }
456                }
457                // if we've run out of text but still haven't found a `>`,
458                // return early without calling `tag_parsed` or emitting lints.
459                // this allows us to either find the `>` in a later event
460                // or emit a lint about it being missing.
461                return;
462            }
463        }
464        if is_self_closing {
465            // https://html.spec.whatwg.org/#parse-error-non-void-html-element-start-tag-with-trailing-solidus
466            let valid = ALLOWED_UNCLOSED.contains(&&self.tag_name[..])
467                || self.tags.iter().take(pos + 1).any(|(at, _)| {
468                    let at = at.to_lowercase();
469                    at == "svg" || at == "math"
470                });
471            if !valid {
472                f(format!("invalid self-closing HTML tag `{}`", self.tag_name), &r, false);
473            }
474        } else if !self.tag_name.is_empty() {
475            self.tags.push((std::mem::take(&mut self.tag_name), r));
476        }
477        self.tag_parsed();
478    }
479    /// Finished parsing a tag, reset related data.
480    fn tag_parsed(&mut self) {
481        self.tag_name.clear();
482        self.is_closing = false;
483        self.in_attrs = false;
484    }
485
486    fn extract_tags(
487        &mut self,
488        text: &str,
489        range: Range<usize>,
490        is_in_comment: &mut Option<Range<usize>>,
491        f: &impl Fn(String, &Range<usize>, bool),
492    ) {
493        let mut iter = text.char_indices().peekable();
494        let mut prev_pos = 0;
495        loop {
496            if self.quote.is_some() {
497                debug_assert!(self.in_attrs && self.quote_pos.is_some());
498            }
499            if self.in_attrs
500                && let Some(&(start_pos, _)) = iter.peek()
501            {
502                self.extract_html_tag(text, &range, start_pos, &mut iter, f);
503                // if no progress is being made, move forward forcefully.
504                if prev_pos == start_pos {
505                    iter.next();
506                }
507                prev_pos = start_pos;
508                continue;
509            }
510            let Some((start_pos, c)) = iter.next() else { break };
511            if is_in_comment.is_some() {
512                if text[start_pos..].starts_with("-->") {
513                    *is_in_comment = None;
514                }
515            } else if c == '<' {
516                // "<!--" is a valid attribute name under html5, so don't treat it as a comment if we're in a tag.
517                if self.tag_name.is_empty() && text[start_pos..].starts_with("<!--") {
518                    // We skip the "!--" part. (Once `advance_by` is stable, might be nice to use it!)
519                    iter.next();
520                    iter.next();
521                    iter.next();
522                    *is_in_comment = Some(Range {
523                        start: range.start + start_pos,
524                        end: range.start + start_pos + 4,
525                    });
526                } else {
527                    if self.tag_name.is_empty() {
528                        self.tag_start_pos = range.start + start_pos;
529                    }
530                    self.extract_html_tag(text, &range, start_pos, &mut iter, f);
531                }
532            } else if !self.tag_name.is_empty() {
533                // partially inside html tag that spans across events
534                self.extract_html_tag(text, &range, start_pos, &mut iter, f);
535            }
536        }
537    }
538}
539
540#[cfg(test)]
541mod tests;