-
Notifications
You must be signed in to change notification settings - Fork 43
/
kotlin-mode-lexer.el
2589 lines (2315 loc) · 90.8 KB
/
kotlin-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
;;; kotlin-mode-lexer.el --- Major mode for kotlin, lexer -*- lexical-binding: t; -*-
;; Copyright © 2015 Shodai Yokoyama
;; Copyright © 2019 taku0
;; Author: Shodai Yokoyama ([email protected])
;; taku0 (http://github.com/taku0)
;; 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:
;; Lexical level routines.
;;; Code:
(require 'rx)
(require 'cl-lib)
(require 'eieio)
;; Terminology:
;; https://kotlinlang.org/docs/reference/basic-types.html#string-templates
;; See also doc/string.png.
;;
;; String template:
;; 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.
;;
;; Template expression:
;; An expression between ${ and } inside a string.
;; Suppose a string "aaa${ foo() }bbb${ bar() }ccc",
;; `foo()' and `bar()' are template expressions.
;;
;; String chunk:
;; A part of single-line/multiline string delimited with quotation marks
;; or template 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 kotlin-mode.
;;; Brackets
(defvar-local kotlin-mode--bracket-positions '()
"List of position of brackets.
Element of the list is a cons (TYPE . POSITION) where TYPE is one of
\(, ), {, }, [, or ], and POSITION is the position of the token.
Elements are sorted by the position in descending order.")
(defun kotlin-mode--clear-bracket-positions-after (position)
"Remove bracket positions after or equal to POSITION from cache."
(while (and kotlin-mode--bracket-positions
(<= position (cdar kotlin-mode--bracket-positions)))
(pop kotlin-mode--bracket-positions)))
(defun kotlin-mode--find-containing-brackets (position)
"Return start position of innermost brackets containing POSITION.
Return a cons (TYPE . POSITION) where TYPE is one of (, ), {, }, [, ],
or outside-of-buffer, and POSITION is the position of the token."
(let ((brackets kotlin-mode--bracket-positions)
(nesting-level 1))
(while (and brackets (<= position (cdar brackets)))
(pop brackets))
(while (and brackets (not (zerop nesting-level)))
(if (memq (caar brackets) '(\( \[ {))
(setq nesting-level (1- nesting-level))
(setq nesting-level (1+ nesting-level)))
(unless (zerop nesting-level)
(pop brackets)))
(if brackets
(car brackets)
(cons 'outside-of-buffer (point-min)))))
;;; Text properties
;; See also doc/string_properties.png.
;;
;; Some properties are put by `syntax-propertize-function', that is
;; `kotlin-mode--syntax-propertize'.
;;
;; The beginning of and end of strings, character literals, backquoted
;; identifiers 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 brackets
;; surrounding template expressions are also marked with
;; '(syntax-table (15)). The property helps font-lock and the
;; tokenizer to recognize strings.
;;
;; The entire string including template expressions, character
;; literal, backquoted identifiers are marked with text property
;; '(syntax-multiline t). The property is used by
;; `kotlin-mode--syntax-propertize-extend-region' to avoid scanning
;; from the middle of strings.
;;
;; The brackets surrounding template expressions have text property
;; '(kotlin-property--matching-bracket POS), where POS is the position
;; of the matching bracket. Strictly speaking, the POS on the closing
;; bracket refers to the dollar sign before the opening
;; parenthesis. The property speeds up the indentation logic.
(defun kotlin-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 kotlin-mode--syntax-propertize (start end)
"Update text properties for strings.
Mark the beginning of and the end of single-line/multiline
strings, character literals, backquoted identifiers between the
position START and END as general string delimiters.
Intended for `syntax-propertize-function'.
Also track position of brackets in `kotlin-mode--bracket-positions'."
(remove-text-properties start end
'(syntax-table
nil
syntax-multiline
nil
kotlin-property--matching-bracket
nil
kotlin-property--interpolation
nil))
(kotlin-mode--clear-bracket-positions-after start)
(let* ((chunk (kotlin-mode--chunk-after (syntax-ppss start))))
(cond
((kotlin-mode--chunk-multiline-string-p chunk)
(kotlin-mode--syntax-propertize-end-of-string end "\"\"\""))
((kotlin-mode--chunk-single-line-string-p chunk)
(kotlin-mode--syntax-propertize-end-of-string end "\""))
((kotlin-mode--chunk-character-literal-p chunk)
(kotlin-mode--syntax-propertize-end-of-string end "'"))
((kotlin-mode--chunk-backquoted-identifier-p chunk)
(kotlin-mode--syntax-propertize-end-of-string end "`"))
((kotlin-mode--chunk-comment-p chunk)
(goto-char (kotlin-mode--chunk-start chunk))
(forward-comment (point-max)))))
(kotlin-mode--syntax-propertize-scan end 0))
(defun kotlin-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 character literals between the current position and
END as general string delimiters.
Assuming the point is not on strings, character-literal,
backquoted identifier, nor comments.
If NESTING-LEVEL is non-zero, nesting of brackets are tracked and
the scan stops where the level becomes zero."
(let ((found-matching-bracket nil)
(pattern
(rx (or "\"\"\"" "\"" "//" "/*" "{" "}" "(" ")" "[" "]" "'" "`")))
match-string
start)
(while (and (not found-matching-bracket)
(< (point) end)
(search-forward-regexp pattern end t))
(setq match-string (match-string-no-properties 0))
(setq start (match-beginning 0))
(cond
;; Quotes
((member match-string '("\"\"\"" "\"" "'" "`"))
;; Mark the start of the quotes as a generic string delimiter.
(put-text-property start (1+ start)
'syntax-table
(string-to-syntax "|"))
;; Scan until end of the string.
(kotlin-mode--syntax-propertize-end-of-string end match-string)
;; Mark whole string, including template expressions,
;; with `syntax-multiline'. The property is used by
;; `kotlin-mode--syntax-propertize-extend-region'.
(put-text-property start (point) 'syntax-multiline t)
(when (equal match-string "`")
;; Backquotes cannot be escaped. So declare the backslashes in
;; the identifier are normal characters, not escape-syntax characters.
(put-text-property (1+ start) (1- (point))
'syntax-table
(string-to-syntax "w"))))
;; Single-line comment
((equal "//" match-string)
(goto-char start)
(forward-comment (point-max)))
;; Multiline comment
((equal "/*" match-string)
(goto-char start)
(forward-comment (point-max)))
;; Open curly bracket
((and (equal "{" match-string)
(/= nesting-level 0))
(push (cons (intern match-string) start) kotlin-mode--bracket-positions)
(setq nesting-level (1+ nesting-level)))
;; Close curly bracket
((and (equal "}" match-string)
(/= nesting-level 0))
(push (cons (intern match-string) start) kotlin-mode--bracket-positions)
(setq nesting-level (1- nesting-level))
(when (= nesting-level 0)
(setq found-matching-bracket t)))
;; Other brackets
((member match-string '("(" ")" "[" "]" "{" "}"))
(push (cons (intern match-string) start)
kotlin-mode--bracket-positions))))
(unless found-matching-bracket
(goto-char end))
found-matching-bracket))
(defun kotlin-mode--syntax-propertize-end-of-string (end quotation)
"Move point to the end of single-line/multiline string.
Assuming the point is on a string, a character literal, or a backquoted
identifier.
If the string go beyond END, stop there.
The string should be terminated with QUOTATION."
(if (and (< (point) end)
(search-forward-regexp
(rx-to-string
`(or ,quotation
"${"
(and "$" (or
(and (char alpha "_") (* (char alnum "_")))
(and "`" (+ (not (any "`\n"))) "`")))))
end t))
(cond
;; End of the string
((and (equal quotation (match-string-no-properties 0))
(or (equal quotation "`") ; backquotes cannot be escaped
(not (kotlin-mode--escaped-p (match-beginning 0)))))
(put-text-property (1- (point)) (point)
'syntax-table
(string-to-syntax "|")))
;; Start of a template expression
((and (equal "${" (match-string-no-properties 0))
(member quotation '("\"\"\"" "\""))
;; Dollar signs cannot be escaped, so we don't need to check it.
)
;; Found an template expression. Skips the expression.
;; We cannot use `scan-sexps' because multiline strings are not yet
;; propertized.
(let ((pos-after-open-bracket (point))
(start
(save-excursion
(backward-char) ;; {
(backward-char) ;; $
(point))))
;; Keep the position of the open bracket.
(push (cons '{ (1+ start)) kotlin-mode--bracket-positions)
;; Declare the open bracket is a generic string delimiter.
(put-text-property
(1- pos-after-open-bracket) pos-after-open-bracket
'syntax-table
(string-to-syntax "|"))
;; Try to skip
(when (kotlin-mode--syntax-propertize-scan end 1)
;; Found the matching bracket. Going further.
;; Declare the close bracket is a generic string delimiter.
(put-text-property (1- (point)) (point)
'syntax-table
(string-to-syntax "|"))
;; Record the positions.
(put-text-property (1- (point)) (point)
'kotlin-property--matching-bracket
start)
(put-text-property start pos-after-open-bracket
'kotlin-property--matching-bracket
(1- (point)))
;; Proceed.
(kotlin-mode--syntax-propertize-end-of-string end quotation))))
;; Template expression without braces
((and (eq (aref (match-string-no-properties 0) 0) ?$)
(not (eq (aref (match-string-no-properties 0) 1) ?{)))
(put-text-property (match-beginning 0) (1+ (match-beginning 0))
'kotlin-property--interpolation
(match-data))
(kotlin-mode--syntax-propertize-end-of-string end quotation))
;; Others
(t
(kotlin-mode--syntax-propertize-end-of-string end quotation)))
(goto-char end)))
(defun kotlin-mode--escaped-p (position)
"Return t if the POSITION in a string is escaped.
A position is escaped if it is proceeded by odd number of backslashes.
Return nil otherwise."
(let ((p position)
(backslash-count 0))
(while (eq (char-before p) ?\\)
(setq backslash-count (1+ backslash-count))
(setq p (1- p)))
(= (mod backslash-count 2) 1)))
;;; Comment or string chunks
(defclass kotlin-mode--chunk ()
((type :initarg :type
:type symbol
:documentation "The type of the chunk.
Valid values:
- single-line-string
- multiline-string
- single-line-comment
- multiline-comment
- character-literal
- backquoted-identifier")
(start :initarg :start
:type number
:documentation "The start position of the chunk."))
"String-chunks, comments, character literals, or backquoted identifiers.
It have the type and the start position.")
(defun kotlin-mode--chunk-type (chunk)
"Return the type of the CHUNK."
(and chunk (oref chunk type)))
(defun kotlin-mode--chunk-start (chunk)
"Return the start position of the CHUNK."
(and chunk (oref chunk start)))
(defun kotlin-mode--chunk-comment-p (chunk)
"Return non-nil if the CHUNK is a comment."
(and chunk
(memq (kotlin-mode--chunk-type chunk)
'(single-line-comment multiline-comment))))
(defun kotlin-mode--chunk-string-p (chunk)
"Return non-nil if the CHUNK is a string."
(and chunk
(memq (kotlin-mode--chunk-type chunk)
'(single-line-string multiline-string))))
(defun kotlin-mode--chunk-single-line-comment-p (chunk)
"Return non-nil if the CHUNK is a single-line comment."
(and chunk (eq (kotlin-mode--chunk-type chunk) 'single-line-comment)))
(defun kotlin-mode--chunk-multiline-comment-p (chunk)
"Return non-nil if the CHUNK is a multiline comment."
(and chunk (eq (kotlin-mode--chunk-type chunk) 'multiline-comment)))
(defun kotlin-mode--chunk-single-line-string-p (chunk)
"Return non-nil if the CHUNK is a single-line string."
(and chunk (eq (kotlin-mode--chunk-type chunk) 'single-line-string)))
(defun kotlin-mode--chunk-multiline-string-p (chunk)
"Return non-nil if the CHUNK is a multiline string."
(and chunk (eq (kotlin-mode--chunk-type chunk) 'multiline-string)))
(defun kotlin-mode--chunk-character-literal-p (chunk)
"Return non-nil if the CHUNK is a character literal."
(and chunk (eq (kotlin-mode--chunk-type chunk) 'character-literal)))
(defun kotlin-mode--chunk-backquoted-identifier-p (chunk)
"Return non-nil if the CHUNK is a backquoted identifier."
(and chunk (eq (kotlin-mode--chunk-type chunk) 'backquoted-identifier)))
(defun kotlin-mode--incomplete-comment-p (chunk)
"Return t if the CHUNK is incomplete comment.
Return nil otherwise."
(and (kotlin-mode--chunk-comment-p chunk)
(save-excursion
(goto-char (kotlin-mode--chunk-start chunk))
(not (forward-comment 1)))))
(defun kotlin-mode--chunk-after (&optional parser-state)
"Return the chunk at the point.
If the point is outside of strings and comments, return nil.
If PARSER-STATE is given, it is used instead of (syntax-ppss)."
(save-excursion
(when (number-or-marker-p parser-state)
(goto-char parser-state))
(when (or (null parser-state) (number-or-marker-p parser-state))
(setq parser-state (save-excursion (syntax-ppss parser-state))))
(cond
((nth 3 parser-state)
;; Syntax category "|" is attached to both single-line and multiline
;; string delimiters. So (nth 3 parser-state) may be t even for
;; single-line string delimiters.
(save-excursion
(goto-char (nth 8 parser-state))
(forward-char)
(kotlin-mode--beginning-of-string)
(cond
((looking-at "\"\"\"")
(make-instance 'kotlin-mode--chunk
:type 'multiline-string
:start (nth 8 parser-state)))
((looking-at "`")
(make-instance 'kotlin-mode--chunk
:type 'backquoted-identifier
:start (nth 8 parser-state)))
((looking-at "'")
(make-instance 'kotlin-mode--chunk
:type 'character-literal
:start (nth 8 parser-state)))
(t
(make-instance 'kotlin-mode--chunk
:type 'single-line-string
:start (nth 8 parser-state))))))
((eq (nth 4 parser-state) t)
(make-instance 'kotlin-mode--chunk
:type 'single-line-comment
:start (nth 8 parser-state)))
((nth 4 parser-state)
(make-instance 'kotlin-mode--chunk
:type 'multiline-comment
:start (nth 8 parser-state)))
((and (eq (char-before) ?/) (eq (char-after) ?/))
(make-instance 'kotlin-mode--chunk
:type 'single-line-comment
:start (1- (point))))
((and (eq (char-before) ?/) (eq (char-after) ?*))
(make-instance 'kotlin-mode--chunk
:type 'multiline-comment
:start (1- (point))))
(t
nil))))
;; Syntax table
(defvar kotlin-mode-syntax-table
(let ((st (make-syntax-table)))
;; Strings
(modify-syntax-entry ?\" "\"" st)
(modify-syntax-entry ?\' "\"" st)
(modify-syntax-entry ?` "\"" st)
;; `_' and `@' as being a valid part of a symbol
(modify-syntax-entry ?_ "_" st)
(modify-syntax-entry ?@ "_" st)
;; b-style comment
(modify-syntax-entry ?/ ". 124b" st)
(modify-syntax-entry ?* ". 23n" st)
(modify-syntax-entry ?\n "> b" st)
(modify-syntax-entry ?\r "> b" st)
st))
;; Token
(defclass kotlin-mode--token ()
((type :initarg :type
:type symbol
:documentation "The type of the token.
Token types is one of the following symbols:
- operator (including as, as?, is, !is, in, !in, ., and ->)
- annotation
(e.g. @ABC, @ABC(def), @file:ABC, @[ABC DEF(ghi)], or @file:[ABC DEF(ghi)])
- atom (including keywords, numbers, strings, and unknown tokens)
- label
- return (including return@identifier)
- continue (including continue@identifier)
- beak (including beak@identifier)
- this (including this@identifier)
- super (including super@identifier)
- [
- ]
- {
- }
- (
- )
- )-before-control-structure-body
- ,
- ;
- implicit-;
- < (as an angle bracket)
- > (as an angle bracket)
- :
- string-chunk-after-template-expression (part of a string ending with \"}\")
- string-chunk-before-template-expression (part of a string ending with \"${\")
- bare-else (\"else\" not followed by \"if\" on the same line, \"->\", or \"{\")
- outside-of-buffer
- anonymous-function-parameter-arrow
- when-expression-arrow
Additionally, `kotlin-mode--backward-token-or-list' may return a parenthesized
expression as a token with one of the following types:
- ()
- ()-before-control-structure-body
- []
- {}
- <>" )
(text :initarg :text
:type string
:documentation "The text of the token.")
(start :initarg :start
:type integer
:documentation "The start position of the token.")
(end :initarg :end
:type integer
:documentation "The point after the token."))
"Token of Kotlin.")
(defun kotlin-mode--token-type (token)
"Return the type of TOKEN."
(and token (oref token type)))
(defun kotlin-mode--token-text (token)
"Return the text of TOKEN."
(and token (oref token text)))
(defun kotlin-mode--token-start (token)
"Return the start position of TOKEN."
(and token (oref token start)))
(defun kotlin-mode--token-end (token)
"Return the end position of TOKEN."
(and token (oref token end)))
;; Token level movements and predicates.
(defconst kotlin-mode--inheritance-modifier-keywords
'("open" "final" "abstract"))
(defconst kotlin-mode--visibility-modifier-keywords
'("public" "private" "internal" "protected"))
(defconst kotlin-mode--member-modifier-keywords
'("lateinit" "override"))
(defconst kotlin-mode--companion-modifier-keywords
'("companion"))
(defconst kotlin-mode--class-modifier-keywords
'("enum" "sealed" "annotation" "data" "inner"))
(defconst kotlin-mode--property-modifier-keywords
'("const"))
(defconst kotlin-mode--platform-modifier-keywords
'("expect" "actual"))
(defconst kotlin-mode--parameter-modifier-keywords
'("vararg" "crossinline" "noinline"))
(defconst kotlin-mode--function-modifier-keywords
'("tailrec" "operator" "infix" "inline" "value" "external" "suspend"))
(defconst kotlin-mode--modifier-keywords
(append kotlin-mode--inheritance-modifier-keywords
kotlin-mode--visibility-modifier-keywords
kotlin-mode--member-modifier-keywords
kotlin-mode--class-modifier-keywords
kotlin-mode--property-modifier-keywords
kotlin-mode--platform-modifier-keywords
kotlin-mode--parameter-modifier-keywords
kotlin-mode--function-modifier-keywords))
(defun kotlin-mode--implicit-semi-p ()
"Return non-nil if the point is after the end of a statement."
(let ((previous-token (save-excursion
(kotlin-mode--extend-annotation-token-backward
(kotlin-mode--backward-token-simple))))
(next-token (save-excursion
(kotlin-mode--extend-annotation-token-forward
(kotlin-mode--forward-token-simple)))))
;; If the point is on the empty line, pretend an identifier is on the line.
(when (and
(< (kotlin-mode--token-end previous-token) (line-beginning-position))
(< (line-end-position) (kotlin-mode--token-start next-token)))
(setq next-token (make-instance 'kotlin-mode--token
:type 'atom
:text ""
:start (point)
:end (point))))
(cond
;; Tokens that end a statement
((memq (kotlin-mode--token-text previous-token)
'("return" "continue" "break"))
t)
;; .* in import declarations end a statement.
((and (equal (kotlin-mode--token-text previous-token) "*")
(equal (kotlin-mode--token-text
(save-excursion
(goto-char (kotlin-mode--token-start previous-token))
(kotlin-mode--backward-token-simple)))
"."))
t)
;; Suppress implicit semicolon after "if ()", "while ()", "for ()"
((kotlin-mode--close-parenthesis-before-control-structure-body-p
previous-token)
nil)
;; Annotations and modifiers, that cannot end a statement/declaration
((or
;; Annotations
(and
(eq (kotlin-mode--token-type previous-token) 'annotation)
;; Exclude super<A>@label. Note that this@label is handled by
;; `kotlin-mode--backward-token-simple'
(not (save-excursion
(goto-char (kotlin-mode--token-start previous-token))
(and (eq (char-before) ?>)
(kotlin-mode--try-backward-type-parameters)
(equal (kotlin-mode--token-text
(kotlin-mode--backward-token-simple))
"super")))))
;; Labels
(eq (kotlin-mode--token-type previous-token) 'label)
;; Modifiers
(and (member (kotlin-mode--token-text previous-token)
kotlin-mode--modifier-keywords)
(not (equal (kotlin-mode--token-text previous-token) "value"))))
nil)
;; Tokens that cannot end a statement
;;
;; TODO prefix ++ and --
;; TODO infix function call
;; TODO prefix !, especially !!
;;
;; Example:
;; var shl = 1
;; val x = shl shl shl
;; shl < 100 && foo() // this is not a continuation of the previous line.
;;
;; var shl = 1
;; val x = shl shl
;; shl < 100 && foo() // this is a continuation of the previous line.
;;
;; var shl = 1
;; val x = shl shl shl ++
;; shl < 100 && foo() // this is not a continuation of the previous line.
;;
;; var shl = 1
;; val x = shl shl ++
;; shl < 100 && foo() // this is a continuation of the previous line.
;;
;; val x = foo()!!
;; foo() // this is not a continuation of the previous line.
;;
;; val x = !!
;; foo() // this is a continuation of the previous line.
((or
(memq
(kotlin-mode--token-type previous-token)
'(implicit-\; string-chunk-before-template-expression))
(member
(kotlin-mode--token-text previous-token)
'("(" "{" "[" "*" "%" "/" "+" "-" "&&" "||" ":" "&"
"=" "+=" "-=" "*=" "/=" "%="
"->" "." ".." "..<" "::" "?:" "?." "<=" ">=" "!=" "!==" "==" "==="
"as" "as?" "is" "!is" "in" "!in" "," ";" "{" "[" "("
;; "class" will be handled later.
"package" "import" "interface" "fun" "object"
"val" "var" "typealias" "constructor" "by" "companion" "init"
"where" "if" "else" "when" "try" "catch" "finally" "for" "do"
"while" "throw" "out" "reified"))
;; Inequality operator cannot end a statement/declaration.
(and (eq (kotlin-mode--token-type previous-token) 'operator)
(member (kotlin-mode--token-text previous-token) '("<" ">"))))
nil)
;; "class" cannot end a statement unless preceded by "::".
;;
;; Example:
;;
;; class // No implicit semicolon here
;; Foo {
;; }
;;
;; val x = Foo ::
;; class // Implicit semicolon here
;; foo()
((and (equal (kotlin-mode--token-text previous-token) "class")
(save-excursion
(goto-char (kotlin-mode--token-start previous-token))
(not (equal (kotlin-mode--token-text
(kotlin-mode--backward-token-simple))
"::"))))
nil)
;; Annotations, labels, and modifiers, that start a statement/declaration,
;; except for getter and setter.
;;
;; "suspend" is excluded because it can be used as type modifier.
((or
(memq (kotlin-mode--token-type next-token) '(annotation label))
(member (kotlin-mode--token-text next-token)
(remove "suspend" kotlin-mode--modifier-keywords)))
(not (save-excursion
(kotlin-mode--try-forward-modifiers)
(member (kotlin-mode--token-text
(kotlin-mode--forward-token-simple))
'("get" "set")))))
;; Tokens that start a statement/declaration
((member
(kotlin-mode--token-text next-token)
;; "class" will be handled later.
'("package" "import" "interface" "val" "var" "typealias"
"constructor" "companion" "init" "for" "do" "is"
;; While we should insert a semicolon before "in" in a "when"
;; expression or beginning of a expression, we should
;; suppress a semicolon before "in" in "for", type
;; parameters, or type arguments:
;;
;; when (x) {
;; 1 -> 1 // implicit semicolon here
;; in xs -> 2
;; }
;;
;; // line breaks are prohibited before infix "in" operator.
;; val x = 1 // implicit semicolon here
;; in xs // Though this is an invalid expression anyway.
;;
;; for (
;; x // no implicit semicolons here
;; in
;; xs
;; ) {}
;;
;; Foo< // no implicit semicolons here
;; in X
;; >
;;
;; Because detecting the context is hard at lexer level, we
;; omit semicolon for now, and handle it later in the
;; indentation code.
))
t)
;; While or do-while
((equal (kotlin-mode--token-text next-token) "while")
;; insert semicolon unless it is a part of do-while.
(save-excursion (not (kotlin-mode--find-do-for-while))))
;; "class" starts a new declaration unless preceded by "::".
;;
;; Example:
;;
;; class Foo { // This start a class declaration.
;; }
;;
;; Foo ::
;; class // This does not start a class declaration.
((and (equal (kotlin-mode--token-text next-token) "class")
(not (equal (kotlin-mode--token-text previous-token) "::")))
t)
;; Tokens that cannot start a statement/declaration.
((or (memq
(kotlin-mode--token-type next-token)
'(implicit-\; string-chunk-after-template-expression))
(member
(kotlin-mode--token-text next-token)
'("*" "%" "/" "&" "&&" "||" ":" "=" "+=" "-=" "*=" "/=" "%="
"->" "." ".." "..<" "::" "?:" "?." "?" "<" ">" "<=" ">="
"!=" "!==" "==" "==="
"," ";" ")" "]" "}"
"as" "as?" "get" "set" "by" "where" "else" "catch" "finally"
;; Because detecting the context is hard at lexer level,
;; we omit semicolon before "in" for now, and handle it
;; later in the indentation code.
"in"
;; Strictly speaking, open curly bracket may start a statement
;; as a part of lambda expression, it is rare case, so we
;; suppress semicolon before it.
"{")))
nil)
;; Open square bracket start a new statement unless preceded by a
;; colon (already handled above).
((eq (kotlin-mode--token-type next-token) '\[)
t)
;; Open parenthesis start a new statement unless preceded by:
;; - a colon (already handled above),
;; - a comma (already handled above),
;; - a dot (already handled above),
;; - an equal sign (already handled above),
;; - "->" (already handled above),
;; - "is" (already handled above),
;; - "!is" (already handled above),
;; - "as" (already handled above),
;; - "as?" (already handled above),
;; - "if" (already handled above),
;; - "while" (already handled above),
;; - "for" (already handled above),
;; - "when" (already handled above),
;; - "catch" (already handled above),
;; or is a part of:
;; - secondary constructor declaration,
;; - class declaration,
;; - function declaration,
;; - variable declaration,
;; - getter declaration,
;; - setter declaration,
;; - constructor declaration call (example: constructor(): this(1)),
;;
;; Examples:
;;
;; public constructor() {}
;;
;; public class Foo() {}
;; public class Foo <A>() {}
;; public class Foo public constructor ()
;; public class Foo <A> @AAA constructor ()
;;
;; fun foo() {}
;; fun <A> foo() {}
;; fun (A).foo() {}
;; fun A.B<A, B>.C.foo() {}
;; fun @AAA (A).foo() {}
;; fun <A> (A).foo() {}
;; fun <A> @AAA (A).foo() {}
;; fun <A> @AAA A.B<A, B>.C.foo() {}
;;
;; fun () {}
;; fun (A).() {}
;; fun A.B<A, B>.C.() {}
;;
;; val (x, y) = foo()
;; var (x, y) = foo()
;; val <A> (x, y) = foo()
;; val (A).(x, y) = foo()
;; val <A> (A).(x, y) = foo()
;; val <A> @AAA A.(x, y) = foo()
;; val <A> @AAA A.B<A, B>.C.(x, y) = foo()
;;
;; get() {}
;; set(value) {}
;;
;; constructor (): this(1)
;; constructor (): super(1)
;;
;; Note that function argument cannot preceded by newline:
;;
;; val x = foo
;; (bar()) // This is not a continuation of the previous line.
((eq (kotlin-mode--token-type next-token) '\()
(and
(not (kotlin-mode--constructor-parameter-clause-p))
(not (kotlin-mode--function-parameter-clause-p))
(not (kotlin-mode--multi-variable-declaration-p))
(not (kotlin-mode--constructor-delegation-call-p))))
;; Suppress implicit semicolon after the beginning of an interpolated
;; expression.
((eq (kotlin-mode--token-type previous-token)
'string-chunk-before-interpolated-expression)
nil)
;; Otherwise, inserts implicit semicolon.
(t t))))
(defun kotlin-mode--close-parenthesis-before-control-structure-body-p (token)
"Return t if TOKEN is close parenthesis before control structure body.
Return t if TOKEN is the close-parenthesis of \"if (...)\",
\"while(...)\", or \"for (...)\", but not followed by \"{\".
Return nil otherwise."
(and
(eq (kotlin-mode--token-type token) '\))
(save-excursion
(goto-char (kotlin-mode--token-end token))
(not (eq (kotlin-mode--token-type (kotlin-mode--forward-token-simple))
'\{)))
(save-excursion
(goto-char (kotlin-mode--token-end token))
(condition-case nil
(progn
(backward-list)
(let ((previous-token (kotlin-mode--backward-token-simple)))
(or
(member (kotlin-mode--token-text previous-token) '("if" "for"))
(and
(equal (kotlin-mode--token-text previous-token) "while")
(not (save-excursion (kotlin-mode--find-do-for-while)))))))
(scan-error
nil)))))
(defun kotlin-mode--find-do-for-while ()
"Return \"do\" token for \"while\" token.
If \"while\" is not part of do-while, return nil.
Assuming the point is before \"while\" token."
;; Example:
;;
;; do
;; while (false)
;; print(1)
;; while (false)
;; print(2)
;;
;; is parsed as three statements:
;;
;; do while (false);
;; print(1);
;; while (false) print(2);
;;
;; So we don't need to worry about bare while-statement in body of do-while.
(let ((nesting-level 1)
previous-token)
(while (< 0 nesting-level)
(setq previous-token (kotlin-mode--backward-token-or-list t))
(cond
((equal (kotlin-mode--token-text previous-token) "while")
(setq nesting-level (1+ nesting-level)))
((equal (kotlin-mode--token-text previous-token) "do")
(setq nesting-level (1- nesting-level)))
((memq (kotlin-mode--token-type previous-token) '(outside-of-buffer {))
;; Unmatched
(setq nesting-level 0))))
(and (equal (kotlin-mode--token-text previous-token) "do")
previous-token)))
(defun kotlin-mode--constructor-parameter-clause-p ()
"Return non-nil if the point is before parameters of constructor declaration."
;; Examples:
;;
;; public constructor() {}
;;
;; public class Foo() {}
;; public class Foo <A>() {}
;; public class Foo public constructor ()
;; public class Foo <A> @AAA constructor ()
(let ((previous-token (save-excursion (kotlin-mode--backward-token-simple))))
(or
(equal (kotlin-mode--token-text previous-token) "constructor")
(save-excursion
(kotlin-mode--try-backward-type-parameters)
(and
(eq (kotlin-mode--token-type (kotlin-mode--backward-token-simple))
'atom)
(equal (kotlin-mode--token-text (kotlin-mode--backward-token-simple))
"class"))))))
(defun kotlin-mode--function-parameter-clause-p ()
"Return non-nil if the point is before parameters of function declaration."
;; Examples:
;;
;; fun foo() {}
;; fun <A> foo() {}
;; fun (A).foo() {}
;; fun A.B<A, B>.C.foo() {}
;; fun @AAA (A).foo() {}
;; fun <A> (A).foo() {}
;; fun <A> @AAA (A).foo() {}
;; fun <A> @AAA A.B<A, B>.C.foo() {}
;;
;; fun () {}
;; fun (A).() {}
;; fun A.B<A, B>.C.() {}
(let ((previous-token (save-excursion (kotlin-mode--backward-token-simple))))
(cond
;; fun () {}
;; fun (A).() {} // for first parenthesis
;; fun (A).foo() {} // for first parenthesis
((equal (kotlin-mode--token-text previous-token) "fun")
t)