-
Notifications
You must be signed in to change notification settings - Fork 795
/
Copy pathLexFilter.fs
2720 lines (2398 loc) · 135 KB
/
LexFilter.fs
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
/// LexFilter - process the token stream prior to parsing.
/// Implements the offside rule and a couple of other lexical transformations.
module internal FSharp.Compiler.LexFilter
open System
open System.Collections.Generic
open Internal.Utilities.Text.Lexing
open Internal.Utilities.Library
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Features
open FSharp.Compiler.LexerStore
open FSharp.Compiler.Lexhelp
open FSharp.Compiler.ParseHelpers
open FSharp.Compiler.Parser
open FSharp.Compiler.UnicodeLexing
let forceDebug = false
let stringOfPos (pos: Position) = sprintf "(%d:%d)" pos.OriginalLine pos.Column
let outputPos os (pos: Position) = Printf.fprintf os "(%d:%d)" pos.OriginalLine pos.Column
/// Used for warning strings, which should display columns as 1-based and display
/// the lines after taking '# line' directives into account (i.e. do not use
/// p.OriginalLine)
let warningStringOfPosition (pos: Position) = warningStringOfCoords pos.Line pos.Column
type Context =
// Position is position of keyword.
// bool indicates 'LET' is an offside let that's part of a CtxtSeqBlock where the 'in' is optional
| CtxtLetDecl of bool * Position
| CtxtIf of Position
| CtxtTry of Position
| CtxtFun of Position
| CtxtFunction of Position
| CtxtWithAsLet of Position // 'with' when used in an object expression
| CtxtWithAsAugment of Position // 'with' as used in a type augmentation
| CtxtMatch of Position
| CtxtFor of Position
| CtxtWhile of Position
| CtxtWhen of Position
| CtxtVanilla of Position * bool // boolean indicates if vanilla started with 'x = ...' or 'x.y = ...'
| CtxtThen of Position
| CtxtElse of Position
| CtxtDo of Position
| CtxtInterfaceHead of Position
| CtxtTypeDefns of Position * equalsEndPos: Position option // 'type <here> =', not removed when we find the "="
| CtxtNamespaceHead of Position * token
| CtxtModuleHead of Position * token * LexingModuleAttributes * isNested: bool
| CtxtMemberHead of Position
| CtxtMemberBody of Position
// If bool is true then this is "whole file"
// module A.B
// If bool is false, this is a "module declaration"
// module A = ...
| CtxtModuleBody of Position * bool
| CtxtNamespaceBody of Position
| CtxtException of Position
| CtxtParen of token * Position
// Position is position of following token
| CtxtSeqBlock of FirstInSequence * Position * AddBlockEnd
// Indicates we're processing the second part of a match, after the 'with'
// First bool indicates "was this 'with' followed immediately by a '|'"?
| CtxtMatchClauses of bool * Position
member c.StartPos =
match c with
| CtxtNamespaceHead (p, _) | CtxtModuleHead (p, _, _, _) | CtxtException p | CtxtModuleBody (p, _) | CtxtNamespaceBody p
| CtxtLetDecl (_, p) | CtxtDo p | CtxtInterfaceHead p | CtxtTypeDefns(p, _) | CtxtParen (_, p) | CtxtMemberHead p | CtxtMemberBody p
| CtxtWithAsLet p
| CtxtWithAsAugment p
| CtxtMatchClauses (_, p) | CtxtIf p | CtxtMatch p | CtxtFor p | CtxtWhile p | CtxtWhen p | CtxtFunction p | CtxtFun p | CtxtTry p | CtxtThen p | CtxtElse p | CtxtVanilla (p, _)
| CtxtSeqBlock (_, p, _) -> p
member c.StartCol = c.StartPos.Column
override c.ToString() =
match c with
| CtxtNamespaceHead _ -> "nshead"
| CtxtModuleHead _ -> "modhead"
| CtxtException _ -> "exception"
| CtxtModuleBody _ -> "modbody"
| CtxtNamespaceBody _ -> "nsbody"
| CtxtLetDecl(b, p) -> sprintf "let(%b, %s)" b (stringOfPos p)
| CtxtWithAsLet p -> sprintf "withlet(%s)" (stringOfPos p)
| CtxtWithAsAugment _ -> "withaug"
| CtxtDo _ -> "do"
| CtxtInterfaceHead _ -> "interface-decl"
| CtxtTypeDefns _ -> "type"
| CtxtParen(_, p) -> sprintf "paren(%s)" (stringOfPos p)
| CtxtMemberHead _ -> "member-head"
| CtxtMemberBody _ -> "body"
| CtxtSeqBlock (b, p, _addBlockEnd) -> sprintf "seqblock(%s, %s)" (match b with FirstInSeqBlock -> "first" | NotFirstInSeqBlock -> "subsequent") (stringOfPos p)
| CtxtMatchClauses _ -> "matching"
| CtxtIf _ -> "if"
| CtxtMatch _ -> "match"
| CtxtFor _ -> "for"
| CtxtWhile p -> sprintf "while(%s)" (stringOfPos p)
| CtxtWhen _ -> "when"
| CtxtTry _ -> "try"
| CtxtFun _ -> "fun"
| CtxtFunction _ -> "function"
| CtxtThen _ -> "then"
| CtxtElse p -> sprintf "else(%s)" (stringOfPos p)
| CtxtVanilla (p, _) -> sprintf "vanilla(%s)" (stringOfPos p)
and AddBlockEnd = AddBlockEnd | NoAddBlockEnd | AddOneSidedBlockEnd
and FirstInSequence = FirstInSeqBlock | NotFirstInSeqBlock
and LexingModuleAttributes = LexingModuleAttributes | NotLexingModuleAttributes
let isInfix token =
match token with
| COMMA
| BAR_BAR
| AMP_AMP
| AMP
| OR
| INFIX_BAR_OP _
| INFIX_AMP_OP _
| INFIX_COMPARE_OP _
| DOLLAR
// For the purposes of #light processing, <, > and = are not considered to be infix operators.
// This is because treating them as infix conflicts with their role in other parts of the grammar,
// e.g. to delimit "f<int>", or for "let f x = ...."
//
// This has the impact that a SeqBlock does not automatically start on the right of a "<", ">" or "=",
// e.g.
// let f x = (x =
// let a = 1 // no #light block started here, parentheses or 'in' needed
// a + x)
// LESS | GREATER | EQUALS
| INFIX_AT_HAT_OP _
| PLUS_MINUS_OP _
| COLON_COLON
| COLON_GREATER
| COLON_QMARK_GREATER
| COLON_EQUALS
| MINUS
| STAR
| INFIX_STAR_DIV_MOD_OP _
| INFIX_STAR_STAR_OP _
| QMARK_QMARK -> true
| _ -> false
let infixTokenLength token =
match token with
| COMMA -> 1
| AMP -> 1
| OR -> 1
| DOLLAR -> 1
| MINUS -> 1
| STAR -> 1
| BAR -> 1
| LESS false -> 1
| GREATER false -> 1
| EQUALS -> 1
| QMARK_QMARK -> 2
| COLON_GREATER -> 2
| COLON_COLON -> 2
| COLON_EQUALS -> 2
| BAR_BAR -> 2
| AMP_AMP -> 2
| INFIX_BAR_OP d
| INFIX_AMP_OP d
| INFIX_COMPARE_OP d
| INFIX_AT_HAT_OP d
| PLUS_MINUS_OP d
| INFIX_STAR_DIV_MOD_OP d
| INFIX_STAR_STAR_OP d -> d.Length
| COLON_QMARK_GREATER -> 3
| _ -> assert false; 1
/// Matches against a left-parenthesis-like token that is valid in expressions.
//
// LBRACK_LESS and GREATER_RBRACK are not here because adding them in these active patterns
// causes more offside warnings, while removing them doesn't add offside warnings in attributes.
[<return: Struct>]
let (|TokenLExprParen|_|) token =
match token with
| BEGIN | LPAREN | LBRACE _ | LBRACE_BAR | LBRACK | LBRACK_BAR | LQUOTE _ | LESS true
-> ValueSome ()
| _ -> ValueNone
/// Matches against a right-parenthesis-like token that is valid in expressions.
[<return: Struct>]
let (|TokenRExprParen|_|) token =
match token with
| END | RPAREN | RBRACE _ | BAR_RBRACE | RBRACK | BAR_RBRACK | RQUOTE _ | GREATER true
-> ValueSome ()
| _ -> ValueNone
/// Determine the tokens that may align with the 'if' of an 'if/then/elif/else' without closing
/// the construct
let rec isIfBlockContinuator token =
match token with
// The following tokens may align with the "if" without closing the "if", e.g.
// if ...
// then ...
// elif ...
// else ...
| THEN | ELSE | ELIF -> true
// Likewise
// if ... then (
// ) elif begin
// end else ...
| END | RPAREN -> true
// The following arise during reprocessing of the inserted tokens, e.g. when we hit a DONE
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true
| ODUMMY token -> isIfBlockContinuator token
| _ -> false
/// Given LanguageFeature.RelaxWhitespace2,
/// Determine the token that may align with the 'match' of a 'match/with' without closing
/// the construct
let rec isMatchBlockContinuator token =
match token with
// These tokens may align with the "match" without closing the construct, e.g.
// match ...
// with ...
| WITH -> true
// The following arise during reprocessing of the inserted tokens when we hit a DONE
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true
| ODUMMY token -> isMatchBlockContinuator token
| _ -> false
/// Determine the token that may align with the 'try' of a 'try/with' or 'try/finally' without closing
/// the construct
let rec isTryBlockContinuator token =
match token with
// These tokens may align with the "try" without closing the construct, e.g.
// try ...
// with ...
| FINALLY | WITH -> true
// The following arise during reprocessing of the inserted tokens when we hit a DONE
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true
| ODUMMY token -> isTryBlockContinuator token
| _ -> false
let rec isThenBlockContinuator token =
match token with
// The following arise during reprocessing of the inserted tokens when we hit a DONE
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true
| ODUMMY token -> isThenBlockContinuator token
| _ -> false
let rec isDoContinuator token =
match token with
// These tokens may align with the "for" without closing the construct, e.g.
// for ...
// do
// ...
// done *)
| DONE -> true
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE
| ODUMMY token -> isDoContinuator token
| _ -> false
let rec isInterfaceContinuator token =
match token with
// These tokens may align with the token "interface" without closing the construct, e.g.
// interface ... with
// ...
// end
| END -> true
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE
| ODUMMY token -> isInterfaceContinuator token
| _ -> false
let rec isNamespaceContinuator token =
match token with
// These tokens end the construct, e.g.
// namespace A.B.C
// ...
// namespace <-- here
// ....
| EOF _ | NAMESPACE -> false
| ODUMMY token -> isNamespaceContinuator token
| _ -> true // anything else is a namespace continuator
let rec isTypeContinuator token =
match token with
// The following tokens may align with the token "type" without closing the construct, e.g.
// type X =
// | A
// | B
// and Y = c <--- 'and' HERE
//
// type X = {
// x: int
// y: int
// } <--- '}' HERE
// and Y = c
//
// type Complex = struct
// val im : float
// end with <--- 'end' HERE
// static member M() = 1
// end
| RBRACE _ | WITH | BAR | AND | END -> true
// The following arise during reprocessing of the inserted tokens when we hit a DONE
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true
| ODUMMY token -> isTypeContinuator token
| _ -> false
let rec isForLoopContinuator token =
match token with
// This token may align with the "for" without closing the construct, e.g.
// for ... do
// ...
// done
| DONE -> true
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true// The following arise during reprocessing of the inserted tokens when we hit a DONE
| ODUMMY token -> isForLoopContinuator token
| _ -> false
let rec isWhileBlockContinuator token =
match token with
// This token may align with the "while" without closing the construct, e.g.
// while ... do
// ...
// done
| DONE -> true
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE
| ODUMMY token -> isWhileBlockContinuator token
| _ -> false
let rec isLetContinuator token =
match token with
// This token may align with the "let" without closing the construct, e.g.
// let ...
// and ...
| AND -> true
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE
| ODUMMY token -> isLetContinuator token
| _ -> false
let rec isTypeSeqBlockElementContinuator token =
match token with
// A sequence of items separated by '|' counts as one sequence block element, e.g.
// type x =
// | A <-- These together count as one element
// | B <-- These together count as one element
// member x.M1
// member x.M2
| BAR -> true
| OBLOCKBEGIN | ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true // The following arise during reprocessing of the inserted tokens when we hit a DONE
| ODUMMY token -> isTypeSeqBlockElementContinuator token
| _ -> false
// Work out when a token doesn't terminate a single item in a sequence definition
let rec isSeqBlockElementContinuator token =
isInfix token ||
// Infix tokens may align with the first column of a sequence block without closing a sequence element and starting a new one
// e.g.
// let f x
// h x
// |> y <------- NOTE: Not a new element in the sequence
match token with
// The following tokens may align with the first column of a sequence block without closing a sequence element and starting a new one *)
// e.g.
// new MenuItem("&Open...",
// new EventHandler(fun _ _ ->
// ...
// ), <------- NOTE RPAREN HERE
// Shortcut.CtrlO)
| END | AND | WITH | THEN | RPAREN | RBRACE _ | BAR_RBRACE | RBRACK | BAR_RBRACK | RQUOTE _ -> true
// The following arise during reprocessing of the inserted tokens when we hit a DONE
| ORIGHT_BLOCK_END _ | OBLOCKEND _ | ODECLEND _ -> true
| ODUMMY token -> isSeqBlockElementContinuator token
| _ -> false
let rec isWithAugmentBlockContinuator token =
match token with
// This token may align with "with" of an augmentation block without closing the construct, e.g.
// interface Foo
// with
// member ...
// end
| END -> true
| ODUMMY token -> isWithAugmentBlockContinuator token
| _ -> false
let isAtomicExprEndToken token =
match token with
| IDENT _
| INT8 _ | INT16 _ | INT32 _ | INT64 _ | NATIVEINT _
| UINT8 _ | UINT16 _ | UINT32 _ | UINT64 _ | UNATIVEINT _
| DECIMAL _ | BIGNUM _ | STRING _ | BYTEARRAY _ | CHAR _
| IEEE32 _ | IEEE64 _
| RPAREN | RBRACK | RBRACE _ | BAR_RBRACE | BAR_RBRACK | END
| NULL | FALSE | TRUE | UNDERSCORE -> true
| _ -> false
//----------------------------------------------------------------------------
// give a 'begin' token, does an 'end' token match?
//--------------------------------------------------------------------------
let parenTokensBalance token1 token2 =
match token1, token2 with
| LPAREN, RPAREN
| LBRACE _, RBRACE _
| LBRACE_BAR, BAR_RBRACE
| LBRACK, RBRACK
| INTERFACE, END
| CLASS, END
| SIG, END
| STRUCT, END
| INTERP_STRING_BEGIN_PART _, INTERP_STRING_END _
| INTERP_STRING_BEGIN_PART _, INTERP_STRING_PART _
| INTERP_STRING_PART _, INTERP_STRING_PART _
| INTERP_STRING_PART _, INTERP_STRING_END _
| LBRACK_BAR, BAR_RBRACK
| LESS true, GREATER true
| BEGIN, END -> true
| LQUOTE q1, RQUOTE q2 when q1 = q2 -> true
| _ -> false
/// Used to save some aspects of the lexbuffer state
[<Struct>]
type LexbufState(startPos: Position,
endPos : Position,
pastEOF : bool) =
member _.StartPos = startPos
member _.EndPos = endPos
member _.PastEOF = pastEOF
override this.ToString() =
$"({this.StartPos}--{this.EndPos})"
/// Used to save the state related to a token
/// Treat as though this is read-only.
[<Class>]
type TokenTup =
// This is mutable for performance reasons.
val mutable Token : token
val mutable LexbufState : LexbufState
val mutable LastTokenPos: Position
new (token, state, lastTokenPos) =
{ Token = token; LexbufState = state;LastTokenPos = lastTokenPos }
/// Returns starting position of the token
member x.StartPos = x.LexbufState.StartPos
/// Returns end position of the token
member x.EndPos = x.LexbufState.EndPos
override this.ToString() =
$"{this.Token} ({this.StartPos}--{this.EndPos})"
type TokenTupPool() =
/// Arbitrary.
/// When parsing the compiler's source files, the pool didn't come close to reaching this limit.
/// Therefore, this seems like a reasonable limit to handle 99% of cases.
[<Literal>]
let maxSize = 100
let mutable currentPoolSize = 0
let stack = Stack(10)
member pool.Rent() =
if stack.Count = 0 then
if currentPoolSize < maxSize then
stack.Push(TokenTup(Unchecked.defaultof<_>, Unchecked.defaultof<_>, Unchecked.defaultof<_>))
currentPoolSize <- currentPoolSize + 1
pool.Rent()
else
assert false
TokenTup(Unchecked.defaultof<_>, Unchecked.defaultof<_>, Unchecked.defaultof<_>)
else
stack.Pop()
member _.Return(x: TokenTup) =
x.Token <- Unchecked.defaultof<_>
x.LexbufState <- Unchecked.defaultof<_>
x.LastTokenPos <- Unchecked.defaultof<_>
if stack.Count >= maxSize then
assert false
else
stack.Push x
/// Returns a token 'tok' with the same position as this token
member pool.UseLocation(x: TokenTup, tok) =
let tokState = x.LexbufState
let tokTup = pool.Rent()
tokTup.Token <- tok
tokTup.LexbufState <- LexbufState(tokState.StartPos, tokState.EndPos, false)
tokTup.LastTokenPos <- x.LastTokenPos
tokTup
/// Returns a token 'tok' with the same position as this token, except that
/// it is shifted by specified number of characters from the left and from the right
/// Note: positive value means shift to the right in both cases
member pool.UseShiftedLocation(x: TokenTup, tok, shiftLeft, shiftRight) =
let tokState = x.LexbufState
let tokTup = pool.Rent()
tokTup.Token <- tok
tokTup.LexbufState <- LexbufState(tokState.StartPos.ShiftColumnBy shiftLeft, tokState.EndPos.ShiftColumnBy shiftRight, false)
tokTup.LastTokenPos <- x.LastTokenPos
tokTup
//----------------------------------------------------------------------------
// Utilities for the tokenizer that are needed in other places
//--------------------------------------------------------------------------*)
[<return: Struct>]
let (|Equals|_|) (s: string) (span: ReadOnlySpan<char>) =
if span.SequenceEqual(s.AsSpan()) then ValueSome Equals
else ValueNone
[<return: Struct>]
let (|StartsWith|_|) (s: string) (span: ReadOnlySpan<char>) =
if span.StartsWith(s.AsSpan()) then ValueSome StartsWith
else ValueNone
// Strip a bunch of leading '>' of a token, at the end of a typar application
// Note: this is used in the 'service.fs' to do limited postprocessing
[<return: Struct>]
let (|TyparsCloseOp|_|) (txt: string) =
if not (txt.StartsWith ">") then
ValueNone
else
match txt.AsSpan().IndexOfAnyExcept '>' with
| -1 -> ValueSome(struct (Array.init txt.Length (fun _ -> GREATER), ValueNone))
| angles ->
let afterAngles = txt.AsSpan angles
let afterOp =
match afterAngles with
| Equals "." -> ValueSome DOT
| Equals "]" -> ValueSome RBRACK
| Equals "-" -> ValueSome MINUS
| Equals ".." -> ValueSome DOT_DOT
| Equals "?" -> ValueSome QMARK
| Equals "??" -> ValueSome QMARK_QMARK
| Equals ":=" -> ValueSome COLON_EQUALS
| Equals "::" -> ValueSome COLON_COLON
| Equals "*" -> ValueSome STAR
| Equals "&" -> ValueSome AMP
| Equals "->" -> ValueSome RARROW
| Equals "<-" -> ValueSome LARROW
| Equals "=" -> ValueSome EQUALS
| Equals "<" -> ValueSome (LESS false)
| Equals "$" -> ValueSome DOLLAR
| Equals "%" -> ValueSome (PERCENT_OP "%")
| Equals "%%" -> ValueSome (PERCENT_OP "%%")
| Equals "" -> ValueNone
| StartsWith "="
| StartsWith "!="
| StartsWith "<"
| StartsWith ">"
| StartsWith "$" -> ValueSome (INFIX_COMPARE_OP (afterAngles.ToString()))
| StartsWith "&" -> ValueSome (INFIX_AMP_OP (afterAngles.ToString()))
| StartsWith "|" -> ValueSome (INFIX_BAR_OP (afterAngles.ToString()))
| StartsWith "!"
| StartsWith "?"
| StartsWith "~" -> ValueSome (PREFIX_OP (afterAngles.ToString()))
| StartsWith "@"
| StartsWith "^" -> ValueSome (INFIX_AT_HAT_OP (afterAngles.ToString()))
| StartsWith "+"
| StartsWith "-" -> ValueSome (PLUS_MINUS_OP (afterAngles.ToString()))
| StartsWith "**" -> ValueSome (INFIX_STAR_STAR_OP (afterAngles.ToString()))
| StartsWith "*"
| StartsWith "/"
| StartsWith "%" -> ValueSome (INFIX_STAR_DIV_MOD_OP (afterAngles.ToString()))
| _ -> ValueNone
ValueSome(struct (Array.init angles (fun _ -> GREATER), afterOp))
[<Struct>]
type PositionWithColumn =
val Position: Position
val Column: int
new (position: Position, column: int) = { Position = position; Column = column }
//----------------------------------------------------------------------------
// build a LexFilter
//--------------------------------------------------------------------------*)
type LexFilterImpl (
indentationSyntaxStatus: IndentationAwareSyntaxStatus,
compilingFSharpCore,
lexer: (Lexbuf -> token),
lexbuf: Lexbuf,
debug: bool
) =
//----------------------------------------------------------------------------
// Part I. Building a new lex stream from an old
//
// A lexbuf is a stateful object that can be enticed to emit tokens by calling
// 'lexer' functions designed to work with the lexbuf. Here we fake a new stream
// coming out of an existing lexbuf. Ideally lexbufs would be abstract interfaces
// and we could just build a new abstract interface that wraps an existing one.
// However that is not how F# lexbufs currently work.
//
// Part of the fakery we perform involves buffering a lookahead token which
// we eventually pass on to the client. However, this client also looks at
// other aspects of the 'state' of lexbuf directly, e.g. F# lexbufs have a triple
// (start-pos, end-pos, eof-reached)
//
// You may ask why the F# parser reads this lexbuf state directly. Well, the
// pars.fsy code itself it doesn't, but the parser engines (prim-parsing.fs)
// certainly do for F#. e.g. when these parsers read a token
// from the lexstream they also read the position information and keep this
// a related stack.
//
// Anyway, this explains the functions getLexbufState(), setLexbufState() etc.
//--------------------------------------------------------------------------
// Make sure we don't report 'eof' when inserting a token, and set the positions to the
// last reported token position
let lexbufStateForInsertedDummyTokens (lastTokenStartPos, lastTokenEndPos) =
LexbufState(lastTokenStartPos, lastTokenEndPos, false)
let getLexbufState() =
LexbufState(lexbuf.StartPos, lexbuf.EndPos, lexbuf.IsPastEndOfStream)
let setLexbufState (p: LexbufState) =
lexbuf.StartPos <- p.StartPos
lexbuf.EndPos <- p.EndPos
lexbuf.IsPastEndOfStream <- p.PastEOF
let posOfTokenTup (tokenTup: TokenTup) =
match tokenTup.Token with
// EOF token is processed as if on column -1
// This forces the closure of all contexts.
| EOF _ -> tokenTup.LexbufState.StartPos.ColumnMinusOne, tokenTup.LexbufState.EndPos.ColumnMinusOne
| _ -> tokenTup.LexbufState.StartPos, tokenTup.LexbufState.EndPos
let startPosOfTokenTup (tokenTup: TokenTup) =
match tokenTup.Token with
// EOF token is processed as if on column -1
// This forces the closure of all contexts.
| EOF _ -> tokenTup.LexbufState.StartPos.ColumnMinusOne
| _ -> tokenTup.LexbufState.StartPos
//----------------------------------------------------------------------------
// TokenTup pool
//--------------------------------------------------------------------------
let pool = TokenTupPool()
//----------------------------------------------------------------------------
// Part II. The state of the new lex stream object.
//--------------------------------------------------------------------------
// Ok, we're going to the wrapped lexbuf. Set the lexstate back so that the lexbuf
// appears consistent and correct for the wrapped lexer function.
let mutable savedLexbufState = Unchecked.defaultof<LexbufState>
let mutable haveLexbufState = false
let runWrappedLexerInConsistentLexbufState() =
let state = if haveLexbufState then savedLexbufState else getLexbufState()
setLexbufState state
let lastTokenEnd = state.EndPos
let token = lexer lexbuf
XmlDocStore.AddGrabPoint(lexbuf)
// Now we've got the token, remember the lexbuf state, associating it with the token
// and remembering it as the last observed lexbuf state for the wrapped lexer function.
let tokenLexbufState = getLexbufState()
savedLexbufState <- tokenLexbufState
haveLexbufState <- true
let tokenTup = pool.Rent()
tokenTup.Token <- token
tokenTup.LexbufState <- tokenLexbufState
tokenTup.LastTokenPos <- lastTokenEnd
tokenTup
//----------------------------------------------------------------------------
// Fetch a raw token, either from the old lexer or from our delayedStack
//--------------------------------------------------------------------------
let delayedStack = Stack<TokenTup>()
let mutable tokensThatNeedNoProcessingCount = 0
let delayToken tokenTup = delayedStack.Push tokenTup
let delayTokenNoProcessing tokenTup = delayToken tokenTup; tokensThatNeedNoProcessingCount <- tokensThatNeedNoProcessingCount + 1
let popNextTokenTup() =
if delayedStack.Count > 0 then
let tokenTup = delayedStack.Pop()
if debug then dprintf "popNextTokenTup: delayed token, tokenStartPos = %a\n" outputPos (startPosOfTokenTup tokenTup)
tokenTup
else
if debug then dprintf "popNextTokenTup: no delayed tokens, running lexer...\n"
runWrappedLexerInConsistentLexbufState()
//----------------------------------------------------------------------------
// Part III. Initial configuration of state.
//
// We read a token. In F# Interactive the parser thread will be correctly blocking
// here.
//--------------------------------------------------------------------------
let mutable initialized = false
let mutable offsideStack = []
let mutable prevWasAtomicEnd = false
let peekInitial() =
// Forget the lexbuf state we might have saved from previous input
haveLexbufState <- false
let initialLookaheadTokenTup = popNextTokenTup()
if debug then dprintf "first token: initialLookaheadTokenLexbufState = %a\n" outputPos (startPosOfTokenTup initialLookaheadTokenTup)
delayToken initialLookaheadTokenTup
initialized <- true
offsideStack <- (CtxtSeqBlock(FirstInSeqBlock, startPosOfTokenTup initialLookaheadTokenTup, NoAddBlockEnd)) :: offsideStack
initialLookaheadTokenTup
let reportDiagnostic reportF (s: TokenTup) msg =
reportF (IndentationProblem(msg, mkSynRange (startPosOfTokenTup s) s.LexbufState.EndPos))
let warn (s: TokenTup) msg =
reportDiagnostic warning s msg
let error (s: TokenTup) msg =
reportDiagnostic errorR s msg
// 'query { join x in ys ... }'
// 'query { ...
// join x in ys ... }'
// 'query { for ... do
// join x in ys ... }'
let detectJoinInCtxt stack =
let rec check s =
match s with
| CtxtParen(LBRACE _, _) :: _ -> true
| (CtxtSeqBlock _ | CtxtDo _ | CtxtFor _) :: rest -> check rest
| _ -> false
match stack with
| CtxtVanilla _ :: rest -> check rest
| _ -> false
//----------------------------------------------------------------------------
// Part IV. Helper functions for pushing contexts and giving good warnings
// if a context is undented.
//
// Undentation rules
//--------------------------------------------------------------------------
let relaxWhitespace2 = lexbuf.SupportsFeature LanguageFeature.RelaxWhitespace2
let strictIndentation =
lexbuf.StrictIndentation |> Option.defaultWith (fun _ -> lexbuf.SupportsFeature LanguageFeature.StrictIndentation)
//let indexerNotationWithoutDot = lexbuf.SupportsFeature LanguageFeature.IndexerNotationWithoutDot
let tryPushCtxt strict ignoreIndent tokenTup (newCtxt: Context) =
let rec undentationLimit strict stack =
match newCtxt, stack with
| _, [] -> PositionWithColumn(newCtxt.StartPos, -1)
// ignore Vanilla because a SeqBlock is always coming
| _, CtxtVanilla _ :: rest -> undentationLimit strict rest
| CtxtSeqBlock(FirstInSeqBlock, _, _), (CtxtDo _ as limitCtxt) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ | CtxtModuleBody _) :: _ ->
PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1)
| CtxtSeqBlock(FirstInSeqBlock, _, _), CtxtWithAsAugment _ :: (CtxtTypeDefns _ as limitCtxt) :: _ ->
PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1)
| _, CtxtSeqBlock _ :: rest when not strict -> undentationLimit strict rest
| _, CtxtParen _ :: rest when not strict -> undentationLimit strict rest
// 'begin match' limited by minimum of two
// '(match' limited by minimum of two
| _, (CtxtMatch _ as ctxt1) :: CtxtSeqBlock _ :: (CtxtParen ((BEGIN | LPAREN), _) as ctxt2) :: _
-> if ctxt1.StartCol <= ctxt2.StartCol
then PositionWithColumn(ctxt1.StartPos, ctxt1.StartCol)
else PositionWithColumn(ctxt2.StartPos, ctxt2.StartCol)
// Insert this rule to allow
// begin match 1 with
// | 1 -> ()
// | 2 ->
// f() // <- No offside warning here
// end
// when relaxWhitespace2
// Otherwise the rule of 'match ... with' limited by 'match' (given RelaxWhitespace2)
// will consider the CtxtMatch as the limiting context instead of allowing undentation until the parenthesis
// Test here: Tests/FSharp.Compiler.ComponentTests/Conformance/LexicalFiltering/Basic/OffsideExceptions.fs, RelaxWhitespace2_AllowedBefore11
| _, (CtxtMatchClauses _ as ctxt1) :: (CtxtMatch _) :: CtxtSeqBlock _ :: (CtxtParen ((BEGIN | LPAREN), _) as ctxt2) :: _ when relaxWhitespace2
-> if ctxt1.StartCol <= ctxt2.StartCol
then PositionWithColumn(ctxt1.StartPos, ctxt1.StartCol)
else PositionWithColumn(ctxt2.StartPos, ctxt2.StartCol)
// 'let ... = function' limited by 'let', precisely
// This covers the common form
//
// let f x = function
// | Case1 -> ...
// | Case2 -> ...
| CtxtMatchClauses _, CtxtFunction _ :: CtxtSeqBlock _ :: (CtxtLetDecl _ as limitCtxt) :: _rest
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// Otherwise 'function ...' places no limit until we hit a CtxtLetDecl etc... (Recursive)
| CtxtMatchClauses _, CtxtFunction _ :: rest
-> undentationLimit false rest
// 'try ... with' limited by 'try'
| _, (CtxtMatchClauses _ :: (CtxtTry _ as limitCtxt) :: _rest)
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// 'match ... with' limited by 'match' (given RelaxWhitespace2)
| _, (CtxtMatchClauses _ :: (CtxtMatch _ as limitCtxt) :: _rest) when relaxWhitespace2
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// 'fun ->' places no limit until we hit a CtxtLetDecl etc... (Recursive)
| _, CtxtFun _ :: rest
-> undentationLimit false rest
// 'let ... = f ... begin' limited by 'let' (given RelaxWhitespace2)
// 'let (' (pattern match) limited by 'let' (given RelaxWhitespace2)
// 'let [' (pattern match) limited by 'let' (given RelaxWhitespace2)
// 'let {' (pattern match) limited by 'let' (given RelaxWhitespace2)
// 'let [|' (pattern match) limited by 'let' (given RelaxWhitespace2)
// 'let x : {|' limited by 'let' (given RelaxWhitespace2)
// 'let x : Foo<' limited by 'let' (given RelaxWhitespace2)
// 'let (ActivePattern <@' limited by 'let' (given RelaxWhitespace2)
// 'let (ActivePattern <@@' limited by 'let' (given RelaxWhitespace2)
// Same for 'match', 'if', 'then', 'else', 'for', 'while', 'member', 'when', and everything: No need to specify rules like the 'then' and 'else's below over and over again
// Test here: Tests/FSharp.Compiler.ComponentTests/Conformance/LexicalFiltering/Basic/OffsideExceptions.fs, RelaxWhitespace2
| _, CtxtParen (TokenLExprParen, _) :: rest
// 'let x = { y =' limited by 'let' (given RelaxWhitespace2) etc.
// 'let x = {| y =' limited by 'let' (given RelaxWhitespace2) etc.
// Test here: Tests/FSharp.Compiler.ComponentTests/Conformance/LexicalFiltering/Basic/OffsideExceptions.fs, RelaxWhitespace2
| _, CtxtSeqBlock _ :: CtxtParen (TokenLExprParen, _) :: rest when relaxWhitespace2
-> undentationLimit false rest
// 'f ...{' places no limit until we hit a CtxtLetDecl etc...
// 'f ...[' places no limit until we hit a CtxtLetDecl etc...
// 'f ...[|' places no limit until we hit a CtxtLetDecl etc...
| _, CtxtParen ((LBRACE _ | LBRACK | LBRACK_BAR), _) :: CtxtSeqBlock _ :: rest
| _, CtxtParen ((LBRACE _ | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: CtxtSeqBlock _ :: rest
| _, CtxtSeqBlock _ :: CtxtParen((LBRACE _ | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: CtxtSeqBlock _ :: rest
-> undentationLimit false rest
// MAJOR PERMITTED UNDENTATION This is allowing:
// if x then y else
// let x = 3 + 4
// x + x
// This is a serious thing to allow, but is required since there is no "return" in this language.
// Without it there is no way of escaping special cases in large bits of code without indenting the main case.
| CtxtSeqBlock _, CtxtElse _ :: (CtxtIf _ as limitCtxt) :: _rest
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// Permitted inner-construct precise block alignment:
// interface ...
// with ...
// end
//
// type ...
// with ...
// end
| CtxtWithAsAugment _, (CtxtInterfaceHead _ | CtxtMemberHead _ | CtxtException _ | CtxtTypeDefns _ as limitCtxt :: _rest)
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// Permit undentation via parentheses (or begin/end) following a 'then', 'else' or 'do':
// if nr > 0 then (
// nr <- nr - 1
// acc <- d
// i <- i - 1
// ) else (
// i <- -1
// )
// PERMITTED UNDENTATION: Inner construct (then, with, else, do) that dangle, places no limit until we hit the corresponding leading construct CtxtIf, CtxtFor, CtxtWhile, CtxtVanilla etc... *)
// e.g. if ... then ...
// expr
// else
// expr
// rather than forcing
// if ...
// then expr
// else expr
// Also ...... with
// ... <-- this is before the "with"
// end
| _, (CtxtWithAsAugment _ | CtxtThen _ | CtxtElse _ | CtxtDo _ ) :: rest
-> undentationLimit false rest
// '... (function ->' places no limit until we hit a CtxtLetDecl etc.... (Recursive)
//
// e.g.
// let fffffff() = function
// | [] -> 0
// | _ -> 1
//
// Note this does not allow
// let fffffff() = function _ ->
// 0
// which is not a permitted undentation. This undentation would make no sense if there are multiple clauses in the 'function', which is, after all, what 'function' is really for
// let fffffff() = function 1 ->
// 0
// | 2 -> ... <---- not allowed
| _, CtxtFunction _ :: rest
-> undentationLimit false rest
// 'module ... : sig' limited by 'module'
// 'module ... : struct' limited by 'module'
// 'module ... : begin' limited by 'module'
// 'if ... then (' limited by 'if'
// 'if ... then {' limited by 'if'
// 'if ... then [' limited by 'if'
// 'if ... then [|' limited by 'if'
// 'if ... else (' limited by 'if'
// 'if ... else {' limited by 'if'
// 'if ... else [' limited by 'if'
// 'if ... else [|' limited by 'if'
| _, CtxtParen ((SIG | STRUCT | BEGIN), _) :: CtxtSeqBlock _ :: (CtxtModuleBody (_, false) as limitCtxt) :: _
| _, CtxtParen ((BEGIN | LPAREN | LBRACK | LBRACE _ | LBRACE_BAR | LBRACK_BAR), _) :: CtxtSeqBlock _ :: CtxtThen _ :: (CtxtIf _ as limitCtxt) :: _
| _, CtxtParen ((BEGIN | LPAREN | LBRACK | LBRACE _ | LBRACE_BAR | LBRACK_BAR | LBRACK_LESS), _) :: CtxtSeqBlock _ :: CtxtElse _ :: (CtxtIf _ as limitCtxt) :: _
// 'f ... (' in seqblock limited by 'f'
// 'f ... {' in seqblock limited by 'f' NOTE: this is covered by the more generous case above
// 'f ... [' in seqblock limited by 'f'
// 'f ... [|' in seqblock limited by 'f'
// 'f ... Foo<' in seqblock limited by 'f'
| _, CtxtParen ((BEGIN | LPAREN | LESS true | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _
// 'type C = class ... ' limited by 'type'
// 'type C = interface ... ' limited by 'type'
// 'type C = struct ... ' limited by 'type'
| _, CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1)
// 'type C(' limited by 'type'
| _, CtxtSeqBlock _ :: CtxtParen(LPAREN, _) :: (CtxtTypeDefns _ as limitCtxt) :: _
// 'static member C(' limited by 'static', likewise others
| _, CtxtSeqBlock _ :: CtxtParen(LPAREN, _) :: (CtxtMemberHead _ as limitCtxt) :: _
// 'static member P with get() = ' limited by 'static', likewise others
| _, CtxtWithAsLet _ :: (CtxtMemberHead _ as limitCtxt) :: _
when lexbuf.SupportsFeature LanguageFeature.RelaxWhitespace
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1)
// REVIEW: document these
| _, CtxtSeqBlock _ :: CtxtParen((BEGIN | LPAREN | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _
| CtxtSeqBlock _, CtxtParen ((BEGIN | LPAREN | LBRACE _ | LBRACE_BAR | LBRACK | LBRACK_BAR), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ | CtxtLetDecl _ | CtxtMemberBody _ | CtxtWithAsLet _ as limitCtxt) :: _
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1)
// Permitted inner-construct (e.g. "then" block and "else" block in overall
// "if-then-else" block ) block alignment:
// if ...
// then expr
// elif expr
// else expr
| (CtxtIf _ | CtxtElse _ | CtxtThen _), (CtxtIf _ as limitCtxt) :: _rest
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// Permitted inner-construct precise block alignment:
// while ...
// do expr
// done
| CtxtDo _, (CtxtFor _ | CtxtWhile _ as limitCtxt) :: _rest
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
// These contexts all require indentation by at least one space
| _, (CtxtInterfaceHead _ | CtxtNamespaceHead _ | CtxtModuleHead _ | CtxtException _ | CtxtModuleBody (_, false) | CtxtIf _ | CtxtWithAsLet _ | CtxtLetDecl _ | CtxtMemberHead _ | CtxtMemberBody _ as limitCtxt :: _)
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1)
// These contexts can have their contents exactly aligning
| _, (CtxtParen _ | CtxtFor _ | CtxtWhen _ | CtxtWhile _ | CtxtTypeDefns _ | CtxtMatch _ | CtxtModuleBody (_, true) | CtxtNamespaceBody _ | CtxtTry _ | CtxtMatchClauses _ | CtxtSeqBlock _ as limitCtxt :: _)
-> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol)
let isCorrectIndent =
if ignoreIndent then true else
match newCtxt with
// Don't bother to check pushes of Vanilla blocks since we've
// always already pushed a SeqBlock at this position.
| CtxtVanilla _
// String interpolation inner expressions are not limited (e.g. multiline strings)
| CtxtParen((INTERP_STRING_BEGIN_PART _ | INTERP_STRING_PART _),_) -> true
| _ ->
let p1 = undentationLimit true offsideStack
let c2 = newCtxt.StartCol
let isCorrectIndent = c2 >= p1.Column
if not isCorrectIndent then
let warnF = if strictIndentation then error else warn
warnF tokenTup
(if debug then
sprintf "possible incorrect indentation: this token is offside of context at position %s, newCtxt = %A, stack = %A, newCtxtPos = %s, c1 = %d, c2 = %d"
(warningStringOfPosition p1.Position) newCtxt offsideStack (stringOfPos newCtxt.StartPos) p1.Column c2