Source

ocaml-indent / machine.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
open Sexplib.Conv
open Pos

module Parser = Xparser

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

  (* CR jfuruse: strange *)
  let indent _last_indent  = function
    | [] -> 0
    | { indent = n } :: _ -> n
end

module State = struct
  type t = {
    modified : bool;   (* Has the source code ever modified ? *)
    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;
    bases : Stack.t;
  } 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

  let print t = print_endline (Sexplib.Sexp.to_string_mach (sexp_of_t t))
end

open State
open Stack
open Parser

(* Check the previous token and tell the LET is toplevel or not *)
let 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
      | COMMENT _ -> lparen_read_ahead lnum str
      | FUN -> false
      | FUNCTION -> false
      | _ -> true

let 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 =

  (** Which line the token is in *)
  let line = Region.lnum region in

  (** Which column the token is at *)
  let cols = Region.columns region in

  (** The indent of the current line.
      If the token is at the head of the line, it may be the original indent
  *)
  let indent = state.last_indent in

  (** The original indent stack. You must update this. *)
  let bases0 = state.bases in

  (** Just change the indentation to [cols]. Useful at the line heads *)
  let fix cols = [{ k = KNone; indent = cols }] in

  (* A basic rule.

     An effect of a token cannot exceed a token whose connectivity power is stronger.

     CR jfuruse: I could encode this information into Stack.k's ordering.
  *)

  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

    | VAL ->
        let bases = unwind_top bases0 in
        bases,
        { k = KVal; 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

    | 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, type, module *)
        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
          (* bit special handling *)
          let rec compute bases = match bases with
            | [] -> indent
            | { k = KLet (_, cols) } :: _ -> max (cols + 2) indent
            | _ :: bs -> compute bs
          in
          { k = KMatch (compute bases0); 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) } :: _ ->
              fix (cols + 2),
              { k = KCaseArrow; indent = cols + 4; } :: bases
          | { k = (KFunction cols) } :: _ ->
              fix (cols + 2),
              { k = KCaseArrow; indent = cols + 6; } :: bases
          | { k = (KFun cols) } :: _ ->
              fix (cols + 2),
              { 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 _ | KTry _ | 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)) | KTry cols | KMatch cols | KFun cols | KFunction cols } :: _ ->
              fix cols, bases
          | { k = KCaseArrow } :: _ -> bases, 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 ~at_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 && at_new_line then
      let pre, _ = token state str at_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 at_new_line fixed_region t
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.