forked from nosami/visualfsharp
/
fsc.fs
2256 lines (1873 loc) · 116 KB
/
fsc.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.
// Driver for F# compiler.
//
// Roughly divides into:
// - Parsing
// - Flags
// - Importing IL assemblies
// - Compiling (including optimizing)
// - Linking (including ILX-IL transformation)
module internal FSharp.Compiler.Driver
open System
open System.Collections.Generic
open System.Diagnostics
open System.Globalization
open System.IO
open System.Reflection
open System.Text
open System.Threading
open Internal.Utilities
open Internal.Utilities.Collections
open Internal.Utilities.Filename
open Internal.Utilities.StructuredFormat
open FSharp.Compiler
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.AbstractIL.Internal
open FSharp.Compiler.AbstractIL.Internal.Library
open FSharp.Compiler.AbstractIL.Internal.Utils
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.AccessibilityLogic
open FSharp.Compiler.CheckExpressions
open FSharp.Compiler.CheckDeclarations
open FSharp.Compiler.CompilerConfig
open FSharp.Compiler.CompilerDiagnostics
open FSharp.Compiler.CompilerImports
open FSharp.Compiler.CompilerOptions
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.ErrorLogger
open FSharp.Compiler.IlxGen
open FSharp.Compiler.InfoReader
open FSharp.Compiler.Lib
open FSharp.Compiler.ParseAndCheckInputs
open FSharp.Compiler.PrettyNaming
open FSharp.Compiler.OptimizeInputs
open FSharp.Compiler.ScriptClosure
open FSharp.Compiler.SyntaxTree
open FSharp.Compiler.Range
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.XmlDoc
open Microsoft.DotNet.DependencyManager
open FSharp.Compiler.AbstractIL.Internal.StrongNameSign
open FSharp.Compiler.AbstractIL.Internal.StrongNameSign
#if !NO_EXTENSIONTYPING
open FSharp.Compiler.ExtensionTyping
#endif
#nowarn "45" // This method will be made public in the underlying IL because it may implement an interface or override a method
//----------------------------------------------------------------------------
// Reporting - warnings, errors
//----------------------------------------------------------------------------
/// An error logger that reports errors up to some maximum, notifying the exiter when that maximum is reached
[<AbstractClass>]
type ErrorLoggerUpToMaxErrors(tcConfigB: TcConfigBuilder, exiter: Exiter, nameForDebugging) =
inherit ErrorLogger(nameForDebugging)
let mutable errors = 0
/// Called when an error or warning occurs
abstract HandleIssue: tcConfigB: TcConfigBuilder * error: PhasedDiagnostic * isError: bool -> unit
/// Called when 'too many errors' has occurred
abstract HandleTooManyErrors: text: string -> unit
override x.ErrorCount = errors
override x.DiagnosticSink(err, isError) =
if isError || ReportWarningAsError tcConfigB.errorSeverityOptions err then
if errors >= tcConfigB.maxErrors then
x.HandleTooManyErrors(FSComp.SR.fscTooManyErrors())
exiter.Exit 1
x.HandleIssue(tcConfigB, err, true)
errors <- errors + 1
match err.Exception, tcConfigB.simulateException with
| InternalError (msg, _), None
| Failure msg, None -> Debug.Assert(false, sprintf "Bug in compiler: %s\n%s" msg (err.Exception.ToString()))
| :? KeyNotFoundException, None -> Debug.Assert(false, sprintf "Lookup exception in compiler: %s" (err.Exception.ToString()))
| _ -> ()
elif ReportWarning tcConfigB.errorSeverityOptions err then
x.HandleIssue(tcConfigB, err, isError)
/// Create an error logger that counts and prints errors
let ConsoleErrorLoggerUpToMaxErrors (tcConfigB: TcConfigBuilder, exiter : Exiter) =
{ new ErrorLoggerUpToMaxErrors(tcConfigB, exiter, "ConsoleErrorLoggerUpToMaxErrors") with
member __.HandleTooManyErrors(text : string) =
DoWithErrorColor false (fun () -> Printf.eprintfn "%s" text)
member __.HandleIssue(tcConfigB, err, isError) =
DoWithErrorColor isError (fun () ->
let diag = OutputDiagnostic (tcConfigB.implicitIncludeDir, tcConfigB.showFullPaths, tcConfigB.flatErrors, tcConfigB.errorStyle, isError)
writeViaBuffer stderr diag err
stderr.WriteLine())
} :> ErrorLogger
/// This error logger delays the messages it receives. At the end, call ForwardDelayedDiagnostics
/// to send the held messages.
type DelayAndForwardErrorLogger(exiter: Exiter, errorLoggerProvider: ErrorLoggerProvider) =
inherit CapturingErrorLogger("DelayAndForwardErrorLogger")
member x.ForwardDelayedDiagnostics(tcConfigB: TcConfigBuilder) =
let errorLogger = errorLoggerProvider.CreateErrorLoggerUpToMaxErrors(tcConfigB, exiter)
x.CommitDelayedDiagnostics errorLogger
and [<AbstractClass>]
ErrorLoggerProvider() =
member this.CreateDelayAndForwardLogger exiter = DelayAndForwardErrorLogger(exiter, this)
abstract CreateErrorLoggerUpToMaxErrors : tcConfigBuilder : TcConfigBuilder * exiter : Exiter -> ErrorLogger
/// Part of LegacyHostedCompilerForTesting
///
/// Yet another ErrorLogger implementation, capturing the messages but only up to the maxerrors maximum
type InProcErrorLoggerProvider() =
let errors = ResizeArray()
let warnings = ResizeArray()
member __.Provider =
{ new ErrorLoggerProvider() with
member log.CreateErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter) =
{ new ErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter, "InProcCompilerErrorLoggerUpToMaxErrors") with
member this.HandleTooManyErrors text = warnings.Add(Diagnostic.Short(false, text))
member this.HandleIssue(tcConfigBuilder, err, isError) =
// 'true' is passed for "suggestNames", since we want to suggest names with fsc.exe runs and this doesn't affect IDE perf
let errs =
CollectDiagnostic
(tcConfigBuilder.implicitIncludeDir, tcConfigBuilder.showFullPaths,
tcConfigBuilder.flatErrors, tcConfigBuilder.errorStyle, isError, err, true)
let container = if isError then errors else warnings
container.AddRange(errs) }
:> ErrorLogger }
member __.CapturedErrors = errors.ToArray()
member __.CapturedWarnings = warnings.ToArray()
/// The default ErrorLogger implementation, reporting messages to the Console up to the maxerrors maximum
type ConsoleLoggerProvider() =
inherit ErrorLoggerProvider()
override this.CreateErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter) = ConsoleErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter)
/// Notify the exiter if any error has occurred
let AbortOnError (errorLogger: ErrorLogger, exiter : Exiter) =
if errorLogger.ErrorCount > 0 then
exiter.Exit 1
//----------------------------------------------------------------------------
// DisposablesTracker
//----------------------------------------------------------------------------
/// Track a set of resources to cleanup
type DisposablesTracker() =
let items = Stack<IDisposable>()
member this.Register i = items.Push i
interface IDisposable with
member this.Dispose() =
let l = List.ofSeq items
items.Clear()
for i in l do
try i.Dispose() with _ -> ()
let TypeCheck (ctok, tcConfig, tcImports, tcGlobals, errorLogger: ErrorLogger, assemblyName, niceNameGen, tcEnv0, inputs, exiter: Exiter) =
try
if isNil inputs then error(Error(FSComp.SR.fscNoImplementationFiles(), Range.rangeStartup))
let ccuName = assemblyName
let tcInitialState = GetInitialTcState (rangeStartup, ccuName, tcConfig, tcGlobals, tcImports, niceNameGen, tcEnv0)
TypeCheckClosedInputSet (ctok, (fun () -> errorLogger.ErrorCount > 0), tcConfig, tcImports, tcGlobals, None, tcInitialState, inputs)
with e ->
errorRecovery e rangeStartup
exiter.Exit 1
/// Check for .fsx and, if present, compute the load closure for of #loaded files.
let AdjustForScriptCompile(ctok, tcConfigB: TcConfigBuilder, commandLineSourceFiles, lexResourceManager, dependencyProvider) =
let combineFilePath file =
try
if FileSystem.IsPathRootedShim file then file
else Path.Combine(tcConfigB.implicitIncludeDir, file)
with _ ->
error (Error(FSComp.SR.pathIsInvalid file, rangeStartup))
let commandLineSourceFiles =
commandLineSourceFiles
|> List.map combineFilePath
let mutable allSources = []
let tcConfig = TcConfig.Create(tcConfigB, validate=false)
let AddIfNotPresent(filename: string) =
if not(allSources |> List.contains filename) then
allSources <- filename :: allSources
let AppendClosureInformation filename =
if IsScript filename then
let closure =
LoadClosure.ComputeClosureOfScriptFiles
(ctok, tcConfig, [filename, rangeStartup], CodeContext.Compilation,
lexResourceManager, dependencyProvider)
// Record the references from the analysis of the script. The full resolutions are recorded as the corresponding #I paths used to resolve them
// are local to the scripts and not added to the tcConfigB (they are added to localized clones of the tcConfigB).
let references =
closure.References
|> List.collect snd
|> List.filter (fun r -> not (Range.equals r.originalReference.Range range0) && not (Range.equals r.originalReference.Range rangeStartup))
references |> List.iter (fun r -> tcConfigB.AddReferencedAssemblyByPath(r.originalReference.Range, r.resolvedPath))
closure.NoWarns |> List.collect (fun (n, ms) -> ms|>List.map(fun m->m, n)) |> List.iter (fun (x,m) -> tcConfigB.TurnWarningOff(x, m))
closure.SourceFiles |> List.map fst |> List.iter AddIfNotPresent
closure.AllRootFileDiagnostics |> List.iter diagnosticSink
else AddIfNotPresent filename
// Find closure of .fsx files.
commandLineSourceFiles |> List.iter AppendClosureInformation
List.rev allSources
let ProcessCommandLineFlags (tcConfigB: TcConfigBuilder, setProcessThreadLocals, lcidFromCodePage, argv) =
let mutable inputFilesRef = []
let collect name =
let lower = String.lowercase name
if List.exists (Filename.checkSuffix lower) [".resx"] then
error(Error(FSComp.SR.fscResxSourceFileDeprecated name, rangeStartup))
else
inputFilesRef <- name :: inputFilesRef
let abbrevArgs = GetAbbrevFlagSet tcConfigB true
// This is where flags are interpreted by the command line fsc.exe.
ParseCompilerOptions (collect, GetCoreFscCompilerOptions tcConfigB, List.tail (PostProcessCompilerArgs abbrevArgs argv))
if not (tcConfigB.portablePDB || tcConfigB.embeddedPDB) then
if tcConfigB.embedAllSource || (tcConfigB.embedSourceList |> isNil |> not) then
error(Error(FSComp.SR.optsEmbeddedSourceRequirePortablePDBs(), rangeCmdArgs))
if not (String.IsNullOrEmpty(tcConfigB.sourceLink)) then
error(Error(FSComp.SR.optsSourceLinkRequirePortablePDBs(), rangeCmdArgs))
if tcConfigB.debuginfo && not tcConfigB.portablePDB then
if tcConfigB.deterministic then
error(Error(FSComp.SR.fscDeterministicDebugRequiresPortablePdb(), rangeCmdArgs))
if tcConfigB.pathMap <> PathMap.empty then
error(Error(FSComp.SR.fscPathMapDebugRequiresPortablePdb(), rangeCmdArgs))
let inputFiles = List.rev inputFilesRef
// Check if we have a codepage from the console
match tcConfigB.lcid with
| Some _ -> ()
| None -> tcConfigB.lcid <- lcidFromCodePage
setProcessThreadLocals tcConfigB
(* step - get dll references *)
let dllFiles, sourceFiles = inputFiles |> List.map(fun p -> trimQuotes p) |> List.partition Filename.isDll
match dllFiles with
| [] -> ()
| h :: _ -> errorR (Error(FSComp.SR.fscReferenceOnCommandLine h, rangeStartup))
dllFiles |> List.iter (fun f->tcConfigB.AddReferencedAssemblyByPath(rangeStartup, f))
sourceFiles
module InterfaceFileWriter =
let BuildInitialDisplayEnvForSigFileGeneration tcGlobals =
let denv = DisplayEnv.Empty tcGlobals
let denv =
{ denv with
showImperativeTyparAnnotations=true
showHiddenMembers=true
showObsoleteMembers=true
showAttributes=true }
denv.SetOpenPaths
[ FSharpLib.RootPath
FSharpLib.CorePath
FSharpLib.CollectionsPath
FSharpLib.ControlPath
(IL.splitNamespace FSharpLib.ExtraTopLevelOperatorsName) ]
let WriteInterfaceFile (tcGlobals, tcConfig: TcConfig, infoReader, declaredImpls) =
/// Use a UTF-8 Encoding with no Byte Order Mark
let os =
if tcConfig.printSignatureFile="" then Console.Out
else (File.CreateText tcConfig.printSignatureFile :> TextWriter)
if tcConfig.printSignatureFile <> "" && not (List.exists (Filename.checkSuffix tcConfig.printSignatureFile) FSharpLightSyntaxFileSuffixes) then
fprintfn os "#light"
fprintfn os ""
for (TImplFile (_, _, mexpr, _, _, _)) in declaredImpls do
let denv = BuildInitialDisplayEnvForSigFileGeneration tcGlobals
writeViaBuffer os (fun os s -> Printf.bprintf os "%s\n\n" s)
(NicePrint.layoutInferredSigOfModuleExpr true { denv with shrinkOverloads = false; printVerboseSignatures = true } infoReader AccessibleFromSomewhere range0 mexpr |> Display.squashTo 80 |> Layout.showL)
if tcConfig.printSignatureFile <> "" then os.Dispose()
module XmlDocWriter =
let hasDoc (doc: XmlDoc) = not doc.IsEmpty
let computeXmlDocSigs (tcGlobals, generatedCcu: CcuThunk) =
(* the xmlDocSigOf* functions encode type into string to be used in "id" *)
let g = tcGlobals
let doValSig ptext (v: Val) = if hasDoc v.XmlDoc then v.XmlDocSig <- XmlDocSigOfVal g false ptext v
let doTyconSig ptext (tc: Tycon) =
if (hasDoc tc.XmlDoc) then tc.XmlDocSig <- XmlDocSigOfTycon [ptext; tc.CompiledName]
for vref in tc.MembersOfFSharpTyconSorted do
doValSig ptext vref.Deref
for uc in tc.UnionCasesArray do
if (hasDoc uc.XmlDoc) then uc.XmlDocSig <- XmlDocSigOfUnionCase [ptext; tc.CompiledName; uc.Id.idText]
for rf in tc.AllFieldsArray do
if (hasDoc rf.XmlDoc) then
rf.XmlDocSig <-
if tc.IsRecordTycon && (not rf.IsStatic) then
// represents a record field, which is exposed as a property
XmlDocSigOfProperty [ptext; tc.CompiledName; rf.Id.idText]
else
XmlDocSigOfField [ptext; tc.CompiledName; rf.Id.idText]
let doModuleMemberSig path (m: ModuleOrNamespace) = m.XmlDocSig <- XmlDocSigOfSubModul [path]
(* moduleSpec - recurses *)
let rec doModuleSig path (mspec: ModuleOrNamespace) =
let mtype = mspec.ModuleOrNamespaceType
let path =
(* skip the first item in the path which is the assembly name *)
match path with
| None -> Some ""
| Some "" -> Some mspec.LogicalName
| Some p -> Some (p+"."+mspec.LogicalName)
let ptext = match path with None -> "" | Some t -> t
if mspec.IsModule then doModuleMemberSig ptext mspec
let vals =
mtype.AllValsAndMembers
|> Seq.toList
|> List.filter (fun x -> not x.IsCompilerGenerated)
|> List.filter (fun x -> x.MemberInfo.IsNone || x.IsExtensionMember)
List.iter (doModuleSig path) mtype.ModuleAndNamespaceDefinitions
List.iter (doTyconSig ptext) mtype.ExceptionDefinitions
List.iter (doValSig ptext) vals
List.iter (doTyconSig ptext) mtype.TypeDefinitions
doModuleSig None generatedCcu.Contents
let writeXmlDoc (assemblyName, generatedCcu: CcuThunk, xmlfile) =
if not (Filename.hasSuffixCaseInsensitive "xml" xmlfile ) then
error(Error(FSComp.SR.docfileNoXmlSuffix(), Range.rangeStartup))
(* the xmlDocSigOf* functions encode type into string to be used in "id" *)
let mutable members = []
let addMember id xmlDoc =
if hasDoc xmlDoc then
let doc = xmlDoc.GetXmlText()
members <- (id, doc) :: members
let doVal (v: Val) = addMember v.XmlDocSig v.XmlDoc
let doUnionCase (uc: UnionCase) = addMember uc.XmlDocSig uc.XmlDoc
let doField (rf: RecdField) = addMember rf.XmlDocSig rf.XmlDoc
let doTycon (tc: Tycon) =
addMember tc.XmlDocSig tc.XmlDoc
for vref in tc.MembersOfFSharpTyconSorted do
doVal vref.Deref
for uc in tc.UnionCasesArray do
doUnionCase uc
for rf in tc.AllFieldsArray do
doField rf
let modulMember (m: ModuleOrNamespace) = addMember m.XmlDocSig m.XmlDoc
(* moduleSpec - recurses *)
let rec doModule (mspec: ModuleOrNamespace) =
let mtype = mspec.ModuleOrNamespaceType
if mspec.IsModule then modulMember mspec
let vals =
mtype.AllValsAndMembers
|> Seq.toList
|> List.filter (fun x -> not x.IsCompilerGenerated)
|> List.filter (fun x -> x.MemberInfo.IsNone || x.IsExtensionMember)
List.iter doModule mtype.ModuleAndNamespaceDefinitions
List.iter doTycon mtype.ExceptionDefinitions
List.iter doVal vals
List.iter doTycon mtype.TypeDefinitions
doModule generatedCcu.Contents
use os = File.CreateText xmlfile
fprintfn os ("<?xml version=\"1.0\" encoding=\"utf-8\"?>")
fprintfn os ("<doc>")
fprintfn os ("<assembly><name>%s</name></assembly>") assemblyName
fprintfn os ("<members>")
members |> List.iter (fun (id, doc) ->
fprintfn os "<member name=\"%s\">" id
fprintfn os "%s" doc
fprintfn os "</member>")
fprintfn os "</members>"
fprintfn os "</doc>"
let DefaultFSharpBinariesDir = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(FSharpEnvironment.tryCurrentDomain()).Value
let GenerateInterfaceData(tcConfig: TcConfig) =
not tcConfig.standalone && not tcConfig.noSignatureData
let EncodeInterfaceData(tcConfig: TcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild) =
if GenerateInterfaceData tcConfig then
let resource = WriteSignatureData (tcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild)
// The resource gets written to a file for FSharp.Core
let useDataFiles = (tcConfig.useOptimizationDataFile || tcGlobals.compilingFslib) && not isIncrementalBuild
if useDataFiles then
let sigDataFileName = (Filename.chopExtension outfile)+".sigdata"
let bytes = resource.GetBytes()
use fileStream = File.Create(sigDataFileName, bytes.Length)
bytes.CopyTo fileStream
let resources =
[ resource ]
let sigAttr = mkSignatureDataVersionAttr tcGlobals (IL.parseILVersion Internal.Utilities.FSharpEnvironment.FSharpBinaryMetadataFormatRevision)
[sigAttr], resources
else
[], []
let GenerateOptimizationData tcConfig =
GenerateInterfaceData tcConfig
let EncodeOptimizationData(tcGlobals, tcConfig: TcConfig, outfile, exportRemapping, data, isIncrementalBuild) =
if GenerateOptimizationData tcConfig then
let data = map2Of2 (Optimizer.RemapOptimizationInfo tcGlobals exportRemapping) data
// As with the sigdata file, the optdata gets written to a file for FSharp.Core
let useDataFiles = (tcConfig.useOptimizationDataFile || tcGlobals.compilingFslib) && not isIncrementalBuild
if useDataFiles then
let ccu, modulInfo = data
let bytes = TypedTreePickle.pickleObjWithDanglingCcus isIncrementalBuild outfile tcGlobals ccu Optimizer.p_CcuOptimizationInfo modulInfo
let optDataFileName = (Filename.chopExtension outfile)+".optdata"
File.WriteAllBytes(optDataFileName, bytes)
let (ccu, optData) =
if tcConfig.onlyEssentialOptimizationData then
map2Of2 Optimizer.AbstractOptimizationInfoToEssentials data
else
data
[ WriteOptimizationData (tcGlobals, outfile, isIncrementalBuild, ccu, optData) ]
else
[ ]
//----------------------------------------------------------------------------
// .res file format, for encoding the assembly version attribute.
//--------------------------------------------------------------------------
// Helpers for generating binary blobs
module BinaryGenerationUtilities =
// Little-endian encoding of int32
let b0 n = byte (n &&& 0xFF)
let b1 n = byte ((n >>> 8) &&& 0xFF)
let b2 n = byte ((n >>> 16) &&& 0xFF)
let b3 n = byte ((n >>> 24) &&& 0xFF)
let i16 (i: int32) = [| b0 i; b1 i |]
let i32 (i: int32) = [| b0 i; b1 i; b2 i; b3 i |]
// Emit the bytes and pad to a 32-bit alignment
let Padded initialAlignment (v: byte[]) =
[| yield! v
for _ in 1..(4 - (initialAlignment + v.Length) % 4) % 4 do
yield 0x0uy |]
// Generate nodes in a .res file format. These are then linked by Abstract IL using linkNativeResources
module ResFileFormat =
open BinaryGenerationUtilities
let ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, data: byte[]) =
[| yield! i32 data.Length // DWORD ResHdr.dwDataSize
yield! i32 0x00000020 // dwHeaderSize
yield! i32 ((dwTypeID <<< 16) ||| 0x0000FFFF) // dwTypeID, sizeof(DWORD)
yield! i32 ((dwNameID <<< 16) ||| 0x0000FFFF) // dwNameID, sizeof(DWORD)
yield! i32 0x00000000 // DWORD dwDataVersion
yield! i16 wMemFlags // WORD wMemFlags
yield! i16 wLangID // WORD wLangID
yield! i32 0x00000000 // DWORD dwVersion
yield! i32 0x00000000 // DWORD dwCharacteristics
yield! Padded 0 data |]
let ResFileHeader() = ResFileNode(0x0, 0x0, 0x0, 0x0, [| |])
// Generate the VS_VERSION_INFO structure held in a Win32 Version Resource in a PE file
//
// Web reference: http://www.piclist.com/tecHREF/os/win/api/win32/struc/src/str24_5.htm
module VersionResourceFormat =
open BinaryGenerationUtilities
let VersionInfoNode(data: byte[]) =
[| yield! i16 (data.Length + 2) // wLength : int16 // Specifies the length, in bytes, of the VS_VERSION_INFO structure.
yield! data |]
let VersionInfoElement(wType, szKey, valueOpt: byte[] option, children: byte[][], isString) =
// for String structs, wValueLength represents the word count, not the byte count
let wValueLength = (match valueOpt with None -> 0 | Some value -> (if isString then value.Length / 2 else value.Length))
VersionInfoNode
[| yield! i16 wValueLength // wValueLength: int16. Specifies the length, in words, of the Value member.
yield! i16 wType // wType : int16 Specifies the type of data in the version resource.
yield! Padded 2 szKey
match valueOpt with
| None -> yield! []
| Some value -> yield! Padded 0 value
for child in children do
yield! child |]
let Version(version: ILVersionInfo) =
[| // DWORD dwFileVersionMS
// Specifies the most significant 32 bits of the file's binary
// version number. This member is used with dwFileVersionLS to form a 64-bit value used
// for numeric comparisons.
yield! i32 (int32 version.Major <<< 16 ||| int32 version.Minor)
// DWORD dwFileVersionLS
// Specifies the least significant 32 bits of the file's binary
// version number. This member is used with dwFileVersionMS to form a 64-bit value used
// for numeric comparisons.
yield! i32 (int32 version.Build <<< 16 ||| int32 version.Revision)
|]
let String(string, value) =
let wType = 0x1 // Specifies the type of data in the version resource.
let szKey = Bytes.stringAsUnicodeNullTerminated string
VersionInfoElement(wType, szKey, Some (Bytes.stringAsUnicodeNullTerminated value), [| |], true)
let StringTable(language, strings) =
let wType = 0x1 // Specifies the type of data in the version resource.
let szKey = Bytes.stringAsUnicodeNullTerminated language
// Specifies an 8-digit hexadecimal number stored as a Unicode string.
let children =
[| for string in strings do
yield String string |]
VersionInfoElement(wType, szKey, None, children, false)
let StringFileInfo(stringTables: #seq<string * #seq<string * string> >) =
let wType = 0x1 // Specifies the type of data in the version resource.
let szKey = Bytes.stringAsUnicodeNullTerminated "StringFileInfo" // Contains the Unicode string StringFileInfo
// Contains an array of one or more StringTable structures.
let children =
[| for stringTable in stringTables do
yield StringTable stringTable |]
VersionInfoElement(wType, szKey, None, children, false)
let VarFileInfo(vars: #seq<int32 * int32>) =
let wType = 0x1 // Specifies the type of data in the version resource.
let szKey = Bytes.stringAsUnicodeNullTerminated "VarFileInfo" // Contains the Unicode string StringFileInfo
// Contains an array of one or more StringTable structures.
let children =
[| for (lang, codePage) in vars do
let szKey = Bytes.stringAsUnicodeNullTerminated "Translation"
yield VersionInfoElement(0x0, szKey, Some([| yield! i16 lang
yield! i16 codePage |]), [| |], false) |]
VersionInfoElement(wType, szKey, None, children, false)
let VS_FIXEDFILEINFO(fileVersion: ILVersionInfo,
productVersion: ILVersionInfo,
dwFileFlagsMask,
dwFileFlags, dwFileOS,
dwFileType, dwFileSubtype,
lwFileDate: int64) =
let dwStrucVersion = 0x00010000
[| // DWORD dwSignature // Contains the value 0xFEEFO4BD.
yield! i32 0xFEEF04BD
// DWORD dwStrucVersion // Specifies the binary version number of this structure.
yield! i32 dwStrucVersion
// DWORD dwFileVersionMS, dwFileVersionLS // Specifies the most/least significant 32 bits of the file's binary version number.
yield! Version fileVersion
// DWORD dwProductVersionMS, dwProductVersionLS // Specifies the most/least significant 32 bits of the file's binary version number.
yield! Version productVersion
// DWORD dwFileFlagsMask // Contains a bitmask that specifies the valid bits in dwFileFlags.
yield! i32 dwFileFlagsMask
// DWORD dwFileFlags // Contains a bitmask that specifies the Boolean attributes of the file.
yield! i32 dwFileFlags
// VS_FF_DEBUG 0x1L The file contains debugging information or is compiled with debugging features enabled.
// VS_FF_INFOINFERRED The file's version structure was created dynamically; therefore, some of the members
// in this structure may be empty or incorrect. This flag should never be set in a file's
// VS_VERSION_INFO data.
// VS_FF_PATCHED The file has been modified and is not identical to the original shipping file of
// the same version number.
// VS_FF_PRERELEASE The file is a development version, not a commercially released product.
// VS_FF_PRIVATEBUILD The file was not built using standard release procedures. If this flag is
// set, the StringFileInfo structure should contain a PrivateBuild entry.
// VS_FF_SPECIALBUILD The file was built by the original company using standard release procedures
// but is a variation of the normal file of the same version number. If this
// flag is set, the StringFileInfo structure should contain a SpecialBuild entry.
//Specifies the operating system for which this file was designed. This member can be one of the following values: Flag
yield! i32 dwFileOS
//VOS_DOS 0x0001L The file was designed for MS-DOS.
//VOS_NT 0x0004L The file was designed for Windows NT.
//VOS__WINDOWS16 The file was designed for 16-bit Windows.
//VOS__WINDOWS32 The file was designed for the Win32 API.
//VOS_OS216 0x00020000L The file was designed for 16-bit OS/2.
//VOS_OS232 0x00030000L The file was designed for 32-bit OS/2.
//VOS__PM16 The file was designed for 16-bit Presentation Manager.
//VOS__PM32 The file was designed for 32-bit Presentation Manager.
//VOS_UNKNOWN The operating system for which the file was designed is unknown to Windows.
// Specifies the general type of file. This member can be one of the following values:
yield! i32 dwFileType
//VFT_UNKNOWN The file type is unknown to Windows.
//VFT_APP The file contains an application.
//VFT_DLL The file contains a dynamic-link library (DLL).
//VFT_DRV The file contains a device driver. If dwFileType is VFT_DRV, dwFileSubtype contains a more specific description of the driver.
//VFT_FONT The file contains a font. If dwFileType is VFT_FONT, dwFileSubtype contains a more specific description of the font file.
//VFT_VXD The file contains a virtual device.
//VFT_STATIC_LIB The file contains a static-link library.
// Specifies the function of the file. The possible values depend on the value of
// dwFileType. For all values of dwFileType not described in the following list,
// dwFileSubtype is zero. If dwFileType is VFT_DRV, dwFileSubtype can be one of the following values:
yield! i32 dwFileSubtype
//VFT2_UNKNOWN The driver type is unknown by Windows.
//VFT2_DRV_COMM The file contains a communications driver.
//VFT2_DRV_PRINTER The file contains a printer driver.
//VFT2_DRV_KEYBOARD The file contains a keyboard driver.
//VFT2_DRV_LANGUAGE The file contains a language driver.
//VFT2_DRV_DISPLAY The file contains a display driver.
//VFT2_DRV_MOUSE The file contains a mouse driver.
//VFT2_DRV_NETWORK The file contains a network driver.
//VFT2_DRV_SYSTEM The file contains a system driver.
//VFT2_DRV_INSTALLABLE The file contains an installable driver.
//VFT2_DRV_SOUND The file contains a sound driver.
//
//If dwFileType is VFT_FONT, dwFileSubtype can be one of the following values:
//
//VFT2_UNKNOWN The font type is unknown by Windows.
//VFT2_FONT_RASTER The file contains a raster font.
//VFT2_FONT_VECTOR The file contains a vector font.
//VFT2_FONT_TRUETYPE The file contains a TrueType font.
//
//If dwFileType is VFT_VXD, dwFileSubtype contains the virtual device identifier included in the virtual device control block.
// Specifies the most significant 32 bits of the file's 64-bit binary creation date and time stamp.
yield! i32 (int32 (lwFileDate >>> 32))
//Specifies the least significant 32 bits of the file's 64-bit binary creation date and time stamp.
yield! i32 (int32 lwFileDate)
|]
let VS_VERSION_INFO(fixedFileInfo, stringFileInfo, varFileInfo) =
let wType = 0x0
let szKey = Bytes.stringAsUnicodeNullTerminated "VS_VERSION_INFO" // Contains the Unicode string VS_VERSION_INFO
let value = VS_FIXEDFILEINFO (fixedFileInfo)
let children =
[| yield StringFileInfo stringFileInfo
yield VarFileInfo varFileInfo
|]
VersionInfoElement(wType, szKey, Some value, children, false)
let VS_VERSION_INFO_RESOURCE data =
let dwTypeID = 0x0010
let dwNameID = 0x0001
let wMemFlags = 0x0030 // REVIEW: HARDWIRED TO ENGLISH
let wLangID = 0x0
ResFileFormat.ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, VS_VERSION_INFO data)
module ManifestResourceFormat =
let VS_MANIFEST_RESOURCE(data, isLibrary) =
let dwTypeID = 0x0018
let dwNameID = if isLibrary then 0x2 else 0x1
let wMemFlags = 0x0
let wLangID = 0x0
ResFileFormat.ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, data)
//----------------------------------------------------------------------------
// Helpers for finding attributes
//----------------------------------------------------------------------------
module AttributeHelpers =
/// Try to find an attribute that takes a string argument
let TryFindStringAttribute (g: TcGlobals) attrib attribs =
match g.TryFindSysAttrib attrib with
| None -> None
| Some attribRef ->
match TryFindFSharpAttribute g attribRef attribs with
| Some (Attrib(_, _, [ AttribStringArg s ], _, _, _, _)) -> Some (s)
| _ -> None
let TryFindIntAttribute (g: TcGlobals) attrib attribs =
match g.TryFindSysAttrib attrib with
| None -> None
| Some attribRef ->
match TryFindFSharpAttribute g attribRef attribs with
| Some (Attrib(_, _, [ AttribInt32Arg i ], _, _, _, _)) -> Some (i)
| _ -> None
let TryFindBoolAttribute (g: TcGlobals) attrib attribs =
match g.TryFindSysAttrib attrib with
| None -> None
| Some attribRef ->
match TryFindFSharpAttribute g attribRef attribs with
| Some (Attrib(_, _, [ AttribBoolArg p ], _, _, _, _)) -> Some (p)
| _ -> None
let (|ILVersion|_|) (versionString: string) =
try Some (IL.parseILVersion versionString)
with e ->
None
// Try to find an AssemblyVersion attribute
let TryFindVersionAttribute g attrib attribName attribs deterministic =
match TryFindStringAttribute g attrib attribs with
| Some versionString ->
if deterministic && versionString.Contains("*") then
errorR(Error(FSComp.SR.fscAssemblyWildcardAndDeterminism(attribName, versionString), Range.rangeStartup))
try Some (IL.parseILVersion versionString)
with e ->
// Warning will be reported by CheckExpressions.fs
None
| _ -> None
//----------------------------------------------------------------------------
// Building the contents of the finalized IL module
//----------------------------------------------------------------------------
module MainModuleBuilder =
let injectedCompatTypes =
set [ "System.Tuple`1"
"System.Tuple`2"
"System.Tuple`3"
"System.Tuple`4"
"System.Tuple`5"
"System.Tuple`6"
"System.Tuple`7"
"System.Tuple`8"
"System.ITuple"
"System.Tuple"
"System.Collections.IStructuralComparable"
"System.Collections.IStructuralEquatable" ]
let typesForwardedToMscorlib =
set [ "System.AggregateException"
"System.Threading.CancellationTokenRegistration"
"System.Threading.CancellationToken"
"System.Threading.CancellationTokenSource"
"System.Lazy`1"
"System.IObservable`1"
"System.IObserver`1" ]
let typesForwardedToSystemNumerics =
set [ "System.Numerics.BigInteger" ]
let createMscorlibExportList (tcGlobals: TcGlobals) =
// We want to write forwarders out for all injected types except for System.ITuple, which is internal
// Forwarding System.ITuple will cause FxCop failures on 4.0
Set.union (Set.filter (fun t -> t <> "System.ITuple") injectedCompatTypes) typesForwardedToMscorlib |>
Seq.map (fun t -> mkTypeForwarder (tcGlobals.ilg.primaryAssemblyScopeRef) t (mkILNestedExportedTypes List.empty<ILNestedExportedType>) (mkILCustomAttrs List.empty<ILAttribute>) ILTypeDefAccess.Public )
|> Seq.toList
let createSystemNumericsExportList (tcConfig: TcConfig) (tcImports: TcImports) =
let refNumericsDllName =
if (tcConfig.primaryAssembly.Name = "mscorlib") then "System.Numerics"
else "System.Runtime.Numerics"
let numericsAssemblyRef =
match tcImports.GetImportedAssemblies() |> List.tryFind<ImportedAssembly>(fun a -> a.FSharpViewOfMetadata.AssemblyName = refNumericsDllName) with
| Some asm ->
match asm.ILScopeRef with
| ILScopeRef.Assembly aref -> Some aref
| _ -> None
| None -> None
match numericsAssemblyRef with
| Some aref ->
let systemNumericsAssemblyRef = ILAssemblyRef.Create(refNumericsDllName, aref.Hash, aref.PublicKey, aref.Retargetable, aref.Version, aref.Locale)
typesForwardedToSystemNumerics |>
Seq.map (fun t ->
{ ScopeRef = ILScopeRef.Assembly systemNumericsAssemblyRef
Name = t
Attributes = enum<TypeAttributes>(0x00200000) ||| TypeAttributes.Public
Nested = mkILNestedExportedTypes []
CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs
MetadataIndex = NoMetadataIdx }) |>
Seq.toList
| None -> []
let fileVersion findStringAttr (assemblyVersion: ILVersionInfo) =
let attrName = "System.Reflection.AssemblyFileVersionAttribute"
match findStringAttr attrName with
| None -> assemblyVersion
| Some (AttributeHelpers.ILVersion v) -> v
| Some _ ->
// Warning will be reported by CheckExpressions.fs
assemblyVersion
let productVersion findStringAttr (fileVersion: ILVersionInfo) =
let attrName = "System.Reflection.AssemblyInformationalVersionAttribute"
let toDotted (version: ILVersionInfo) = sprintf "%d.%d.%d.%d" version.Major version.Minor version.Build version.Revision
match findStringAttr attrName with
| None | Some "" -> fileVersion |> toDotted
| Some (AttributeHelpers.ILVersion v) -> v |> toDotted
| Some v ->
// Warning will be reported by CheckExpressions.fs
v
let productVersionToILVersionInfo (version: string) : ILVersionInfo =
let parseOrZero i (v:string) =
let v =
// When i = 3 then this is the 4th part of the version. The last part of the version can be trailed by any characters so we trim them off
if i <> 3 then
v
else
((false, ""), v)
||> Seq.fold(fun (finished, v) c ->
match finished with
| false when Char.IsDigit(c) -> false, v + c.ToString()
| _ -> true, v)
|> snd
match System.UInt16.TryParse v with
| (true, i) -> i
| (false, _) -> 0us
let validParts =
version.Split('.')
|> Array.mapi(fun i v -> parseOrZero i v)
|> Seq.toList
match validParts @ [0us; 0us; 0us; 0us] with
| major :: minor :: build :: rev :: _ -> ILVersionInfo(major, minor, build, rev)
| x -> failwithf "error converting product version '%s' to binary, tried '%A' " version x
let CreateMainModule
(ctok, tcConfig: TcConfig, tcGlobals, tcImports: TcImports,
pdbfile, assemblyName, outfile, topAttrs,
(iattrs, intfDataResources), optDataResources,
codegenResults, assemVerFromAttrib, metadataVersion, secDecls) =
RequireCompilationThread ctok
let ilTypeDefs =
//let topTypeDef = mkILTypeDefForGlobalFunctions tcGlobals.ilg (mkILMethods [], emptyILFields)
mkILTypeDefs codegenResults.ilTypeDefs
let mainModule =
let hashAlg = AttributeHelpers.TryFindIntAttribute tcGlobals "System.Reflection.AssemblyAlgorithmIdAttribute" topAttrs.assemblyAttrs
let locale = AttributeHelpers.TryFindStringAttribute tcGlobals "System.Reflection.AssemblyCultureAttribute" topAttrs.assemblyAttrs
let flags = match AttributeHelpers.TryFindIntAttribute tcGlobals "System.Reflection.AssemblyFlagsAttribute" topAttrs.assemblyAttrs with | Some f -> f | _ -> 0x0
// You're only allowed to set a locale if the assembly is a library
if (locale <> None && locale.Value <> "") && tcConfig.target <> CompilerTarget.Dll then
error(Error(FSComp.SR.fscAssemblyCultureAttributeError(), rangeCmdArgs))
// Add the type forwarders to any .NET DLL post-.NET-2.0, to give binary compatibility
let exportedTypesList =
if tcConfig.compilingFslib then
List.append (createMscorlibExportList tcGlobals) (createSystemNumericsExportList tcConfig tcImports)
else
[]
let ilModuleName = GetGeneratedILModuleName tcConfig.target assemblyName
let isDLL = (tcConfig.target = CompilerTarget.Dll || tcConfig.target = CompilerTarget.Module)
mkILSimpleModule assemblyName ilModuleName isDLL tcConfig.subsystemVersion tcConfig.useHighEntropyVA ilTypeDefs hashAlg locale flags (mkILExportedTypes exportedTypesList) metadataVersion
let disableJitOptimizations = not (tcConfig.optSettings.jitOpt())
let tcVersion = tcConfig.version.GetVersionInfo(tcConfig.implicitIncludeDir)
let reflectedDefinitionAttrs, reflectedDefinitionResources =
codegenResults.quotationResourceInfo
|> List.map (fun (referencedTypeDefs, reflectedDefinitionBytes) ->
let reflectedDefinitionResourceName = QuotationPickler.SerializedReflectedDefinitionsResourceNameBase+"-"+assemblyName+"-"+string(newUnique())+"-"+string(hash reflectedDefinitionBytes)
let reflectedDefinitionAttrs =
let qf = QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat tcGlobals
if qf.SupportsDeserializeEx then
[ mkCompilationMappingAttrForQuotationResource tcGlobals (reflectedDefinitionResourceName, referencedTypeDefs) ]
else
[ ]
let reflectedDefinitionResource =
{ Name=reflectedDefinitionResourceName
Location = ILResourceLocation.Local(ByteStorage.FromByteArray(reflectedDefinitionBytes))
Access= ILResourceAccess.Public
CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs
MetadataIndex = NoMetadataIdx }
reflectedDefinitionAttrs, reflectedDefinitionResource)
|> List.unzip
|> (fun (attrs, resource) -> List.concat attrs, resource)
let manifestAttrs =
mkILCustomAttrs
[ if not tcConfig.internConstantStrings then
yield mkILCustomAttribute tcGlobals.ilg
(tcGlobals.FindSysILTypeRef "System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
[tcGlobals.ilg.typ_Int32], [ILAttribElem.Int32( 8)], [])
yield! iattrs
yield! codegenResults.ilAssemAttrs
if Option.isSome pdbfile then
yield (tcGlobals.mkDebuggableAttributeV2 (tcConfig.jitTracking, tcConfig.ignoreSymbolStoreSequencePoints, disableJitOptimizations, false (* enableEnC *) ))
yield! reflectedDefinitionAttrs ]
// Make the manifest of the assembly
let manifest =
if tcConfig.target = CompilerTarget.Module then None else
let man = mainModule.ManifestOfAssembly
let ver =
match assemVerFromAttrib with
| None -> tcVersion
| Some v -> v
Some { man with Version= Some ver
CustomAttrsStored = storeILCustomAttrs manifestAttrs
DisableJitOptimizations=disableJitOptimizations
JitTracking= tcConfig.jitTracking
IgnoreSymbolStoreSequencePoints = tcConfig.ignoreSymbolStoreSequencePoints
SecurityDeclsStored=storeILSecurityDecls secDecls }
let resources =
mkILResources
[ for file in tcConfig.embedResources do
let name, bytes, pub =
let file, name, pub = TcConfigBuilder.SplitCommandLineResourceInfo file
let file = tcConfig.ResolveSourceFile(rangeStartup, file, tcConfig.implicitIncludeDir)
let bytes = FileSystem.ReadAllBytesShim file
name, bytes, pub
yield { Name=name
Location=ILResourceLocation.Local(ByteStorage.FromByteArray(bytes))
Access=pub
CustomAttrsStored=storeILCustomAttrs emptyILCustomAttrs
MetadataIndex = NoMetadataIdx }
yield! reflectedDefinitionResources
yield! intfDataResources
yield! optDataResources
for ri in tcConfig.linkResources do
let file, name, pub = TcConfigBuilder.SplitCommandLineResourceInfo ri
yield { Name=name
Location=ILResourceLocation.File(ILModuleRef.Create(name=file, hasMetadata=false, hash=Some (sha1HashBytes (FileSystem.ReadAllBytesShim file))), 0)
Access=pub
CustomAttrsStored=storeILCustomAttrs emptyILCustomAttrs
MetadataIndex = NoMetadataIdx } ]
let assemblyVersion =
match tcConfig.version with
| VersionNone -> assemVerFromAttrib
| _ -> Some tcVersion
let findAttribute name =
AttributeHelpers.TryFindStringAttribute tcGlobals name topAttrs.assemblyAttrs
//NOTE: the culture string can be turned into a number using this:
// sprintf "%04x" (CultureInfo.GetCultureInfo("en").KeyboardLayoutId )
let assemblyVersionResources findAttr assemblyVersion =
match assemblyVersion with
| None -> []
| Some assemblyVersion ->
let FindAttribute key attrib =
match findAttr attrib with
| Some text -> [(key, text)]
| _ -> []
let fileVersionInfo = fileVersion findAttr assemblyVersion
let productVersionString = productVersion findAttr fileVersionInfo