Source

js-elisp / omake.ml

Full commit
  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

(* TODO:

   Handle the event
   'Preprocessing error on file chris.ml'

   Sometimes it's ok, as in

   File "chris.ml", line 74, characters 14-15:
   Parse error: [module_longident] expected after "." (in [module_longident])
   Preprocessing error on file chris.ml

   But other times, for example when hacking camlp4, there is no
   file position to jump to.

   File "core_set.ml", line 807, characters 68-69: 
   Parse error: [ctyp level ctyp2] expected after ")" (in [ctyp]) 
   Preprocessing error on file core_set.ml
*)

open Core.Std
open Async.Std

(* -------------------------------------------------------------------------- *)
(*  Util                                                                      *)
(* -------------------------------------------------------------------------- *)

type path = string with sexp
type elisp = string
type id = path
type 'a result = ('a, exn) Result.t
type 'a deferred = 'a Deferred.t

let max_line_length = 80

let (|!) x f = f x

let truncate s =
  if String.length s > max_line_length then
    String.prefix s (max_line_length - 3) ^ "..."
  else s

let ( ** ) f g x = f (g x)

let some x = Some x

let quote s = sprintf "\"%s\"" (String.escaped s)

let debug = ref true

type debug =
| Event
| Debug

let genprintf d s =
  if !debug then
    match d with
    | Event -> Printf.eprintf ("[event] " ^^ s ^^ "\n%!")
    | Debug -> Printf.eprintf ("[debug] " ^^ s ^^ "\n%!")
  else Printf.ifprintf Out_channel.stderr s

let eprintf fmt = genprintf Event fmt
let dprintf fmt = genprintf Debug fmt

(* -------------------------------------------------------------------------- *)
(*  Regular expressions                                                       *)
(* -------------------------------------------------------------------------- *)

module type Regex = sig
  type t

  val rewrite : t -> template:string -> string -> string
  val has_match : t -> string -> bool

  type id_t = [ `Index of int | `Name of string ]
  type match_
  val get_pos : t -> sub:id_t -> match_ -> int * int
  val get : t -> sub:id_t -> match_ -> string
  val matches : t -> string -> match_ list
  val of_string : string -> t
end

module Pcre : Regex = struct
  type t = Pcre.regexp
  let of_string s = Pcre.regexp s
  let rewrite rex ~template s = Pcre.replace ~rex ~templ:template s
  let has_match rex s = Pcre.pmatch ~rex s
  type id_t = [ `Index of int | `Name of string ]
  type match_ = Pcre.substrings
  let get_pos rex ~sub m =
    let (l, r) = match sub with
      | `Index n -> Pcre.get_substring_ofs m n
      | `Name s -> Pcre.get_named_substring_ofs rex s m
    in
    (l, r - l)
  let get rex ~sub m = match sub with
    | `Index n -> Pcre.get_substring m n
    | `Name s -> Pcre.get_named_substring rex s m
  let matches rex s =
    try Pcre.exec_all ~rex s |! Array.to_list with
    | Not_found -> []
end

module Regex = Pcre

(* -------------------------------------------------------------------------- *)
(*  OCaml errors                                                              *)
(* -------------------------------------------------------------------------- *)

module Error : sig
  type t = {
    relpath : path;
    file : path;
    line : int;
    char_beg : int;
    char_end : int;
    text : string;
    full_text : string option;
  } with sexp
  val to_string : t -> string
  val to_elisp : id:string -> t -> elisp
  (* path from the omake root *)
  val rootpath : t -> path
  val dedup : t list -> t list
  val shorten_lines : string -> string
  val abbreviate : string -> string option
  val compare : t -> t -> int
  val equal : t -> t -> bool
