package ppx_windtrap

All checked builds pass
  1. Overview
  2. Docs
PPX and instrumentation backend for windtrap

Install

dune-project
 Dependency

Authors

Maintainers

Sources

windtrap-0.3.1.tbz
sha256=9a8c7926c77b1c258010e027eb219164e46a036bfe2df32b34b8781884c8d11c
sha512=10d53181d709e713e8437774aecf8465153c7ce2cda5f42ede02c92cb6ada38a6dcd091566807d3c75b6c8017ca1ca012989ad4aa50788c6ab1fd6c4a1e927de

doc/src/windtrap_mutate_ppx/instrument.ml.html

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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
(*---------------------------------------------------------------------------
   Copyright (c) 2026 Invariant Systems. All rights reserved.
   SPDX-License-Identifier: ISC
  ---------------------------------------------------------------------------*)

(* A guard replaces its site in place and its disarmed arm is the original
   expression, so the rewriter is a map that threads one context: whether an
   expression must be a boolean, and whether it is a condition. Every arm
   keeps the emission law of
   instrument.mli, because all the mutants share one binary and one ill-typed
   arm breaks the build of the whole project. *)

open Ppxlib
open Ast_builder.Default

(* Attributes *)

type directive = No_directive | Off of string | On | Exclude_file

(* The grammar is the [coverage] attribute's (ppx/coverage/instrument.ml). *)
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

(* Every attribute is read, so a malformed one is an error beside an [off]
   too. *)
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

(* Inline tests *)

(* ppx_windtrap marks each item it generates for a test with
   [[@@windtrap.test]]. Without ppx_windtrap a test stays an extension node,
   which is never traversed. *)
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

(* Operators *)

type family = Ari | Cmp | Con

(* Each rewritten operator with its family, the name of its rewrite and the
   operator that replaces it. *)
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", "&&"));
  ]

(* A family keeps its sites only where its operators are Stdlib's: [ari]
   names its replacement, [con] turns [&&] into an [if], and [cmp] swaps
   operands of one type. A binding that this pass sees loses the family of
   its name; what an [open] brings in is not seen. *)
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)

(* Mutants *)

(* [Condition] is an [if] or [while] condition or an arm's guard, and
   [Boolean] a direct operand of [&&] or [||]. [cmp] fires in these two
   alone, where the expression must be a boolean, so that a user's comparison
   cannot give its two arms two types. *)
type context = Condition | Boolean | Ordinary

(* A bare operator applied to two unlabelled arguments. A qualified operator
   may be anything, and is no site. *)
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)

(* [apply ~loc name args] applies the bare operator [name] to [args]. *)
let apply ~loc name args =
  pexp_apply ~loc
    (pexp_ident ~loc { txt = Lident name; loc })
    (List.map (fun arg -> (Nolabel, arg)) args)

(* A text is printed from the parsetree, since a preprocessor cannot rely on
   the path of its source, and each run of blanks becomes one space. *)
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 " "

(* How a guard arms its site. The emission law forbids naming a comparison's
   partner, so [cmp] negates the operator the source wrote: on a total order
   [a <= b] is [not (b < a)], so an ordering swaps its operands, and [a <> b]
   is [not (a = b)], so an equality does not. *)
type guard =
  | Neg
  | Operator of application * operator_guard
  | Literal of expression (* [int] and [bool], by this constant *)
  | Delete (* [del], whose guard [descend] builds *)

and operator_guard =
  | Negate (* [cmp] on an equality *)
  | Swap (* [cmp] on an ordering *)
  | Branch (* [con] *)
  | Replace of string (* [ari], by this operator *)

type mutant = { guard : guard; rewrite : string; after : string }

(* A connective with a connective operand carries no mutant, since its guard
   would hold another site. *)
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 ())

(* Literals *)

type direction = Up | Down

(* [int] moves a literal by one in the type of its suffix: 1 to 0, and any
   other [n] to [n + 1], unless that leaves the type. Each [of_string] reads
   the literal as the compiler does, so a hexadecimal one may wrap. *)
