]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
rustdoc: update macro highlight tests
[rust.git] / src / tools / linkchecker / main.rs
1 //! Script to check the validity of `href` links in our HTML documentation.
2 //!
3 //! In the past we've been quite error prone to writing in broken links as most
4 //! of them are manually rather than automatically added. As files move over
5 //! time or apis change old links become stale or broken. The purpose of this
6 //! script is to check all relative links in our documentation to make sure they
7 //! actually point to a valid place.
8 //!
9 //! Currently this doesn't actually do any HTML parsing or anything fancy like
10 //! that, it just has a simple "regex" to search for `href` and `id` tags.
11 //! These values are then translated to file URLs if possible and then the
12 //! destination is asserted to exist.
13 //!
14 //! A few exceptions are allowed as there's known bugs in rustdoc, but this
15 //! should catch the majority of "broken link" cases.
16
17 #![cfg_attr(bootstrap, feature(str_split_once))]
18
19 use std::collections::hash_map::Entry;
20 use std::collections::{HashMap, HashSet};
21 use std::env;
22 use std::fs;
23 use std::path::{Component, Path, PathBuf};
24 use std::rc::Rc;
25
26 use once_cell::sync::Lazy;
27 use regex::Regex;
28
29 use crate::Redirect::*;
30
31 // Add linkcheck exceptions here
32 // If at all possible you should use intra-doc links to avoid linkcheck issues. These
33 // are cases where that does not work
34 // [(generated_documentation_page, &[broken_links])]
35 const LINKCHECK_EXCEPTIONS: &[(&str, &[&str])] = &[
36     // These try to link to std::collections, but are defined in alloc
37     // https://github.com/rust-lang/rust/issues/74481
38     ("std/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
39     ("std/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
40     ("alloc/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
41     ("alloc/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
42 ];
43
44 #[rustfmt::skip]
45 const INTRA_DOC_LINK_EXCEPTIONS: &[(&str, &[&str])] = &[
46     // This will never have links that are not in other pages.
47     // To avoid repeating the exceptions twice, an empty list means all broken links are allowed.
48     ("reference/print.html", &[]),
49     // All the reference 'links' are actually ENBF highlighted as code
50     ("reference/comments.html", &[
51          "/</code> <code>!",
52          "*</code> <code>!",
53     ]),
54     ("reference/identifiers.html", &[
55          "a</code>-<code>z</code> <code>A</code>-<code>Z",
56          "a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_",
57          "a</code>-<code>z</code> <code>A</code>-<code>Z</code>] [<code>a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_",
58     ]),
59     ("reference/tokens.html", &[
60          "0</code>-<code>1",
61          "0</code>-<code>7",
62          "0</code>-<code>9",
63          "0</code>-<code>9",
64          "0</code>-<code>9</code> <code>a</code>-<code>f</code> <code>A</code>-<code>F",
65     ]),
66     ("reference/notation.html", &[
67          "b</code> <code>B",
68          "a</code>-<code>z",
69     ]),
70     // This is being used in the sense of 'inclusive range', not a markdown link
71     ("core/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
72     ("std/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
73     ("core/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
74     ("alloc/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
75     ("std/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
76
77 ];
78
79 static BROKEN_INTRA_DOC_LINK: Lazy<Regex> =
80     Lazy::new(|| Regex::new(r#"\[<code>(.*)</code>\]"#).unwrap());
81
82 macro_rules! t {
83     ($e:expr) => {
84         match $e {
85             Ok(e) => e,
86             Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
87         }
88     };
89 }
90
91 fn main() {
92     let docs = env::args_os().nth(1).unwrap();
93     let docs = env::current_dir().unwrap().join(docs);
94     let mut errors = false;
95     walk(&mut HashMap::new(), &docs, &docs, &mut errors);
96     if errors {
97         panic!("found some broken links");
98     }
99 }
100
101 #[derive(Debug)]
102 pub enum LoadError {
103     IOError(std::io::Error),
104     BrokenRedirect(PathBuf, std::io::Error),
105     IsRedirect,
106 }
107
108 enum Redirect {
109     SkipRedirect,
110     FromRedirect(bool),
111 }
112
113 struct FileEntry {
114     source: Rc<String>,
115     ids: HashSet<String>,
116 }
117
118 type Cache = HashMap<PathBuf, FileEntry>;
119
120 fn small_url_encode(s: &str) -> String {
121     s.replace("<", "%3C")
122         .replace(">", "%3E")
123         .replace(" ", "%20")
124         .replace("?", "%3F")
125         .replace("'", "%27")
126         .replace("&", "%26")
127         .replace(",", "%2C")
128         .replace(":", "%3A")
129         .replace(";", "%3B")
130         .replace("[", "%5B")
131         .replace("]", "%5D")
132         .replace("\"", "%22")
133 }
134
135 impl FileEntry {
136     fn parse_ids(&mut self, file: &Path, contents: &str, errors: &mut bool) {
137         if self.ids.is_empty() {
138             with_attrs_in_source(contents, " id", |fragment, i, _| {
139                 let frag = fragment.trim_start_matches("#").to_owned();
140                 let encoded = small_url_encode(&frag);
141                 if !self.ids.insert(frag) {
142                     *errors = true;
143                     println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
144                 }
145                 // Just in case, we also add the encoded id.
146                 self.ids.insert(encoded);
147             });
148         }
149     }
150 }
151
152 fn walk(cache: &mut Cache, root: &Path, dir: &Path, errors: &mut bool) {
153     for entry in t!(dir.read_dir()).map(|e| t!(e)) {
154         let path = entry.path();
155         let kind = t!(entry.file_type());
156         if kind.is_dir() {
157             walk(cache, root, &path, errors);
158         } else {
159             let pretty_path = check(cache, root, &path, errors);
160             if let Some(pretty_path) = pretty_path {
161                 let entry = cache.get_mut(&pretty_path).unwrap();
162                 // we don't need the source anymore,
163                 // so drop to reduce memory-usage
164                 entry.source = Rc::new(String::new());
165             }
166         }
167     }
168 }
169
170 fn is_intra_doc_exception(file: &Path, link: &str) -> bool {
171     if let Some(entry) = INTRA_DOC_LINK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
172         entry.1.is_empty() || entry.1.contains(&link)
173     } else {
174         false
175     }
176 }
177
178 fn is_exception(file: &Path, link: &str) -> bool {
179     if let Some(entry) = LINKCHECK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
180         entry.1.contains(&link)
181     } else {
182         // FIXME(#63351): Concat trait in alloc/slice reexported in primitive page
183         //
184         // NOTE: This cannot be added to `LINKCHECK_EXCEPTIONS` because the resolved path
185         // calculated in `check` function is outside `build/<triple>/doc` dir.
186         // So the `strip_prefix` method just returns the old absolute broken path.
187         if file.ends_with("std/primitive.slice.html") {
188             if link.ends_with("primitive.slice.html") {
189                 return true;
190             }
191         }
192         false
193     }
194 }
195
196 fn check(cache: &mut Cache, root: &Path, file: &Path, errors: &mut bool) -> Option<PathBuf> {
197     // Ignore non-HTML files.
198     if file.extension().and_then(|s| s.to_str()) != Some("html") {
199         return None;
200     }
201
202     let res = load_file(cache, root, file, SkipRedirect);
203     let (pretty_file, contents) = match res {
204         Ok(res) => res,
205         Err(_) => return None,
206     };
207     {
208         cache.get_mut(&pretty_file).unwrap().parse_ids(&pretty_file, &contents, errors);
209     }
210
211     // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
212     with_attrs_in_source(&contents, " href", |url, i, base| {
213         // Ignore external URLs
214         if url.starts_with("http:")
215             || url.starts_with("https:")
216             || url.starts_with("javascript:")
217             || url.starts_with("ftp:")
218             || url.starts_with("irc:")
219             || url.starts_with("data:")
220         {
221             return;
222         }
223         let (url, fragment) = match url.split_once('#') {
224             None => (url, None),
225             Some((url, fragment)) => (url, Some(fragment)),
226         };
227         // NB: the `splitn` always succeeds, even if the delimiter is not present.
228         let url = url.splitn(2, '?').next().unwrap();
229
230         // Once we've plucked out the URL, parse it using our base url and
231         // then try to extract a file path.
232         let mut path = file.to_path_buf();
233         if !base.is_empty() || !url.is_empty() {
234             path.pop();
235             for part in Path::new(base).join(url).components() {
236                 match part {
237                     Component::Prefix(_) | Component::RootDir => {
238                         // Avoid absolute paths as they make the docs not
239                         // relocatable by making assumptions on where the docs
240                         // are hosted relative to the site root.
241                         *errors = true;
242                         println!(
243                             "{}:{}: absolute path - {}",
244                             pretty_file.display(),
245                             i + 1,
246                             Path::new(base).join(url).display()
247                         );
248                         return;
249                     }
250                     Component::CurDir => {}
251                     Component::ParentDir => {
252                         path.pop();
253                     }
254                     Component::Normal(s) => {
255                         path.push(s);
256                     }
257                 }
258             }
259         }
260
261         // Alright, if we've found a file name then this file had better
262         // exist! If it doesn't then we register and print an error.
263         if path.exists() {
264             if path.is_dir() {
265                 // Links to directories show as directory listings when viewing
266                 // the docs offline so it's best to avoid them.
267                 *errors = true;
268                 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
269                 println!(
270                     "{}:{}: directory link - {}",
271                     pretty_file.display(),
272                     i + 1,
273                     pretty_path.display()
274                 );
275                 return;
276             }
277             if let Some(extension) = path.extension() {
278                 // Ignore none HTML files.
279                 if extension != "html" {
280                     return;
281                 }
282             }
283             let res = load_file(cache, root, &path, FromRedirect(false));
284             let (pretty_path, contents) = match res {
285                 Ok(res) => res,
286                 Err(LoadError::IOError(err)) => {
287                     panic!("error loading {}: {}", path.display(), err);
288                 }
289                 Err(LoadError::BrokenRedirect(target, _)) => {
290                     *errors = true;
291                     println!(
292                         "{}:{}: broken redirect to {}",
293                         pretty_file.display(),
294                         i + 1,
295                         target.display()
296                     );
297                     return;
298                 }
299                 Err(LoadError::IsRedirect) => unreachable!(),
300             };
301
302             if let Some(ref fragment) = fragment {
303                 // Fragments like `#1-6` are most likely line numbers to be
304                 // interpreted by javascript, so we're ignoring these
305                 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
306                     return;
307                 }
308
309                 // These appear to be broken in mdbook right now?
310                 if fragment.starts_with('-') {
311                     return;
312                 }
313
314                 let entry = &mut cache.get_mut(&pretty_path).unwrap();
315                 entry.parse_ids(&pretty_path, &contents, errors);
316
317                 if !entry.ids.contains(*fragment) && !is_exception(file, &format!("#{}", fragment))
318                 {
319                     *errors = true;
320                     print!("{}:{}: broken link fragment ", pretty_file.display(), i + 1);
321                     println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
322                 };
323             }
324         } else {
325             let pretty_path = path.strip_prefix(root).unwrap_or(&path);
326             if !is_exception(file, pretty_path.to_str().unwrap()) {
327                 *errors = true;
328                 print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
329                 println!("{}", pretty_path.display());
330             }
331         }
332     });
333
334     // Search for intra-doc links that rustdoc didn't warn about
335     // FIXME(#77199, 77200) Rustdoc should just warn about these directly.
336     // NOTE: only looks at one line at a time; in practice this should find most links
337     for (i, line) in contents.lines().enumerate() {
338         for broken_link in BROKEN_INTRA_DOC_LINK.captures_iter(line) {
339             if !is_intra_doc_exception(file, &broken_link[1]) {
340                 *errors = true;
341                 print!("{}:{}: broken intra-doc link - ", pretty_file.display(), i + 1);
342                 println!("{}", &broken_link[0]);
343             }
344         }
345     }
346     Some(pretty_file)
347 }
348
349 fn load_file(
350     cache: &mut Cache,
351     root: &Path,
352     file: &Path,
353     redirect: Redirect,
354 ) -> Result<(PathBuf, Rc<String>), LoadError> {
355     let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
356
357     let (maybe_redirect, contents) = match cache.entry(pretty_file.clone()) {
358         Entry::Occupied(entry) => (None, entry.get().source.clone()),
359         Entry::Vacant(entry) => {
360             let contents = match fs::read_to_string(file) {
361                 Ok(s) => Rc::new(s),
362                 Err(err) => {
363                     return Err(if let FromRedirect(true) = redirect {
364                         LoadError::BrokenRedirect(file.to_path_buf(), err)
365                     } else {
366                         LoadError::IOError(err)
367                     });
368                 }
369             };
370
371             let maybe = maybe_redirect(&contents);
372             if maybe.is_some() {
373                 if let SkipRedirect = redirect {
374                     return Err(LoadError::IsRedirect);
375                 }
376             } else {
377                 entry.insert(FileEntry { source: contents.clone(), ids: HashSet::new() });
378             }
379             (maybe, contents)
380         }
381     };
382     match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
383         Some(redirect_file) => load_file(cache, root, &redirect_file, FromRedirect(true)),
384         None => Ok((pretty_file, contents)),
385     }
386 }
387
388 fn maybe_redirect(source: &str) -> Option<String> {
389     const REDIRECT: &str = "<p>Redirecting to <a href=";
390
391     let mut lines = source.lines();
392     let redirect_line = lines.nth(6)?;
393
394     redirect_line.find(REDIRECT).map(|i| {
395         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
396         let pos_quote = rest.find('"').unwrap();
397         rest[..pos_quote].to_owned()
398     })
399 }
400
401 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
402     let mut base = "";
403     for (i, mut line) in contents.lines().enumerate() {
404         while let Some(j) = line.find(attr) {
405             let rest = &line[j + attr.len()..];
406             // The base tag should always be the first link in the document so
407             // we can get away with using one pass.
408             let is_base = line[..j].ends_with("<base");
409             line = rest;
410             let pos_equals = match rest.find('=') {
411                 Some(i) => i,
412                 None => continue,
413             };
414             if rest[..pos_equals].trim_start_matches(' ') != "" {
415                 continue;
416             }
417
418             let rest = &rest[pos_equals + 1..];
419
420             let pos_quote = match rest.find(&['"', '\''][..]) {
421                 Some(i) => i,
422                 None => continue,
423             };
424             let quote_delim = rest.as_bytes()[pos_quote] as char;
425
426             if rest[..pos_quote].trim_start_matches(' ') != "" {
427                 continue;
428             }
429             let rest = &rest[pos_quote + 1..];
430             let url = match rest.find(quote_delim) {
431                 Some(i) => &rest[..i],
432                 None => continue,
433             };
434             if is_base {
435                 base = url;
436                 continue;
437             }
438             f(url, i, base)
439         }
440     }
441 }