Source

ocaml-indent / main.ml

The default branch has multiple heads

  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
open Sexplib.Conv
open Pos
open Reader

module Stack = struct
    
  type k = 
    | KExpr of int
    | KParen of int
    | KBrace of int
    | KBracket of int
    | KLet of [`Top | `Local ] * int 
    | KVal 
    | KType of int 
    | KException of int
    | KNone 
    | KStruct of int 
    | KSig of int 
    | KModule of int 
    | KOpen 
    | KBegin of int
    | KObject of int
    | KMatch of int
    | KTry of int
    | KWith of int
    | KWhile of int
    | KIf of int
    | KThen of int
    | KElse of int
    | KFor of int
    | KDo of int
    | KFunction of int
    | KFun of int
    | KCaseArrow
  with sexp

  type elt = { k : k;
               indent : int }

  let sexp_of_elt { k; indent } =
    Sexplib.Sexp.List [ sexp_of_k k;
                        sexp_of_int indent ]

  type t = elt list with sexp_of

  let rec indent last_indent  = function
    | [] -> 0
    | { indent = n } :: _ -> n
end

module State = struct
  type t = {
    bases : Stack.t;
    orig_indent : int; (* The original indent of the current line *)
    last_indent : int; (* At line head, first pass: the fixed indent of the last line
                          At line head, snd pass: the fixed indent of the current line
                          Otherwise: the fixed indent of the current line *)
    last_token : Parser.token option;
    modified : bool (* Has the source code ever modified ? *)
  } with sexp_of

  let init = { bases = []; orig_indent = 0; last_indent = 0; last_token = None; modified = false }

  let indent t = Stack.indent t.last_indent t.bases
end

open State
open Stack
open Parser

(* Check the previous token and tell the LET is toplevel or not *)
let rec is_top_let = function
  | None -> true
  | Some t ->
      match t with
      | COMMENT -> assert false (* COMMENT must be skipped *)
      | STRUCT | SEMISEMI 

      | UIDENT _|STRING _|OPTLABEL _|NATIVEINT _|LIDENT _|LABEL _|INT64 _|INT32 _
      | INT _|FLOAT _|CHAR _|WITH|VIRTUAL|VAL|UNDERSCORE|TYPE|TRUE|TILDE|SIG|SHARP
      | RPAREN|REC|RBRACKET|RBRACE|QUOTE|QUESTIONQUESTION|QUESTION|PRIVATE|OPEN
      | OF|OBJECT|NEW|MUTABLE|MODULE|METHOD|MATCH|LET|LAZY|INHERIT|INCLUDE
      | GREATERRBRACKET|GREATERRBRACE|FUNCTOR|FUNCTION|FUN|FOR|FALSE
      | EXTERNAL|EXCEPTION|EOF|END|DOTDOT|DOT|DONE|CONSTRAINT|COLONGREATER
      | COLON|CLASS|BARRBRACKET|BAR|BANG|BACKQUOTE|ASSERT|AS|AND
       -> true

      | _ -> false

