raz / tools / Mutate.raz

96 lines · 2.5 KiB · raw · history · last change e0d008cd

1(* Mutate: a raz source with one random change, to try the compiler's
2 recovery from errors.
3
4 Mutate File.raz seed
5 prints the file with one symbol deleted, duplicated, swapped with the
6 next, or replaced by another symbol of the file. The seed picks the
7 change: the same seed gives the same text. Comments and spacing stay
8 as they are around the change. *)
9module Mutate;
10import Out, Rt, Buf, Heap, Scan, Files;
11
12var
13 src: []const U8;
14 state: U64; (* the generator: xorshift64 *)
15
16(* A number from the generator, below n. *)
17proc random(n: INT): INT;
18begin
19 state := state xor (state shl 13);
20 state := state xor (state shr 7);
21 state := state xor (state shl 17);
22 return INT(state mod U64(n));
23end;
24
25(* The seed, as a nonzero state. *)
26proc seed(s: []const U8);
27var i: INT;
28begin
29 state := 88172645463325252;
30 for i := 0 to LEN(s) - 1 do state := state * 31 + U64(s[i]); end;
31 if state = 0 then state := 1; end;
32 for i := 1 to 10 do _ := random(2); end;
33end;
34
35(* The symbols that aren't comments. *)
36proc count(): INT;
37var sc: Scan.Scanner; n: INT;
38begin
39 Scan.init(sc, src);
40 Scan.next(sc);
41 n := 0;
42 while sc.kind # Scan.eof do
43 if sc.kind # Scan.comment then INC(n); end;
44 Scan.next(sc);
45 end;
46 return n;
47end;
48
49(* Symbol k, counting from 0 and leaving out comments. *)
50proc symbol(k: INT): Scan.Scanner;
51var sc: Scan.Scanner;
52begin
53 Scan.init(sc, src);
54 repeat
55 Scan.next(sc);
56 if sc.kind # Scan.comment then DEC(k); end;
57 until k < 0;
58 return sc;
59end;
60
61proc main*;
62var buf: Buf.Buf; n, op, i: INT; a, b, c: Scan.Scanner;
63begin
64 if ARGC() # 3 then Rt.stop("usage: Mutate File.raz seed"); end;
65 Buf.init(buf, Heap.heap);
66 if not Files.read(Files.arg(1), buf) then Rt.stop("Mutate: can't read the file"); end;
67 src := Buf.bytes(buf);
68 seed(Files.arg(2));
69 n := count();
70 if n < 2 then Out.str(src); return; end;
71 op := random(4);
72 i := random(n - 1);
73 a := symbol(i);
74 b := symbol(i + 1);
75 c := symbol(random(n));
76 Out.str(src[0..a.start]);
77 if op = 0 then
78 Out.str(src[a.stop..b.start]);
79 elsif op = 1 then
80 Out.str(Scan.text(a));
81 Out.str(" ");
82 Out.str(Scan.text(a));
83 Out.str(src[a.stop..b.start]);
84 elsif op = 2 then
85 Out.str(Scan.text(b));
86 Out.str(src[a.stop..b.start]);
87 Out.str(Scan.text(a));
88 b.start := b.stop; (* b has been written, as the first *)
89 else
90 Out.str(Scan.text(c));
91 Out.str(src[a.stop..b.start]);
92 end;
93 Out.str(src[b.start..LEN(src)]);
94end;
95
96end Mutate.