Source file instrument.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
open Ppxlib
open Ast_builder.Default
type directive = No_directive | Off of string | On | Exclude_file
let directive { attr_name; attr_payload; attr_loc } =
let payload =
match attr_payload with
| PStr [ { pstr_desc = Pstr_eval (payload, _); _ } ] ->
Some payload.pexp_desc
| _ -> None
in
if not (String.equal attr_name.txt "mutate") then No_directive
else
match payload with
| Some (Pexp_ident { txt = Lident "off"; _ }) -> Off ""
| Some (Pexp_ident { txt = Lident "on"; _ }) -> On
| Some (Pexp_ident { txt = Lident "exclude_file"; _ }) -> Exclude_file
| Some
(Pexp_apply
( { pexp_desc = Pexp_ident { txt = Lident "off"; _ }; _ },
[
( Nolabel,
{ pexp_desc = Pexp_constant (Pconst_string (reason, _, _)); _ }
);
] )) ->
Off reason
| _ ->
Location.raise_errorf ~loc:attr_loc "Bad payload in mutate attribute."
let err_misplaced attribute name =
Location.raise_errorf ~loc:attribute.attr_loc "mutate %s is not allowed here."
name
let off_reason attributes =
List.fold_left
(fun found attribute ->
match directive attribute with
| No_directive -> found
| Off reason -> Some reason
| On -> err_misplaced attribute "on"
| Exclude_file -> err_misplaced attribute "exclude_file")
None attributes
let is_off attributes = Option.is_some (off_reason attributes)
let excludes_file structure =
List.exists
(function
| { pstr_desc = Pstr_attribute attribute; _ } -> (
match directive attribute with
| Exclude_file -> true
| No_directive | Off _ | On -> false)
| _ -> false)
structure
let is_test_item si =
let marked =
List.exists (fun a -> String.equal a.attr_name.txt "windtrap.test")
in
match si.pstr_desc with
| Pstr_value (_, bindings) ->
List.exists (fun b -> marked b.pvb_attributes) bindings
| Pstr_module mb -> marked mb.pmb_attributes
| _ -> false
type family = Ari | Cmp | Con
let operators =
[
("+", (Ari, "sub", "-"));
("-", (Ari, "add", "+"));
("+.", (Ari, "fsub", "-."));
("-.", (Ari, "fadd", "+."));
("<", (Cmp, "le", "<="));
("<=", (Cmp, "lt", "<"));
(">", (Cmp, "ge", ">="));
(">=", (Cmp, "gt", ">"));
("=", (Cmp, "neq", "<>"));
("<>", (Cmp, "eq", "="));
("&&", (Con, "or", "||"));
("||", (Con, "and", "&&"));
]
let kept_families structure =
let lose name lost =
match List.assoc_opt name operators with
| Some (family, _, _) -> family :: lost
| None -> lost
in
let scan =
object
inherit [family list] Ast_traverse.fold as super
method! pattern p lost =
let lost =
match p.ppat_desc with
| Ppat_var { txt; _ } -> lose txt lost
| _ -> lost
in
super#pattern p lost
method! value_description vd lost =
super#value_description vd (lose vd.pval_name.txt lost)
end
in
let lost = scan#structure structure [] in
fun family -> not (List.mem family lost)
type context = Condition | Boolean | Ordinary
type application = {
name : string;
operator : expression;
left : expression;
right : expression;
}
let application e =
match e.pexp_desc with
| Pexp_apply
( ({ pexp_desc = Pexp_ident { txt = Lident name; _ }; _ } as operator),
[ (Nolabel, left); (Nolabel, right) ] ) ->
Some { name; operator; left; right }
| _ -> None
let applies name e =
match application e with
| Some app -> String.equal app.name name
| None -> false
let is_connective ~keeps e = keeps Con && (applies "&&" e || applies "||" e)
let apply ~loc name args =
pexp_apply ~loc
(pexp_ident ~loc { txt = Lident name; loc })
(List.map (fun arg -> (Nolabel, arg)) args)
let render e =
Pprintast.string_of_expression { e with pexp_attributes = [] }
|> String.map (function '\t' | '\n' | '\r' -> ' ' | c -> c)
|> String.split_on_char ' '
|> List.filter (fun word -> word <> "")
|> String.concat " "
type guard = Neg | Operator of application * operator_guard
and operator_guard =
| Negate
| Swap
| Branch
| Replace of string
type mutant = { guard : guard; rewrite : string; after : string }
let mutant ~keeps context e =
let loc = e.pexp_loc in
let neg () =
if context <> Condition then None
else
let negated = apply ~loc "not" [ { e with pexp_attributes = [] } ] in
Some { guard = Neg; rewrite = "not"; after = render negated }
in
match application e with
| None -> neg ()
| Some app -> (
match List.assoc_opt app.name operators with
| Some (family, rewrite, replacement) when keeps family -> (
let after = render (apply ~loc replacement [ app.left; app.right ]) in
let mutant guard =
Some { guard = Operator (app, guard); rewrite; after }
in
match family with
| Con ->
if is_connective ~keeps app.left || is_connective ~keeps app.right
then None
else mutant Branch
| Cmp when context = Ordinary -> None
| Cmp ->
mutant
(if app.name = "=" || app.name = "<>" then Negate else Swap)
| Ari -> mutant (Replace replacement))
| Some _ | None -> neg ())
let binder index role = Printf.sprintf "__windtrap_mut_%d_%s" index role
let generated_module_name file =
let buffer = Buffer.create (String.length file + 16) in
Buffer.add_string buffer "Windtrap_mut___";
String.iter
(function
| ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_') as c ->
Buffer.add_char buffer c
| _ -> Buffer.add_string buffer "___")
file;
Buffer.contents buffer
let armed ~loc ~module_name index =
pexp_apply ~loc
(pexp_ident ~loc
{ txt = Ldot (Lident module_name, "___windtrap_armed___"); loc })
[ (Nolabel, eint ~loc index) ]
let negation ~loc ~module_name ~index value =
let p = binder index "p" in
[%expr
let [%p pvar ~loc p] = [%e value] in
if [%e armed ~loc ~module_name index] then Stdlib.not [%e evar ~loc p]
else [%e evar ~loc p]]
let binary ~loc ~module_name ~index ~pin e app ~armed_arm left right =
let l = binder index "l" and r = binder index "r" in
let operands =
let tuple = pexp_tuple ~loc [ left; right ] in
if not pin then tuple
else
pexp_constraint ~loc tuple
(ptyp_constr ~loc
{ txt = Ldot (Lident module_name, "operands"); loc }
[ ptyp_any ~loc ])
in
let disarmed =
{
(pexp_apply ~loc:e.pexp_loc app.operator
[ (Nolabel, evar ~loc l); (Nolabel, evar ~loc r) ])
with
pexp_attributes = e.pexp_attributes;
}
in
[%expr
let [%p pvar ~loc l], [%p pvar ~loc r] = [%e operands] in
if [%e armed ~loc ~module_name index] then
[%e armed_arm (evar ~loc l) (evar ~loc r)]
else [%e disarmed]]
let branch ~loc ~module_name ~index e app left right =
let p = binder index "p" in
let value = [%expr ([%e evar ~loc p] : Stdlib.Bool.t)] in
let armed = armed ~loc ~module_name index in
let test =
if String.equal app.name "&&" then
[%expr Stdlib.( <> ) [%e value] [%e armed]]
else [%expr Stdlib.( = ) [%e value] [%e armed]]
in
{
([%expr
let [%p pvar ~loc p] = [%e left] in
if [%e test] then [%e right] else [%e evar ~loc p]])
with
pexp_attributes = e.pexp_attributes;
}
let rec is_trivial_syntactic_value e =
match e.pexp_desc with
| Pexp_function _ | Pexp_poly _ | Pexp_ident _ | Pexp_constant _
| Pexp_construct (_, None) ->
true
| Pexp_constraint (inner, _) | Pexp_coerce (inner, _, _) ->
is_trivial_syntactic_value inner
| _ -> false
let is_opaque e =
match e.pexp_desc with
| Pexp_assert _ -> true
| Pexp_lazy body -> is_trivial_syntactic_value body
| _ -> false
type site = {
line : int;
col : int;
rewrite : string;
before : string;
after : string;
dismissed : string option;
}
class instrumenter ~keeps ~module_name =
object (self)
inherit Ast_traverse.map as super
val seen = Hashtbl.create 64
val mutable sites = []
val mutable pins = false
val mutable suppressed = false
method sites = List.rev sites
method pins = pins
method private site e (mutant : mutant) ~dismissed =
let start = e.pexp_loc.loc_start in
let line = start.pos_lnum and col = start.pos_cnum - start.pos_bol in
let key = (line, col, mutant.rewrite) in
if e.pexp_loc.loc_ghost || Hashtbl.mem seen key then None
else begin
let index = Hashtbl.length seen in
Hashtbl.add seen key ();
let site =
{
line;
col;
rewrite = mutant.rewrite;
before = render e;
after = mutant.after;
dismissed;
}
in
sites <- site :: sites;
Some index
end
method private mutate ?(chained = false) context e =
let off = off_reason e.pexp_attributes in
if is_opaque e then e
else
match (off, mutant ~keeps context e) with
| Some _, None -> e
| Some reason, Some mutant ->
if not chained then
ignore (self#site e mutant ~dismissed:(Some reason));
e
| None, None -> self#descend e
| None, Some mutant ->
let index =
if chained then None else self#site e mutant ~dismissed:None
in
self#guard e mutant index
method private guard e mutant index =
let loc = { e.pexp_loc with loc_ghost = true } in
match mutant.guard with
| Neg -> (
let value = self#descend e in
match index with
| None -> value
| Some index -> negation ~loc ~module_name ~index value)
| Operator (app, guard) -> (
let context =
match guard with
| Branch -> Boolean
| Negate | Swap | Replace _ -> Ordinary
in
let chained = applies app.name app.left in
let left = self#mutate ~chained context app.left in
let right = self#mutate context app.right in
let rebuilt =
{
e with
pexp_desc =
Pexp_apply (app.operator, [ (Nolabel, left); (Nolabel, right) ]);
}
in
match index with
| None -> rebuilt
| Some index -> (
match guard with
| Negate -> negation ~loc ~module_name ~index rebuilt
| Swap ->
pins <- true;
binary ~loc ~module_name ~index ~pin:true e app left right
~armed_arm:(fun l r ->
let swapped =
pexp_apply ~loc app.operator
[ (Nolabel, r); (Nolabel, l) ]
in
[%expr Stdlib.not [%e swapped]])
| Branch -> branch ~loc ~module_name ~index e app left right
| Replace replacement ->
binary ~loc ~module_name ~index ~pin:false e app left right
~armed_arm:(fun l r -> apply ~loc replacement [ l; r ])))
method private descend e =
match e.pexp_desc with
| Pexp_ifthenelse (condition, then_, else_) ->
{
e with
pexp_desc =
Pexp_ifthenelse
( self#mutate Condition condition,
self#expression then_,
Option.map self#expression else_ );
}
| Pexp_while (condition, body) ->
{
e with
pexp_desc =
Pexp_while (self#mutate Condition condition, self#expression body);
}
| Pexp_apply (operator, [ (Nolabel, left); (Nolabel, right) ])
when is_connective ~keeps e ->
{
e with
pexp_desc =
Pexp_apply
( operator,
[
(Nolabel, self#mutate Boolean left);
(Nolabel, self#mutate Boolean right);
] );
}
| _ -> super#expression e
method! expression e = if suppressed then e else self#mutate Ordinary e
method! case c =
{
pc_lhs = self#pattern c.pc_lhs;
pc_guard = Option.map (self#mutate Condition) c.pc_guard;
pc_rhs = self#expression c.pc_rhs;
}
method! module_binding mb =
if is_off mb.pmb_attributes then mb else super#module_binding mb
method! structure_item si =
match si.pstr_desc with
| Pstr_attribute attribute ->
(match directive attribute with
| No_directive -> ()
| Off _ ->
if suppressed then
Location.raise_errorf ~loc:attribute.attr_loc
"Mutation is already off.";
suppressed <- true
| On ->
if not suppressed then
Location.raise_errorf ~loc:attribute.attr_loc
"Mutation is already on.";
suppressed <- false
| Exclude_file -> err_misplaced attribute "exclude_file");
si
| Pstr_value (rec_flag, bindings) when not suppressed ->
let binding b =
if is_off b.pvb_attributes then b
else { b with pvb_expr = self#expression b.pvb_expr }
in
{
si with
pstr_desc = Pstr_value (rec_flag, List.map binding bindings);
}
| _ -> super#structure_item si
method! structure items =
let outer = suppressed in
let items =
List.map
(fun si -> if is_test_item si then si else self#structure_item si)
items
in
suppressed <- outer;
items
method! extension extension = extension
method! attribute attribute = attribute
end
let runtime_initialization ~file ~module_name ~sites ~pins =
let loc = { (Location.in_file file) with loc_ghost = true } in
let site { line; col; rewrite; before; after; dismissed } =
let dismissed =
match dismissed with
| None -> [%expr None]
| Some reason -> [%expr Some [%e estring ~loc reason]]
in
[%expr
{
line = [%e eint ~loc line];
col = [%e eint ~loc col];
rewrite = [%e estring ~loc rewrite];
before = [%e estring ~loc before];
after = [%e estring ~loc after];
dismissed = [%e dismissed];
}]
in
let site_type =
[%stri
type site = Windtrap_runtime.Mutate.site = {
line : int;
col : int;
rewrite : string;
before : string;
after : string;
dismissed : string option;
}]
in
let operands = [%stri type 'a operands = 'a * 'a] in
let armed =
[%stri
let ___windtrap_armed___ =
Windtrap_runtime.Mutate.register ~file:[%e estring ~loc file]
~sites:[%e pexp_array ~loc (List.map site sites)]]
in
let items =
if pins then [ site_type; operands; armed ] else [ site_type; armed ]
in
let generated =
pstr_module ~loc
(module_binding ~loc
~name:{ txt = Some module_name; loc }
~expr:(pmod_structure ~loc items))
in
let = [%stri [@@@ocaml.text "/*"]] in
[ stop_comment; generated; stop_comment ]
let always_ignore_paths = [ "//toplevel//"; "(stdin)" ]
let always_ignore_basenames = [ ".ocamlinit"; "topfind" ]
let transform_impl_file ctxt ast =
let file = Expansion_context.Base.input_name ctxt in
if
List.mem file always_ignore_paths
|| List.mem (Filename.basename file) always_ignore_basenames
|| excludes_file ast
then ast
else
let module_name = generated_module_name file in
let instrumenter =
new instrumenter ~keeps:(kept_families ast) ~module_name
in
let instrumented = instrumenter#structure ast in
match instrumenter#sites with
| [] -> ast
| sites ->
runtime_initialization ~file ~module_name ~sites ~pins:instrumenter#pins
@ instrumented