]> git.lizzy.rs Git - rust.git/blob - src/fuzzer/fuzzer.rs
Get expr-moving fuzzer working again
[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::ioivec;
10 import std::ioivec::stdout;
11 import std::vec;
12 import std::ivec;
13 import std::str;
14 import std::uint;
15 import std::option;
16
17 import rustc::syntax::ast;
18 import rustc::syntax::fold;
19 import rustc::syntax::walk;
20 import rustc::syntax::codemap;
21 import rustc::syntax::parse::parser;
22 import rustc::syntax::print::pprust;
23
24
25 fn read_whole_file(filename: &str) -> str {
26     str::unsafe_from_bytes_ivec(ioivec::file_reader(filename).read_whole_stream())
27 }
28
29 fn write_file(filename: &str, content: &str) {
30     ioivec::file_writer(filename,
31                         ~[ioivec::create,
32                           ioivec::truncate]).write_str(content);
33     // Work around https://github.com/graydon/rust/issues/726
34     std::run::run_program("chmod", ["644", filename]);
35 }
36
37 fn file_contains(filename: &str, needle: &str) -> bool {
38     let contents = read_whole_file(filename);
39     ret str::find(contents, needle) != -1;
40 }
41
42 fn contains(haystack: &str, needle: &str) -> bool {
43     str::find(haystack, needle) != -1
44 }
45
46 fn find_rust_files(files: &mutable str[], path: str) {
47     if str::ends_with(path, ".rs") {
48         if file_contains(path, "xfail-stage1") {
49             //log_err "Skipping " + path + " because it is marked as xfail-stage1";
50         } else { files += ~[path]; }
51     } else if (fs::file_is_dir(path) && str::find(path, "compile-fail") == -1)
52      {
53         for p in fs::list_dir(path) { find_rust_files(files, p); }
54     }
55 }
56
57 fn safe_to_steal(e: ast::expr_) -> bool {
58     alt e {
59
60       // pretty-printer precedence issues -- https://github.com/graydon/rust/issues/670
61       ast::expr_unary(_, _) {
62         false
63       }
64       ast::expr_lit(lit) {
65         alt lit.node {
66           ast::lit_str(_, _) { true }
67           ast::lit_char(_) { true }
68           ast::lit_int(_) { false }
69           ast::lit_uint(_) { false }
70           ast::lit_mach_int(_, _) { false }
71           ast::lit_float(_) { false }
72           ast::lit_mach_float(_, _) { false }
73           ast::lit_nil. { true }
74           ast::lit_bool(_) { true }
75         }
76       }
77       ast::expr_cast(_, _) { false }
78       ast::expr_send(_, _) { false }
79       ast::expr_recv(_, _) { false }
80       ast::expr_assert(_) { false }
81       ast::expr_binary(_, _, _) { false }
82       ast::expr_assign(_, _) { false }
83       ast::expr_assign_op(_, _, _) { false }
84       ast::expr_fail(option::none.) { false /* https://github.com/graydon/rust/issues/764 */ }
85       ast::expr_ret(option::none.) { false }
86       ast::expr_put(option::none.) { false }
87
88       _ {
89         true
90       }
91     }
92 }
93
94 fn steal_exprs(crate: &ast::crate) -> ast::expr[] {
95     let exprs: @mutable ast::expr[] = @mutable ~[];
96     // "Stash" is not type-parameterized because of the need for safe_to_steal
97     fn stash_expr(es: @mutable ast::expr[], e: &@ast::expr) {
98         if safe_to_steal(e.node) {
99             *es += ~[*e];
100         } else {/* now my indices are wrong :( */ }
101     }
102     let v =
103         {visit_expr_pre: bind stash_expr(exprs, _)
104             with walk::default_visitor()};
105     walk::walk_crate(v, crate);
106     *exprs
107 }
108
109 // https://github.com/graydon/rust/issues/652
110 fn safe_to_replace(e: ast::expr_) -> bool {
111     alt e {
112       ast::expr_if(_, _, _) { false }
113       ast::expr_block(_) { false }
114       _ { true }
115     }
116 }
117
118 // Replace the |i|th expr (in fold order) of |crate| with |newexpr|.
119 fn replace_expr_in_crate(crate: &ast::crate, i: uint, newexpr: ast::expr_) ->
120    ast::crate {
121     let j: @mutable uint = @mutable 0u;
122     fn fold_expr_rep(j_: @mutable uint, i_: uint, newexpr_: &ast::expr_,
123                      original: &ast::expr_, fld: fold::ast_fold) ->
124        ast::expr_ {
125         *j_ += 1u;
126         if i_ + 1u == *j_ && safe_to_replace(original) {
127             newexpr_
128         } else { fold::noop_fold_expr(original, fld) }
129     }
130     let afp =
131         {fold_expr: bind fold_expr_rep(j, i, newexpr, _, _)
132             with *fold::default_ast_fold()};
133     let af = fold::make_fold(afp);
134     let crate2: @ast::crate = @af.fold_crate(crate);
135     fold::dummy_out(af); // work around a leak (https://github.com/graydon/rust/issues/651)
136     *crate2
137 }
138
139 iter under(n: uint) -> uint {
140     let i: uint = 0u;
141     while i < n { put i; i += 1u; }
142 }
143
144 fn devnull() -> ioivec::writer { std::ioivec::string_writer().get_writer() }
145
146 fn as_str(f: fn(ioivec::writer) ) -> str {
147     let w = std::ioivec::string_writer();
148     f(w.get_writer());
149     ret w.get_str();
150 }
151
152 fn pp_variants(crate: &ast::crate, codemap: &codemap::codemap, filename: &str) {
153     let exprs = steal_exprs(crate);
154     let exprsL = ivec::len(exprs);
155     if (exprsL < 100u) {
156         for each i: uint in under(uint::min(exprsL, 20u)) {
157             log_err "Replacing... " + pprust::expr_to_str(@exprs.(i));
158             for each j: uint in under(uint::min(exprsL, 5u)) {
159                 log_err "With... " + pprust::expr_to_str(@exprs.(j));
160                 let crate2 = @replace_expr_in_crate(crate, i, exprs.(j).node);
161                 // It would be best to test the *crate* for stability, but testing the
162                 // string for stability is easier and ok for now.
163                 let str3 = as_str(bind pprust::print_crate(codemap, crate2, filename,
164                                   ioivec::string_reader(""), _,
165                                   pprust::no_ann()));
166                 // 1u would be sane here, but the pretty-printer currently has lots of whitespace and paren issues,
167                 // and https://github.com/graydon/rust/issues/766 is hilarious.
168                 check_roundtrip_convergence(str3, 7u);
169             }
170         }
171     }
172 }
173
174 fn parse_and_print(code: &str) -> str {
175     let filename = "tmp.rs";
176     let codemap = codemap::new_codemap();
177     //write_file(filename, code);
178     let crate =
179         parser::parse_crate_from_source_str(filename, code, ~[], codemap);
180     ret as_str(bind pprust::print_crate(codemap, crate, filename,
181                                         ioivec::string_reader(code), _,
182                                         pprust::no_ann()));
183 }
184
185 fn content_is_dangerous_to_modify(code: &str) -> bool {
186     let dangerous_patterns = [
187          "obj", // not safe to steal; https://github.com/graydon/rust/issues/761
188          "#macro", // not safe to steal things inside of it, because they have a special syntax
189          " be " // don't want to replace its child with a non-call: "Non-call expression in tail call"
190     ];
191
192     for p: str in dangerous_patterns { if contains(code, p) { ret true; } }
193     ret false;
194 }
195
196 fn content_is_confusing(code: &str) -> bool {
197     let  // https://github.com/graydon/rust/issues/671
198          // https://github.com/graydon/rust/issues/669
199          // https://github.com/graydon/rust/issues/669
200          // https://github.com/graydon/rust/issues/669
201          // crazy rules enforced by parser rather than typechecker?
202          // more precedence issues
203          // more precedence issues?
204         confusing_patterns =
205         ["#macro", "][]", "][mutable]", "][mutable ]", "self", "spawn",
206          "bind",
207          "\n\n\n\n\n", // https://github.com/graydon/rust/issues/759
208          " : ", // https://github.com/graydon/rust/issues/760
209          "if ret",
210          "alt ret",
211          "if fail",
212          "alt fail"
213          ];
214
215     for p: str in confusing_patterns { if contains(code, p) { ret true; } }
216     ret false;
217 }
218
219 fn file_is_confusing(filename: &str) -> bool {
220     let
221
222          // https://github.com/graydon/rust/issues/674
223
224          // something to do with () as a lone pattern
225
226          // an issue where -2147483648 gains an
227          // extra negative sign each time through,
228          // which i can't reproduce using "rustc
229          // --pretty normal"???
230          confusing_files =
231         ["block-expr-precedence.rs", "nil-pattern.rs",
232          "syntax-extension-fmt.rs",
233          "newtype.rs" // modifying it hits something like https://github.com/graydon/rust/issues/670
234          ];
235
236     for f in confusing_files { if contains(filename, f) { ret true; } }
237
238     ret false;
239 }
240
241 fn check_roundtrip_convergence(code: &str, maxIters: uint) {
242
243     let i = 0u;
244     let new = code;
245     let old = code;
246
247     while i < maxIters {
248         old = new;
249         if content_is_confusing(old) { ret; }
250         new = parse_and_print(old);
251         if old == new { break; }
252         i += 1u;
253     }
254
255     if old == new {
256         log_err #fmt("Converged after %u iterations", i);
257     } else {
258         log_err #fmt("Did not converge after %u iterations!", i);
259         write_file("round-trip-a.rs", old);
260         write_file("round-trip-b.rs", new);
261         std::run::run_program("diff", ["-w", "-u", "round-trip-a.rs", "round-trip-b.rs"]);
262         fail "Mismatch";
263     }
264 }
265
266 fn check_convergence(files: &str[]) {
267     log_err #fmt("pp convergence tests: %u files", ivec::len(files));
268     for file in files {
269         if !file_is_confusing(file) {
270             let s = read_whole_file(file);
271             if !content_is_confusing(s) {
272                 log_err #fmt("pp converge: %s", file);
273                 // Change from 7u to 2u when https://github.com/graydon/rust/issues/759 is fixed
274                 check_roundtrip_convergence(s, 7u);
275             }
276         }
277     }
278 }
279
280 fn check_convergence_of_variants(files: &str[]) {
281     for file in files {
282         if !file_is_confusing(file) {
283             let s = read_whole_file(file);
284             if content_is_dangerous_to_modify(s) || content_is_confusing(s) { cont; }
285             log_err "check_convergence_of_variants: " + file;
286             let codemap = codemap::new_codemap();
287             let crate = parser::parse_crate_from_source_str(file, s, ~[], codemap);
288             log_err as_str(bind pprust::print_crate(codemap, crate, file,
289                                         ioivec::string_reader(s), _,
290                                         pprust::no_ann()));
291             pp_variants(*crate, codemap, file);
292         }
293     }
294 }
295
296 fn main(args: vec[str]) {
297     if vec::len(args) != 2u {
298         log_err #fmt("usage: %s <testdir>", args.(0));
299         ret;
300     }
301     let files = ~[];
302     let root = args.(1);
303
304     find_rust_files(files, root);
305     check_convergence(files);
306     check_convergence_of_variants(files);
307 }
308
309 // Local Variables:
310 // mode: rust;
311 // fill-column: 78;
312 // indent-tabs-mode: nil
313 // c-basic-offset: 4
314 // buffer-file-coding-system: utf-8-unix
315 // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
316 // End: