-
Notifications
You must be signed in to change notification settings - Fork 47
/
swift-mode-lexer.el
1736 lines (1549 loc) · 64.2 KB
/
swift-mode-lexer.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
;;; swift-mode-lexer.el --- Major-mode for Apple's Swift programming language, lexer. -*- lexical-binding: t -*-
;; Copyright (C) 2014-2021 taku0, Chris Barrett, Bozhidar Batsov,
;; Arthur Evstifeev
;; Author: taku0 (http://github.com/taku0)
;; Chris Barrett <[email protected]>
;; Bozhidar Batsov <[email protected]>
;; Arthur Evstifeev <[email protected]>
;; This file is not part of GNU Emacs.
;; This program 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 3 of the License, or
;; (at your option) any later version.
;; This program 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.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Routines for Swift tokens
;; Token is a tuple consists of:
;;
;; - Token type
;; - Token text
;; - Start position (inclusive)
;; - End position (exclusive)
;;; Code:
;; Terminology:
;; (See also docs/string.png)
;;
;; Interpolated string:
;; A string containing expressions to be evaluated and inserted into the
;; string at run time.
;; Example: "1 + 1 = \(1 + 1)" is evaluated to "1 + 1 = 2" at run time.
;; https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
;; https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html
;;
;; Interpolated expression:
;; An expression between \( and ) inside a string.
;; Suppose a string "aaa\( foo() )bbb\( bar() )ccc",
;; `foo()' and `bar()' are interpolated expression.
;; https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html
;; Why not interpolating expression?
;;
;; String chunk:
;; A part of single-line/multiline string delimited with quotation marks
;; or interpolated expressions.
;; Suppose a string "aaa\( foo() )bbb\( bar() )ccc",
;; "aaa\(, )bbb\(, and )ccc" are string chunks.
;;
;; This is not a official term; used only in swift-mode.
(declare-function swift-mode:backward-sexps-until "swift-mode-indent.el"
(token-types
&optional
stop-at-eol-token-types
stop-at-bol-token-types))
(declare-function swift-mode:try-backward-generic-parameters
"swift-mode-indent.el"
())
(defun swift-mode:token (type text start end)
"Construct and return a token.
TYPE is the type of the token such as `binary-operator' or {.
TEXT is the text of the token.
START is the start position of the token.
END is the point after the token."
(list type text start end))
(defun swift-mode:token:type (token)
"Return the type of TOKEN."
(nth 0 token))
(defun swift-mode:token:text (token)
"Return the text of TOKEN."
(nth 1 token))
(defun swift-mode:token:start (token)
"Return the start position of TOKEN."
(nth 2 token))
(defun swift-mode:token:end (token)
"Return the end position of TOKEN."
(nth 3 token))
;; Token types is one of the following symbols:
;;
;; - prefix-operator (including try, try?, try!, await, consume, copy, discard,
;; and each)
;; - postfix-operator
;; - binary-operator (including as, as?, as!, is, =, ., and ->)
;; - attribute (e.g. @objc, @abc(def))
;; - identifier (including keywords, numbers, implicit parameters, and unknown
;; tokens)
;; - [
;; - ]
;; - {
;; - }
;; - (
;; - )
;; - ,
;; - ;
;; - implicit-;
;; - < (as an angle bracket)
;; - > (as an angle bracket)
;; - supertype-: (colon for supertype declaration or type declaration of let or
;; var)
;; - case-: (colon for case or default label)
;; - : (part of conditional operator, key-value separator, label-statement
;; separator)
;; - anonymous-function-parameter-in ("in" after anonymous function parameter)
;; - string-chunk-after-interpolated-expression (part of a string starting with
;; ")")
;; - string-chunk-before-interpolated-expression (part of a string ending with
;; "\\(")
;; - outside-of-buffer
;;
;; Additionally, `swift-mode:backward-token-or-list' may return a parenthesized
;; expression as a token with one of the following types:
;; - ()
;; - []
;; - {}
;; - <>
;;; Syntax table
(defconst swift-mode:syntax-table
(let ((table (make-syntax-table)))
;; Whitespace characters
;; Word constituents
;; Symbol constituents
(modify-syntax-entry ?_ "_" table)
(modify-syntax-entry ?$ "_" table)
(modify-syntax-entry ?@ "_" table)
(modify-syntax-entry ?# "_" table)
;; Punctuation characters
;;
;; Operators
;; https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
;; TODO Unicode operators
;;
;; / and * will be overridden below as comment delimiters
(mapc (lambda (c) (modify-syntax-entry c "." table)) "/=-+!*%<>&|^~?.")
;; Separators
(mapc (lambda (c) (modify-syntax-entry c "." table)) ",;")
;; Parenthesis characters
(modify-syntax-entry ?\( "()" table)
(modify-syntax-entry ?\) ")(" table)
(modify-syntax-entry ?\[ "(]" table)
(modify-syntax-entry ?\] ")[" table)
(modify-syntax-entry ?{ "(}" table)
(modify-syntax-entry ?} "){" table)
;; String quotes
(modify-syntax-entry ?\" "\"" table)
(modify-syntax-entry ?` "\"" table)
;; Escape-syntax characters
(modify-syntax-entry ?\\ "\\" table)
;; Character quotes
;; Paired delimiters
;; Expression prefixes
;; Comments
(modify-syntax-entry ?/ ". 124b" table)
(modify-syntax-entry ?* ". 23n" table)
(modify-syntax-entry ?\n "> b" table)
(modify-syntax-entry ?\r "> b" table)
table))
;;; Text properties
;; (See also docs/string_properties.png)
;;
;; Some properties are put by `syntax-propertize-function', that is
;; `swift-mode:syntax-propertize'.
;;
;; The beginning of and end of strings are marked with text property
;; '(syntax-table (15)), which indicates generic string delimiters. Both
;; single-line strings and multiline strings are marked with it. The
;; parentheses surrounding interpolated expressions are also marked with
;; '(syntax-table (15)). The property helps font-lock and the tokenizer to
;; recognize strings.
;;
;; The entire string, including interpolated expressions, are marked with text
;; property '(syntax-multiline t). The property is used by
;; `swift-mode:syntax-propertize-extend-region' to avoid scanning from the
;; middle of strings.
;;
;; The parentheses surrounding interpolated expressions have text property
;; '(swift-mode:matching-parenthesis POS), where POS is the position of the
;; matching parenthesis. Strictly speaking, the POS on the closing parenthesis
;; refers to the backslash before the opening parenthesis. The property speeds
;; up the indentation logic.
(defun swift-mode:syntax-propertize-extend-region (start end)
"Return region to be propertized.
The returned region contains the region (START . END).
If the region is not modified, return nil.
Intended for `syntax-propertize-extend-region-functions'."
(syntax-propertize-multiline start end))
(defun swift-mode:syntax-propertize (start end)
"Update text properties for strings.
Mark the beginning of and the end of single-line/multiline strings and regexes
between the position START and END as general string delimiters.
Intended for `syntax-propertize-function'."
(remove-text-properties start end
'(syntax-table
nil
syntax-multiline
nil
swift-mode:matching-parenthesis
nil
swift-mode:comment
nil))
(let* ((chunk (swift-mode:chunk-after (syntax-ppss start)))
comment-start)
(cond
((swift-mode:chunk:multiline-string-p chunk)
(swift-mode:syntax-propertize:end-of-string
end "\"\"\"" (swift-mode:chunk:pound-count chunk)))
((swift-mode:chunk:single-line-string-p chunk)
(swift-mode:syntax-propertize:end-of-string
end "\"" (swift-mode:chunk:pound-count chunk)))
((swift-mode:chunk:regex-p chunk)
(swift-mode:syntax-propertize:end-of-regex
(swift-mode:chunk:start chunk)))
((swift-mode:chunk:comment-p chunk)
(goto-char (swift-mode:chunk:start chunk))
(setq comment-start (point))
(forward-comment 1)
(put-text-property comment-start (point) 'swift-mode:comment t))))
(swift-mode:syntax-propertize:scan end 0))
(defun swift-mode:syntax-propertize:scan (end nesting-level)
"Update text properties for strings.
Mark the beginning of and the end of single-line/multiline strings and regexes
between the current position and END as general string delimiters.
Assuming the cursor is not on strings, regexes, nor comments.
If NESTING-LEVEL is non-zero, nesting of parentheses are tracked and the scan
stops where the level becomes zero."
(let ((found-matching-parenthesis nil)
(pattern (mapconcat #'regexp-quote
'("\"\"\"" "\"" "/" "(" ")")
"\\|")))
(while (and (not found-matching-parenthesis)
(< (point) end)
(search-forward-regexp pattern end t))
(cond
((member (match-string-no-properties 0) '("\"\"\"" "\""))
(let ((start (match-beginning 0))
(quotation (match-string-no-properties 0))
pound-count)
(save-excursion
(goto-char start)
(skip-chars-backward "#")
(setq pound-count (- start (point)))
(setq start (point)))
(put-text-property start (1+ start)
'syntax-table
(string-to-syntax "|"))
(swift-mode:syntax-propertize:end-of-string
end quotation pound-count)
(swift-mode:put-syntax-multiline-property start (point))))
((equal "/" (match-string-no-properties 0))
(let ((start (match-beginning 0))
regex-start)
(save-excursion
(goto-char start)
(skip-chars-backward "#")
(setq regex-start (point)))
(cond
;; Regexes
((swift-mode:syntax-propertize:end-of-regex regex-start)
(put-text-property regex-start (1+ regex-start)
'syntax-table
(string-to-syntax "|"))
(swift-mode:put-syntax-multiline-property regex-start (point)))
;; Comments
((memq (char-after) '(?/ ?*))
(goto-char start)
(forward-comment 1)
(put-text-property start (point) 'swift-mode:comment t))
;; Operators
(t nil))))
((and (equal "(" (match-string-no-properties 0))
(/= nesting-level 0))
(setq nesting-level (1+ nesting-level)))
((and (equal ")" (match-string-no-properties 0))
(/= nesting-level 0))
(setq nesting-level (1- nesting-level))
(when (= nesting-level 0)
(setq found-matching-parenthesis t)))))
(unless found-matching-parenthesis
(goto-char end))
found-matching-parenthesis))
(defun swift-mode:put-syntax-multiline-property (start end)
"Put `syntax-multiline` text propery from START to END.
Also call `font-lock-flush' with START and END."
(put-text-property start end 'syntax-multiline t)
(if (fboundp 'font-lock-flush)
(font-lock-flush start end)
(if (eq font-lock-fontify-buffer-function #'jit-lock-refontify)
(jit-lock-refontify start end)
(font-lock-after-change-function start end (- end start)))))
(defun swift-mode:syntax-propertize:end-of-string (end quotation pound-count)
"Move point to the end of single-line/multiline string.
Assuming the cursor is on a string.
If the string go beyond END, stop there.
The string should be terminated with QUOTATION, followed by POUND-COUNT of
pound signs."
(if (and
(< (point) end)
(search-forward-regexp (concat (regexp-quote quotation) "\\|(") end t))
(cond
((and (equal quotation (match-string-no-properties 0))
(not (swift-mode:escaped-p (match-beginning 0) pound-count))
(progn
(skip-chars-forward "#" (min end (+ (point) pound-count)))
(= (- (point) (match-end 0)) pound-count)))
(put-text-property (1- (point)) (point)
'syntax-table
(string-to-syntax "|")))
((and (equal "(" (match-string-no-properties 0))
(swift-mode:escaped-p (match-beginning 0) pound-count))
;; Found an interpolated expression. Skips the expression.
;; We cannot use `scan-sexps' because multiline strings are not yet
;; propertized.
(let ((pos-after-open-paren (point))
(start
(save-excursion
(backward-char) ;; (
(skip-chars-backward "#")
(backward-char) ;; \
(point))))
;; Declares the backslash is not a escape-syntax characters.
(put-text-property start (1+ start)
'syntax-table
(string-to-syntax "w"))
;; Declares the open parentheses is a generic string delimiter.
(put-text-property (1- pos-after-open-paren) pos-after-open-paren
'syntax-table
(string-to-syntax "|"))
(when (swift-mode:syntax-propertize:scan end 1)
;; Found the matching parenthesis. Going further.
;; Declares the close parentheses is a generic string delimiter.
(put-text-property (1- (point)) (point)
'syntax-table
(string-to-syntax "|"))
;; Records the positions.
(put-text-property (1- (point)) (point)
'swift-mode:matching-parenthesis
start)
(put-text-property start pos-after-open-paren
'swift-mode:matching-parenthesis
(1- (point)))
(swift-mode:syntax-propertize:end-of-string
end quotation pound-count))))
(t
(swift-mode:syntax-propertize:end-of-string end quotation pound-count)))
(goto-char end)))
(defun swift-mode:escaped-p (position pound-count)
"Return t if the POSITION in a string is escaped.
A position is escaped if it is proceeded by POUND-COUNT or more of pound signs
and odd number of backslashes.
Return nil otherwise."
(let ((p position)
(backslash-count 0))
(while (eq (char-before p) ?#)
(setq p (1- p)))
(and
;; While it is a syntax error to have extra pound signs, we allow them
;; here to prevent corruption.
(<= pound-count (- position p))
(progn
(while (eq (char-before p) ?\\)
(setq backslash-count (1+ backslash-count))
(setq p (1- p)))
(= (mod backslash-count 2) 1)))))
(defun swift-mode:syntax-propertize:end-of-regex (start)
"Move point to the end of regex if any.
START is the position of the open delimiter, including pounds if any.
If START is not a start of a regex, keep the point and return nil. Otherwise,
return non-nil.
This function doesn't take end parameter since if the closing delimiter is
missing, this function must return nil."
(let* ((pound-count (save-excursion
(goto-char start)
(skip-chars-forward "#")
(- (point) start)))
end-of-regex)
(setq end-of-regex
(if (zerop pound-count)
(swift-mode:syntax-propertize:end-of-basic-regex start)
(swift-mode:syntax-propertize:end-of-extended-regex
start
pound-count)))
(when end-of-regex
(put-text-property (1- end-of-regex) end-of-regex
'syntax-table
(string-to-syntax "|")))
end-of-regex))
(defun swift-mode:syntax-propertize:end-of-basic-regex (start)
"Move point to the end of regex if any.
START is the position of the open delimiter.
If START is not a start of a regex, keep the point and return nil. Otherwise,
return non-nil."
(let* ((pos (point))
(start-of-contents (1+ start))
after-last-dot
(square-brackets-count 0)
(parentheses-count 0)
(limit (line-end-position))
(end-of-regex nil))
(if (or
;; Cannot starts with spaces, tabs, slashes, or asterisks.
(memq (char-after start-of-contents) '(?\s ?\t ?/ ?*))
;; Cannot be a comment closer: /**/+++/.
(get-text-property start 'swift-mode:comment)
;; Cannot be preceded with infix operators while it can be preceded
;; with prefix operators.
(save-excursion
(goto-char start)
;; TODO Unicode operators
(skip-chars-backward "-/=+!*%<>&|^~?")
(when (eq (char-before) ?.)
(setq after-last-dot (point))
(skip-chars-backward "-/=+!*%<>&|^~?.")
(unless (eq (char-after) ?.)
(goto-char (1- after-last-dot))))
(and
;; preceded with an operator
(/= start (point))
;; it is not a prefix operator
(not (memq (char-before)
'(nil ?\s ?\t ?\[ ?\( ?{ ?, ?\; ?:)))
;; it does't contain comments: a/**/+/**//b /
(not (text-property-any (point) start 'swift-mode:comment t)))))
nil
(goto-char start-of-contents)
(while (and (null end-of-regex)
(search-forward-regexp "[][()\\/]" limit t))
(cond
((eq (char-before) ?\\)
(forward-char))
((eq (char-before) ?\[)
(setq square-brackets-count (1+ square-brackets-count)))
((eq (char-before) ?\])
(when (< 0 square-brackets-count)
(setq square-brackets-count (1- square-brackets-count))))
((eq (char-before) ?\()
(when (zerop square-brackets-count)
(setq parentheses-count (1+ parentheses-count))))
((eq (char-before) ?\))
(cond
((< 0 square-brackets-count)
nil)
((zerop parentheses-count)
;; Found an unmatching close parenthesis. This is not a regex
;; literal.
(goto-char limit))
(t
(setq parentheses-count (1- parentheses-count)))))
((eq (char-before) ?/)
(if (memq (char-after) '(?/ ?*))
(goto-char limit)
(setq end-of-regex (point)))))))
(when (and end-of-regex
(memq (char-before (1- end-of-regex)) '(?\s ?\t))
(not (swift-mode:escaped-p (- end-of-regex 2) 0)))
;; Cannot ends with spaces or tabs unless escaped.
(setq end-of-regex nil))
(unless end-of-regex
(goto-char pos))
end-of-regex))
(defun swift-mode:syntax-propertize:end-of-extended-regex (start pound-count)
"Move point to the end of extended regex if any.
START is the position of the open delimiter, including pounds of POUND-COUNT.
If START is not a start of a regex, keep the point and return nil. Otherwise,
return non-nil."
(let* ((pos (point))
(start-of-contents (1+ (+ start pound-count)))
(starts-with-line-break (save-excursion
(goto-char start-of-contents)
(skip-chars-forward "\s\t")
(eolp)))
(end-of-regex nil))
(goto-char start-of-contents)
(if starts-with-line-break
(while (and (null end-of-regex)
(zerop (forward-line)))
(skip-chars-forward "\s\t")
(when (and (eq (char-after) ?/)
(progn
(forward-char)
(eq (skip-chars-forward "#" (+ (point) pound-count))
pound-count)))
(setq end-of-regex (point))))
(while (and (null end-of-regex)
(search-forward-regexp "/#" (line-end-position) t))
(backward-char)
(when (and (eq (skip-chars-forward "#" (+ (point) pound-count))
pound-count)
;; Inside regex literal, backslashes without pounds are
;; still special.
(not (swift-mode:escaped-p (match-beginning 0) 0)))
(setq end-of-regex (point)))))
(unless end-of-regex
(swift-mode:put-syntax-multiline-property start (point))
(goto-char pos))
end-of-regex))
;;; Lexers
(defun swift-mode:implicit-semi-p ()
"Return t if the cursor is after the end of a statement."
(let
((previous-token (save-excursion
(swift-mode:backquote-identifier-if-after-dot
(swift-mode:backward-token-simple))))
(next-token (save-excursion
(swift-mode:backquote-identifier-if-after-dot
(swift-mode:forward-token-simple)))))
;; If the cursor is on the empty line, pretend an identifier is on the line.
(when (and
(< (swift-mode:token:end previous-token) (line-beginning-position))
(< (line-end-position) (swift-mode:token:start next-token)))
(setq next-token (swift-mode:token 'identifier "" (point) (point))))
(cond
((or
;; Suppresses implicit semicolon around binary operators and separators.
(memq (swift-mode:token:type previous-token)
'(binary-operator \; \, :))
(memq (swift-mode:token:type next-token)
'(binary-operator \; \, :))
;; Suppresses implicit semicolon after try, try?, try!, and await.
(member (swift-mode:token:text previous-token)
'("try" "try?" "try!" "await"))
;; Suppress implicit semicolon after open brackets or before close
;; brackets.
(memq (swift-mode:token:type previous-token) '({ \( \[))
(memq (swift-mode:token:type next-token) '(} \) \]))
;; Supress implicit semicolon before/after open angle bracket.
(and (equal (swift-mode:token:text previous-token) "<")
(save-excursion
(goto-char (swift-mode:token:start previous-token))
(swift-mode:generic-parameter-clause-start-p)))
(and (equal (swift-mode:token:text next-token) "<")
(save-excursion
(goto-char (swift-mode:token:start next-token))
(swift-mode:generic-parameter-clause-start-p)))
;; Suppress implicit semicolon after/before string chunks inside
;; interpolated expressions.
(eq (swift-mode:token:type previous-token)
'string-chunk-before-interpolated-expression)
(eq (swift-mode:token:type next-token)
'string-chunk-after-interpolated-expression)
;; Suppress implicit semicolon around keywords that cannot start or end
;; statements.
(member (swift-mode:token:text previous-token)
'("any" "some" "inout" "borrowing" "consuming" "sending" "in"
"where" "isolated" "each"))
(member (swift-mode:token:text next-token)
'("any" "some" "inout" "borrowing" "consuming" "sending" "throws"
"rethrows" "in" "where" "isolated" "each"))
;; Suppress implicit semicolon between throws and open parenthesis.
(and (equal (swift-mode:token:text previous-token) "throws")
(eq (swift-mode:token:type next-token) '\()))
nil)
;; Before async
;;
;; Examples:
;;
;; func foo() async throws -> Void
;; foo { () async throws -> void in }
;; let f: () async throws -> Void = g
;; get async throws {}
;; async let x = foo()
;;
;; Suppresses implicit semicolon if and only if before let.
;;
;; Example:
;;
;; let a = f as (Int, Int)
;; async -> Int
;; let b = t as (Int, Int)
;; async
;; let c = 1
((equal (swift-mode:token:text next-token) "async")
(equal (swift-mode:token:text (save-excursion
(swift-mode:forward-token-simple)
(swift-mode:forward-token-simple)))
"let"))
;; After async
;;
;; Suppresses implicit semicolon if before let.
((and (equal (swift-mode:token:text previous-token) "async")
(equal (swift-mode:token:text next-token) "let"))
nil)
;; Suppress implicit semicolon around else
((or
(equal (swift-mode:token:text previous-token) "else")
(equal (swift-mode:token:text next-token) "else"))
nil)
;; Inserts semicolon before open curly bracket.
;;
;; Open curly bracket may continue the previous line, but we do not indent
;; there. For example, the code below is parsed as `(foo() { x in ... })'
;; by the Swift compiler, but we indent it like `foo(); { x in ... }'.
;;
;; foo()
;; { // does not indent here
;; x in
;; ...
;; }
((eq (swift-mode:token:type next-token) '\{) t)
;; Suppress implicit semicolon after attributes.
((eq (swift-mode:token:type previous-token) 'attribute)
nil)
;; Suppress implicit semicolon after modifiers.
((member (swift-mode:token:text previous-token)
'("indirect" "convenience" "dynamic" "final" "infix" "lazy"
"mutating" "nonmutating" "optional" "override" "postfix"
"prefix" "required" "static" "unowned" "weak" "internal"
"package" "private" "public" "open" "fileprivate" "nonisolated"
"distributed"))
nil)
;; internal(set) private(set) public(set) open(set) fileprivate(set)
;; unowned(safe) unowned(unsafe) nonisolated(unsafe)
((and
(eq (swift-mode:token:type previous-token) '\))
(save-excursion
(and
(eq (swift-mode:token:type (swift-mode:backward-token-simple)) '\))
(member (swift-mode:token:text (swift-mode:backward-token-simple))
'("set" "safe" "unsafe"))
(eq (swift-mode:token:type (swift-mode:backward-token-simple)) '\()
(member (swift-mode:token:text
(swift-mode:backquote-identifier-if-after-dot
(swift-mode:backward-token-simple)))
'("unowned" "internal" "private" "public" "open"
"fileprivate" "nonisolated")))))
nil)
;; Suppress implicit semicolon after declaration starters.
((member (swift-mode:token:text previous-token)
'("class" "struct" "actor" "protocol" "enum" "extension" "func"
"typealias" "associatedtype" "precedencegroup" "operator"
"macro"))
nil)
;; Insert implicit semicolon before modifiers.
;;
;; Preceding modifiers takes precedence over this.
((member (swift-mode:token:text next-token)
'("indirect" "convenience" "dynamic" "final" "infix" "lazy"
"mutating" "nonmutating" "optional" "override" "postfix"
"prefix" "required" "static" "unowned" "weak" "internal"
"package" "private" "public" "open" "fileprivate" "nonisolated"
"distributed"))
t)
;; Inserts implicit semicolon around keywords that forms single keyword
;; statements.
((or
(member (swift-mode:token:text previous-token)
'("break" "continue" "fallthrough"))
(member (swift-mode:token:text next-token)
'("break" "continue" "fallthrough")))
t)
;; Suppress implicit semicolon after keywords that cannot end statements.
((member (swift-mode:token:text previous-token)
'("while" "for" "switch" "case" "default" "catch" "if" "guard"
"let" "var" "throw" "import"))
nil)
;; Suppress import semicolon after `repeat' unless followed by a open
;; curly bracket.
((and (equal (swift-mode:token:text previous-token) "repeat")
(not (eq (swift-mode:token:type next-token) '{)))
nil)
;; Inserts implicit semicolon before keywords that starts a new
;; statement.
((member (swift-mode:token:text next-token)
'("for" "repeat" "case" "default" "defer" "do"
"guard" "let" "var" "throw" "import" "return"))
t)
;; Suppress implicit semicolon after return.
((equal (swift-mode:token:text previous-token) "return")
nil)
;; Inserts implicit semicolon before `while' unless it is part of
;; `repeat...while'.
((equal (swift-mode:token:text next-token) "while")
(save-excursion
(not
(and
(eq (swift-mode:token:type previous-token) '\})
(progn
(backward-list)
(equal (swift-mode:token:text
(swift-mode:backquote-identifier-if-after-dot
(swift-mode:backward-token-simple)))
"repeat"))))))
;; Inserts implicit semicolon before keywords that behave like method
;; names.
((member (swift-mode:token:text next-token)
'("get" "set" "willSet" "didSet" "subscript" "init" "deinit"))
t)
;; Inserts implicit semicolon before declaration starters.
;; Modifiers take precedence over this.
;;
;; Notes that class-requirement is handled by the `:' rule above:
;;
;; protocol Foo: // not insert semicolon here
;; class
;;
;; `protocol' is handled by the next rule
((member (swift-mode:token:text next-token)
'("class" "struct" "actor" "enum" "extension" "func" "typealias"
"associatedtype" "precedencegroup" "macro"))
t)
;; Inserts implicit semicolon before protocol unless it is followed by <.
((equal "protocol" (swift-mode:token:text next-token))
(not (equal (swift-mode:token:text
(save-excursion
(swift-mode:forward-token-simple)
(swift-mode:forward-token-simple)))
"<")))
;; Suppress implicit semicolon after keywords that behave like method
;; names.
;;
;; Note that binary operators take precedence over this:
;;
;; self . // not insert semicolon here
;; init
;;
;; var x {
;; set // not insert semicolon here
;; (x) {
;; }
;; }
;;
;; var x {
;; set // inserts semicolon here
;; {
;; }
;; }
((member (swift-mode:token:text previous-token)
'("set" "willSet" "didSet" "subscript" "init" "deinit"))
nil)
;; Inserts implicit semicolon before open square bracket.
;;
;; Open square bracket for array indexing cannot appear at the start of a
;; line.
;; https://github.com/apple/swift/blob/8d4b1cc3c47c7624d57f188d5b227152ccb03163/lib/Parse/ParseExpr.cpp#L1525
;;
;; Note that the following pattern (i.e. after binary-operator) is handled
;; by above case.
;;
;; let x =
;; [
;; 1
;; ]
((eq (swift-mode:token:type next-token) '\[) t)
;; Inserts implicit semicolon before open parenthesis, unless it is a
;; function parameter clause. Suppress implicit semicolon before function
;; parameter clause.
;;
;; Open parenthesis for function arguments cannot appear at the start of a
;; line.
;; https://github.com/apple/swift/blob/8d4b1cc3c47c7624d57f188d5b227152ccb03163/lib/Parse/ParseExpr.cpp#L1251
;;
;; Note that the following pattern (i.e. after binary-operator) is handled
;; by above case.
;;
;; let x =
;; (
;; 1
;; )
((eq (swift-mode:token:type next-token) '\()
(not (swift-mode:function-parameter-clause-p)))
;; Suppress implicit semicolon after the beginning of an interpolated
;; expression.
((eq (swift-mode:token:type previous-token)
'string-chunk-before-interpolated-expression)
nil)
;; Otherwise, inserts implicit semicolon.
(t t))))
(defun swift-mode:function-parameter-clause-p ()
"Return t if the cursor is before a function/macro parameter clause.
Return nil otherwise."
(save-excursion
(let* ((previous-token (swift-mode:backward-token-simple))
(previous-type (swift-mode:token:type previous-token)))
(cond
((eq previous-type '>)
(and
(/= (point)
;; FIXME: mutual dependency
(progn (swift-mode:try-backward-generic-parameters) (point)))
(swift-mode:function-parameter-clause-p)))
((eq previous-type 'identifier)
(member (swift-mode:token:text (swift-mode:backward-token-simple))
'("func" "macro")))
(t nil)))))
(defun swift-mode:supertype-colon-p ()
"Return t if a colon at the cursor is the colon for supertype.
That is supertype declaration or type declaration of let or var."
(save-excursion
(let ((previous-token (swift-mode:backward-token-simple)))
;; class Foo<T>: Bar ← supertype colon
;; class Foo<T> : Bar ← supertype colon
;; class Foo<T where T: Bar<[(Int, String)]>> : Bar ← supertype colon
;; case Foo: ← not a supertype colon
;; case Foo where foo: ← not a supertype colon
;; case let Foo(x) where x is Foo<Int>: ← not a supertype colon
;; default: ← not a supertype colon
;; foo ? bar : baz ← not a supertype colon
;; [
;; foo: ← not a supertype colon
;; bar
;; ]
;; foo(bar, baz: baz) ← not a supertype colon
;; protocol Foo {
;; associatedtype Bar<A>: Baz ← supertype colon
;; }
(or
;; FIXME case let Foo(x) where x is Foo<Int>
(eq (swift-mode:token:type previous-token) '>)
;; class Foo: ← supertype colon
;; extension Foo: ← supertype colon
;; let foo: ← not a supertype colon
;; var foo: ← not a supertype colon
;; protocol Foo {
;; associatedtype Bar: Baz ← supertype colon
;; }
(member (swift-mode:token:text
(swift-mode:backquote-identifier-if-after-dot
(swift-mode:backward-token-simple)))
'("class" "extension" "enum" "struct" "actor" "protocol"
"typealias" "associatedtype"))))))
(defvar swift-mode:in-recursive-call-of-case-colon-p nil
"Non-nil if `case-colon-p' is being evaluated.")
(defun swift-mode:case-colon-p ()
"Return non-nil if the colon at the cursor follows case or default label.
Return nil otherwise."
(if swift-mode:in-recursive-call-of-case-colon-p
nil
(save-excursion
(setq swift-mode:in-recursive-call-of-case-colon-p t)
(unwind-protect
(member
;; FIXME:
;; This function can be confused by conditional operator.
;;
;; switch foo {
;; case let x where x is Foo ?
;; a : // This function should return nil but it
;; // actually returns t.
;; b: // This function should return t but it
;; // actually return nil.
;; let y = a ? b : c // This function returns nil correctly for
;; // this.
;; }
;; FIXME: mutual dependency
(swift-mode:token:text
(swift-mode:backward-sexps-until
'(implicit-\; \; { \( \[ "case" "default" ":")))
'("case" "default"))
(setq swift-mode:in-recursive-call-of-case-colon-p nil)))))
(defun swift-mode:anonymous-parameter-in-p ()
"Return t if a `in' token at the cursor is for anonymous function parameters."
(save-excursion
(eq
;; FIXME: mutual dependency
(swift-mode:token:type (swift-mode:backward-sexps-until
'(\; { \( \[ "for")))
'{)))
(defun swift-mode:generic-parameter-clause-start-p ()
"Return t if the `<' at the cursor is a start of generic parameters.
Return nil otherwise."
(save-excursion
(or (member (swift-mode:token:text (swift-mode:backward-token-simple))
'("init" "subscript"))
(member (swift-mode:token:text (swift-mode:backward-token-simple))
'("typealias" "func" "enum" "struct" "actor" "class" "init"
"macro")))))
(defun swift-mode:fix-operator-type (token)
"Return new operator token with proper token type.
Other properties are the same as the TOKEN."
;; Operator type (i.e. prefix, postfix, infix) is decided from spaces or
;; comments around the operator.
;; https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
;; https://github.com/apple/swift-evolution/blob/master/proposals/0037-clarify-comments-and-operators.md
(let*
((text (swift-mode:token:text token))
(start (swift-mode:token:start token))
(end (swift-mode:token:end token))
(has-preceding-space (or
(= start (point-min))
(memq (char-syntax (char-before start)) '(? ?>))
(memq (char-before start) '(?\( ?\[ ?{ ?, ?\; ?:))
(nth 4 (save-excursion
(syntax-ppss (1- start))))))
(has-following-space (or
(= end (point-max))
(memq (char-syntax (char-after end)) '(? ?<))
(memq (char-after end) '(?\) ?\] ?} ?, ?\; ?:))
(save-excursion (goto-char end)
(looking-at "/\\*\\|//"))
(= (char-after end) ?\C-j)))
(has-following-dot (eq (char-after end) ?.))
(is-declaration (save-excursion
;; i.e.
;; func +++(x1: X, x2: X)