Source

js-elisp / ocaml / contrib / ocp-indent / src / indentBlock.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
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
(**************************************************************************)
(*                                                                        *)
(*  Copyright 2011 Jun Furuse                                             *)
(*  Copyright 2012,2013 OCamlPro                                          *)
(*                                                                        *)
(*  All rights reserved.  This file is distributed under the terms of     *)
(*  the GNU Public License version 3.0.                                   *)
(*                                                                        *)
(*  TypeRex is distributed in the hope that it will be useful,            *)
(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)
(*  GNU General Public License for more details.                          *)
(*                                                                        *)
(**************************************************************************)

open Pos
open Nstream
open Approx_lexer
open Util

module Node = struct

  (* Node kind *)
  type kind =
    | KParen
    | KBrace
    | KBracket
    | KBracketBar
    | KLet
    | KAnd of kind
    | KLetIn
    | KIn

    | KExpr of int
    (* actually handles also patterns / types / ... *)
    (* Parameter:Priority - next expression is deindented if the op has
       lower priority *)

    | KBody of kind
    | KArrow of kind
    | KColon
    | KType
    | KException
    | KOpen
    | KInclude
    | KVal
    | KBar of kind
    | KNone
    | KStruct
    | KSig
    | KModule
    | KBegin
    | KObject
    | KMatch
    | KTry
    | KWith of kind
    | KLoop
    | KIf
    | KThen
    | KElse
    | KDo
    | KFun
    | KWhen
    | KExternal

  (* Priority of open expression constructs (see below for operators) *)
  let prio = function
    | KIn | KArrow _ -> 0
    | KThen | KElse -> 10
    | KExpr i -> i
    | _ -> -10

  let prio_max = 200
  let prio_apply = 140
  let expr_atom = KExpr prio_max
  let expr_apply = KExpr 140
  (* Special operators that should break arrow indentation have this prio
     (eg monad operators, >>=) *)
  let prio_flatop = 59
  let prio_semi = 5

  let rec follow = function
    | KAnd k
    | KBody k
    | KWith k -> follow k
    | k -> k

  let rec string_of_kind = function
    | KExpr i -> Printf.sprintf "KExpr(%d)" i
    | KParen -> "KParen"
    | KBrace -> "KBrace"
    | KBracket -> "KBracket"
    | KBracketBar -> "KBracketBar"
    (* | KField -> "KField" *)
    | KLet -> "KLet"
    | KIn -> "KIn"
    | KAnd k -> aux "KAnd" k
    | KLetIn -> "KLetIn"
    | KBody k -> aux "KBody" k
    | KArrow k -> aux "KArrow" k
    | KColon -> "KColon"
    | KVal -> "KVal"
    | KBar k -> aux "KBar" k
    | KOpen -> "KOpen"
    | KInclude -> "KInclude"
    | KNone -> "KNone"
    | KType -> "Ktype"
    | KException -> "KException"
    | KStruct -> "KStruct"
    | KSig -> "KSig"
    | KModule -> "KModule"
    | KBegin -> "KBegin"
    | KObject -> "KObject"
    | KMatch -> "KMatch"
    | KTry -> "KTry"
    | KWith k -> aux "KWith" k
    | KLoop -> "KLoop"
    | KIf -> "KIf"
    | KThen -> "Kthen"
    | KElse -> "KElse"
    | KDo -> "KDo"
    | KFun -> "KFun"
    | KWhen -> "KWhen"
    | KExternal -> "KExternal"

  and aux str k =
    Printf.sprintf "%s(%s)" str (string_of_kind k)

  (* A node:
     - has a kind
     - has the current line offset [l]
     - has the current token offset [t]
     - has a inner padding [pad]
     - has a line count [count]

             XXX XXX XXX [
                                XXX
                         ]

             XXX XXX XXX [
                   XXX
             ]

     <---l--->
     <----------x-------->
                         <-pad->
             <-pad->
  *)

  type t = {
    k:   kind;
    l:   int;
    t:   int;
    pad : int;
    line: int;
  }

  let to_string i t =
    Printf.sprintf "%s%s %d|%d-%d(%d)"
      (String.make i ' ') (string_of_kind t.k) t.line t.l t.t t.pad

  let create k l t pad line =
    { k; l; t; pad; line }

  let shift node n =
    let n = max n (- node.l) in
    { node with l = node.l + n; t = node.t + n }

end

