-
Notifications
You must be signed in to change notification settings - Fork 805
/
Copy pathParseAndCheckInputs.fs
1989 lines (1635 loc) · 82.9 KB
/
ParseAndCheckInputs.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.
/// Contains logic to coordinate the parsing and checking of one or a group of files
module internal FSharp.Compiler.ParseAndCheckInputs
open System
open System.Diagnostics
open System.IO
open System.Threading
open System.Collections.Generic
open FSharp.Compiler.Parser
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open Internal.Utilities.Text.Lexing
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.CheckBasics
open FSharp.Compiler.CheckDeclarations
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.CompilerDiagnostics
open FSharp.Compiler.CompilerImports
open FSharp.Compiler.Diagnostics
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Features
open FSharp.Compiler.IO
open FSharp.Compiler.Lexhelp
open FSharp.Compiler.NameResolution
open FSharp.Compiler.ParseHelpers
open FSharp.Compiler.Syntax
open FSharp.Compiler.SyntaxTrivia
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Position
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Xml
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TcGlobals
let CanonicalizeFilename fileName =
let basic = FileSystemUtils.fileNameOfPath fileName
String.capitalize (
try
FileSystemUtils.chopExtension basic
with _ ->
basic
)
let IsScript fileName =
FSharpScriptFileSuffixes |> List.exists (FileSystemUtils.checkSuffix fileName)
let IsMLCompatFile fileName =
FSharpMLCompatFileSuffixes |> List.exists (FileSystemUtils.checkSuffix fileName)
// Give a unique name to the different kinds of inputs. Used to correlate signature and implementation files
// QualFileNameOfModuleName - files with a single module declaration or an anonymous module
let QualFileNameOfModuleName m fileName modname =
QualifiedNameOfFile(mkSynId m (textOfLid modname + (if IsScript fileName then "$fsx" else "")))
let QualFileNameOfFilename m fileName =
QualifiedNameOfFile(mkSynId m (CanonicalizeFilename fileName + (if IsScript fileName then "$fsx" else "")))
// Interactive fragments
let ComputeQualifiedNameOfFileFromUniquePath (m, p: string list) =
QualifiedNameOfFile(mkSynId m (String.concat "_" p))
let QualFileNameOfSpecs fileName specs =
match specs with
| [ SynModuleOrNamespaceSig(longId = modname; kind = kind; range = m) ] when kind.IsModule ->
QualFileNameOfModuleName m fileName modname
| [ SynModuleOrNamespaceSig(kind = kind; range = m) ] when not kind.IsModule -> QualFileNameOfFilename m fileName
| _ -> QualFileNameOfFilename (mkRange fileName pos0 pos0) fileName
let QualFileNameOfImpls fileName specs =
match specs with
| [ SynModuleOrNamespace(longId = modname; kind = kind; range = m) ] when kind.IsModule -> QualFileNameOfModuleName m fileName modname
| [ SynModuleOrNamespace(kind = kind; range = m) ] when not kind.IsModule -> QualFileNameOfFilename m fileName
| _ -> QualFileNameOfFilename (mkRange fileName pos0 pos0) fileName
let PrependPathToQualFileName x (QualifiedNameOfFile q) =
ComputeQualifiedNameOfFileFromUniquePath(q.idRange, pathOfLid x @ [ q.idText ])
let PrependPathToImpl x (SynModuleOrNamespace(longId, isRecursive, kind, decls, xmlDoc, attribs, accessibility, range, trivia)) =
SynModuleOrNamespace(x @ longId, isRecursive, kind, decls, xmlDoc, attribs, accessibility, range, trivia)
let PrependPathToSpec x (SynModuleOrNamespaceSig(longId, isRecursive, kind, decls, xmlDoc, attribs, accessibility, range, trivia)) =
SynModuleOrNamespaceSig(x @ longId, isRecursive, kind, decls, xmlDoc, attribs, accessibility, range, trivia)
let PrependPathToInput x inp =
match inp with
| ParsedInput.ImplFile(ParsedImplFileInput(b, c, q, d, hd, impls, e, trivia, i)) ->
ParsedInput.ImplFile(
ParsedImplFileInput(b, c, PrependPathToQualFileName x q, d, hd, List.map (PrependPathToImpl x) impls, e, trivia, i)
)
| ParsedInput.SigFile(ParsedSigFileInput(b, q, d, hd, specs, trivia, i)) ->
ParsedInput.SigFile(ParsedSigFileInput(b, PrependPathToQualFileName x q, d, hd, List.map (PrependPathToSpec x) specs, trivia, i))
let IsValidAnonModuleName (modname: string) =
modname |> String.forall (fun c -> Char.IsLetterOrDigit c || c = '_')
let ComputeAnonModuleName check defaultNamespace fileName (m: range) =
let modname = CanonicalizeFilename fileName
if check && not (IsValidAnonModuleName modname) && not (IsScript fileName) then
warning (Error(FSComp.SR.buildImplicitModuleIsNotLegalIdentifier (modname, (FileSystemUtils.fileNameOfPath fileName)), m))
let combined =
match defaultNamespace with
| None -> modname
| Some ns -> textOfPath [ ns; modname ]
let anonymousModuleNameRange =
let fileName = m.FileName
mkRange fileName pos0 pos0
pathToSynLid anonymousModuleNameRange (splitNamespace combined)
let FileRequiresModuleOrNamespaceDecl isLast isExe fileName =
not (isLast && isExe) && not (IsScript fileName || IsMLCompatFile fileName)
let PostParseModuleImpl (_i, defaultNamespace, isLastCompiland, fileName, impl) =
match impl with
| ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(lid, isRec, kind, decls, xmlDoc, attribs, access, m, trivia)) ->
let lid =
match lid with
| [ id ] when kind.IsModule && id.idText = MangledGlobalName ->
error (Error(FSComp.SR.buildInvalidModuleOrNamespaceName (), id.idRange))
| id :: rest when id.idText = MangledGlobalName -> rest
| _ -> lid
SynModuleOrNamespace(lid, isRec, kind, decls, xmlDoc, attribs, access, m, trivia)
| ParsedImplFileFragment.AnonModule(defs, m) ->
let isLast, isExe = isLastCompiland
if FileRequiresModuleOrNamespaceDecl isLast isExe fileName then
match defs with
| SynModuleDecl.NestedModule _ :: _ -> errorR (Error(FSComp.SR.noEqualSignAfterModule (), trimRangeToLine m))
| _ -> errorR (Error(FSComp.SR.buildMultiFileRequiresNamespaceOrModule (), trimRangeToLine m))
let modname =
ComputeAnonModuleName (not (isNil defs)) defaultNamespace fileName (trimRangeToLine m)
let trivia: SynModuleOrNamespaceTrivia =
{
LeadingKeyword = SynModuleOrNamespaceLeadingKeyword.None
}
SynModuleOrNamespace(modname, false, SynModuleOrNamespaceKind.AnonModule, defs, PreXmlDoc.Empty, [], None, m, trivia)
| ParsedImplFileFragment.NamespaceFragment(lid, isRecursive, kind, decls, xmlDoc, attributes, range, trivia) ->
let lid, kind =
match lid with
| id :: rest when id.idText = MangledGlobalName ->
let kind =
if rest.IsEmpty then
SynModuleOrNamespaceKind.GlobalNamespace
else
kind
rest, kind
| _ -> lid, kind
SynModuleOrNamespace(lid, isRecursive, kind, decls, xmlDoc, attributes, None, range, trivia)
let PostParseModuleSpec (_i, defaultNamespace, isLastCompiland, fileName, intf) =
match intf with
| ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(lid, isRec, kind, decls, xmlDoc, attribs, access, m, trivia)) ->
let lid =
match lid with
| [ id ] when kind.IsModule && id.idText = MangledGlobalName ->
error (Error(FSComp.SR.buildInvalidModuleOrNamespaceName (), id.idRange))
| id :: rest when id.idText = MangledGlobalName -> rest
| _ -> lid
SynModuleOrNamespaceSig(lid, isRec, SynModuleOrNamespaceKind.NamedModule, decls, xmlDoc, attribs, access, m, trivia)
| ParsedSigFileFragment.AnonModule(defs, m) ->
let isLast, isExe = isLastCompiland
if FileRequiresModuleOrNamespaceDecl isLast isExe fileName then
match defs with
| SynModuleSigDecl.NestedModule _ :: _ -> errorR (Error(FSComp.SR.noEqualSignAfterModule (), m))
| _ -> errorR (Error(FSComp.SR.buildMultiFileRequiresNamespaceOrModule (), m))
let modname =
ComputeAnonModuleName (not (isNil defs)) defaultNamespace fileName (trimRangeToLine m)
let trivia: SynModuleOrNamespaceSigTrivia =
{
LeadingKeyword = SynModuleOrNamespaceLeadingKeyword.None
}
SynModuleOrNamespaceSig(modname, false, SynModuleOrNamespaceKind.AnonModule, defs, PreXmlDoc.Empty, [], None, m, trivia)
| ParsedSigFileFragment.NamespaceFragment(lid, isRecursive, kind, decls, xmlDoc, attributes, range, trivia) ->
let lid, kind =
match lid with
| id :: rest when id.idText = MangledGlobalName ->
let kind =
if rest.IsEmpty then
SynModuleOrNamespaceKind.GlobalNamespace
else
kind
rest, kind
| _ -> lid, kind
SynModuleOrNamespaceSig(lid, isRecursive, kind, decls, xmlDoc, attributes, None, range, trivia)
let GetScopedPragmasForHashDirective hd (langVersion: LanguageVersion) =
let supportsNonStringArguments =
langVersion.SupportsFeature(LanguageFeature.ParsedHashDirectiveArgumentNonQuotes)
[
match hd with
| ParsedHashDirective("nowarn", numbers, m) ->
for s in numbers do
let warningNumber =
match supportsNonStringArguments, s with
| _, ParsedHashDirectiveArgument.SourceIdentifier _ -> None
| true, ParsedHashDirectiveArgument.LongIdent _ -> None
| true, ParsedHashDirectiveArgument.Int32(n, _) -> GetWarningNumber(m, string n, true)
| true, ParsedHashDirectiveArgument.Ident(s, _) -> GetWarningNumber(m, s.idText, true)
| _, ParsedHashDirectiveArgument.String(s, _, _) -> GetWarningNumber(m, s, true)
| _ -> None
match warningNumber with
| None -> ()
| Some n -> ScopedPragma.WarningOff(m, n)
| _ -> ()
]
let private collectCodeComments (lexbuf: UnicodeLexing.Lexbuf) (tripleSlashComments: range list) =
[
yield! LexbufCommentStore.GetComments(lexbuf)
yield! (List.map CommentTrivia.LineComment tripleSlashComments)
]
|> List.sortBy (function
| CommentTrivia.LineComment r
| CommentTrivia.BlockComment r -> r.StartLine, r.StartColumn)
let PostParseModuleImpls
(
defaultNamespace,
fileName,
isLastCompiland,
ParsedImplFile(hashDirectives, impls),
lexbuf: UnicodeLexing.Lexbuf,
tripleSlashComments: range list,
identifiers: Set<string>
) =
let othersWithSameName =
impls
|> List.rev
|> List.tryPick (function
| ParsedImplFileFragment.NamedModule(SynModuleOrNamespace(longId = lid)) -> Some lid
| _ -> None)
match othersWithSameName with
| Some lid when impls.Length > 1 -> errorR (Error(FSComp.SR.buildMultipleToplevelModules (), rangeOfLid lid))
| _ -> ()
let impls =
impls
|> List.mapi (fun i x -> PostParseModuleImpl(i, defaultNamespace, isLastCompiland, fileName, x))
let qualName = QualFileNameOfImpls fileName impls
let isScript = IsScript fileName
let scopedPragmas =
[
for SynModuleOrNamespace(decls = decls) in impls do
for d in decls do
match d with
| SynModuleDecl.HashDirective(hd, _) -> yield! GetScopedPragmasForHashDirective hd lexbuf.LanguageVersion
| _ -> ()
for hd in hashDirectives do
yield! GetScopedPragmasForHashDirective hd lexbuf.LanguageVersion
]
let conditionalDirectives = LexbufIfdefStore.GetTrivia(lexbuf)
let codeComments = collectCodeComments lexbuf tripleSlashComments
let trivia: ParsedImplFileInputTrivia =
{
ConditionalDirectives = conditionalDirectives
CodeComments = codeComments
}
ParsedInput.ImplFile(
ParsedImplFileInput(fileName, isScript, qualName, scopedPragmas, hashDirectives, impls, isLastCompiland, trivia, identifiers)
)
let PostParseModuleSpecs
(
defaultNamespace,
fileName,
isLastCompiland,
ParsedSigFile(hashDirectives, specs),
lexbuf: UnicodeLexing.Lexbuf,
tripleSlashComments: range list,
identifiers: Set<string>
) =
let othersWithSameName =
specs
|> List.rev
|> List.tryPick (function
| ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(longId = lid)) -> Some lid
| _ -> None)
match othersWithSameName with
| Some lid when specs.Length > 1 -> errorR (Error(FSComp.SR.buildMultipleToplevelModules (), rangeOfLid lid))
| _ -> ()
let specs =
specs
|> List.mapi (fun i x -> PostParseModuleSpec(i, defaultNamespace, isLastCompiland, fileName, x))
let qualName = QualFileNameOfSpecs fileName specs
let scopedPragmas =
[
for SynModuleOrNamespaceSig(decls = decls) in specs do
for d in decls do
match d with
| SynModuleSigDecl.HashDirective(hd, _) -> yield! GetScopedPragmasForHashDirective hd lexbuf.LanguageVersion
| _ -> ()
for hd in hashDirectives do
yield! GetScopedPragmasForHashDirective hd lexbuf.LanguageVersion
]
let conditionalDirectives = LexbufIfdefStore.GetTrivia(lexbuf)
let codeComments = collectCodeComments lexbuf tripleSlashComments
let trivia: ParsedSigFileInputTrivia =
{
ConditionalDirectives = conditionalDirectives
CodeComments = codeComments
}
ParsedInput.SigFile(ParsedSigFileInput(fileName, qualName, scopedPragmas, hashDirectives, specs, trivia, identifiers))
type ModuleNamesDict = Map<string, Map<string, QualifiedNameOfFile>>
/// Checks if a module name is already given and deduplicates the name if needed.
let DeduplicateModuleName (moduleNamesDict: ModuleNamesDict) (fileName: string) (qualNameOfFile: QualifiedNameOfFile) =
let path = !! Path.GetDirectoryName(fileName)
let path =
if FileSystem.IsPathRootedShim path then
try
FileSystem.GetFullPathShim path
with _ ->
path
else
path
match moduleNamesDict.TryGetValue qualNameOfFile.Text with
| true, paths ->
match paths.TryGetValue path with
| true, pathV -> pathV, moduleNamesDict
| false, _ ->
let count = paths.Count + 1
let id = qualNameOfFile.Id
let qualNameOfFileT =
if count = 1 then
qualNameOfFile
else
QualifiedNameOfFile(Ident(id.idText + "___" + count.ToString(), id.idRange))
let moduleNamesDictT =
moduleNamesDict.Add(qualNameOfFile.Text, paths.Add(path, qualNameOfFileT))
qualNameOfFileT, moduleNamesDictT
| _ ->
let moduleNamesDictT =
moduleNamesDict.Add(qualNameOfFile.Text, Map.empty.Add(path, qualNameOfFile))
qualNameOfFile, moduleNamesDictT
/// Checks if a ParsedInput is using a module name that was already given and deduplicates the name if needed.
let DeduplicateParsedInputModuleName (moduleNamesDict: ModuleNamesDict) input =
match input with
| ParsedInput.ImplFile implFile ->
let (ParsedImplFileInput(fileName, isScript, qualNameOfFile, scopedPragmas, hashDirectives, modules, flags, trivia, identifiers)) =
implFile
let qualNameOfFileR, moduleNamesDictR =
DeduplicateModuleName moduleNamesDict fileName qualNameOfFile
let implFileR =
ParsedImplFileInput(fileName, isScript, qualNameOfFileR, scopedPragmas, hashDirectives, modules, flags, trivia, identifiers)
let inputR = ParsedInput.ImplFile implFileR
inputR, moduleNamesDictR
| ParsedInput.SigFile sigFile ->
let (ParsedSigFileInput(fileName, qualNameOfFile, scopedPragmas, hashDirectives, modules, trivia, identifiers)) =
sigFile
let qualNameOfFileR, moduleNamesDictR =
DeduplicateModuleName moduleNamesDict fileName qualNameOfFile
let sigFileR =
ParsedSigFileInput(fileName, qualNameOfFileR, scopedPragmas, hashDirectives, modules, trivia, identifiers)
let inputT = ParsedInput.SigFile sigFileR
inputT, moduleNamesDictR
let ParseInput
(
lexer,
diagnosticOptions: FSharpDiagnosticOptions,
diagnosticsLogger: DiagnosticsLogger,
lexbuf: UnicodeLexing.Lexbuf,
defaultNamespace,
fileName,
isLastCompiland,
identCapture,
userOpName
) =
use _ =
Activity.start
"ParseAndCheckFile.parseFile"
[|
Activity.Tags.fileName, fileName
Activity.Tags.buildPhase, !! BuildPhase.Parse.ToString()
Activity.Tags.userOpName, userOpName |> Option.defaultValue ""
|]
// The assert below is almost ok, but it fires in two cases:
// - fsi.exe sometimes passes "stdin" as a dummy file name
// - if you have a #line directive, e.g.
// # 1000 "Line01.fs"
// then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651.
// Delay sending errors and warnings until after the file is parsed. This gives us a chance to scrape the
// #nowarn declarations for the file
let delayLogger = CapturingDiagnosticsLogger("Parsing")
use _ = UseDiagnosticsLogger delayLogger
use _ = UseBuildPhase BuildPhase.Parse
let mutable scopedPragmas = []
try
let input =
let identStore = HashSet<string>()
let lexer =
if identCapture then
(fun x ->
let token = lexer x
match token with
| Parser.token.PERCENT_OP ident
| Parser.token.FUNKY_OPERATOR_NAME ident
| Parser.token.ADJACENT_PREFIX_OP ident
| Parser.token.PLUS_MINUS_OP ident
| Parser.token.INFIX_AMP_OP ident
| Parser.token.INFIX_STAR_DIV_MOD_OP ident
| Parser.token.PREFIX_OP ident
| Parser.token.INFIX_BAR_OP ident
| Parser.token.INFIX_AT_HAT_OP ident
| Parser.token.INFIX_COMPARE_OP ident
| Parser.token.INFIX_STAR_STAR_OP ident
| Parser.token.IDENT ident -> identStore.Add ident |> ignore
| _ -> ()
token)
else
lexer
if FSharpMLCompatFileSuffixes |> List.exists (FileSystemUtils.checkSuffix fileName) then
if lexbuf.SupportsFeature LanguageFeature.MLCompatRevisions then
errorR (Error(FSComp.SR.buildInvalidSourceFileExtensionML fileName, rangeStartup))
else
mlCompatWarning (FSComp.SR.buildCompilingExtensionIsForML ()) rangeStartup
// Call the appropriate parser - for signature files or implementation files
if FSharpImplFileSuffixes |> List.exists (FileSystemUtils.checkSuffix fileName) then
let impl = Parser.implementationFile lexer lexbuf
let tripleSlashComments =
LexbufLocalXmlDocStore.ReportInvalidXmlDocPositions(lexbuf)
PostParseModuleImpls(defaultNamespace, fileName, isLastCompiland, impl, lexbuf, tripleSlashComments, Set identStore)
elif FSharpSigFileSuffixes |> List.exists (FileSystemUtils.checkSuffix fileName) then
let intfs = Parser.signatureFile lexer lexbuf
let tripleSlashComments =
LexbufLocalXmlDocStore.ReportInvalidXmlDocPositions(lexbuf)
PostParseModuleSpecs(defaultNamespace, fileName, isLastCompiland, intfs, lexbuf, tripleSlashComments, Set identStore)
else if lexbuf.SupportsFeature LanguageFeature.MLCompatRevisions then
error (Error(FSComp.SR.buildInvalidSourceFileExtensionUpdated fileName, rangeStartup))
else
error (Error(FSComp.SR.buildInvalidSourceFileExtension fileName, rangeStartup))
scopedPragmas <- input.ScopedPragmas
input
finally
// OK, now commit the errors, since the ScopedPragmas will (hopefully) have been scraped
let filteringDiagnosticsLogger =
GetDiagnosticsLoggerFilteringByScopedPragmas(false, scopedPragmas, diagnosticOptions, diagnosticsLogger)
delayLogger.CommitDelayedDiagnostics filteringDiagnosticsLogger
type Tokenizer = unit -> Parser.token
// Show all tokens in the stream, for testing purposes
let ShowAllTokensAndExit (tokenizer: Tokenizer, lexbuf: LexBuffer<char>, exiter: Exiter) =
let mutable indent = 0
while true do
let t = tokenizer ()
indent <-
match t with
| OBLOCKEND_IS_HERE -> max (indent - 1) 0
| _ -> indent
let indentStr = String.replicate indent " "
printfn $"{indentStr}{token_to_string t} {lexbuf.LexemeRange}"
indent <-
match t with
| OBLOCKBEGIN -> indent + 1
| _ -> indent
match t with
| Parser.EOF _ -> exiter.Exit 0
| _ -> ()
if lexbuf.IsPastEndOfStream then
printf "!!! at end of stream\n"
// Test one of the parser entry points, just for testing purposes
let TestInteractionParserAndExit (tokenizer: Tokenizer, lexbuf: LexBuffer<char>, exiter: Exiter) =
while true do
match (Parser.interaction (fun _ -> tokenizer ()) lexbuf) with
| ParsedScriptInteraction.Definitions(l, m) -> printfn "Parsed OK, got %d defs @ %a" l.Length outputRange m
exiter.Exit 0
// Report the statistics for testing purposes
let ReportParsingStatistics res =
let rec flattenSpecs specs =
specs
|> List.collect (function
| SynModuleSigDecl.NestedModule(moduleDecls = subDecls) -> flattenSpecs subDecls
| spec -> [ spec ])
let rec flattenDefns specs =
specs
|> List.collect (function
| SynModuleDecl.NestedModule(decls = subDecls) -> flattenDefns subDecls
| defn -> [ defn ])
let flattenModSpec (SynModuleOrNamespaceSig(decls = decls)) = flattenSpecs decls
let flattenModImpl (SynModuleOrNamespace(decls = decls)) = flattenDefns decls
match res with
| ParsedInput.SigFile sigFile -> printfn "parsing yielded %d specs" (List.collect flattenModSpec sigFile.Contents).Length
| ParsedInput.ImplFile implFile -> printfn "parsing yielded %d definitions" (List.collect flattenModImpl implFile.Contents).Length
let EmptyParsedInput (fileName, isLastCompiland) =
if FSharpSigFileSuffixes |> List.exists (FileSystemUtils.checkSuffix fileName) then
ParsedInput.SigFile(
ParsedSigFileInput(
fileName,
QualFileNameOfImpls fileName [],
[],
[],
[],
{
ConditionalDirectives = []
CodeComments = []
},
Set.empty
)
)
else
ParsedInput.ImplFile(
ParsedImplFileInput(
fileName,
false,
QualFileNameOfImpls fileName [],
[],
[],
[],
isLastCompiland,
{
ConditionalDirectives = []
CodeComments = []
},
Set.empty
)
)
/// Parse an input, drawing tokens from the LexBuffer
let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, lexbuf, fileName, isLastCompiland, diagnosticsLogger) =
use unwindbuildphase = UseBuildPhase BuildPhase.Parse
try
// Don't report whitespace from lexer
let skipWhitespaceTokens = true
// Set up the initial status for indentation-aware processing
let indentationSyntaxStatus =
IndentationAwareSyntaxStatus(tcConfig.ComputeIndentationAwareSyntaxInitialStatus fileName, true)
// Set up the initial lexer arguments
let lexargs =
mkLexargs (
tcConfig.conditionalDefines,
indentationSyntaxStatus,
lexResourceManager,
[],
diagnosticsLogger,
tcConfig.pathMap,
tcConfig.applyLineDirectives
)
let input =
usingLexbufForParsing (lexbuf, fileName) (fun lexbuf ->
// Set up the LexFilter over the token stream
let tokenizer, tokenizeOnly =
match tcConfig.tokenize with
| TokenizeOption.Unfiltered -> (fun () -> Lexer.token lexargs skipWhitespaceTokens lexbuf), true
| TokenizeOption.Only ->
LexFilter
.LexFilter(
indentationSyntaxStatus,
tcConfig.compilingFSharpCore,
Lexer.token lexargs skipWhitespaceTokens,
lexbuf,
tcConfig.tokenize = TokenizeOption.Debug
)
.GetToken,
true
| _ ->
LexFilter
.LexFilter(
indentationSyntaxStatus,
tcConfig.compilingFSharpCore,
Lexer.token lexargs skipWhitespaceTokens,
lexbuf,
tcConfig.tokenize = TokenizeOption.Debug
)
.GetToken,
false
// If '--tokenize' then show the tokens now and exit
if tokenizeOnly then
ShowAllTokensAndExit(tokenizer, lexbuf, tcConfig.exiter)
// Test hook for one of the parser entry points
if tcConfig.testInteractionParser then
TestInteractionParserAndExit(tokenizer, lexbuf, tcConfig.exiter)
// Parse the input
let res =
ParseInput(
(fun _ -> tokenizer ()),
tcConfig.diagnosticsOptions,
diagnosticsLogger,
lexbuf,
None,
fileName,
isLastCompiland,
tcConfig.captureIdentifiersWhenParsing,
None
)
// Report the statistics for testing purposes
if tcConfig.reportNumDecls then
ReportParsingStatistics res
res)
input
with RecoverableException exn ->
errorRecovery exn rangeStartup
EmptyParsedInput(fileName, isLastCompiland)
let ValidSuffixes = FSharpSigFileSuffixes @ FSharpImplFileSuffixes
let checkInputFile (tcConfig: TcConfig) fileName =
if List.exists (FileSystemUtils.checkSuffix fileName) ValidSuffixes then
if not (FileSystem.FileExistsShim fileName) then
error (Error(FSComp.SR.buildCouldNotFindSourceFile fileName, rangeStartup))
else
error (Error(FSComp.SR.buildInvalidSourceFileExtension (SanitizeFileName fileName tcConfig.implicitIncludeDir), rangeStartup))
let parseInputStreamAux
(
tcConfig: TcConfig,
lexResourceManager,
fileName,
isLastCompiland,
diagnosticsLogger,
retryLocked,
stream: Stream
) =
use reader = stream.GetReader(tcConfig.inputCodePage, retryLocked)
// Set up the LexBuffer for the file
let lexbuf =
UnicodeLexing.StreamReaderAsLexbuf(not tcConfig.compilingFSharpCore, tcConfig.langVersion, tcConfig.strictIndentation, reader)
// Parse the file drawing tokens from the lexbuf
ParseOneInputLexbuf(tcConfig, lexResourceManager, lexbuf, fileName, isLastCompiland, diagnosticsLogger)
let parseInputSourceTextAux
(
tcConfig: TcConfig,
lexResourceManager,
fileName,
isLastCompiland,
diagnosticsLogger,
sourceText: ISourceText
) =
// Set up the LexBuffer for the file
let lexbuf =
UnicodeLexing.SourceTextAsLexbuf(not tcConfig.compilingFSharpCore, tcConfig.langVersion, tcConfig.strictIndentation, sourceText)
// Parse the file drawing tokens from the lexbuf
ParseOneInputLexbuf(tcConfig, lexResourceManager, lexbuf, fileName, isLastCompiland, diagnosticsLogger)
let parseInputFileAux (tcConfig: TcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked) =
// Get a stream reader for the file
use fileStream = FileSystem.OpenFileForReadShim(fileName)
use reader = fileStream.GetReader(tcConfig.inputCodePage, retryLocked)
// Set up the LexBuffer for the file
let lexbuf =
UnicodeLexing.StreamReaderAsLexbuf(not tcConfig.compilingFSharpCore, tcConfig.langVersion, tcConfig.strictIndentation, reader)
// Parse the file drawing tokens from the lexbuf
ParseOneInputLexbuf(tcConfig, lexResourceManager, lexbuf, fileName, isLastCompiland, diagnosticsLogger)
/// Parse an input from stream
let ParseOneInputStream
(
tcConfig: TcConfig,
lexResourceManager,
fileName,
isLastCompiland,
diagnosticsLogger,
retryLocked,
stream: Stream
) =
try
parseInputStreamAux (tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked, stream)
with RecoverableException exn ->
errorRecovery exn rangeStartup
EmptyParsedInput(fileName, isLastCompiland)
/// Parse an input from source text
let ParseOneInputSourceText
(
tcConfig: TcConfig,
lexResourceManager,
fileName,
isLastCompiland,
diagnosticsLogger,
sourceText: ISourceText
) =
try
parseInputSourceTextAux (tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, sourceText)
with RecoverableException exn ->
errorRecovery exn rangeStartup
EmptyParsedInput(fileName, isLastCompiland)
/// Parse an input from disk
let ParseOneInputFile (tcConfig: TcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked) =
try
checkInputFile tcConfig fileName
parseInputFileAux (tcConfig, lexResourceManager, fileName, isLastCompiland, diagnosticsLogger, retryLocked)
with RecoverableException exn ->
errorRecovery exn rangeStartup
EmptyParsedInput(fileName, isLastCompiland)
/// Prepare to process inputs independently, e.g. partially in parallel.
///
/// To do this we create one CapturingDiagnosticLogger for each input and
/// then ensure the diagnostics are presented in deterministic order after processing completes.
/// On completion all diagnostics are forwarded to the DiagnosticLogger given as input.
///
/// NOTE: Max errors is currently counted separately for each logger. When max errors is reached on one compilation
/// the given Exiter will be called.
///
/// NOTE: this needs to be improved to commit diagnotics as soon as possible
///
/// NOTE: If StopProcessing is raised by any piece of work then the overall function raises StopProcessing.
let UseMultipleDiagnosticLoggers (inputs, diagnosticsLogger, eagerFormat) f =
// Check input files and create delayed error loggers before we try to parallel parse.
let delayLoggers =
inputs
|> List.map (fun _ -> CapturingDiagnosticsLogger("TcDiagnosticsLogger", ?eagerFormat = eagerFormat))
try
f (List.zip inputs delayLoggers)
finally
for logger in delayLoggers do
logger.CommitDelayedDiagnostics diagnosticsLogger
let ParseInputFilesInParallel (tcConfig: TcConfig, lexResourceManager, sourceFiles, delayLogger: DiagnosticsLogger, retryLocked) =
let isLastCompiland, isExe = sourceFiles |> tcConfig.ComputeCanContainEntryPoint
for fileName in sourceFiles do
checkInputFile tcConfig fileName
let sourceFiles = List.zip sourceFiles isLastCompiland
UseMultipleDiagnosticLoggers (sourceFiles, delayLogger, None) (fun sourceFilesWithDelayLoggers ->
sourceFilesWithDelayLoggers
|> ListParallel.map (fun ((fileName, isLastCompiland), delayLogger) ->
let directoryName = Path.GetDirectoryName fileName
let input =
parseInputFileAux (tcConfig, lexResourceManager, fileName, (isLastCompiland, isExe), delayLogger, retryLocked)
(input, directoryName)))
let ParseInputFilesSequential (tcConfig: TcConfig, lexResourceManager, sourceFiles, diagnosticsLogger: DiagnosticsLogger, retryLocked) =
let isLastCompiland, isExe = sourceFiles |> tcConfig.ComputeCanContainEntryPoint
let sourceFiles = isLastCompiland |> List.zip sourceFiles |> Array.ofList
sourceFiles
|> Array.map (fun (fileName, isLastCompiland) ->
let directoryName = Path.GetDirectoryName fileName
let input =
ParseOneInputFile(tcConfig, lexResourceManager, fileName, (isLastCompiland, isExe), diagnosticsLogger, retryLocked)
(input, directoryName))
|> List.ofArray
/// Parse multiple input files from disk
let ParseInputFiles (tcConfig: TcConfig, lexResourceManager, sourceFiles, diagnosticsLogger: DiagnosticsLogger, retryLocked) =
try
if tcConfig.concurrentBuild then
ParseInputFilesInParallel(tcConfig, lexResourceManager, sourceFiles, diagnosticsLogger, retryLocked)
else
ParseInputFilesSequential(tcConfig, lexResourceManager, sourceFiles, diagnosticsLogger, retryLocked)
with e ->
errorRecoveryNoRange e
tcConfig.exiter.Exit 1
let ProcessMetaCommandsFromInput
(nowarnF: 'state -> range * string -> 'state,
hashReferenceF: 'state -> range * string * Directive -> 'state,
loadSourceF: 'state -> range * string -> unit)
(tcConfig: TcConfigBuilder, inp: ParsedInput, pathOfMetaCommandSource, state0)
=
use _ = UseBuildPhase BuildPhase.Parse
let canHaveScriptMetaCommands =
match inp with
| ParsedInput.SigFile _ -> false
| ParsedInput.ImplFile file -> file.IsScript
let ProcessDependencyManagerDirective directive args m state =
if not canHaveScriptMetaCommands then
errorR (HashReferenceNotAllowedInNonScript m)
match args with
| [ path ] ->
let p = if String.IsNullOrWhiteSpace(path) then "" else !!path
hashReferenceF state (m, p, directive)
| _ ->
errorR (Error(FSComp.SR.buildInvalidHashrDirective (), m))
state
let ProcessMetaCommand state hash =
let mutable matchedm = range0
try
match hash with
| ParsedHashDirective("I", [ path ], m) ->
if not canHaveScriptMetaCommands then
errorR (HashIncludeNotAllowedInNonScript m)
else
let arguments = parsedHashDirectiveStringArguments [ path ] tcConfig.langVersion
match arguments with
| [ path ] ->
matchedm <- m
tcConfig.AddIncludePath(m, path, pathOfMetaCommandSource)
| _ -> errorR (Error(FSComp.SR.buildInvalidHashIDirective (), m))
state
| ParsedHashDirective("nowarn", hashArguments, m) ->
let arguments = parsedHashDirectiveArguments hashArguments tcConfig.langVersion
List.fold (fun state d -> nowarnF state (m, d)) state arguments
| ParsedHashDirective(("reference" | "r") as c, [], m) ->
if not canHaveScriptMetaCommands then
errorR (HashDirectiveNotAllowedInNonScript m)
else
let arg = (parsedHashDirectiveArguments [] tcConfig.langVersion)
warning (Error((FSComp.SR.fsiInvalidDirective (c, String.concat " " arg)), m))
state
| ParsedHashDirective(("reference" | "r"), [ reference ], m) ->
if not canHaveScriptMetaCommands then
errorR (HashDirectiveNotAllowedInNonScript m)
state
else
let arguments =
parsedHashDirectiveStringArguments [ reference ] tcConfig.langVersion
match arguments with
| [ reference ] ->
matchedm <- m
ProcessDependencyManagerDirective Directive.Resolution [ reference ] m state
| _ -> state
| ParsedHashDirective("i", [ path ], m) ->
if not canHaveScriptMetaCommands then
errorR (HashDirectiveNotAllowedInNonScript m)
state
else
matchedm <- m
let arguments = parsedHashDirectiveStringArguments [ path ] tcConfig.langVersion
match arguments with
| [ path ] -> ProcessDependencyManagerDirective Directive.Include [ path ] m state
| _ -> state
| ParsedHashDirective("load", paths, m) ->
if not canHaveScriptMetaCommands then
errorR (HashDirectiveNotAllowedInNonScript m)
else
let arguments = parsedHashDirectiveArguments paths tcConfig.langVersion
match arguments with
| _ :: _ ->
matchedm <- m
arguments |> List.iter (fun path -> loadSourceF state (m, path))
| _ -> errorR (Error(FSComp.SR.buildInvalidHashloadDirective (), m))
state
| ParsedHashDirective("time", switch, m) ->
if not canHaveScriptMetaCommands then
errorR (HashDirectiveNotAllowedInNonScript m)
else
let arguments = parsedHashDirectiveArguments switch tcConfig.langVersion
match arguments with
| [] -> matchedm <- m
| [ "on" | "off" ] -> matchedm <- m
| _ -> errorR (Error(FSComp.SR.buildInvalidHashtimeDirective (), m))
state
| _ ->
(* warning(Error("This meta-command has been ignored", m)) *)
state
with RecoverableException e ->
errorRecovery e matchedm
state
let rec WarnOnIgnoredSpecDecls decls =
decls
|> List.iter (fun d ->
match d with
| SynModuleSigDecl.HashDirective(_, m) -> warning (Error(FSComp.SR.buildDirectivesInModulesAreIgnored (), m))
| SynModuleSigDecl.NestedModule(moduleDecls = subDecls) -> WarnOnIgnoredSpecDecls subDecls
| _ -> ())
let rec WarnOnIgnoredImplDecls decls =
decls
|> List.iter (fun d ->
match d with
| SynModuleDecl.HashDirective(_, m) -> warning (Error(FSComp.SR.buildDirectivesInModulesAreIgnored (), m))