This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
/
fsi.fs
executable file
·2558 lines (2161 loc) · 133 KB
/
fsi.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. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
module internal Microsoft.FSharp.Compiler.Interactive.Shell
#nowarn "55"
[<assembly: System.Runtime.InteropServices.ComVisible(false)>]
[<assembly: System.CLSCompliant(true)>]
do()
open Internal.Utilities
module Tc = Microsoft.FSharp.Compiler.TypeChecker
open System
open System.Collections.Generic
open System.Diagnostics
open System.Globalization
open System.Runtime.InteropServices
open System.Runtime.CompilerServices
open System.IO
open System.Text
open System.Threading
open System.Reflection
#if !FX_NO_WINFORMS
open System.Windows.Forms
#endif
open Microsoft.FSharp.Compiler.AbstractIL
open Microsoft.FSharp.Compiler.AbstractIL.Diagnostics
open Microsoft.FSharp.Compiler.AbstractIL.IL
open Microsoft.FSharp.Compiler.AbstractIL.Internal
open Microsoft.FSharp.Compiler.AbstractIL.Internal.Library
open Microsoft.FSharp.Compiler.AbstractIL.Extensions.ILX
open Microsoft.FSharp.Compiler.AbstractIL.ILRuntimeWriter
open Microsoft.FSharp.Compiler.Interactive.Settings
open Microsoft.FSharp.Compiler.Interactive.RuntimeHelpers
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.AccessibilityLogic
open Microsoft.FSharp.Compiler.Ast
open Microsoft.FSharp.Compiler.CompileOptions
open Microsoft.FSharp.Compiler.CompileOps
open Microsoft.FSharp.Compiler.ErrorLogger
open Microsoft.FSharp.Compiler.Infos
open Microsoft.FSharp.Compiler.InfoReader
open Microsoft.FSharp.Compiler.IlxGen
open Microsoft.FSharp.Compiler.Lexhelp
open Microsoft.FSharp.Compiler.Layout
open Microsoft.FSharp.Compiler.Lib
open Microsoft.FSharp.Compiler.Optimizer
open Microsoft.FSharp.Compiler.PostTypeCheckSemanticChecks
open Microsoft.FSharp.Compiler.Range
open Microsoft.FSharp.Compiler.TypeChecker
open Microsoft.FSharp.Compiler.Tast
open Microsoft.FSharp.Compiler.Tastops
open Microsoft.FSharp.Compiler.TcGlobals
open Internal.Utilities.Collections
open Internal.Utilities.StructuredFormat
//----------------------------------------------------------------------------
// Hardbinding dependencies should we NGEN fsi.exe
//----------------------------------------------------------------------------
#if FX_RESHAPED_REFLECTION
open Microsoft.FSharp.Core.ReflectionAdapters
#endif
open System.Runtime.CompilerServices
#if !FX_NO_DEFAULT_DEPENDENCY_TYPE
[<Dependency("FSharp.Compiler",LoadHint.Always)>] do ()
[<Dependency("FSharp.Core",LoadHint.Always)>] do ()
#endif
module internal Utilities =
type IAnyToLayoutCall =
abstract AnyToLayout : FormatOptions * obj -> Internal.Utilities.StructuredFormat.Layout
abstract FsiAnyToLayout : FormatOptions * obj -> Internal.Utilities.StructuredFormat.Layout
type private AnyToLayoutSpecialization<'T>() =
interface IAnyToLayoutCall with
member this.AnyToLayout(options, o : obj) = Internal.Utilities.StructuredFormat.Display.any_to_layout options (Unchecked.unbox o : 'T)
member this.FsiAnyToLayout(options, o : obj) = Internal.Utilities.StructuredFormat.Display.fsi_any_to_layout options (Unchecked.unbox o : 'T)
let getAnyToLayoutCall ty =
let specialized = typedefof<AnyToLayoutSpecialization<_>>.MakeGenericType [| ty |]
Activator.CreateInstance(specialized) :?> IAnyToLayoutCall
let callStaticMethod (ty:Type) name args =
ty.InvokeMember(name, (BindingFlags.InvokeMethod ||| BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic), null, null, Array.ofList args,Globalization.CultureInfo.InvariantCulture)
let ignoreAllErrors f = try f() with _ -> ()
let referencedAssemblies = Dictionary<string, DateTime>()
//----------------------------------------------------------------------------
// Timing support
//----------------------------------------------------------------------------
[<AutoSerializable(false)>]
type internal FsiTimeReporter(outWriter: TextWriter) =
let stopwatch = new System.Diagnostics.Stopwatch()
let ptime = System.Diagnostics.Process.GetCurrentProcess()
let numGC = System.GC.MaxGeneration
member tr.TimeOp(f) =
let startTotal = ptime.TotalProcessorTime
let startGC = [| for i in 0 .. numGC -> System.GC.CollectionCount(i) |]
stopwatch.Reset()
stopwatch.Start()
let res = f ()
stopwatch.Stop()
let total = ptime.TotalProcessorTime - startTotal
let spanGC = [ for i in 0 .. numGC-> System.GC.CollectionCount(i) - startGC.[i] ]
let elapsed = stopwatch.Elapsed
fprintfn outWriter "%s" (FSIstrings.SR.fsiTimeInfoMainString((sprintf "%02d:%02d:%02d.%03d" (int elapsed.TotalHours) elapsed.Minutes elapsed.Seconds elapsed.Milliseconds),(sprintf "%02d:%02d:%02d.%03d" (int total.TotalHours) total.Minutes total.Seconds total.Milliseconds),(String.concat ", " (List.mapi (sprintf "%s%d: %d" (FSIstrings.SR.fsiTimeInfoGCGenerationLabelSomeShorthandForTheWordGeneration())) spanGC))))
res
member tr.TimeOpIf flag f = if flag then tr.TimeOp f else f ()
type internal FsiValuePrinterMode =
| PrintExpr
| PrintDecl
/// Used to print value signatures along with their values, according to the current
/// set of pretty printers installed in the system, and default printing rules.
type internal FsiValuePrinter(ilGlobals, generateDebugInfo, resolvePath, outWriter) =
/// This printer is used by F# Interactive if no other printers apply.
let DefaultPrintingIntercept (ienv: Internal.Utilities.StructuredFormat.IEnvironment) (obj:obj) =
match obj with
| null -> None
| :? System.Collections.IDictionary as ie ->
let it = ie.GetEnumerator()
try
let itemLs =
Internal.Utilities.StructuredFormat.LayoutOps.unfoldL // the function to layout each object in the unfold
(fun obj -> ienv.GetLayout obj)
// the function to call at each step of the unfold
(fun () ->
if it.MoveNext() then
Some((it.Key, it.Value),())
else None) ()
// the maximum length
(1+fsi.PrintLength/3)
let makeListL itemLs =
(leftL "[") ^^
sepListL (rightL ";") itemLs ^^
(rightL "]")
Some(wordL "dict" --- makeListL itemLs)
finally
match it with
| :? System.IDisposable as d -> d.Dispose()
| _ -> ()
| _ -> None
/// Get the print options used when formatting output using the structured printer.
member __.GetFsiPrintOptions() =
{ Internal.Utilities.StructuredFormat.FormatOptions.Default with
FormatProvider = fsi.FormatProvider;
PrintIntercepts =
// The fsi object supports the addition of two kinds of printers, one which converts to a string
// and one which converts to another object that is recursively formatted.
// The internal AddedPrinters reports these to FSI.EXE and we pick them up here to produce a layout
[ for x in fsi.AddedPrinters do
match x with
| Choice1Of2 (aty: System.Type, printer) ->
yield (fun _ienv (obj:obj) ->
match obj with
| null -> None
| _ when aty.IsAssignableFrom(obj.GetType()) ->
match printer obj with
| null -> None
| s -> Some (wordL s)
| _ -> None)
| Choice2Of2 (aty: System.Type, converter) ->
yield (fun ienv (obj:obj) ->
match obj with
| null -> None
| _ when aty.IsAssignableFrom(obj.GetType()) ->
match converter obj with
| null -> None
| res -> Some (ienv.GetLayout res)
| _ -> None)
yield DefaultPrintingIntercept];
FloatingPointFormat = fsi.FloatingPointFormat;
PrintWidth = fsi.PrintWidth;
PrintDepth = fsi.PrintDepth;
PrintLength = fsi.PrintLength;
PrintSize = fsi.PrintSize;
ShowProperties = fsi.ShowProperties;
ShowIEnumerable = fsi.ShowIEnumerable; }
/// Get the evaluation context used when inverting the storage mapping of the ILRuntimeWriter.
member __.GetEvaluationContext emEnv =
let cenv = { ilg = ilGlobals ; generatePdb = generateDebugInfo; resolvePath=resolvePath }
{ LookupFieldRef = ILRuntimeWriter.LookupFieldRef emEnv >> Option.get
LookupMethodRef = ILRuntimeWriter.LookupMethodRef emEnv >> Option.get
LookupTypeRef = ILRuntimeWriter.LookupTypeRef cenv emEnv
LookupType = ILRuntimeWriter.LookupType cenv emEnv }
/// Generate a layout for an actual F# value, where we know the value has the given static type.
member __.PrintValue (printMode, opts:FormatOptions, x:obj, ty:System.Type) =
// We do a dynamic invoke of any_to_layout with the right System.Type parameter for the static type of the saved value.
// In principle this helps any_to_layout do the right thing as it descends through terms. In practice it means
// it at least does the right thing for top level 'null' list and option values (but not for nested ones).
//
// The static type was saved into the location used by RuntimeHelpers.GetSavedItType when RuntimeHelpers.SaveIt was called.
// RuntimeHelpers.SaveIt has type ('a -> unit), and fetches the System.Type for 'a by using a typeof<'a> call.
// The funny thing here is that you might think that the driver (this file) knows more about the static types
// than the compiled code does. But it doesn't! In particular, it's not that easy to get a System.Type value based on the
// static type information we do have: we have no direct way to bind a F# TAST type or even an AbstractIL type to
// a System.Type value (I guess that functionality should be in ilreflect.fs).
//
// This will be more significant when we print values other then 'it'
//
try
let anyToLayoutCall = Utilities.getAnyToLayoutCall ty
match printMode with
| PrintDecl ->
// When printing rhs of fsi declarations, use "fsi_any_to_layout".
// This will suppress some less informative values, by returning an empty layout. [fix 4343].
anyToLayoutCall.FsiAnyToLayout(opts, x)
| PrintExpr ->
anyToLayoutCall.AnyToLayout(opts, x)
with
#if !FX_REDUCED_EXCEPTIONS
| :? ThreadAbortException -> Layout.wordL ""
#endif
| e ->
#if DEBUG
printf "\n\nPrintValue: x = %+A and ty=%s\n" x (ty.FullName)
#endif
printf "%s" (FSIstrings.SR.fsiExceptionDuringPrettyPrinting(e.ToString()));
Layout.wordL ""
/// Display the signature of an F# value declaration, along with its actual value.
member valuePrinter.InvokeDeclLayout (emEnv, ilxGenerator: IlxAssemblyGenerator, v:Val) =
// Implemented via a lookup from v to a concrete (System.Object,System.Type).
// This (obj,objTy) pair can then be fed to the fsi value printer.
// Note: The value may be (null:Object).
// Note: A System.Type allows the value printer guide printing of nulls, e.g. as None or [].
//-------
// IlxGen knows what the v:Val was converted to w.r.t. AbsIL datastructures.
// Ilreflect knows what the AbsIL was generated to.
// Combining these allows for obtaining the (obj,objTy) by reflection where possible.
// This assumes the v:Val was given appropriate storage, e.g. StaticField.
if fsi.ShowDeclarationValues then
// Adjust "opts" for printing for "declared-values":
// - No sequences, because they may have effects or time cost.
// - No properties, since they may have unexpected effects.
// - Limit strings to roughly one line, since huge strings (e.g. 1 million chars without \n are slow in vfsi).
// - Limit PrintSize which is a count on nodes.
let declaredValueReductionFactor = 10 (* reduce PrintSize for declared values, e.g. see less of large terms *)
let opts = valuePrinter.GetFsiPrintOptions()
let opts = {opts with ShowProperties = false // properties off, motivated by Form props
ShowIEnumerable = false // seq off, motivated by db query concerns
StringLimit = max 0 (opts.PrintWidth-4) // 4 allows for an indent of 2 and 2 quotes (rough)
PrintSize = opts.PrintSize / declaredValueReductionFactor } // print less
let res =
try ilxGenerator.LookupGeneratedValue (valuePrinter.GetEvaluationContext emEnv, v)
with e ->
assert false
#if DEBUG
//fprintfn fsiConsoleOutput.Out "lookGenerateVal: failed on v=%+A v.Name=%s" v v.LogicalName
#endif
None // lookup may fail
match res with
| None -> None
| Some (obj,objTy) ->
let lay = valuePrinter.PrintValue (FsiValuePrinterMode.PrintDecl, opts, obj, objTy)
if isEmptyL lay then None else Some lay // suppress empty layout
else
None
/// Fetch the saved value of an expression out of the 'it' register and show it.
member valuePrinter.InvokeExprPrinter (denv, vref) =
let opts = valuePrinter.GetFsiPrintOptions()
let savedIt = Microsoft.FSharp.Compiler.Interactive.RuntimeHelpers.GetSavedIt()
let savedItType = Microsoft.FSharp.Compiler.Interactive.RuntimeHelpers.GetSavedItType()
let rhsL = valuePrinter.PrintValue (FsiValuePrinterMode.PrintExpr, opts, savedIt, savedItType)
let denv = { denv with suppressMutableKeyword = true } // suppress 'mutable' in 'val mutable it = ...'
let fullL = if isEmptyL rhsL then
NicePrint.layoutValOrMember denv vref (* the rhs was suppressed by the printer, so no value to print *)
else
(NicePrint.layoutValOrMember denv vref ++ wordL "=") --- rhsL
Internal.Utilities.StructuredFormat.Display.output_layout opts outWriter fullL;
outWriter.WriteLine()
/// Used to make a copy of input in order to include the input when displaying the error text.
type internal FsiStdinSyphon(errorWriter: TextWriter) =
let syphonText = new StringBuilder()
/// Clears the syphon text
member x.Reset () =
syphonText.Clear() |> ignore
/// Adds a new line to the syphon text
member x.Add (str:string) =
syphonText.Append str |> ignore
/// Gets the indicated line in the syphon text
member x.GetLine filename i =
if filename <> Lexhelp.stdinMockFilename then
""
else
let text = syphonText.ToString()
// In Visual Studio, when sending a block of text, it prefixes with '# <line> "filename"\n'
// and postfixes with '# 1 "stdin"\n'. To first, get errors filename context,
// and second to get them back into stdin context (no position stack...).
// To find an error line, trim upto the last stdinReset string the syphoned text.
//printf "PrePrune:-->%s<--\n\n" text;
let rec prune (text:string) =
let stdinReset = "# 1 \"stdin\"\n"
let idx = text.IndexOf(stdinReset,StringComparison.Ordinal)
if idx <> -1 then
prune (text.Substring(idx + stdinReset.Length))
else
text
let text = prune text
let lines = text.Split '\n'
if 0 < i && i <= lines.Length then lines.[i-1] else ""
/// Display the given error.
member syphon.PrintError (tcConfig:TcConfigBuilder, isWarn, err) =
Utilities.ignoreAllErrors (fun () ->
DoWithErrorColor isWarn (fun () ->
errorWriter.WriteLine();
writeViaBufferWithEnvironmentNewLines errorWriter (OutputErrorOrWarningContext " " syphon.GetLine) err;
writeViaBufferWithEnvironmentNewLines errorWriter (OutputErrorOrWarning (tcConfig.implicitIncludeDir,tcConfig.showFullPaths,tcConfig.flatErrors,tcConfig.errorStyle,false)) err;
errorWriter.WriteLine()))
/// Encapsulates functions used to write to outWriter and errorWriter
type internal FsiConsoleOutput(tcConfigB, outWriter:TextWriter, errorWriter:TextWriter) =
let nullOut = new StreamWriter(Stream.Null) :> TextWriter
let fprintfnn (os: TextWriter) fmt = Printf.kfprintf (fun _ -> os.WriteLine(); os.WriteLine()) os fmt
/// uprintf to write usual responses to stdout (suppressed by --quiet), with various pre/post newlines
member out.uprintf fmt = fprintf (if tcConfigB.noFeedback then nullOut else outWriter) fmt
member out.uprintfn fmt = fprintfn (if tcConfigB.noFeedback then nullOut else outWriter) fmt
member out.uprintfnn fmt = fprintfnn (if tcConfigB.noFeedback then nullOut else outWriter) fmt
member out.uprintnf fmt = out.uprintfn ""; out.uprintf fmt
member out.uprintnfn fmt = out.uprintfn ""; out.uprintfn fmt
member out.uprintnfnn fmt = out.uprintfn ""; out.uprintfnn fmt
member out.Out = outWriter
member out.Error = errorWriter
/// This ErrorLogger reports all warnings, but raises StopProcessing on first error or early exit
type internal ErrorLoggerThatStopsOnFirstError(tcConfigB:TcConfigBuilder, fsiStdinSyphon:FsiStdinSyphon, fsiConsoleOutput: FsiConsoleOutput) =
inherit ErrorLogger("ErrorLoggerThatStopsOnFirstError")
let mutable errors = 0
member x.SetError() =
errors <- 1
member x.ErrorSinkHelper(err) =
fsiStdinSyphon.PrintError(tcConfigB,false,err)
errors <- errors + 1
if tcConfigB.abortOnError then exit 1 (* non-zero exit code *)
// STOP ON FIRST ERROR (AVOIDS PARSER ERROR RECOVERY)
raise StopProcessing
member x.CheckForErrors() = (errors > 0)
member x.ResetErrorCount() = (errors <- 0)
override x.WarnSinkImpl(err) =
DoWithErrorColor true (fun () ->
if ReportWarningAsError (tcConfigB.globalWarnLevel, tcConfigB.specificWarnOff, tcConfigB.specificWarnOn, tcConfigB.specificWarnAsError, tcConfigB.specificWarnAsWarn, tcConfigB.globalWarnAsError) err then
x.ErrorSinkHelper err
elif ReportWarning (tcConfigB.globalWarnLevel, tcConfigB.specificWarnOff, tcConfigB.specificWarnOn) err then
fsiConsoleOutput.Error.WriteLine()
writeViaBufferWithEnvironmentNewLines fsiConsoleOutput.Error (OutputErrorOrWarningContext " " fsiStdinSyphon.GetLine) err
writeViaBufferWithEnvironmentNewLines fsiConsoleOutput.Error (OutputErrorOrWarning (tcConfigB.implicitIncludeDir,tcConfigB.showFullPaths,tcConfigB.flatErrors,tcConfigB.errorStyle,true)) err
fsiConsoleOutput.Error.WriteLine())
override x.ErrorSinkImpl err = x.ErrorSinkHelper err
override x.ErrorCount = errors
/// A helper function to check if its time to abort
member x.AbortOnError() =
if errors > 0 then
fprintf fsiConsoleOutput.Error "%s" (FSIstrings.SR.stoppedDueToError())
fsiConsoleOutput.Error.Flush()
raise StopProcessing
/// Get the directory name from a string, with some defaults if it doesn't have one
let internal directoryName (s:string) =
if s = "" then "."
else
match Path.GetDirectoryName s with
| null -> if FileSystem.IsPathRootedShim s then s else "."
| res -> if res = "" then "." else res
//----------------------------------------------------------------------------
// cmd line - state for options
//----------------------------------------------------------------------------
/// Process the command line options
type internal FsiCommandLineOptions(argv: string[], tcConfigB, fsiConsoleOutput: FsiConsoleOutput) =
let mutable enableConsoleKeyProcessing =
#if FX_REDUCED_CONSOLE
false
#else
// Mono on Win32 doesn't implement correct console processing
not (runningOnMono && System.Environment.OSVersion.Platform = System.PlatformID.Win32NT)
#endif
// In the cross-platform edition of F#, 'gui' support is currently off by default
#if CROSS_PLATFORM_COMPILER
let mutable gui = false // override via "--gui", off by default
#else
let mutable gui = true // override via "--gui", on by default
#endif
#if DEBUG
let mutable showILCode = false // show modul il code
#endif
let mutable showTypes = true // show types after each interaction?
let mutable fsiServerName = ""
let mutable interact = true
let mutable explicitArgs = []
let mutable inputFilesAcc = []
let mutable fsiServerInputCodePage = None
let mutable fsiServerOutputCodePage = None
let mutable fsiLCID = None
// internal options
let mutable probeToSeeIfConsoleWorks = true
let mutable peekAheadOnConsoleToPermitTyping = true
let isInteractiveServer() = fsiServerName <> ""
let recordExplicitArg arg = explicitArgs <- explicitArgs @ [arg]
let executableFileName =
lazy
match tcConfigB.exename with
| Some s -> s
| None ->
let currentProcess = System.Diagnostics.Process.GetCurrentProcess()
Path.GetFileName(currentProcess.MainModule.FileName)
// Additional fsi options are list below.
// In the "--help", these options can be printed either before (fsiUsagePrefix) or after (fsiUsageSuffix) the core options.
let displayHelpFsi tcConfigB (blocks:CompilerOptionBlock list) =
DisplayBannerText tcConfigB;
fprintfn fsiConsoleOutput.Out ""
fprintfn fsiConsoleOutput.Out "%s" (FSIstrings.SR.fsiUsage(executableFileName.Value))
PrintCompilerOptionBlocks blocks
exit 0
// option tags
let tagFile = "<file>"
let tagNone = ""
/// These options preceed the FsiCoreCompilerOptions in the help blocks
let fsiUsagePrefix tcConfigB =
[PublicOptions(FSIstrings.SR.fsiInputFiles(),
[CompilerOption("use",tagFile, OptionString (fun s -> inputFilesAcc <- inputFilesAcc @ [(s,true)]), None,
Some (FSIstrings.SR.fsiUse()));
CompilerOption("load",tagFile, OptionString (fun s -> inputFilesAcc <- inputFilesAcc @ [(s,false)]), None,
Some (FSIstrings.SR.fsiLoad()));
]);
PublicOptions(FSIstrings.SR.fsiCodeGeneration(),[]);
PublicOptions(FSIstrings.SR.fsiErrorsAndWarnings(),[]);
PublicOptions(FSIstrings.SR.fsiLanguage(),[]);
PublicOptions(FSIstrings.SR.fsiMiscellaneous(),[]);
PublicOptions(FSIstrings.SR.fsiAdvanced(),[]);
PrivateOptions(
[// Make internal fsi-server* options. Do not print in the help. They are used by VFSI.
CompilerOption("fsi-server","", OptionString (fun s -> fsiServerName <- s), None, None); // "FSI server mode on given named channel");
CompilerOption("fsi-server-input-codepage","",OptionInt (fun n -> fsiServerInputCodePage <- Some(n)), None, None); // " Set the input codepage for the console");
CompilerOption("fsi-server-output-codepage","",OptionInt (fun n -> fsiServerOutputCodePage <- Some(n)), None, None); // " Set the output codepage for the console");
CompilerOption("fsi-server-no-unicode","", OptionUnit (fun () -> fsiServerOutputCodePage <- None; fsiServerInputCodePage <- None), None, None); // "Do not set the codepages for the console");
CompilerOption("fsi-server-lcid","", OptionInt (fun n -> fsiLCID <- Some(n)), None, None); // "LCID from Visual Studio"
// We do not want to print the "script.fsx arg2..." as part of the options
CompilerOption("script.fsx arg1 arg2 ...","",
OptionGeneral((fun args -> args.Length > 0 && IsScript args.[0]),
(fun args -> let scriptFile = args.[0]
let scriptArgs = List.tail args
inputFilesAcc <- inputFilesAcc @ [(scriptFile,true)] (* record script.fsx for evaluation *)
List.iter recordExplicitArg scriptArgs (* record rest of line as explicit arguments *)
tcConfigB.noFeedback <- true (* "quiet", no banners responses etc *)
interact <- false (* --exec, exit after eval *)
[] (* no arguments passed on, all consumed here *)
)),None,None); // "Run script.fsx with the follow command line arguments: arg1 arg2 ...");
]);
PrivateOptions(
[
// Private options, related to diagnostics around console probing
CompilerOption("probeconsole","", OptionSwitch (fun flag -> probeToSeeIfConsoleWorks <- flag=OptionSwitch.On), None, None); // "Probe to see if Console looks functional");
CompilerOption("peekahead","", OptionSwitch (fun flag -> peekAheadOnConsoleToPermitTyping <- flag=OptionSwitch.On), None, None); // "Probe to see if Console looks functional");
])
]
/// These options follow the FsiCoreCompilerOptions in the help blocks
let fsiUsageSuffix tcConfigB =
[PublicOptions(FSComp.SR.optsHelpBannerInputFiles(),
[CompilerOption("--","", OptionRest recordExplicitArg, None,
Some (FSIstrings.SR.fsiRemaining()));
]);
PublicOptions(FSComp.SR.optsHelpBannerMisc(),
[ CompilerOption("help", tagNone,
OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks),None,
Some (FSIstrings.SR.fsiHelp()))
]);
PrivateOptions(
[ CompilerOption("?" , tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help");
CompilerOption("help" , tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help");
CompilerOption("full-help", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help");
]);
PublicOptions(FSComp.SR.optsHelpBannerAdvanced(),
[CompilerOption("exec", "", OptionUnit (fun () -> interact <- false), None, Some (FSIstrings.SR.fsiExec()));
CompilerOption("gui", tagNone, OptionSwitch(fun flag -> gui <- (flag = OptionSwitch.On)),None,Some (FSIstrings.SR.fsiGui()));
CompilerOption("quiet", "", OptionUnit (fun () -> tcConfigB.noFeedback <- true), None,Some (FSIstrings.SR.fsiQuiet()));
(* Renamed --readline and --no-readline to --tabcompletion:+|- *)
CompilerOption("readline", tagNone, OptionSwitch(fun flag -> enableConsoleKeyProcessing <- (flag = OptionSwitch.On)), None, Some(FSIstrings.SR.fsiReadline()));
CompilerOption("quotations-debug", tagNone, OptionSwitch(fun switch -> tcConfigB.emitDebugInfoInQuotations <- switch = OptionSwitch.On),None, Some(FSIstrings.SR.fsiEmitDebugInfoInQuotations()));
#if SHADOW_COPY_REFERENCES
CompilerOption("shadowcopyreferences", tagNone, OptionSwitch(fun flag -> tcConfigB.shadowCopyReferences <- flag = OptionSwitch.On), None, Some(FSIstrings.SR.shadowCopyReferences()));
#endif
]);
]
/// Process command line, flags and collect filenames.
/// The ParseCompilerOptions function calls imperative function to process "real" args
/// Rather than start processing, just collect names, then process them.
let sourceFiles =
let collect name =
let fsx = CompileOps.IsScript name
inputFilesAcc <- inputFilesAcc @ [(name,fsx)] // O(n^2), but n small...
try
let fsiCompilerOptions = fsiUsagePrefix tcConfigB @ GetCoreFsiCompilerOptions tcConfigB @ fsiUsageSuffix tcConfigB
let abbrevArgs = GetAbbrevFlagSet tcConfigB false
ParseCompilerOptions (collect, fsiCompilerOptions, List.tail (PostProcessCompilerArgs abbrevArgs argv))
with e ->
stopProcessingRecovery e range0; exit 1;
inputFilesAcc
do
if tcConfigB.utf8output then
Console.OutputEncoding <- System.Text.Encoding.UTF8
do
let firstArg =
match sourceFiles with
| [] -> argv.[0]
| _ -> fst (List.head (List.rev sourceFiles) )
let args = Array.ofList (firstArg :: explicitArgs)
fsi.CommandLineArgs <- args
//----------------------------------------------------------------------------
// Banner
//----------------------------------------------------------------------------
member __.ShowBanner() =
fsiConsoleOutput.uprintnfn "%s" (tcConfigB.productNameForBannerText)
fsiConsoleOutput.uprintfnn "%s" (FSComp.SR.optsCopyright())
fsiConsoleOutput.uprintfn "%s" (FSIstrings.SR.fsiBanner3())
member __.ShowHelp() =
let helpLine = sprintf "%s --help" (Path.GetFileNameWithoutExtension executableFileName.Value)
fsiConsoleOutput.uprintfn ""
fsiConsoleOutput.uprintfnn "%s" (FSIstrings.SR.fsiIntroTextHeader1directives());
fsiConsoleOutput.uprintfn " #r \"file.dll\";; %s" (FSIstrings.SR.fsiIntroTextHashrInfo());
fsiConsoleOutput.uprintfn " #I \"path\";; %s" (FSIstrings.SR.fsiIntroTextHashIInfo());
fsiConsoleOutput.uprintfn " #load \"file.fs\" ...;; %s" (FSIstrings.SR.fsiIntroTextHashloadInfo());
fsiConsoleOutput.uprintfn " #time [\"on\"|\"off\"];; %s" (FSIstrings.SR.fsiIntroTextHashtimeInfo());
fsiConsoleOutput.uprintfn " #help;; %s" (FSIstrings.SR.fsiIntroTextHashhelpInfo());
fsiConsoleOutput.uprintfn " #quit;; %s" (FSIstrings.SR.fsiIntroTextHashquitInfo()); (* last thing you want to do, last thing in the list - stands out more *)
fsiConsoleOutput.uprintfn "";
fsiConsoleOutput.uprintfnn "%s" (FSIstrings.SR.fsiIntroTextHeader2commandLine());
fsiConsoleOutput.uprintfn "%s" (FSIstrings.SR.fsiIntroTextHeader3(helpLine));
fsiConsoleOutput.uprintfn "";
fsiConsoleOutput.uprintfn "";
#if DEBUG
member __.ShowILCode with get() = showILCode and set v = showILCode <- v
#endif
member __.ShowTypes with get() = showTypes and set v = showTypes <- v
member __.FsiServerName = fsiServerName
member __.FsiServerInputCodePage = fsiServerInputCodePage
member __.FsiServerOutputCodePage = fsiServerOutputCodePage
member __.FsiLCID with get() = fsiLCID and set v = fsiLCID <- v
member __.IsInteractiveServer = isInteractiveServer()
member __.ProbeToSeeIfConsoleWorks = probeToSeeIfConsoleWorks
member __.EnableConsoleKeyProcessing = enableConsoleKeyProcessing
member __.Interact = interact
member __.PeekAheadOnConsoleToPermitTyping = peekAheadOnConsoleToPermitTyping
member __.SourceFiles = sourceFiles
member __.Gui = gui
#if FX_LCIDFROMCODEPAGE
/// Set the current ui culture for the current thread.
let internal SetCurrentUICultureForThread (lcid : int option) =
match lcid with
| Some n -> Thread.CurrentThread.CurrentUICulture <- new CultureInfo(n)
| None -> ()
#endif
//----------------------------------------------------------------------------
// Reporting - warnings, errors
//----------------------------------------------------------------------------
let internal InstallErrorLoggingOnThisThread errorLogger =
if !progress then dprintfn "Installing logger on id=%d name=%s" Thread.CurrentThread.ManagedThreadId Thread.CurrentThread.Name
SetThreadErrorLoggerNoUnwind(errorLogger)
SetThreadBuildPhaseNoUnwind(BuildPhase.Interactive)
#if !NO_SERVERCODEPAGES
/// Set the input/output encoding. The use of a thread is due to a known bug on
/// on Vista where calls to Console.InputEncoding can block the process.
let internal SetServerCodePages(fsiOptions: FsiCommandLineOptions) =
match fsiOptions.FsiServerInputCodePage, fsiOptions.FsiServerOutputCodePage with
| None,None -> ()
| inputCodePageOpt,outputCodePageOpt ->
let successful = ref false
Async.Start (async { do match inputCodePageOpt with
| None -> ()
| Some(n:int) ->
let encoding = System.Text.Encoding.GetEncoding(n)
// Note this modifies the real honest-to-goodness settings for the current shell.
// and the modifiations hang around even after the process has exited.
Console.InputEncoding <- encoding
do match outputCodePageOpt with
| None -> ()
| Some(n:int) ->
let encoding = System.Text.Encoding.GetEncoding n
// Note this modifies the real honest-to-goodness settings for the current shell.
// and the modifiations hang around even after the process has exited.
Console.OutputEncoding <- encoding
do successful := true });
for pause in [10;50;100;1000;2000;10000] do
if not !successful then
Thread.Sleep(pause);
if not !successful then
System.Windows.Forms.MessageBox.Show(FSIstrings.SR.fsiConsoleProblem()) |> ignore
#endif
//----------------------------------------------------------------------------
// Prompt printing
//----------------------------------------------------------------------------
type internal FsiConsolePrompt(fsiOptions: FsiCommandLineOptions, fsiConsoleOutput: FsiConsoleOutput) =
// A prompt gets "printed ahead" at start up. Tells users to start type while initialisation completes.
// A prompt can be skipped by "silent directives", e.g. ones sent to FSI by VS.
let mutable dropPrompt = 0
// NOTE: SERVER-PROMPT is not user displayed, rather it's a prefix that code elsewhere
// uses to identify the prompt, see vs\FsPkgs\FSharp.VS.FSI\fsiSessionToolWindow.fs
let prompt = if fsiOptions.IsInteractiveServer then "SERVER-PROMPT>\n" else "> "
member __.Print() = if dropPrompt = 0 then fsiConsoleOutput.uprintf "%s" prompt else dropPrompt <- dropPrompt - 1
member __.PrintAhead() = dropPrompt <- dropPrompt + 1; fsiConsoleOutput.uprintf "%s" prompt
member __.SkipNext() = dropPrompt <- dropPrompt + 1
member __.FsiOptions = fsiOptions
//----------------------------------------------------------------------------
// Startup processing
//----------------------------------------------------------------------------
type internal FsiConsoleInput(fsiOptions: FsiCommandLineOptions, inReader: TextReader, outWriter: TextWriter) =
let consoleLooksOperational() =
if fsiOptions.ProbeToSeeIfConsoleWorks then
if !progress then fprintfn outWriter "probing to see if console works..."
try
// Probe to see if the console looks functional on this version of .NET
let _ = Console.KeyAvailable
let c1 = Console.ForegroundColor
let c2 = Console.BackgroundColor
let _ = Console.CursorLeft <- Console.CursorLeft
if !progress then fprintfn outWriter "probe succeeded, we might have a console, comparing foreground (%A) and background (%A) colors, if they are the same then we're running in emacs or VS on unix and we turn off readline by default..." c1 c2
c1 <> c2
with _ ->
if !progress then fprintfn outWriter "probe failed, we have no console..."
(* warning(Failure("Note: there was a problem setting up custom readline console support. Consider starting fsi.exe with the --no-readline option")); *)
false
else
true
let consoleOpt =
// The "console.fs" code does a limited form of "TAB-completion".
// Currently, it turns on if it looks like we have a console.
if fsiOptions.EnableConsoleKeyProcessing && consoleLooksOperational() then
Some(new Microsoft.FSharp.Compiler.Interactive.ReadLineConsole())
else
None
// When VFSI is running, there should be no "console", and in particular the console.fs readline code should not to run.
do if fsiOptions.IsInteractiveServer then assert(consoleOpt = None)
/// This threading event gets set after the first-line-reader has finished its work
let consoleReaderStartupDone = new ManualResetEvent(false)
/// When using a key-reading console this holds the first line after it is read
let mutable firstLine = None
/// Peek on the standard input so that the user can type into it from a console window.
do if fsiOptions.Interact then
if fsiOptions.PeekAheadOnConsoleToPermitTyping then
(new Thread(fun () ->
match consoleOpt with
| Some console when fsiOptions.EnableConsoleKeyProcessing && not fsiOptions.IsInteractiveServer ->
if List.isEmpty fsiOptions.SourceFiles then
if !progress then fprintfn outWriter "first-line-reader-thread reading first line...";
firstLine <- Some(console.ReadLine());
if !progress then fprintfn outWriter "first-line-reader-thread got first line = %A..." firstLine;
consoleReaderStartupDone.Set() |> ignore
if !progress then fprintfn outWriter "first-line-reader-thread has set signal and exited." ;
| _ ->
ignore(inReader.Peek());
consoleReaderStartupDone.Set() |> ignore
)).Start()
else
if !progress then fprintfn outWriter "first-line-reader-thread not in use."
consoleReaderStartupDone.Set() |> ignore
/// Try to get the first line, if we snarfed it while probing.
member __.TryGetFirstLine() = let r = firstLine in firstLine <- None; r
/// Try to get the console, if it appears operational.
member __.TryGetConsole() = consoleOpt
member __.In = inReader
member __.WaitForInitialConsoleInput() = WaitHandle.WaitAll [| consoleReaderStartupDone |] |> ignore;
//----------------------------------------------------------------------------
// FsiDynamicCompilerState
//----------------------------------------------------------------------------
[<AutoSerializable(false)>]
[<NoEquality; NoComparison>]
type internal FsiDynamicCompilerState =
{ optEnv : Optimizer.IncrementalOptimizationEnv
emEnv : ILRuntimeWriter.emEnv
tcGlobals : TcGlobals
tcState : TcState
ilxGenerator : IlxGen.IlxAssemblyGenerator
// Why is this not in FsiOptions?
timing : bool
debugBreak : bool }
let internal WithImplicitHome (tcConfigB, dir) f =
let old = tcConfigB.implicitIncludeDir
tcConfigB.implicitIncludeDir <- dir;
try f()
finally tcConfigB.implicitIncludeDir <- old
/// Encapsulates the coordination of the typechecking, optimization and code generation
/// components of the F# compiler for interactively executed fragments of code.
///
/// A single instance of this object is created per interactive session.
type internal FsiDynamicCompiler
(timeReporter : FsiTimeReporter,
tcConfigB: TcConfigBuilder,
tcLockObject : obj,
errorLogger: ErrorLoggerThatStopsOnFirstError,
outWriter: TextWriter,
tcImports: TcImports,
tcGlobals: TcGlobals,
ilGlobals: ILGlobals,
fsiOptions : FsiCommandLineOptions,
fsiConsoleOutput : FsiConsoleOutput,
niceNameGen,
resolvePath) =
let outfile = "TMPFSCI.exe"
let assemblyName = "FSI-ASSEMBLY"
let mutable fragmentId = 0
let mutable prevIt : ValRef option = None
let generateDebugInfo = tcConfigB.debuginfo
let valuePrinter = FsiValuePrinter(ilGlobals, generateDebugInfo, resolvePath, outWriter)
let assemblyBuilder,moduleBuilder = ILRuntimeWriter.mkDynamicAssemblyAndModule (assemblyName, tcConfigB.optSettings.localOpt(), generateDebugInfo, false)
let rangeStdin = rangeN Lexhelp.stdinMockFilename 0
let infoReader = InfoReader(tcGlobals,tcImports.GetImportMap())
/// Add attributes
let CreateModuleFragment (tcConfigB: TcConfigBuilder, assemblyName, codegenResults) =
if !progress then fprintfn fsiConsoleOutput.Out "Creating main module...";
let mainModule = mkILSimpleModule assemblyName (GetGeneratedILModuleName tcConfigB.target assemblyName) (tcConfigB.target = Dll) tcConfigB.subsystemVersion tcConfigB.useHighEntropyVA (mkILTypeDefs codegenResults.ilTypeDefs) None None 0x0 (mkILExportedTypes []) ""
{ mainModule
with Manifest =
(let man = mainModule.ManifestOfAssembly
Some { man with CustomAttrs = mkILCustomAttrs codegenResults.ilAssemAttrs }); }
let ProcessInputs(istate: FsiDynamicCompilerState, inputs: ParsedInput list, showTypes: bool, isIncrementalFragment: bool, isInteractiveItExpr: bool, prefixPath: LongIdent) =
let optEnv = istate.optEnv
let emEnv = istate.emEnv
let tcState = istate.tcState
let ilxGenerator = istate.ilxGenerator
let tcConfig = TcConfig.Create(tcConfigB,validate=false)
// Typecheck. The lock stops the type checker running at the same time as the
// server intellisense implementation (which is currently incomplete and #if disabled)
let (tcState:TcState),topCustomAttrs,declaredImpls,tcEnvAtEndOfLastInput =
lock tcLockObject (fun _ -> TypeCheckClosedInputSet(errorLogger.CheckForErrors,tcConfig,tcImports,tcGlobals, Some prefixPath,tcState,inputs))
#if DEBUG
// Logging/debugging
if tcConfig.printAst then
for input in declaredImpls do
fprintfn fsiConsoleOutput.Out "AST:"
fprintfn fsiConsoleOutput.Out "%+A" input
#endif
errorLogger.AbortOnError();
let importMap = tcImports.GetImportMap()
// optimize: note we collect the incremental optimization environment
let optimizedImpls, _optData, optEnv = ApplyAllOptimizations (tcConfig, tcGlobals, (LightweightTcValForUsingInBuildMethodCall tcGlobals), outfile, importMap, isIncrementalFragment, optEnv, tcState.Ccu, declaredImpls)
errorLogger.AbortOnError();
let fragName = textOfLid prefixPath
let codegenResults = GenerateIlxCode (IlReflectBackend, isInteractiveItExpr, runningOnMono, tcConfig, topCustomAttrs, optimizedImpls, fragName, true, ilxGenerator)
errorLogger.AbortOnError();
// Each input is like a small separately compiled extension to a single source file.
// The incremental extension to the environment is dictated by the "signature" of the values as they come out
// of the type checker. Hence we add the declaredImpls (unoptimized) to the environment, rather than the
// optimizedImpls.
ilxGenerator.AddIncrementalLocalAssemblyFragment (isIncrementalFragment, fragName, declaredImpls)
ReportTime tcConfig "TAST -> ILX";
errorLogger.AbortOnError();
ReportTime tcConfig "Linking";
let ilxMainModule = CreateModuleFragment (tcConfigB, assemblyName, codegenResults)
errorLogger.AbortOnError();
ReportTime tcConfig "Assembly refs Normalised";
let mainmod3 = Morphs.morphILScopeRefsInILModuleMemoized ilGlobals (NormalizeAssemblyRefs tcImports) ilxMainModule
errorLogger.AbortOnError();
#if DEBUG
if fsiOptions.ShowILCode then
fsiConsoleOutput.uprintnfn "--------------------";
ILAsciiWriter.output_module outWriter mainmod3;
fsiConsoleOutput.uprintnfn "--------------------"
#else
ignore(fsiOptions)
#endif
ReportTime tcConfig "Reflection.Emit";
let emEnv,execs = ILRuntimeWriter.emitModuleFragment(ilGlobals, emEnv, assemblyBuilder, moduleBuilder, mainmod3, generateDebugInfo, resolvePath)
errorLogger.AbortOnError();
// Explicitly register the resources with the QuotationPickler module
// We would save them as resources into the dynamic assembly but there is missing
// functionality System.Reflection for dynamic modules that means they can't be read back out
let cenv = { ilg = ilGlobals ; generatePdb = generateDebugInfo; resolvePath=resolvePath }
for (referencedTypeDefs, bytes) in codegenResults.quotationResourceInfo do
let referencedTypes =
[| for tref in referencedTypeDefs do
yield ILRuntimeWriter.LookupTypeRef cenv emEnv tref |]
Microsoft.FSharp.Quotations.Expr.RegisterReflectedDefinitions (assemblyBuilder, fragName, bytes, referencedTypes);
ReportTime tcConfig "Run Bindings";
timeReporter.TimeOpIf istate.timing (fun () ->
execs |> List.iter (fun exec ->
match exec() with
| Some err ->
fprintfn fsiConsoleOutput.Error "%s" (err.ToString())
errorLogger.SetError()
errorLogger.AbortOnError()
| None -> ())) ;
errorLogger.AbortOnError();
// Echo the decls (reach inside wrapping)
// This code occurs AFTER the execution of the declarations.
// So stored values will have been initialised, modified etc.
if showTypes && not tcConfig.noFeedback then
let denv = tcState.TcEnvFromImpls.DisplayEnv
let denv =
if isIncrementalFragment then
// Extend denv with a (Val -> layout option) function for printing of val bindings.
{denv with generatedValueLayout = (fun v -> valuePrinter.InvokeDeclLayout (emEnv, ilxGenerator, v)) }
else
// With #load items, the vals in the inferred signature do not tie up with those generated. Disable printing.
denv
// 'Open' the path for the fragment we just compiled for any future printing.
let denv = denv.AddOpenPath (pathOfLid prefixPath)
for (TImplFile(_qname,_,mexpr,_,_)) in declaredImpls do
let responseL = NicePrint.layoutInferredSigOfModuleExpr false denv infoReader AccessibleFromSomewhere rangeStdin mexpr
if not (Layout.isEmptyL responseL) then
fsiConsoleOutput.uprintfn "";
let opts = valuePrinter.GetFsiPrintOptions()
let responseL = Internal.Utilities.StructuredFormat.Display.squash_layout opts responseL
Layout.renderL (Layout.channelR outWriter) responseL |> ignore
fsiConsoleOutput.uprintfnn ""
// Build the new incremental state.
let istate = {istate with optEnv = optEnv;
emEnv = emEnv;
ilxGenerator = ilxGenerator;
tcState = tcState }
// Return the new state and the environment at the end of the last input, ready for further inputs.
(istate,tcEnvAtEndOfLastInput)
let nextFragmentId() = fragmentId <- fragmentId + 1; fragmentId
let mkFragmentPath i =
// NOTE: this text shows in exn traces and type names. Make it clear and fixed width
[mkSynId rangeStdin (FsiDynamicModulePrefix + sprintf "%04d" i)]
member __.DynamicAssemblyName = assemblyName
member __.DynamicAssembly = (assemblyBuilder :> Assembly)
member __.EvalParsedSourceFiles (istate, inputs) =
let i = nextFragmentId()
let prefix = mkFragmentPath i
// Ensure the path includes the qualifying name
let inputs = inputs |> List.map (PrependPathToInput prefix)
let istate,_ = ProcessInputs (istate, inputs, true, false, false, prefix)
istate
/// Evaluate the given definitions and produce a new interactive state.
member __.EvalParsedDefinitions (istate, showTypes, isInteractiveItExpr, defs: SynModuleDecls) =
let filename = Lexhelp.stdinMockFilename
let i = nextFragmentId()
let prefix = mkFragmentPath i
let prefixPath = pathOfLid prefix
let impl = SynModuleOrNamespace(prefix,(*isRec*)false, (* isModule: *) true,defs,PreXmlDoc.Empty,[],None,rangeStdin)
let input = ParsedInput.ImplFile(ParsedImplFileInput(filename,true, ComputeQualifiedNameOfFileFromUniquePath (rangeStdin,prefixPath),[],[],[impl],(true (* isLastCompiland *), false (* isExe *)) ))
let istate,tcEnvAtEndOfLastInput = ProcessInputs (istate, [input], showTypes, true, isInteractiveItExpr, prefix)
let tcState = istate.tcState
{ istate with tcState = tcState.NextStateAfterIncrementalFragment(tcEnvAtEndOfLastInput) }
/// Evaluate the given expression and produce a new interactive state.
member fsiDynamicCompiler.EvalParsedExpression (istate, expr: SynExpr) =
let tcConfig = TcConfig.Create (tcConfigB, validate=false)
let itName = "it"
// Construct the code that saves the 'it' value into the 'SaveIt' register.
let defs = fsiDynamicCompiler.BuildItBinding expr
// Evaluate the overall definitions.
let istate = fsiDynamicCompiler.EvalParsedDefinitions (istate, false, true, defs)
// Snarf the type for 'it' via the binding
match istate.tcState.TcEnvFromImpls.NameEnv.FindUnqualifiedItem itName with
| NameResolution.Item.Value vref ->
if not tcConfig.noFeedback then
valuePrinter.InvokeExprPrinter (istate.tcState.TcEnvFromImpls.DisplayEnv, vref.Deref)
/// Clear the value held in the previous "it" binding, if any, as long as it has never been referenced.
match prevIt with
| Some prevVal when not prevVal.Deref.HasBeenReferenced ->
istate.ilxGenerator.ClearGeneratedValue (valuePrinter.GetEvaluationContext istate.emEnv, prevVal.Deref)
| _ -> ()
prevIt <- Some vref
| _ -> ()
// Return the interactive state.
istate
// Construct the code that saves the 'it' value into the 'SaveIt' register.
member __.BuildItBinding (expr: SynExpr) =
let m = expr.Range
let itName = "it"