let nudge text suffix =
  let nudge of_string to_string ~zero ~one ~succ ~max =
    match of_string text with
    | None -> None
    | Some n when n = one -> Some (Down, to_string zero)
    | Some n when n = max -> None
    | Some n -> Some (Up, to_string (succ n))
  in
  match suffix with
  | None ->
      nudge int_of_string_opt string_of_int ~zero:0 ~one:1 ~succ ~max:max_int
  | Some 'l' ->
      nudge Int32.of_string_opt Int32.to_string ~zero:0l ~one:1l
        ~succ:Int32.succ ~max:Int32.max_int
  | Some 'L' ->
      nudge Int64.of_string_opt Int64.to_string ~zero:0L ~one:1L
        ~succ:Int64.succ ~max:Int64.max_int
  | Some 'n' ->
      nudge Nativeint.of_string_opt Nativeint.to_string ~zero:0n ~one:1n
        ~succ:Nativeint.succ ~max:Nativeint.max_int
  | Some _ -> None

(* ROR's move on a comparison's constant, which [int] would repeat: [x < c]
   armed is [x <= c], which is [x < c + 1]. A constant on the left mirrors the
   operator. *)
let boundary_move ~constant_right = function
  | "<" -> Some (if constant_right then Up else Down)
  | "<=" -> Some (if constant_right then Down else Up)
  | ">" -> Some (if constant_right then Down else Up)
  | ">=" -> Some (if constant_right then Up else Down)
  | _ -> None

let last_name = function
  | { pexp_desc = Pexp_ident { txt = Lident name | Ldot (_, name); _ }; _ } ->
      Some name
  | _ -> None

(* An argument of [Hashtbl.create], [Buffer.create] and their kin is a
   capacity, which no test should pin. *)
let is_create fn =
  match last_name fn with
  | Some name -> String.ends_with ~suffix:"create" name
  | None -> false

(* The labels of an OS flag, which no test observes. *)
let os_flags = [ "cloexec" ]

(* A resource release: a call of a [close] function, also under [ignore] or a
   [try]. *)
let releases =
  [
    "close";
    "close_in";
    "close_out";
    "close_noerr";
    "close_in_noerr";
    "close_out_noerr";
    "closedir";
  ]

let rec is_release e =
  match e.pexp_desc with
  | Pexp_apply (fn, [ (Nolabel, arg) ])
    when Option.equal String.equal (last_name fn) (Some "ignore") ->
      is_release arg
  | Pexp_apply (fn, _) -> (
      match last_name fn with
      | Some name -> List.mem name releases
      | None -> false)
  | Pexp_try (body, _) -> is_release body
  | _ -> false

(* Guards *)

(* A binder is site-indexed in a reserved namespace, so that a guard shadows
   neither a user's binding nor another guard's. *)
let binder index role = Printf.sprintf "__windtrap_mut_%d_%s" index role

(* The module is named after the file, so that each compilation unit calls its
   own. The coverage rewriter mangles its module in the same way. *)
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) ]

(* [neg], and [cmp] on an equality. The value is bound once, so it is
   evaluated as often as before, and binding the whole comparison leaves its
   operands the order the compiler gives them. *)
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]]

(* [cmp] on an ordering, and [ari]: [let l, r = left, right in if armed then
   ... else l op r], where the disarmed arm is the application of [e] rebuilt
   over the binders, with its location and its attributes.

   The type-checker reads the tuple left to right, as it reads the arguments
   of an application, so a qualified field of the left operand still resolves
   an unqualified field of the right one. The match compiler destructures the
   literal tuple without building it, into the [let] chain the application
   compiles to, right operand first: each operand is evaluated once, in the
   original order, with no allocation. A [let] chain written here would impose
   one order on both, and a right-to-left check breaks that disambiguation.

   An application also checks its right argument against the type of the left
   one, which resolves a constructor or a record literal whose name a later
   type declaration reuses. [~pin] restores that for an ordering by the
   annotation [_ operands], with [type 'a operands = 'a * 'a]. The swapped arm
   already needs one type for both operands, so the pin rejects nothing. A
   variable [: 'a] cannot say it: it is scoped to the whole toplevel phrase,
   so it would tie the phrase's sites together and keep a local
   [let lt x y = x < y] from generalizing. [ari] does not pin, since an
   [open]-provided [+] may take two types, and number types disambiguate
   nothing.

   An applied [(fun l r -> ...) left right] would keep its call and its
   closure in bytecode under [-g]. Binding the operator, as in [let op = if
   armed then ( <= ) else ( < )], names a second operator, and reaches the
   polymorphic comparison even when nothing is armed. *)
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]]

