Source file mutaml_ppx.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
open Ppxlib
module Base_exp_context = Ppxlib.Expansion_context.Base
module Pprintast = Ppxlib_ast.Pprintast
module Const = Ppxlib.Ast_helper.Const
module Exp = Ppxlib.Ast_helper.Exp
module Pat = Ppxlib.Ast_helper.Pat
module Vb = Ppxlib.Ast_helper.Vb
(** Returns a new structure with an added mutaml preamble *)
let add_preamble structure input_name =
let loc = Location.in_file input_name in
[%stri let __MUTAML_MUTANT__ = Stdlib.Sys.getenv_opt "MUTAML_MUTANT"]::
[%stri let __is_mutaml_mutant__ m = match __MUTAML_MUTANT__ with None -> false | Some mutant -> String.equal m mutant]::
structure
(** Write mutations of a file 'src/lib.ml' to a 'src/lib.muts' *)
let write_muts_file input_name mutations =
let output_name = Filename.(remove_extension input_name) ^ ".muts" in
Printf.printf "Writing mutation info to %s\n%!" output_name;
let ch = open_out output_name in
let ys = mutations |> List.rev |> List.map Mutaml_common.yojson_of_mutant in
Yojson.Safe.to_channel ch (`List ys);
close_out ch;
output_name
(** Appends a file name 'src/lib.muts' to the log-file Mutaml_common.mutaml_mut_file *)
let append_muts_file_to_log output_name =
let ch =
open_out_gen [Open_wronly; Open_append; Open_creat; Open_text] 0o660 Mutaml_common.defaults.mutaml_mut_file in
output_string ch (output_name ^ "\n");
close_out ch
(** Shorthand to ease string-conversion of surface changes *)
let string_of_exp = Pprintast.string_of_expression
module Options =
struct
let seed = ref 0
let mut_rate = ref 100
let gadt = ref false
end
module Match =
struct
let rec pat_matches_exception pat = match pat.ppat_desc with
| Ppat_any | Ppat_var _ | Ppat_constant _ | Ppat_interval _ | Ppat_construct _
| Ppat_variant _ | Ppat_alias _ | Ppat_tuple _ | Ppat_record _ | Ppat_array _
| Ppat_constraint _ | Ppat_type _ | Ppat_lazy _ | Ppat_unpack _ | Ppat_extension _
| Ppat_open _ -> false
| Ppat_exception _ -> true
| Ppat_or (p,p') -> pat_matches_exception p || pat_matches_exception p'
let rec pat_is_catch_all pat = match pat.ppat_desc with
| Ppat_constant _ | Ppat_interval _ | Ppat_construct _ | Ppat_variant _
| Ppat_array _ | Ppat_type _ | Ppat_unpack _ | Ppat_exception _
| Ppat_extension _ -> false
| Ppat_any | Ppat_var _ -> true
| Ppat_tuple ps -> List.for_all pat_is_catch_all ps
| Ppat_record (entries,_flag) -> List.for_all (fun (_,p) -> pat_is_catch_all p) entries
| Ppat_or (p,p') -> pat_is_catch_all p || pat_is_catch_all p'
| Ppat_alias (p,_)
| Ppat_constraint (p,_)
| Ppat_lazy p
| Ppat_open (_,p) -> pat_is_catch_all p
let case_is_catch_all case =
pat_is_catch_all case.pc_lhs && case.pc_guard = None && case.pc_rhs.pexp_desc<>Pexp_unreachable
let cases_contain_catch_all = List.exists case_is_catch_all
let rec pat_bind_free p = match p.ppat_desc with
| Ppat_any | Ppat_constant _ | Ppat_interval _
| Ppat_type _ | Ppat_construct (_,None) -> true
| Ppat_var _ | Ppat_alias _ | Ppat_unpack _
| Ppat_variant _
| Ppat_extension _ -> false
| Ppat_tuple ps
| Ppat_array ps -> List.for_all pat_bind_free ps
| Ppat_record (es,_) -> List.for_all (fun (_,p) -> pat_bind_free p) es
| Ppat_or (p1,p2) -> pat_bind_free p1 && pat_bind_free p2
| Ppat_construct (_,Some (_,p'))
| Ppat_constraint (p',_)
| Ppat_lazy p'
| Ppat_exception p'
| Ppat_open (_,p') -> pat_bind_free p'
let rec patterns_agree p1 p2 =
(not !Options.gadt &&
pat_bind_free p1 &&
pat_bind_free p2)
||
match p1.ppat_desc, p2.ppat_desc with
| (Ppat_any | Ppat_constant _ | Ppat_interval _),
(Ppat_any | Ppat_constant _ | Ppat_interval _) -> true
| Ppat_any, Ppat_tuple ps -> List.for_all (fun p2' -> patterns_agree p1 p2') ps
| Ppat_tuple ps, Ppat_any -> List.for_all (fun p1' -> patterns_agree p1' p2) ps
| Ppat_tuple ps, Ppat_tuple ps' ->
(try List.for_all2 patterns_agree ps ps'
with Invalid_argument _ -> false)
| Ppat_var x, Ppat_var y -> x.txt = y.txt
| Ppat_alias (p,x), Ppat_alias (p',y) ->
x.txt = y.txt && patterns_agree p p'
| Ppat_construct (c,Some (_,p1)), Ppat_construct (c',Some (_,p2)) ->
c.txt = c'.txt && patterns_agree p1 p2
| Ppat_any, Ppat_record (es,_fl) ->
List.for_all (fun (_i2,p2') -> patterns_agree p1 p2') es
| Ppat_record (es,_fl), Ppat_any ->
List.for_all (fun (_i1,p1') -> patterns_agree p1' p2) es
| Ppat_record (es,fl), Ppat_record (es',fl') ->
fl=fl' &&
(try List.for_all2 (fun (i1,p1) (i2,p2) -> i1.txt = i2.txt && patterns_agree p1 p2)
(List.sort (fun (i,_) (i',_) -> Stdlib.compare i i') es)
(List.sort (fun (i,_) (i',_) -> Stdlib.compare i i') es')
with Invalid_argument _ -> false)
| Ppat_or (p,p'), _ -> patterns_agree p p2 && patterns_agree p' p2
| _, Ppat_or (p,p') -> patterns_agree p1 p && patterns_agree p2 p'
| Ppat_array ps, Ppat_array ps' ->
(try List.for_all2 patterns_agree ps ps'
with Invalid_argument _ -> false)
| Ppat_constraint (p,t), Ppat_constraint (p',t') ->
t.ptyp_desc = t'.ptyp_desc && patterns_agree p p'
| Ppat_lazy p, Ppat_lazy p' -> patterns_agree p p'
| Ppat_unpack m, Ppat_unpack m' -> m.txt = m'.txt
| Ppat_open (m,p), Ppat_open (m',p') ->
m.txt = m'.txt && patterns_agree p p'
| Ppat_variant _, Ppat_variant _
| _ -> false
let rec cases_contain_matching_patterns cs = match cs with
| [] | [_] -> false
| c1::(c2::_ as cs') ->
(not (pat_is_catch_all c2.pc_lhs)
&& patterns_agree c1.pc_lhs c2.pc_lhs
&& c1.pc_rhs.pexp_desc<>Pexp_unreachable
&& c2.pc_rhs.pexp_desc<>Pexp_unreachable)
|| cases_contain_matching_patterns cs'
end
let return = Ppxlib.With_errors.return
let (>>=) = Ppxlib.With_errors.(>>=)
let (>>|) = Ppxlib.With_errors.(>>|)
class mutate_mapper (rs : RS.t) =
object (self)
inherit Ppxlib.Ast_traverse.map_with_expansion_context_and_errors as super
val mutable mut_count = 0
val mutable mutations = []
val mutable tmp_var_count = 0
method choose_to_mutate = RS.int rs 100 <= !Options.mut_rate
method incr_count =
let old_count = mut_count in
mut_count <- mut_count + 1;
old_count
method make_tmp_var () =
let old = tmp_var_count in
tmp_var_count <- tmp_var_count + 1;
Printf.sprintf "__MUTAML_TMP%i__" old
method let_bind ~loc exp = match exp.pexp_desc with
| Pexp_ident _
| Pexp_constant _ ->
Fun.id, exp
| _ ->
let tmp = self#make_tmp_var () in
let tmp_id = Exp.ident { txt = Lident tmp; loc } in
let cont e =
Exp.let_ ~loc Nonrecursive [Vb.mk (Pat.var { txt = tmp; loc }) exp] e in
cont, tmp_id
method make_mut_number_and_id loc ctx =
let mut_no = self#incr_count in
let mut_id = Mutaml_common.make_mut_id (Base_exp_context.input_name ctx) mut_no in
mut_no, Ast_builder.Default.estring ~loc mut_id
method mutaml_mutant ctx loc e_new e_rec repl_str =
let mut_no,mut_id_exp = self#make_mut_number_and_id loc ctx in
let mutation = Mutaml_common.{ number = mut_no; repl = Some repl_str; loc } in
mutations <- mutation::mutations;
[%expr
if __is_mutaml_mutant__ [%e mut_id_exp]
then [%e e_new]
else [%e e_rec]]
method! constant _ctx e = return e
method mutate_constant _ctx c = match c with
| Pconst_integer (i,None) ->
(match i with
| "1" -> Const.integer "0"
| _ -> Const.int (1 + int_of_string i))
| Pconst_string (" ",loc,None) -> Const.string ~loc ""
| _ -> c
method mutate_arithmetic ctx e =
let loc = e.pexp_loc in
match e with
| [%expr 1 + [%e? exp]] ->
super#expression ctx exp >>| fun exp' ->
let k, tmp_var = self#let_bind ~loc:exp.pexp_loc exp' in
k (self#mutaml_mutant ctx loc
{ e with pexp_desc = tmp_var.pexp_desc }
{ e with pexp_desc = [%expr 1 + [%e tmp_var]].pexp_desc }
(string_of_exp exp))
| [%expr [%e? exp] + 1]
| [%expr [%e? exp] - 1] ->
let op = (match e.pexp_desc with | Pexp_apply (op, _args) -> op | _ -> assert false) in
super#expression ctx exp >>| fun exp' ->
let k, tmp_var = self#let_bind ~loc:exp.pexp_loc exp' in
k (self#mutaml_mutant ctx loc
{ e with pexp_desc = tmp_var.pexp_desc }
{ e with pexp_desc = [%expr [%e op] [%e tmp_var] 1].pexp_desc }
(string_of_exp exp))
| [%expr [%e? op] [%e? exp1] [%e? exp2]] ->
let mut_op = { op with pexp_desc = (match op.pexp_desc with
| Pexp_ident ({ txt = Lident "+"; loc }) -> Pexp_ident { txt = Lident "-"; loc }
| Pexp_ident ({ txt = Lident "-"; loc }) -> Pexp_ident { txt = Lident "+"; loc }
| Pexp_ident ({ txt = Lident "*"; loc }) -> Pexp_ident { txt = Lident "+"; loc }
| Pexp_ident ({ txt = Lident "/"; loc }) -> Pexp_ident { txt = Lident "mod"; loc }
| Pexp_ident ({ txt = Lident "mod"; loc }) -> Pexp_ident { txt = Lident "/"; loc }
| _ ->
failwith ("mutaml_ppx, mutate_arithmetic: found some other operator case: " ^ (string_of_exp op))
)} in
self#expression ctx exp2 >>= fun exp2' ->
let k2, tmp_var2 = self#let_bind ~loc:exp2.pexp_loc exp2' in
self#expression ctx exp1 >>| fun exp1' ->
let k1, tmp_var1 = self#let_bind ~loc:exp1.pexp_loc exp1' in
k2 (k1 (self#mutaml_mutant ctx loc
{ e with pexp_desc = [%expr [%e mut_op] [%e tmp_var1] [%e tmp_var2]].pexp_desc }
{ e with pexp_desc = [%expr [%e op] [%e tmp_var1] [%e tmp_var2]].pexp_desc }
(string_of_exp [%expr [%e mut_op] [%e exp1] [%e exp2]])))
| _ -> failwith "mutaml_ppx, mutate_arithmetic: pattern matching on case is was not applied to"
method! cases ctx cases =
super#cases ctx cases >>| fun cases ->
let cases_exc, cases_pure =
List.partition (fun c -> Match.pat_matches_exception c.pc_lhs) cases in
let cases_contain_catch_all
= Match.cases_contain_catch_all cases_pure && List.length cases_pure >= 3 in
if cases_contain_catch_all || Match.cases_contain_matching_patterns cases_pure
then
let instr_cases = self#mutate_pure_cases ctx cases_pure ~cases_contain_catch_all in
instr_cases @ cases_exc
else cases
method mutate_pure_cases ctx cases ~cases_contain_catch_all = match cases with
| []
| [_] -> cases
| case1::(case2::_ as cases') ->
let cases' = self#mutate_pure_cases ctx cases' ~cases_contain_catch_all in
if Match.pat_is_catch_all case1.pc_lhs
then case1::cases'
else
if (not cases_contain_catch_all
&& (not (Match.patterns_agree case1.pc_lhs case2.pc_lhs)
|| Match.pat_is_catch_all case2.pc_lhs))
|| not self#choose_to_mutate
then case1::cases'
else
let loc = { case1.pc_lhs.ppat_loc with
loc_end = case1.pc_rhs.pexp_loc.loc_end } in
let mut_no,mut_id_exp = self#make_mut_number_and_id loc ctx in
let mut_guard = [%expr not (__is_mutaml_mutant__ [%e mut_id_exp]) ] in
let guard = (match case1.pc_guard with
| None -> Some mut_guard
| Some g -> Some [%expr [%e g] && [%e mut_guard] ]) in
let case1' = { case1 with pc_guard = guard } in
if cases_contain_catch_all || case1.pc_guard <> None
then
let mutation = Mutaml_common.{ number = mut_no; repl = None;
loc = { loc with loc_end = case2.pc_lhs.ppat_loc.loc_start }} in
mutations <- mutation::mutations;
case1'::cases'
else
(match cases' with
| [] -> failwith "mutaml_ppx, mutate_pure_cases: recursing on a non-empty list yielded back an empty one"
| case2'::cs' ->
let or_pat = [%pat? [%p case1.pc_lhs] | [%p case2.pc_lhs]] in
let repl_str =
Pprintast.pattern Format.str_formatter or_pat;
Format.flush_str_formatter () in
let mutation = Mutaml_common.{ number = mut_no;
repl = Some repl_str;
loc = { loc with loc_end = case2.pc_lhs.ppat_loc.loc_end }} in
mutations <- mutation::mutations;
let lhs = { case2'.pc_lhs with ppat_desc = Ppat_or (case1.pc_lhs, case2'.pc_lhs) } in
let case2'_with_or = { case2' with pc_lhs = lhs } in
case1'::case2'_with_or::cs')
method! expression ctx e =
let loc = e.pexp_loc in
match e, e.pexp_desc with
| [%expr assert [%e? _]], _-> return e
| [%expr true],_ when self#choose_to_mutate ->
let false_exp = { e with pexp_desc = [%expr false].pexp_desc } in
return (self#mutaml_mutant ctx loc false_exp e (string_of_exp false_exp))
| [%expr false],_ when self#choose_to_mutate ->
let true_exp = { e with pexp_desc = [%expr true].pexp_desc } in
return (self#mutaml_mutant ctx loc true_exp e (string_of_exp true_exp))
| [%expr [%e? _] + [%e? _]],_
| [%expr [%e? _] - [%e? _]],_
| [%expr [%e? _] * [%e? _]],_
| [%expr [%e? _] / [%e? _]],_
| [%expr [%e? _] mod [%e? _]],_ when self#choose_to_mutate ->
self#mutate_arithmetic ctx e
| _, Pexp_constant c when self#choose_to_mutate ->
let c' = self#mutate_constant ctx c in
if c = c' then return e else
let e_new = { e with pexp_desc = Pexp_constant c' } in
return (self#mutaml_mutant ctx loc e_new e (string_of_exp e_new))
| _, Pexp_ifthenelse (e0,e1,e2_opt) when self#choose_to_mutate ->
self#expression ctx e0 >>= fun e0' ->
self#expression ctx e1 >>= fun e1' ->
let cont e2_opt' =
let k, tmp_var = self#let_bind ~loc:e0.pexp_loc e0' in
let e0'_guarded =
k (self#mutaml_mutant ctx e0.pexp_loc
[%expr not [%e tmp_var]]
[%expr [%e tmp_var]]
(string_of_exp [%expr not [%e e0]])) in
{ e with pexp_desc = Pexp_ifthenelse (e0'_guarded,e1',e2_opt') }
in
(match e2_opt with
| None -> return (cont None)
| Some e2 -> self#expression ctx e2 >>| fun e2' -> cont (Some e2'))
| _, Pexp_sequence (e0,e1) when self#choose_to_mutate ->
self#expression ctx e0 >>= fun e0' ->
self#expression ctx e1 >>| fun e1' ->
let e0'' =
self#mutaml_mutant ctx loc [%expr ()] e0' (string_of_exp e1) in
{ e0 with pexp_desc = Pexp_sequence (e0'',e1') }
| _, Pexp_function cases ->
self#cases ctx cases >>| fun cases_pure ->
let function_ = { e with pexp_desc = Pexp_function cases_pure } in
if Match.cases_contain_matching_patterns cases_pure
then
Exp.attr function_
{ attr_name = {txt = "ocaml.warning"; loc};
attr_payload = PStr [[%stri "-8"]];
attr_loc = loc }
else function_
| _, Pexp_match (me,cases) ->
super#expression ctx me >>= fun me ->
self#cases ctx cases >>| fun cases ->
let cases_pure = List.filter (fun c -> not (Match.pat_matches_exception c.pc_lhs)) cases in
let match_ = { e with pexp_desc = Pexp_match (me, cases) } in
if Match.cases_contain_matching_patterns cases_pure
then
Exp.attr match_
{ attr_name = {txt = "ocaml.warning"; loc};
attr_payload = PStr [[%stri "-8"]];
attr_loc = loc }
else match_
| _ ->
super#expression ctx e
method! attributes _ctx attrs = return attrs
method transform_impl_file ctx impl_ast =
let input_name = Base_exp_context.input_name ctx in
Printf.printf "Running mutaml instrumentation on \"%s\"\n%!" input_name;
Printf.printf "Randomness seed: %i %!" !Options.seed;
Printf.printf "Mutation rate: %i %!" !Options.mut_rate;
Printf.printf "GADTs enabled: %s\n%!" (Bool.to_string !Options.gadt);
let instrumented_ast,errs = super#structure ctx impl_ast in
let errs =
List.map (fun error ->
Ast_builder.Default.pstr_extension
~loc:(Location.Error.get_location error)
(Location.Error.to_extension error)
[]) errs in
let mut_count = List.length mutations in
Printf.printf "Created %i mutation%s of %s\n%!" mut_count (if mut_count=1 then "" else "s") input_name;
let output_name = write_muts_file input_name mutations in
let () = append_muts_file_to_log output_name in
errs @ (add_preamble instrumented_ast input_name)
end