-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathr-syntax.el
1586 lines (1380 loc) · 49.5 KB
/
r-syntax.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
;;; r-syntax.el --- Utils to work with R code
;;
;; Copyright (C) 2016 Lionel Henry, Vitalie Spinu
;;
;; Author: Lionel Henry <[email protected]>
;; Created: 3 Jul 2016
;;
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;;
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; A copy of the GNU General Public License is available at
;; http://www.r-project.org/Licenses/
;;
;;; Commentary:
;;
;; API is not yet stable.
;;
;;; Code:
(require 'regexp-opt)
(require 'cl-lib)
(require 'r-utils)
;;*;; Utils
;; VS[04-07-2016]: fixme: these macros rely on dynamic scope. That's bad.
(defmacro r-save-excursion-when-nil (&rest body)
(declare (indent 0)
(debug (&rest form)))
`(let ((orig-point (point)))
(cond ((progn ,@body))
(t (prog1 nil
(goto-char orig-point))))))
(defmacro r-while (test &rest body)
"Like (while) but return `t' when body gets executed once."
(declare (indent 1)
(debug (&rest form)))
`(let (executed)
(while ,test
(setq executed t)
,@body)
executed))
(defmacro r-at-indent-point (&rest body)
(declare (indent 0)
(debug (&rest form)))
`(save-excursion
(goto-char indent-point)
(r-back-to-indentation)
(progn ,@body)))
(defmacro r-at-containing-sexp (&rest body)
(declare (indent 0)
(debug (&rest form)))
'(when (not (bound-and-true-p containing-sexp))
(error "Internal error: containing-sexp is nil or undefined"))
`(save-excursion
(goto-char containing-sexp)
(progn ,@body)))
(defmacro r-any (&rest forms)
"Evaluates all arguments and return non-nil if one of the
arguments is non-nil. This is useful to trigger
side-effects. FORMS follows the same syntax as arguments to
`(cond)'."
(declare (indent 0) (debug nil))
`(let ((forms (list ,@(mapcar (lambda (form) `(progn ,@form)) forms))))
(cl-some 'identity (mapcar 'eval forms))))
(defun r-char-syntax (string)
(char-to-string (char-syntax (string-to-char string))))
;;*;; Tokenisation
(defun r-token-type (token) (car (nth 0 token)))
(defun r-token-value (token) (cdr (nth 0 token)))
(defun r-token-start (token) (car (nth 1 token)))
(defun r-token-end (token) (cdr (nth 1 token)))
(defun r-token-refined-type (token)
(r-token-type (r-refine-token token)))
(defun r-token-after (&optional token)
"Returns next token.
Cons cell containing the token type and string representation."
(save-excursion
(when token
(goto-char (r-token-end token)))
(r-jump-token)))
(defun r-token-before (&optional token)
"Returns previous token.
Cons cell containing the token type and string representation."
(save-excursion
(when token
(goto-char (r-token-start token)))
(r-climb-token)))
(defun r-climb-token (&optional type string)
(r-save-excursion-when-nil
(r-escape-comment)
(r-skip-blanks-backward t)
(let ((token (or (r-climb-token--back)
(r-climb-token--back-and-forth)
(error "Internal error: Backward tokenization failed:\n%s"
(buffer-substring (line-beginning-position)
(line-end-position))))))
(if (or type string)
(when (r-token= token type string)
token)
token))))
(defun r-token--cons (type value)
(if (eq type 'self)
(cons value nil)
(cons type value)))
(defun r-climb-token--back ()
(let* ((token-end (point))
(token-type (if (= (point) (point-min))
"buffer-start"
(r-climb-token--operator)))
(token-value (buffer-substring-no-properties (point) token-end)))
(unless (null token-type)
(list (r-token--cons token-type token-value)
(cons (point) token-end)))))
;; Difficult to use regexps here because we want to match greedily
;; backward
(defun r-climb-token--operator ()
(when (pcase (char-before)
((or ?+ ?/ ?^ ?~ ?? ?!)
(r-backward-char))
(`?=
(prog1 (r-backward-char)
(or (r-climb-token--char ?=)
(r-climb-token--char ?!)
(r-climb-token--char ?:)
(r-climb-token--char ?>)
(r-climb-token--char ?<))))
((or ?& ?| ?* ?@ ?$)
(prog1 (r-backward-char)
(r-climb-token--char (char-after))))
(`?<
(r-backward-char))
(`?>
(prog1 (r-backward-char)
(or (r-climb-token--char ?-)
(and (looking-back "->" (- (point) 2))
(goto-char (- (point) 2))))))
(`?-
(prog1 (r-backward-char)
(r-climb-token--char ?< ?<)))
(`?:
(prog1 (r-backward-char)
(r-climb-token--char ?: ?:))))
'self))
(defsubst r-climb-token--char (&rest chars)
(r-while (and chars
(eq (char-before) (car chars))
(r-backward-char))
(setq chars (cdr chars))))
(defun r-climb-token--back-and-forth ()
(let ((limit (point)))
(when (r-skip-token-backward)
(save-restriction
(narrow-to-region (point) limit)
(r-token-after)))))
(defun r-skip-token-backward ()
(r-save-excursion-when-nil
(cond
;; Punctuation
((memq (char-before) '(?, ?\;))
(r-backward-char))
;; Quoting delimiters
((memq (char-syntax (char-before)) '(?\" ?$))
(r-backward-sexp))
;; Syntaxic delimiters
((memq (char-syntax (char-before)) '(?\( ?\)))
(prog1 (r-backward-char)
;; Also skip double brackets
(r-save-excursion-when-nil
(when (let ((current-delim (char-after)))
(r-skip-blanks-backward)
(and (memq (char-before) '(?\[ ?\]))
(eq current-delim (char-before))))
(r-backward-char)))))
;; Identifiers and numbers
((/= (skip-syntax-backward "w_") 0)))))
(defun r-jump-token (&optional type string)
"Consume a token forward.
Returns a cons cell containing the token type and the token
string content. Returns nil when the end of the buffer is
reached."
(r-save-excursion-when-nil
(r-skip-blanks-forward t)
(let* ((token-start (point))
(token-type (or (r-jump-token--regexps)
(r-jump-token--literal)
(r-jump-token--infix-op)
(r-jump-token--punctuation)
(error "Internal error: Forward tokenization failed:\n%s"
(buffer-substring (line-beginning-position)
(line-end-position)))))
(token-value (buffer-substring-no-properties token-start (point))))
(let ((token (list (r-token--cons token-type token-value)
(cons token-start (point)))))
(if (or type string)
(when (r-token= token type string)
token)
token)))))
(defun r-jump-token--literal ()
(cond
;; Simply assume anything starting with a digit is a number. May be
;; too liberal but takes care of fractional numbers, integers such
;; as 10L, etc. False positives are not valid R code anyway.
((looking-at "[0-9]")
(r-forward-sexp)
"number")
((or (looking-at "\\sw\\|\\s_")
(eq (char-after) ?`))
(r-forward-sexp)
"identifier")
((memq (char-after) '(?\" ?\'))
(r-forward-sexp)
"string")))
(defun r-jump-token--punctuation ()
(or (when (= (point) (point-max))
"buffer-end")
(pcase (char-after)
(`?\;
(forward-char)
'self)
(`?,
(forward-char)
;; Treat blanks after comma as part of an argument
(r-skip-blanks-forward t)
","))))
(defvar r-prefix-keywords-list
'("if" "for" "while" "function"))
(defvar r-keywords-list
(append r-prefix-keywords-list '("else")))
(defvar r-delimiters-list
'("(" ")" "{" "}" "[" "]" "[[" "]]"))
(defvar r-operators-list
'("+" "-" "*" "/" "%%" "**" "^"
"&" "&&" "|" "||" "!" "?" "~"
"==" "!=" "<" "<=" ">=" ">"
"=" "<-" "<<-" "->" "->>"
"$" "@" ":" "::" ":::" ":="))
(defvar r-keywords-re
(concat (regexp-opt r-keywords-list) "\\_>"))
(defvar r-delimiters-re
(regexp-opt r-delimiters-list))
(defvar r-operators-re
(regexp-opt r-operators-list))
(defun r-jump-token--regexps ()
(when (or (looking-at r-keywords-re)
(looking-at r-delimiters-re)
(looking-at r-operators-re))
(goto-char (match-end 0))
'self))
(defun r-jump-token--infix-op ()
(or (when (looking-at r-operators-re)
(goto-char (match-end 0))
'self)
(when (eq (char-after) ?%)
(r-forward-sexp)
"%infix%")))
(defun r-escape-token ()
(r-escape-comment)
(r-skip-blanks-forward)
(or (r-escape-string)
(when (r-token-delimiter-p (r-token-after))
(prog1 t
(mapc (lambda (delims)
(while (and (r-token-after= nil delims)
(eq (char-before) (string-to-char
(car delim))))
(r-backward-char)))
'(("[" "[[") ("]" "]]")))))
(r-token-after= '("," ";"))
(and (r-token-after= "identifier")
(not (memq (char-syntax (char-before)) '(?w ?_))))
(progn (/= (skip-syntax-backward ".") 0)
(r-token-operator-p (r-token-after)))
(/= (skip-syntax-backward "w_") 0)))
(defun r-refine-token (token)
(let ((refined-type
(pcase (r-token-type token)
;; Parameter assignment
("="
(save-excursion
(goto-char (r-token-start token))
(let ((containing-sexp (r-containing-sexp-position)))
(when (and containing-sexp
(r-at-containing-sexp
(and (r-token-after= "(")
(r-token-before= '("identifier" "string"))))
(save-excursion
(and (r-climb-token)
(r-token-before= '("," "(")))))
"param-assign"))))
;; Quoted identifiers
("string"
(when (or
;; Quoted parameter names
(r-refined-token= (r-token-after) "param-assign")
;; Quoted call names
(r-token-after= "("))
"identifier"))
((or "(" ")")
(or (save-excursion
(if (r-token-close-delimiter-p token)
(r-climb-paired-delims nil token)
(goto-char (r-token-start token)))
(when (r-token-keyword-p (r-token-before))
"prefixed-expr-delimiter"))
;; Fixme: probably too crude. Better handled in parser
(when (r-token= token ")")
(save-excursion
(r-climb-paired-delims ")" token)
(when (r-token-before= '("identifier" "string" ")" "]" "]]" "}"))
"argslist-delimiter")))))
((or "{" "}")
(save-excursion
(unless (r-climb-paired-delims "}" token)
(goto-char (r-token-start token)))
(when (r-refined-token= (r-token-before) "prefixed-expr-delimiter")
"prefixed-expr-delimiter"))))))
(if refined-type
(list (cons refined-type (r-token-value token))
(nth 1 token))
token)))
(defun r-token-balancing-delim (token)
(pcase (r-token-type token)
(`"(" ")")
(`")" "(")
(`"[" "]")
(`"]" "[")
(`"[[" "]]")
(`"]]" "[[")))
;;;*;;; Token predicates
(defun r-token= (token &optional type string)
(when (and (null type)
(null string))
(error "No condition supplied"))
(let ((type (if (stringp type) (list type) type))
(string (if (stringp string) (list string) string)))
(and (if type (member (r-token-type token) type) t)
(if string (member (r-token-value token) string) t))))
(defun r-refined-token= (token type &optional string)
(r-token= (r-refine-token token) type string))
(defun r-token-after= (type &optional string)
(r-token= (r-token-after) type string))
(defun r-token-before= (type &optional string)
(r-token= (r-token-before) type string))
(defun r-token-open-delimiter-p (token)
(string= (r-char-syntax (r-token-type token)) "("))
(defun r-token-close-delimiter-p (token)
(string= (r-char-syntax (r-token-type token)) ")"))
(defun r-token-delimiter-p (token)
(or (r-token-open-delimiter-p token)
(r-token-close-delimiter-p token)))
(defun r-token-operator-p (token &optional strict)
(and (or (member (r-token-type token) r-operators-list)
(string= (r-token-type token) "%infix%"))
(or (null strict)
(not (r-refined-token= token "param-assign")))))
(defun r-token-keyword-p (token)
(member (r-token-type token) r-keywords-list))
;;;*;;; Tokens properties and accessors
(defun r-token-make-hash (&rest specs)
(let ((table (make-hash-table :test #'equal)))
(mapc (lambda (spec)
;; alist
(if (listp (cdr spec))
(mapc (lambda (cell)
(puthash (car cell) (cdr cell) table))
spec)
;; Cons cell
(mapc (lambda (token)
(puthash token (cdr spec) table))
(car spec))))
specs)
table))
(defvar r-token-r-powers-delimiters
'(("(" . 100)
("[" . 100)
("[[" . 100)))
(defvar r-token-r-powers-operator
'(("?" . 5)
("else" . 8)
("<-" . 10)
("<<-" . 10)
("=" . 15)
("->" . 20)
("->>" . 20)
("~" . 25)
("|" . 30)
("||" . 30)
("&" . 35)
("&&" . 35)
("!" . 40)
("<" . 45)
(">" . 45)
("<=" . 45)
(">=" . 45)
("==" . 45)
("+" . 50)
("-" . 50)
("*" . 55)
("/" . 55)
("%infix%" . 60)
(":" . 65)
("^" . 70)
("$" . 75)
("@" . 75)
("::" . 80)
(":::" . 80)))
(defvar r-token-r-power-table
(r-token-make-hash r-token-r-powers-operator
r-token-r-powers-delimiters))
(defvar r-token-r-right-powers-operator
'((")" . 1)))
(defvar r-token-r-right-power-table
(r-token-make-hash r-token-r-powers-operator
r-token-r-right-powers-operator))
(defvar r-token-r-nud-table
(r-token-make-hash
'(("identifier" . identity)
("literal" . identity)
("number" . identity)
("function" . identity)
("if" . identity)
("while" . identity)
("for" . identity))
'(("(" . r-parser-nud-block)
("{" . r-parser-nud-block))))
(defvar r-token-r-rnud-table
(r-token-make-hash
'(("identifier" . identity)
("literal" . identity)
("number" . identity))
'((")" . r-parser-rnud-paren)
("}" . r-parser-nud-block))))
(defvar r-token-r-leds-operator
(let ((operators-list (append '("%infix%" "else") r-operators-list)))
(cons operators-list #'r-parser-led-lassoc)))
(defvar r-token-r-leds-delimiter
'(("(" . r-parser-led-funcall)
("[" . r-parser-led-funcall)
("[[" . r-parser-led-funcall)))
(defvar r-token-r-led-table
(r-token-make-hash r-token-r-leds-operator
r-token-r-leds-delimiter))
(defvar r-token-r-rid-table
(r-token-make-hash
'((")" . r-parser-rid-expr-prefix))))
;;;*;;; Nud, led and rid functions
(defun r-parser-nud-block (prefix-token)
(let ((right (list (cons "TODO" nil))))
(r-parser-advance-pair nil prefix-token)
(r-node (cons "block" nil)
(cons (r-token-start prefix-token) (point))
(list prefix-token right))))
(defun r-parser-led-lassoc (start infix-token)
(let* ((power (r-parser-power infix-token))
(end (r-parse-expression power)))
(r-node (cons "binary-op" nil)
(cons (r-parser-token-start start) (point))
(list start infix-token end))))
(defun r-parser-led-funcall (left infix-token)
(when (r-token= left (append '("identifier" "string" "node")
r-prefix-keywords-list))
(let* ((power (r-parser-power infix-token))
(right (r-parse-arglist power infix-token))
(type (if (r-token= left r-prefix-keywords-list)
"prefixed-expr"
"funcall")))
(when (string= type "prefixed-expr")
(setq right (list right (r-parse-expression 0))))
(r-node (cons type nil)
(cons (r-parser-token-start left) (point))
(list left right)))))
(defun r-parser-rid-expr-prefix (right suffix-token)
(when (r-refined-token= suffix-token "prefixed-expr-delimiter")
(r-parser-rnud-paren suffix-token right)))
(defun r-parser-rnud-paren (suffix-token &optional prefixed-expr)
(let* ((infix-token (save-excursion
(r-parser-advance-pair nil suffix-token)))
(power (r-parser-power infix-token))
(args (r-parse-arglist power suffix-token))
(left (if prefixed-expr
(r-parser-advance)
(r-parse-expression power)))
(type (cond (prefixed-expr "prefixed-expr")
(left "funcall")
(t "enclosed-expr"))))
(when prefixed-expr
(setcdr (car prefixed-expr) (list infix-token suffix-token)))
(r-node (cons type nil)
(cons (r-parser-token-start suffix-token) (point))
(if prefixed-expr
(list prefixed-expr args left)
(list args left)))))
;;;*;;; Parsing
(defun r-parser-advance (&optional type value)
(if (bound-and-true-p r-parser--backward)
(r-climb-token type value)
(r-jump-token type value)))
(defun r-parser-advance-pair (&optional type token)
(if (bound-and-true-p r-parser--backward)
(r-climb-paired-delims type token)
(r-jump-paired-delims type token)))
(defun r-parser-next-token ()
(if (bound-and-true-p r-parser--backward)
(r-token-before)
(r-token-after)))
(defun r-parser-token-start (token)
(if (bound-and-true-p r-parser--backward)
(r-token-end token)
(r-token-start token)))
(defun r-parser-power (token)
(or (if (bound-and-true-p r-parser--backward)
(gethash (r-token-type token) r-token-r-right-power-table)
(gethash (r-token-type token) r-token-r-power-table))
0))
(defun r-node (type pos contents)
(let ((pos (if (bound-and-true-p r-parser--backward)
(cons (cdr pos) (car pos))
pos))
(contents (if (bound-and-true-p r-parser--backward)
(nreverse contents)
contents)))
(list type pos contents)))
(defalias 'r-node-start #'r-token-start)
(defalias 'r-node-end #'r-token-end)
(defun r-parse-start-token (token)
(let* ((table (if (bound-and-true-p r-parser--backward)
r-token-r-rnud-table
r-token-r-nud-table))
(nud (gethash (r-token-type token) table)))
(when (fboundp nud)
(funcall nud token))))
(defun r-parse-infix-token (infix-token left)
(let ((infix-power (r-parser-power infix-token))
(led (or (when (bound-and-true-p r-parser--backward)
(gethash (r-token-type infix-token) r-token-r-rid-table))
(gethash (r-token-type infix-token) r-token-r-led-table))))
(funcall led left infix-token)))
(defun r-parse-expression (&optional power)
(let ((current (r-parse-start-token (r-parser-advance)))
(power (or power 0))
(next (r-parser-next-token))
(last-sucessful-pos (point))
last-success)
(setq last-success current)
(while (and current (< power (r-parser-power next)))
(r-parser-advance)
(when (setq current (r-parse-infix-token next current))
(setq last-sucessful-pos (point))
(setq last-success current))
(setq next (r-parser-next-token)))
(goto-char last-sucessful-pos)
last-success))
(defun r-parse-arglist (power start-token)
(let ((start-pos (point))
(arg-start-pos (point))
(arglist (list start-token))
(closing-delim (r-token-balancing-delim start-token))
expr)
(while (and (setq expr (r-parse-expression))
(push (r-node (cons "arg" nil)
(cons arg-start-pos (point))
(list expr))
arglist)
(r-parser-advance ","))
(setq arg-start-pos (point)))
(push (r-parser-advance closing-delim) arglist)
(r-node (cons "arglist" nil)
(cons start-pos (1- (point)))
(nreverse arglist))))
(defun forward-r-expr ()
(interactive)
(r-save-excursion-when-nil
(r-escape-token)
(r-parse-expression)))
(defun forward-r-sexp ()
(interactive)
(r-save-excursion-when-nil
(r-escape-token)
(let* ((orig-token (r-token-after))
(tree (r-parse-expression))
(sexp-node (r-parser-tree-assoc orig-token tree)))
(when sexp-node
(goto-char (r-token-end sexp-node))
sexp-node))))
(defun backward-r-expr ()
(interactive)
(let ((r-parser--backward t))
(r-parse-expression)))
(defun backward-r-sexp ()
(interactive)
(error "todo"))
(defun r-parser-tree-assoc (key tree)
(let ((next tree)
stack last-node result)
(while (and next (null result))
(cond ((eq next 'node-end)
(pop last-node))
((nth 2 next)
(push 'node-end stack)
(dolist (node (nth 2 next))
(push node stack))
(push next last-node))
((equal next key)
(setq result (car last-node))))
(setq next (pop stack)))
result))
;;*;; Point predicates
;; fixme: not a good name for a section. Many predicates from the next section
;; are also point-predicates.
(defun r-within-call-p (&optional call)
"Is point in a function or indexing call?"
(let ((containing-sexp (or (bound-and-true-p containing-sexp)
(r-containing-sexp-position))))
(save-excursion
(and (prog1 (r-goto-char containing-sexp)
(r-climb-chained-delims))
(save-excursion
(forward-char)
(r-up-list))
(or (r-behind-call-opening "(")
(looking-at "\\["))
(r-within-call-name-p call)))))
(defun r-within-continuation-p ()
(unless (or (looking-at ",")
(r-behind-call-opening "[[(]"))
(or (save-excursion
(r-jump-object)
(and (not (r-ahead-param-assign-p))
(r-behind-operator-p)))
(save-excursion
(r-climb-object)
(r-climb-operator)
(and (r-behind-operator-p)
(not (r-ahead-param-assign-p)))))))
(defun r-within-call-name-p (&optional call)
(save-excursion
(r-climb-call-name call)))
(defun r-within-prefixed-block-p (&optional call)
"Return t if point in a prefixed block.
Prefixed blocks refer to the blocks following function
declarations, control flow statements, etc.
If CALL is non nil, check if the prefix corresponds to a CALL. If
nil, return the prefix."
(save-excursion
(r-escape-prefixed-block call)))
(defun r-within-comment-p (&optional state)
(let ((state (or state (syntax-ppss))))
(eq (syntax-ppss-context state) 'comment)))
(defun r-within-string-p (&optional state)
(let ((state (or state (syntax-ppss))))
(eq (syntax-ppss-context state) 'string)))
;;*;; Syntactic Travellers and Predicates
;;;*;;; Basic
(defun r-ahead-closing-p ()
(memq (char-before) '(?\] ?\} ?\))))
(defun r-ahead-boundary-p ()
(looking-back "[][ \t\n(){},]" (1- (point))))
(defun r-goto-char (pos)
"Just as `goto-char' but return nil when POS is nil."
(when pos
(goto-char pos)))
(defun r-goto-line (line)
"Go to LINE."
(save-restriction
(widen)
(goto-char (point-min))
(forward-line (1- line))))
(defun r-backward-sexp (&optional N)
"Like `backward-sexp' but don't throw."
(r-forward-sexp (- (or N 1))))
(defun r-forward-sexp (&optional N)
"Like `forward-sexp' but don't throw."
(setq N (or N 1))
(condition-case nil
(prog1 t
(goto-char (or (scan-sexps (point) N)
(buffer-end N))))
(error nil)))
(defun r-up-list (&optional N)
"Like `up-char' but don't throw."
(condition-case nil
(progn (up-list N) t)
(error nil)))
(defun r-forward-char (&optional N)
"Like `forward-char' but don't throw at point-max.
Return t when succeed, nil otherwise."
(unless (= (point) (point-max))
(forward-char (or N 1))
t))
(defun r-backward-char (&optional N)
"Like `backward-char' but don't throw."
(unless (= (point) (point-min))
(forward-char (- (or N 1)))
t))
(defun r-jump-char (char)
(r-save-excursion-when-nil
(r-skip-blanks-forward t)
(when (looking-at char)
(goto-char (match-end 0)))))
;; VS[04-07-2016]: Is this really needed?
(defun r-back-to-indentation ()
"Move point to the first non-whitespace character on this line.
This non-interactive version of (back-to-indentation) should not
be advised"
(beginning-of-line 1)
(skip-syntax-forward " " (line-end-position))
;; Move back over chars that have whitespace syntax but have the p flag.
(backward-prefix-chars))
(defun r-skip-blanks-backward (&optional newlines)
"Skip blanks and newlines backward, taking end-of-line comments
into account."
(r-any ((r-skip-blanks-backward-1))
((when newlines
(r-while (and (/= (point) (point-min))
(= (point) (line-beginning-position)))
(forward-line -1)
(goto-char (r-line-end-position))
(r-skip-blanks-backward-1))))))
(defun r-skip-blanks-backward-1 ()
(and (/= (point) (point-min))
(/= 0 (skip-syntax-backward " "))))
(defun r-skip-blanks-forward (&optional newlines)
"Skip blanks and newlines forward, taking end-of-line comments
into account."
(r-any ((/= 0 (skip-syntax-forward " ")))
((r-while (and newlines
(= (point) (r-line-end-position))
(when (r-save-excursion-when-nil
;; Handles corner cases such as point being on last line
(let ((orig-point (point)))
(forward-line)
(r-back-to-indentation)
(> (point) orig-point)))
(skip-chars-forward " \t")
t))))))
;; fixme: meaning of "escape" is not clear
(defun r-escape-comment ()
(when (r-within-comment-p)
(prog1 (comment-beginning)
(skip-chars-backward "#+[ \t]*"))))
(defun r-escape-string ()
(and (nth 3 (syntax-ppss))
(r-goto-char (nth 8 (syntax-ppss)))))
(defun r-climb-paired-delims (&optional type token)
(r-save-excursion-when-nil
(let ((token (or token (r-token-before))))
(goto-char (r-token-end token))
(when (if type
(r-token= token type)
(r-token-delimiter-p token))
(and (r-backward-sexp)
(r-token-after))))))
(defun r-jump-paired-delims (&optional type token)
(r-save-excursion-when-nil
(let ((token (or token (r-token-after))))
(goto-char (r-token-start token))
(when (if type
(r-token= token type)
(r-token-delimiter-p token))
(and (r-forward-sexp)
(r-token-before))))))
;;;*;;; Blocks
(defvar r-prefixed-block-patterns
(mapcar (lambda (fun) (concat fun "[ \t\n]*("))
'("function" "if" "for" "while")))
(defun r-block-opening-p ()
(save-excursion
(cond
((looking-at "{"))
;; Opening parenthesis not attached to a function opens up a
;; block too. Only pick up those that are last on their line
((r-behind-block-paren-p)))))
(defun r-block-closing-p ()
(save-excursion
(cond
((looking-at "}"))
((looking-at ")")
(forward-char)
(backward-sexp)
(not (looking-back
(concat r-name-pattern "[[:blank:]]*")
(line-beginning-position)))))))
(defun r-block-p ()
(or (save-excursion
(when containing-sexp
(goto-char containing-sexp)
(r-block-opening-p)))
(r-unbraced-block-p)))
;; Parenthesised expressions
(defun r-behind-block-paren-p ()
(and (looking-at "(")
(not (r-ahead-attached-name-p))))
(defun r-behind-prefixed-block-p (&optional call)
(if call
(looking-at (concat call "[ \t]*("))
(cl-some 'looking-at r-prefixed-block-patterns)))
(defun r-unbraced-block-p (&optional ignore-ifelse)
"This indicates whether point is in front of an unbraced
prefixed block following a control flow statement. Returns
position of the control flow function (if, for, while, etc)."
(save-excursion
(and (r-backward-sexp)
(or (and (looking-at "else\\b")
(not ignore-ifelse))
(and (looking-at "(")
(r-backward-sexp)
(cl-some 'looking-at r-prefixed-block-patterns)
(if ignore-ifelse
(not (looking-at "if\\b"))
t)))
(point))))
(defun r-climb-block (&optional ignore-ifelse)
(r-save-excursion-when-nil
(cond
((and (not ignore-ifelse)
(r-climb-if-else 'to-start)))
((and (eq (char-before) ?\})
(prog2
(forward-char -1)
(r-up-list -1)
(r-climb-block-prefix)))))))
(defun r-climb-block-prefix (&optional call ignore-ifelse)
"Climb the prefix of a prefixed block. Prefixed blocks refer to
the blocks following function declarations, control flow
statements, etc.
Should be called either in front of a naked block or in front
of the curly brackets of a braced block.
If CALL not nil, check if the prefix corresponds to CALL. If nil,
return the prefix."
(r-save-excursion-when-nil
(or (and (not ignore-ifelse)
(prog1 (and (r-climb-if-else-call)
(or (null call)
(looking-at call)))
(when (r-token-after= "else")
(r-climb-token "}"))))
(let ((pos (r-unbraced-block-p ignore-ifelse)))
(and (r-goto-char pos)
(if call
(looking-at call)
(cond ((looking-at "function")
"function")
((looking-at "for")
"for")
((looking-at "if")
"if")
((looking-at "else")
"else"))))))))
(defun r-escape-prefixed-block (&optional call)
"Climb outside of a prefixed block."
(let ((containing-sexp (or (bound-and-true-p containing-sexp)
(r-containing-sexp-position))))
(or (r-save-excursion-when-nil
(and (r-goto-char containing-sexp)
(looking-at "{")
(r-climb-block-prefix call)))
(r-escape-unbraced-block call))))
(defun r-escape-unbraced-block (&optional call)
(r-save-excursion-when-nil
(while (and (not (r-unbraced-block-p))
(or (r-escape-continuations)