]> git.lizzy.rs Git - rust.git/blob - src/fuzzer/fuzzer.rs
Fuzzer: move tys around in addition to exprs
[rust.git] / src / fuzzer / fuzzer.rs
1 use std;
2 use rustc;
3
4 import std::fs;
5 import std::getopts;
6 import std::getopts::optopt;
7 import std::getopts::opt_present;
8 import std::getopts::opt_str;
9 import std::io;
10 import std::io::stdout;
11 import std::vec;
12 import std::str;
13 import std::uint;
14 import std::option;
15
16 import rustc::syntax::ast;
17 import rustc::syntax::fold;
18 import rustc::syntax::visit;
19 import rustc::syntax::codemap;
20 import rustc::syntax::parse::parser;
21 import rustc::syntax::print::pprust;
22
23 fn write_file(filename: &str, content: &str) {
24     io::file_writer(filename, [io::create, io::truncate]).write_str(content);
25     // Work around https://github.com/graydon/rust/issues/726
26     std::run::run_program("chmod", ["644", filename]);
27 }
28
29 fn file_contains(filename: &str, needle: &str) -> bool {
30     let contents = io::read_whole_file_str(filename);
31     ret str::find(contents, needle) != -1;
32 }
33
34 fn contains(haystack: &str, needle: &str) -> bool {
35     str::find(haystack, needle) != -1
36 }
37
38 fn find_rust_files(files: &mutable [str], path: &str) {
39     if str::ends_with(path, ".rs") {
40         if file_contains(path, "xfail-test") {
41             //log_err "Skipping " + path + " because it is marked as xfail-test";
42         } else { files += [path]; }
43     } else if fs::file_is_dir(path)
44         && str::find(path, "compile-fail") == -1 {
45         for p in fs::list_dir(path) {
46             find_rust_files(files, p);
47         }
48     }
49 }
50
51 fn safe_to_steal_expr(e: &@ast::expr) -> bool {
52     alt e.node {
53
54       // https://github.com/graydon/rust/issues/890
55       ast::expr_lit(lit) {
56         alt lit.node {
57           ast::lit_str(_) { true }
58           ast::lit_char(_) { true }
59           ast::lit_int(_) { false }
60           ast::lit_uint(_) { true }
61           ast::lit_mach_int(_, _) { false }
62           ast::lit_float(_) { false }
63           ast::lit_mach_float(_, _) { false }
64           ast::lit_nil. { true }
65           ast::lit_bool(_) { true }
66         }
67       }
68
69       // https://github.com/graydon/rust/issues/890
70       ast::expr_cast(_, _) { false }
71       ast::expr_assert(_) { false }
72       ast::expr_binary(_, _, _) { false }
73       ast::expr_assign(_, _) { false }
74       ast::expr_assign_op(_, _, _) { false }
75
76       // https://github.com/graydon/rust/issues/764
77       ast::expr_fail(option::none.) { false }
78       ast::expr_ret(option::none.) { false }
79       ast::expr_put(option::none.) { false }
80
81       // These prefix-operator keywords are not being parenthesized when in callee positions.
82       // https://github.com/graydon/rust/issues/891
83       ast::expr_ret(_) { false }
84       ast::expr_put(_) { false }
85       ast::expr_check(_, _) { false }
86       ast::expr_log(_, _) { false }
87
88       _ { true }
89     }
90 }
91
92 fn safe_to_steal_ty(t: &@ast::ty) -> bool {
93     // Same restrictions
94     safe_to_replace_ty(t.node)
95 }
96
97 // Not type-parameterized: https://github.com/graydon/rust/issues/898
98 fn stash_expr_if(c: fn(&@ast::expr)->bool, es: @mutable [ast::expr], e: &@ast::expr) {
99     if c(e) {
100         *es += [*e];
101     } else {/* now my indices are wrong :( */ }
102 }
103
104 fn stash_ty_if(c: fn(&@ast::ty)->bool, es: @mutable [ast::ty], e: &@ast::ty) {
105     if c(e) {
106         *es += [*e];
107     } else {/* now my indices are wrong :( */ }
108 }
109
110 type stolen_stuff = {exprs: [ast::expr], tys: [ast::ty]};
111
112 fn steal(crate: &ast::crate) -> stolen_stuff {
113     let exprs = @mutable [];
114     let tys = @mutable [];
115     let v = visit::mk_simple_visitor(@{
116         visit_expr: bind stash_expr_if(safe_to_steal_expr, exprs, _),
117         visit_ty: bind stash_ty_if(safe_to_steal_ty, tys, _)
118         with *visit::default_simple_visitor()
119     });
120     visit::visit_crate(crate, (), v);
121     {exprs: *exprs, tys: *tys}
122 }
123
124 // https://github.com/graydon/rust/issues/652
125 fn safe_to_replace_expr(e: ast::expr_) -> bool {
126     alt e {
127       ast::expr_if(_, _, _) { false }
128       ast::expr_block(_) { false }
129       _ { true }
130     }
131 }
132
133 fn safe_to_replace_ty(t: ast::ty_) -> bool {
134     alt t {
135       ast::ty_infer. { false } // always implicit, always top level
136       ast::ty_bot. { false }   // in source, can only appear as the out type of a function
137       ast::ty_mac(_) { false }
138       _ { true }
139     }
140 }
141
142 // Replace the |i|th expr (in fold order) of |crate| with |newexpr|.
143 fn replace_expr_in_crate(crate: &ast::crate, i: uint, newexpr: &ast::expr) ->
144    ast::crate {
145     let j: @mutable uint = @mutable 0u;
146     fn fold_expr_rep(j_: @mutable uint, i_: uint, newexpr_: &ast::expr_,
147                      original: &ast::expr_, fld: fold::ast_fold) ->
148        ast::expr_ {
149         *j_ += 1u;
150         if i_ + 1u == *j_ && safe_to_replace_expr(original) {
151             newexpr_
152         } else { fold::noop_fold_expr(original, fld) }
153     }
154     let afp =
155         {fold_expr: bind fold_expr_rep(j, i, newexpr.node, _, _)
156             with *fold::default_ast_fold()};
157     let af = fold::make_fold(afp);
158     let crate2: @ast::crate = @af.fold_crate(crate);
159     fold::dummy_out(af); // work around a leak (https://github.com/graydon/rust/issues/651)
160     *crate2
161 }
162
163 // Replace the |i|th ty (in fold order) of |crate| with |newty|.
164 fn replace_ty_in_crate(crate: &ast::crate, i: uint, newty: &ast::ty) ->
165    ast::crate {
166     let j: @mutable uint = @mutable 0u;
167     fn fold_ty_rep(j_: @mutable uint, i_: uint, newty_: &ast::ty_,
168                      original: &ast::ty_, fld: fold::ast_fold) ->
169        ast::ty_ {
170         *j_ += 1u;
171         if i_ + 1u == *j_ && safe_to_replace_ty(original) {
172             newty_
173         } else { fold::noop_fold_ty(original, fld) }
174     }
175     let afp =
176         {fold_ty: bind fold_ty_rep(j, i, newty.node, _, _)
177             with *fold::default_ast_fold()};
178     let af = fold::make_fold(afp);
179     let crate2: @ast::crate = @af.fold_crate(crate);
180     fold::dummy_out(af); // work around a leak (https://github.com/graydon/rust/issues/651)
181     *crate2
182 }
183
184 iter under(n: uint) -> uint {
185     let i: uint = 0u;
186     while i < n { put i; i += 1u; }
187 }
188
189 fn devnull() -> io::writer { std::io::string_writer().get_writer() }
190
191 fn as_str(f: fn(io::writer)) -> str {
192     let w = std::io::string_writer();
193     f(w.get_writer());
194     ret w.get_str();
195 }
196
197 fn check_variants_of_ast(crate: &ast::crate, codemap: &codemap::codemap,
198                          filename: &str) {
199     let stolen = steal(crate);
200     check_variants_T(crate, codemap, filename, "expr", stolen.exprs, pprust::expr_to_str, replace_expr_in_crate);
201     check_variants_T(crate, codemap, filename, "ty", stolen.tys, pprust::ty_to_str, replace_ty_in_crate);
202 }
203
204 fn check_variants_T<T>(
205   crate: &ast::crate,
206   codemap: &codemap::codemap,
207   filename: &str,
208   thing_label: &str,
209   things: [T],
210   stringifier: fn(&@T) -> str,
211   replacer: fn(&ast::crate, uint, &T) -> ast::crate
212   ) {
213     log_err #fmt("%s contains %u %s objects", filename, vec::len(things), thing_label);
214
215     let L = vec::len(things);
216
217     if L < 100u {
218         for each i: uint in under(uint::min(L, 20u)) {
219             log_err "Replacing... " + stringifier(@things[i]);
220             for each j: uint in under(uint::min(L, 5u)) {
221                 log_err "With... " + stringifier(@things[j]);
222                 let crate2 = @replacer(crate, i, things[j]);
223                 // It would be best to test the *crate* for stability, but testing the
224                 // string for stability is easier and ok for now.
225                 let str3 =
226                     as_str(bind pprust::print_crate(codemap, crate2,
227                                                     filename,
228                                                     io::string_reader(""), _,
229                                                     pprust::no_ann()));
230                 check_roundtrip_convergence(str3, 1u);
231                 //let file_label = #fmt("buggy_%s_%s_%u_%u.rs", last_part(filename), thing_label, i, j);
232                 //check_whole_compiler(str3, file_label);
233             }
234         }
235     }
236 }
237
238 fn last_part(filename: &str) -> str {
239   let ix = str::rindex(filename, 47u8 /* '/' */);
240   assert ix >= 0;
241   str::slice(filename, ix as uint + 1u, str::byte_len(filename) - 3u)
242 }
243
244 tag compile_result { known_bug(str); passed(str); failed(str); }
245
246 // We'd find more bugs if we could take an AST here, but
247 // - that would find many "false positives" or unimportant bugs
248 // - that would be tricky, requiring use of tasks or serialization or randomness.
249 // This seems to find plenty of bugs as it is :)
250 fn check_whole_compiler(code: &str, suggested_filename: &str) {
251     let filename = "test.rs";
252     write_file(filename, code);
253     alt check_whole_compiler_inner(filename) {
254       known_bug(s) {
255         log_err "Ignoring known bug: " + s;
256       }
257       failed(s) {
258         log_err "check_whole_compiler failure: " + s;
259         write_file(suggested_filename, code);
260         log_err "Saved as: " + suggested_filename;
261       }
262       passed(_) { }
263     }
264 }
265
266 fn check_whole_compiler_inner(filename: &str) -> compile_result {
267     let p = std::run::program_output(
268             "/Users/jruderman/code/rust/build/stage1/rustc",
269             ["-c", filename]);
270
271     //log_err #fmt("Status: %d", p.status);
272     if p.err != "" {
273         if contains(p.err, "May only branch on boolean predicates") {
274             known_bug("https://github.com/graydon/rust/issues/892")
275         } else if contains(p.err, "(S->getType()->isPointerTy() && \"Invalid cast\")") {
276             known_bug("https://github.com/graydon/rust/issues/895")
277         } else if contains(p.err, "Initializer type must match GlobalVariable type") {
278             known_bug("https://github.com/graydon/rust/issues/899")
279         } else if contains(p.err, "(castIsValid(op, S, Ty) && \"Invalid cast!\"), function Create") {
280             known_bug("https://github.com/graydon/rust/issues/901")
281         } else {
282             log_err "Stderr: " + p.err;
283             failed("Unfamiliar error message")
284         }
285     } else if p.status == 256 {
286         if contains(p.out, "Out of stack space, sorry") {
287             known_bug("Recursive types - https://github.com/graydon/rust/issues/742")
288         } else {
289             log_err "Stdout: " + p.out;
290             failed("Unfamiliar sudden exit")
291         }
292     } else if p.status == 6 {
293         if contains(p.out, "get_id_ident: can't find item in ext_map") {
294             known_bug("https://github.com/graydon/rust/issues/876")
295         } else if contains(p.out, "Assertion !cx.terminated failed") {
296             known_bug("https://github.com/graydon/rust/issues/893 or https://github.com/graydon/rust/issues/894")
297         } else if !contains(p.out, "error:") {
298             log_err "Stdout: " + p.out;
299             failed("Rejected the input program without a span-error explanation")
300         } else {
301             passed("Rejected the input program cleanly")
302         }
303     } else if p.status == 11 {
304         failed("Crashed!?")
305     } else if p.status == 0 {
306         passed("Accepted the input program")
307     } else {
308         log_err p.status;
309         log_err "!Stdout: " + p.out;
310         failed("Unfamiliar status code")
311     }
312 }
313
314
315 fn parse_and_print(code: &str) -> str {
316     let filename = "tmp.rs";
317     let sess = @{cm: codemap::new_codemap(), mutable next_id: 0};
318     //write_file(filename, code);
319     let crate = parser::parse_crate_from_source_str(
320         filename, code, [], sess);
321     ret as_str(bind pprust::print_crate(sess.cm, crate,
322                                         filename,
323                                         io::string_reader(code), _,
324                                         pprust::no_ann()));
325 }
326
327 fn content_is_dangerous_to_modify(code: &str) -> bool {
328     let dangerous_patterns =
329         ["#macro", // not safe to steal things inside of it, because they have a special syntax
330          "#",      // strange representation of the arguments to #fmt, for example
331          "tag",    // typeck hang: https://github.com/graydon/rust/issues/900
332          " be "];  // don't want to replace its child with a non-call: "Non-call expression in tail call"
333
334     for p: str in dangerous_patterns { if contains(code, p) { ret true; } }
335     ret false;
336 }
337
338 fn content_is_confusing(code: &str) -> bool {
339     let confusing_patterns =
340         ["self",       // crazy rules enforced by parser rather than typechecker?
341         "spawn",       // precedence issues?
342          "bind",       // precedence issues?
343          "\n\n\n\n\n"  // https://github.com/graydon/rust/issues/850
344         ];
345
346     for p: str in confusing_patterns { if contains(code, p) { ret true; } }
347     ret false;
348 }
349
350 fn file_is_confusing(filename: &str) -> bool {
351     let confusing_files = [];
352
353     for f in confusing_files { if contains(filename, f) { ret true; } }
354
355     ret false;
356 }
357
358 fn check_roundtrip_convergence(code: &str, maxIters: uint) {
359
360     let i = 0u;
361     let new = code;
362     let old = code;
363
364     while i < maxIters {
365         old = new;
366         if content_is_confusing(old) { ret; }
367         new = parse_and_print(old);
368         if old == new { break; }
369         i += 1u;
370     }
371
372     if old == new {
373         log_err #fmt["Converged after %u iterations", i];
374     } else {
375         log_err #fmt["Did not converge after %u iterations!", i];
376         write_file("round-trip-a.rs", old);
377         write_file("round-trip-b.rs", new);
378         std::run::run_program("diff",
379                               ["-w", "-u", "round-trip-a.rs",
380                                "round-trip-b.rs"]);
381         fail "Mismatch";
382     }
383 }
384
385 fn check_convergence(files: &[str]) {
386     log_err #fmt["pp convergence tests: %u files", vec::len(files)];
387     for file in files {
388         if !file_is_confusing(file) {
389             let s = io::read_whole_file_str(file);
390             if !content_is_confusing(s) {
391                 log_err #fmt["pp converge: %s", file];
392                 // Change from 7u to 2u once https://github.com/graydon/rust/issues/850 is fixed
393                 check_roundtrip_convergence(s, 7u);
394             }
395         }
396     }
397 }
398
399 fn check_variants(files: &[str]) {
400     for file in files {
401         if !file_is_confusing(file) {
402             let s = io::read_whole_file_str(file);
403             if content_is_dangerous_to_modify(s) || content_is_confusing(s) {
404                 cont;
405             }
406             log_err "check_variants: " + file;
407             let sess = @{cm: codemap::new_codemap(), mutable next_id: 0};
408             let crate =
409                 parser::parse_crate_from_source_str(
410                     file,
411                     s, [], sess);
412             log_err as_str(bind pprust::print_crate(sess.cm, crate,
413                                                     file,
414                                                     io::string_reader(s), _,
415                                                     pprust::no_ann()));
416             check_variants_of_ast(*crate, sess.cm, file);
417         }
418     }
419 }
420
421 fn main(args: [str]) {
422     if vec::len(args) != 2u {
423         log_err #fmt["usage: %s <testdir>", args[0]];
424         ret;
425     }
426     let files = [];
427     let root = args[1];
428
429     find_rust_files(files, root);
430     check_convergence(files);
431     check_variants(files);
432     log_err "Fuzzer done";
433 }
434
435 // Local Variables:
436 // mode: rust;
437 // fill-column: 78;
438 // indent-tabs-mode: nil
439 // c-basic-offset: 4
440 // buffer-file-coding-system: utf-8-unix
441 // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
442 // End: