]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/header.rs
Auto merge of #42394 - ollie27:rustdoc_deref_box, r=QuietMisdreavus
[rust.git] / src / tools / compiletest / src / header.rs
1 // Copyright 2012-2013 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 use std::env;
12 use std::fs::File;
13 use std::io::BufReader;
14 use std::io::prelude::*;
15 use std::path::{Path, PathBuf};
16
17 use common::Config;
18 use common;
19 use util;
20
21 use extract_gdb_version;
22
23 /// Properties which must be known very early, before actually running
24 /// the test.
25 pub struct EarlyProps {
26     pub ignore: bool,
27     pub should_fail: bool,
28     pub aux: Vec<String>,
29 }
30
31 impl EarlyProps {
32     pub fn from_file(config: &Config, testfile: &Path) -> Self {
33         let mut props = EarlyProps {
34             ignore: false,
35             should_fail: false,
36             aux: Vec::new(),
37         };
38
39         iter_header(testfile,
40                     None,
41                     &mut |ln| {
42             props.ignore =
43                 props.ignore || config.parse_name_directive(ln, "ignore-test") ||
44                 config.parse_name_directive(ln, &ignore_target(config)) ||
45                 config.parse_name_directive(ln, &ignore_architecture(config)) ||
46                 config.parse_name_directive(ln, &ignore_stage(config)) ||
47                 config.parse_name_directive(ln, &ignore_env(config)) ||
48                 (config.mode == common::Pretty &&
49                  config.parse_name_directive(ln, "ignore-pretty")) ||
50                 (config.target != config.host &&
51                  config.parse_name_directive(ln, "ignore-cross-compile")) ||
52                 ignore_gdb(config, ln) ||
53                 ignore_lldb(config, ln) ||
54                 ignore_llvm(config, ln);
55
56             if let Some(s) = config.parse_aux_build(ln) {
57                 props.aux.push(s);
58             }
59
60             props.should_fail = props.should_fail || config.parse_name_directive(ln, "should-fail");
61         });
62
63         return props;
64
65         fn ignore_target(config: &Config) -> String {
66             format!("ignore-{}", util::get_os(&config.target))
67         }
68         fn ignore_architecture(config: &Config) -> String {
69             format!("ignore-{}", util::get_arch(&config.target))
70         }
71         fn ignore_stage(config: &Config) -> String {
72             format!("ignore-{}", config.stage_id.split('-').next().unwrap())
73         }
74         fn ignore_env(config: &Config) -> String {
75             format!("ignore-{}",
76                     util::get_env(&config.target).unwrap_or("<unknown>"))
77         }
78         fn ignore_gdb(config: &Config, line: &str) -> bool {
79             if config.mode != common::DebugInfoGdb {
80                 return false;
81             }
82
83             if config.parse_name_directive(line, "ignore-gdb") {
84                 return true;
85             }
86
87             if let Some(actual_version) = config.gdb_version {
88                 if line.starts_with("min-gdb-version") {
89                     let (start_ver, end_ver) = extract_gdb_version_range(line);
90
91                     if start_ver != end_ver {
92                         panic!("Expected single GDB version")
93                     }
94                     // Ignore if actual version is smaller the minimum required
95                     // version
96                     actual_version < start_ver
97                 } else if line.starts_with("ignore-gdb-version") {
98                     let (min_version, max_version) = extract_gdb_version_range(line);
99
100                     if max_version < min_version {
101                         panic!("Malformed GDB version range: max < min")
102                     }
103
104                     actual_version >= min_version && actual_version <= max_version
105                 } else {
106                     false
107                 }
108             } else {
109                 false
110             }
111         }
112
113         // Takes a directive of the form "ignore-gdb-version <version1> [- <version2>]",
114         // returns the numeric representation of <version1> and <version2> as
115         // tuple: (<version1> as u32, <version2> as u32)
116         // If the <version2> part is omitted, the second component of the tuple
117         // is the same as <version1>.
118         fn extract_gdb_version_range(line: &str) -> (u32, u32) {
119             const ERROR_MESSAGE: &'static str = "Malformed GDB version directive";
120
121             let range_components = line.split(&[' ', '-'][..])
122                                        .filter(|word| !word.is_empty())
123                                        .map(extract_gdb_version)
124                                        .skip_while(Option::is_none)
125                                        .take(3) // 3 or more = invalid, so take at most 3.
126                                        .collect::<Vec<Option<u32>>>();
127
128             match range_components.len() {
129                 1 => {
130                     let v = range_components[0].unwrap();
131                     (v, v)
132                 }
133                 2 => {
134                     let v_min = range_components[0].unwrap();
135                     let v_max = range_components[1].expect(ERROR_MESSAGE);
136                     (v_min, v_max)
137                 }
138                 _ => panic!(ERROR_MESSAGE),
139             }
140         }
141
142         fn ignore_lldb(config: &Config, line: &str) -> bool {
143             if config.mode != common::DebugInfoLldb {
144                 return false;
145             }
146
147             if config.parse_name_directive(line, "ignore-lldb") {
148                 return true;
149             }
150
151             if let Some(ref actual_version) = config.lldb_version {
152                 if line.starts_with("min-lldb-version") {
153                     let min_version = line.trim_right()
154                         .rsplit(' ')
155                         .next()
156                         .expect("Malformed lldb version directive");
157                     // Ignore if actual version is smaller the minimum required
158                     // version
159                     lldb_version_to_int(actual_version) < lldb_version_to_int(min_version)
160                 } else {
161                     false
162                 }
163             } else {
164                 false
165             }
166         }
167
168         fn ignore_llvm(config: &Config, line: &str) -> bool {
169             if let Some(ref actual_version) = config.llvm_version {
170                 if line.starts_with("min-llvm-version") {
171                     let min_version = line.trim_right()
172                         .rsplit(' ')
173                         .next()
174                         .expect("Malformed llvm version directive");
175                     // Ignore if actual version is smaller the minimum required
176                     // version
177                     &actual_version[..] < min_version
178                 } else {
179                     false
180                 }
181             } else {
182                 false
183             }
184         }
185     }
186 }
187
188 #[derive(Clone, Debug)]
189 pub struct TestProps {
190     // Lines that should be expected, in order, on standard out
191     pub error_patterns: Vec<String>,
192     // Extra flags to pass to the compiler
193     pub compile_flags: Vec<String>,
194     // Extra flags to pass when the compiled code is run (such as --bench)
195     pub run_flags: Option<String>,
196     // If present, the name of a file that this test should match when
197     // pretty-printed
198     pub pp_exact: Option<PathBuf>,
199     // Other crates that should be compiled (typically from the same
200     // directory as the test, but for backwards compatibility reasons
201     // we also check the auxiliary directory)
202     pub aux_builds: Vec<String>,
203     // Environment settings to use for compiling
204     pub rustc_env: Vec<(String, String)>,
205     // Environment settings to use during execution
206     pub exec_env: Vec<(String, String)>,
207     // Lines to check if they appear in the expected debugger output
208     pub check_lines: Vec<String>,
209     // Build documentation for all specified aux-builds as well
210     pub build_aux_docs: bool,
211     // Flag to force a crate to be built with the host architecture
212     pub force_host: bool,
213     // Check stdout for error-pattern output as well as stderr
214     pub check_stdout: bool,
215     // Don't force a --crate-type=dylib flag on the command line
216     pub no_prefer_dynamic: bool,
217     // Run --pretty expanded when running pretty printing tests
218     pub pretty_expanded: bool,
219     // Which pretty mode are we testing with, default to 'normal'
220     pub pretty_mode: String,
221     // Only compare pretty output and don't try compiling
222     pub pretty_compare_only: bool,
223     // Patterns which must not appear in the output of a cfail test.
224     pub forbid_output: Vec<String>,
225     // Revisions to test for incremental compilation.
226     pub revisions: Vec<String>,
227     // Directory (if any) to use for incremental compilation.  This is
228     // not set by end-users; rather it is set by the incremental
229     // testing harness and used when generating compilation
230     // arguments. (In particular, it propagates to the aux-builds.)
231     pub incremental_dir: Option<PathBuf>,
232     // Specifies that a cfail test must actually compile without errors.
233     pub must_compile_successfully: bool,
234     // rustdoc will test the output of the `--test` option
235     pub check_test_line_numbers_match: bool,
236     // The test must be compiled and run successfully. Only used in UI tests for
237     // now.
238     pub run_pass: bool,
239 }
240
241 impl TestProps {
242     pub fn new() -> Self {
243         TestProps {
244             error_patterns: vec![],
245             compile_flags: vec![],
246             run_flags: None,
247             pp_exact: None,
248             aux_builds: vec![],
249             revisions: vec![],
250             rustc_env: vec![],
251             exec_env: vec![],
252             check_lines: vec![],
253             build_aux_docs: false,
254             force_host: false,
255             check_stdout: false,
256             no_prefer_dynamic: false,
257             pretty_expanded: false,
258             pretty_mode: format!("normal"),
259             pretty_compare_only: false,
260             forbid_output: vec![],
261             incremental_dir: None,
262             must_compile_successfully: false,
263             check_test_line_numbers_match: false,
264             run_pass: false,
265         }
266     }
267
268     pub fn from_aux_file(&self,
269                          testfile: &Path,
270                          cfg: Option<&str>,
271                          config: &Config)
272                          -> Self {
273         let mut props = TestProps::new();
274
275         // copy over select properties to the aux build:
276         props.incremental_dir = self.incremental_dir.clone();
277         props.load_from(testfile, cfg, config);
278
279         props
280     }
281
282     pub fn from_file(testfile: &Path, config: &Config) -> Self {
283         let mut props = TestProps::new();
284         props.load_from(testfile, None, config);
285         props
286     }
287
288     /// Load properties from `testfile` into `props`. If a property is
289     /// tied to a particular revision `foo` (indicated by writing
290     /// `//[foo]`), then the property is ignored unless `cfg` is
291     /// `Some("foo")`.
292     pub fn load_from(&mut self,
293                      testfile: &Path,
294                      cfg: Option<&str>,
295                      config: &Config) {
296         iter_header(testfile,
297                     cfg,
298                     &mut |ln| {
299             if let Some(ep) = config.parse_error_pattern(ln) {
300                 self.error_patterns.push(ep);
301             }
302
303             if let Some(flags) = config.parse_compile_flags(ln) {
304                 self.compile_flags.extend(flags.split_whitespace()
305                     .map(|s| s.to_owned()));
306             }
307
308             if let Some(r) = config.parse_revisions(ln) {
309                 self.revisions.extend(r);
310             }
311
312             if self.run_flags.is_none() {
313                 self.run_flags = config.parse_run_flags(ln);
314             }
315
316             if self.pp_exact.is_none() {
317                 self.pp_exact = config.parse_pp_exact(ln, testfile);
318             }
319
320             if !self.build_aux_docs {
321                 self.build_aux_docs = config.parse_build_aux_docs(ln);
322             }
323
324             if !self.force_host {
325                 self.force_host = config.parse_force_host(ln);
326             }
327
328             if !self.check_stdout {
329                 self.check_stdout = config.parse_check_stdout(ln);
330             }
331
332             if !self.no_prefer_dynamic {
333                 self.no_prefer_dynamic = config.parse_no_prefer_dynamic(ln);
334             }
335
336             if !self.pretty_expanded {
337                 self.pretty_expanded = config.parse_pretty_expanded(ln);
338             }
339
340             if let Some(m) = config.parse_pretty_mode(ln) {
341                 self.pretty_mode = m;
342             }
343
344             if !self.pretty_compare_only {
345                 self.pretty_compare_only = config.parse_pretty_compare_only(ln);
346             }
347
348             if let Some(ab) = config.parse_aux_build(ln) {
349                 self.aux_builds.push(ab);
350             }
351
352             if let Some(ee) = config.parse_env(ln, "exec-env") {
353                 self.exec_env.push(ee);
354             }
355
356             if let Some(ee) = config.parse_env(ln, "rustc-env") {
357                 self.rustc_env.push(ee);
358             }
359
360             if let Some(cl) = config.parse_check_line(ln) {
361                 self.check_lines.push(cl);
362             }
363
364             if let Some(of) = config.parse_forbid_output(ln) {
365                 self.forbid_output.push(of);
366             }
367
368             if !self.must_compile_successfully {
369                 self.must_compile_successfully = config.parse_must_compile_successfully(ln);
370             }
371
372             if !self.check_test_line_numbers_match {
373                 self.check_test_line_numbers_match = config.parse_check_test_line_numbers_match(ln);
374             }
375
376             if !self.run_pass {
377                 self.run_pass = config.parse_run_pass(ln);
378             }
379         });
380
381         for key in vec!["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
382             match env::var(key) {
383                 Ok(val) => {
384                     if self.exec_env.iter().find(|&&(ref x, _)| *x == key).is_none() {
385                         self.exec_env.push((key.to_owned(), val))
386                     }
387                 }
388                 Err(..) => {}
389             }
390         }
391     }
392 }
393
394 fn iter_header(testfile: &Path, cfg: Option<&str>, it: &mut FnMut(&str)) {
395     if testfile.is_dir() {
396         return;
397     }
398     let rdr = BufReader::new(File::open(testfile).unwrap());
399     for ln in rdr.lines() {
400         // Assume that any directives will be found before the first
401         // module or function. This doesn't seem to be an optimization
402         // with a warm page cache. Maybe with a cold one.
403         let ln = ln.unwrap();
404         let ln = ln.trim();
405         if ln.starts_with("fn") || ln.starts_with("mod") {
406             return;
407         } else if ln.starts_with("//[") {
408             // A comment like `//[foo]` is specific to revision `foo`
409             if let Some(close_brace) = ln.find("]") {
410                 let lncfg = &ln[3..close_brace];
411                 let matches = match cfg {
412                     Some(s) => s == &lncfg[..],
413                     None => false,
414                 };
415                 if matches {
416                     it(ln[(close_brace + 1) ..].trim_left());
417                 }
418             } else {
419                 panic!("malformed condition directive: expected `//[foo]`, found `{}`",
420                        ln)
421             }
422         } else if ln.starts_with("//") {
423             it(ln[2..].trim_left());
424         }
425     }
426     return;
427 }
428
429 impl Config {
430
431     fn parse_error_pattern(&self, line: &str) -> Option<String> {
432         self.parse_name_value_directive(line, "error-pattern")
433     }
434
435     fn parse_forbid_output(&self, line: &str) -> Option<String> {
436         self.parse_name_value_directive(line, "forbid-output")
437     }
438
439     fn parse_aux_build(&self, line: &str) -> Option<String> {
440         self.parse_name_value_directive(line, "aux-build")
441     }
442
443     fn parse_compile_flags(&self, line: &str) -> Option<String> {
444         self.parse_name_value_directive(line, "compile-flags")
445     }
446
447     fn parse_revisions(&self, line: &str) -> Option<Vec<String>> {
448         self.parse_name_value_directive(line, "revisions")
449             .map(|r| r.split_whitespace().map(|t| t.to_string()).collect())
450     }
451
452     fn parse_run_flags(&self, line: &str) -> Option<String> {
453         self.parse_name_value_directive(line, "run-flags")
454     }
455
456     fn parse_check_line(&self, line: &str) -> Option<String> {
457         self.parse_name_value_directive(line, "check")
458     }
459
460     fn parse_force_host(&self, line: &str) -> bool {
461         self.parse_name_directive(line, "force-host")
462     }
463
464     fn parse_build_aux_docs(&self, line: &str) -> bool {
465         self.parse_name_directive(line, "build-aux-docs")
466     }
467
468     fn parse_check_stdout(&self, line: &str) -> bool {
469         self.parse_name_directive(line, "check-stdout")
470     }
471
472     fn parse_no_prefer_dynamic(&self, line: &str) -> bool {
473         self.parse_name_directive(line, "no-prefer-dynamic")
474     }
475
476     fn parse_pretty_expanded(&self, line: &str) -> bool {
477         self.parse_name_directive(line, "pretty-expanded")
478     }
479
480     fn parse_pretty_mode(&self, line: &str) -> Option<String> {
481         self.parse_name_value_directive(line, "pretty-mode")
482     }
483
484     fn parse_pretty_compare_only(&self, line: &str) -> bool {
485         self.parse_name_directive(line, "pretty-compare-only")
486     }
487
488     fn parse_must_compile_successfully(&self, line: &str) -> bool {
489         self.parse_name_directive(line, "must-compile-successfully")
490     }
491
492     fn parse_check_test_line_numbers_match(&self, line: &str) -> bool {
493         self.parse_name_directive(line, "check-test-line-numbers-match")
494     }
495
496     fn parse_run_pass(&self, line: &str) -> bool {
497         self.parse_name_directive(line, "run-pass")
498     }
499
500     fn parse_env(&self, line: &str, name: &str) -> Option<(String, String)> {
501         self.parse_name_value_directive(line, name).map(|nv| {
502             // nv is either FOO or FOO=BAR
503             let mut strs: Vec<String> = nv.splitn(2, '=')
504                 .map(str::to_owned)
505                 .collect();
506
507             match strs.len() {
508                 1 => (strs.pop().unwrap(), "".to_owned()),
509                 2 => {
510                     let end = strs.pop().unwrap();
511                     (strs.pop().unwrap(), end)
512                 }
513                 n => panic!("Expected 1 or 2 strings, not {}", n),
514             }
515         })
516     }
517
518     fn parse_pp_exact(&self, line: &str, testfile: &Path) -> Option<PathBuf> {
519         if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
520             Some(PathBuf::from(&s))
521         } else {
522             if self.parse_name_directive(line, "pp-exact") {
523                 testfile.file_name().map(PathBuf::from)
524             } else {
525                 None
526             }
527         }
528     }
529
530     fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
531         // Ensure the directive is a whole word. Do not match "ignore-x86" when
532         // the line says "ignore-x86_64".
533         line.starts_with(directive) && match line.as_bytes().get(directive.len()) {
534             None | Some(&b' ') | Some(&b':') => true,
535             _ => false
536         }
537     }
538
539     pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
540         let colon = directive.len();
541         if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
542             let value = line[(colon + 1) ..].to_owned();
543             debug!("{}: {}", directive, value);
544             Some(expand_variables(value, self))
545         } else {
546             None
547         }
548     }
549 }
550
551 pub fn lldb_version_to_int(version_string: &str) -> isize {
552     let error_string = format!("Encountered LLDB version string with unexpected format: {}",
553                                version_string);
554     let error_string = error_string;
555     let major: isize = version_string.parse().ok().expect(&error_string);
556     return major;
557 }
558
559 fn expand_variables(mut value: String, config: &Config) -> String {
560     const CWD: &'static str = "{{cwd}}";
561     const SRC_BASE: &'static str = "{{src-base}}";
562     const BUILD_BASE: &'static str = "{{build-base}}";
563
564     if value.contains(CWD) {
565         let cwd = env::current_dir().unwrap();
566         value = value.replace(CWD, &cwd.to_string_lossy());
567     }
568
569     if value.contains(SRC_BASE) {
570         value = value.replace(SRC_BASE, &config.src_base.to_string_lossy());
571     }
572
573     if value.contains(BUILD_BASE) {
574         value = value.replace(BUILD_BASE, &config.build_base.to_string_lossy());
575     }
576
577     value
578 }