let rec unwind_top bases = match bases with (* unwind the top *)
  | { k = KLet (`Top, _) } :: bs -> bs (* CR jfuruse: probably we don't need it *)
  | { k = (KStruct _ | KSig _) } :: _ -> bases
  | _ :: bs -> unwind_top bs
  | [] -> []

(* true means I found something to make the token a block *)
let rec lparen_read_ahead lnum str =
  match Tokenstr.destr str with
  | None -> false
  | Some (i, _) when Region.lnum i.Tokenstr.region <> lnum -> false
  | Some (i, str) ->
      match i.Tokenstr.token with
      | FUN -> false
      | FUNCTION -> false
      | COMMENT -> lparen_read_ahead lnum str
      | _ -> true

let rec lbrace_read_ahead lnum str =
  match Tokenstr.destr str with
  | None -> false
  | Some (i, _) when Region.lnum i.Tokenstr.region <> lnum -> false
  | Some (i, str) ->
      match i.Tokenstr.token with
      | COMMENT -> lparen_read_ahead lnum str
      | _ -> true

let lbracket_read_ahead = lbrace_read_ahead

let function_read_ahead = lbrace_read_ahead

let token state str at_the_head region (t : Parser.token) : State.t * State.t = 
  let line = Region.lnum region in
  let cols = Region.columns region in
  let indent = state.last_indent in
  let bases0 = state.bases in

  let fix cols = [{ k = KNone; indent = cols }] in

  let pre_bases, post_bases = match t with
    | SEMISEMI ->
        (* unwind the top *)
        let bases = unwind_top bases0 in
        bases, bases

    | OPEN -> 
        let bases = unwind_top bases0 in
        bases, 
        { k = KOpen; indent = cols + 2; } :: bases

    | MODULE ->
        let bases = unwind_top bases0 in
        bases, 
        { k = KModule cols; indent = cols + 2; } :: bases

    | LET when is_top_let state.last_token ->
        let bases = unwind_top bases0 in
        bases, 
        { k = KLet (`Top, cols); indent = cols + 2; } :: bases

    | LET ->
        bases0, { k = KLet (`Local, cols); indent = cols + 2; } :: bases0

    | VAL -> 
        let bases = unwind_top bases0 in
        bases, 
        { k = KVal; indent = cols + 2; } :: bases

    | EQUAL ->
        (* CR jfuruse: TODO
           - pre bases
           - for non definition equals *)
        let rec f bases = match bases with
          (* Definition equal rolls things back to its head *)
          | {k = (KLet (_,cols) | KType cols | KModule cols) } :: _ ->
              bases, bases
          (* Equal can exceed the following *)
          | { k = (KExpr _ | KNone) } :: bs -> f bs  
          (* Equal cannot exceed the other *)
          | _ :: bs -> bases0, bases0
          | [] -> [], []
        in
        f bases0
        
    | TYPE when state.last_token = Some MODULE -> (* module type *)
        (* we might change the kind to KModuleType, but ... let's keep it simpler *)
        bases0, bases0 
          
    | TYPE ->
        let bases = unwind_top bases0 in
        bases, 
        { k = KType cols; indent = cols + 2; } :: bases
          
    | EXCEPTION ->
        let bases = unwind_top bases0 in
        bases, 
        { k = KException cols; indent = cols + 2; } :: bases
        
    | AND -> 
        (* for let *)
        (* recover the last let *)
        let rec f bases = match bases with
          | {k = (KLet (_,cols) | KType cols | KModule cols) } :: _ ->
              fix cols, bases
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | IN ->
        (* in must paired with let *)
        let rec f bases = match bases with
          | { k = KLet(_, cols) } :: bs -> 
              fix cols, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | STRUCT ->
        bases0, { k = KStruct indent; indent = indent + 2; } :: bases0

    | SIG ->
        bases0, { k = KSig indent; indent = indent + 2; } :: bases0

    | BEGIN ->
        bases0, { k = KBegin indent; indent = indent + 2; } :: bases0

    | OBJECT ->
        bases0, { k = KObject indent; indent = indent + 2; } :: bases0

    | END ->
        let rec f bases = match bases with
          | { k = (KStruct cols | KSig cols | KBegin cols | KObject cols) } :: bs -> 
              fix cols, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | MATCH ->
        bases0, 
        if at_the_head then
          { k = KMatch cols; indent = cols + 2; } :: bases0
        else
          { k = KMatch (indent + 2); indent = cols + 2; } :: bases0

    | TRY ->
        bases0, 
        if at_the_head then
          { k = KTry cols; indent = cols + 2; } :: bases0
        else
          { k = KTry indent; indent = indent + 2; } :: bases0

    | WITH ->
        (* support for typeconv *)
        let rec f bases = match bases with
          | { k = KBrace cols } :: _ ->
              fix (cols + 2), bases
          | { k = (KType cols | KException cols | KMatch cols | KTry cols) } :: bs -> 
              fix cols, 
             { k = KWith cols; indent = cols + 2; } :: bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | IF -> 
        bases0, { k = KIf cols; indent = cols + 2; } :: bases0

    | THEN ->
        let rec f bases = match bases with
          | { k = KIf cols } :: bs ->
              fix cols,
              { k = KThen cols; indent = cols + 2; } :: bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | ELSE ->
        let rec f bases = match bases with
          | { k = KThen cols } :: bs ->
              fix cols,
              { k = KElse cols; indent = cols + 2; } :: bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | WHILE -> 
        bases0, { k = KWhile indent; indent = cols + 2; } :: bases0

    | DO ->
        let rec f bases = match bases with
          | { k = (KWhile cols ) } :: bs -> 
              { k = KDo cols; indent = cols; } :: bs, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | DONE ->
        let rec f bases = match bases with
          | { k = (KDo cols ) } :: bs -> 
              fix cols, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | LPAREN ->
        if lparen_read_ahead line str then
          bases0, { k = KParen cols; indent = cols + 2; } :: bases0
        else
          bases0, { k = KParen indent; indent = indent + 2; } :: bases0

    | RPAREN ->
        let rec f bases = match bases with
          | { k = (KParen cols ) } :: bs -> 
              fix cols, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | LBRACE ->
        if lbrace_read_ahead line str then
          bases0, { k = KBrace cols; indent = cols + 2; } :: bases0
        else
          bases0, { k = KBrace indent; indent = indent + 2; } :: bases0

    | RBRACE ->
        let rec f bases = match bases with
          | { k = (KBrace cols ) } :: bs -> 
              fix cols, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | LBRACKET ->
        if lbracket_read_ahead line str then
          bases0, { k = KBracket cols; indent = cols + 2; } :: bases0
        else
          bases0, { k = KBracket indent; indent = indent + 2; } :: bases0

    | RBRACKET ->
        let rec f bases = match bases with
          | { k = (KBracket cols ) } :: bs -> 
              fix cols, bs
          | [] -> [], []
          | _ :: bs -> f bs
        in
        f bases0

    | FUNCTION ->
        if function_read_ahead line str then
          bases0, 
          { k = KFunction cols; indent = cols + 10 (* function+2 *); } :: bases0 
        else
          bases0, 
          { k = KFunction indent; indent = indent + 4 (* "  | " *); } :: bases0 

    | FUN -> 
        bases0, { k = KFun indent; indent = indent + 2; } :: bases0 

    | BAR ->
        let rec f bases = match bases with
          | { k = ( KType cols 
                  | KFunction cols) } :: _ ->
              fix (cols + 2), bases
          | { k = ( KBracket cols 
                  | KWith cols
                  | KParen cols) } :: _ ->
              fix cols, bases
          | [] -> bases0, bases0 (* if overrun, keep the original *)
          | _ :: bs -> f bs
        in
        f bases0

    | MINUSGREATER ->
        let rec f bases = match bases with
          | { k = (KWith cols) } :: _ ->
              bases0, 
              { k = KCaseArrow; indent = cols + 4; } :: bases
          | { k = (KFunction cols) } :: _ ->
              bases0, 
              { k = KCaseArrow; indent = cols + 6; } :: bases
          | { k = (KFun cols) } :: _ ->
              bases0, 
              { k = KCaseArrow; indent = cols + 2; } :: bases
          | [] -> bases0, bases0 (* if overrun, keep the original *)
          | _ :: bs -> f bs
        in
        f bases0

    | COMMA ->
        let rec f bases = match bases with
          | { k = ( KBegin cols 
                  | KBracket cols 
                  | KBrace cols 
                  | KLet (_, cols) ) } :: _ ->
              fix (cols + 2), bases
          | { k = ( KParen cols ) } :: _ ->
              fix cols, bases
          (* comma cannot exceeds them (comma is stronger than them) *)
          | { k = (KThen _ | KElse _ | KWith _ | KFunction _ | KFun _ | KMatch _ | KCaseArrow ) } :: _ ->
              bases0, bases
          | [] -> bases0, bases0 (* if overrun, keep the original *)
          | _ :: bs -> f bs
        in
        f bases0

    | SEMI ->
        let rec f bases = match bases with
          | { k = (KParen cols | KBegin cols | KBracket cols | KBrace cols | KLet (_, cols)) } :: _ ->
              fix cols, bases
          | { k = (KThen cols | KElse cols) } :: bs -> 
              fix cols, bs
          | [] -> bases0, bases0 (* if overrun, keep the original *)
          | _ :: bs -> f bs
        in
        f bases0
          
    | INT64 _ | INT32 _ | INT _ | LIDENT _ | UIDENT _ | FLOAT _| CHAR _ | STRING _ | TRUE | FALSE ->
        let rec f bases = match bases with
          | { k = KExpr _ } :: _ -> bases0, bases0
          | [] -> bases0, { k = KExpr cols; indent = cols + 2; } :: bases0
          | _ :: bs -> f bs
        in
        f bases0

    | STAR | PLUSDOT | PLUS | MINUSDOT | MINUS 
    | INFIXOP4 _ | INFIXOP3 _ | INFIXOP2 _ | INFIXOP1 _ | INFIXOP0 _ 
    | LESS | GREATER | AMPERSAND | AMPERAMPER
      ->
        let rec f bases = match bases with
          | { k = KExpr cols } :: _ -> 
              { k = KNone; indent = cols } :: bases0, bases0
          | [] -> bases0, bases0
          | _ :: bs -> f bs
        in
        f bases0

    | COMMENT ->
        (* Comments are tricky. It is:
           
           - sometimes affected by the previous line's indentation
           - sometimes affected by the next line's indentation
           - sometimes independent
        *)
        fix cols, bases0
        
    |PREFIXOP _|OPTLABEL _|NATIVEINT _|LABEL _
    |WHEN|VIRTUAL|UNDERSCORE|TO|TILDE|
      SHARP|REC|QUOTE|QUESTIONQUESTION|QUESTION|
      PRIVATE|OR|OF|NEW|MUTABLE|METHOD
          |LESSMINUS|LBRACKETGREATER|LBRACKETLESS|LBRACKETBAR|
      LBRACELESS|LAZY|INITIALIZER|INHERIT|INCLUDE|GREATERRBRACKET|
      GREATERRBRACE|FUNCTOR|FOR|EXTERNAL|EOF|
      DOWNTO|DOTDOT|DOT|CONSTRAINT|COLONGREATER|COLONEQUAL|
      COLONCOLON|COLON|CLASS|BARRBRACKET|BARBAR|BANG|BACKQUOTE|ASSERT|AS
        -> bases0, bases0
  in
  { state with bases = pre_bases },
  { state with bases = post_bases }

let update_state state new_line fix_indent str orig_region t = 

  (* If it is a new line + we need to fix the indent of the line, compute the line's indentation. 
     Otherwise, we use the original state.
  *)
  let state' =
    if fix_indent && new_line then
      let pre, _ = token state str new_line orig_region t in
      { pre with last_indent = State.indent pre }
    else
      state
  in

  (* Fix the indentation. It may be updated by the previous call of [token]. *)
  let fixed_region = 
    (* CR jfuruse: Spaghetti... *)
    if fix_indent then Region.move_chars (state'.last_indent - state.orig_indent) orig_region else orig_region
  in
  let state = { state 
                with 
                  last_indent = state'.last_indent
                  ; modified = state'.modified || orig_region <> fixed_region 
              } 
  in

  (* Rerun [token] *)
  token state str new_line fixed_region t

let parse_args () = 
  let rev_paths = ref [] in
  let debug = ref false in
  let lines = ref None in
  Arg.parse [
    ("-debug", Arg.Set debug, "debugging");
    ("-lines", Arg.String (fun s ->
      try 
        let pos = String.index s '-' in
        let (start,end_) = (int_of_string (String.sub s 0 pos),
                            int_of_string (String.sub s (pos+1) (String.length s - pos - 1))) in
        if start <= 0 || end_ <= 0 || start > end_ then
          failwith (Printf.sprintf "Wrong -lines specification: %s" s);
        lines := Some (start, end_)
      with
      | _ -> failwith (Printf.sprintf "Wrong -lines specification: %s" s)),
     "lines, ex. 10-12") 
  ] (fun s -> rev_paths := s :: !rev_paths) "indent paths";
  let paths = List.rev !rev_paths in
  let paths = if paths = [] then [""] else paths in (* CR jfuruse: ugly *)
  let debug = !debug in
  let lines = !lines in
  begin match paths, lines with
  | [], _ -> assert false
  | [_], _ -> ()
  | _, Some _ -> failwith "Region can be specified with at most one file" 
  | _ -> ()
  end;
  paths, debug, lines

let paths, debug, lines = parse_args ()

module Printer = struct

  type t = (int * int) option
      
  let add_string ?(no_exit=false) t lnum s =
    let add_line t lnum s =
      match t with
      | None -> print_string s
      | Some (start, end_) ->
          if lnum < start then ()
          else if lnum > end_ then if no_exit then () else raise Exit
          else print_string s
    in
    let get_line s =
      try 
        let pos = String.index s '\n' in
        String.sub s 0 (pos + 1), 
        Some (String.sub s (pos + 1) (String.length s - pos - 1))
      with
      | Not_found -> s, None
    in
    let rec iter lnum s = 
      let line, rest =  get_line s in
      add_line t lnum line;
      match rest with
      | Some s -> iter (lnum+1) s
      | None -> ()
    in
    iter lnum s
  ;;
    
end 

let _ = 
  let printer = lines in
    
  List.iter (fun path ->
    let str = if path = "" then Tokenstr.of_channel stdin else Tokenstr.of_path path in

    let rec loop last_orig_region state str = match Tokenstr.destr str with
      | None -> ()

      | Some (({Tokenstr.token = EOF} as i), _) ->
          let space_between = i.Tokenstr.space in
          Printer.add_string printer (Region.lnum last_orig_region) space_between
            
      | Some (i, str) ->
          let t = i.Tokenstr.token in
          let orig_region = i.Tokenstr.region in
          let space_between = i.Tokenstr.space in
          let substr = i.Tokenstr.substr in

          (*
            Format.eprintf "<%s %d>@."
            (Sexplib.Sexp.to_string_mach (Parser.sexp_of_token t))
            (Region.columns orig_region);
          *)

          let last_line = Region.lnum last_orig_region in
          let current_line = Region.lnum orig_region in
          let new_line = last_line <>  current_line in

          let state = 
            if new_line then { state with orig_indent = Region.columns orig_region } else state
          in
          
          let fix_indent = 
            match lines with
            | Some (start, _) -> start <= Region.lnum orig_region
            | _ -> true
          in

          let pre, post = update_state state new_line fix_indent str orig_region t in
          
          (* printing *)
          
          if new_line then begin
            (* the line 1 has no previous new line char *)
            let spaces = try String.sub space_between 0 (String.rindex space_between '\n' + 1) with _ -> "" in 
            Printer.add_string printer last_line spaces;
            
            let indent_string = String.make (State.indent pre) ' ' in
            if debug then begin
              Printer.add_string printer current_line indent_string;
              if pre == post then 
                Printer.add_string ~no_exit:true printer current_line 
                  (Printf.sprintf "-- %s\n" (Sexplib.Sexp.to_string_mach (Stack.sexp_of_t pre.bases)))
              else
                Printer.add_string ~no_exit:true printer current_line 
                  (Printf.sprintf "-- %s // %s\n" 
                     (Sexplib.Sexp.to_string_mach (Stack.sexp_of_t pre.bases))
                     (Sexplib.Sexp.to_string_mach (Stack.sexp_of_t post.bases)))
            end;
            
            Printer.add_string printer current_line indent_string;
            Printer.add_string printer current_line substr
          end else begin
            Printer.add_string printer current_line space_between;
            Printer.add_string printer current_line substr;
          end;
          
          (* Now move to the next token *)
          
          let post = 
            if new_line then 
              { post with 
                last_token = (if t <> COMMENT then Some t else state.last_token)
              ; last_indent = State.indent pre 
              }
            else 
              { post with 
                last_token = (if t <> COMMENT then Some t else state.last_token)
              }
                
          in
          
          loop orig_region post str
    in
    try
      loop Region.zero State.init str;
      raise Exit
    with
    | Exit -> Tokenstr.close str
  ) paths