module Path = struct

  open Node
  type t = Node.t list

  let to_string t =
    String.concat " \027[35m/\027[m "
      (List.map (fun n -> Node.to_string 0 n) (List.rev t))

  let l = function
    | [] -> 0
    | t :: _ -> t.l

  let t = function
    | [] -> 0
    | t :: _ -> t.t

  let pad = function
    | [] -> 0
    | t :: _ -> t.pad

  let maptop f = function
    | []   -> []
    | t::l -> f t :: l

  let shift path n =
    maptop (fun t -> Node.shift t n) path
end

open Node

(* A block is:
   - a node path to go to this block
   - the last token of this block
   - the last token offset
   - the original starting column for this block *)
type t = {
  path: Path.t;
  last: Nstream.token option;
  toff: int;
  orig: int;
}

let shift t n =
  { t with path = Path.shift t.path n }

let to_string t =
  Path.to_string t.path
    (* Printf.sprintf "%s\n%d %b" (Path.to_string t.path) t.toff *)

let empty = {
  path = [];
  last = None;
  toff = 0;
  orig = 0;
}

(*
(* Does the token close a top LET construct ? *)
(* NB: we do this with another way below, but this one might be more robust *)
let rec close_top_let = function
  | None -> true
  | Some t ->
      match t.token with
      | COMMENT _ -> assert false (* COMMENT must be skipped *)

      (* Tokens that allow a let-in after them *)
      | AMPERSAND | AMPERAMPER | BARBAR | BEGIN | COLONCOLON | COLONEQUAL
      | COMMA | DO | DOWNTO | ELSE | EQUAL | GREATER | IF | IN
      | INFIXOP0 _ | INFIXOP1 _ | INFIXOP2 _ | INFIXOP3 _ | INFIXOP4 _
      | LBRACE | LBRACELESS
      | LBRACKET | LBRACKETBAR | LBRACKETLESS | LBRACKETGREATER
      | LESS | LESSMINUS | LPAREN | MATCH | MINUS | MINUSDOT | MINUSGREATER | OR
      | PLUS | PLUSDOT | QUESTION | QUESTIONQUESTION | SEMI | STAR | THEN
      | TO | TRY | WHEN | WHILE
      | TILDE -> false

      | _ -> true
*)

(* Go back to the node path path until [f] holds *)
let rec unwind f path = match path with
  | { k } :: _ when f k -> path
  | _ :: path -> unwind f path
  | [] -> []

(* Unwinds the path while [f] holds, returning the last step for which it does *)
let unwind_while f path =
  let rec aux acc = function
    | { k } as h :: p when f k -> aux h p
    | p -> acc :: p
  in
  match path with
  | { k } as h :: p when f k -> Some (aux h p)
  | _ -> None

(* Unwind the struct/sig top *)
let unwind_top =
  unwind (function KStruct|KSig|KParen|KBegin|KObject -> true | _ -> false)

(* Get the parent node *)
let parent = function
  | []     -> []
  | _ :: t -> t

(* Get the next token *)
let rec next_token_full stream =
  match Nstream.next stream with
  | None
  | Some ({token=EOF},_)       -> None
  | Some ({token=COMMENT _},s) -> next_token_full s
  | Some (t,_)                 -> Some t

let next_token stream =
  match next_token_full stream with
  | None -> None
  | Some t -> Some t.token

let last_token t =
  match t.last with
  | None   -> None
  | Some t -> Some t.token

(* a more efficient way to do this would be to store a
   "context-type" in the stack *)
let rec is_inside_type path =
  match unwind (function
      | KParen | KBegin | KBracket | KBrace | KBracketBar
      | KVal | KLet | KLetIn | KBody (KVal | KLet | KLetIn)
      | KBody(KType|KExternal) | KColon -> true
      | _ -> false)
      path
  with
  | {k=KBody(KVal|KType|KExternal) | KColon}::_ -> true
  | {k=KParen | KBegin | KBracket | KBrace}::p ->
      is_inside_type p
  | _ -> false

let stacktrace t =
  Printf.eprintf "\027[32m%8s\027[m %s\n%!"
    (match t.last with Some tok -> tok.substr | _ -> "")
    (to_string t)

(* different kinds of position:
   [T]: token aligned: the child is aligned with the token position
   [L]: line aligned: the child is aligned with the begining of line
   [A]: absolute position *)
type pos = L | T | A of int (* position *)

(* Take a block, a token stream and a token.
   Return the new block stack. *)
