forked from rust-lang/rust-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rust-mode.el
2117 lines (1865 loc) · 82 KB
/
rust-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
;;; rust-mode.el --- A major emacs mode for editing Rust source code -*-lexical-binding: t-*-
;; Version: 0.5.0
;; Author: Mozilla
;; Url: https://github.com/rust-lang/rust-mode
;; Keywords: languages
;; Package-Requires: ((emacs "25.1"))
;; This file is distributed under the terms of both the MIT license and the
;; Apache License (version 2.0).
;;; Commentary:
;;
;;; Code:
(eval-when-compile (require 'rx)
(require 'compile)
(require 'url-vars))
(require 'json)
(require 'thingatpt)
(defvar electric-pair-inhibit-predicate)
(defvar electric-pair-skip-self)
(defvar electric-indent-chars)
(defvar rust-buffer-project)
(make-variable-buffer-local 'rust-buffer-project)
(defun rust-re-word (inner) (concat "\\<" inner "\\>"))
(defun rust-re-grab (inner) (concat "\\(" inner "\\)"))
(defun rust-re-shy (inner) (concat "\\(?:" inner "\\)"))
(defconst rust-re-ident "[[:word:][:multibyte:]_][[:word:][:multibyte:]_[:digit:]]*")
(defconst rust-re-lc-ident "[[:lower:][:multibyte:]_][[:word:][:multibyte:]_[:digit:]]*")
(defconst rust-re-uc-ident "[[:upper:]][[:word:][:multibyte:]_[:digit:]]*")
(defconst rust-re-unsafe "unsafe")
(defconst rust-re-extern "extern")
(defconst rust-re-async-or-const "async\\|const")
(defconst rust-re-generic
(concat "<[[:space:]]*'" rust-re-ident "[[:space:]]*>"))
(defconst rust-re-union
(rx-to-string
`(seq
(or space line-start)
(group symbol-start "union" symbol-end)
(+ space) (regexp ,rust-re-ident))))
(defvar rust-re-vis
;; pub | pub ( crate ) | pub ( self ) | pub ( super ) | pub ( in SimplePath )
(concat
"pub"
(rust-re-shy
(concat
"[[:space:]]*([[:space:]]*"
(rust-re-shy
(concat "crate" "\\|"
"\\(?:s\\(?:elf\\|uper\\)\\)" "\\|"
;; in SimplePath
(rust-re-shy
(concat
"in[[:space:]]+"
rust-re-ident
(rust-re-shy (concat "::" rust-re-ident)) "*"))))
"[[:space:]]*)"))
"?"))
;;; Start of a Rust item
(defvar rust-top-item-beg-re
(concat "\\s-*"
;; TODO some of this does only make sense for `fn' (unsafe, extern...)
;; and not other items
(rust-re-shy (concat (rust-re-shy rust-re-vis) "[[:space:]]+")) "?"
(rust-re-shy (concat (rust-re-shy rust-re-async-or-const) "[[:space:]]+")) "?"
(rust-re-shy (concat (rust-re-shy rust-re-unsafe) "[[:space:]]+")) "?"
(regexp-opt
'("enum" "struct" "union" "type" "mod" "use" "fn" "static" "impl"
"extern" "trait"))
"\\_>"))
(defun rust-looking-back-str (str)
"Return non-nil if there's a match on the text before point and STR.
Like `looking-back' but for fixed strings rather than regexps (so
that it's not so slow)."
(let ((len (length str)))
(and (> (point) len)
(equal str (buffer-substring-no-properties (- (point) len) (point))))))
(defun rust-looking-back-symbols (symbols)
"Return non-nil if the point is after a member of SYMBOLS.
SYMBOLS is a list of strings that represent the respective
symbols."
(save-excursion
(let* ((pt-orig (point))
(beg-of-symbol (progn (forward-thing 'symbol -1) (point)))
(end-of-symbol (progn (forward-thing 'symbol 1) (point))))
(and
(= end-of-symbol pt-orig)
(member (buffer-substring-no-properties beg-of-symbol pt-orig)
symbols)))))
(defun rust-looking-back-ident ()
"Non-nil if we are looking backwards at a valid rust identifier."
(let ((beg-of-symbol (save-excursion (forward-thing 'symbol -1) (point))))
(looking-back rust-re-ident beg-of-symbol)))
(defun rust-looking-back-macro ()
"Non-nil if looking back at an ident followed by a !
This is stricter than rust syntax which allows a space between
the ident and the ! symbol. If this space is allowed, then we
would also need a keyword check to avoid `if !(condition)` being
seen as a macro."
(if (> (- (point) (point-min)) 1)
(save-excursion
(backward-char)
(and (= ?! (char-after))
(rust-looking-back-ident)))))
;; Syntax definitions and helpers
(defvar rust-mode-syntax-table
(let ((table (make-syntax-table)))
;; Operators
(dolist (i '(?+ ?- ?* ?/ ?% ?& ?| ?^ ?! ?< ?> ?~ ?@))
(modify-syntax-entry i "." table))
;; Strings
(modify-syntax-entry ?\" "\"" table)
(modify-syntax-entry ?\\ "\\" table)
;; Angle brackets. We suppress this with syntactic propertization
;; when needed
(modify-syntax-entry ?< "(>" table)
(modify-syntax-entry ?> ")<" table)
;; Comments
(modify-syntax-entry ?/ ". 124b" table)
(modify-syntax-entry ?* ". 23n" table)
(modify-syntax-entry ?\n "> b" table)
(modify-syntax-entry ?\^m "> b" table)
table))
(defgroup rust-mode nil
"Support for Rust code."
:link '(url-link "https://www.rust-lang.org/")
:group 'languages)
(defcustom rust-indent-offset 4
"Indent Rust code by this number of spaces."
:type 'integer
:group 'rust-mode
:safe #'integerp)
(defcustom rust-indent-method-chain nil
"Indent Rust method chains, aligned by the `.' operators."
:type 'boolean
:group 'rust-mode
:safe #'booleanp)
(defcustom rust-indent-where-clause nil
"Indent lines starting with the `where' keyword following a function or trait.
When nil, `where' will be aligned with `fn' or `trait'."
:type 'boolean
:group 'rust-mode
:safe #'booleanp)
(defcustom rust-indent-return-type-to-arguments t
"Indent a line starting with the `->' (RArrow) following a function, aligning
to the function arguments. When nil, `->' will be indented one level."
:type 'boolean
:group 'rust-mode
:safe #'booleanp)
(defcustom rust-playpen-url-format "https://play.rust-lang.org/?code=%s"
"Format string to use when submitting code to the playpen."
:type 'string
:group 'rust-mode)
(defcustom rust-shortener-url-format "https://is.gd/create.php?format=simple&url=%s"
"Format string to use for creating the shortened link of a playpen submission."
:type 'string
:group 'rust-mode)
(defcustom rust-match-angle-brackets t
"Whether to attempt angle bracket matching (`<' and `>') where appropriate."
:type 'boolean
:safe #'booleanp
:group 'rust-mode)
(defcustom rust-format-on-save nil
"Format future rust buffers before saving using rustfmt."
:type 'boolean
:safe #'booleanp
:group 'rust-mode)
(defcustom rust-format-show-buffer t
"Show *rustfmt* buffer if formatting detected problems."
:type 'boolean
:safe #'booleanp
:group 'rust-mode)
(defcustom rust-format-goto-problem t
"Jump to location of first detected problem when formatting buffer."
:type 'boolean
:safe #'booleanp
:group 'rust-mode)
(defcustom rust-rustfmt-bin "rustfmt"
"Path to rustfmt executable."
:type 'string
:group 'rust-mode)
(defcustom rust-rustfmt-switches '("--edition" "2018")
"Arguments to pass when invoking the `rustfmt' executable."
:type '(repeat string)
:group 'rust-mode)
(defcustom rust-cargo-bin "cargo"
"Path to cargo executable."
:type 'string
:group 'rust-mode)
(defcustom rust-always-locate-project-on-open nil
"Whether to run `cargo locate-project' every time `rust-mode' is activated."
:type 'boolean
:group 'rust-mode)
(defface rust-unsafe-face
'((t :inherit font-lock-warning-face))
"Face for the `unsafe' keyword."
:group 'rust-mode)
(defface rust-question-mark-face
'((t :weight bold :inherit font-lock-builtin-face))
"Face for the question mark operator."
:group 'rust-mode)
(defface rust-builtin-formatting-macro-face
'((t :inherit font-lock-builtin-face))
"Face for builtin formatting macros (print! &c.)."
:group 'rust-mode)
(defface rust-string-interpolation-face
'((t :slant italic :inherit font-lock-string-face))
"Face for interpolating braces in builtin formatting macro strings."
:group 'rust-mode)
(defun rust-paren-level () (nth 0 (syntax-ppss)))
(defun rust-in-str () (nth 3 (syntax-ppss)))
(defun rust-in-str-or-cmnt () (nth 8 (syntax-ppss)))
(defun rust-rewind-past-str-cmnt () (goto-char (nth 8 (syntax-ppss))))
(defun rust-rewind-irrelevant ()
(let ((continue t))
(while continue
(let ((starting (point)))
(skip-chars-backward "[:space:]\n")
(when (rust-looking-back-str "*/")
(backward-char))
(when (rust-in-str-or-cmnt)
(rust-rewind-past-str-cmnt))
;; Rewind until the point no longer moves
(setq continue (/= starting (point)))))))
(defvar-local rust-macro-scopes nil
"Cache for the scopes calculated by `rust-macro-scope'.
This variable can be `let' bound directly or indirectly around
`rust-macro-scope' as an optimization but should not be otherwise
set.")
(defun rust-macro-scope (start end)
"Return the scope of macros in the buffer.
The return value is a list of (START END) positions in the
buffer.
If set START and END are optimizations which limit the return
value to scopes which are approximately with this range."
(save-excursion
;; need to special case macro_rules which has unique syntax
(let ((scope nil)
(start (or start (point-min)))
(end (or end (point-max))))
(goto-char start)
;; if there is a start move back to the previous top level,
;; as any macros before that must have closed by this time.
(let ((top (syntax-ppss-toplevel-pos (syntax-ppss))))
(when top
(goto-char top)))
(while
(and
;; The movement below may have moved us passed end, in
;; which case search-forward will error
(< (point) end)
(search-forward "!" end t))
(let ((pt (point)))
(cond
;; in a string or comment is boring, move straight on
((rust-in-str-or-cmnt))
;; in a normal macro,
((and (skip-chars-forward " \t\n\r")
(memq (char-after)
'(?\[ ?\( ?\{))
;; Check that we have a macro declaration after.
(rust-looking-back-macro))
(let ((start (point)))
(ignore-errors (forward-list))
(setq scope (cons (list start (point)) scope))))
;; macro_rules, why, why, why did you not use macro syntax??
((save-excursion
;; yuck -- last test moves point, even if it fails
(goto-char (- pt 1))
(skip-chars-backward " \t\n\r")
(rust-looking-back-str "macro_rules"))
(save-excursion
(when (re-search-forward "[[({]" nil t)
(backward-char)
(let ((start (point)))
(ignore-errors (forward-list))
(setq scope (cons (list start (point)) scope)))))))))
;; Return 'empty rather than nil, to indicate a buffer with no
;; macros at all.
(or scope 'empty))))
(defun rust-in-macro (&optional start end)
"Return non-nil when point is within the scope of a macro.
If START and END are set, minimize the buffer analysis to
approximately this location as an optimization.
Alternatively, if `rust-macro-scopes' is a list use the scope
information in this variable. This last is an optimization and
the caller is responsible for ensuring that the data in
`rust-macro-scopes' is up to date."
(when (> (rust-paren-level) 0)
(let ((scopes
(or
rust-macro-scopes
(rust-macro-scope start end))))
;; `rust-macro-scope' can return the symbol `empty' if the
;; buffer has no macros at all.
(when (listp scopes)
(seq-some
(lambda (sc)
(and (>= (point) (car sc))
(< (point) (cadr sc))))
scopes)))))
(defun rust-looking-at-where ()
"Return T when looking at the \"where\" keyword."
(and (looking-at-p "\\bwhere\\b")
(not (rust-in-str-or-cmnt))))
(defun rust-rewind-to-where (&optional limit)
"Rewind the point to the closest occurrence of the \"where\" keyword.
Return T iff a where-clause was found. Does not rewind past
LIMIT when passed, otherwise only stops at the beginning of the
buffer."
(when (re-search-backward "\\bwhere\\b" limit t)
(if (rust-in-str-or-cmnt)
(rust-rewind-to-where limit)
t)))
(defun rust-align-to-expr-after-brace ()
(save-excursion
(forward-char)
;; We don't want to indent out to the open bracket if the
;; open bracket ends the line
(when (not (looking-at "[[:blank:]]*\\(?://.*\\)?$"))
(when (looking-at "[[:space:]]")
(forward-word 1)
(backward-word 1))
(current-column))))
(defun rust-rewind-to-beginning-of-current-level-expr ()
(let ((current-level (rust-paren-level)))
(back-to-indentation)
(when (looking-at "->")
(rust-rewind-irrelevant)
(back-to-indentation))
(while (> (rust-paren-level) current-level)
(backward-up-list)
(back-to-indentation))
;; When we're in the where clause, skip over it. First find out the start
;; of the function and its paren level.
(let ((function-start nil) (function-level nil))
(save-excursion
(rust-beginning-of-defun)
(back-to-indentation)
;; Avoid using multiple-value-bind
(setq function-start (point)
function-level (rust-paren-level)))
;; On a where clause
(when (or (rust-looking-at-where)
;; or in one of the following lines, e.g.
;; where A: Eq
;; B: Hash <- on this line
(and (save-excursion
(rust-rewind-to-where function-start))
(= current-level function-level)))
(goto-char function-start)))))
(defun rust-align-to-method-chain ()
(save-excursion
;; for method-chain alignment to apply, we must be looking at
;; another method call or field access or something like
;; that. This avoids rather "eager" jumps in situations like:
;;
;; {
;; something.foo()
;; <indent>
;;
;; Without this check, we would wind up with the cursor under the
;; `.`. In an older version, I had the inverse of the current
;; check, where we checked for situations that should NOT indent,
;; vs checking for the one situation where we SHOULD. It should be
;; clear that this is more robust, but also I find it mildly less
;; annoying to have to press tab again to align to a method chain
;; than to have an over-eager indent in all other cases which must
;; be undone via tab.
(when (looking-at (concat "\s*\." rust-re-ident))
(forward-line -1)
(end-of-line)
;; Keep going up (looking for a line that could contain a method chain)
;; while we're in a comment or on a blank line. Stop when the paren
;; level changes.
(let ((level (rust-paren-level)))
(while (and (or (rust-in-str-or-cmnt)
;; Only whitespace (or nothing) from the beginning to
;; the end of the line.
(looking-back "^\s*" (point-at-bol)))
(= (rust-paren-level) level))
(forward-line -1)
(end-of-line)))
(let
;; skip-dot-identifier is used to position the point at the
;; `.` when looking at something like
;;
;; foo.bar
;; ^ ^
;; | |
;; | position of point
;; returned offset
;;
((skip-dot-identifier
(lambda ()
(when (and (rust-looking-back-ident)
(save-excursion
(forward-thing 'symbol -1)
(= ?. (char-before))))
(forward-thing 'symbol -1)
(backward-char)
(- (current-column) rust-indent-offset)))))
(cond
;; foo.bar(...)
((looking-back "[)?]" (1- (point)))
(backward-list 1)
(funcall skip-dot-identifier))
;; foo.bar
(t (funcall skip-dot-identifier)))))))
(defun rust-mode-indent-line ()
(interactive)
(let ((indent
(save-excursion
(back-to-indentation)
;; Point is now at beginning of current line
(let* ((level (rust-paren-level))
(baseline
;; Our "baseline" is one level out from the
;; indentation of the expression containing the
;; innermost enclosing opening bracket. That way
;; if we are within a block that has a different
;; indentation than this mode would give it, we
;; still indent the inside of it correctly relative
;; to the outside.
(if (= 0 level)
0
(or
(when rust-indent-method-chain
(rust-align-to-method-chain))
(save-excursion
(rust-rewind-irrelevant)
(backward-up-list)
(rust-rewind-to-beginning-of-current-level-expr)
(+ (current-column) rust-indent-offset))))))
(cond
;; Indent inside a non-raw string only if the previous line
;; ends with a backslash that is inside the same string
((nth 3 (syntax-ppss))
(let*
((string-begin-pos (nth 8 (syntax-ppss)))
(end-of-prev-line-pos
(and (not (rust--same-line-p (point) (point-min)))
(line-end-position 0))))
(when
(and
;; If the string begins with an "r" it's a raw string and
;; we should not change the indentation
(/= ?r (char-after string-begin-pos))
;; If we're on the first line this will be nil and the
;; rest does not apply
end-of-prev-line-pos
;; The end of the previous line needs to be inside the
;; current string...
(> end-of-prev-line-pos string-begin-pos)
;; ...and end with a backslash
(= ?\\ (char-before end-of-prev-line-pos)))
;; Indent to the same level as the previous line, or the
;; start of the string if the previous line starts the string
(if (rust--same-line-p end-of-prev-line-pos string-begin-pos)
;; The previous line is the start of the string.
;; If the backslash is the only character after the
;; string beginning, indent to the next indent
;; level. Otherwise align with the start of the string.
(if (> (- end-of-prev-line-pos string-begin-pos) 2)
(save-excursion
(goto-char (+ 1 string-begin-pos))
(current-column))
baseline)
;; The previous line is not the start of the string, so
;; match its indentation.
(save-excursion
(goto-char end-of-prev-line-pos)
(back-to-indentation)
(current-column))))))
;; A function return type is indented to the corresponding
;; function arguments, if -to-arguments is selected.
((and rust-indent-return-type-to-arguments
(looking-at "->"))
(save-excursion
(backward-list)
(or (rust-align-to-expr-after-brace)
(+ baseline rust-indent-offset))))
;; A closing brace is 1 level unindented
((looking-at "[]})]") (- baseline rust-indent-offset))
;; Doc comments in /** style with leading * indent to line up the *s
((and (nth 4 (syntax-ppss)) (looking-at "*"))
(+ 1 baseline))
;; When the user chose not to indent the start of the where
;; clause, put it on the baseline.
((and (not rust-indent-where-clause)
(rust-looking-at-where))
baseline)
;; If we're in any other token-tree / sexp, then:
(t
(or
;; If we are inside a pair of braces, with something after the
;; open brace on the same line and ending with a comma, treat
;; it as fields and align them.
(when (> level 0)
(save-excursion
(rust-rewind-irrelevant)
(backward-up-list)
;; Point is now at the beginning of the containing set of braces
(rust-align-to-expr-after-brace)))
;; When where-clauses are spread over multiple lines, clauses
;; should be aligned on the type parameters. In this case we
;; take care of the second and following clauses (the ones
;; that don't start with "where ")
(save-excursion
;; Find the start of the function, we'll use this to limit
;; our search for "where ".
(let ((function-start nil) (function-level nil))
(save-excursion
;; If we're already at the start of a function,
;; don't go back any farther. We can easily do
;; this by moving to the end of the line first.
(end-of-line)
(rust-beginning-of-defun)
(back-to-indentation)
;; Avoid using multiple-value-bind
(setq function-start (point)
function-level (rust-paren-level)))
;; When we're not on a line starting with "where ", but
;; still on a where-clause line, go to "where "
(when (and
(not (rust-looking-at-where))
;; We're looking at something like "F: ..."
(looking-at (concat rust-re-ident ":"))
;; There is a "where " somewhere after the
;; start of the function.
(rust-rewind-to-where function-start)
;; Make sure we're not inside the function
;; already (e.g. initializing a struct) by
;; checking we are the same level.
(= function-level level))
;; skip over "where"
(forward-char 5)
;; Unless "where" is at the end of the line
(if (eolp)
;; in this case the type parameters bounds are just
;; indented once
(+ baseline rust-indent-offset)
;; otherwise, skip over whitespace,
(skip-chars-forward "[:space:]")
;; get the column of the type parameter and use that
;; as indentation offset
(current-column)))))
(progn
(back-to-indentation)
;; Point is now at the beginning of the current line
(if (or
;; If this line begins with "else" or "{", stay on the
;; baseline as well (we are continuing an expression,
;; but the "else" or "{" should align with the beginning
;; of the expression it's in.)
;; Or, if this line starts a comment, stay on the
;; baseline as well.
(looking-at "\\<else\\>\\|{\\|/[/*]")
;; If this is the start of a top-level item,
;; stay on the baseline.
(looking-at rust-top-item-beg-re)
(save-excursion
(rust-rewind-irrelevant)
;; Point is now at the end of the previous line
(or
;; If we are at the start of the buffer, no
;; indentation is needed, so stay at baseline...
(= (point) 1)
;; ..or if the previous line ends with any of these:
;; { ? : ( , ; [ }
;; then we are at the beginning of an
;; expression, so stay on the baseline...
(looking-back "[(,:;[{}]\\|[^|]|" (- (point) 2))
;; or if the previous line is the end of an
;; attribute, stay at the baseline...
(progn (rust-rewind-to-beginning-of-current-level-expr)
(looking-at "#")))))
baseline
;; Otherwise, we are continuing the same expression from
;; the previous line, so add one additional indent level
(+ baseline rust-indent-offset))))))))))
(when indent
;; If we're at the beginning of the line (before or at the current
;; indentation), jump with the indentation change. Otherwise, save the
;; excursion so that adding the indentations will leave us at the
;; equivalent position within the line to where we were before.
(if (<= (current-column) (current-indentation))
(indent-line-to indent)
(save-excursion (indent-line-to indent))))))
(defun rust--same-line-p (pos1 pos2)
"Return non-nil if POS1 and POS2 are on the same line."
(save-excursion (= (progn (goto-char pos1) (line-end-position))
(progn (goto-char pos2) (line-end-position)))))
;; Font-locking definitions and helpers
(defconst rust-mode-keywords
'("as" "async" "await"
"box" "break"
"const" "continue" "crate"
"do" "dyn"
"else" "enum" "extern"
"false" "fn" "for"
"if" "impl" "in"
"let" "loop"
"match" "mod" "move" "mut"
"priv" "pub"
"ref" "return"
"self" "static" "struct" "super"
"true" "trait" "type" "try"
"use"
"virtual"
"where" "while"
"yield"))
(defconst rust-special-types
'("u8" "i8"
"u16" "i16"
"u32" "i32"
"u64" "i64"
"u128" "i128"
"f32" "f64"
"isize" "usize"
"bool"
"str" "char"))
(defconst rust-re-type-or-constructor
(rx symbol-start
(group upper (0+ (any word nonascii digit "_")))
symbol-end))
(defconst rust-re-pre-expression-operators "[-=!%&*/:<>[{(|.^;}]")
(defun rust-re-item-def (itype)
(concat (rust-re-word itype)
(rust-re-shy rust-re-generic) "?"
"[[:space:]]+" (rust-re-grab rust-re-ident)))
;; TODO some of this does only make sense for `fn' (unsafe, extern...)
;; and not other items
(defun rust-re-item-def-imenu (itype)
(concat "^[[:space:]]*"
(rust-re-shy (concat rust-re-vis "[[:space:]]+")) "?"
(rust-re-shy (concat (rust-re-word "default") "[[:space:]]+")) "?"
(rust-re-shy (concat (rust-re-shy rust-re-async-or-const) "[[:space:]]+")) "?"
(rust-re-shy (concat (rust-re-word rust-re-unsafe) "[[:space:]]+")) "?"
(rust-re-shy (concat (rust-re-word rust-re-extern) "[[:space:]]+"
(rust-re-shy "\"[^\"]+\"[[:space:]]+") "?")) "?"
(rust-re-item-def itype)))
(defconst rust-re-special-types (regexp-opt rust-special-types 'symbols))
(defun rust-path-font-lock-matcher (re-ident)
"Match occurrences of RE-IDENT followed by a double-colon.
Examples include to match names like \"foo::\" or \"Foo::\".
Does not match type annotations of the form \"foo::<\"."
`(lambda (limit)
(catch 'rust-path-font-lock-matcher
(while t
(let* ((symbol-then-colons (rx-to-string '(seq (group (regexp ,re-ident)) "::")))
(match (re-search-forward symbol-then-colons limit t)))
(cond
;; If we didn't find a match, there are no more occurrences
;; of foo::, so return.
((null match) (throw 'rust-path-font-lock-matcher nil))
;; If this isn't a type annotation foo::<, we've found a
;; match, so a return it!
((not (looking-at (rx (0+ space) "<")))
(throw 'rust-path-font-lock-matcher match))))))))
(defun rust-next-string-interpolation (limit)
"Search forward from point for the next Rust interpolation marker before LIMIT.
Set point to the end of the occurrence found, and return match beginning
and end."
(catch 'match
(save-match-data
(save-excursion
(while (search-forward "{" limit t)
(if (eql (char-after (point)) ?{)
(forward-char)
(let ((start (match-beginning 0)))
;; According to fmt_macros::Parser::next, an opening brace
;; must be followed by an optional argument and/or format
;; specifier, then a closing brace. A single closing brace
;; without a corresponding unescaped opening brace is an
;; error. We don't need to do anything special with
;; arguments, specifiers, or errors, so we only search for
;; the single closing brace.
(when (search-forward "}" limit t)
(throw 'match (list start (point)))))))))))
(defun rust-string-interpolation-matcher (limit)
"Match the next Rust interpolation marker before LIMIT; set match data if found.
Returns nil if the point is not within a Rust string."
(when (rust-in-str)
(let ((match (rust-next-string-interpolation limit)))
(when match
(set-match-data match)
(goto-char (cadr match))
match))))
(defvar rust-builtin-formatting-macros
'("eprint"
"eprintln"
"format"
"print"
"println")
"List of builtin Rust macros for string formatting.
This is used by `rust-mode-font-lock-keywords'.
(`write!' is handled separately).")
(defvar rust-formatting-macro-opening-re
"[[:space:]\n]*[({[][[:space:]\n]*"
"Regular expression to match the opening delimiter of a Rust formatting macro.")
(defvar rust-start-of-string-re
"\\(?:r#*\\)?\""
"Regular expression to match the start of a Rust raw string.")
(defvar rust-mode-font-lock-keywords
(append
`(
;; Keywords proper
(,(regexp-opt rust-mode-keywords 'symbols) . font-lock-keyword-face)
;; Contextual keywords
("\\_<\\(default\\)[[:space:]]+fn\\_>" 1 font-lock-keyword-face)
(,rust-re-union 1 font-lock-keyword-face)
;; Special types
(,(regexp-opt rust-special-types 'symbols) . font-lock-type-face)
;; The unsafe keyword
("\\_<unsafe\\_>" . 'rust-unsafe-face)
;; Attributes like `#[bar(baz)]` or `#![bar(baz)]` or `#[bar = "baz"]`
(,(rust-re-grab (concat "#\\!?\\[" rust-re-ident "[^]]*\\]"))
1 font-lock-preprocessor-face keep)
;; Builtin formatting macros
(,(concat (rust-re-grab
(concat (rust-re-word (regexp-opt rust-builtin-formatting-macros))
"!"))
(concat rust-formatting-macro-opening-re
"\\(?:" rust-start-of-string-re) "\\)?")
(1 'rust-builtin-formatting-macro-face)
(rust-string-interpolation-matcher
(rust-end-of-string)
nil
(0 'rust-string-interpolation-face t nil)))
;; write! macro
(,(concat (rust-re-grab (concat (rust-re-word "write\\(ln\\)?") "!"))
(concat rust-formatting-macro-opening-re
"[[:space:]]*[^\"]+,[[:space:]]*" rust-start-of-string-re))
(1 'rust-builtin-formatting-macro-face)
(rust-string-interpolation-matcher
(rust-end-of-string)
nil
(0 'rust-string-interpolation-face t nil)))
;; Syntax extension invocations like `foo!`, highlight including the !
(,(concat (rust-re-grab (concat rust-re-ident "!")) "[({[:space:][]")
1 font-lock-preprocessor-face)
;; Field names like `foo:`, highlight excluding the :
(,(concat (rust-re-grab rust-re-ident) "[[:space:]]*:[^:]")
1 font-lock-variable-name-face)
;; CamelCase Means Type Or Constructor
(,rust-re-type-or-constructor 1 font-lock-type-face)
;; Type-inferred binding
(,(concat "\\_<\\(?:let\\s-+ref\\|let\\|ref\\|for\\)\\s-+\\(?:mut\\s-+\\)?"
(rust-re-grab rust-re-ident) "\\_>") 1 font-lock-variable-name-face)
;; Type names like `Foo::`, highlight excluding the ::
(,(rust-path-font-lock-matcher rust-re-uc-ident) 1 font-lock-type-face)
;; Module names like `foo::`, highlight excluding the ::
(,(rust-path-font-lock-matcher rust-re-lc-ident) 1 font-lock-constant-face)
;; Lifetimes like `'foo`
(,(concat "'" (rust-re-grab rust-re-ident) "[^']") 1 font-lock-variable-name-face)
;; Question mark operator
("\\?" . 'rust-question-mark-face)
)
;; Ensure we highlight `Foo` in `struct Foo` as a type.
(mapcar #'(lambda (x)
(list (rust-re-item-def (car x))
1 (cdr x)))
'(("enum" . font-lock-type-face)
("struct" . font-lock-type-face)
("union" . font-lock-type-face)
("type" . font-lock-type-face)
("mod" . font-lock-constant-face)
("use" . font-lock-constant-face)
("fn" . font-lock-function-name-face)))))
(defun rust-syntax-class-before-point ()
(when (> (point) 1)
(syntax-class (syntax-after (1- (point))))))
(defun rust-rewind-qualified-ident ()
(while (rust-looking-back-ident)
(backward-sexp)
(when (save-excursion (rust-rewind-irrelevant) (rust-looking-back-str "::"))
(rust-rewind-irrelevant)
(backward-char 2)
(rust-rewind-irrelevant))))
(defun rust-rewind-type-param-list ()
(cond
((and (rust-looking-back-str ">") (equal 5 (rust-syntax-class-before-point)))
(backward-sexp)
(rust-rewind-irrelevant))
;; We need to be able to back up past the Fn(args) -> RT form as well. If
;; we're looking back at this, we want to end up just after "Fn".
((member (char-before) '(?\] ?\) ))
(let* ((is-paren (rust-looking-back-str ")"))
(dest (save-excursion
(backward-sexp)
(rust-rewind-irrelevant)
(or
(when (rust-looking-back-str "->")
(backward-char 2)
(rust-rewind-irrelevant)
(when (rust-looking-back-str ")")
(backward-sexp)
(point)))
(and is-paren (point))))))
(when dest
(goto-char dest))))))
(defun rust-rewind-to-decl-name ()
"Return the point at the beginning of the name in a declaration.
I.e. if we are before an ident that is part of a declaration that
can have a where clause, rewind back to just before the name of
the subject of that where clause and return the new point.
Otherwise return nil."
(let* ((ident-pos (point))
(newpos (save-excursion
(rust-rewind-irrelevant)
(rust-rewind-type-param-list)
(cond
((rust-looking-back-symbols
'("fn" "trait" "enum" "struct" "union" "impl" "type"))
ident-pos)
((equal 5 (rust-syntax-class-before-point))
(backward-sexp)
(rust-rewind-to-decl-name))
((looking-back "[:,'+=]" (1- (point)))
(backward-char)
(rust-rewind-to-decl-name))
((rust-looking-back-str "->")
(backward-char 2)
(rust-rewind-to-decl-name))
((rust-looking-back-ident)
(rust-rewind-qualified-ident)
(rust-rewind-to-decl-name))))))
(when newpos (goto-char newpos))
newpos))
(defun rust-is-in-expression-context (token)
"Return t if what comes right after the point is part of an
expression (as opposed to starting a type) by looking at what
comes before. Takes a symbol that roughly indicates what is
after the point.
This function is used as part of `rust-is-lt-char-operator' as
part of angle bracket matching, and is not intended to be used
outside of this context."
(save-excursion
(let ((postchar (char-after)))
(rust-rewind-irrelevant)
;; A type alias or ascription could have a type param list. Skip backwards past it.
(when (member token '(ambiguous-operator open-brace))
(rust-rewind-type-param-list))
(cond
;; Certain keywords always introduce expressions
((rust-looking-back-symbols '("if" "while" "match" "return" "box" "in")) t)
;; "as" introduces a type
((rust-looking-back-symbols '("as")) nil)
;; An open angle bracket never introduces expression context WITHIN the angle brackets
((and (equal token 'open-brace) (equal postchar ?<)) nil)
;; An ident! followed by an open brace is a macro invocation. Consider
;; it to be an expression.
((and (equal token 'open-brace) (rust-looking-back-macro)) t)
;; In a brace context a "]" introduces an expression.
((and (eq token 'open-brace) (rust-looking-back-str "]")))
;; An identifier is right after an ending paren, bracket, angle bracket
;; or curly brace. It's a type if the last sexp was a type.
((and (equal token 'ident) (equal 5 (rust-syntax-class-before-point)))
(backward-sexp)
(rust-is-in-expression-context 'open-brace))
;; If a "for" appears without a ; or { before it, it's part of an
;; "impl X for y", so the y is a type. Otherwise it's
;; introducing a loop, so the y is an expression
((and (equal token 'ident) (rust-looking-back-symbols '("for")))
(backward-sexp)
(rust-rewind-irrelevant)
(looking-back "[{;]" (1- (point))))
((rust-looking-back-ident)
(rust-rewind-qualified-ident)
(rust-rewind-irrelevant)
(cond
((equal token 'open-brace)
;; We now know we have:
;; ident <maybe type params> [{([]