-
Notifications
You must be signed in to change notification settings - Fork 859
Expand file tree
/
Copy pathCompiler.fs
More file actions
2313 lines (1917 loc) · 113 KB
/
Compiler.fs
File metadata and controls
2313 lines (1917 loc) · 113 KB
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.
namespace FSharp.Test
open FSharp.Compiler.Interactive.Shell
open FSharp.Compiler.IO
open FSharp.Compiler.Diagnostics
open FSharp.Compiler.Symbols
open FSharp.Compiler.Text
open FSharp.Test.Assert
open FSharp.Test.Utilities
open FSharp.Test.ScriptHelpers
open Microsoft.CodeAnalysis
open Microsoft.CodeAnalysis.CSharp
open Xunit
open System
open System.Collections.Immutable
open System.IO
open System.Text
open System.Text.RegularExpressions
open System.Reflection
open System.Reflection.Metadata
open System.Reflection.PortableExecutable
open FSharp.Test.CompilerAssertHelpers
open TestFramework
open System.Runtime.CompilerServices
open System.Runtime.InteropServices
open FSharp.Compiler.CodeAnalysis
module rec Compiler =
[<AutoOpen>]
type SourceUtilities () =
static member getCurrentMethodName([<CallerMemberName; Optional; DefaultParameterValue("")>] memberName: string) = memberName
type BaselineFile =
{
FilePath: string
BslSource: string
Content: string option
}
type Baseline =
{
SourceFilename: string option
FSBaseline: BaselineFile
ILBaseline: BaselineFile
}
type TestType =
| Text of string
| Path of string
type CompilationUnit =
| FS of FSharpCompilationSource
| CS of CSharpCompilationSource
| IL of ILCompilationSource
override this.ToString() = match this with | FS fs -> fs.ToString() | _ -> (sprintf "%A" this)
member this.OutputDirectory =
let toString diOpt =
match diOpt: DirectoryInfo option with
| Some di -> di.FullName
| None -> ""
match this with
| FS fs -> fs.OutputDirectory |> toString
| CS cs -> cs.OutputDirectory |> toString
| _ -> raise (Exception "Not supported for this compilation type")
member this.WithStaticLink(staticLink: bool) = match this with | FS fs -> FS { fs with StaticLink = staticLink } | cu -> cu
type FSharpCompilationSource =
{ Source: SourceCodeFileKind
AdditionalSources:SourceCodeFileKind list
Baseline: Baseline option
Options: string list
OutputType: CompileOutput
OutputDirectory: DirectoryInfo option
Name: string option
IgnoreWarnings: bool
References: CompilationUnit list
TargetFramework: TargetFramework
StaticLink: bool
}
member this.CreateOutputDirectory() =
match this.OutputDirectory with
| Some d -> d.Create()
| None -> ()
member this.FullName =
match this.OutputDirectory, this.Name with
| Some directory, Some name -> Some(Path.Combine(directory.FullName, name))
| None, _ -> this.Name
| _ -> None
member this.OutputFileName =
match this.FullName, this.OutputType with
| Some fullName, CompileOutput.Library -> Some (Path.ChangeExtension(fullName, ".dll"))
| Some fullName, CompileOutput.Exe -> Some (Path.ChangeExtension(fullName, ".exe"))
| _ -> None
override this.ToString() = match this.Name with | Some n -> n | _ -> (sprintf "%A" this)
type CSharpCompilationSource =
{
Source: SourceCodeFileKind
LangVersion: CSharpLanguageVersion
TargetFramework: TargetFramework
OutputType: CompileOutput
OutputDirectory: DirectoryInfo option
Name: string option
References: CompilationUnit list
}
type ILCompilationSource =
{
Source: TestType
References: CompilationUnit list
}
type ErrorType = Error of int | Warning of int | Information of int | Hidden of int
type SymbolType =
| MemberOrFunctionOrValue of string
| Entity of string
| GenericParameter of string
| Parameter of string
| StaticParameter of string
| ActivePatternCase of string
| UnionCase of string
| Field of string
member this.FullName () =
match this with
| MemberOrFunctionOrValue fullname
| Entity fullname
| GenericParameter fullname
| Parameter fullname
| StaticParameter fullname
| ActivePatternCase fullname
| UnionCase fullname
| Field fullname -> fullname
let mapDiagnosticSeverity severity errorNumber =
match severity with
| FSharpDiagnosticSeverity.Hidden -> Hidden errorNumber
| FSharpDiagnosticSeverity.Info -> Information errorNumber
| FSharpDiagnosticSeverity.Warning -> Warning errorNumber
| FSharpDiagnosticSeverity.Error -> Error errorNumber
type Line = Line of int
type Col = Col of int
type Range =
{ StartLine: int
StartColumn: int
EndLine: int
EndColumn: int }
type Disposable (dispose : unit -> unit) =
interface IDisposable with
member this.Dispose() =
dispose()
type ErrorInfo =
{ Error: ErrorType
Range: Range
NativeRange : FSharp.Compiler.Text.range
Message: string
SubCategory: string }
// This type is used either for the output of the compiler (typically in CompilationResult coming from 'compile')
// or for the output of the code generated by the compiler (in CompilationResult coming from 'run')
type EvalOutput =
{ Result: Result<FsiValue option, exn>
StdOut: string
StdErr: string }
type RunOutput =
| EvalOutput of EvalOutput
| ExecutionOutput of ExecutionOutput
type SourceCodeFileName = string
type CompilationOutput =
{ OutputPath: string option
Dependencies: string list
Adjust: int
Diagnostics: ErrorInfo list
PerFileErrors: (SourceCodeFileName * ErrorInfo) list
Output: RunOutput option
Compilation: CompilationUnit }
[<RequireQualifiedAccess>]
type CompilationResult =
| Success of CompilationOutput
| Failure of CompilationOutput
with
member this.Output = match this with Success o | Failure o -> o
member this.RunOutput = this.Output.Output
member this.Compilation = this.Output.Compilation
member this.OutputPath = this.Output.OutputPath
type ExecutionPlatform =
| Anycpu = 0
| AnyCpu32bitPreferred = 1
| X86 = 2
| Itanium = 3
| X64 = 4
| Arm = 5
| Arm64 = 6
let public defaultOptions : string list = ["--realsig+"]
let normalizePathSeparator (text:string) = text.Replace(@"\", "/")
let normalizeName name =
let invalidPathChars = Array.concat [Path.GetInvalidPathChars(); [| ':'; '\\'; '/'; ' '; '.' |]]
let result = invalidPathChars |> Array.fold(fun (acc:string) (c:char) -> acc.Replace(string(c), "_")) name
result
let readFileOrDefault (path: string): string option =
match FileSystem.FileExistsShim(path) with
| true -> Some (File.ReadAllText path)
| _ -> None
let createCompilationUnit sourceBaselineSuffix ilBaselineSuffixes directoryPath filename =
let outputDirectoryPath = createTemporaryDirectory().FullName
let sourceFilePath = normalizePathSeparator (directoryPath ++ filename)
let fsBslFilePath = sourceFilePath + sourceBaselineSuffix + ".err.bsl"
let ilBslFilePath =
let ilBslPaths = [|
for baselineSuffix in ilBaselineSuffixes do
#if DEBUG
#if NETCOREAPP
yield sourceFilePath + baselineSuffix + ".il.netcore.debug.bsl"
yield sourceFilePath + baselineSuffix + ".il.netcore.bsl"
#else
yield sourceFilePath + baselineSuffix + ".il.net472.debug.bsl"
yield sourceFilePath + baselineSuffix + ".il.net472.bsl"
#endif
yield sourceFilePath + baselineSuffix + ".il.debug.bsl"
yield sourceFilePath + baselineSuffix + ".il.bsl"
#else
#if NETCOREAPP
yield sourceFilePath + baselineSuffix + ".il.netcore.release.bsl"
yield sourceFilePath + baselineSuffix + ".il.netcore.bsl"
#else
yield sourceFilePath + baselineSuffix + ".il.net472.release.bsl"
yield sourceFilePath + baselineSuffix + ".il.net472.bsl"
#endif
yield sourceFilePath + baselineSuffix + ".il.release.bsl"
yield sourceFilePath + baselineSuffix + ".il.bsl"
#endif
|]
let findBaseline =
ilBslPaths
|> Array.tryPick(fun p -> if File.Exists(p) then Some p else None)
match findBaseline with
| Some s -> s
| None -> sourceFilePath + sourceBaselineSuffix + ".il.bsl"
let fsOutFilePath = normalizePathSeparator (Path.ChangeExtension(outputDirectoryPath ++ filename, ".err"))
let ilOutFilePath = normalizePathSeparator (Path.ChangeExtension(outputDirectoryPath ++ filename, ".il"))
let fsBslSource = readFileOrDefault fsBslFilePath
let ilBslSource = readFileOrDefault ilBslFilePath
{ Source = SourceCodeFileKind.Create(sourceFilePath)
AdditionalSources = []
Baseline =
Some
{
SourceFilename = Some sourceFilePath
FSBaseline = { FilePath = fsOutFilePath; BslSource = fsBslFilePath; Content = fsBslSource }
ILBaseline = { FilePath = ilOutFilePath; BslSource = ilBslFilePath; Content = ilBslSource }
}
Options = Compiler.defaultOptions
OutputType = Library
Name = Some filename
IgnoreWarnings = false
References = []
OutputDirectory = Some (DirectoryInfo(outputDirectoryPath))
TargetFramework = TargetFramework.Current
StaticLink = false
} |> FS
/// For all files specified in the specified directory, whose name can be found in includedFiles
/// create a compilation with all baselines correctly when set
let createCompilationUnitForFiles baselineSuffix directoryPath includedFiles =
if not (Directory.Exists(directoryPath)) then
failwith (sprintf "Directory does not exist: \"%s\"." directoryPath)
let allFiles : string[] = Directory.GetFiles(directoryPath, "*.fs")
let filteredFiles =
match includedFiles |> Array.map (fun f -> normalizePathSeparator (directoryPath ++ f)) with
| [||] -> allFiles
| incl -> incl
let fsFiles = filteredFiles |> Array.map Path.GetFileName
if fsFiles |> Array.length < 1 then
failwith (sprintf "No required files found in \"%s\".\nAll files: %A.\nIncludes:%A." directoryPath allFiles includedFiles)
for f in filteredFiles do
if not <| FileSystem.FileExistsShim(f) then
failwithf "Requested file \"%s\" not found.\nAll files: %A.\nIncludes:%A." f allFiles includedFiles
let results =
fsFiles
|> Array.map (fun fs -> (createCompilationUnit baselineSuffix [baselineSuffix] directoryPath fs) :> obj)
|> Seq.map (fun c -> [| c |])
results
let getTestOutputDirectory dir testCaseName extraDirectory =
// If the executing assembly has 'artifacts\bin' in it's path then we are operating normally in the CI or dev tests
// Thus the output directory will be in a subdirectory below where we are executing.
// The subdirectory will be relative to the source directory containing the test source file,
// E.g
// When the source code is in:
// $(repo-root)\tests\FSharp.Compiler.ComponentTests\Conformance\PseudoCustomAttributes
// and the test is running in the FSharp.Compiler.ComponentTeststest library
// The output directory will be:
// artifacts\bin\FSharp.Compiler.ComponentTests\$(Flavour)\$(TargetFramework)\tests\FSharp.Compiler.ComponentTests\Conformance\PseudoCustomAttributes
//
// If we can't find anything then we execute in the directory containing the source
//
try
let testlibraryLocation = normalizePathSeparator (Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
let pos = testlibraryLocation.IndexOf("artifacts/bin",StringComparison.OrdinalIgnoreCase)
if pos > 0 then
// Running under CI or dev build
let testRoot = Path.Combine(testlibraryLocation.Substring(0, pos), @"tests/")
let testSourceDirectory =
let dirInfo = normalizePathSeparator (Path.GetFullPath(dir))
let testPaths = dirInfo.Replace(testRoot, "").Split('/')
testPaths[0] <- "tests"
Path.Combine(testPaths)
let n = Path.Combine(testlibraryLocation, testSourceDirectory.Trim('/'), normalizeName testCaseName, extraDirectory)
let outputDirectory = new DirectoryInfo(n)
Some outputDirectory
else
raise (new InvalidOperationException($"Failed to find the test output directory:\nTest Library Location: '{testlibraryLocation}'\n Pos: {pos}"))
None
with | e ->
raise (new InvalidOperationException($" '{e.Message}'. Can't get the location of the executing assembly"))
// Not very safe version of reading stuff from file, but we want to fail fast for now if anything goes wrong.
let private getSource (src: TestType) : string =
match src with
| Text t -> t
| Path p ->
use stream = FileSystem.OpenFileForReadShim(p)
stream.ReadAllText()
// Load the source file from the path
let loadSourceFromFile path = getSource(TestType.Path path)
let fsFromString (source: SourceCodeFileKind): FSharpCompilationSource =
source.GetSourceText |> Option.iter (Range.setTestSource source.GetSourceFileName)
{
Source = source
AdditionalSources = []
Baseline = None
Options = defaultOptions
OutputType = Library
OutputDirectory = None
Name = None
IgnoreWarnings = false
References = []
TargetFramework = TargetFramework.Current
StaticLink = false
}
let private csFromString (source: SourceCodeFileKind) : CSharpCompilationSource =
{
Source = source
LangVersion = CSharpLanguageVersion.CSharp9
TargetFramework = TargetFramework.Current
OutputType = Library
OutputDirectory = None
Name = None
References = []
}
let private fromFSharpDiagnostic (errors: FSharpDiagnostic[]) : (SourceCodeFileName * ErrorInfo) list =
let toErrorInfo (e: FSharpDiagnostic) : SourceCodeFileName * ErrorInfo =
let errorNumber = e.ErrorNumber
let severity = e.Severity
let error =
match severity with
| FSharpDiagnosticSeverity.Warning -> Warning errorNumber
| FSharpDiagnosticSeverity.Error -> Error errorNumber
| FSharpDiagnosticSeverity.Info -> Information errorNumber
| FSharpDiagnosticSeverity.Hidden -> Hidden errorNumber
e.FileName |> Path.GetFileName,
{ Error = error
NativeRange = e.Range
SubCategory = e.Subcategory
Range =
{ StartLine = e.StartLine
StartColumn = e.StartColumn
EndLine = e.EndLine
EndColumn = e.EndColumn }
Message = e.Message }
errors
|> List.ofArray
|> List.map toErrorInfo
let private fromFSharpDiagnosticDistinct (errors: ErrorInfo[]) : (SourceCodeFileName * ErrorInfo) list =
let errors = fromFSharpDiagnosticDistinct errors
errors
|> List.distinctBy (fun (name, ei) -> name, ei.NativeRange.Start, ei.NativeRange.StartColumn, ei.NativeRange.End, ei.NativeRange.EndColumn, ei.Message)
let private partitionErrors diagnostics = diagnostics |> List.partition (fun e -> match e.Error with Error _ -> true | _ -> false)
let private getErrors diagnostics = diagnostics |> List.filter (fun e -> match e.Error with Error _ -> true | _ -> false)
let private getWarnings diagnostics = diagnostics |> List.filter (fun e -> match e.Error with Warning _ -> true | _ -> false)
let private adjustRange (range: Range) (adjust: int) : Range =
{
StartLine = range.StartLine - adjust
StartColumn = range.StartColumn + 1
EndLine = range.EndLine - adjust
EndColumn = range.EndColumn + 1
}
let FsxSourceCode source =
SourceCodeFileKind.Fsx({FileName="test.fsx"; SourceText=Some source})
let Source source =
SourceCodeFileKind.Create("test.fs", source)
let SourceFromPath path =
SourceCodeFileKind.Create(path)
let FsiSource source =
SourceCodeFileKind.Fsi({FileName="test.fsi"; SourceText=Some source })
let FsSource source =
SourceCodeFileKind.Fs({FileName="test.fs"; SourceText=Some source })
let FsSourceWithFileName name source =
SourceCodeFileKind.Fs({FileName=name; SourceText=Some source })
let CsSource source =
SourceCodeFileKind.Cs({FileName="test.cs"; SourceText=Some source })
let CsFromPath (path: string) : CompilationUnit =
csFromString (SourceFromPath path)
|> CS
|> withName (Path.GetFileNameWithoutExtension(path))
let Fsx (source: string) : CompilationUnit =
fsFromString (FsxSourceCode source) |> FS
let FsxFromPath (path: string) : CompilationUnit =
fsFromString (SourceFromPath path) |> FS
let Fs (source: string) : CompilationUnit =
fsFromString (FsSource source) |> FS
let Fsi (source: string) : CompilationUnit =
fsFromString (FsiSource source) |> FS
let FSharp (source: string) : CompilationUnit =
Fs source
let FSharpWithFileName name (source: string) : CompilationUnit =
fsFromString (SourceCodeFileKind.Fs({FileName=name; SourceText=Some source }))
|> FS
let FsFromPath (path: string) : CompilationUnit =
fsFromString (SourceFromPath path)
|> FS
|> withName (Path.GetFileNameWithoutExtension(path))
let FSharpWithInputAndOutputPath (src: string) (inputFilePath: string) (outputFilePath: string) : CompilationUnit =
let compileDirectory = Path.GetDirectoryName(outputFilePath)
let name = Path.GetFileName(outputFilePath)
{
Source = SourceCodeFileKind.Create(inputFilePath, src)
AdditionalSources = []
Baseline = None
Options = defaultOptions
OutputType = Library
OutputDirectory = Some(DirectoryInfo(compileDirectory))
Name = Some name
IgnoreWarnings = false
References = []
TargetFramework = TargetFramework.Current
StaticLink = false
} |> FS
let CSharp (source: string) : CompilationUnit =
csFromString (SourceCodeFileKind.Fs({FileName="test.cs"; SourceText=Some source })) |> CS
let CSharpFromPath (path: string) : CompilationUnit =
csFromString (SourceFromPath path) |> CS
let asFs (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS { Source = SourceCodeFileKind.Fsi _} -> cUnit
| FS src -> FS {src with Source=SourceCodeFileKind.Fs({FileName=src.Source.GetSourceFileName; SourceText=src.Source.GetSourceText})}
| _ -> failwith "Only F# compilation can be of type Fs."
let asFsi (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS src -> FS {src with Source=SourceCodeFileKind.Fsi({FileName=src.Source.GetSourceFileName; SourceText=src.Source.GetSourceText})}
| _ -> failwith "Only F# compilation can be of type Fsi."
let asFsx (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS src -> FS {src with Source=SourceCodeFileKind.Fsx({FileName=src.Source.GetSourceFileName; SourceText=src.Source.GetSourceText})}
| _ -> failwith "Only F# compilation can be of type Fsx."
let withName (name: string) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS src -> FS { src with Name = Some name }
| CS src -> CS { src with Name = Some name }
| IL _ -> failwith "IL Compilation cannot be named."
let withFileName (name: string) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS compilationSource -> FS { compilationSource with Source = compilationSource.Source.WithFileName(name) }
| CS cSharpCompilationSource -> CS { cSharpCompilationSource with Source = cSharpCompilationSource.Source.WithFileName(name) }
| IL _ -> failwith "IL Compilation cannot be named."
let withReferenceFSharpCompilerService (cUnit: CompilationUnit) : CompilationUnit =
// Compute the location of the FSharp.Compiler.Service dll that matches the target framework used to build this test assembly
let compilerServiceAssemblyLocation =
typeof<FSharp.Compiler.Text.Range>.Assembly.Location
withOptionsHelper [ $"-r:{compilerServiceAssemblyLocation}" ] "withReferenceFSharpCompilerService is only supported for F#" cUnit
let withReferences (references: CompilationUnit list) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with References = fs.References @ references }
| CS cs -> CS { cs with References = cs.References @ references }
| IL _ -> failwith "References are not supported in IL"
let withStaticLink (references: CompilationUnit list) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with References = fs.References @ references }
| CS cs -> CS { cs with References = cs.References @ references }
| IL _ -> failwith "References are not supported in IL"
let withAdditionalSourceFiles (additionalSources: SourceCodeFileKind list) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with AdditionalSources = fs.AdditionalSources @ additionalSources }
| CS _ -> failwith "References are not supported in C#"
| IL _ -> failwith "References are not supported in IL"
let withAdditionalSourceFile (additionalSource: SourceCodeFileKind) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with AdditionalSources = fs.AdditionalSources @ [additionalSource]}
| CS _ -> failwith "References are not supported in C#"
| IL _ -> failwith "References are not supported in IL"
let private withOptionsHelper (options: string list) (message:string) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with Options = fs.Options @ options }
| _ -> failwith message
let withCodepage (codepage:string) (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--codepage:{codepage}" ] "codepage is only supported on F#" cUnit
let withDebug (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug+" ] "debug+ is only supported on F#" cUnit
let withNoDebug (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug-" ] "debug- is only supported on F#" cUnit
let withOptions (options: string list) (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper options "withOptions is only supported for F#" cUnit
let withOptionsString (options: string) (cUnit: CompilationUnit) : CompilationUnit =
let options = if String.IsNullOrWhiteSpace options then [] else (options.Split([|';'|])) |> Array.toList
withOptionsHelper options "withOptionsString is only supported for F#" cUnit
let withOutputDirectory (path: DirectoryInfo option) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with OutputDirectory = path }
| CS cs -> CS { cs with OutputDirectory = path }
| _ -> failwith "withOutputDirectory is only supported on F# and C#"
let withCheckNulls (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper ["--checknulls+"] "checknulls is only supported in F#" cUnit
let withBufferWidth (width: int)(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--bufferwidth:{width}" ] "withBufferWidth is only supported on F#" cUnit
let withDefines (defines: string list) (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper (defines |> List.map(fun define -> $"--define:{define}")) "withDefines is only supported on F#" cUnit
let withErrorRanges (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--test:ErrorRanges" ] "withErrorRanges is only supported on F#" cUnit
let withLangVersion80 (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--langversion:8.0" ] "withLangVersion80 is only supported on F#" cUnit
let withLangVersion90 (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--langversion:9.0" ] "withLangVersion90 is only supported on F#" cUnit
let withLangVersion10 (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--langversion:10.0" ] "withLangVersion10 is only supported on F#" cUnit
let withLangVersionPreview (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--langversion:preview" ] "withLangVersionPreview is only supported on F#" cUnit
let withLangVersion (version: string) (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--langversion:{version}" ] "withLangVersion is only supported on F#" cUnit
let withAssemblyVersion (version:string) (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--version:{version}" ] "withAssemblyVersion is only supported on F#" cUnit
let withWarnOn warning (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--warnon:{warning}" ] "withWarnOn is only supported for F#" cUnit
let withNoWarn warning (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--nowarn:{warning}" ] "withNoWarn is only supported for F#" cUnit
let withNoOptimize (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--optimize-" ] "withNoOptimize is only supported for F#" cUnit
let withOptimize (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--optimize+" ] "withOptimize is only supported for F#" cUnit
let withOptimization (optimization: bool) (cUnit: CompilationUnit) : CompilationUnit =
let option = if optimization then "--optimize+" else "--optimize-"
withOptionsHelper [ option ] "withOptimization is only supported for F#" cUnit
let withFullPdb(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug:full" ] "withFullPdb is only supported for F#" cUnit
let withPdbOnly(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug:pdbonly" ] "withPdbOnly is only supported for F#" cUnit
let withPortablePdb(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug:portable" ] "withPortablePdb is only supported for F#" cUnit
let withEmbeddedPdb(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--debug:embedded" ] "withEmbeddedPdb is only supported for F#" cUnit
let withEmbedAllSource(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--embed+" ] "withEmbedAllSource is only supported for F#" cUnit
let withEmbedNoSource(cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--embed-" ] "withEmbedNoSource is only supported for F#" cUnit
let withEmbedSourceFiles(cUnit: CompilationUnit) files : CompilationUnit =
withOptionsHelper [ $"--embed:{files}" ] "withEmbedSourceFiles is only supported for F#" cUnit
/// Turns on checks that check integrity of XML doc comments
let withXmlCommentChecking (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--warnon:3390" ] "withXmlCommentChecking is only supported for F#" cUnit
/// Turns on checks that force the documentation of all parameters
let withXmlCommentStrictParamChecking (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--warnon:3391" ] "withXmlCommentChecking is only supported for F#" cUnit
/// Only include optimization information essential for implementing inlined constructs. Inhibits cross-module inlining but improves binary compatibility.
let withNoOptimizationData (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--nooptimizationdata" ] "withNoOptimizationData is only supported for F#" cUnit
/// Don't add a resource to the generated assembly containing F#-specific metadata
let withNoInterfaceData (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ "--nointerfacedata" ] "withNoInterfaceData is only supported for F#" cUnit
//--refonly[+|-]
let withRefOnly (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--refonly+" ] "withRefOnly is only supported for F#" cUnit
//--refonly[+|-]
let withNoRefOnly (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--refonly-" ] "withRefOnly is only supported for F#" cUnit
//--refout:<file> Produce a reference assembly with the specified file path.
let withRefOut (name:string) (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--refout:{name}" ] "withNoInterfaceData is only supported for F#" cUnit
let withCSharpLanguageVersion (ver: CSharpLanguageVersion) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| CS cs -> CS { cs with LangVersion = ver }
| _ -> failwith "Only supported in C#"
let withCSharpLanguageVersionPreview =
withCSharpLanguageVersion CSharpLanguageVersion.Preview
let withOutputType (outputType : CompileOutput) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS x -> FS { x with OutputType = outputType }
| CS x -> CS { x with OutputType = outputType }
| _ -> failwith "TODO: Implement where applicable."
let withRealInternalSignatureOff (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with Options = fs.Options @ ["--realsig-"] }
| _ -> failwith "withRealInternalSignatureOff only supported by f#"
let withRealInternalSignatureOn (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with Options = fs.Options @ ["--realsig+"] }
| _ -> failwith "withRealInternalSignatureOn only supported by f#"
let withRealInternalSignature (realSig: bool) (cUnit: CompilationUnit) : CompilationUnit =
if realSig then
cUnit |> withRealInternalSignatureOn
else
cUnit |> withRealInternalSignatureOff
let asExe (cUnit: CompilationUnit) : CompilationUnit =
withOutputType CompileOutput.Exe cUnit
let asLibrary (cUnit: CompilationUnit) : CompilationUnit =
withOutputType CompileOutput.Library cUnit
let asModule (cUnit: CompilationUnit) : CompilationUnit =
withOutputType CompileOutput.Module cUnit
let asNetStandard20 (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with TargetFramework = TargetFramework.NetStandard20 }
| CS _ -> failwith "References are not supported in CS"
| IL _ -> failwith "References are not supported in IL"
let withPlatform (platform:ExecutionPlatform) (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS _ ->
let p =
match platform with
| ExecutionPlatform.Anycpu -> "anycpu"
| ExecutionPlatform.AnyCpu32bitPreferred -> "anycpu32bitpreferred"
| ExecutionPlatform.Itanium -> "Itanium"
| ExecutionPlatform.X64 -> "x64"
| ExecutionPlatform.X86 -> "x86"
| ExecutionPlatform.Arm -> "arm"
| ExecutionPlatform.Arm64 -> "arm64"
| _ -> failwith $"Unknown value for ExecutionPlatform: {platform}"
withOptionsHelper [ $"--platform:{p}" ] "withPlatform is only supported for F#" cUnit
| _ -> failwith "TODO: Implement ignorewarnings for the rest."
let ignoreWarnings (cUnit: CompilationUnit) : CompilationUnit =
match cUnit with
| FS fs -> FS { fs with IgnoreWarnings = true }
| _ -> failwith "TODO: Implement ignorewarnings for the rest."
let withCulture culture (cUnit: CompilationUnit) : CompilationUnit =
withOptionsHelper [ $"--preferreduilang:%s{culture}" ] "preferreduilang is only supported for F#" cUnit
let rec private asMetadataReference (cUnit: CompilationUnit) reference =
let ignoreWarnings =
match cUnit with
| FS fs -> fs.IgnoreWarnings
| _ -> false
match reference with
| CompilationReference (cmpl, _) ->
let result = compileFSharpCompilation cmpl ignoreWarnings cUnit
match result with
| CompilationResult.Failure f ->
let message = sprintf "Operation failed (expected to succeed).\n All errors:\n%A" (f.Diagnostics)
failwith message
| CompilationResult.Success s ->
match s.OutputPath with
| None -> failwith "Operation didn't produce any output!"
| Some p -> p |> MetadataReference.CreateFromFile
| TestCompilationReference cmpl ->
let outputDirectory = createTemporaryDirectory()
let tmp = cmpl.EmitToDirectory outputDirectory
tmp |> MetadataReference.CreateFromFile
let private processReferences (references: CompilationUnit list) defaultOutputDirectory =
let rec loop acc = function
| [] -> List.rev acc
| x::xs ->
match x with
| FS fs ->
let refs = loop [] fs.References
let options = fs.Options |> List.toArray
let name = defaultArg fs.Name null
let outDir =
match fs.OutputDirectory with
| Some outputDirectory -> outputDirectory
| _ -> defaultOutputDirectory
let cmpl =
CompilationReference.CreateFSharp(Compilation.CreateFromSources([fs.Source] @ fs.AdditionalSources, fs.OutputType, options, fs.TargetFramework, refs, name, outDir), fs.StaticLink)
loop (cmpl::acc) xs
| CS cs ->
let refs = loop [] cs.References
let name = defaultArg cs.Name null
let metadataReferences = List.map (asMetadataReference x) refs
let cmpl =
CompilationUtil.CreateCSharpCompilation(cs.Source, cs.LangVersion, cs.TargetFramework, additionalReferences = metadataReferences.ToImmutableArray().As<PortableExecutableReference>(), name = name)
|> CompilationReference.Create
loop (cmpl::acc) xs
| IL _ -> failwith "TODO: Process references for IL"
loop [] references
let private compileFSharpCompilation compilation ignoreWarnings (cUnit: CompilationUnit) : CompilationResult =
use capture = new TestConsole.ExecutionCapture()
let ((err: FSharpDiagnostic[], exn, outputFilePath: string), deps) =
CompilerAssert.CompileRaw(compilation, ignoreWarnings)
// Create and stash the console output
let diagnostics = err |> fromFSharpDiagnostic
let outcome = exn |> Option.map Failure |> Option.defaultValue NoExitCode
let result = {
OutputPath = None
Dependencies = deps
Adjust = 0
PerFileErrors = diagnostics
Diagnostics = diagnostics |> List.map snd
Output = Some (RunOutput.ExecutionOutput { Outcome = outcome; StdOut = capture.OutText; StdErr = capture.ErrorText })
Compilation = cUnit
}
let (errors, warnings) = partitionErrors result.Diagnostics
// Treat warnings as errors if "IgnoreWarnings" is false
if errors.Length > 0 || (warnings.Length > 0 && not ignoreWarnings) then
CompilationResult.Failure result
else
CompilationResult.Success { result with OutputPath = Some outputFilePath }
let private compileFSharp (fs: FSharpCompilationSource) : CompilationResult =
let output = fs.OutputType
let options = fs.Options |> Array.ofList
let name = defaultArg fs.Name null
let outputDirectory =
match fs.OutputDirectory with
| Some di -> di
| None -> createTemporaryDirectory()
let references = processReferences fs.References outputDirectory
let compilation = Compilation.CreateFromSources([fs.Source] @ fs.AdditionalSources, output, options, fs.TargetFramework, references, name, outputDirectory)
compileFSharpCompilation compilation fs.IgnoreWarnings (FS fs)
let toErrorInfo (d: Diagnostic) =
let span = d.Location.GetMappedLineSpan().Span
let number = d.Id |> Seq.where Char.IsDigit |> String.Concat |> int
{ Error =
match d.Severity with
| DiagnosticSeverity.Error -> Error
| DiagnosticSeverity.Warning -> Warning
| DiagnosticSeverity.Info -> Information
| DiagnosticSeverity.Hidden -> Hidden
| x -> failwith $"Unknown severity {x}"
|> (|>) number
Range =
{ StartLine = span.Start.Line
StartColumn = span.Start.Character
EndLine = span.End.Line
EndColumn = span.End.Character }
NativeRange = Unchecked.defaultof<_>
SubCategory = ""
Message = d.GetMessage() }
let private compileCSharpCompilation (compilation: CSharpCompilation) csSource (filePath : string) dependencies : CompilationResult =
let cmplResult = compilation.Emit filePath
let result =
{ OutputPath = None
Dependencies = dependencies
Adjust = 0
Diagnostics = cmplResult.Diagnostics |> Seq.map toErrorInfo |> Seq.toList
PerFileErrors= List.empty // Not needed for C# testing for now. Implement when needed
Output = None
Compilation = CS csSource }
if cmplResult.Success then
CompilationResult.Success { result with OutputPath = Some filePath }
else
CompilationResult.Failure result
let private compileCSharp (csSource: CSharpCompilationSource) : CompilationResult =
let source = csSource.Source.GetSourceText |> Option.defaultValue ""
let name = defaultArg csSource.Name (getTemporaryFileName())
let outputDirectory =
match csSource.OutputDirectory with
| Some di -> di
| None -> createTemporaryDirectory()
let additionalReferences =
processReferences csSource.References outputDirectory
|> List.map (asMetadataReference (CS csSource))
let additionalMetadataReferences = additionalReferences.ToImmutableArray().As<MetadataReference>()
let additionalReferencePaths = [for r in additionalReferences -> r.FilePath]
let references = TargetFrameworkUtil.getReferences csSource.TargetFramework
let lv = CSharpLanguageVersion.toLanguageVersion csSource.LangVersion
let outputKind, extension =
match csSource.OutputType with
| Exe -> OutputKind.ConsoleApplication, "exe"
| Library -> OutputKind.DynamicallyLinkedLibrary, "dll"
| Module -> OutputKind.NetModule, "mod"
let cmpl =
CSharpCompilation.Create(
name,
[ CSharpSyntaxTree.ParseText (source, CSharpParseOptions lv) ],
references.As<MetadataReference>().AddRange additionalMetadataReferences,
CSharpCompilationOptions outputKind)
let filename = Path.ChangeExtension(cmpl.AssemblyName, extension)
let filePath = Path.Combine(outputDirectory.FullName, filename)
compileCSharpCompilation cmpl csSource filePath additionalReferencePaths
let compile (cUnit: CompilationUnit) : CompilationResult =
match cUnit with
| FS fs -> compileFSharp fs
| CS cs -> compileCSharp cs
| _ -> failwith "TODO"
let private getAssemblyInBytes (result: CompilationResult) =
match result with
| CompilationResult.Success output ->
match output.OutputPath with
| Some filePath -> File.ReadAllBytes(filePath)
| _ -> failwith "Output path not found."
| _ ->
failwith "Compilation has errors."
let getAssembly = getAssemblyInBytes >> Assembly.Load
let withPeReader func compilationResult =
let bytes = getAssemblyInBytes compilationResult
use reader = new PEReader(bytes.ToImmutableArray())
func reader
let withMetadataReader func =
withPeReader (fun reader -> reader.GetMetadataReader() |> func)
let compileGuid cUnit =
cUnit
|> compile
|> shouldSucceed
|> withMetadataReader (fun reader -> reader.GetModuleDefinition().Mvid |> reader.GetGuid)
let compileAssembly cUnit =
cUnit
|> compile
|> shouldSucceed
|> getAssembly
let private parseFSharp (fsSource: FSharpCompilationSource) : CompilationResult =
let source = fsSource.Source.GetSourceText |> Option.defaultValue ""
let fileName = fsSource.Source.ChangeExtension.GetSourceFileName
let parseResults = CompilerAssert.Parse(source, fileName = fileName)
let failed = parseResults.ParseHadErrors
let diagnostics = parseResults.Diagnostics |> fromFSharpDiagnostic
let result =
{ OutputPath = None
Dependencies = []
Adjust = 0
Diagnostics = diagnostics |> List.map snd
PerFileErrors= diagnostics
Output = None
Compilation = FS fsSource }
if failed then
CompilationResult.Failure result
else
CompilationResult.Success result
let parse (cUnit: CompilationUnit) : CompilationResult =
match cUnit with
| FS fs -> parseFSharp fs
| _ -> failwith "Parsing only supported for F#."
let private typecheckFSharpSourceAndReturnErrors (fsSource: FSharpCompilationSource) : FSharpDiagnostic [] =
let source =
match fsSource.Source.GetSourceText with
| None -> File.ReadAllText(fsSource.Source.GetSourceFileName)