let update_path config t stream tok =
  let open IndentConfig in
  let is_first_line = Region.char_offset tok.region = tok.offset in
  let starts_line = tok.newlines > 0 || is_first_line in
  let node replace k pos pad path =
    let line = Region.start_line tok.region in
    if starts_line then
      let l = match pos with
        | A p -> p
        | L   -> Path.l path + if replace then 0 else Path.pad path
        | T   -> Path.t path + if replace then 0 else Path.pad path in
      Node.create k l l pad line
    else
      let l = Path.l path in
      let t = t.toff + tok.offset in
      Node.create k l t pad line
  in
  (* Add a new child block *)
  let append k pos ?(pad=config.i_base) path =
    node false k pos pad path :: path
  in
  (* replace the current block with a new one *)
  let replace k pos ?(pad=config.i_base) path = match path with
    | []   -> [node true k pos pad path]
    | _::t -> node true k pos pad path :: t
  in
  (* Used when expressions are merged together (for example in "3 +" the "+"
     extends the lower-priority expression "3") *)
  let extend k pos ?(pad=config.i_base) = function
    | [] -> [node true k pos pad []]
    | h::p ->
        let negative_indent () =
          (* Special negative indent: relative, only at beginning of line,
             and when prio is changed or there is a paren to back-align to *)
          if pad >= 0 || not starts_line then None else
            match p with
            | {k=KParen|KBracket|KBracketBar|KBrace|KBar _|KWith KBrace}
              as paren :: _
              when paren.line = h.line
              ->
                let paren_len = match paren.k with
                  | KParen | KBracket | KBrace | KBar _ -> 1
                  | KBracketBar -> 2
                  | KWith KBrace -> 4
                  | _ -> assert false
                in
                let l = paren.t + paren_len + 1 (* usually 1 space *) + pad in
                Some ({ h with k; l; t=l } :: p)
            | _ ->
                match k,h.k with
                | KExpr pk, KExpr ph when ph = pk ->
                    (* respect the indent of the above same-priority term, we
                       assume it was already back-indented *)
                    Some ({ h with k; l=h.t; t=h.t; pad = h.pad } :: p)
                | _ ->
                    let l = h.t + pad in
                    if l < 0 then None
                    else Some ({ h with k; l; t=l; pad = -pad } :: p)
        in
        match negative_indent () with
        | Some p -> p
        | None -> (* normal case *)
            (* change l to set the starting column of the expression *)
            let pad = max 0 pad in
            let l,pad =
              if pos = T then h.t + pad, 0
              else
                (* set indent of the whole expr accoring to its parent *)
                Path.l p + Path.pad p, pad
            in
            { h with k; l; pad } :: p
  in
  (* use before appending a new expr_atom: checks if that may cause an
     apply and folds parent exprs accordingly *)
  let fold_expr path =
    match path with
    | {k=KExpr _} :: ({k=KFun}::_ as p) -> p
    | {k=KExpr i}::_ when i = prio_max ->
        (* we are appending two expr_atom next to each other:
           this is an apply. *)
        (* this "folds" the left-side of the apply *)
        let p = match unwind_while (fun k -> prio k >= prio_apply) path with
          | Some({k=KExpr i}::_ as p) when i = prio_apply -> p
          | Some({k=KExpr _}::{k=KArrow (KMatch|KTry)}::_ as p) ->
              (* Special case: switch to token-aligned (see test js-args) *)
              extend (KExpr prio_apply) T p
          | Some p -> extend (KExpr prio_apply) L p
          | None -> assert false
        in
        p
    | _ -> path
  in
  let before_append_atom = function
    | {k=KWith(KTry|KMatch as m); pad}::_ as path ->
        (* Special case: 'match with' and no bar for the 1st case:
           we append a virtual bar for alignment *)
        let p =
          append (KBar m) L ~pad:(max 2 pad) path
        in
        if not starts_line then
          let t = max 0 (t.toff + tok.offset - 2) in
          Path.maptop (fun h -> {h with t}) p
        else p
    | path -> fold_expr path
  in
  let atom path =
    let path = before_append_atom path in
    let pad = match path with {k=KExpr _; pad}::_ -> pad | _ -> config.i_base in
    append expr_atom L ~pad path
  in
  let open_paren k path =
    let path = before_append_atom path in
    let p = append k L (fold_expr path) in
    match p with
    | [] -> []
    | {k=KParen|KBegin} :: {k=KArrow _} :: _
      when not starts_line ->
        (* Special case: paren/begin after arrow has extra indent
           (see test js-begin) *)
        Path.shift p config.i_base
    | h::p as path ->
        match next_token_full stream with
        | Some next
          when Region.start_line next.region = Region.end_line tok.region
          ->
            if k = KBegin then path
            else if starts_line then
              (* set padding for next lines *)
              { h with pad = next.offset } :: p
            else if k = KParen then path
            else
              let l = t.toff + tok.offset in
              (* set alignment for next lines relative to [ *)
              { h with l; t=l; pad = next.offset } :: p
        | _ -> path
  in
  let close f path =
    (* Remove the padding for the closing brace/bracket/paren/etc. *)
    Path.maptop (fun h -> {h with k=expr_atom; pad=0}) (unwind f path)
  in
  let op_prio_align_indent = function
    (* anything else : -10 *)
    (* in -> : 0 *)
    | SEMI -> prio_semi,L,-2
    | AS -> 8,L,config.i_base
    (* special negative indent is only honored at beginning of line *)
    (* then else : 10 *)
    | BAR -> 10,T,-2
    | OF -> 20,L,2
    | LESSMINUS | COLONEQUAL -> 20,L,config.i_base
    | COMMA -> 30,L,0
    | MINUSGREATER -> 32,L,0 (* is an operator only in types *)
    | COLON | COLONGREATER -> 35,L,config.i_base
    | OR | BARBAR -> 40,T,0
    | AMPERSAND | AMPERAMPER -> 50,T,0
    | INFIXOP0 s ->
        (match String.sub s 0 (min 2 (String.length s)) with
         (* these should deindent fun -> *)
         | ">>" -> prio_flatop,L,0
         | "|!" | "|>" -> prio_flatop,T,0
         | _ -> 60,L,config.i_base)
    | EQUAL | LESS | GREATER -> 60,L,config.i_base
    | INFIXOP1 _ -> 70,L,config.i_base
    | COLONCOLON -> 80,L,config.i_base
    | INFIXOP2 _ | PLUSDOT | PLUS | MINUSDOT | MINUS -> 90,L,config.i_base
    | INFIXOP3 _ | STAR -> 100,L,config.i_base
    | INFIXOP4 _ -> 110,L,config.i_base
    (* apply: 140 *)
    | TILDE | QUESTION -> 140,L,config.i_base
    | LABEL _ | OPTLABEL _ -> 145,L,0
    | SHARP -> 150,L,config.i_base
    | DOT -> 160,L,config.i_base
    | _ -> assert false
  in
  let make_infix token path =
    let op_prio, align, indent = op_prio_align_indent token in
    match path with
    | {k=KExpr prio}::_ when prio >= op_prio && prio < prio_max ->
        (* we are just after another operator (should be an atom).
           handle as unary (eg. x + -y) : indented but no effect
           on following expressions *)
        (* append KNone L path *)
        append (KExpr prio) L ~pad:(max 0 indent) path
    | _ ->
        match unwind_while (fun k -> prio k >= op_prio) path with
        | Some p ->
            extend (KExpr op_prio) align ~pad:indent p
        | None -> (* used as prefix ? Don't apply T indent *)
            append (KExpr op_prio) L ~pad:(max 0 indent) path
  in
  (* KNone nodes correspond to comments or top-level stuff, they shouldn't be
     taken into account when indenting the next token *)
  let t0 = t in
  let t = match t.path with {k=KNone}::path -> {t with path}
                          | _ -> t
  in
  match tok.token with
  | SEMISEMI    -> append KNone L ~pad:0 (unwind_top t.path)
  | INCLUDE     -> append KInclude L (unwind_top t.path)
  | EXCEPTION   -> append KException L (unwind_top t.path)
  | BEGIN       -> open_paren KBegin t.path
  | OBJECT      -> append KObject L t.path
  | VAL         -> append KVal L (unwind_top t.path)
  | MATCH       -> append KMatch L (fold_expr t.path)
  | TRY         -> append KTry L (fold_expr t.path)
  | LPAREN      -> open_paren KParen t.path
  | LBRACKET | LBRACKETGREATER | LBRACKETLESS ->
      open_paren KBracket t.path
  | LBRACKETBAR -> open_paren KBracketBar t.path
  | LBRACE | LBRACELESS ->
      open_paren KBrace t.path
  | FUNCTION ->
      (match fold_expr t.path with
       | l :: _ as p when not starts_line && not config.i_with_never ->
           append (KWith KMatch) L ~pad:(max l.pad config.i_with) p
       | p ->
           append (KWith KMatch) L ~pad:config.i_with p)
  | FUN | FUNCTOR ->
      (match t.path with
       | {k=KArrow KFun}::p ->
           replace KFun L (unwind (function KFun -> true | _ -> false) p)
       | p -> append KFun L (fold_expr p))
  | STRUCT ->
      append KStruct L  (Path.maptop (fun n -> {n with pad=0}) t.path)
  | WHEN ->
      append KWhen L ~pad:(config.i_base + if starts_line then 0 else 2)
        (unwind (function
           | KWith(KTry|KMatch) | KBar(KTry|KMatch) | KFun -> true
           | _ -> false)
           t.path)
  | SIG ->
      append KSig L (Path.maptop (fun n -> {n with pad=0}) t.path)

  | OPEN ->
      if last_token t = Some LET then
        append KOpen L t.path
      else
        append KOpen L (unwind_top t.path)

  | LET ->
      (* Two ways to detect let vs letin ;
         both seem to work, but need to check which one
         is the most robust (for example w.r.t. unfinished expressions) *)
      (* - it's a top Let if it is after a closed expression *)
      (match t.path with
       | {k=KExpr i}::p when i = prio_max ->
           append KLet L (unwind_top p)
       | {k=KNone}::_ | [] ->
           append KLet L []
       | _ ->
           append KLetIn L (fold_expr t.path))
      (* - or if after a specific token *)
      (* if close_top_let t.last then *)
      (*   append KLet L config.i_base (unwind_top t.path) *)
      (* else *)
      (*   append KLetIn L config.i_base (fold_expr t.path) *)

  | CLASS ->
      append KLet L (unwind_top t.path)

  | METHOD ->
      append KLet L (unwind_top t.path)

  | INITIALIZER ->
      append (KBody KLet) L (unwind_top t.path)

  | CONSTRAINT ->
      let path =
        unwind
          (function KType | KBody KType | KObject -> true | _ -> false)
          t.path
      in
      append KLet L path

  | AND ->
      let unwind_to = function
        | KLet | KLetIn | KType | KModule -> true
        | _ -> false
      in let path = unwind (unwind_to @* follow) t.path in
      (match path with
       | {k=KType|KModule|KBody (KType|KModule)}
         :: ({k=KWith _} as m) :: p ->
           (* hack to align "and" with the 'i' of "with": consider "with" was
              1 column further to the right *)
           let m = if starts_line then {m with t = m.t+1} else m in
           replace (KAnd m.k) T ~pad:0 (m :: p)
       | {k=KType|KModule|KBody (KType|KModule)}
         :: ({k=KAnd (KWith _)} as m) :: p ->
           replace m.k T ~pad:0 (m :: p)
       | h::_ -> replace (KAnd (follow h.k)) L path
       | []   -> append (KAnd KNone) L path)

  | IN ->
      let path = unwind ((=) KLetIn @* follow) t.path in
      let pad = match next_token stream with
        | Some LET -> 0
        | _ -> config.i_in
      in
      (match unwind_while ((=) KIn) (parent path) with
       | Some p -> extend KIn L ~pad p
       | None -> extend KIn L ~pad path)

  | TYPE ->
      (match last_token t with
       | Some (MODULE | CLASS) -> t.path (* module type *)
       | Some (WITH|AND) -> append KType L t.path
       | _ -> append KType L (unwind_top t.path))

  | MODULE ->
      (match last_token t with
       | Some LET -> t.path (* let module *)
       | Some (WITH|AND) -> append KType L t.path
       | _ -> append KModule L (unwind_top t.path))

  | END ->
      close (function KStruct|KSig|KBegin|KObject -> true | _ -> false) t.path

  | WITH ->
      (match next_token_full stream with
       | Some ({token=TYPE|MODULE as tm}) ->
           let path =
             unwind (function
               | KModule | KOpen | KInclude | KParen
               | KBegin | KColon | KBody KModule ->
                   true
               | _ -> false)
               t.path
           in
           let k =
             match tm with TYPE -> KType | MODULE -> KModule | _ -> assert false
           in
           append (KWith k) L path
       | next ->
           let path = unwind (function
               |KTry|KMatch
               |KVal|KType|KBody KType|KException (* type-conv *)
               |KBrace -> true
               | _ -> false
             ) t.path in
           match path with
           | {k=KBrace; pad} :: _ ->
               (match next with
                | Some next
                  when Region.start_line next.region
                    = Region.end_line tok.region ->
                    Path.maptop (fun n -> {n with l=n.t})
                      (append (KWith KBrace) L ~pad:next.offset path)
                | _ ->
                    append (KWith KBrace) L ~pad:(pad + config.i_with) path)
           | {k=KVal|KType|KException as k}::_ -> replace (KWith k) L path
           | {k=KTry|KMatch} as n :: {pad} :: _
             when n.line = Region.start_line tok.region
               && n.t <> n.l
               && not config.i_with_never
             ->
               replace (KWith KMatch)
                 L ~pad:(max pad config.i_with)
                 path
           | {k=(KTry|KMatch as k)}::_ ->
               replace (KWith k) L ~pad:config.i_with path
           | _ -> path)

  | IF ->
      (match last_token t with
       | Some ELSE  -> replace KIf L t.path
       | _ -> append  KIf L (fold_expr t.path))

  | THEN ->
      extend KThen L (unwind ((=) KIf) t.path)

  | ELSE ->
      extend KElse L (unwind ((=) KThen) t.path)

  | WHILE | FOR ->
      append KLoop L (fold_expr t.path)

  | TO | DOWNTO ->
      let p =
        Path.maptop (fun n -> { n with l = n.l + config.i_base })
          (unwind ((=) KLoop) t.path)
      in
      replace KLoop L p

  | DO ->
      extend KDo L (unwind ((=) KLoop) t.path)

  | DONE ->
      close ((=) KDo) t.path

  | BARRBRACKET -> close ((=) KBracketBar) t.path

  | RPAREN -> close ((=) KParen) t.path

  | RBRACE | GREATERRBRACE -> close ((=) KBrace) t.path

  | RBRACKET | GREATERRBRACKET -> close ((=) KBracket) t.path

  | BAR ->
      let path = unwind (function
          | KParen | KBegin | KBracket | KBrace | KBracketBar
          | KWith(KMatch|KTry) | KBar(KMatch|KTry) | KArrow(KMatch|KTry)
          | KLet | KLetIn
          | KBody(KType) -> true
          | _ -> false)
          t.path
      in
      (match path with
       | {k=KWith m} :: _ -> append (KBar m) L path
       | {k=KArrow (KMatch|KTry as m)} :: ({k=KBar _} as h:: _ as p) ->
           Path.maptop (fun x -> {x with t = h.t})
             (replace (KBar m) (A h.t) p)
       | {k=KArrow m} :: p ->
           append (KBar m) L p
       | _ ->
           match t.path with
           | {k = KExpr _}::_ -> make_infix tok.token t.path
           | _ -> append (KBar KType) L t.path)

  | MINUSGREATER ->
      let rec find_parent path =
        let path = unwind (function
            | KParen | KBegin | KBracket | KBrace | KBracketBar
            | KWith(KMatch|KTry) | KBar(KMatch|KTry) | KArrow(KMatch|KTry)
            | KFun
            | KBody(KType|KExternal) | KColon -> true
            | _ -> false)
            path
        in
        match path with
        | {k=KFun} :: {k=KExpr i} :: path when i = prio_flatop ->
            (* eg '>>= fun x ->': indent like the top of the expression *)
            path
        | {k=KFun} :: _ -> append (KArrow KFun) L path
        | {k=KWith m | KBar m} :: _ ->
            let pad =
              config.i_match_clause
              - if starts_line then config.i_base else 0
            in
            append (KArrow m) L ~pad path
        | {k=KArrow(KMatch|KTry)} :: p ->
            (* might happen if doing 'when match' for example *)
            (match
              unwind (function
                | KParen | KBegin | KBracket | KBrace | KBracketBar
                | KWith(KMatch|KTry)
                | KFun
                | KBody(KType|KExternal) | KColon -> true
                | _ -> false)
                p
            with
            | {k=KWith(_)}::p -> find_parent p
            | _ -> make_infix tok.token t.path)
        | _ -> make_infix tok.token t.path
      in
      find_parent t.path

  | EQUAL ->
      let unwind_to = function
        | KParen | KBegin | KBrace | KBracket | KBracketBar | KBody _
        | KExternal | KModule | KType | KLet | KLetIn | KException
        | KAnd(KModule|KType|KLet|KLetIn) -> true
        | _ -> false
      in let path = unwind unwind_to t.path in
      (match path with
       | {k=KBody KType}::_ -> (* type t = t' = ... *)
           replace (KBody KType) L ~pad:config.i_type path
       | {k=KParen|KBegin|KBrace|KBracket|KBracketBar|KBody _}::_ ->
           make_infix tok.token t.path
       | {k=KAnd k | k} as h::p ->
           let indent = match next_token stream, k with
             | Some (STRUCT|SIG), _ -> 0
             | _, (KType | KBody KType) -> config.i_type
             | _ -> config.i_base
           in
           if starts_line then
             let h = {h with l = h.l + indent; pad = 0} in
             replace (KBody k) L ~pad:0 (h :: p)
           else
             replace (KBody k) L ~pad:indent (h :: p)
       | [] ->
           make_infix tok.token t.path)

  | COLONEQUAL ->
      (match
        unwind_while (function KExpr _ | KType -> true | _ -> false) t.path
      with
      | Some ({k=KType}::_ as p) -> (* type t := t' *)
          replace (KBody KType) L p
      | _ ->
          make_infix tok.token t.path)

  | COLON ->
      let path = unwind (function
          | KParen | KBegin | KBrace | KBracket | KBracketBar | KBody _
          | KModule | KLet | KLetIn | KExternal | KVal
          | KAnd(KModule|KLet|KLetIn) -> true
          | _ -> false)
          t.path
      in
      (match path with
       | {k = KModule|KLet|KLetIn|KExternal
         | KAnd(KModule|KLet|KLetIn|KExternal)} :: _ ->
           append KColon L path
       | {k=KVal} as h :: p ->
           let indent = config.i_base in
           if starts_line then
             let h = {h with l = h.l + indent; pad = 0} in
             replace (KBody h.k) L ~pad:0 (h :: p)
           else
             replace (KBody h.k) L ~pad:indent (h :: p)
       | {k=KBrace}::_ -> (* record type *)
           (match t.path with
            | {k=KExpr i}::{k=KBrace}::_ as p
              when i = prio_max ->
                extend KColon L p
            | {k=KExpr i}::({k=KExpr j}::{k=KBrace}::_ as p)
              when i = prio_max && j = prio_apply -> (* "mutable" *)
                extend KColon L p
            | _ -> make_infix tok.token t.path)
       | _ -> make_infix tok.token t.path)

  | SEMI ->
      (match unwind (fun k -> prio k < prio_semi) t.path with
       | {k=KColon}::({k=KBrace}::_ as p) -> p
       | _ -> make_infix tok.token t.path)

  (* Some commom preprocessor directives *)
  | UIDENT ("INCLUDE"|"IFDEF"|"THEN"|"ELSE"|"ENDIF"
           |"TEST"|"TEST_UNIT"|"TEST_MODULE" as s)
    when starts_line ->
      if String.sub s 0 4 = "TEST" then
        append KLet L ~pad:(2 * config.i_base) (unwind_top t.path)
      else
        replace KNone L (unwind_top t.path)

  | EXTERNAL ->
      append KExternal L (unwind_top t.path)

  | DOT ->
      (match t.path with
       | {k=KExpr i} :: ({k=KBrace} as h :: p)
         when i = prio_max ->
           (* special case: distributive { Module. field; field } *)
           { h with pad = config.i_base } :: p
       | _ -> make_infix tok.token t.path)

  | AMPERAMPER | BARBAR ->
      (* back-indented when after if or when *)
      let op_prio, _align, _indent = op_prio_align_indent tok.token in
      (match unwind_while (fun k -> prio k >= op_prio) t.path with
       | Some ({k=KExpr _}::{k=KWhen|KIf}::_ as p) ->
           extend (KExpr op_prio) T ~pad:(-3) p
       | _ -> make_infix tok.token t.path)

  | LESS ->
      if is_inside_type t.path then
        (* object type *)
        open_paren KBrace t.path
      else
        make_infix tok.token t.path

  | GREATER ->
      if is_inside_type t.path then
        match unwind (function
            | KParen | KBegin | KBracket | KBrace | KBracketBar
            | KBody(KType|KExternal) | KColon -> true
            | _ -> false)
            t.path
        with
        | {k=KBrace}::_ as p ->
            close (fun _ -> true) p
        | _ -> append expr_apply L (fold_expr t.path)
      else
        make_infix tok.token t.path

  | LESSMINUS | COMMA | OR
  | AMPERSAND | INFIXOP0 _ | INFIXOP1 _
  | COLONCOLON | INFIXOP2 _ | PLUSDOT | PLUS | MINUSDOT | MINUS
  | INFIXOP3 _ | STAR | INFIXOP4 _
  | SHARP | AS | COLONGREATER
  | OF ->
      make_infix tok.token t.path

  | LABEL _ | OPTLABEL _ ->
      (match
        unwind_while (function
          | KExpr _ | KLet | KLetIn | KFun | KAnd(KLet|KLetIn) -> true
          | _ -> false)
          t.path
      with
      | Some ({k=KExpr _}::_) | None ->
          (* considered as infix, but forcing function application *)
          make_infix tok.token (fold_expr t.path)
      | _ -> (* in function definition *)
          atom t.path)

  | UIDENT _ ->
      (match t.path with
       | {k=KBody KType}::_ when starts_line ->
           (* type =\nA\n| B : append a virtual bar before A for alignment *)
           let path = append (KBar KType) L ~pad:2 t.path
           in atom path
       | _ -> atom t.path)

  | INT64 _ | INT32 _ | INT _ | LIDENT _
  | FLOAT _ | CHAR _ | STRING _ | EOF_IN_STRING _
  | TRUE | FALSE | NATIVEINT _
  | UNDERSCORE | TILDE | QUESTION
  | QUOTE | QUOTATION | EOF_IN_QUOTATION _ ->
      atom t.path

  | PREFIXOP _ | BANG | QUESTIONQUESTION ->
      (* FIXME: should be highest priority, > atom
         ( append is not right for atoms ) *)
      atom t.path

  | ASSERT | LAZY | NEW | MUTABLE ->
      append expr_apply L (fold_expr t.path)

  | INHERIT -> append KLet L t.path

  | COMMENT _ | EOF_IN_COMMENT _ ->
      (if not starts_line then append KNone L ~pad:0 t0.path
       else match t.path with
         | {k=KExpr i}::_ when i = prio_max ->
             (* after a closed expr: look-ahead *)
             (match next_token stream with
              | Some ( TYPE | VAL | MODULE | LET | EXCEPTION
                     | CLASS | OPEN | INCLUDE | EXTERNAL | AND
                     | INHERIT | METHOD | EOF)
              | None ->
                  (* top-level comment, _unless_ it is directly after a
                     case in a sum-type *)
                  if tok.newlines <= 1
                  && match t0.path with
                     | {k=KNone}::_ -> false
                     | _ ->
                         match unwind
                             (function KBar _ | KBody KType -> true
                                     | _ -> false)
                             t.path
                         with {k=KBar _}::_ -> true
                            | _ -> false
                  then
                    append KNone (A (Path.l t.path)) ~pad:0 t.path
                  else
                    let p = unwind_top t.path in
                    append KNone (A (Path.l p + Path.pad p)) ~pad:0 t.path
              | _ ->
                  append KNone (A (Path.l t.path)) ~pad:0 t.path)
         | _ ->
             append KNone (A (Path.l t.path + Path.pad t.path)) ~pad:0 t.path)

  |VIRTUAL
  |REC
  |PRIVATE|EOF
  |DOTDOT
  |BACKQUOTE|ILLEGAL_CHAR _ ->
      (* indent the token, but otherwise ignored *)
      append KNone L t.path

  | LINE_DIRECTIVE ->
      append KNone (A 0) ~pad:0 t.path

let update config block stream t =
  let path = update_path config block stream t in
  let last = match t.token with
    | COMMENT _ -> block.last
    | _         -> Some t in
  let toff =
    if t.newlines > 0 then
      Path.l path
    else
      block.toff + t.offset in
  let orig = Region.start_column t.region in
  { path; last; toff; orig }

let indent t = Path.l t.path

let original_column t =
  t.orig

let offset t = t.toff

let set_column t col =
  { t with
    path = Path.maptop (fun n -> {n with l = col}) t.path;
    toff = col }

let reverse t =
  let col = t.orig in
  if col = t.toff then t
  else match t.last with
    | Some tok when tok.newlines > 0 ->
        let diff = col - t.toff in
        let path = match t.path with
          | n1::n2::p ->
              { n1 with l = col; t = col }
              :: { n2 with pad = n2.pad + diff }
              :: p
          | n::[] -> { n with l = col; t = col } :: []
          | [] -> []
        in
        { t with path; toff = col }
    | _ -> { t with toff = col }

let guess_indent line t =
  match t with
  | { path = {k=KExpr i}::p; last = Some tok }
    when i = prio_max &&
         line > Region.end_line tok.region + 1
    ->
      (* closed expr and newline: we probably want a toplevel block *)
      let p = unwind_top p in
      Path.l p + Path.pad p
  | { path } ->
      (* we probably want to write a child of the current node *)
      match path with
      | {l;pad}::_ -> l + pad
      | [] -> 0