-
Notifications
You must be signed in to change notification settings - Fork 0
/
fstar-extended-mode.el
2679 lines (2507 loc) · 114 KB
/
fstar-extended-mode.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
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
;;
;; Custom commands and bindings for the F* mode
;;
;; TODO: many manipulations in the below functions can be simplified by using:
;; - save-current-buffer, with-current-buffer (to switch buffer), with-temp-buffer
;; TODO: make the naming conventions coherent:
;; - capital letters for function parameters
;; - use $ for local variables
;; - 'fem-' prefix for all functions
;; I encountered some problems with undo (for instance, insert-assert-pre-post
;; works properly when executed as a command, but undo performs weird things
;; if it is linked to a key binding). Some very good explanations are provided
;; in the link below:
;; https://stackoverflow.com/questions/15097012/how-to-prevent-emacs-from-setting-an-undo-boundary
;; My current fix is to use temporary buffers which names start with a space.
;; Note that for now I don't want to use functions like to-switch-buffer because
;; I want to keep a trace of the data processing for debugging
;;; Code:
;;; Imports
(use-package fstar-mode :demand)
;;; Customization
;;; Constants
(defconst fem-log-buffer "*fstar-extended-debug*")
(defconst fem-message-prefix "[F*] ")
(defconst fem-tactic-message-prefix "[F*] TAC>> ")
(defconst fem-start-fstar-msg "\n%FEM:FSTAR_META:START%")
(defconst fem-end-fstar-msg "\n[F*] %FEM:FSTAR_META:END%")
(defconst fem-messages-buffer "*Messages*")
;; Small trick to solve the undo problems: we use temporary buffer names which
;; start with a ' ' so that emacs deactivates undo by default in those buffers,
;; preventing the insertion of problematic undo-boundary.
;; Note that for now we switch buffers "by hand" rather than using the emacs
;; macros like with-current-buffer because it leaves a trace which helps debugging.
(defconst fem-process-buffer1 " *fstar-temp-buffer1*")
(defconst fem-process-buffer2 " *fstar-temp-buffer2*")
(defconst fem-pos-marker "(*[_#%s#_]*) ")
(defvar fem-pos-marker-overlay nil)
(defvar fem-saved-pos nil)
;;; Type definitions
(cl-defstruct fem-pair
fst snd)
(cl-defstruct fem-triple
fst snd thd)
(cl-defstruct fem-subexpr
"A parsed expression of the form 'let _ = _ in', '_;' or '_' (return value)"
beg end ;; point delimiters
is-let-in ;; is of the form: 'let _ = _ in'
has-semicol ;; is of the form: '_;'
)
(cl-defstruct fem-result
"Results exported by F* to the *Messages* buffer"
error pres posts)
;;; Debugging and errors
(define-error 'fstar-meta-parsing "Error while parsing F*")
(defvar fem-debug nil "If t debug mode is activated")
(defun fem-switch-debug ()
(interactive)
"Switch between debugging/non-debugging mode."
(setq fem-debug (not fem-debug)))
(defun fem-log-msg (FORMAT-STRING &rest FORMAT-PARAMS)
"Log a message in the log buffer.
Format FORMAT-PARAMS according to FORMAT-STRING."
(apply #'message FORMAT-STRING FORMAT-PARAMS))
(defun fem-log-dbg (FORMAT-STRING &rest FORMAT-PARAMS)
"Log a message in the log buffer if fem-debug is t.
Format FORMAT-PARAMS according to FORMAT-STRING."
(when fem-debug (apply #'message FORMAT-STRING FORMAT-PARAMS)))
;;; Utilities
(defun fem-replace-in-string (FROM TO STR)
"Replace FROM with TO in string STR."
(replace-regexp-in-string (regexp-quote FROM) TO STR nil 'literal))
(defun fem-back-to-indentation-or-beginning ()
"Switch between beginning of line or end of indentation."
(interactive)
(if (= (point) (progn (back-to-indentation) (point)))
(beginning-of-line)))
(defun fem-current-line-is-whitespaces ()
"Check if the current line is only made of spaces."
(save-excursion
(beginning-of-line)
(looking-at-p "[ ]*$")))
(defun fem-current-line-is-comments-and-spaces ()
"Check if the current line is only made of comments and spaces."
(save-excursion
(beginning-of-line)
(fem-skip-comments-and-spaces t (point-at-eol))
(= (point) (point-at-eol))))
(defun fem-count-lines-in-string (STR)
"Count the number of lines in a string"
(save-match-data
(let (($num-lines 1) (pos 0))
(while (string-match (regexp-quote "\n") STR pos)
(setq pos (match-end 0))
(setq $num-lines (+ $num-lines 1)))
$num-lines)))
(defun fem-consume-string-forward (STR &optional NO_ERROR)
"If the pointer looks at string STR, moves the pointer after it. Otherwise,
returns nil or raises an error depending on NO_ERROR."
(if (looking-at-p (regexp-quote STR))
(progn (forward-char (length STR)) t)
(if NO_ERROR nil (error (format "fem-consume-string-forward %s failed" STR)))))
(defun fem-insert-newline-term (TERM)
"Insert a new line if the current one is not empty, then insert TERM."
(interactive)
(let (($indent-str nil))
(if (fem-current-line-is-whitespaces) ()
;; Create the new line
(end-of-line)
(newline)
(indent-according-to-mode))
(insert TERM)))
(defun fem-previous-char-is-semicol-p (&optional POS)
"Return t if the point before POS is ';'."
(ignore-errors
(= (char-before) ?;)))
(defun fem-next-char-is-semicol-p (&optional POS)
"Return t if the point before POS is ';'."
(ignore-errors
(= (char-after) ?;)))
(defun fem-parse-next-sexp-p (&optional POS LIMIT)
"Skip comments and spaces and parse the next sexp as a pair of positions.
Return nil if no sexp was found."
(let (($limit (or LIMIT (point-max)))
$p0)
(goto-char (or POS (point)))
(fem-skip-comments-and-spaces t $limit)
(setq $p0 (point))
;; Ignore the errors: if can't parse a sexp, return nil
(ignore-errors
(forward-sexp)
(make-fem-pair :fst $p0 :snd (point)))))
(defun fem-parse-next-sexp-as-string-p (&optional POS LIMIT)
"Skip comments and spaces and parse the next sexp as a string.
Return nil if no sexp was found."
(let ($sexp)
(setq $sexp (fem-parse-next-sexp-p POS LIMIT))
(if $sexp
(buffer-substring-no-properties (fem-pair-fst $sexp) (fem-pair-snd $sexp))
nil)))
(defun fem-parse-previous-sexp-p (&optional POS LIMIT)
"Skip comments and spaces and parse the previous sexp as a pair of positions.
Return nil if no sexp was found."
(let (($limit (or LIMIT (point-min)))
$p0)
(goto-char (or POS (point)))
(fem-skip-comments-and-spaces nil $limit)
(setq $p0 (point))
;; Ignore the errors: if can't parse a sexp, return nil
(ignore-errors
(backward-sexp)
(make-fem-pair :fst (point) :snd $p0))))
(defun fem-parse-previous-sexp-as-string-p (&optional POS LIMIT)
"Skip comments and spaces and parse the previous sexp as a string.
Return nil if no sexp was found."
(let ($sexp)
(setq $sexp (fem-parse-previous-sexp-p POS LIMIT))
(if $sexp
(buffer-substring-no-properties (fem-pair-fst $sexp) (fem-pair-snd $sexp))
nil)))
;; TODO: this can be greatly improved by using more precise parsing primitives
;; - take example on fem-parse-control-flow
(defun fem-parse-previous-letb (&optional LIMIT)
"Return a fem-pair delimiting the parsed let expression, nil otherwise.
The expression can also of the form: '...;', which is syntactic sugar for 'let _ = ... in;'"
(let (($limit (or LIMIT (point-min)))
($p0 (point))
($p (point))
($p1 nil)
($continue t)
($in-cnt 0) ;; Count the number of 'in' encountered, to handle nested let expressions
$parse-sexp
$exp)
(fem-log-dbg "[> fem-parse-previous-letb")
;; Find the end of expression delimiter
(fem-skip-comments-and-spaces nil $limit)
;; Check if previous is ';': if so, find next occurrence of ';' or 'in'
(if (fem-previous-char-is-semicol-p)
(progn
(fem-log-dbg "End delimiter is ';'")
(backward-char 1)
(while (and $continue (not (= (point) (point-min))))
(setq $p (point))
(fem-skip-comments-and-spaces nil $limit)
(if (fem-previous-char-is-semicol-p)
;; Semicol: stop here, but ignore the comments
(setq $p1 (point) $continue nil)
;; Otherwise: parse the next sexp
(setq $exp (fem-parse-previous-sexp-as-string-p))
(if (not $exp)
;; Error: abort
(setq $continue nil)
;; Check if 'in' - note that we don't have to worry about nested let here
(when (string-equal "in" $exp)
(setq $p1 $p $continue nil)))))
;; Return
(if (not $p1)
nil
(goto-char $p1)
(fem-skip-comments-and-spaces t)
(setq $p1 (point))
(if $p1 (make-fem-pair :fst $p1 :snd $p0) nil)))
;; Check if previous is 'in': if so find next occurrence of 'let'
(setq $exp (fem-parse-previous-sexp-as-string-p))
(if (and $exp (string-equal $exp "in"))
(progn
(fem-log-dbg "End delimiter is 'in'")
(while $continue
(fem-skip-comments-and-spaces nil $limit)
(setq $exp (fem-parse-previous-sexp-as-string-p))
(if (not $exp)
;; Error: abort
(setq $continue nil)
;; Check if 'let'
(fem-log-dbg (concat "Parsed [" $exp "]"))
(cond
;; If find a 'in': increment the counter
((string-equal "in" $exp)
(setq $in-cnt (+ $in-cnt 1)))
;; If find a 'let': stop if counter is 0, otherwise decrement it
((string-equal "let" $exp)
(if (= $in-cnt 0)
(setq $p1 (point) $continue nil)
(setq $in-cnt (- $in-cnt 1))))
;; Otherwise: do nothing
(t nil))))
;; Return
(if $p1 (make-fem-pair :fst $p1 :snd $p0) nil))
;; Otherwise: return nil
nil))))
(defun fem-insert-newline-term-smart-indent (TERM)
"Insert a new line if the current one is not empty, then insert TERM."
(interactive)
(let (($indent-str nil)
($p0 (point))
$p1
$letb)
;; If the current line is empty: insert in this line
(if (fem-current-line-is-whitespaces) ()
;; Go to the end of the line then move backward until we find some code
(end-of-line)
(fem-skip-comments-and-spaces nil)
(setq $p1 (point))
;; Try to parse the expression
(setq $letb (fem-parse-previous-letb))
;; If we managed to parse the expression: use the indent of the expression
(if $letb (goto-char (fem-pair-fst $letb))
;; Otherwise, use the indent of the line where we were
(goto-char $p1))
;; Compute the indent
(beginning-of-line)
(fem-skip-spaces t (point-at-eol))
(setq $indent-str (make-string (- (point) (point-at-bol)) ? ))
;; Go to the original position
(goto-char $p0)
;; Create the new line
(end-of-line)
(newline))
;; Insert
(if $indent-str (insert $indent-str) (indent-according-to-mode))
(insert TERM)))
(defun fem-newline-keep-indent ()
"Insert a newline with an indentation equal to the current column position."
(interactive)
(let ($p $i)
(setq $p (point))
(back-to-indentation)
(setq $i (- (point) (line-beginning-position)))
(goto-char $p)
(newline)
(dotimes (i $i) (insert " "))
$i))
(defun fem-empty-line ()
"Delete all the characters on the current line.
Return the number of deleted characters."
(interactive)
(let ($p)
(setq $p (- (line-end-position) (line-beginning-position)))
(delete-region (line-beginning-position) (line-end-position))
$p))
(defun fem-empty-delete-line ()
"Remove all the characters on the line if not empty, delete the line otherwise."
(interactive)
(if (equal (line-beginning-position) (line-end-position))
(progn (move-backward) (delete-char 1) 1) (fem-empty-line)))
(defun fem-delete-always-line ()
"Delete the current line."
(interactive)
(let ($c)
(if (equal (line-beginning-position) (line-end-position))
(progn (move-backward) (delete-char 1) 1)
(progn (setq $c (fem-empty-line))
(move-backward) (delete-char 1) (+ $c 1)))))
(defun fem-find-region-delimiters (ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH &optional POS)
"Find the delimiters for the region around the pointer.
Mostly works by moving forward/backward by a paragraph, remembering the positions we reached."
(save-excursion
(let ($p $p1 $p2)
;; Save the current point
(when POS (goto-char POS))
(setq $p (point))
;; Find the region delimiters (and move the pointer back to its original position):
;; First check if we need to use the selected region
(if (and (use-region-p) ALLOW_SELECTION)
;; Use the selected region
(setq $p1 (region-beginning) $p2 (region-end))
;; Compute a new region
(progn
;; - beginning of region
(progn (if ABOVE_PARAGRAPH (backward-paragraph)
(if INCLUDE_CURRENT_LINE (move-beginning-of-line ()) (move-end-of-line ())))
(setq $p1 (point)) (goto-char $p))
;; - end of region
(progn (if BELOW_PARAGRAPH (forward-paragraph)
(if INCLUDE_CURRENT_LINE (move-end-of-line ()) (move-beginning-of-line ())))
(setq $p2 (point)) (goto-char $p))))
(make-fem-pair :fst $p1 :snd $p2))))
(defun fem-apply-in-current-region (ACTION ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH)
"Apply the action given as argument to the region around the pointer.
The ACTION function should move the pointer back to its (equivalent) original position."
(let ($delimiters $p1 $p2 $r)
;; Find the region delimiters
(setq $delimiters (fem-find-region-delimiters ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH))
(setq $p1 (fem-pair-fst $delimiters) $p2 (fem-pair-snd $delimiters))
;; Apply the action in the delimited region
(save-restriction
(narrow-to-region $p1 $p2)
(setq $r (funcall ACTION)))
;; return the result of performing the action
$r))
(defun fem-apply-in-current-line (ACTION)
"Apply the ACTION given as argument to the current line.
The ACTION function should move the pointer back to its (equivalent) original position."
(fem-apply-in-current-region ACTION nil t nil nil))
(defun fem-replace-all-in (FROM TO &optional IGNORE_COMMENTS FULL_SEXP BEG END)
"Replace all the occurrences of FROM by TO.
Return the number of characters by which the pointer was shifted.
BEG and END delimit the region where to perform the replacement.
If IGNORE_COMMENTS is t, don't replace inside comments.
If FULL_SEXP, check if the term to replace is a sexpression before replacing it."
(let (($p0 (point)) ;; original position
($p (point)) ;; current position
($shift 0) ;; number of characters by which we shift the original position
($length-dif (- (length TO) (length FROM))) ;; shift of one replacement
($beg (or BEG (point-min)))
($end (or END (point-max)))
$replace
$exp)
;; Replace all the occurrences of FROM
(goto-char $beg)
(while (and (< (point) $end) (search-forward FROM $end t))
;; Check if we need to replace
(cond
;; Ignore comments
((and IGNORE_COMMENTS (fem-in-general-comment-p))
(setq $replace nil))
;; Check if full sexp
(FULL_SEXP
(goto-char (match-beginning 0))
(setq $exp (fem-sexp-at-p-as-string))
(if $exp (setq $replace (string-equal $exp FROM))
(setq $replace nil)))
(t (setq $replace t)))
(goto-char (match-end 0))
;; Replace
(when $replace
(progn
;; Compute the pointer shift: if the current position is smaller or equal
;; to the original position with the current shift, add $length-dif
;; to the shift
(setq $p (point))
(when (<= $p (+ $p0 $shift)) (setq $shift (+ $shift $length-dif)))
;; Replace
(replace-match TO))
;; Otherwise: just move
(goto-char (match-end 0))))
;; Move to the shifted position and return the shift
(goto-char (+ $p0 $shift))
$shift))
(defun fem-replace-in-current-region (FROM TO IGNORE_COMMENTS FULL_SEXP
ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH)
"Replace FROM by TO in the current region."
(let (($r (apply-partially 'fem-replace-all-in FROM TO IGNORE_COMMENTS FULL_SEXP)))
;; Apply the replace function
(fem-apply-in-current-region $r ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH)))
;;; General F* code management commands
(defun fem-switch-assert-assume-in-current-region (ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH)
(interactive)
"Switch between assertions and assumptions in the current region.
First check if there are assertions in the current region.
If so, replace them with assumptions.
Ohterwise, replace the assumptions with assumptions."
(let ($p $p1 $p2 $keep-selection $has-asserts $replace $delimiters)
;; Find the region delimiters and restrain the region
(setq $delimiters (fem-find-region-delimiters ALLOW_SELECTION INCLUDE_CURRENT_LINE
ABOVE_PARAGRAPH BELOW_PARAGRAPH))
(setq $p1 (fem-pair-fst $delimiters)
$p2 (fem-pair-snd $delimiters)
$keep-selection (and (use-region-p) ALLOW_SELECTION))
(save-restriction
(narrow-to-region $p1 $p2)
(setq $p (point))
;; Check if there are assertions to know whether to replace assertions
;; by assumptions or the revert
(goto-char (point-min))
(setq $has-asserts (fem-search-forward-not-comment "assert" t nil))
(goto-char $p)
;; Replace
(if $has-asserts
(progn
(fem-replace-all-in "assert_norm" "assume(*norm*)" t t)
(fem-replace-all-in "assert" "assume" t t))
(progn
(fem-replace-all-in "assume(*norm*)" "assert_norm" t nil)
(fem-replace-all-in "assume" "assert" t t))))
;; Maintain the selection if there was one
(when $keep-selection
(setq deactivate-mark nil)
(exchange-point-and-mark)
(exchange-point-and-mark))))
(defun fem-switch-assert-assume-p-or-selection ()
(interactive)
"Switch the assertions/assumptiosn under the pointer, or in the active selection."
(let ($p $passert $p1 $p2 $keep-selection $has-asserts $replace $delimiters)
(setq $p (point))
;; Find the region delimiters and restrain the region
(if (use-region-p)
;; Use selection
(setq $p1 (region-beginning) $p2 (region-end) $keep-selection t)
;; Otherwise: look for the assertion/assumption under the pointer
(setq $passert (fem-find-assert-assume-p))
;; If we couldn't find the assertion, try to move backward
(when (not $passert)
;; Go to the left, check if we find a semicolon
(fem-skip-comments-and-spaces nil (point-at-bol))
;; If there is a semicolon, ignore it
(when (fem-previous-char-is-semicol-p)
(backward-char))
;; Retry the search
(setq $passert (fem-find-assert-assume-p)))
;; If still not found, move forward
(when (not $passert)
(goto-char $p)
(fem-skip-comments-and-spaces t (point-at-eol))
(setq $passert (fem-find-assert-assume-p)))
;; Use the assertion if we found one, otherwise use an empty search
(if (not $passert)
;; Use an empty search
(setq $p1 (point) $p2 (point))
;; Use the region containing the assertion - note that we include the
;; assertion parameter, because if we limit ourselves to the head
;; keyword, we might not replace an "assert(*norm*)"
(setq $p1 (fem-pair-fst (fem-pair-fst $passert))
$p2 (fem-pair-snd (fem-pair-snd $passert)))))
(setq $p1 (min $p1 $p) $p2 (max $p2 $p))
;; Replace
;; Check if there are assertions to know whether to replace assertions
;; by assumptions or the revert
(goto-char $p1)
(setq $has-asserts (fem-search-forward-not-comment "assert" t $p2))
(when (not $has-asserts)
(goto-char $p1)
(setq $has-asserts (fem-search-forward-not-comment "assert_norm" t $p2)))
(goto-char $p)
;; Replace
(if $has-asserts
(progn
(fem-replace-all-in "assert_norm" "assume(*norm*)" t t $p1 $p2)
(fem-replace-all-in "assert" "assume" t t $p1 $p2))
(progn
(fem-replace-all-in "assume(*norm*)" "assert_norm" t nil $p1 $p2)
(fem-replace-all-in "assume" "assert" t t $p1 $p2)))
;; Maintain the selection if there was one
(when $keep-selection
(setq deactivate-mark nil)
(exchange-point-and-mark)
(exchange-point-and-mark))))
(defun fem-switch-assert-assume-in-above-paragraph ()
(interactive)
"Switch between assertions/assumptions in the current paragraph."
(fem-switch-assert-assume-in-current-region t t t nil))
(defun fem-switch-assert-assume-in-current-line ()
(interactive)
"Switch between assertions/assumptions in the current line."
(fem-switch-assert-assume-in-current-region t t nil nil))
(defun fem-roll-delete-term (TERM FORWARD BEGIN END)
(interactive)
"Roll TERM around.
Used for the rolling admit technique.
Look for the last/first occurence of TERM in the region and ask the user
if he wants to delete it, if there is any. Delete the following semicolon if
there is any. Leave the pointer at its original position (before the command was
called).
Return a tuple: (found term, optional shift if term was deleted, deleted a semicolon)"
(let ($p $s $f $r $semicol $opt_shift)
(setq $s 0)
;; Retrieve the original position
(setq $p (point))
;; Look for an admit
(if FORWARD (setq $f (fem-search-forward-not-comment TERM nil END))
(setq $f (fem-search-backward-not-comment TERM nil BEGIN)))
;; If there is an occurrence of TERM, ask for removal
(when $f
(when (y-or-n-p (concat "Remove this '" (concat TERM "'?")))
(progn
(replace-match "")
(setq $r t)
;; Look for a semicolon to delete
(when (char-equal ?\; (following-char))
(progn
(delete-char 1)
(setq $semicol t)
(when (not FORWARD) (setq $s 1))))
;; Delete the whole line if it is empty
(when (fem-current-line-is-whitespaces) (setq $s (fem-delete-always-line)))
;; Compute the position shift
(when (not FORWARD) (setq $s (+ (length TERM) $s)))
)))
;; Go to the original position
(goto-char (- $p $s))
;; Return the shift if we deleted a TERM
(if $r (setq $opt_shift $s) (setq $opt_shift nil))
;; Return
(list (cons 'found $f) (cons 'opt_shift $opt_shift) (cons 'semicol $semicol))))
(defun fem-roll-admit ()
(interactive)
"Roll an admit.
We start by looking for an admit after the cursor position, then before."
(let ($p $p1 $p2 $s)
;; Save the current point
(setq $p (point))
;; Find the region delimiters
(progn (forward-paragraph) (setq $p2 (point))
(progn (goto-char $p) (backward-paragraph) (setq $p1 (point)))
(goto-char $p))
;; Delete forward
(setq $s (fem-roll-delete-term "admit()" t $p1 $p2))
;; Delete backward
(when (not (cdr (assoc 'opt_shift $s)))
(setq $s (fem-roll-delete-term "admit()" nil $p1 $p2)))
;; Insert the admit
(if (cdr (assoc 'semicol $s))
(fem-insert-newline-term-smart-indent "admit();")
(fem-insert-newline-term-smart-indent "admit()"))))
;;; Parsing commands
(defun fem-in-general-comment-p (&optional POS)
"Return t is POS is in an F* comment."
(save-restriction
(or (fstar-in-comment-p POS) (fstar-in-literate-comment-p))))
(defun fem-search-forward-not-comment (STR &optional FULL_SEXP LIMIT)
"Look for the first occurrence of STR not inside a comment.
Return t and move the pointer immediately after if found one.
Don't move the pointer and return nil otherwise.
If FULL_SEXP, look for the first occurrence which is a sexpression."
(let (($p (point))
$exp)
(fstar--search-predicated-forward
(lambda ()
(if (fem-in-general-comment-p)
nil
(if (not FULL_SEXP)
t
(goto-char (match-beginning 0))
(setq $exp (fem-sexp-at-p-as-string))
(goto-char (match-end 0))
(if $exp
(string-equal $exp STR)
nil))))
STR LIMIT)
(not (= $p (point)))))
;; TODO: add to fstar-mode.el
(defun fem-fstar--search-predicated-backward (test-fn needle &optional bound)
"Search backward for matches of NEEDLE before BOUND satisfying TEST-FN."
(when (fstar--search-predicated #'search-backward test-fn
#'fstar--adjust-point-backward needle bound)
(goto-char (match-beginning 0))))
(defun fem-search-backward-not-comment (STR &optional FULL_SEXP LIMIT)
"Look backward for the first occurrence of STR not inside a comment."
(let (($p (point)) $exp)
(fem-fstar--search-predicated-backward
(lambda ()
(if (fem-in-general-comment-p)
nil
(if (not FULL_SEXP)
t
(goto-char (match-beginning 0))
(setq $exp (fem-sexp-at-p-as-string))
(goto-char (match-end 0))
(if $exp
(string-equal $exp STR)
nil))))
STR LIMIT)
(not (= $p (point)))))
;; TODO: use forward-comment
(defun fem-skip-comment (FORWARD &optional LIMIT)
"Move the cursor forward or backward until out of a comment.
Stop and don't fail if we reach the end of the buffer."
(let ($stop)
;; Set the limit to the move
(if FORWARD (setq $stop (or LIMIT (point-max)))
(setq $stop (or LIMIT (point-min))))
(cond
;; Inside a comment
((fstar-in-comment-p)
(if FORWARD
;; Forward: go forward until we are out of the comment
(while (and (fstar-in-comment-p) (< (point) $stop)) (forward-char))
;; Backward: we can use the parsing state to jump
(goto-char (nth 8 (fstar--syntax-ppss (point))))))
;; Inside a literate comment
((fstar-in-literate-comment-p)
(if FORWARD (if (search-forward "\n" $stop t) (point) (goto-char $stop))
(if (search-backward "\n" $stop t) (point) (goto-char $stop))))
(t (point)))))
(defun fem-is-at-comment-limit (FORWARD &optional LIMIT)
"Check if the pointer is just before/after a comment symbol."
(if FORWARD
;; If forward: the comments delimiters are always made of two characters
;; and we can't know if we are inside a comment unless we process those
;; two characters
(progn
(if (> (+ (point) 2) (or LIMIT (point-max))) nil
(fstar-in-comment-p (+ (point) 2))))
;; If backward: we just need to go one character back
(progn
(if (< (- (point) 1) (or LIMIT (point-min))) nil
(fstar-in-comment-p (- (point) 1))))))
(defun fem-skip-chars (FORWARD CHARS &optional LIMIT)
"Move until the current character is not in CHARS.
FORWARD controls the direction, LIMIT delimits where to stop."
(if FORWARD
(skip-chars-forward CHARS LIMIT)
(skip-chars-backward CHARS LIMIT)))
(defun fem-skip-spaces (FORWARD &optional LIMIT)
"Move the cursor until there are no spaces.
FORWARD controls the direction, LIMIT delimits where to stop."
(let ($continue $p1 $p2 $limit $reached-limit)
(if FORWARD (setq $p1 (point) $p2 (or LIMIT (point-max)))
(setq $p2 (point) $p1 (or LIMIT (point-min))))
(if FORWARD (setq $limit $p2) (setq $limit $p1))
(save-restriction
(narrow-to-region $p1 $p2)
(fem-skip-chars FORWARD fstar--spaces))
(point)))
(defun fem-skip-comments-and-spaces (FORWARD &optional LIMIT)
"Move the cursor until we are out of a comment and there are no spaces.
FORWARD controls the direction, LIMIT delimits the region."
(let ($continue $p1 $p2 $limit $reached-limit)
(if FORWARD (setq $p1 (point) $p2 (or LIMIT (point-max)))
(setq $p2 (point) $p1 (or LIMIT (point-min))))
(if FORWARD (setq $limit $p2) (setq $limit $p1))
(save-restriction
(narrow-to-region $p1 $p2)
(setq $continue t)
(while $continue
(fem-skip-comment FORWARD LIMIT)
(fem-skip-chars FORWARD fstar--spaces)
(setq $reached-limit (= (point) $limit))
(if $reached-limit (setq $continue nil)
(if (fem-is-at-comment-limit FORWARD)
(if FORWARD (forward-char 2) (backward-char 1))
(setq $continue nil)))))
(point)))
(defun fem-skip-forward-pragma (&optional LIMIT)
"Skip a pragma instruction (#push-options, #pop-options...).
If we are at the beginning of a #push-options or #pop-options instruction,
move forward until we are out of it or reach LIMIT.
Don't move if there isn't such an instruction.
Returns the position where the pointer is left."
(save-restriction
(narrow-to-region (point) (if LIMIT LIMIT (point-max)))
(let (($continue t) $go)
(defun go (STR CONTINUE)
(if (looking-at-p (regexp-quote STR))
(progn (forward-char (length STR)) (setq $continue CONTINUE) t)
nil))
(cond ((go "#set-options" t) ())
((go "#reset-options" t) ())
((go "#push-options" t) ())
((go "#pop-options" nil) ())
((go "#restart-solver" nil) ())
((go "#light" nil) ())
(t (setq $continue nil)))
;; Skip the parameters (the string) - note that there may be comments
;; between the pragma and the paramters
(when $continue
(fem-skip-comments-and-spaces t)
(forward-sexp)))))
(defun fem-skip-forward-open-module ()
"Skip an 'open ...' instruction.
Don't move if there isn't such an instruction."
;; TODO: so far, doesn't ignore comments
(save-match-data
(when (looking-at "open[\t\n\r ]+[a-zA-Z0-9]+\\(\\.[a-zA-Z0-9]+\\)*")
(goto-char (match-end 0)))
(point)))
(defun fem-skip-forward-open-rename-module ()
"Skip a 'module ... = ...' instruction.
Don't move if there isn't such an instruction."
;; TODO: so far, doesn't ignore comments
(save-match-data
(when (looking-at "module[\t\n\r ]+[a-zA-Z0-9]+[\t\n\r ]+=[\t\n\r ]+[a-zA-Z0-9]+\\(\\.[a-zA-Z0-9]+\\)*")
(goto-char (match-end 0)))
(point)))
(defun fem-skip-forward-module ()
"Skip a 'open ...' or 'module ... = ...' instruction"
;; TODO: so far, doesn't ignore comments
(fem-skip-forward-open-module)
(fem-skip-forward-open-rename-module))
(defun fem-skip-forward-square-brackets (&optional LIMIT)
"If look at '[', go after the closing ']'.
LIMIT delimits the end of the search."
(save-restriction
(narrow-to-region (point) (if LIMIT LIMIT (point-max)))
(when (looking-at-p (regexp-quote "["))
(forward-sexp)))
(point))
(defun fem-skip-forward-comments-pragmas-modules-spaces (&optional LIMIT)
"Go forward until there are no comments, pragma instructions or module openings instructions.
Stop at LIMIT."
(save-restriction
(narrow-to-region (point) (or LIMIT (point-max)))
(let (($continue t)
($p (point)))
(while $continue
(fem-skip-comments-and-spaces t)
(fem-skip-forward-pragma)
(fem-skip-forward-module)
(when (or (= (point) $p) (= (point) (point-max)))
(setq $continue nil))
(setq $p (point))))))
(defun fem-region-is-comments-and-spaces (BEG END &optional NO_NEWLINE)
"Check if a region is only made of spaces and comments.
The region is delimited by BEG and END.
NO_NEWLINE controls whether newline characters are considered spaces or not."
(let (($p (point)) ($continue t))
(goto-char BEG)
(fem-skip-comments-and-spaces t END)
(if (< (point) END) nil
;; If we reached the end: eventually check if there are new line characters
(goto-char BEG)
(if NO_NEWLINE (not (search-forward "\n" END t)) t))))
(defun fem-region-is-tuple (BEG END)
"Return t if the text region delimited by BEG and END is a tuple.
In practice, simply check if there is a ',' inside."
(save-excursion
(save-restriction
(goto-char BEG)
(fem-search-forward-not-comment "," nil END))))
(defun fem-space-after-p (&optional POS)
"Return t if there is a space at POS.
POS defaults to the pointer's position."
(seq-contains fstar--spaces (char-after POS)))
(defun fem-space-before-p (&optional POS)
"Return t if there is a space before POS.
POS defaults to the pointer's position."
(seq-contains fstar--spaces (char-before POS)))
(defun fem-is-in-spaces-p (&optional POS)
"Return t if there are spaces before and after POS.
POS defaults to the pointer's position."
(and (fem-space-after-p POS) (fem-space-before-p POS)))
(defun fem-safe-backward-sexp (&optional ARG)
"Call (backward-sexp ARG) and return nil instead of raising errors."
(ignore-errors (backward-sexp ARG)))
(defun fem-safe-forward-sexp (&optional ARG)
"Call (forward-sexp ARG) and return nil instead of raising errors."
(ignore-errors (forward-sexp ARG)))
(defun fem-sexp-at-p (&optional POS ACCEPT_COMMENTS)
"Find the sexp at POS.
POS defaults to the pointer's position.
Returns a fem-pair of positions if succeeds, nil otherwise.
If ACCEPT_COMMENTS is nil, return nil if the sexp is inside a comment."
(save-excursion
(let (($p0 (or POS (point))) ($not-ok nil) $beg $end)
;; Must not be in a comment (unless the user wants it) or surrounded by spaces
(setq $not-ok (or (and (fem-in-general-comment-p) (not ACCEPT_COMMENTS))
(fem-is-in-spaces-p)))
;; Find the beginning and end positions
(if $not-ok nil
;; End: if looking at space, this is the end position. Otherwise,
;; go to the end of the sexp
(when (not (fem-space-after-p)) (fem-safe-forward-sexp))
(setq $end (point))
;; Beginning: just go backward
(fem-safe-backward-sexp)
(setq $beg (point))
;; Sanity check
(if (and (<= $beg $p0) (>= $end $p0))
(make-fem-pair :fst $beg :snd $end)
nil)))))
(defun fem-sexp-at-p-as-string (&optional POS)
"Return the sexp at POS."
(let (($r (fem-sexp-at-p)))
(if $r (buffer-substring-no-properties (fem-pair-fst $r) (fem-pair-snd $r))
nil)))
;; TODO: could be dramatically improved by using proper regexps
(defun fem-parse-subexpr (BEG END)
"Parse a sub-expression of the form 'let _ = _ in', '_;' or '_'.
Parses in the region delimited by BEG and END.
Returns a fem-subexpr."
(let ($delimiters $beg $end $is-let-in $has-semicol)
;; Parse: 3 cases:
;; - let _ = _ in
;; - _;
;; - _
(setq $is-let-in nil $has-semicol nil)
;; Note that there may be a comment/spaces at the beginning and/or at the end
;; of the processed region, which we need to skip:
;; - beginning
(goto-char BEG)
(fem-skip-comments-and-spaces t)
(setq $beg (point))
;; - end
(goto-char END)
(fem-skip-comments-and-spaces nil $beg)
(setq $end (point))
;; We do the regexp matching in a narrowed region
(save-restriction
(narrow-to-region $beg $end)
;; Check if the narrowed region matches: 'let _ = _ in'
(goto-char (point-min))
(setq $is-let-in
;; TODO: rewrite the regexp
(re-search-forward "\\=let[[:ascii:][:nonascii:]]+in\\'" (point-max) t 1))
;; (when $is-let-in (setq $bterm (fem-parse-letb-term $beg $end)))
;; Check if the narrowed region matches: '_ ;'
(goto-char (point-min))
(setq $has-semicol
;; We could just check if the character before last is ';'
;; TODO: rewrite the regexp
(re-search-forward "\\=[[:ascii:][:nonascii:]]+;\\'" (point-max) t 1))
;; Otherwise: it is a return value (end of function)
) ;; end of regexp matching
;; Return
(make-fem-subexpr :beg $beg :end $end :is-let-in $is-let-in :has-semicol $has-semicol)))
;; :bterm $bterm)))
(defun fem-shift-subexpr-pos (SHIFT SUBEXPR)
"Shift by SHIFT the positions in the fem-subexpr SUBEXPR.
Return the updated fem-subexpr."
(setf (fem-subexpr-beg SUBEXPR) (+ SHIFT (fem-subexpr-beg SUBEXPR)))
(setf (fem-subexpr-end SUBEXPR) (+ SHIFT (fem-subexpr-end SUBEXPR)))
SUBEXPR)
(defun fem-find-encompassing-assert-assume-p (&optional POS BEG END)
"Find the encompassing F* assert(_norm)/assume.
Takes an optional pointer position POS and region delimiters BEG and END.
Returns a fem-pair of fem-pair of positions if found (for the assert identifier and
the content of the assert), nil otherwise."
(save-excursion
(save-restriction
;; The strategy is very simple: look for the closest previous asset/assume
;; which is not in a comment and such that, ignoring comments, the next
;; sexp contains the current point
(let (($rbeg (if BEG BEG (point-min))) ;; region beginning
($rend (if END END (point-max))) ;; region end
($pos (if POS POS (point)))
$abeg $aend ;; assert/assume beginning/end positions
$pbeg $pend ;; proposition beginning/end positions
$pred ;; predicate function (just for variable shadowing)
)
(narrow-to-region $rbeg $rend)
;; The predicate function for the search
(defun $pred ()
(save-match-data
(save-excursion
(let ($ar $str $pr)
;; Check that we are looking at an assert(_norm)/assume
(setq $ar (fem-sexp-at-p))
;; $ar might be nil here
(if (not $ar) nil
(setq $abeg (fem-pair-fst $ar) $aend (fem-pair-snd $ar))
(setq $str (buffer-substring-no-properties $abeg $aend))
(if (not (or (string-equal $str "assert")
(string-equal $str "assert_norm")
(string-equal $str "assume")))
;; Not ok
nil
;; Ok: check if the pointer is inside the argument
(goto-char $aend)
(fem-skip-comments-and-spaces t)
(setq $pbeg (point))
(fem-safe-forward-sexp)
(setq $pend (point))
(and (<= $pbeg $pos) (>= $pend $pos))))))))
;; Search and return
(when (fstar--re-search-predicated-backward '$pred "assert\\|assume" $rbeg)
;; Return
nil
(make-fem-pair :fst (make-fem-pair :fst $abeg :snd $aend)
:snd (make-fem-pair :fst $pbeg :snd $pend))
)))))
(defun fem-find-assert-assume-p (&optional POS BEG END)
"Find the F* assert(_norm)/assume at the pointer position.
Takes an optional pointer position POS and region delimiters BEG and END.
Returns a fem-pair of fem-pair of positions if found (for the assert identifier and
the content of the assert), nil otherwise.
At the difference of find-encompassing-assert-assume-p, the pointer doesn't
have to be inside the assertion/assumption. It can for instance be on an
``assert`` identifier."
(save-excursion
(save-restriction
(let (($rbeg (if BEG BEG (point-min))) ;; region beginning
($rend (if END END (point-max))) ;; region end
($pos (if POS POS (point)))
$sexp $pbeg $pend $str)
;; First check if we are not exactly on the identifier, otherwise
;; call find-encompassing-assert-assume-p
(goto-char $pos)
(setq $sexp (fem-sexp-at-p))
(if $sexp
(setq $str (buffer-substring-no-properties (fem-pair-fst $sexp)
(fem-pair-snd $sexp)))
(setq $str ""))