forked from dotnet/fsharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.fs
745 lines (607 loc) · 29.5 KB
/
service.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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
namespace FSharp.Compiler.CodeAnalysis
open System
open System.Diagnostics
open System.IO
open System.Reflection
open System.Reflection.Emit
open System.Threading
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open FSharp.Compiler
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.AbstractIL.ILDynamicAssemblyWriter
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.CodeAnalysis.TransparentCompiler
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.CompilerDiagnostics
open FSharp.Compiler.CompilerImports
open FSharp.Compiler.CompilerOptions
open FSharp.Compiler.DependencyManager
open FSharp.Compiler.Diagnostics
open FSharp.Compiler.Driver
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.IO
open FSharp.Compiler.ParseAndCheckInputs
open FSharp.Compiler.ScriptClosure
open FSharp.Compiler.Symbols
open FSharp.Compiler.Syntax
open FSharp.Compiler.Tokenization
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.BuildGraph
[<RequireQualifiedAccess>]
type DocumentSource =
| FileSystem
| Custom of (string -> Async<ISourceText option>)
/// Callback that indicates whether a requested result has become obsolete.
[<NoComparison; NoEquality>]
type IsResultObsolete = IsResultObsolete of (unit -> bool)
module CompileHelpers =
let mkCompilationDiagnosticsHandlers (flatErrors) =
let diagnostics = ResizeArray<_>()
let diagnosticsLogger =
{ new DiagnosticsLogger("CompileAPI") with
member _.DiagnosticSink(diag, isError) =
diagnostics.Add(FSharpDiagnostic.CreateFromException(diag, isError, range0, true, flatErrors, None)) // Suggest names for errors
member _.ErrorCount =
diagnostics
|> Seq.filter (fun diagnostic -> diagnostic.Severity = FSharpDiagnosticSeverity.Error)
|> Seq.length
}
let loggerProvider =
{ new IDiagnosticsLoggerProvider with
member _.CreateLogger(_tcConfigB, _exiter) = diagnosticsLogger
}
diagnostics, diagnosticsLogger, loggerProvider
let tryCompile diagnosticsLogger f =
use _ = UseBuildPhase BuildPhase.Parse
use _ = UseDiagnosticsLogger diagnosticsLogger
let exiter = StopProcessingExiter()
try
f exiter
0
with e ->
stopProcessingRecovery e range0
1
/// Compile using the given flags. Source files names are resolved via the FileSystem API. The output file must be given by a -o flag.
let compileFromArgs (ctok, argv: string[], legacyReferenceResolver, tcImportsCapture, dynamicAssemblyCreator) =
let diagnostics, diagnosticsLogger, loggerProvider =
mkCompilationDiagnosticsHandlers (argv |> Array.contains "--flaterrors")
let result =
tryCompile diagnosticsLogger (fun exiter ->
CompileFromCommandLineArguments(
ctok,
argv,
legacyReferenceResolver,
true,
ReduceMemoryFlag.Yes,
CopyFSharpCoreFlag.No,
exiter,
loggerProvider,
tcImportsCapture,
dynamicAssemblyCreator
))
diagnostics.ToArray(), result
let setOutputStreams execute =
// Set the output streams, if requested
match execute with
| Some(writer, error) ->
Console.SetOut writer
Console.SetError error
| None -> ()
[<Sealed; AutoSerializable(false)>]
// There is typically only one instance of this type in an IDE process.
type FSharpChecker
(
legacyReferenceResolver,
projectCacheSize,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
parallelReferenceResolution,
captureIdentifiersWhenParsing,
getSource,
useChangeNotifications,
useSyntaxTreeCache,
useTransparentCompiler
) =
let backgroundCompiler =
if useTransparentCompiler = Some true then
TransparentCompiler(
legacyReferenceResolver,
projectCacheSize,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
parallelReferenceResolution,
captureIdentifiersWhenParsing,
getSource,
useChangeNotifications,
useSyntaxTreeCache
)
:> IBackgroundCompiler
else
BackgroundCompiler(
legacyReferenceResolver,
projectCacheSize,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
parallelReferenceResolution,
captureIdentifiersWhenParsing,
getSource,
useChangeNotifications,
useSyntaxTreeCache
)
:> IBackgroundCompiler
static let globalInstance = lazy FSharpChecker.Create()
// STATIC ROOT: FSharpLanguageServiceTestable.FSharpChecker.braceMatchCache. Most recently used cache for brace matching. Accessed on the
// background UI thread, not on the compiler thread.
//
// This cache is safe for concurrent access.
let braceMatchCache =
MruCache<AnyCallerThreadToken, _, _>(braceMatchCacheSize, areSimilar = AreSimilarForParsing, areSame = AreSameForParsing)
static let inferParallelReferenceResolution (parallelReferenceResolution: bool option) =
let explicitValue =
parallelReferenceResolution
|> Option.defaultValue false
|> function
| true -> ParallelReferenceResolution.On
| false -> ParallelReferenceResolution.Off
let withEnvOverride =
// Override ParallelReferenceResolution set on the constructor with an environment setting if present.
getParallelReferenceResolutionFromEnvironment ()
|> Option.defaultValue explicitValue
withEnvOverride
static member getParallelReferenceResolutionFromEnvironment() =
getParallelReferenceResolutionFromEnvironment ()
/// Instantiate an interactive checker.
static member Create
(
?projectCacheSize,
?keepAssemblyContents,
?keepAllBackgroundResolutions,
?legacyReferenceResolver,
?tryGetMetadataSnapshot,
?suggestNamesForErrors,
?keepAllBackgroundSymbolUses,
?enableBackgroundItemKeyStoreAndSemanticClassification,
?enablePartialTypeChecking,
?parallelReferenceResolution: bool,
?captureIdentifiersWhenParsing: bool,
?documentSource: DocumentSource,
?useSyntaxTreeCache: bool,
?useTransparentCompiler: bool
) =
use _ = Activity.startNoTags "FSharpChecker.Create"
let legacyReferenceResolver =
match legacyReferenceResolver with
| Some rr -> rr
| None -> SimulatedMSBuildReferenceResolver.getResolver ()
let keepAssemblyContents = defaultArg keepAssemblyContents false
let keepAllBackgroundResolutions = defaultArg keepAllBackgroundResolutions true
let projectCacheSizeReal = defaultArg projectCacheSize projectCacheSizeDefault
let tryGetMetadataSnapshot = defaultArg tryGetMetadataSnapshot (fun _ -> None)
let suggestNamesForErrors = defaultArg suggestNamesForErrors false
let keepAllBackgroundSymbolUses = defaultArg keepAllBackgroundSymbolUses true
let enableBackgroundItemKeyStoreAndSemanticClassification =
defaultArg enableBackgroundItemKeyStoreAndSemanticClassification false
let enablePartialTypeChecking = defaultArg enablePartialTypeChecking false
let captureIdentifiersWhenParsing = defaultArg captureIdentifiersWhenParsing false
let useChangeNotifications =
match documentSource with
| Some(DocumentSource.Custom _) -> true
| _ -> false
let useSyntaxTreeCache = defaultArg useSyntaxTreeCache true
if keepAssemblyContents && enablePartialTypeChecking then
invalidArg "enablePartialTypeChecking" "'keepAssemblyContents' and 'enablePartialTypeChecking' cannot be both enabled."
let parallelReferenceResolution = inferParallelReferenceResolution parallelReferenceResolution
FSharpChecker(
legacyReferenceResolver,
projectCacheSizeReal,
keepAssemblyContents,
keepAllBackgroundResolutions,
tryGetMetadataSnapshot,
suggestNamesForErrors,
keepAllBackgroundSymbolUses,
enableBackgroundItemKeyStoreAndSemanticClassification,
enablePartialTypeChecking,
parallelReferenceResolution,
captureIdentifiersWhenParsing,
(match documentSource with
| Some(DocumentSource.Custom f) -> Some f
| _ -> None),
useChangeNotifications,
useSyntaxTreeCache,
useTransparentCompiler
)
member _.UsesTransparentCompiler = useTransparentCompiler = Some true
member _.TransparentCompiler =
match useTransparentCompiler with
| Some true -> backgroundCompiler :?> TransparentCompiler
| _ -> failwith "Transparent Compiler is not enabled."
member this.Caches = this.TransparentCompiler.Caches
member _.ReferenceResolver = legacyReferenceResolver
member _.MatchBraces(fileName, sourceText: ISourceText, options: FSharpParsingOptions, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
use _ =
Activity.start "FSharpChecker.MatchBraces" [| Activity.Tags.fileName, fileName; Activity.Tags.userOpName, userOpName |]
let hash = sourceText.GetHashCode() |> int64
async {
match braceMatchCache.TryGet(AnyCallerThread, (fileName, hash, options)) with
| Some res -> return res
| None ->
let! ct = Async.CancellationToken
let res =
ParseAndCheckFile.matchBraces (sourceText, fileName, options, userOpName, suggestNamesForErrors, ct)
braceMatchCache.Set(AnyCallerThread, (fileName, hash, options), res)
return res
}
member ic.MatchBraces(fileName, source: string, options: FSharpProjectOptions, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options)
ic.MatchBraces(fileName, SourceText.ofString source, parsingOptions, userOpName)
member ic.GetParsingOptionsFromProjectOptions(options) : FSharpParsingOptions * _ =
let sourceFiles = List.ofArray options.SourceFiles
let argv = List.ofArray options.OtherOptions
ic.GetParsingOptionsFromCommandLineArgs(sourceFiles, argv, options.UseScriptResolutionRules)
member _.ParseFile(fileName, sourceText, options, ?cache, ?userOpName: string) =
let cache = defaultArg cache true
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ParseFile(fileName, sourceText, options, cache, false, userOpName)
member _.ParseFile(fileName, projectSnapshot, ?userOpName) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ParseFile(fileName, projectSnapshot, userOpName)
member ic.ParseFileInProject(fileName, source: string, options, ?cache: bool, ?userOpName: string) =
let parsingOptions, _ = ic.GetParsingOptionsFromProjectOptions(options)
ic.ParseFile(fileName, SourceText.ofString source, parsingOptions, ?cache = cache, ?userOpName = userOpName)
member _.GetBackgroundParseResultsForFileInProject(fileName, options, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName)
|> Async.AwaitNodeCode
member _.GetBackgroundCheckResultsForFileInProject(fileName, options, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.GetBackgroundCheckResultsForFileInProject(fileName, options, userOpName)
|> Async.AwaitNodeCode
/// Try to get recent approximate type check results for a file.
member _.TryGetRecentCheckResultsForFile(fileName: string, options: FSharpProjectOptions, ?sourceText, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.TryGetRecentCheckResultsForFile(fileName, options, sourceText, userOpName)
member _.Compile(argv: string[], ?userOpName: string) =
let _userOpName = defaultArg userOpName "Unknown"
use _ = Activity.start "FSharpChecker.Compile" [| Activity.Tags.userOpName, _userOpName |]
async {
let ctok = CompilationThreadToken()
return CompileHelpers.compileFromArgs (ctok, argv, legacyReferenceResolver, None, None)
}
/// This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation.
/// For example, the type provider approvals file may have changed.
member ic.InvalidateAll() = ic.ClearCaches()
member ic.ClearCaches() =
let utok = AnyCallerThread
braceMatchCache.Clear(utok)
backgroundCompiler.ClearCaches()
ClearAllILModuleReaderCache()
member ic.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() =
use _ =
Activity.startNoTags "FsharpChecker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients"
ic.ClearCaches()
GC.Collect()
GC.WaitForPendingFinalizers()
FxResolver.ClearStaticCaches()
/// This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions.
/// For example, dependent references may have been deleted or created.
member _.InvalidateConfiguration(options: FSharpProjectOptions, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.InvalidateConfiguration(options, userOpName)
/// Clear the internal cache of the given projects.
member _.ClearCache(options: seq<FSharpProjectOptions>, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ClearCache(options, userOpName)
member _.ClearCache(projects: ProjectSnapshot.FSharpProjectIdentifier seq, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ClearCache(projects, userOpName)
/// This function is called when a project has been cleaned, and thus type providers should be refreshed.
member _.NotifyProjectCleaned(options: FSharpProjectOptions, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.NotifyProjectCleaned(options, userOpName)
member _.NotifyFileChanged(fileName: string, options: FSharpProjectOptions, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.NotifyFileChanged(fileName, options, userOpName)
|> Async.AwaitNodeCode
/// Typecheck a source code file, returning a handle to the results of the
/// parse including the reconstructed types in the file.
member _.CheckFileInProjectAllowingStaleCachedResults
(
parseResults: FSharpParseFileResults,
fileName: string,
fileVersion: int,
source: string,
options: FSharpProjectOptions,
?userOpName: string
) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.CheckFileInProjectAllowingStaleCachedResults(
parseResults,
fileName,
fileVersion,
SourceText.ofString source,
options,
userOpName
)
|> Async.AwaitNodeCode
/// Typecheck a source code file, returning a handle to the results of the
/// parse including the reconstructed types in the file.
member _.CheckFileInProject
(
parseResults: FSharpParseFileResults,
fileName: string,
fileVersion: int,
sourceText: ISourceText,
options: FSharpProjectOptions,
?userOpName: string
) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.CheckFileInProject(parseResults, fileName, fileVersion, sourceText, options, userOpName)
|> Async.AwaitNodeCode
/// Typecheck a source code file, returning a handle to the results of the
/// parse including the reconstructed types in the file.
member _.ParseAndCheckFileInProject
(
fileName: string,
fileVersion: int,
sourceText: ISourceText,
options: FSharpProjectOptions,
?userOpName: string
) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ParseAndCheckFileInProject(fileName, fileVersion, sourceText, options, userOpName)
|> Async.AwaitNodeCode
member _.ParseAndCheckFileInProject(fileName: string, projectSnapshot: FSharpProjectSnapshot, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ParseAndCheckFileInProject(fileName, projectSnapshot, userOpName)
|> Async.AwaitNodeCode
member _.ParseAndCheckProject(options: FSharpProjectOptions, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ParseAndCheckProject(options, userOpName)
|> Async.AwaitNodeCode
member _.ParseAndCheckProject(projectSnapshot: FSharpProjectSnapshot, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.ParseAndCheckProject(projectSnapshot, userOpName)
|> Async.AwaitNodeCode
member _.FindBackgroundReferencesInFile
(
fileName: string,
options: FSharpProjectOptions,
symbol: FSharpSymbol,
?canInvalidateProject: bool,
?fastCheck: bool,
?userOpName: string
) =
let canInvalidateProject = defaultArg canInvalidateProject true
let userOpName = defaultArg userOpName "Unknown"
node {
if fastCheck <> Some true || not captureIdentifiersWhenParsing then
return! backgroundCompiler.FindReferencesInFile(fileName, options, symbol, canInvalidateProject, userOpName)
else
let! parseResults = backgroundCompiler.GetBackgroundParseResultsForFileInProject(fileName, options, userOpName)
if
parseResults.ParseTree.Identifiers |> Set.contains symbol.DisplayNameCore
|| parseResults.ParseTree.Identifiers |> NamesContainAttribute symbol
then
return! backgroundCompiler.FindReferencesInFile(fileName, options, symbol, canInvalidateProject, userOpName)
else
return Seq.empty
}
|> Async.AwaitNodeCode
member _.FindBackgroundReferencesInFile(fileName: string, projectSnapshot: FSharpProjectSnapshot, symbol: FSharpSymbol, ?userOpName: string) =
let userOpName = defaultArg userOpName "Unknown"
node {
let! parseResults =
backgroundCompiler.ParseFile(fileName, projectSnapshot, userOpName)
|> NodeCode.AwaitAsync
if
parseResults.ParseTree.Identifiers |> Set.contains symbol.DisplayNameCore
|| parseResults.ParseTree.Identifiers |> NamesContainAttribute symbol
then
return! backgroundCompiler.FindReferencesInFile(fileName, projectSnapshot, symbol, userOpName)
else
return Seq.empty
}
|> Async.AwaitNodeCode
member _.GetBackgroundSemanticClassificationForFile(fileName: string, options: FSharpProjectOptions, ?userOpName) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.GetSemanticClassificationForFile(fileName, options, userOpName)
|> Async.AwaitNodeCode
member _.GetBackgroundSemanticClassificationForFile(fileName: string, snapshot: FSharpProjectSnapshot, ?userOpName) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.GetSemanticClassificationForFile(fileName, snapshot, userOpName)
|> Async.AwaitNodeCode
/// For a given script file, get the ProjectOptions implied by the #load closure
member _.GetProjectOptionsFromScript
(
fileName,
source,
?previewEnabled,
?loadedTimeStamp,
?otherFlags,
?useFsiAuxLib,
?useSdkRefs,
?assumeDotNetFramework,
?sdkDirOverride,
?optionsStamp: int64,
?userOpName: string
) =
let userOpName = defaultArg userOpName "Unknown"
backgroundCompiler.GetProjectOptionsFromScript(
fileName,
source,
previewEnabled,
loadedTimeStamp,
otherFlags,
useFsiAuxLib,
useSdkRefs,
sdkDirOverride,
assumeDotNetFramework,
optionsStamp,
userOpName
)
member _.GetProjectOptionsFromCommandLineArgs(projectFileName, argv, ?loadedTimeStamp, ?isInteractive, ?isEditing) =
let isEditing = defaultArg isEditing false
let isInteractive = defaultArg isInteractive false
let loadedTimeStamp = defaultArg loadedTimeStamp DateTime.MaxValue // Not 'now', we don't want to force reloading
let argv =
let define =
if isInteractive then
"--define:INTERACTIVE"
else
"--define:COMPILED"
Array.append argv [| define |]
let argv =
if isEditing then
Array.append argv [| "--define:EDITING" |]
else
argv
{
ProjectFileName = projectFileName
ProjectId = None
SourceFiles = [||] // the project file names will be inferred from the ProjectOptions
OtherOptions = argv
ReferencedProjects = [||]
IsIncompleteTypeCheckEnvironment = false
UseScriptResolutionRules = false
LoadTime = loadedTimeStamp
UnresolvedReferences = None
OriginalLoadReferences = []
Stamp = None
}
member _.GetParsingOptionsFromCommandLineArgs(sourceFiles, argv, ?isInteractive, ?isEditing) =
let isEditing = defaultArg isEditing false
let isInteractive = defaultArg isInteractive false
use errorScope = new DiagnosticsScope(argv |> List.contains "--flaterrors")
let tcConfigB =
TcConfigBuilder.CreateNew(
legacyReferenceResolver,
defaultFSharpBinariesDir = FSharpCheckerResultsSettings.defaultFSharpBinariesDir,
reduceMemoryUsage = ReduceMemoryFlag.Yes,
implicitIncludeDir = "",
isInteractive = isInteractive,
isInvalidationSupported = false,
defaultCopyFSharpCore = CopyFSharpCoreFlag.No,
tryGetMetadataSnapshot = tryGetMetadataSnapshot,
sdkDirOverride = None,
rangeForErrors = range0
)
// These defines are implied by the F# compiler
tcConfigB.conditionalDefines <-
let define = if isInteractive then "INTERACTIVE" else "COMPILED"
define :: tcConfigB.conditionalDefines
if isEditing then
tcConfigB.conditionalDefines <- "EDITING" :: tcConfigB.conditionalDefines
// Apply command-line arguments and collect more source files if they are in the arguments
let sourceFilesNew = ApplyCommandLineArgs(tcConfigB, sourceFiles, argv)
FSharpParsingOptions.FromTcConfigBuilder(tcConfigB, Array.ofList sourceFilesNew, isInteractive), errorScope.Diagnostics
member ic.GetParsingOptionsFromCommandLineArgs(argv, ?isInteractive: bool, ?isEditing) =
ic.GetParsingOptionsFromCommandLineArgs([], argv, ?isInteractive = isInteractive, ?isEditing = isEditing)
member _.BeforeBackgroundFileCheck = backgroundCompiler.BeforeBackgroundFileCheck
member _.FileParsed = backgroundCompiler.FileParsed
member _.FileChecked = backgroundCompiler.FileChecked
member _.ProjectChecked = backgroundCompiler.ProjectChecked
static member ActualParseFileCount = BackgroundCompiler.ActualParseFileCount
static member ActualCheckFileCount = BackgroundCompiler.ActualCheckFileCount
static member Instance = globalInstance.Force()
member internal _.FrameworkImportsCache = backgroundCompiler.FrameworkImportsCache
/// Tokenize a single line, returning token information and a tokenization state represented by an integer
member _.TokenizeLine(line: string, state: FSharpTokenizerLexState) =
let tokenizer = FSharpSourceTokenizer([], None, None, None)
let lineTokenizer = tokenizer.CreateLineTokenizer line
let mutable state = (None, state)
let tokens =
[|
while (state <- lineTokenizer.ScanToken(snd state)
(fst state).IsSome) do
yield (fst state).Value
|]
tokens, snd state
/// Tokenize an entire file, line by line
member x.TokenizeFile(source: string) : FSharpTokenInfo[][] =
let lines = source.Split('\n')
let tokens =
[|
let mutable state = FSharpTokenizerLexState.Initial
for line in lines do
let tokens, n = x.TokenizeLine(line, state)
state <- n
yield tokens
|]
tokens
namespace FSharp.Compiler
open System
open System.IO
open Internal.Utilities
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.EditorServices
open FSharp.Compiler.Text.Range
open FSharp.Compiler.DiagnosticsLogger
type CompilerEnvironment() =
/// Source file extensions
static let compilableExtensions = FSharpSigFileSuffixes @ FSharpImplFileSuffixes @ FSharpScriptFileSuffixes
/// Single file projects extensions
static let singleFileProjectExtensions = FSharpScriptFileSuffixes
static member BinFolderOfDefaultFSharpCompiler(?probePoint) =
FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(probePoint)
// Legacy entry point, no longer used by FSharp.Editor
static member DefaultReferencesForOrphanSources assumeDotNetFramework =
let currentDirectory = Directory.GetCurrentDirectory()
let fxResolver =
FxResolver(
assumeDotNetFramework,
currentDirectory,
rangeForErrors = range0,
useSdkRefs = true,
isInteractive = false,
sdkDirOverride = None
)
let references, _ = fxResolver.GetDefaultReferences(useFsiAuxLib = false)
references
/// Publish compiler-flags parsing logic. Must be fast because its used by the colorizer.
static member GetConditionalDefinesForEditing(parsingOptions: FSharpParsingOptions) =
SourceFileImpl.GetImplicitConditionalDefinesForEditing(parsingOptions.IsInteractive)
@ parsingOptions.ConditionalDefines
/// Return true if this is a subcategory of error or warning message that the language service can emit
static member IsCheckerSupportedSubcategory(subcategory: string) =
// Beware: This code logic is duplicated in DocumentTask.cs in the language service
PhasedDiagnostic.IsSubcategoryOfCompile(subcategory)
/// Return the language ID, which is the expression evaluator id that the
/// debugger will use.
static member GetDebuggerLanguageID() =
Guid(0xAB4F38C9u, 0xB6E6us, 0x43baus, 0xBEuy, 0x3Buy, 0x58uy, 0x08uy, 0x0Buy, 0x2Cuy, 0xCCuy, 0xE3uy)
static member IsScriptFile(fileName: string) = ParseAndCheckInputs.IsScript fileName
/// Whether or not this file is compilable
static member IsCompilable file =
let ext = Path.GetExtension file
compilableExtensions
|> List.exists (fun e -> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase))
/// Whether or not this file should be a single-file project
static member MustBeSingleFileProject file =
let ext = Path.GetExtension file
singleFileProjectExtensions
|> List.exists (fun e -> 0 = String.Compare(e, ext, StringComparison.OrdinalIgnoreCase))