end = struct
  type t = {
    relpath : path;
    file : path;
    line : int;
    char_beg : int;
    char_end : int;
    text : string;
    full_text : string option;
  } with sexp

  let to_string = Sexp.to_string_hum ** sexp_of_t

  let rootpath e = e.relpath ^/ e.file

  let compare e1 e2 =
    match String.compare (rootpath e1) (rootpath e2) with
    | n when n <> 0 -> n
    | _ -> Int.compare e1.line e2.line

  let equal x y =
    String.equal x.file y.file &&
    Int.equal x.line y.line &&
    Int.equal x.char_beg x.char_beg &&
    Int.equal x.char_end y.char_end

  (* n^2 dedup.  Errors must maintain their relative order in the raw buffer.
     Of the equal errors, keep the last. *)
  let rec dedup l = match l with
    | [] -> l
    | x :: xs ->
      let xs = dedup xs in
      if List.exists ~f:(equal x) xs then xs else x :: xs

  (* truncate long lines that may wrap to the next line *)
  let shorten_lines s =
    let lines = String.split ~on:'\n' s in
    let lines = List.map lines ~f:truncate in
    String.concat lines ~sep:"\n"

  let abbreviate s =
    let lines = String.split ~on:'\n' s in
    let n = List.length lines in
    if n < 10 then None
    else
      List.take lines 3 @ "       ..." :: List.drop lines (n - 3)
      |! String.concat ~sep:"\n"
      |! some

  (* to_elisp corresponds to the elisp constructor *)
  let to_elisp ~id t =
    let text = String.escaped t.text in
    let full_text = match t.full_text with
      | None -> text
      | Some ftext -> String.escaped ftext
    in
    sprintf "
      (Omake.Error :id \"%s\"
                   :relpath \"%s\"
                   :file \"%s\"
                   :line %d
                   :char-beg %d
                   :char-end %d
                   :text \"%s\"
                   :full-text \"%s\")"
      id t.relpath t.file t.line t.char_beg t.char_end
      text full_text
end
type error = Error.t with sexp

(* -------------------------------------------------------------------------- *)
(*  Partial errors                                                            *)
(* -------------------------------------------------------------------------- *)

module Partial_error : sig
  type t
  val create_ocaml
    :  relpath:path
    -> file:string
    -> line:int
    -> char_beg:int
    -> char_end:int
    -> text:string
    -> t
  val create_omake
    :  text:string
    -> t
  val add_line : t -> string -> unit
  val reify : t -> [`Ocaml of Error.t | `Omake of string]
end = struct
  type ocaml = {
    relpath : path;
    file : string;
    line : int;
    char_beg : int;
    char_end : int;
    mutable lines : string list;
  }

  type omake = {
    mutable lines_ : string list;
  }

  type t = [`Ocaml of ocaml | `Omake of omake]

  let create_ocaml ~relpath ~file ~line ~char_beg ~char_end ~text =
    `Ocaml { relpath; file; line; char_beg; char_end; lines = [ text ] }

  let create_omake ~text = `Omake { lines_ = [ text ] }

  let add_line t s = match t with
    | `Ocaml ocaml -> ocaml.lines <- s :: ocaml.lines
    | `Omake omake -> omake.lines_ <- s :: omake.lines_

  (* Clean up the error message by deleting irrelevant lines and
     removing the status bar. *)
  let scrub : string list -> string =
    (* Remove lines that we don't want to see in error messages. *)
    let ignore_lines = List.map ~f:Regex.of_string
      [ "^[[:space:]]*$"
      ; "\\*\\*\\*.*"
      ; "- build.*"
      ; "- exit.*"
      ; "\\+ ocaml.*"
      ; "^\\[=+"
      ; "depends on:.*"
      ; "make\\[.*"
      ; ".*\\.cmx.*"
      (* Need *.cmi for
         "does not match the interface top_state.cmi:"
         It seems paths with / are ok to delete.
      *)
      ; ".*/.*\\.cmi"
      ; ".*/.*\\.cmo"
      ; ".*/.*\\.o"
      ; ".*/.*\\.c"
      ; ".*/.*\\.d"
      ; "ln -sf.*"
      ; "cp .*\\.a.*"
      ; "<scanner.*"
      ; "Preprocessing error.*"
      ; "^\\[saved .omakedb"
      ]
    in
    (* Remove status bar from the end of lines *)
    let remove_progress_bar =
      let status_regex = Regex.of_string "([^\\[].*)\\[=+\\].*" in
      fun l -> Regex.rewrite status_regex l ~template:"\\1"
    in
    let spaces_before_text s =
      let n = String.length s in
      let k = ref 0 in
      while !k < n && String.get s !k = ' ' do incr k done;
      !k
    in
    let unindent lines =
      let indent = List.fold lines ~init:1000 ~f:(fun k s ->
        let k' = spaces_before_text s in
        if k' < k then k' else k)
      in
      (* let str = String.concat ~sep:"\n" lines in
       * dprintf "Unindenting %d chars\n%d lines\n%s" indent (List.length lines) str; *)
      List.map lines ~f:(fun s ->
        let n = String.length s in
        String.sub s ~pos:indent ~len:(n - indent))
    in
    let clean lines =
      let lines = List.map lines ~f:remove_progress_bar in
      List.filter lines ~f:(fun line ->
        let keep =
          not (List.exists ignore_lines ~f:(fun regex ->
            Regex.has_match regex line))
        in
        if not keep then dprintf "Ignoring line: %s" line;
        keep)
      |! unindent
      |! String.concat ~sep:"\n"
    in
    clean

  let to_ocaml_error t =
    let text = scrub (List.rev t.lines) in
    let text, full_text = match Error.abbreviate text with
      | None -> Error.shorten_lines text, None
      | Some short_text -> Error.shorten_lines short_text, Some text
    in
    { Error.relpath = t.relpath
    ; file = t.file
    ; line = t.line
    ; char_beg = t.char_beg
    ; char_end = t.char_end
    ; text
    ; full_text
    }

  let to_omake_error t = scrub (List.rev t.lines_)

  let reify = function
    | `Ocaml t -> `Ocaml (to_ocaml_error t)
    | `Omake t -> `Omake (to_omake_error t)
end

(* -------------------------------------------------------------------------- *)
(*  Rex                                                                       *)
(* -------------------------------------------------------------------------- *)

module Rex = struct
  let reading_omakefiles = Regex.of_string
    (sprintf "(%s|%s)"
       "omake: reading OMakefiles"
       "omake: a configuration file changed, restarting")

  let finished_omakefiles = Regex.of_string
    "\\*\\*\\* omake: finished reading OMakefiles"

  let reading_omakefiles_failed = Regex.of_string
    "\\*\\*\\* omake: reading OMakefiles failed"

  (* *** omake: 11789/11796 targets are up to date *)
  let targets_up_to_date = Regex.of_string
    "\\*\\*\\* omake: (?P<num>[0-9]+)/(?P<denom>[0-9]+) targets are up to date"

  (* [=======================  ] 11789 / 11796 *)
  let progress_bar = Regex.of_string
    "\\[=* *\\] (?P<num>[0-9]+) / (?P<denom>[0-9]+)"

  (* - build base/core/lib inline_tests.ml.  This will set
     base/core/lib as the relative path and inline_tests.ml as the file.
     The former changes the state for all following errors until a reset.

     Dir examples: eye/2.0/mama_tally_channel
  *)
  let build = Regex.of_string
    "- (build|scan) (?P<dir>[a-zA-Z/_0-9.-]+) (?P<file>[a-zA-Z_0-9-]+)\\..*"

  let start_build = Regex.of_string
    "- build \\. <\\.BUILD_BEGIN>"

  (* *** omake: file base/core/lib/core_list.mli changed *)
  let changed = Regex.of_string
    "\\*\\*\\* omake: file ((?P<dir>[^ ]+)/)?(?P<file>[^ /]+)\\..* changed"

  (* File "marcin.ml", line 24, characters 2-5: *)
  let ocaml_error = Regex.of_string
    (String.concat
       [ "File \"(?P<file>.+)\", "
       ; "line (?P<line>[0-9]+), "
       ; "characters (?P<charbeg>[0-9]+)-(?P<charend>[0-9]+)[^\n]*"
       ])

  let polling = Regex.of_string
    "\\*\\*\\* omake: polling for filesystem changes.*"

  let rebuilding = Regex.of_string
    "\\*\\*\\* omake: rebuilding"

  let done_ = Regex.of_string
    "\\*\\*\\* omake: done"

  (* We used to process blocked messages, but I think you get
     either a 'done' or 'blocked' message when compilation stops.
     If this is true, than the absence of 'done' means it's blocked.
  *)
  (* let blocked = Regex.of_string
   *   "\\*\\*\\* omake: blocked" *)

  (* Handle varied omake errors.

   Examples:

   Error: Files inline_tests.cmo and std.cmo
          make inconsistent assumptions over interface Std

   File "core.cmx", line 1, characters 0-1:
        Error: File caml.cmx
        was not compiled with the `-for-pack Core' option
  *)
  let omake_error =
    let error1 = "\\*\\*\\* omake error:" in
    let error2 = " *Error: Forward reference" in
    let error3 = " *Error: No implementations provided" in
    let error4 = " *Error: Cannot find file" in
    let error5 = "omake: \".*\" failed on" in
    let error6 = " *Error: Files" in
    let error7 = " *File \".*\\.cmx\"" in
    Regex.of_string (sprintf "(%s|%s|%s|%s|%s|%s|%s)"
                       error1 error2 error3 error4 error5 error6 error7)
end

(* -------------------------------------------------------------------------- *)
(*  Status                                                                    *)
(* -------------------------------------------------------------------------- *)

module Status = struct
  type t =
  | Starting
  | Polling
  | Reading_omakefiles
  | Reading_omakefiles_failed
  | Finished_omakefiles
  | Building
  with sexp
  let to_string s = Sexp.to_string (sexp_of_t s)
  let to_elisp = function
    | Starting -> "Omake.Status.Starting"
    | Polling -> "Omake.Status.Polling"
    | Reading_omakefiles -> "Omake.Status.Reading_omakefiles"
    | Reading_omakefiles_failed -> "Omake.Status.Reading_omakefiles_failed"
    | Finished_omakefiles -> "Omake.Status.Finished_omakefiles"
    | Building -> "Omake.Status.Building"
end

(* -------------------------------------------------------------------------- *)
(*  Events                                                                    *)
(* -------------------------------------------------------------------------- *)

module Event : sig
  type t =
  | Status of Status.t
  | Progress_bar of int * int
  | Targets_up_to_date of int * int
  | New_error of [`Ocaml of Error.t | `Omake of string]
  | Refresh_file of [`Dir of path] * [`Filename_with_no_extension of string]
  | Done
  | Last_line of string
  with sexp
  val parse_events : string Pipe.Reader.t -> t result Pipe.Reader.t
end = struct
  type t =
  | Status of Status.t
  | Progress_bar of int * int
  | Targets_up_to_date of int * int
  | New_error of [`Ocaml of Error.t | `Omake of string]
  | Refresh_file of [`Dir of path] * [`Filename_with_no_extension of string]
  | Done
  | Last_line of string
  with sexp

  let parse_events string_reader =
    let (event_reader, event_writer) = Pipe.create () in
    let write t =
      (* dprintf "parse_events: ok: %s" (Sexp.to_string (sexp_of_t t)); *)
      Pipe.write event_writer (Ok t)
    in
    let relpath = ref None in
    let partial_error = ref None in
    let add_error_line l = match !partial_error with
      | None -> ()
      | Some e -> Partial_error.add_line e l
    in
    let finish_error () = match !partial_error with
      | None -> Deferred.unit
      | Some p ->
        let e = Partial_error.reify p in
        write (New_error e) >>| fun () ->
        partial_error := None
    in
    (* Don't write progress bars as last lines *)
    let last_line s =
      if not (Regex.has_match Rex.progress_bar s) then
        write (Last_line s)
      else
        Deferred.unit
    in
    let iter () : unit deferred = Pipe.iter string_reader ~f:(function
      | s when String.equal (String.strip s) "" ->
        Deferred.unit
      | s ->
        last_line s >>= fun () ->
        if Regex.has_match Rex.reading_omakefiles s then
          begin
            finish_error () >>= fun () ->
            write (Status Status.Reading_omakefiles)
          end
        else if Regex.has_match Rex.reading_omakefiles_failed s then
          begin
            finish_error () >>= fun () ->
            write (Status Status.Reading_omakefiles_failed)
          end
        else if Regex.has_match Rex.finished_omakefiles s then
          begin
            finish_error () >>= fun () ->
            write (Status Status.Finished_omakefiles)
          end
        else if Regex.has_match Rex.start_build s then
          begin
            finish_error () >>= fun () ->
            write (Status Status.Building)
          end
        else if Regex.has_match Rex.polling s then
          begin
            finish_error () >>= fun () ->
            write (Status Status.Polling)
          end
        else if Regex.has_match Rex.rebuilding s then
          begin
            finish_error () >>= fun () ->
            write (Status Status.Building)
          end
        else if Regex.has_match Rex.done_ s then
          begin
            finish_error () >>= fun () ->
            write Done
          end
        else if Regex.has_match Rex.omake_error s then
          begin
            let partial = Partial_error.create_omake ~text:s in
            finish_error () >>| fun () ->
            partial_error := Some partial
          end
        else
          (* Please keep the nonstandard indentation *)
          let rex = Rex.targets_up_to_date in
          match Regex.matches rex s with
          | m :: _ ->
            let num = Regex.get rex ~sub:(`Name "num") m |! Int.of_string in
            let denom = Regex.get rex ~sub:(`Name "denom") m |! Int.of_string in
            finish_error () >>= fun () ->
            write (Targets_up_to_date (num, denom))
          | [] ->
          let rex = Rex.progress_bar in
          match Regex.matches rex s with
          | m :: _ ->
            let num = Regex.get rex ~sub:(`Name "num") m |! Int.of_string in
            let denom = Regex.get rex ~sub:(`Name "denom") m |! Int.of_string in
            finish_error () >>= fun () ->
            write (Progress_bar (num, denom))
          | [] ->
          let rex = Rex.build in
          match Regex.matches rex s with
          | m :: _ ->
            let dir = Regex.get rex ~sub:(`Name "dir") m in
            let file = Regex.get rex ~sub:(`Name "file") m in
            relpath := Some dir;
            finish_error () >>= fun () ->
            write (Status Status.Building) >>= fun () ->
            write (Refresh_file (`Dir dir, `Filename_with_no_extension file))
          | [] ->
          let rex = Rex.changed in
          match Regex.matches rex s with
          | m :: _ ->
            let dir = Regex.get rex ~sub:(`Name "dir") m in
            let file = Regex.get rex ~sub:(`Name "file") m in
            finish_error () >>= fun () ->
            write (Refresh_file (`Dir dir, `Filename_with_no_extension file))
          | [] ->
          let rex = Rex.ocaml_error in
          match Regex.matches rex s with
          | m :: _ ->
            let get s = Regex.get rex ~sub:(`Name s) m in
            let file = get "file" in
            let line = get "line" |! int_of_string in
            let char_beg = get "charbeg" |! int_of_string in
            let char_end = get "charend" |! int_of_string in
            let relpath = match !relpath with
              | None ->
                dprintf "ERROR: Can't find relpath for %s" s;
                ""
              | Some r -> r
            in
            let partial = Partial_error.create_ocaml
              ~relpath ~file ~line ~char_beg ~char_end ~text:s
            in
            finish_error () >>| fun () ->
            partial_error := Some partial
          | [] ->
            add_error_line s;
            Deferred.unit)
    in
    whenever (iter ());
    event_reader
end

(* -------------------------------------------------------------------------- *)
(*  State                                                                     *)
(* -------------------------------------------------------------------------- *)

module State : sig
  type t
  val create : omakeroot_dir:path -> t
  val handle_events
    :  t
    -> Event.t result Pipe.Reader.t
    -> elisp result Pipe.Reader.t
end = struct

  module T = struct
    type t = {
      omakeroot_dir : path;
      mutable relpath : path option;
      mutable status : Status.t;
      mutable errors : Error.t list;
      mutable targets_up_to_date : int * int;
      mutable progress_bar : int * int;
      mutable omake_error : string option;
      mutable last_line : string;
      mutable done_ : bool;
    }

    let create ~omakeroot_dir = {
      omakeroot_dir;
      relpath = None;
      status = Status.Starting;
      errors = [];
      targets_up_to_date = (0, 0);
      progress_bar = (0, 0);
      omake_error = None;
      last_line = "";
      done_ = false;
    }
  end
  include T

  module Snapshot : sig
    type t
    val to_elisp : t -> elisp
    val take : last:(t option) -> T.t -> t option
  end = struct
    type t = {
      omakeroot_dir : path;
      relpath : path option;
      status : Status.t;
      last_line : string;
      targets_up_to_date : int * int;
      progress_bar : int * int;
      omake_error : string option;
      errors : Error.t list;
      done_ : bool;
    }

    let diff t1 t2 =
      let omakeroot_dir =
        if String.equal t1.omakeroot_dir t2.omakeroot_dir then None else
          Some "omakeroot_dir"
      in
      let status = if t1.status = t2.status then None else
          Some "status"
      in
      let targets = if t1.targets_up_to_date = t2.targets_up_to_date then None else
          Some "targets"
      in
      let progress = if t1.progress_bar = t2.progress_bar then None else
          Some "progress"
      in
      let err = if t1.omake_error = t2.omake_error then None else
          Some "omake_error"
      in
      let last = if t1.last_line = t2.last_line then None else
          Some "last"
      in
      let done_ = if t1.done_ = t2.done_ then None else
          Some "done_"
      in
      let errs =
        if List.length t1.errors = List.length t2.errors
        && List.for_all (List.zip_exn t1.errors t2.errors) ~f:(fun (e1, e2) ->
          Error.equal e1 e2)
        then None else Some "errors"
      in
      match
        List.filter_opt
          [omakeroot_dir;status;targets;progress;err;last;done_;errs]
      with
      | [] -> None
      | l -> Some (String.concat ~sep:"," l)

    let to_elisp t =
      let id = t.omakeroot_dir in
      let elisp_list : 'a list -> f:('a -> elisp) -> elisp =
        fun l ~f -> match l with
        | [] -> "nil"
        | _ -> sprintf "(list %s)" (String.concat ~sep:"    \n" (List.map ~f l))
      in
      match t.omake_error with
      | None ->
        let status = Status.to_elisp t.status in
        let last_line = quote t.last_line in
        let targets_up_to_date =
          let (num, denom) = t.targets_up_to_date in
          sprintf "'(%d . %d)" num denom
        in
        let progress_bar =
          let (num, denom) = t.progress_bar in
          sprintf "'(%d . %d)" num denom
        in
        let done_ = if t.done_ then "t" else "nil" in
        let errors = elisp_list t.errors ~f:(Error.to_elisp ~id) in
        sprintf "\
(Omake.Ocaml.update-model-ok
  :id \"%s\"
  :status %s
  :last-line %s
  :targets-up-to-date %s
  :progress-bar %s
  :done %s
  :errors
    %s)"
          id
          status
          last_line
          targets_up_to_date
          progress_bar
          done_
          errors
      | Some msg ->
        sprintf "\
(Omake.Ocaml.update-model-failure
  :id \"%s\"
  :msg %s)"
          id
          (quote msg)
    ;;

    let take ~last t =
      let t' = {
        omakeroot_dir = t.T.omakeroot_dir;
        relpath = t.T.relpath;
        status = t.T.status;
        last_line = t.T.last_line;
        errors = t.T.errors;
        targets_up_to_date = t.T.targets_up_to_date;
        progress_bar = t.T.progress_bar;
        omake_error = t.T.omake_error;
        done_ = t.T.done_;
      }
      in
      match last with
      | None -> Some t'
      | Some t -> match diff t t' with
        | None -> None
        | Some _ -> Some t'
  end

  let remove_extension f =
    match String.index f '.' with
    | None -> f
    | Some n -> String.sub f ~pos:0 ~len:n

  let handle_events t event_reader =
    let module E = Event in
    let (elisp_reader, elisp_writer) = Pipe.create () in
    (* Send periodic snapshots when the model has changed *)
    let (update_reader, update_writer) = Pipe.create () in
    let update =
      let last_snapshot = ref None in
      (* Don't send updates faster than [span] *)
      let span = Time.Span.of_sec 1.0 in
      fun () ->
        match Snapshot.take ~last:!last_snapshot t with
        | None ->
          Deferred.unit
        | Some t ->
          last_snapshot := Some t;
          let elisp = Snapshot.to_elisp t in
          dprintf "%s" (String.escaped elisp);
          Pipe.write elisp_writer (Ok elisp) >>= fun () ->
          Clock.after span
    in
    whenever (Pipe.iter update_reader ~f:update);
    let update () =
      whenever (Pipe.write update_writer ());
      Deferred.unit
    in
    (* update the model *)
    let write_error e = Pipe.write elisp_writer (Error e) in
    let iter () = Pipe.iter event_reader ~f:(function
      | Error e -> write_error e
      | Ok e ->
        eprintf "%s" (Sexp.to_string (Event.sexp_of_t e));
        match e with
        | E.Last_line s ->
          t.last_line <- s;
          update ()
        | E.Status status ->
          begin
            t.status <- status;
            match status with
            | Status.Reading_omakefiles ->
              t.errors <- [];
              t.omake_error <- None;
              t.done_ <- false;
            | _ -> ()
          end;
          update ()
        | E.Progress_bar (num, denom) ->
          t.progress_bar <- (num, denom);
          t.omake_error <- None;
          update ()
        | E.Targets_up_to_date (num, denom) ->
          t.targets_up_to_date <- (num, denom);
          update ()
        | E.New_error (`Ocaml e) ->
          t.omake_error <- None;
          begin
            match List.find t.errors ~f:(fun e' -> Error.equal e e') with
            | Some _ -> ()
            | None -> t.errors <- e :: t.errors
          end;
          update ()
        | E.New_error (`Omake e) ->
          t.omake_error <- Some e;
          update ()
        | E.Refresh_file (`Dir d, `Filename_with_no_extension f) ->
          let errs = List.filter t.errors ~f:(fun e ->
            let ef = remove_extension e.Error.file in
            not (String.equal e.Error.relpath d
                 && String.equal ef f))
          in
          t.errors <- errs;
          t.done_ <- false;
          t.omake_error <- None;
          update ()
        | E.Done ->
          let errors = t.errors in
          let omake_error = t.omake_error in
          t.errors <- [];
          t.omake_error <- None;
          t.done_ <- true;
          let errors = match errors with
            | [] -> Deferred.unit
            | _ ->
              let errs = String.concat ~sep:"," (List.map t.errors ~f:(fun e ->
                Error.to_string e))
              in
              write_error (Failure (sprintf "Got 'done' but still had errors: %s" errs))
          in
          let omake_error = match omake_error with
            | None -> Deferred.unit
            | Some e ->
              write_error
                (Failure (sprintf "Got 'done' but still had omake error: %s" e))
          in
          errors >>= fun () ->
          omake_error >>= fun () ->
          update ())
    in
    whenever (iter ());
    elisp_reader
end

(* -------------------------------------------------------------------------- *)
(*  Parse                                                                     *)
(* -------------------------------------------------------------------------- *)

module Parse : sig
  val parse
    :  omakeroot_dir:path
    -> string Pipe.Reader.t
    -> elisp result Pipe.Reader.t
end = struct
  let cleanup_chars =
  (* Either ocamlopt or omake generate multibyte characters in the output.  This
     throws off error reporting. Remove them after reading in the file.  Note that
     this does not throw off error reporting on the emacs side because multibyte
     chars count as a single character in emacs.  Additionally, omake adds \r  *)
    let table = List.map ~f:(fun (r, v) -> (Regex.of_string r, v))
      [ ("’|‘", "'") ]
    in
    fun line -> 
      let lines = String.split ~on:'\r' line in
      let replace line = List.fold table
        ~init:line
        ~f:(fun line (rex, template) -> Regex.rewrite rex ~template line)
      in
      List.map ~f:replace lines

  let parse ~omakeroot_dir reader =
    let state = State.create ~omakeroot_dir in
    let lines = Pipe.map ~f:cleanup_chars reader in
    let (reader, writer) = Pipe.create () in
    whenever (Pipe.iter lines ~f:(Deferred.List.iter ~f:(Pipe.write writer)));
    let events = Event.parse_events reader in
    State.handle_events state events
end

let parse_omake_output = Parse.parse