(* [con] branches once on the armed flag, which keeps the short circuit, the
   tail position of [b] and one copy of each operand:

     a && b  ->  let p = a in
                 if Stdlib.( <> ) (p : Stdlib.Bool.t) (armed i) then b else p
     a || b  ->  let p = a in
                 if Stdlib.( = ) (p : Stdlib.Bool.t) (armed i) then b else p

   Armed, the first reads [if not p then b else p], which is [a || b]. The
   constraint makes the comparison an integer one, and it names
   [Stdlib.Bool.t] because a file may declare its own [bool]. No node of the
   guard is the original expression, so the whole guard takes its
   attributes. *)
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;
  }

(* Traversal *)

(* [lazy] of a trivial syntactic value compiles as already forced, and a
   guard under it would change that. Coverage's predicate, verbatim. No guard
   weakens the generalization of a binding: every site but a literal is an
   application, a condition or a statement, and the guard of a literal is an
   [if] whose two arms are constants, which the type-checker counts as a
   syntactic value, as it does a sequence whose last expression is one. *)
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

(* Nothing under an opaque expression is rewritten. The type-checker gives
   [assert false] every type only as written. *)
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;
  end_line : int;
  end_col : int;
  rewrite : string;
  before : string;
  after : string;
  dismissed : string option;
}

class instrumenter ~keeps ~module_name =
  object (self)
    inherit Ast_traverse.map as super

    (* The identifier of every recorded site, so its length is the next
       index. *)
    val seen = Hashtbl.create 64
    val mutable sites = [] (* newest first *)
    val mutable pins = false (* a guard names [operands] *)
    val mutable suppressed = false (* inside a [[@@@mutate off]] region *)

    (* The expression whose children are being rewritten, with its context,
       which the arid rules of a literal read. *)
    val mutable parent = None

    (* Whether the code being rewritten runs when the module is initialized:
       outside every function, [lazy], method and functor. *)
    val mutable at_load = true
    method sites = List.rev sites
    method pins = pins

    (* [site e mutant ~dismissed] records the site of [e] and is its index.
       It is [None], with nothing recorded, for generated code and for a site
       whose identifier another one has, as a deriver's copy does. *)
    method private site e (mutant : mutant) ~dismissed =
      let start = e.pexp_loc.loc_start and stop = e.pexp_loc.loc_end 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;
            end_line = stop.pos_lnum;
            end_col = stop.pos_cnum - stop.pos_bol;
            rewrite = mutant.rewrite;
            before = render e;
            after = mutant.after;
            dismissed;
          }
        in
        sites <- site :: sites;
        Some index
      end

    (* The mutant of a literal, when no arid rule drops it. Neither rewrite
       has a site that runs when the module is initialized, before any test,
       where no run can judge it. [int] skips a constant whose nudge is ROR's
       own boundary move, an operand of [+] or [-], which AOR moves, and a
       [create] argument. [bool] flips a literal outside a boolean context,
       where [neg] already acts, and skips an OS flag. *)
    method private literal context e =
      let is_child arg = arg == e in
      let applied =
        Option.bind parent (fun (p, c) ->
            Option.map (fun a -> (p, c, a)) (application p))
      in
      let loc = e.pexp_loc in
      match e.pexp_desc with
      | Pexp_constant (Pconst_integer (text, suffix)) -> (
          match nudge text suffix with
          | None -> None
          | Some (direction, nudged) ->
              let arid =
                at_load
                || (match applied with
                  | Some (_, _, app) when app.name = "+" || app.name = "-" ->
                      true
                  | Some (_, c, app) when keeps Cmp && c <> Ordinary ->
                      boundary_move ~constant_right:(is_child app.right)
                        app.name
                      = Some direction
                  | Some _ | None -> false)
                ||
                match parent with
                | Some ({ pexp_desc = Pexp_apply (fn, args); _ }, _) ->
                    is_create fn && List.exists (fun (_, a) -> is_child a) args
                | Some _ | None -> false
              in
              if arid then None
              else
                let replacement =
                  pexp_constant ~loc (Pconst_integer (nudged, suffix))
                in
                Some
                  {
                    guard = Literal replacement;
                    rewrite = "int";
                    after = render replacement;
                  })
      | Pexp_construct ({ txt = Lident (("true" | "false") as b); _ }, None)
        when context = Ordinary ->
          let os_flag =
            match parent with
            | Some ({ pexp_desc = Pexp_apply (_, args); _ }, _) ->
                List.exists
                  (fun (label, a) ->
                    is_child a
                    &&
                    match label with
                    | Labelled l | Optional l -> List.mem l os_flags
                    | Nolabel -> false)
                  args
            | Some _ | None -> false
          in
          if at_load || os_flag then None
          else
            let flipped = if String.equal b "true" then "false" else "true" in
            let replacement =
              pexp_construct ~loc { txt = Lident flipped; loc } None
            in
            Some
              { guard = Literal replacement; rewrite = "bool"; after = flipped }
      | _ -> None

    (* [chained] marks the left operand of a site that applies the same
       operator: a chain of one operator carries one mutant, and reading it
       from the tree keeps a bracket from changing the count. A dismissal
       leaves [e] as written. [parent] and [at_load] hold for the children of
       [e] while they are rewritten. *)
    method private mutate ?chained context e =
      let outer = (parent, at_load) in
      let mutant =
        match mutant ~keeps context e with
        | Some mutant -> Some mutant
        | None -> self#literal context e
      in
      parent <- Some (e, context);
      (match e.pexp_desc with
      | Pexp_function _ | Pexp_lazy _ | Pexp_poly _ | Pexp_object _
      | Pexp_newtype _ ->
          at_load <- false
      | _ -> ());
      let rewritten = self#rewrite ?chained context e mutant in
      parent <- fst outer;
      at_load <- snd outer;
      rewritten

    method private rewrite ?(chained = false) context e mutant =
      let off = off_reason e.pexp_attributes in
      if is_opaque e then e
      else
        match (off, mutant) 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
      | Delete -> e (* [descend] guards a statement *)
      | Literal replacement -> (
          match index with
          | None -> e
          | Some index ->
              [%expr
                if [%e armed ~loc ~module_name index] then
                  [%e { replacement with pexp_loc = loc }]
                else [%e e]])
      | 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 ])))

    (* [descend e] rewrites the children of [e], each in the context that [e]
       gives it. A connective that carries no mutant still has boolean
       operands. *)
    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_sequence (first, rest) -> (
          (* [del] drops a statement: [(if armed then () else (e1; ())); e2],
             where [e1; ()] types [e1] as the statement it was. *)
          let deletable =
            (not at_load)
            && (not (is_opaque first))
            && (not (is_release first))
            &&
            match first.pexp_desc with
            | Pexp_construct ({ txt = Lident "()"; _ }, None) -> false
            | _ -> true
          in
          let off = off_reason first.pexp_attributes in
          let index =
            if not deletable then None
            else
              let mutant = { guard = Delete; rewrite = "del"; after = "()" } in
              match self#site first mutant ~dismissed:off with
              | Some _ when Option.is_some off -> None
              | index -> index
          in
          let first' = self#expression first in
          let rest' = self#expression rest in
          match index with
          | None -> { e with pexp_desc = Pexp_sequence (first', rest') }
          | Some index ->
              let loc = { first.pexp_loc with loc_ghost = true } in
              let dropped =
                [%expr
                  if [%e armed ~loc ~module_name index] then ()
                  else (
                    [%e first'];
                    ())]
              in
              { e with pexp_desc = Pexp_sequence (dropped, rest') })
      | 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

    (* Inside a region, every structure item but a value binding reaches its
       expressions through here. *)
    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

    (* A functor's body and a class run when they are applied or
       instantiated, not when the module is initialized. *)
    method! module_expr me =
      match me.pmod_desc with
      | Pmod_functor _ ->
          let outer = at_load in
          at_load <- false;
          let me = super#module_expr me in
          at_load <- outer;
          me
      | _ -> super#module_expr me

    method! class_expr ce =
      let outer = at_load in
      at_load <- false;
      let ce = super#class_expr ce in
      at_load <- outer;
      ce

    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

(* The generated module *)

(* The module re-exports the runtime's [site] type, so that the table names
   its fields without type-directed disambiguation: the runtime declares these
   labels on three records, and warning 42 is fatal under [-w +a -warn-error
   +a]. The type equation turns a runtime record that drifted into a compile
   error. Because of its labels the module is never opened, and a file whose
   every site is dismissed has no unused [open].

   [register] allocates the arrays of the file, so indices are file-local, and
   the stop comments hide the module from odoc. The module stands above the
   user's code, so it names [int], [option] and [Some] unqualified, which a
   guard cannot. *)
let runtime_initialization ~file ~module_name ~sites ~pins =
  let loc = { (Location.in_file file) with loc_ghost = true } in
  let site { line; col; end_line; end_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];
        end_line = [%e eint ~loc end_line];
        end_col = [%e eint ~loc end_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;
        end_line : int;
        end_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 stop_comment = [%stri [@@@ocaml.text "/*"]] in
  [ stop_comment; generated; stop_comment ]

(* Rewriting *)

(* The ignore lists are the coverage rewriter's. *)
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