]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
Rollup merge of #89170 - rusticstuff:aarch64_macos_disable_leak_sanitizer, r=petrochenkov
[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 use std::cell::RefCell;
18 use std::collections::{HashMap, HashSet};
19 use std::env;
20 use std::fs;
21 use std::io::ErrorKind;
22 use std::path::{Component, Path, PathBuf};
23 use std::rc::Rc;
24 use std::time::Instant;
25
26 use once_cell::sync::Lazy;
27 use regex::Regex;
28
29 // Add linkcheck exceptions here
30 // If at all possible you should use intra-doc links to avoid linkcheck issues. These
31 // are cases where that does not work
32 // [(generated_documentation_page, &[broken_links])]
33 #[rustfmt::skip]
34 const LINKCHECK_EXCEPTIONS: &[(&str, &[&str])] = &[
35     // These try to link to std::collections, but are defined in alloc
36     // https://github.com/rust-lang/rust/issues/74481
37     ("std/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
38     ("std/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
39     ("alloc/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
40     ("alloc/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
41
42     // These try to link to various things in std, but are defined in core.
43     // The docs in std::primitive use proper intra-doc links, so these seem fine to special-case.
44     // Most these are broken because liballoc uses `#[lang_item]` magic to define things on
45     // primitives that aren't available in core.
46     ("alloc/slice/trait.Join.html", &["#method.join"]),
47     ("alloc/slice/trait.Concat.html", &["#method.concat"]),
48     ("alloc/slice/index.html", &["#method.concat", "#method.join"]),
49     ("alloc/vec/struct.Vec.html", &["#method.sort_by_key", "#method.sort_by_cached_key"]),
50     ("core/primitive.str.html", &["#method.to_ascii_uppercase", "#method.to_ascii_lowercase"]),
51     ("core/primitive.slice.html", &["#method.to_ascii_uppercase", "#method.to_ascii_lowercase",
52                                     "core/slice::sort_by_key", "core\\slice::sort_by_key",
53                                     "#method.sort_by_cached_key"]),
54 ];
55
56 #[rustfmt::skip]
57 const INTRA_DOC_LINK_EXCEPTIONS: &[(&str, &[&str])] = &[
58     // This will never have links that are not in other pages.
59     // To avoid repeating the exceptions twice, an empty list means all broken links are allowed.
60     ("reference/print.html", &[]),
61     // All the reference 'links' are actually ENBF highlighted as code
62     ("reference/comments.html", &[
63          "/</code> <code>!",
64          "*</code> <code>!",
65     ]),
66     ("reference/identifiers.html", &[
67          "a</code>-<code>z</code> <code>A</code>-<code>Z",
68          "a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_",
69          "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>_",
70     ]),
71     ("reference/tokens.html", &[
72          "0</code>-<code>1",
73          "0</code>-<code>7",
74          "0</code>-<code>9",
75          "0</code>-<code>9",
76          "0</code>-<code>9</code> <code>a</code>-<code>f</code> <code>A</code>-<code>F",
77     ]),
78     ("reference/notation.html", &[
79          "b</code> <code>B",
80          "a</code>-<code>z",
81     ]),
82     // This is being used in the sense of 'inclusive range', not a markdown link
83     ("core/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
84     ("std/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
85     ("core/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
86     ("alloc/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
87     ("std/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
88
89 ];
90
91 static BROKEN_INTRA_DOC_LINK: Lazy<Regex> =
92     Lazy::new(|| Regex::new(r#"\[<code>(.*)</code>\]"#).unwrap());
93
94 macro_rules! t {
95     ($e:expr) => {
96         match $e {
97             Ok(e) => e,
98             Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
99         }
100     };
101 }
102
103 fn main() {
104     let docs = env::args_os().nth(1).expect("doc path should be first argument");
105     let docs = env::current_dir().unwrap().join(docs);
106     let mut checker = Checker { root: docs.clone(), cache: HashMap::new() };
107     let mut report = Report {
108         errors: 0,
109         start: Instant::now(),
110         html_files: 0,
111         html_redirects: 0,
112         links_checked: 0,
113         links_ignored_external: 0,
114         links_ignored_exception: 0,
115         intra_doc_exceptions: 0,
116     };
117     checker.walk(&docs, &mut report);
118     report.report();
119     if report.errors != 0 {
120         println!("found some broken links");
121         std::process::exit(1);
122     }
123 }
124
125 struct Checker {
126     root: PathBuf,
127     cache: Cache,
128 }
129
130 struct Report {
131     errors: u32,
132     start: Instant,
133     html_files: u32,
134     html_redirects: u32,
135     links_checked: u32,
136     links_ignored_external: u32,
137     links_ignored_exception: u32,
138     intra_doc_exceptions: u32,
139 }
140
141 /// A cache entry.
142 enum FileEntry {
143     /// An HTML file.
144     ///
145     /// This includes the contents of the HTML file, and an optional set of
146     /// HTML IDs. The IDs are used for checking fragments. They are computed
147     /// as-needed. The source is discarded (replaced with an empty string)
148     /// after the file has been checked, to conserve on memory.
149     HtmlFile { source: Rc<String>, ids: RefCell<HashSet<String>> },
150     /// This file is an HTML redirect to the given local path.
151     Redirect { target: PathBuf },
152     /// This is not an HTML file.
153     OtherFile,
154     /// This is a directory.
155     Dir,
156     /// The file doesn't exist.
157     Missing,
158 }
159
160 /// A cache to speed up file access.
161 type Cache = HashMap<String, FileEntry>;
162
163 fn small_url_encode(s: &str) -> String {
164     s.replace("<", "%3C")
165         .replace(">", "%3E")
166         .replace(" ", "%20")
167         .replace("?", "%3F")
168         .replace("'", "%27")
169         .replace("&", "%26")
170         .replace(",", "%2C")
171         .replace(":", "%3A")
172         .replace(";", "%3B")
173         .replace("[", "%5B")
174         .replace("]", "%5D")
175         .replace("\"", "%22")
176 }
177
178 impl Checker {
179     /// Primary entry point for walking the filesystem to find HTML files to check.
180     fn walk(&mut self, dir: &Path, report: &mut Report) {
181         for entry in t!(dir.read_dir()).map(|e| t!(e)) {
182             let path = entry.path();
183             let kind = t!(entry.file_type());
184             if kind.is_dir() {
185                 self.walk(&path, report);
186             } else {
187                 self.check(&path, report);
188             }
189         }
190     }
191
192     /// Checks a single file.
193     fn check(&mut self, file: &Path, report: &mut Report) {
194         let (pretty_path, entry) = self.load_file(file, report);
195         let source = match entry {
196             FileEntry::Missing => panic!("missing file {:?} while walking", file),
197             FileEntry::Dir => unreachable!("never with `check` path"),
198             FileEntry::OtherFile => return,
199             FileEntry::Redirect { .. } => return,
200             FileEntry::HtmlFile { source, ids } => {
201                 parse_ids(&mut ids.borrow_mut(), &pretty_path, source, report);
202                 source.clone()
203             }
204         };
205
206         // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
207         with_attrs_in_source(&source, " href", |url, i, base| {
208             // Ignore external URLs
209             if url.starts_with("http:")
210                 || url.starts_with("https:")
211                 || url.starts_with("javascript:")
212                 || url.starts_with("ftp:")
213                 || url.starts_with("irc:")
214                 || url.starts_with("data:")
215             {
216                 report.links_ignored_external += 1;
217                 return;
218             }
219             report.links_checked += 1;
220             let (url, fragment) = match url.split_once('#') {
221                 None => (url, None),
222                 Some((url, fragment)) => (url, Some(fragment)),
223             };
224             // NB: the `splitn` always succeeds, even if the delimiter is not present.
225             let url = url.splitn(2, '?').next().unwrap();
226
227             // Once we've plucked out the URL, parse it using our base url and
228             // then try to extract a file path.
229             let mut path = file.to_path_buf();
230             if !base.is_empty() || !url.is_empty() {
231                 path.pop();
232                 for part in Path::new(base).join(url).components() {
233                     match part {
234                         Component::Prefix(_) | Component::RootDir => {
235                             // Avoid absolute paths as they make the docs not
236                             // relocatable by making assumptions on where the docs
237                             // are hosted relative to the site root.
238                             report.errors += 1;
239                             println!(
240                                 "{}:{}: absolute path - {}",
241                                 pretty_path,
242                                 i + 1,
243                                 Path::new(base).join(url).display()
244                             );
245                             return;
246                         }
247                         Component::CurDir => {}
248                         Component::ParentDir => {
249                             path.pop();
250                         }
251                         Component::Normal(s) => {
252                             path.push(s);
253                         }
254                     }
255                 }
256             }
257
258             let (target_pretty_path, target_entry) = self.load_file(&path, report);
259             let (target_source, target_ids) = match target_entry {
260                 FileEntry::Missing => {
261                     if is_exception(file, &target_pretty_path) {
262                         report.links_ignored_exception += 1;
263                     } else {
264                         report.errors += 1;
265                         println!(
266                             "{}:{}: broken link - `{}`",
267                             pretty_path,
268                             i + 1,
269                             target_pretty_path
270                         );
271                     }
272                     return;
273                 }
274                 FileEntry::Dir => {
275                     // Links to directories show as directory listings when viewing
276                     // the docs offline so it's best to avoid them.
277                     report.errors += 1;
278                     println!(
279                         "{}:{}: directory link to `{}` \
280                          (directory links should use index.html instead)",
281                         pretty_path,
282                         i + 1,
283                         target_pretty_path
284                     );
285                     return;
286                 }
287                 FileEntry::OtherFile => return,
288                 FileEntry::Redirect { target } => {
289                     let t = target.clone();
290                     drop(target);
291                     let (target, redir_entry) = self.load_file(&t, report);
292                     match redir_entry {
293                         FileEntry::Missing => {
294                             report.errors += 1;
295                             println!(
296                                 "{}:{}: broken redirect from `{}` to `{}`",
297                                 pretty_path,
298                                 i + 1,
299                                 target_pretty_path,
300                                 target
301                             );
302                             return;
303                         }
304                         FileEntry::Redirect { target } => {
305                             // Redirect to a redirect, this link checker
306                             // currently doesn't support this, since it would
307                             // require cycle checking, etc.
308                             report.errors += 1;
309                             println!(
310                                 "{}:{}: redirect from `{}` to `{}` \
311                                  which is also a redirect (not supported)",
312                                 pretty_path,
313                                 i + 1,
314                                 target_pretty_path,
315                                 target.display()
316                             );
317                             return;
318                         }
319                         FileEntry::Dir => {
320                             report.errors += 1;
321                             println!(
322                                 "{}:{}: redirect from `{}` to `{}` \
323                                  which is a directory \
324                                  (directory links should use index.html instead)",
325                                 pretty_path,
326                                 i + 1,
327                                 target_pretty_path,
328                                 target
329                             );
330                             return;
331                         }
332                         FileEntry::OtherFile => return,
333                         FileEntry::HtmlFile { source, ids } => (source, ids),
334                     }
335                 }
336                 FileEntry::HtmlFile { source, ids } => (source, ids),
337             };
338
339             // Alright, if we've found an HTML file for the target link. If
340             // this is a fragment link, also check that the `id` exists.
341             if let Some(ref fragment) = fragment {
342                 // Fragments like `#1-6` are most likely line numbers to be
343                 // interpreted by javascript, so we're ignoring these
344                 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
345                     return;
346                 }
347
348                 // These appear to be broken in mdbook right now?
349                 if fragment.starts_with('-') {
350                     return;
351                 }
352
353                 parse_ids(&mut target_ids.borrow_mut(), &pretty_path, target_source, report);
354
355                 if target_ids.borrow().contains(*fragment) {
356                     return;
357                 }
358
359                 if is_exception(file, &format!("#{}", fragment)) {
360                     report.links_ignored_exception += 1;
361                 } else {
362                     report.errors += 1;
363                     print!("{}:{}: broken link fragment ", pretty_path, i + 1);
364                     println!("`#{}` pointing to `{}`", fragment, target_pretty_path);
365                 };
366             }
367         });
368
369         // Search for intra-doc links that rustdoc didn't warn about
370         // FIXME(#77199, 77200) Rustdoc should just warn about these directly.
371         // NOTE: only looks at one line at a time; in practice this should find most links
372         for (i, line) in source.lines().enumerate() {
373             for broken_link in BROKEN_INTRA_DOC_LINK.captures_iter(line) {
374                 if is_intra_doc_exception(file, &broken_link[1]) {
375                     report.intra_doc_exceptions += 1;
376                 } else {
377                     report.errors += 1;
378                     print!("{}:{}: broken intra-doc link - ", pretty_path, i + 1);
379                     println!("{}", &broken_link[0]);
380                 }
381             }
382         }
383         // we don't need the source anymore,
384         // so drop to reduce memory-usage
385         match self.cache.get_mut(&pretty_path).unwrap() {
386             FileEntry::HtmlFile { source, .. } => *source = Rc::new(String::new()),
387             _ => unreachable!("must be html file"),
388         }
389     }
390
391     /// Load a file from disk, or from the cache if available.
392     fn load_file(&mut self, file: &Path, report: &mut Report) -> (String, &FileEntry) {
393         // https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
394         #[cfg(windows)]
395         const ERROR_INVALID_NAME: i32 = 123;
396
397         let pretty_path =
398             file.strip_prefix(&self.root).unwrap_or(&file).to_str().unwrap().to_string();
399
400         let entry =
401             self.cache.entry(pretty_path.clone()).or_insert_with(|| match fs::metadata(file) {
402                 Ok(metadata) if metadata.is_dir() => FileEntry::Dir,
403                 Ok(_) => {
404                     if file.extension().and_then(|s| s.to_str()) != Some("html") {
405                         FileEntry::OtherFile
406                     } else {
407                         report.html_files += 1;
408                         load_html_file(file, report)
409                     }
410                 }
411                 Err(e) if e.kind() == ErrorKind::NotFound => FileEntry::Missing,
412                 Err(e) => {
413                     // If a broken intra-doc link contains `::`, on windows, it will cause `ERROR_INVALID_NAME` rather than `NotFound`.
414                     // Explicitly check for that so that the broken link can be allowed in `LINKCHECK_EXCEPTIONS`.
415                     #[cfg(windows)]
416                     if e.raw_os_error() == Some(ERROR_INVALID_NAME)
417                         && file.as_os_str().to_str().map_or(false, |s| s.contains("::"))
418                     {
419                         return FileEntry::Missing;
420                     }
421                     panic!("unexpected read error for {}: {}", file.display(), e);
422                 }
423             });
424         (pretty_path, entry)
425     }
426 }
427
428 impl Report {
429     fn report(&self) {
430         println!("checked links in: {:.1}s", self.start.elapsed().as_secs_f64());
431         println!("number of HTML files scanned: {}", self.html_files);
432         println!("number of HTML redirects found: {}", self.html_redirects);
433         println!("number of links checked: {}", self.links_checked);
434         println!("number of links ignored due to external: {}", self.links_ignored_external);
435         println!("number of links ignored due to exceptions: {}", self.links_ignored_exception);
436         println!("number of intra doc links ignored: {}", self.intra_doc_exceptions);
437         println!("errors found: {}", self.errors);
438     }
439 }
440
441 fn load_html_file(file: &Path, report: &mut Report) -> FileEntry {
442     let source = match fs::read_to_string(file) {
443         Ok(s) => Rc::new(s),
444         Err(err) => {
445             // This usually should not fail since `metadata` was already
446             // called successfully on this file.
447             panic!("unexpected read error for {}: {}", file.display(), err);
448         }
449     };
450     match maybe_redirect(&source) {
451         Some(target) => {
452             report.html_redirects += 1;
453             let target = file.parent().unwrap().join(target);
454             FileEntry::Redirect { target }
455         }
456         None => FileEntry::HtmlFile { source: source.clone(), ids: RefCell::new(HashSet::new()) },
457     }
458 }
459
460 fn is_intra_doc_exception(file: &Path, link: &str) -> bool {
461     if let Some(entry) = INTRA_DOC_LINK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
462         entry.1.is_empty() || entry.1.contains(&link)
463     } else {
464         false
465     }
466 }
467
468 fn is_exception(file: &Path, link: &str) -> bool {
469     if let Some(entry) = LINKCHECK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
470         entry.1.contains(&link)
471     } else {
472         // FIXME(#63351): Concat trait in alloc/slice reexported in primitive page
473         //
474         // NOTE: This cannot be added to `LINKCHECK_EXCEPTIONS` because the resolved path
475         // calculated in `check` function is outside `build/<triple>/doc` dir.
476         // So the `strip_prefix` method just returns the old absolute broken path.
477         if file.ends_with("std/primitive.slice.html") {
478             if link.ends_with("primitive.slice.html") {
479                 return true;
480             }
481         }
482         false
483     }
484 }
485
486 /// If the given HTML file contents is an HTML redirect, this returns the
487 /// destination path given in the redirect.
488 fn maybe_redirect(source: &str) -> Option<String> {
489     const REDIRECT: &str = "<p>Redirecting to <a href=";
490
491     let mut lines = source.lines();
492     let redirect_line = lines.nth(7)?;
493
494     redirect_line.find(REDIRECT).map(|i| {
495         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
496         let pos_quote = rest.find('"').unwrap();
497         rest[..pos_quote].to_owned()
498     })
499 }
500
501 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(source: &str, attr: &str, mut f: F) {
502     let mut base = "";
503     for (i, mut line) in source.lines().enumerate() {
504         while let Some(j) = line.find(attr) {
505             let rest = &line[j + attr.len()..];
506             // The base tag should always be the first link in the document so
507             // we can get away with using one pass.
508             let is_base = line[..j].ends_with("<base");
509             line = rest;
510             let pos_equals = match rest.find('=') {
511                 Some(i) => i,
512                 None => continue,
513             };
514             if rest[..pos_equals].trim_start_matches(' ') != "" {
515                 continue;
516             }
517
518             let rest = &rest[pos_equals + 1..];
519
520             let pos_quote = match rest.find(&['"', '\''][..]) {
521                 Some(i) => i,
522                 None => continue,
523             };
524             let quote_delim = rest.as_bytes()[pos_quote] as char;
525
526             if rest[..pos_quote].trim_start_matches(' ') != "" {
527                 continue;
528             }
529             let rest = &rest[pos_quote + 1..];
530             let url = match rest.find(quote_delim) {
531                 Some(i) => &rest[..i],
532                 None => continue,
533             };
534             if is_base {
535                 base = url;
536                 continue;
537             }
538             f(url, i, base)
539         }
540     }
541 }
542
543 fn parse_ids(ids: &mut HashSet<String>, file: &str, source: &str, report: &mut Report) {
544     if ids.is_empty() {
545         with_attrs_in_source(source, " id", |fragment, i, _| {
546             let frag = fragment.trim_start_matches("#").to_owned();
547             let encoded = small_url_encode(&frag);
548             if !ids.insert(frag) {
549                 report.errors += 1;
550                 println!("{}:{}: id is not unique: `{}`", file, i, fragment);
551             }
552             // Just in case, we also add the encoded id.
553             ids.insert(encoded);
554         });
555     }
556 }