]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/check.rs
rustdoc: Hide `self: Box<Self>` in list of deref methods
[rust.git] / src / bootstrap / check.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Implementation of the test-related targets of the build system.
12 //!
13 //! This file implements the various regression test suites that we execute on
14 //! our CI.
15
16 extern crate build_helper;
17
18 use std::collections::HashSet;
19 use std::env;
20 use std::fmt;
21 use std::fs;
22 use std::path::{PathBuf, Path};
23 use std::process::Command;
24
25 use build_helper::output;
26
27 use {Build, Compiler, Mode};
28 use dist;
29 use util::{self, dylib_path, dylib_path_var, exe};
30
31 const ADB_TEST_DIR: &'static str = "/data/tmp/work";
32
33 /// The two modes of the test runner; tests or benchmarks.
34 #[derive(Copy, Clone)]
35 pub enum TestKind {
36     /// Run `cargo test`
37     Test,
38     /// Run `cargo bench`
39     Bench,
40 }
41
42 impl TestKind {
43     // Return the cargo subcommand for this test kind
44     fn subcommand(self) -> &'static str {
45         match self {
46             TestKind::Test => "test",
47             TestKind::Bench => "bench",
48         }
49     }
50 }
51
52 impl fmt::Display for TestKind {
53     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54         f.write_str(match *self {
55             TestKind::Test => "Testing",
56             TestKind::Bench => "Benchmarking",
57         })
58     }
59 }
60
61 /// Runs the `linkchecker` tool as compiled in `stage` by the `host` compiler.
62 ///
63 /// This tool in `src/tools` will verify the validity of all our links in the
64 /// documentation to ensure we don't have a bunch of dead ones.
65 pub fn linkcheck(build: &Build, host: &str) {
66     println!("Linkcheck ({})", host);
67     let compiler = Compiler::new(0, host);
68
69     let _time = util::timeit();
70     build.run(build.tool_cmd(&compiler, "linkchecker")
71                    .arg(build.out.join(host).join("doc")));
72 }
73
74 /// Runs the `cargotest` tool as compiled in `stage` by the `host` compiler.
75 ///
76 /// This tool in `src/tools` will check out a few Rust projects and run `cargo
77 /// test` to ensure that we don't regress the test suites there.
78 pub fn cargotest(build: &Build, stage: u32, host: &str) {
79     let ref compiler = Compiler::new(stage, host);
80
81     // Note that this is a short, cryptic, and not scoped directory name. This
82     // is currently to minimize the length of path on Windows where we otherwise
83     // quickly run into path name limit constraints.
84     let out_dir = build.out.join("ct");
85     t!(fs::create_dir_all(&out_dir));
86
87     let _time = util::timeit();
88     let mut cmd = Command::new(build.tool(&Compiler::new(0, host), "cargotest"));
89     build.prepare_tool_cmd(compiler, &mut cmd);
90     build.run(cmd.arg(&build.cargo)
91                  .arg(&out_dir)
92                  .env("RUSTC", build.compiler_path(compiler))
93                  .env("RUSTDOC", build.rustdoc(compiler)))
94 }
95
96 /// Runs `cargo test` for `cargo` packaged with Rust.
97 pub fn cargo(build: &Build, stage: u32, host: &str) {
98     let ref compiler = Compiler::new(stage, host);
99
100     // Configure PATH to find the right rustc. NB. we have to use PATH
101     // and not RUSTC because the Cargo test suite has tests that will
102     // fail if rustc is not spelled `rustc`.
103     let path = build.sysroot(compiler).join("bin");
104     let old_path = ::std::env::var("PATH").expect("");
105     let sep = if cfg!(windows) { ";" } else {":" };
106     let ref newpath = format!("{}{}{}", path.display(), sep, old_path);
107
108     let mut cargo = build.cargo(compiler, Mode::Tool, host, "test");
109     cargo.arg("--manifest-path").arg(build.src.join("src/tools/cargo/Cargo.toml"));
110
111     // Don't build tests dynamically, just a pain to work with
112     cargo.env("RUSTC_NO_PREFER_DYNAMIC", "1");
113
114     // Don't run cross-compile tests, we may not have cross-compiled libstd libs
115     // available.
116     cargo.env("CFG_DISABLE_CROSS_TESTS", "1");
117
118     build.run(cargo.env("PATH", newpath));
119 }
120
121 /// Runs the `tidy` tool as compiled in `stage` by the `host` compiler.
122 ///
123 /// This tool in `src/tools` checks up on various bits and pieces of style and
124 /// otherwise just implements a few lint-like checks that are specific to the
125 /// compiler itself.
126 pub fn tidy(build: &Build, host: &str) {
127     println!("tidy check ({})", host);
128     let compiler = Compiler::new(0, host);
129     let mut cmd = build.tool_cmd(&compiler, "tidy");
130     cmd.arg(build.src.join("src"));
131     if !build.config.vendor {
132         cmd.arg("--no-vendor");
133     }
134     build.run(&mut cmd);
135 }
136
137 fn testdir(build: &Build, host: &str) -> PathBuf {
138     build.out.join(host).join("test")
139 }
140
141 /// Executes the `compiletest` tool to run a suite of tests.
142 ///
143 /// Compiles all tests with `compiler` for `target` with the specified
144 /// compiletest `mode` and `suite` arguments. For example `mode` can be
145 /// "run-pass" or `suite` can be something like `debuginfo`.
146 pub fn compiletest(build: &Build,
147                    compiler: &Compiler,
148                    target: &str,
149                    mode: &str,
150                    suite: &str) {
151     println!("Check compiletest suite={} mode={} ({} -> {})",
152              suite, mode, compiler.host, target);
153     let mut cmd = Command::new(build.tool(&Compiler::new(0, compiler.host),
154                                           "compiletest"));
155     build.prepare_tool_cmd(compiler, &mut cmd);
156
157     // compiletest currently has... a lot of arguments, so let's just pass all
158     // of them!
159
160     cmd.arg("--compile-lib-path").arg(build.rustc_libdir(compiler));
161     cmd.arg("--run-lib-path").arg(build.sysroot_libdir(compiler, target));
162     cmd.arg("--rustc-path").arg(build.compiler_path(compiler));
163     cmd.arg("--rustdoc-path").arg(build.rustdoc(compiler));
164     cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
165     cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
166     cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
167     cmd.arg("--mode").arg(mode);
168     cmd.arg("--target").arg(target);
169     cmd.arg("--host").arg(compiler.host);
170     cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(&build.config.build));
171
172     if let Some(nodejs) = build.config.nodejs.as_ref() {
173         cmd.arg("--nodejs").arg(nodejs);
174     }
175
176     let mut flags = vec!["-Crpath".to_string()];
177     if build.config.rust_optimize_tests {
178         flags.push("-O".to_string());
179     }
180     if build.config.rust_debuginfo_tests {
181         flags.push("-g".to_string());
182     }
183
184     let mut hostflags = build.rustc_flags(&compiler.host);
185     hostflags.extend(flags.clone());
186     cmd.arg("--host-rustcflags").arg(hostflags.join(" "));
187
188     let mut targetflags = build.rustc_flags(&target);
189     targetflags.extend(flags);
190     targetflags.push(format!("-Lnative={}",
191                              build.test_helpers_out(target).display()));
192     cmd.arg("--target-rustcflags").arg(targetflags.join(" "));
193
194     cmd.arg("--docck-python").arg(build.python());
195
196     if build.config.build.ends_with("apple-darwin") {
197         // Force /usr/bin/python on macOS for LLDB tests because we're loading the
198         // LLDB plugin's compiled module which only works with the system python
199         // (namely not Homebrew-installed python)
200         cmd.arg("--lldb-python").arg("/usr/bin/python");
201     } else {
202         cmd.arg("--lldb-python").arg(build.python());
203     }
204
205     if let Some(ref gdb) = build.config.gdb {
206         cmd.arg("--gdb").arg(gdb);
207     }
208     if let Some(ref vers) = build.lldb_version {
209         cmd.arg("--lldb-version").arg(vers);
210     }
211     if let Some(ref dir) = build.lldb_python_dir {
212         cmd.arg("--lldb-python-dir").arg(dir);
213     }
214     let llvm_config = build.llvm_config(target);
215     let llvm_version = output(Command::new(&llvm_config).arg("--version"));
216     cmd.arg("--llvm-version").arg(llvm_version);
217
218     cmd.args(&build.flags.cmd.test_args());
219
220     if build.config.verbose() || build.flags.verbose() {
221         cmd.arg("--verbose");
222     }
223
224     if build.config.quiet_tests {
225         cmd.arg("--quiet");
226     }
227
228     // Only pass correct values for these flags for the `run-make` suite as it
229     // requires that a C++ compiler was configured which isn't always the case.
230     if suite == "run-make" {
231         let llvm_components = output(Command::new(&llvm_config).arg("--components"));
232         let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
233         cmd.arg("--cc").arg(build.cc(target))
234            .arg("--cxx").arg(build.cxx(target))
235            .arg("--cflags").arg(build.cflags(target).join(" "))
236            .arg("--llvm-components").arg(llvm_components.trim())
237            .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
238     } else {
239         cmd.arg("--cc").arg("")
240            .arg("--cxx").arg("")
241            .arg("--cflags").arg("")
242            .arg("--llvm-components").arg("")
243            .arg("--llvm-cxxflags").arg("");
244     }
245
246     if build.remote_tested(target) {
247         cmd.arg("--remote-test-client")
248            .arg(build.tool(&Compiler::new(0, &build.config.build),
249                            "remote-test-client"));
250     }
251
252     // Running a C compiler on MSVC requires a few env vars to be set, to be
253     // sure to set them here.
254     //
255     // Note that if we encounter `PATH` we make sure to append to our own `PATH`
256     // rather than stomp over it.
257     if target.contains("msvc") {
258         for &(ref k, ref v) in build.cc[target].0.env() {
259             if k != "PATH" {
260                 cmd.env(k, v);
261             }
262         }
263     }
264     cmd.env("RUSTC_BOOTSTRAP", "1");
265     build.add_rust_test_threads(&mut cmd);
266
267     if build.config.sanitizers {
268         cmd.env("SANITIZER_SUPPORT", "1");
269     }
270
271     cmd.arg("--adb-path").arg("adb");
272     cmd.arg("--adb-test-dir").arg(ADB_TEST_DIR);
273     if target.contains("android") {
274         // Assume that cc for this target comes from the android sysroot
275         cmd.arg("--android-cross-path")
276            .arg(build.cc(target).parent().unwrap().parent().unwrap());
277     } else {
278         cmd.arg("--android-cross-path").arg("");
279     }
280
281     let _time = util::timeit();
282     build.run(&mut cmd);
283 }
284
285 /// Run `rustdoc --test` for all documentation in `src/doc`.
286 ///
287 /// This will run all tests in our markdown documentation (e.g. the book)
288 /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to
289 /// `compiler`.
290 pub fn docs(build: &Build, compiler: &Compiler) {
291     // Do a breadth-first traversal of the `src/doc` directory and just run
292     // tests for all files that end in `*.md`
293     let mut stack = vec![build.src.join("src/doc")];
294     let _time = util::timeit();
295
296     while let Some(p) = stack.pop() {
297         if p.is_dir() {
298             stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
299             continue
300         }
301
302         if p.extension().and_then(|s| s.to_str()) != Some("md") {
303             continue
304         }
305
306         // The nostarch directory in the book is for no starch, and so isn't guaranteed to build.
307         // we don't care if it doesn't build, so skip it.
308         use std::ffi::OsStr;
309         let path: &OsStr = p.as_ref();
310         if let Some(path) = path.to_str() {
311             if path.contains("nostarch") {
312                 continue;
313             }
314         }
315
316         println!("doc tests for: {}", p.display());
317         markdown_test(build, compiler, &p);
318     }
319 }
320
321 /// Run the error index generator tool to execute the tests located in the error
322 /// index.
323 ///
324 /// The `error_index_generator` tool lives in `src/tools` and is used to
325 /// generate a markdown file from the error indexes of the code base which is
326 /// then passed to `rustdoc --test`.
327 pub fn error_index(build: &Build, compiler: &Compiler) {
328     println!("Testing error-index stage{}", compiler.stage);
329
330     let dir = testdir(build, compiler.host);
331     t!(fs::create_dir_all(&dir));
332     let output = dir.join("error-index.md");
333
334     let _time = util::timeit();
335     build.run(build.tool_cmd(&Compiler::new(0, compiler.host),
336                              "error_index_generator")
337                    .arg("markdown")
338                    .arg(&output)
339                    .env("CFG_BUILD", &build.config.build));
340
341     markdown_test(build, compiler, &output);
342 }
343
344 fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) {
345     let mut cmd = Command::new(build.rustdoc(compiler));
346     build.add_rustc_lib_path(compiler, &mut cmd);
347     build.add_rust_test_threads(&mut cmd);
348     cmd.arg("--test");
349     cmd.arg(markdown);
350     cmd.env("RUSTC_BOOTSTRAP", "1");
351
352     let mut test_args = build.flags.cmd.test_args().join(" ");
353     if build.config.quiet_tests {
354         test_args.push_str(" --quiet");
355     }
356     cmd.arg("--test-args").arg(test_args);
357
358     build.run(&mut cmd);
359 }
360
361 /// Run all unit tests plus documentation tests for an entire crate DAG defined
362 /// by a `Cargo.toml`
363 ///
364 /// This is what runs tests for crates like the standard library, compiler, etc.
365 /// It essentially is the driver for running `cargo test`.
366 ///
367 /// Currently this runs all tests for a DAG by passing a bunch of `-p foo`
368 /// arguments, and those arguments are discovered from `cargo metadata`.
369 pub fn krate(build: &Build,
370              compiler: &Compiler,
371              target: &str,
372              mode: Mode,
373              test_kind: TestKind,
374              krate: Option<&str>) {
375     let (name, path, features, root) = match mode {
376         Mode::Libstd => {
377             ("libstd", "src/libstd", build.std_features(), "std")
378         }
379         Mode::Libtest => {
380             ("libtest", "src/libtest", String::new(), "test")
381         }
382         Mode::Librustc => {
383             ("librustc", "src/rustc", build.rustc_features(), "rustc-main")
384         }
385         _ => panic!("can only test libraries"),
386     };
387     println!("{} {} stage{} ({} -> {})", test_kind, name, compiler.stage,
388              compiler.host, target);
389
390     // If we're not doing a full bootstrap but we're testing a stage2 version of
391     // libstd, then what we're actually testing is the libstd produced in
392     // stage1. Reflect that here by updating the compiler that we're working
393     // with automatically.
394     let compiler = if build.force_use_stage1(compiler, target) {
395         Compiler::new(1, compiler.host)
396     } else {
397         compiler.clone()
398     };
399
400     // Build up the base `cargo test` command.
401     //
402     // Pass in some standard flags then iterate over the graph we've discovered
403     // in `cargo metadata` with the maps above and figure out what `-p`
404     // arguments need to get passed.
405     let mut cargo = build.cargo(&compiler, mode, target, test_kind.subcommand());
406     cargo.arg("--manifest-path")
407          .arg(build.src.join(path).join("Cargo.toml"))
408          .arg("--features").arg(features);
409
410     match krate {
411         Some(krate) => {
412             cargo.arg("-p").arg(krate);
413         }
414         None => {
415             let mut visited = HashSet::new();
416             let mut next = vec![root];
417             while let Some(name) = next.pop() {
418                 // Right now jemalloc is our only target-specific crate in the
419                 // sense that it's not present on all platforms. Custom skip it
420                 // here for now, but if we add more this probably wants to get
421                 // more generalized.
422                 //
423                 // Also skip `build_helper` as it's not compiled normally for
424                 // target during the bootstrap and it's just meant to be a
425                 // helper crate, not tested. If it leaks through then it ends up
426                 // messing with various mtime calculations and such.
427                 if !name.contains("jemalloc") && name != "build_helper" {
428                     cargo.arg("-p").arg(&format!("{}:0.0.0", name));
429                 }
430                 for dep in build.crates[name].deps.iter() {
431                     if visited.insert(dep) {
432                         next.push(dep);
433                     }
434                 }
435             }
436         }
437     }
438
439     // The tests are going to run with the *target* libraries, so we need to
440     // ensure that those libraries show up in the LD_LIBRARY_PATH equivalent.
441     //
442     // Note that to run the compiler we need to run with the *host* libraries,
443     // but our wrapper scripts arrange for that to be the case anyway.
444     let mut dylib_path = dylib_path();
445     dylib_path.insert(0, build.sysroot_libdir(&compiler, target));
446     cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap());
447
448     if target.contains("emscripten") || build.remote_tested(target) {
449         cargo.arg("--no-run");
450     }
451
452     cargo.arg("--");
453
454     if build.config.quiet_tests {
455         cargo.arg("--quiet");
456     }
457
458     let _time = util::timeit();
459
460     if target.contains("emscripten") {
461         build.run(&mut cargo);
462         krate_emscripten(build, &compiler, target, mode);
463     } else if build.remote_tested(target) {
464         build.run(&mut cargo);
465         krate_remote(build, &compiler, target, mode);
466     } else {
467         cargo.args(&build.flags.cmd.test_args());
468         build.run(&mut cargo);
469     }
470 }
471
472 fn krate_emscripten(build: &Build,
473                     compiler: &Compiler,
474                     target: &str,
475                     mode: Mode) {
476     let mut tests = Vec::new();
477     let out_dir = build.cargo_out(compiler, mode, target);
478     find_tests(&out_dir.join("deps"), target, &mut tests);
479
480     for test in tests {
481         let test_file_name = test.to_string_lossy().into_owned();
482         println!("running {}", test_file_name);
483         let nodejs = build.config.nodejs.as_ref().expect("nodejs not configured");
484         let mut cmd = Command::new(nodejs);
485         cmd.arg(&test_file_name);
486         if build.config.quiet_tests {
487             cmd.arg("--quiet");
488         }
489         build.run(&mut cmd);
490     }
491 }
492
493 fn krate_remote(build: &Build,
494                 compiler: &Compiler,
495                 target: &str,
496                 mode: Mode) {
497     let mut tests = Vec::new();
498     let out_dir = build.cargo_out(compiler, mode, target);
499     find_tests(&out_dir.join("deps"), target, &mut tests);
500
501     let tool = build.tool(&Compiler::new(0, &build.config.build),
502                           "remote-test-client");
503     for test in tests {
504         let mut cmd = Command::new(&tool);
505         cmd.arg("run")
506            .arg(&test);
507         if build.config.quiet_tests {
508             cmd.arg("--quiet");
509         }
510         cmd.args(&build.flags.cmd.test_args());
511         build.run(&mut cmd);
512     }
513 }
514
515 fn find_tests(dir: &Path,
516               target: &str,
517               dst: &mut Vec<PathBuf>) {
518     for e in t!(dir.read_dir()).map(|e| t!(e)) {
519         let file_type = t!(e.file_type());
520         if !file_type.is_file() {
521             continue
522         }
523         let filename = e.file_name().into_string().unwrap();
524         if (target.contains("windows") && filename.ends_with(".exe")) ||
525            (!target.contains("windows") && !filename.contains(".")) ||
526            (target.contains("emscripten") && filename.ends_with(".js")) {
527             dst.push(e.path());
528         }
529     }
530 }
531
532 pub fn remote_copy_libs(build: &Build, compiler: &Compiler, target: &str) {
533     if !build.remote_tested(target) {
534         return
535     }
536
537     println!("REMOTE copy libs to emulator ({})", target);
538     t!(fs::create_dir_all(build.out.join("tmp")));
539
540     let server = build.cargo_out(compiler, Mode::Tool, target)
541                       .join(exe("remote-test-server", target));
542
543     // Spawn the emulator and wait for it to come online
544     let tool = build.tool(&Compiler::new(0, &build.config.build),
545                           "remote-test-client");
546     let mut cmd = Command::new(&tool);
547     cmd.arg("spawn-emulator")
548        .arg(target)
549        .arg(&server)
550        .arg(build.out.join("tmp"));
551     if let Some(rootfs) = build.qemu_rootfs(target) {
552         cmd.arg(rootfs);
553     }
554     build.run(&mut cmd);
555
556     // Push all our dylibs to the emulator
557     for f in t!(build.sysroot_libdir(compiler, target).read_dir()) {
558         let f = t!(f);
559         let name = f.file_name().into_string().unwrap();
560         if util::is_dylib(&name) {
561             build.run(Command::new(&tool)
562                               .arg("push")
563                               .arg(f.path()));
564         }
565     }
566 }
567
568 /// Run "distcheck", a 'make check' from a tarball
569 pub fn distcheck(build: &Build) {
570     if build.config.build != "x86_64-unknown-linux-gnu" {
571         return
572     }
573     if !build.config.host.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
574         return
575     }
576     if !build.config.target.iter().any(|s| s == "x86_64-unknown-linux-gnu") {
577         return
578     }
579
580     println!("Distcheck");
581     let dir = build.out.join("tmp").join("distcheck");
582     let _ = fs::remove_dir_all(&dir);
583     t!(fs::create_dir_all(&dir));
584
585     let mut cmd = Command::new("tar");
586     cmd.arg("-xzf")
587        .arg(dist::rust_src_location(build))
588        .arg("--strip-components=1")
589        .current_dir(&dir);
590     build.run(&mut cmd);
591     build.run(Command::new("./configure")
592                      .args(&build.config.configure_args)
593                      .arg("--enable-vendor")
594                      .current_dir(&dir));
595     build.run(Command::new(build_helper::make(&build.config.build))
596                      .arg("check")
597                      .current_dir(&dir));
598
599     // Now make sure that rust-src has all of libstd's dependencies
600     println!("Distcheck rust-src");
601     let dir = build.out.join("tmp").join("distcheck-src");
602     let _ = fs::remove_dir_all(&dir);
603     t!(fs::create_dir_all(&dir));
604
605     let mut cmd = Command::new("tar");
606     cmd.arg("-xzf")
607        .arg(dist::rust_src_installer(build))
608        .arg("--strip-components=1")
609        .current_dir(&dir);
610     build.run(&mut cmd);
611
612     let toml = dir.join("rust-src/lib/rustlib/src/rust/src/libstd/Cargo.toml");
613     build.run(Command::new(&build.cargo)
614                      .arg("generate-lockfile")
615                      .arg("--manifest-path")
616                      .arg(&toml)
617                      .current_dir(&dir));
618 }
619
620 /// Test the build system itself
621 pub fn bootstrap(build: &Build) {
622     let mut cmd = Command::new(&build.cargo);
623     cmd.arg("test")
624        .current_dir(build.src.join("src/bootstrap"))
625        .env("CARGO_TARGET_DIR", build.out.join("bootstrap"))
626        .env("RUSTC", &build.rustc);
627     cmd.arg("--").args(&build.flags.cmd.test_args());
628     build.run(&mut cmd);
629 }