-
Notifications
You must be signed in to change notification settings - Fork 793
/
Copy pathfsc.fs
2070 lines (1731 loc) · 115 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 Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. 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 Microsoft.FSharp.Compiler.Driver
open System
open System.Diagnostics
open System.Globalization
open System.IO
open System.Threading
open System.Reflection
open System.Collections.Generic
open System.Runtime.CompilerServices
open System.Text
open Internal.Utilities
open Internal.Utilities.Collections
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.AbstractIL
open Microsoft.FSharp.Compiler.AbstractIL.IL
open Microsoft.FSharp.Compiler.AbstractIL.Internal
open Microsoft.FSharp.Compiler.AbstractIL.Extensions.ILX
open Microsoft.FSharp.Compiler.AbstractIL.Internal.Library
open Microsoft.FSharp.Compiler.AbstractIL.Diagnostics
open Microsoft.FSharp.Compiler.AbstractIL.IL
#if NO_COMPILER_BACKEND
#else
open Microsoft.FSharp.Compiler.IlxGen
#endif
open Microsoft.FSharp.Compiler.Ast
open Microsoft.FSharp.Compiler.ErrorLogger
open Microsoft.FSharp.Compiler.Range
open Microsoft.FSharp.Compiler.TypeChecker
open Microsoft.FSharp.Compiler.Infos
open Microsoft.FSharp.Compiler.Infos.AccessibilityLogic
open Microsoft.FSharp.Compiler.Infos.AttributeChecking
open Microsoft.FSharp.Compiler.Tast
open Microsoft.FSharp.Compiler.Tastops
open Microsoft.FSharp.Compiler.Optimizer
open Microsoft.FSharp.Compiler.TcGlobals
open Microsoft.FSharp.Compiler.CompileOps
open Microsoft.FSharp.Compiler.Lib
open Microsoft.FSharp.Compiler.CompileOptions
open Microsoft.FSharp.Compiler.DiagnosticMessage
#if EXTENSIONTYPING
open Microsoft.FSharp.Compiler.ExtensionTyping
#endif
//----------------------------------------------------------------------------
// No SQM logging support
//----------------------------------------------------------------------------
#if SQM_SUPPORT
open Microsoft.FSharp.Compiler.SqmLogger
#else
let SqmLoggerWithConfigBuilder _tcConfigB _errorNumbers _warningNumbers = ()
let SqmLoggerWithConfig _tcConfig _errorNumbers _warningNumbers = ()
#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
//----------------------------------------------------------------------------
[<AbstractClass>]
type ErrorLoggerThatQuitsAfterMaxErrors(tcConfigB: TcConfigBuilder, exiter: Exiter, caption) =
inherit ErrorLogger(caption)
let mutable errors = 0
let mutable errorNumbers = []
let mutable warningNumbers = []
abstract HandleIssue : tcConfigB : TcConfigBuilder * error : PhasedError * isWarning : bool -> unit
abstract HandleTooManyErrors : text : string -> unit
override x.ErrorCount = errors
override x.ErrorSinkImpl(err) =
if errors >= tcConfigB.maxErrors then
x.HandleTooManyErrors(FSComp.SR.fscTooManyErrors())
SqmLoggerWithConfigBuilder tcConfigB errorNumbers warningNumbers
exiter.Exit 1
x.HandleIssue(tcConfigB, err, false)
errors <- errors + 1
errorNumbers <- (GetErrorNumber err) :: errorNumbers
match err.Exception with
| InternalError _
| Failure _
| :? KeyNotFoundException ->
match tcConfigB.simulateException with
| Some _ -> () // Don't show an assert for simulateException case so that unittests can run without an assert dialog.
| None -> Debug.Assert(false,sprintf "Bug seen in compiler: %s" (err.ToString()))
| _ ->
()
override x.WarnSinkImpl(err) =
if ReportWarningAsError (tcConfigB.globalWarnLevel, tcConfigB.specificWarnOff, tcConfigB.specificWarnOn, tcConfigB.specificWarnAsError, tcConfigB.specificWarnAsWarn, tcConfigB.globalWarnAsError) err then
x.ErrorSink(err)
elif ReportWarning (tcConfigB.globalWarnLevel, tcConfigB.specificWarnOff, tcConfigB.specificWarnOn) err then
x.HandleIssue(tcConfigB, err, true)
warningNumbers <- (GetErrorNumber err) :: warningNumbers
override x.WarningNumbers = warningNumbers
override x.ErrorNumbers = errorNumbers
/// Create an error logger that counts and prints errors
let ConsoleErrorLoggerThatQuitsAfterMaxErrors (tcConfigB:TcConfigBuilder, exiter : Exiter) : ErrorLogger =
{ new ErrorLoggerThatQuitsAfterMaxErrors(tcConfigB, exiter, "ConsoleErrorLoggerThatQuitsAfterMaxErrors") with
member this.HandleTooManyErrors(text : string) =
DoWithErrorColor true (fun () -> Printf.eprintfn "%s" text)
member this.HandleIssue(tcConfigB, err, isWarning) =
DoWithErrorColor isWarning (fun () ->
(writeViaBufferWithEnvironmentNewLines stderr (OutputErrorOrWarning (tcConfigB.implicitIncludeDir,tcConfigB.showFullPaths,tcConfigB.flatErrors,tcConfigB.errorStyle,isWarning)) err;
stderr.WriteLine())
)
} :> _
/// This error logger delays the messages it recieves. At the end, call ForwardDelayedErrorsAndWarnings
/// to send the held messages.
type DelayAndForwardErrorLogger(exiter: Exiter, errorLoggerProvider: ErrorLoggerProvider) =
inherit ErrorLogger("DelayAndForwardErrorLogger")
let delayed = new ResizeArray<_>()
let mutable errors = 0
override x.ErrorSinkImpl(e) =
errors <- errors + 1
delayed.Add (e,true)
override x.ErrorCount = delayed |> Seq.filter snd |> Seq.length
override x.WarnSinkImpl(e) = delayed.Add(e,false)
member x.ForwardDelayedErrorsAndWarnings(errorLogger:ErrorLogger) =
// Eagerly grab all the errors and warnings from the mutable collection
let errors = delayed |> Seq.toList
// Now report them
for (e,isError) in errors do
if isError then errorLogger.ErrorSink(e) else errorLogger.WarnSink(e)
// Clear errors just reported. Keep errors count.
delayed.Clear()
member x.ForwardDelayedErrorsAndWarnings(tcConfigB:TcConfigBuilder) =
let errorLogger = errorLoggerProvider.CreateErrorLoggerThatQuitsAfterMaxErrors(tcConfigB, exiter)
x.ForwardDelayedErrorsAndWarnings(errorLogger)
member x.FullErrorCount = errors
override x.WarningNumbers = delayed |> Seq.filter (snd >> not) |> Seq.map (fst >> GetErrorNumber) |> Seq.toList
override x.ErrorNumbers = delayed |> Seq.filter snd |> Seq.map (fst >> GetErrorNumber) |> Seq.toList
and [<AbstractClass>]
ErrorLoggerProvider() =
member this.CreateDelayAndForwardLogger(exiter) = DelayAndForwardErrorLogger(exiter, this)
abstract CreateErrorLoggerThatQuitsAfterMaxErrors : tcConfigBuilder : TcConfigBuilder * exiter : Exiter -> ErrorLogger
let AbortOnError (errorLogger:ErrorLogger, _tcConfig:TcConfig, exiter : Exiter) =
if errorLogger.ErrorCount > 0 then
SqmLoggerWithConfig _tcConfig errorLogger.ErrorNumbers errorLogger.WarningNumbers
exiter.Exit 1
type DefaultLoggerProvider() =
inherit ErrorLoggerProvider()
override this.CreateErrorLoggerThatQuitsAfterMaxErrors(tcConfigBuilder, exiter) = ConsoleErrorLoggerThatQuitsAfterMaxErrors(tcConfigBuilder, exiter)
//----------------------------------------------------------------------------
// Cleaning up
/// 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 _ -> ()
//----------------------------------------------------------------------------
/// Type checking a set of inputs
let TypeCheck (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 ((fun () -> errorLogger.ErrorCount > 0),tcConfig,tcImports,tcGlobals,None,tcInitialState,inputs)
with e ->
errorRecovery e rangeStartup
SqmLoggerWithConfig tcConfig errorLogger.ErrorNumbers errorLogger.WarningNumbers
exiter.Exit 1
/// Check for .fsx and, if present, compute the load closure for of #loaded files.
let AdjustForScriptCompile(tcConfigB:TcConfigBuilder,commandLineSourceFiles,lexResourceManager) =
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 allSources = ref []
let tcConfig = TcConfig.Create(tcConfigB,validate=false)
let AddIfNotPresent(filename:string) =
if not(!allSources |> List.mem filename) then
allSources := filename::!allSources
let AppendClosureInformation(filename) =
if IsScript filename then
let closure = LoadClosure.ComputeClosureOfSourceFiles(tcConfig,[filename,rangeStartup],CodeContext.Compilation,lexResourceManager=lexResourceManager,useDefaultScriptingReferences=false)
let references = closure.References |> List.map snd |> List.concat |> List.map (fun r->r.originalReference) |> List.filter (fun r->r.Range<>range0)
references |> List.iter (fun r-> tcConfigB.AddReferencedAssemblyByPath(r.Range,r.Text))
closure.NoWarns |> List.map(fun (n,ms)->ms|>List.map(fun m->m,n)) |> List.concat |> List.iter tcConfigB.TurnWarningOff
closure.SourceFiles |> List.map fst |> List.iter AddIfNotPresent
closure.RootWarnings |> List.iter warnSink
closure.RootErrors |> List.iter errorSink
else AddIfNotPresent(filename)
// Find closure of .fsx files.
commandLineSourceFiles |> List.iter AppendClosureInformation
List.rev !allSources
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This code has logic for a prefix of the compile that is also used by the project system to do the front-end
// logic that starts at command-line arguments and gets as far as importing all references (used for deciding
// to pop up the type provider security dialog).
//
// The project system needs to be able to somehow crack open assemblies to look for type providers in order to pop up the security dialog when necessary when a user does 'Build'.
// Rather than have the PS re-code that logic, it re-uses the existing code in the very front end of the compiler that parses the command-line and imports the referenced assemblies.
// This code used to be in fsc.exe. The PS only references FSharp.LanguageService.Compiler, so this code moved from fsc.exe to FS.C.S.dll so that the PS can re-use it.
// A great deal of the logic of this function is repeated in fsi.fs, so maybe should refactor fsi.fs to call into this as well.
let GetTcImportsFromCommandLine
(displayPSTypeProviderSecurityDialogBlockingUI : (string->unit) option,
argv : string[],
defaultFSharpBinariesDir : string,
directoryBuildingFrom : string,
lcidFromCodePage : int option,
setProcessThreadLocals : TcConfigBuilder -> unit,
displayBannerIfNeeded : TcConfigBuilder -> unit,
optimizeForMemory : bool,
exiter : Exiter,
errorLoggerProvider : ErrorLoggerProvider,
disposables : DisposablesTracker) =
let tcConfigB = TcConfigBuilder.CreateNew(defaultFSharpBinariesDir, optimizeForMemory, directoryBuildingFrom, isInteractive=false, isInvalidationSupported=false)
// Preset: --optimize+ -g --tailcalls+ (see 4505)
SetOptimizeSwitch tcConfigB OptionSwitch.On
SetDebugSwitch tcConfigB None OptionSwitch.Off
SetTailcallSwitch tcConfigB OptionSwitch.On
// Now install a delayed logger to hold all errors from flags until after all flags have been parsed (for example, --vserrors)
let delayForFlagsLogger = errorLoggerProvider.CreateDelayAndForwardLogger(exiter)
let _unwindEL_1 = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayForFlagsLogger)
// Share intern'd strings across all lexing/parsing
let lexResourceManager = new Lexhelp.LexResourceManager()
// process command line, flags and collect filenames
let sourceFiles =
// The ParseCompilerOptions function calls imperative function to process "real" args
// Rather than start processing, just collect names, then process them.
try
let inputFilesRef = ref ([] : string list)
let collect name =
let lower = String.lowercase name
if List.exists (Filename.checkSuffix lower) [".resx"] then
warning(Error(FSComp.SR.fscResxSourceFileDeprecated name,rangeStartup))
tcConfigB.AddEmbeddedResource name
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))
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)
// Get DLL references
let dllFiles,sourceFiles = List.partition Filename.isDll inputFiles
match dllFiles with
| [] -> ()
| h::_ -> errorR (Error(FSComp.SR.fscReferenceOnCommandLine(h),rangeStartup))
dllFiles |> List.iter (fun f->tcConfigB.AddReferencedAssemblyByPath(rangeStartup,f))
let sourceFiles = AdjustForScriptCompile(tcConfigB,sourceFiles,lexResourceManager)
sourceFiles
with e ->
errorRecovery e rangeStartup
SqmLoggerWithConfigBuilder tcConfigB delayForFlagsLogger.ErrorNumbers delayForFlagsLogger.WarningNumbers
delayForFlagsLogger.ForwardDelayedErrorsAndWarnings(tcConfigB)
exiter.Exit 1
tcConfigB.sqmNumOfSourceFiles <- sourceFiles.Length
tcConfigB.conditionalCompilationDefines <- "COMPILED" :: tcConfigB.conditionalCompilationDefines
displayBannerIfNeeded tcConfigB
// Create tcGlobals and frameworkTcImports
let outfile,pdbfile,assemblyName =
try
tcConfigB.DecideNames sourceFiles
with e ->
errorRecovery e rangeStartup
SqmLoggerWithConfigBuilder tcConfigB delayForFlagsLogger.ErrorNumbers delayForFlagsLogger.WarningNumbers
delayForFlagsLogger.ForwardDelayedErrorsAndWarnings(tcConfigB)
exiter.Exit 1
// DecideNames may give "no inputs" error. Abort on error at this point. bug://3911
if not tcConfigB.continueAfterParseFailure && delayForFlagsLogger.FullErrorCount > 0 then
SqmLoggerWithConfigBuilder tcConfigB delayForFlagsLogger.ErrorNumbers delayForFlagsLogger.WarningNumbers
delayForFlagsLogger.ForwardDelayedErrorsAndWarnings(tcConfigB)
exiter.Exit 1
// If there's a problem building TcConfig, abort
let tcConfig =
try
TcConfig.Create(tcConfigB,validate=false)
with e ->
SqmLoggerWithConfigBuilder tcConfigB delayForFlagsLogger.ErrorNumbers delayForFlagsLogger.WarningNumbers
delayForFlagsLogger.ForwardDelayedErrorsAndWarnings(tcConfigB)
exiter.Exit 1
let errorLogger = errorLoggerProvider.CreateErrorLoggerThatQuitsAfterMaxErrors(tcConfigB, exiter)
// Install the global error logger and never remove it. This logger does have all command-line flags considered.
let _unwindEL_2 = PushErrorLoggerPhaseUntilUnwind (fun _ -> errorLogger)
// Forward all errors from flags
delayForFlagsLogger.ForwardDelayedErrorsAndWarnings(errorLogger)
// step - decideNames
if not tcConfigB.continueAfterParseFailure then
AbortOnError(errorLogger, tcConfig, exiter)
let tcGlobals,tcImports,frameworkTcImports,generatedCcu,typedAssembly,topAttrs,tcConfig =
ReportTime tcConfig "Import mscorlib"
if tcConfig.useIncrementalBuilder then
ReportTime tcConfig "Incremental Parse and Typecheck"
let builder =
new IncrementalFSharpBuild.IncrementalBuilder(tcConfig, directoryBuildingFrom, assemblyName, NiceNameGenerator(), lexResourceManager, sourceFiles,
ensureReactive=false,
errorLogger=errorLogger,
keepGeneratedTypedAssembly=true)
let tcState,topAttribs,typedAssembly,_tcEnv,tcImports,tcGlobals,tcConfig = builder.TypeCheck()
tcGlobals,tcImports,tcImports,tcState.Ccu,typedAssembly,topAttribs,tcConfig
else
ReportTime tcConfig "Import mscorlib and FSharp.Core.dll"
let foundationalTcConfigP = TcConfigProvider.Constant(tcConfig)
let sysRes,otherRes,knownUnresolved = TcAssemblyResolutions.SplitNonFoundationalResolutions(tcConfig)
let tcGlobals,frameworkTcImports = TcImports.BuildFrameworkTcImports (foundationalTcConfigP, sysRes, otherRes)
// register framework tcImports to be disposed in future
disposables.Register frameworkTcImports
// step - parse sourceFiles
ReportTime tcConfig "Parse inputs"
use unwindParsePhase = PushThreadBuildPhaseUntilUnwind (BuildPhase.Parse)
let inputs =
try
sourceFiles
|> tcConfig.ComputeCanContainEntryPoint
|> List.zip sourceFiles
// PERF: consider making this parallel, once uses of global state relevant to parsing are cleaned up
|> List.choose (fun (filename:string,isLastCompiland:bool) ->
let pathOfMetaCommandSource = Path.GetDirectoryName(filename)
match ParseOneInputFile(tcConfig,lexResourceManager,["COMPILED"],filename,isLastCompiland,errorLogger,(*retryLocked*)false) with
| Some(input)->Some(input,pathOfMetaCommandSource)
| None -> None
)
with e ->
errorRecoveryNoRange e
SqmLoggerWithConfig tcConfig errorLogger.ErrorNumbers errorLogger.WarningNumbers
exiter.Exit 1
if tcConfig.parseOnly then exiter.Exit 0
if not tcConfig.continueAfterParseFailure then
AbortOnError(errorLogger, tcConfig, exiter)
if tcConfig.printAst then
inputs |> List.iter (fun (input,_filename) -> printf "AST:\n"; printfn "%+A" input; printf "\n")
let tcConfig = (tcConfig,inputs) ||> List.fold ApplyMetaCommandsFromInputToTcConfig
let tcConfigP = TcConfigProvider.Constant(tcConfig)
ReportTime tcConfig "Import non-system references"
let tcGlobals,tcImports =
let tcImports = TcImports.BuildNonFrameworkTcImports(displayPSTypeProviderSecurityDialogBlockingUI,tcConfigP,tcGlobals,frameworkTcImports,otherRes,knownUnresolved)
tcGlobals,tcImports
// register tcImports to be disposed in future
disposables.Register tcImports
if not tcConfig.continueAfterParseFailure then
AbortOnError(errorLogger, tcConfig, exiter)
if tcConfig.importAllReferencesOnly then exiter.Exit 0
ReportTime tcConfig "Typecheck"
use unwindParsePhase = PushThreadBuildPhaseUntilUnwind (BuildPhase.TypeCheck)
let tcEnv0 = GetInitialTcEnv (Some assemblyName, rangeStartup, tcConfig, tcImports, tcGlobals)
// typecheck
let inputs : ParsedInput list = inputs |> List.map fst
let tcState,topAttrs,typedAssembly,_tcEnvAtEnd =
TypeCheck(tcConfig,tcImports,tcGlobals,errorLogger,assemblyName,NiceNameGenerator(),tcEnv0,inputs,exiter)
let generatedCcu = tcState.Ccu
AbortOnError(errorLogger, tcConfig, exiter)
ReportTime tcConfig "Typechecked"
(tcGlobals,tcImports,frameworkTcImports,generatedCcu,typedAssembly,topAttrs,tcConfig)
tcGlobals,tcImports,frameworkTcImports,generatedCcu,typedAssembly,topAttrs,tcConfig,outfile,pdbfile,assemblyName,errorLogger
// only called from the project system, as a way to run the front end of the compiler far enough to determine if we need to pop up the dialog (and do so if necessary)
let ProcessCommandLineArgsAndImportAssemblies
(displayPSTypeProviderSecurityDialogBlockingUI : (string -> unit),
argv : string[],
defaultFSharpBinariesDir : string,
directoryBuildingFrom : string,
exiter : Exiter) =
use disposables = new DisposablesTracker() // ensure that any resources that can be allocated in GetTcImportsFromCommandLine will be correctly disposed
// We don't care about the result, we just called 'GetTcImportsFromCommandLine' to have the effect of popping up the dialog if the TP is unknown
GetTcImportsFromCommandLine
(Some displayPSTypeProviderSecurityDialogBlockingUI,
argv,
defaultFSharpBinariesDir,
directoryBuildingFrom,
None,
(fun _ -> ()), // setProcessThreadLocals
(fun tcConfigB ->
// (kind of abusing this lambda for an unintended purpose, but this is a convenient and correctly-timed place to poke the tcConfigB)
tcConfigB.importAllReferencesOnly <- true // stop after importing assemblies (do not typecheck, we don't need typechecking)
// for flags below, see IncrementalBuilder.fs:CreateBackgroundBuilderForProjectOptions, as there are many similarities, as these are the two places that we create this from VS code-paths
tcConfigB.openBinariesInMemory <- true // uses more memory but means we don't take read-exclusions on the DLLs we reference (important for VS code path)
tcConfigB.openDebugInformationForLaterStaticLinking <- false // Never open PDB files for the PS, even if --standalone is specified
if tcConfigB.framework then
Debug.Assert(false, "Project system requires --noframework flag")
tcConfigB.framework<-false),
true, // optimizeForMemory - want small memory footprint in VS
exiter,
DefaultLoggerProvider(), // this function always use default set of loggers
disposables)
|> ignore
#if NO_COMPILER_BACKEND
#else
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Code from here on down is just used by fsc.exe
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
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, typedAssembly) =
let (TAssembly declaredImpls) = typedAssembly
/// 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
writeViaBufferWithEnvironmentNewLines os (fun os s -> Printf.bprintf os "%s\n\n" s)
(NicePrint.layoutInferredSigOfModuleExpr true denv infoReader AccessibleFromSomewhere range0 mexpr |> Layout.squashTo 80 |> Layout.showL)
if tcConfig.printSignatureFile <> "" then os.Close()
module XmlDocWriter =
let getDoc xmlDoc =
match XmlDoc.Process xmlDoc with
| XmlDoc [| |] -> ""
| XmlDoc strs -> strs |> Array.toList |> String.concat Environment.NewLine
let hasDoc xmlDoc =
// No need to process the xml doc - just need to know if there's anything there
match xmlDoc with
| XmlDoc [| |] -> false
| _ -> true
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 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.UnionCasesAsList do
if (hasDoc uc.XmlDoc) then uc.XmlDocSig <- XmlDocSigOfUnionCase [ptext; tc.CompiledName; uc.Id.idText]
for rf in tc.AllFieldsAsList 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 members = ref []
let addMember id xmlDoc =
if hasDoc xmlDoc then
let doc = getDoc xmlDoc
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.UnionCasesAsList do
doUnionCase uc
for rf in tc.AllFieldsAsList 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>";
//----------------------------------------------------------------------------
// cmd line - option state
//----------------------------------------------------------------------------
let defaultFSharpBinariesDir =
let exeName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName)
Filename.directoryName exeName
let outpath outfile extn =
String.concat "." (["out"; Filename.chopExtension (Filename.fileNameOfPath outfile); extn])
let GenerateInterfaceData(tcConfig:TcConfig) =
(* (tcConfig.target = Dll || tcConfig.target = Module) && *)
not tcConfig.standalone && not tcConfig.noSignatureData
type ILResource with
/// Read the bytes from a resource local to an assembly
member r.Bytes =
match r.Location with
| ILResourceLocation.Local b -> b()
| _-> error(InternalError("Bytes",rangeStartup))
let EncodeInterfaceData(tcConfig:TcConfig,tcGlobals,exportRemapping,_errorLogger:ErrorLogger,generatedCcu,outfile,exiter:Exiter) =
try
if GenerateInterfaceData(tcConfig) then
if verbose then dprintfn "Generating interface data attribute...";
let resource = WriteSignatureData (tcConfig,tcGlobals,exportRemapping,generatedCcu,outfile)
if verbose then dprintf "Generated interface data attribute!\n";
// REVIEW: need a better test for this
let outFileNoExtension = Filename.chopExtension outfile
let isCompilerServiceDll = outFileNoExtension.Contains("FSharp.LanguageService.Compiler")
if tcConfig.useOptimizationDataFile || tcGlobals.compilingFslib || isCompilerServiceDll then
let sigDataFileName = (Filename.chopExtension outfile)+".sigdata"
File.WriteAllBytes(sigDataFileName,resource.Bytes);
let sigAttr = mkSignatureDataVersionAttr tcGlobals (IL.parseILVersion Internal.Utilities.FSharpEnvironment.FSharpBinaryMetadataFormatRevision)
// The resource gets written to a file for FSharp.Core
let resources =
[ if not tcGlobals.compilingFslib && not isCompilerServiceDll then
yield resource ]
[sigAttr], resources
else
[],[]
with e ->
errorRecoveryNoRange e
SqmLoggerWithConfig tcConfig _errorLogger.ErrorNumbers _errorLogger.WarningNumbers
exiter.Exit 1
//----------------------------------------------------------------------------
// EncodeOptimizationData
//----------------------------------------------------------------------------
let GenerateOptimizationData(tcConfig) =
(* (tcConfig.target =Dll || tcConfig.target = Module) && *)
GenerateInterfaceData(tcConfig)
let EncodeOptimizationData(tcGlobals,tcConfig,outfile,exportRemapping,data) =
if GenerateOptimizationData tcConfig then
let data = map2Of2 (Optimizer.RemapOptimizationInfo tcGlobals exportRemapping) data
if verbose then dprintn "Generating optimization data attribute...";
// REVIEW: need a better test for this
let outFileNoExtension = Filename.chopExtension outfile
let isCompilerServiceDll = outFileNoExtension.Contains("FSharp.LanguageService.Compiler")
if tcConfig.useOptimizationDataFile || tcGlobals.compilingFslib || isCompilerServiceDll then
let ccu,modulInfo = data
let bytes = TastPickle.pickleObjWithDanglingCcus outfile tcGlobals ccu Optimizer.p_CcuOptimizationInfo modulInfo
let optDataFileName = (Filename.chopExtension outfile)+".optdata"
File.WriteAllBytes(optDataFileName,bytes);
// As with the sigdata file, the optdata gets written to a file for FSharp.Core, FSharp.Compiler.Silverlight and FSharp.LanguageService.Compiler
if tcGlobals.compilingFslib || isCompilerServiceDll then
[]
else
let (ccu, optData) =
if tcConfig.onlyEssentialOptimizationData || tcConfig.useOptimizationDataFile
then map2Of2 Optimizer.AbstractOptimizationInfoToEssentials data
else data
[ WriteOptimizationData (tcGlobals, outfile, 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 the
// linkNativeResources function, which invokes the cvtres.exe utility
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. This length does not include any padding that aligns any subsequent version resource data on a 32-bit boundary.
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. This value is zero if there is no Value member associated with the current version structure.
yield! i16 wType // wType : int16; Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
yield! Padded 2 szKey
match valueOpt with
| None -> yield! []
| Some value -> yield! Padded 0 value
for child in children do
yield! child |]
let Version((v1,v2,v3,v4):ILVersionInfo) =
[| yield! i32 (int32 v1 <<< 16 ||| int32 v2) // 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 v3 <<< 16 ||| int32 v4) // 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.
|]
let String(string,value) =
let wType = 0x1 // Specifies the type of data in the version resource. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
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. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
let szKey = Bytes.stringAsUnicodeNullTerminated language
// Specifies an 8-digit hexadecimal number stored as a Unicode string. The four most significant digits represent the language identifier. The four least significant digits represent the code page for which the data is formatted.
// Each Microsoft Standard Language identifier contains two parts: the low-order 10 bits specify the major language, and the high-order 6 bits specify the sublanguage. For a table of valid identifiers see Language Identifiers.
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. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
let szKey = Bytes.stringAsUnicodeNullTerminated "StringFileInfo" // Contains the Unicode string StringFileInfo
// Contains an array of one or more StringTable structures. Each StringTable structures szKey member indicates the appropriate language and code page for displaying the text in that StringTable structure.
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. This member is 1 if the version resource contains text data and 0 if the version resource contains binary data.
let szKey = Bytes.stringAsUnicodeNullTerminated "VarFileInfo" // Contains the Unicode string StringFileInfo
// Contains an array of one or more StringTable structures. Each StringTable structures szKey member indicates the appropriate language and code page for displaying the text in that StringTable structure.
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
[| yield! i32 0xFEEF04BD // DWORD dwSignature; // Contains the value 0xFEEFO4BD. This is used with the szKey member of the VS_VERSION_INFO structure when searching a file for the VS_FIXEDFILEINFO structure.
yield! i32 dwStrucVersion // DWORD dwStrucVersion; // Specifies the binary version number of this structure. The high-order word of this member contains the major version number, and the low-order word contains the minor version number.
yield! Version fileVersion // DWORD dwFileVersionMS,dwFileVersionLS; // Specifies the most/least 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! Version productVersion // DWORD dwProductVersionMS,dwProductVersionLS; // Specifies the most/least 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 dwFileFlagsMask // DWORD dwFileFlagsMask; // Contains a bitmask that specifies the valid bits in dwFileFlags. A bit is valid only if it was defined when the file was created.
yield! i32 dwFileFlags // DWORD dwFileFlags; // Contains a bitmask that specifies the Boolean attributes of the file. This member can include one or more of the following values:
// 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.
yield! i32 dwFileOS //Specifies the operating system for which this file was designed. This member can be one of the following values: Flag
//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.
yield! i32 dwFileType // Specifies the general type of file. This member can be one of the following values:
//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.
yield! i32 dwFileSubtype // 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:
//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.
yield! i32 (int32 (lwFileDate >>> 32)) // Specifies the most significant 32 bits of the file's 64-bit binary creation date and time stamp.
yield! i32 (int32 lwFileDate) //Specifies the least significant 32 bits of the file's 64-bit binary creation date and time stamp.
|]
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 tcGlobals attrib attribs =
match TryFindFSharpAttribute tcGlobals (mkMscorlibAttrib tcGlobals attrib) attribs with
| Some (Attrib(_,_,[ AttribStringArg(s) ],_,_,_,_)) -> Some (s)
| _ -> None
let TryFindIntAttribute tcGlobals attrib attribs =
match TryFindFSharpAttribute tcGlobals (mkMscorlibAttrib tcGlobals attrib) attribs with
| Some (Attrib(_,_,[ AttribInt32Arg(i) ],_,_,_,_)) -> Some (i)
| _ -> None
let TryFindBoolAttribute tcGlobals attrib attribs =
match TryFindFSharpAttribute tcGlobals (mkMscorlibAttrib tcGlobals attrib) attribs with
| Some (Attrib(_,_,[ AttribBoolArg(p) ],_,_,_,_)) -> Some (p)
| _ -> None
// Try to find an AssemblyVersion attribute
let TryFindVersionAttribute tcGlobals attrib attribName attribs =
match TryFindStringAttribute tcGlobals attrib attribs with
| Some versionString ->
try Some(IL.parseILVersion versionString)
with e ->
warning(Error(FSComp.SR.fscBadAssemblyVersion(attribName, versionString),Range.rangeStartup));
None
| _ -> None
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 =
// 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 ->
{ ScopeRef = tcGlobals.sysCcu.ILScopeRef ;
Name = t ;
IsForwarder = true ;
Access = ILTypeDefAccess.Public ;
Nested = mkILNestedExportedTypes List.empty<ILNestedExportedType> ;
CustomAttrs = mkILCustomAttrs List.empty<ILAttribute> }) |>
Seq.toList
let createSystemNumericsExportList tcGlobals =
let sysAssemblyRef = tcGlobals.sysCcu.ILScopeRef.AssemblyRef
let systemNumericsAssemblyRef = ILAssemblyRef.Create("System.Numerics", sysAssemblyRef.Hash, sysAssemblyRef.PublicKey, sysAssemblyRef.Retargetable, sysAssemblyRef.Version, sysAssemblyRef.Locale)
typesForwardedToSystemNumerics |>
Seq.map (fun t ->
{ ScopeRef = ILScopeRef.Assembly(systemNumericsAssemblyRef)
Name = t;
IsForwarder = true ;
Access = ILTypeDefAccess.Public ;
Nested = mkILNestedExportedTypes List.empty<ILNestedExportedType> ;
CustomAttrs = mkILCustomAttrs List.empty<ILAttribute> }) |>
Seq.toList
module MainModuleBuilder =