-
Notifications
You must be signed in to change notification settings - Fork 1
/
futhark-indent.el
640 lines (558 loc) · 23.4 KB
/
futhark-indent.el
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
;;; futhark-indent.el --- automatic indentation for futhark-mode -*- lexical-binding: t; -*-
;; Copyright (C) DIKU 2013-2019, University of Copenhagen
;; This file is not part of GNU Emacs.
;;; License:
;; ICS <https://github.com/diku-dk/futhark-mode/blob/master/LICENSE>
;;; Commentary:
;; See futhark-mode.el.
;;; Code:
(require 'smie) ; built-in
(require 'cl-lib)
(defconst futhark-indent-level 2
"The basic indent level for `futhark-mode'.")
;;; Lexer:
(defun futhark-indent-symbol (word)
"Add blanks around WORD."
(concat "\\<" word "\\>"))
(defun futhark-indent-looking-back-at (word)
"Do the same as `looking-at', but move one token back before checking for WORD."
(save-excursion
(futhark-indent-backward-token-base)
(looking-at word)))
(defun futhark-indent-is-empty-line ()
"Check if the line of the current point is empty.
It is considered empty if the line consists of zero or more
whitespace characters."
(save-excursion
(forward-line 0)
(or (looking-at "[[:space:]]*\n")
(looking-at "[[:space:]]*$"))))
(defun futhark-indent-max (&rest args)
"Like `max', but also accepts nil values in ARGS."
(let ((args-nonnil (cl-remove-if-not 'identity args)))
(if args-nonnil
(apply 'max args-nonnil)
nil)))
(defun futhark-indent-column-of (p)
"Get the column of point P."
(when p
(save-excursion
(goto-char p)
(current-column))))
(defmacro futhark-indent-try (func)
"Try to use FUNC, but go back to the point in START on nil return."
`(or (,func) (progn (goto-char start) nil)))
(defun futhark-indent-forward-token-base ()
"Find the next Futhark token, if any."
(forward-comment (point-max))
(buffer-substring-no-properties
(point)
(progn (or (/= 0 (skip-syntax-forward "w_")) ; variables, keywords
(skip-syntax-forward ".")) ; operators, keywords
(point))))
(defun futhark-indent-backward-token-base ()
"Find the previous Futhark token, if any."
(forward-comment (- (point)))
(buffer-substring-no-properties
(point)
(progn (or (/= 0 (skip-syntax-backward "w_"))
(skip-syntax-backward "."))
(point))))
;; Lexer extension: Support 'let' chains with the 'in's left out. Operator
;; precedence grammars are quite limited, but we still want to be able to
;; express these very typical cases properly. It is easy to write a grammar
;; rule for function bodies like
;;
;; let x = 0 in
;; let y = 1 in
;; ...
;;
;; but it is impossible for function bodies like
;;
;; let x = 0
;; let y = 0
;; ...
;;
;; where the intermediate 'in's are implicit. We solve this by using the empty
;; space just prior to 'let' as the 'in-implicit' token. There will always be
;; at least `futhark-indent-level' empty spaces, since this only needs to
;; work on non-top-level 'let's.
(defun futhark-indent-forward-token-in-implicit ()
"Find the next token."
(when (looking-at " let") ; currently on the 'in-implicit' token.
;; Normalise the point position.
(futhark-indent-backward-token-base)
(futhark-indent-forward-token-base))
(if (not (or (futhark-indent-looking-back-at "=")
(futhark-indent-looking-back-at "->")
(futhark-indent-looking-back-at (futhark-indent-symbol "in"))
(futhark-indent-looking-back-at (futhark-indent-symbol "then"))
(futhark-indent-looking-back-at (futhark-indent-symbol "else"))
(futhark-indent-looking-back-at (futhark-indent-symbol "do"))
(futhark-indent-looking-back-at (futhark-indent-symbol "unsafe"))
(save-excursion
(forward-line 0)
(looking-at "[^{\n]*{[[:space:]]*$"))
(futhark-indent-is-empty-line)
(looking-at " ")))
(unless (looking-at (futhark-indent-symbol "let"))
(let ((found (futhark-indent-forward-token-base)))
(and (equal found "let")
(progn (goto-char (- (point) 4))
t)
(looking-at " ")
"in-implicit")))))
(defun futhark-indent-backward-token-in-implicit ()
"Find the previous token."
(when (looking-at " let")
(futhark-indent-forward-token-base)
(futhark-indent-backward-token-base))
(if (looking-at (futhark-indent-symbol "let"))
(let ((let-point (point))
(found (futhark-indent-backward-token-base)))
(and (not (or (equal found "=")
(equal found "->")
(equal found "in")
(equal found "then")
(equal found "else")
(equal found "do")
(equal found "unsafe")
(save-excursion
(forward-line 0)
(looking-at "[^{\n]*{[[:space:]]*$"))
(futhark-indent-is-empty-line)))
(progn (goto-char (- let-point 2))
t)
(looking-at " ")
"in-implicit"))))
(defun futhark-indent-forward-token ()
"Find the next Futhark token, if any."
(let ((start (point)))
(or (futhark-indent-try futhark-indent-forward-token-in-implicit)
(futhark-indent-forward-token-base))))
(defun futhark-indent-backward-token ()
"Find the previous Futhark token, if any."
(let ((start (point)))
(or (futhark-indent-try futhark-indent-backward-token-in-implicit)
(futhark-indent-backward-token-base))))
(defmacro futhark-indent-first-token (func-token func-sexp)
"Go to the first token through FUNC-TOKEN and FUNC-SEXP.
Return its point."
`(save-excursion
(let ((cur (point))
(found nil))
(while (and cur (not found))
(let ((found-cur (,func-token)))
(cond ((equal found-cur token)
(setq found t))
((equal found-cur "")
(ignore-errors (,func-sexp 1) t))))
(setq cur (if (= (point) cur) nil (point))))
(when found (point)))))
(defun futhark-indent-first-backward-token (token)
"Find the first token TOKEN before the current position, if it exists.
Return its point."
(futhark-indent-first-token futhark-indent-backward-token-base backward-sexp))
(defun futhark-indent-first-forward-token (token)
"Find the first token TOKEN after the current position, if it exists.
Return its point."
(futhark-indent-first-token futhark-indent-forward-token-base forward-sexp))
(defun futhark-indent-first-backward-token-local (token)
"Find the first TOKEN before the current position, or 'local'.
If the token just prior to the found token is 'local', return the
position of that instead."
(let ((pos (futhark-indent-first-backward-token token)))
(when pos
(save-excursion
(goto-char pos)
(if (equal (futhark-indent-backward-token) "local")
(point)
pos)))))
(defvar-local futhark-indent-state-current-outer-module nil
"Contains the current indentation needed for top-level elements.
Is only used when indenting a region, and is always nil
otherwise (to avoid using a state that has been invalidated by a
change in the program).")
(defun futhark-indent-state-current-outer-start ()
"Start the state keeping."
(let ((outer (futhark-indent-find-outer-module-1)))
(setq-local futhark-indent-state-current-outer-module
(or outer -2))))
(defun futhark-indent-state-current-outer-stop ()
"Stop the state keeping."
(setq-local futhark-indent-state-current-outer-module nil))
(defun futhark-indent-state-current-outer-enters ()
"Do we enter a module-like structure?"
(looking-at "[^{\n]*{"))
(defun futhark-indent-state-current-outer-exits ()
"Do we exit a module-like structure?"
(looking-at "[^}\n]*}"))
(defun futhark-indent-state-current-outer-update ()
"Update the state based on the current line."
(when futhark-indent-state-current-outer-module
(cond ((and (futhark-indent-state-current-outer-enters)
(futhark-indent-state-current-outer-exits))
t) ; ignore, since both { and } occur on the line
((futhark-indent-state-current-outer-enters)
(setq-local futhark-indent-state-current-outer-module
(+ futhark-indent-state-current-outer-module
futhark-indent-level)))
((futhark-indent-state-current-outer-exits)
(setq-local futhark-indent-state-current-outer-module
(- futhark-indent-state-current-outer-module
futhark-indent-level))))))
(defun futhark-indent-find-outer-module ()
"Try to find the 'module' or 'open' enclosing the current code block.
Uses the `futhark-indent-state-current-outer-module' state as a
lookup when indenting a region."
(if futhark-indent-state-current-outer-module
(if (< futhark-indent-state-current-outer-module 0) nil
futhark-indent-state-current-outer-module)
(futhark-indent-find-outer-module-1)))
(defmacro with-basic-forward-sexp (code)
"Run CODE with the default `forward-sexp' implementation.
Assumes CODE does not error."
`(let ((cur-forward-sexp forward-sexp-function))
(setq-local forward-sexp-function nil)
,code
(setq-local forward-sexp-function cur-forward-sexp)))
(defun futhark-indent-find-outer-module-1 ()
"The actual code."
(save-excursion
(with-basic-forward-sexp (ignore-errors (backward-up-list 1) t))
(when (or (looking-at "{") (looking-at "("))
(futhark-indent-max
(futhark-indent-column-of (futhark-indent-first-backward-token-local "module"))
(futhark-indent-column-of (futhark-indent-first-backward-token-local "open"))
;; We need to go two levels up in case of functors like
;;
;; module foo = bar({ ... })
(and
(equal (futhark-indent-backward-token-base) "")
(with-basic-forward-sexp (ignore-errors (backward-up-list 1) t))
(futhark-indent-max
(futhark-indent-column-of (futhark-indent-first-backward-token-local "module"))
(futhark-indent-column-of (futhark-indent-first-backward-token-local "open"))))))))
;;; Grammar for the SMIE parser:
(defconst futhark-indent-grammar
(smie-prec2->grammar
(smie-merge-prec2s
;; The main grammar.
(smie-bnf->prec2
'(
(id)
(attr ("#[" exp "]"))
(types (type)
(type "," type))
(type (id)
("(" types ")")
("{" params "}")
(type "|" type))
(param (id)
(id ":" type))
(params (param)
(params "," params))
(pat (param)
("(" params ")"))
(pats)
(match-case (exp "->" exp))
(match-cases (match-case)
(match-case "case" match-case))
(exps (exp)
(exp "," exp))
(record-assignment (id "=" exp))
(record-assignments (record-assignment)
(record-assignment "," record-assignment))
(exp (id)
(attr)
("[" exps "]")
("{" record-assignments "}")
("unsafe" exp)
("\\" pats "->" exp)
("let" pat "=" exp "in" exp)
;; SMIE gets less confused if we leave out the final 'exp'
;; non-terminal after the 'in-implicit' token (probably because we
;; use empty space as a token). This means that the body expression
;; of a function gets parsed into a *series of* expressions, but
;; there is still enough structure to properly indent -- extra
;; bindings in a let chain don't change the overall picture.
("let" pat "=" exp "in-implicit")
("if" exp "then" exp "else" exp)
("loop" pat "for" exp "do" exp)
("loop" pat "=" exp "for" exp "do" exp)
("loop" pat "while" exp "do" exp)
("loop" pat "=" exp "while" exp "do" exp)
("match" exp "case" match-cases)
("with") ; this is good enough
)
;; We describe the declarations in terms of separators, not
;; openers/closers. SMIE's operator precedence grammar engine gets less
;; confused this way.
(decls (decls "entry" decls)
(decls "def" decls)
(decls "type" decls)
(decls "val" decls)
(decls "include" decls)
(decls "import" decls)
(decls "module" decls)
(decls "open" decls)
(decls "local" decls)))
;; Resolve conflicts (poorly): If more than one relation exists between two
;; tokens (i.e., a shift/reduce conflict), just collapse the relations into
;; a single '=' relation (i.e., shift).
'((assoc "entry" "def" "type" "val" "include"
"import" "module" "open" "local"))
'((assoc "," "|" "case" "->"))
)
;; Basic operator precedences.
(smie-precs->prec2
'((nonassoc "->")
(assoc "|>")
(assoc "<|")
(assoc "||")
(assoc "&&")
(assoc "<=" ">=" ">" "<" "==" "!=")
(assoc "&" "^" "|")
(assoc "<<" ">>")
(assoc "+" "-")
(assoc "*" "/" "%" "//" "%%")
(assoc "**")))
))
"The simplified Futhark grammar.")
;;; Extra indentation rules to supplement the grammar-generated ones:
(defun futhark-indent-rules (kind token)
"The SMIE rules for indentation.
See SMIE documentation for info on KIND and TOKEN."
;; Uncomment this for convenient debugging. Note that SMIE will
;; call this function several times as it tries to hazily figure out
;; what is going on, so keep your *Messages* buffer handy.
;;
;; (message "%S" (cons kind token))
(pcase (cons kind token)
(`(:elem . basic) futhark-indent-level)
(`(:elem . args) 0)
(`(:after . "in")
(smie-rule-parent))
;; Indent the following line one level. This is a bit hacky because of our
;; declarations-as-separators grammar rules.
(`(:after . "=")
(unless (smie-rule-parent-p "loop")
(let ((base (futhark-indent-max
(futhark-indent-first-backward-token "let")
(futhark-indent-first-backward-token "def")
(futhark-indent-first-backward-token "entry")
(futhark-indent-first-backward-token "type"))))
(when base
;; In the case of 'local let ...' lines, indent relative to 'local',
;; not 'let'.
(let* ((base-local
(save-excursion
(goto-char base)
(when (equal (futhark-indent-backward-token) "local") (point))))
(base (or base-local base)))
`(column . ,(+ (futhark-indent-column-of base) futhark-indent-level)))))))
(`(:before . "in-implicit")
(save-excursion
(ignore-errors (backward-sexp 1) t)
(when (looking-at (futhark-indent-symbol "let"))
`(column . ,(current-column)))))
(`(:before . ,(or "def" "entry" "type" "val"
"include" "import" "module" "open" "local"))
(when (smie-rule-bolp)
(let ((outer (futhark-indent-find-outer-module)))
`(column . ,(if outer (+ outer futhark-indent-level) 0)))))
(`(:after . ,(or "then" "else" "do"))
(when (smie-rule-next-p "let")
;; waste a little less indentation in these special cases
(smie-rule-parent)))
(`(:after . "unsafe") ; indent next token directly under 'unsafe'
`(column . ,(current-column)))
(`(:before . ",")
(when (smie-rule-bolp)
(smie-rule-parent)))
(`(:after . "]") ; attributes
(save-excursion
(ignore-errors (forward-char))
(ignore-errors (backward-sexp))
(ignore-errors (backward-char))
(when (looking-at "#")
`(column . ,(current-column)))))
(`(:after . ":") ; functors
(smie-rule-parent futhark-indent-level))
;; Handle long 'val' declarations by disabling auto-indentation.
(`(:before . "->")
(when (smie-rule-bolp)
(let ((valp (futhark-indent-first-backward-token "val")))
(when (and valp
(> valp (or (futhark-indent-first-backward-token "\\") 0))
(> valp (or (futhark-indent-first-backward-token "case") 0)))
`(column . (current-column))))))
(`(:after . "->")
(cond ((smie-rule-parent-p "\\") ; lambdas
futhark-indent-level)
((save-excursion ; case expressions
(futhark-indent-backward-token)
(equal (futhark-indent-backward-token) "case"))
(save-excursion
(futhark-indent-backward-token)
(futhark-indent-backward-token)
`(column . ,(+ (current-column) futhark-indent-level))))))
(`(:before . "with")
(and
(smie-rule-bolp)
(let ((prevp (futhark-indent-first-backward-token "with")))
(and prevp `(column . ,(futhark-indent-column-of prevp))))))
(`(:before . "if")
(and
(smie-rule-bolp)
(smie-rule-parent-p "if")
(smie-rule-parent)))
(`(:before . ,(or "then" "else")) ; indent relative to 'else if' chains
(save-excursion
(and
(smie-rule-bolp)
(progn (futhark-indent-forward-token)
(ignore-errors (backward-sexp 1) t) t)
(looking-at (futhark-indent-symbol "if"))
(equal (futhark-indent-backward-token) "else")
-5))) ; length of 'else ' (relative un-indent)
(`(:before . "|") ; in type constructor definitions
(let ((p (and (smie-rule-bolp)
(progn (futhark-indent-forward-token)
(looking-at " *#"))
(futhark-indent-first-backward-token "="))))
(when p `(column . ,(futhark-indent-column-of p)))))
(`(:before . "case")
`(column . ,(futhark-indent-column-of
(futhark-indent-max (futhark-indent-first-backward-token "match")
(futhark-indent-first-backward-token "case")))))))
(defun futhark-compute-indentation ()
"Compute indentation for current line based on ad-hoc rules.
Returns NIL if no indentation can be computed."
(save-excursion
(forward-line 0)
(skip-chars-forward " \t")
(let* ((cur-col (current-column)))
(cond
;; Align closing '}' to 'module'/'open', and not directly to the
;; matching '{' (as SMIE would seemingly have it).
((looking-at "}")
(futhark-indent-find-outer-module-1)) ; always use the
; non-state-dependent variant
;; Indent a '}'-subsequent line relative to the '}' symbol, unless it
;; is probably part of a record and not a module.
((and
(not (or (looking-at ",") (looking-at ")") (looking-at "]")))
(save-excursion
(forward-line -1)
(looking-at "[[:space:]]*}[[:space:]]*$")))
(save-excursion
(forward-line -1)
(skip-syntax-forward " \t")
(current-column)))
;; Emacs 24 (and the accompanying SMIE) subtly fail at indenting a ']'
;; directly below the matching '['.
((looking-at "]")
(save-excursion
(backward-up-list 1)
(current-column)))
;; Align to previous line if that is a comment.
((save-excursion
(forward-line -1)
(skip-syntax-forward " \t")
(looking-at comment-start))
(save-excursion
(forward-line -1)
(skip-syntax-forward " \t")
(current-column)))
;; Align comment to next non-comment line.
((looking-at comment-start)
(save-excursion
(forward-comment (count-lines (point-min) (point)))
(current-column)))
;; Work around the limitations of the 'in-implicit' token: If the user
;; has (temporarily) removed all indentation in front of a 'let'
;; token, there is no empty space for the implicit 'in' token. In
;; this edge case we force the insertion of spaces, and leave the
;; heavy lifting to SMIE.
((and (equal "let" (save-excursion
(futhark-indent-forward-token)))
(save-excursion
(forward-line 0)
(looking-at "[[:space:]]?let\\>")))
(save-excursion
(forward-line 0)
(insert " ")
nil))
;; Use a simpler default than SMIE for where to start the new line.
;; SMIE likes to assume that we want to keep adding terms to a
;; previous expression if one exists, but it is more common to want to
;; make a new binding. This only affects the default position on an
;; *empty* line, and only if that empty line has a very specific
;; context; if the programmer writes something else than a new
;; binding, that will also be indented correctly.
((and (futhark-indent-is-empty-line)
(save-excursion
(not (equal "=" (futhark-indent-backward-token))))
(save-excursion
(forward-line -1)
(or (save-excursion
(member (futhark-indent-forward-token) '("in-implicit" "let")))
(futhark-indent-is-empty-line))))
(or
(futhark-indent-column-of (futhark-indent-first-backward-token "let"))
(let ((c (futhark-indent-column-of (futhark-indent-first-backward-token ""))))
(when c (max 0 (1- c))))))
;; Do not auto-indent multi-line function parameters.
(t
(let ((cur (point))
(function-start (futhark-indent-max
(futhark-indent-first-backward-token "def")
(futhark-indent-first-backward-token "entry"))))
(when function-start
(save-excursion
(goto-char function-start)
(let ((first-eq (futhark-indent-first-forward-token "=")))
(when (and first-eq
(< cur first-eq))
cur-col))))))))))
(defun futhark-indent-line-basic ()
"Try to indent the current line.
Handles edge cases where SMIE fails. SMIE will not re-indent
these indented lines."
(let ((indent (futhark-compute-indentation)))
(when indent
(progn (indent-line-to indent)
t))))
(defun futhark-indent-line ()
"Indent the current line."
(let ((start (point)))
(or (futhark-indent-try futhark-indent-line-basic)
(smie-indent-line))))
(defun futhark-indent-line-with-state ()
"Indent the current line, and update the state as well.
Used only for indenting regions, and only to make it go faster."
(futhark-indent-line)
(futhark-indent-state-current-outer-update))
(defun futhark-indent-region (start end)
"Indent the region from START to END.
This has the same semantics as running `futhark-indent-line'
on each line, but contains optimisations to make it run faster."
(save-excursion
(goto-char start)
(futhark-indent-state-current-outer-start)
(while (and (< (point) end) (not (eobp)))
(unless (and (bolp) (eolp))
(futhark-indent-line-with-state))
(forward-line 1))
(futhark-indent-state-current-outer-stop)))
(defun futhark-indent-setup ()
"Setup Emacs' Simple Minded Indentation Engine for Futhark."
(smie-setup futhark-indent-grammar #'futhark-indent-rules
:backward-token #'futhark-indent-backward-token
:forward-token #'futhark-indent-forward-token)
;; Use more flexible indentation functions.
(setq-local indent-line-function #'futhark-indent-line)
(setq-local indent-region-function #'futhark-indent-region))
(provide 'futhark-indent)
;;; futhark-indent.el ends here