/
fsi.fs
3027 lines (2531 loc) · 160 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. See License.txt in the project root for license information.
module FSharp.Compiler.Interactive.Shell
#nowarn "55"
[<assembly: System.Runtime.InteropServices.ComVisible(false)>]
[<assembly: System.CLSCompliant(true)>]
do()
open System
open System.Collections.Generic
open System.Diagnostics
open System.Globalization
open System.Runtime.InteropServices
open System.IO
open System.Text
open System.Threading
open System.Reflection
open System.Runtime.CompilerServices
open FSharp.Compiler
open FSharp.Compiler.AbstractIL
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.ILBinaryReader
open FSharp.Compiler.AbstractIL.Internal
open FSharp.Compiler.AbstractIL.Internal.Library
open FSharp.Compiler.AbstractIL.Extensions.ILX
open FSharp.Compiler.AbstractIL.ILRuntimeWriter
open FSharp.Compiler.Lib
open FSharp.Compiler.AccessibilityLogic
open FSharp.Compiler.Ast
open FSharp.Compiler.CompileOptions
open FSharp.Compiler.CompileOps
open FSharp.Compiler.ErrorLogger
open FSharp.Compiler.Infos
open FSharp.Compiler.InfoReader
open FSharp.Compiler.NameResolution
open FSharp.Compiler.IlxGen
open FSharp.Compiler.Lexhelp
open FSharp.Compiler.Layout
open FSharp.Compiler.Lib
open FSharp.Compiler.Optimizer
open FSharp.Compiler.PostTypeCheckSemanticChecks
open FSharp.Compiler.Range
open FSharp.Compiler.TypeChecker
open FSharp.Compiler.Tast
open FSharp.Compiler.Tastops
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.ReferenceResolver
open Internal.Utilities
open Internal.Utilities.Collections
open Internal.Utilities.StructuredFormat
//----------------------------------------------------------------------------
// For the FSI as a service methods...
//----------------------------------------------------------------------------
type FsiValue(reflectionValue:obj, reflectionType:Type, fsharpType:FSharpType) =
member x.ReflectionValue = reflectionValue
member x.ReflectionType = reflectionType
member x.FSharpType = fsharpType
[<AutoOpen>]
module internal Utilities =
type IAnyToLayoutCall =
abstract AnyToLayout : FormatOptions * obj * Type -> Internal.Utilities.StructuredFormat.Layout
abstract FsiAnyToLayout : FormatOptions * obj * Type -> Internal.Utilities.StructuredFormat.Layout
type private AnyToLayoutSpecialization<'T>() =
interface IAnyToLayoutCall with
member this.AnyToLayout(options, o : obj, ty : Type) = Internal.Utilities.StructuredFormat.Display.any_to_layout options ((Unchecked.unbox o : 'T), ty)
member this.FsiAnyToLayout(options, o : obj, ty : Type) = Internal.Utilities.StructuredFormat.Display.fsi_any_to_layout options ((Unchecked.unbox o : 'T), ty)
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 _ -> ()
// TODO: this dotnet/core polyfill can be removed when it surfaces in Type
let getMember (name: string) (memberType: MemberTypes) (attr: BindingFlags) (declaringType: Type) =
let memberType =
if memberType &&& MemberTypes.NestedType = MemberTypes.NestedType then
memberType ||| MemberTypes.TypeInfo
else
memberType
declaringType.GetMembers(attr) |> Array.filter(fun m -> 0 <> (int(m.MemberType &&& memberType)) && m.Name = name)
let rec tryFindMember (name: string) (memberType: MemberTypes) (declaringType: Type) =
let bindingFlags = BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic
match declaringType |> getMember name memberType bindingFlags with
| [||] -> declaringType.GetInterfaces() |> Array.tryPick (tryFindMember name memberType)
| [|m|] -> Some m
| _ -> raise <| new AmbiguousMatchException(sprintf "Ambiguous match for member '%s'" name)
let getInstanceProperty (obj:obj) (nm:string) =
let p = (tryFindMember nm MemberTypes.Property <| obj.GetType()).Value :?> PropertyInfo
p.GetValue(obj, [||]) |> unbox
let setInstanceProperty (obj:obj) (nm:string) (v:obj) =
let p = (tryFindMember nm MemberTypes.Property <| obj.GetType()).Value :?> PropertyInfo
p.SetValue(obj, v, [||]) |> unbox
let callInstanceMethod0 (obj:obj) (typeArgs : Type []) (nm:string) =
let m = (tryFindMember nm MemberTypes.Method <| obj.GetType()).Value :?> MethodInfo
let m = match typeArgs with [||] -> m | _ -> m.MakeGenericMethod(typeArgs)
m.Invoke(obj, [||]) |> unbox
let callInstanceMethod1 (obj:obj) (typeArgs : Type []) (nm:string) (v:obj) =
let m = (tryFindMember nm MemberTypes.Method <| obj.GetType()).Value :?> MethodInfo
let m = match typeArgs with [||] -> m | _ -> m.MakeGenericMethod(typeArgs)
m.Invoke(obj, [|v|]) |> unbox
let callInstanceMethod3 (obj:obj) (typeArgs : Type []) (nm:string) (v1:obj) (v2:obj) (v3:obj) =
let m = (tryFindMember nm MemberTypes.Method <| obj.GetType()).Value :?> MethodInfo
let m = match typeArgs with [||] -> m | _ -> m.MakeGenericMethod(typeArgs)
m.Invoke(obj, [|v1;v2;v3|]) |> unbox
let colorPrintL (outWriter : TextWriter) opts layout =
let renderer =
{ new LayoutRenderer<NoResult,NoState> with
member r.Start () = NoState
member r.AddText z s =
let color =
match s.Tag with
| LayoutTag.Keyword -> ConsoleColor.White
| LayoutTag.TypeParameter
| LayoutTag.Alias
| LayoutTag.Class
| LayoutTag.Module
| LayoutTag.Interface
| LayoutTag.Record
| LayoutTag.Struct
| LayoutTag.Union
| LayoutTag.UnknownType -> ConsoleColor.Cyan
| LayoutTag.UnionCase
| LayoutTag.ActivePatternCase -> ConsoleColor.Magenta
| LayoutTag.StringLiteral -> ConsoleColor.Yellow
| LayoutTag.NumericLiteral -> ConsoleColor.Green
| _ -> Console.ForegroundColor
DoWithColor color (fun () -> outWriter.Write s.Text)
z
member r.AddBreak z n =
outWriter.WriteLine()
outWriter.Write (String.replicate n " ")
z
member r.AddTag z (tag,attrs,start) = z
member r.Finish z =
outWriter.WriteLine()
NoResult
}
layout
|> Internal.Utilities.StructuredFormat.Display.squash_layout opts
|> Layout.renderL renderer
|> ignore
outWriter.WriteLine()
//----------------------------------------------------------------------------
// 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
type EvaluationEventArgs(fsivalue : FsiValue option, symbolUse : FSharpSymbolUse, decl: FSharpImplementationFileDeclaration) =
inherit EventArgs()
member x.Name = symbolUse.Symbol.DisplayName
member x.FsiValue = fsivalue
member x.SymbolUse = symbolUse
member x.Symbol = symbolUse.Symbol
member x.ImplementationDeclaration = decl
[<AbstractClass>]
/// User-configurable information that changes how F# Interactive operates, stored in the 'fsi' object
/// and accessible via the programming model
type FsiEvaluationSessionHostConfig () =
let evaluationEvent = new Event<EvaluationEventArgs> ()
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract FormatProvider: System.IFormatProvider
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract FloatingPointFormat: string
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract AddedPrinters : Choice<(System.Type * (obj -> string)), (System.Type * (obj -> obj))> list
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract ShowDeclarationValues: bool
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract ShowIEnumerable: bool
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract ShowProperties : bool
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract PrintSize : int
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract PrintDepth : int
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract PrintWidth : int
/// Called by the evaluation session to ask the host for parameters to format text for output
abstract PrintLength : int
/// The evaluation session calls this to report the preferred view of the command line arguments after
/// stripping things like "/use:file.fsx", "-r:Foo.dll" etc.
abstract ReportUserCommandLineArgs : string [] -> unit
/// The evaluation session calls this to ask the host for the special console reader.
/// Returning 'Some' indicates a console is to be used, so some special rules apply.
///
/// A "console" gets used if
/// --readline- is specified (the default on Windows + .NET); and
/// not --fsi-server (which should always be combined with --readline-); and
/// GetOptionalConsoleReadLine() returns a Some
///
/// "Peekahead" occurs if --peekahead- is not specified (i.e. it is the default):
/// - If a console is being used then
/// - a prompt is printed early
/// - a background thread is created
/// - the GetOptionalConsoleReadLine() callback is used to read the first line
/// - Otherwise call inReader.Peek()
///
/// Further lines are read as follows:
/// - If a console is being used then use GetOptionalConsoleReadLine()
/// - Otherwise use inReader.ReadLine()
abstract GetOptionalConsoleReadLine : probeToSeeIfConsoleWorks: bool -> (unit -> string) option
/// The evaluation session calls this at an appropriate point in the startup phase if the --fsi-server parameter was given
abstract StartServer : fsiServerName:string -> unit
/// Called by the evaluation session to ask the host to enter a dispatch loop like Application.Run().
/// Only called if --gui option is used (which is the default).
/// Gets called towards the end of startup and every time a ThreadAbort escaped to the backup driver loop.
/// Return true if a 'restart' is required, which is a bit meaningless.
abstract EventLoopRun : unit -> bool
/// Request that the given operation be run synchronously on the event loop.
abstract EventLoopInvoke : codeToRun: (unit -> 'T) -> 'T
/// Schedule a restart for the event loop.
abstract EventLoopScheduleRestart : unit -> unit
/// Implicitly reference FSharp.Compiler.Interactive.Settings.dll
abstract UseFsiAuxLib : bool
/// Hook for listening for evaluation bindings
member x.OnEvaluation = evaluationEvent.Publish
member internal x.TriggerEvaluation (value, symbolUse, decl) =
evaluationEvent.Trigger (EvaluationEventArgs (value, symbolUse, decl) )
/// 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(fsi: FsiEvaluationSessionHostConfig, g: TcGlobals, generateDebugInfo, resolveAssemblyRef, outWriter: TextWriter) =
/// 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 (TaggedTextOps.tagText "[")) ^^
sepListL (rightL (TaggedTextOps.tagText ";")) itemLs ^^
(rightL (TaggedTextOps.tagText "]"))
Some(wordL (TaggedTextOps.tagText "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 (TaggedTextOps.tagText 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 = g.ilg ; generatePdb = generateDebugInfo; resolveAssemblyRef=resolveAssemblyRef; tryFindSysILTypeRef=g.TryFindSysILTypeRef }
{ 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, ty)
| PrintExpr ->
anyToLayoutCall.AnyToLayout(opts, x, ty)
with
#if !FX_REDUCED_EXCEPTIONS
| :? ThreadAbortException -> Layout.wordL (TaggedTextOps.tagText "")
#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 (TaggedTextOps.tagText "")
/// 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
/// Format a value
member valuePrinter.FormatValue (obj:obj, objTy) =
let opts = valuePrinter.GetFsiPrintOptions()
let lay = valuePrinter.PrintValue (FsiValuePrinterMode.PrintExpr, opts, obj, objTy)
Internal.Utilities.StructuredFormat.Display.layout_to_string opts lay
/// Fetch the saved value of an expression out of the 'it' register and show it.
member valuePrinter.InvokeExprPrinter (denv, emEnv, ilxGenerator: IlxAssemblyGenerator, vref) =
let opts = valuePrinter.GetFsiPrintOptions()
let res = ilxGenerator.LookupGeneratedValue (valuePrinter.GetEvaluationContext emEnv, vref)
let rhsL =
match res with
| None -> None
| Some (obj,objTy) ->
let lay = valuePrinter.PrintValue (FsiValuePrinterMode.PrintExpr, opts, obj, objTy)
if isEmptyL lay then None else Some lay // suppress empty layout
let denv = { denv with suppressMutableKeyword = true } // suppress 'mutable' in 'val mutable it = ...'
let fullL =
if Option.isNone rhsL || isEmptyL rhsL.Value then
NicePrint.prettyLayoutOfValOrMemberNoInst denv vref (* the rhs was suppressed by the printer, so no value to print *)
else
(NicePrint.prettyLayoutOfValOrMemberNoInst denv vref ++ wordL (TaggedTextOps.tagText "=")) --- rhsL.Value
Utilities.colorPrintL outWriter opts fullL
/// 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, err) =
Utilities.ignoreAllErrors (fun () ->
let isError = true
DoWithErrorColor isError (fun () ->
errorWriter.WriteLine();
writeViaBufferWithEnvironmentNewLines errorWriter (OutputDiagnosticContext " " syphon.GetLine) err;
writeViaBufferWithEnvironmentNewLines errorWriter (OutputDiagnostic (tcConfig.implicitIncludeDir,tcConfig.showFullPaths,tcConfig.flatErrors,tcConfig.errorStyle,isError)) err;
errorWriter.WriteLine()
errorWriter.WriteLine()
errorWriter.Flush()))
/// 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 errorCount = 0
member x.SetError() =
errorCount <- 1
member x.ResetErrorCount() = (errorCount <- 0)
override x.DiagnosticSink(err, isError) =
if isError || ReportWarningAsError tcConfigB.errorSeverityOptions err then
fsiStdinSyphon.PrintError(tcConfigB,err)
errorCount <- errorCount + 1
if tcConfigB.abortOnError then exit 1 (* non-zero exit code *)
// STOP ON FIRST ERROR (AVOIDS PARSER ERROR RECOVERY)
raise StopProcessing
else
DoWithErrorColor isError (fun () ->
if ReportWarning tcConfigB.errorSeverityOptions err then
fsiConsoleOutput.Error.WriteLine()
writeViaBufferWithEnvironmentNewLines fsiConsoleOutput.Error (OutputDiagnosticContext " " fsiStdinSyphon.GetLine) err
writeViaBufferWithEnvironmentNewLines fsiConsoleOutput.Error (OutputDiagnostic (tcConfigB.implicitIncludeDir,tcConfigB.showFullPaths,tcConfigB.flatErrors,tcConfigB.errorStyle,isError)) err
fsiConsoleOutput.Error.WriteLine()
fsiConsoleOutput.Error.WriteLine()
fsiConsoleOutput.Error.Flush())
override x.ErrorCount = errorCount
type ErrorLogger with
member x.CheckForErrors() = (x.ErrorCount > 0)
/// A helper function to check if its time to abort
member x.AbortOnError(fsiConsoleOutput:FsiConsoleOutput) =
if x.ErrorCount > 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(fsi: FsiEvaluationSessionHostConfig, argv: string[], tcConfigB, fsiConsoleOutput: FsiConsoleOutput) =
let mutable enableConsoleKeyProcessing =
// Mono on Win32 doesn't implement correct console processing
not (runningOnMono && System.Environment.OSVersion.Platform = System.PlatformID.Win32NT)
let mutable gui = not runningOnMono // override via "--gui", on by default except when on Mono
#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 precede 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");
// Disables interaction (to be used by libraries embedding FSI only!)
CompilerOption("noninteractive","", OptionUnit (fun () -> interact <- false), None, None); // "Deprecated, use --exec instead"
])
]
/// 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()));
CompilerOption("shadowcopyreferences", tagNone, OptionSwitch(fun flag -> tcConfigB.shadowCopyReferences <- flag = OptionSwitch.On), None, Some(FSIstrings.SR.shadowCopyReferences()));
]);
]
/// 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; failwithf "Error creating evaluation session: %A" e
inputFilesAcc
do
if tcConfigB.utf8output then
let prev = Console.OutputEncoding
Console.OutputEncoding <- System.Text.Encoding.UTF8
#if FX_NO_APP_DOMAINS
ignore prev
#else
System.AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> Console.OutputEncoding <- prev)
#endif
do
let firstArg =
match sourceFiles with
| [] -> argv.[0]
| _ -> fst (List.head (List.rev sourceFiles) )
let args = Array.ofList (firstArg :: explicitArgs)
fsi.ReportUserCommandLineArgs 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
/// Set the current ui culture for the current thread.
#if FX_LCIDFROMCODEPAGE
let internal SetCurrentUICultureForThread (lcid : int option) =
let culture = Thread.CurrentThread.CurrentUICulture
match lcid with
| Some n -> Thread.CurrentThread.CurrentUICulture <- new CultureInfo(n)
| None -> ()
{ new IDisposable with member x.Dispose() = Thread.CurrentThread.CurrentUICulture <- culture }
#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 !FX_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 modifications 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 modifications 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 LOGGING_GUI
if not !successful then
System.Windows.Forms.MessageBox.Show(FSIstrings.SR.fsiConsoleProblem()) |> ignore
#endif
#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 service\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(fsi: FsiEvaluationSessionHostConfig, fsiOptions: FsiCommandLineOptions, inReader: TextReader, outWriter: TextWriter) =
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 then
fsi.GetOptionalConsoleReadLine(fsiOptions.ProbeToSeeIfConsoleWorks)
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.IsNone)
/// 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());
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
//----------------------------------------------------------------------------
type internal FsiInteractionStepStatus =
| CtrlC
| EndOfFile
| Completed of option<FsiValue>
| CompletedWithReportedError of exn
[<AutoSerializable(false)>]
[<NoEquality; NoComparison>]
type internal FsiDynamicCompilerState =
{ optEnv : Optimizer.IncrementalOptimizationEnv
emEnv : ILRuntimeWriter.emEnv
tcGlobals : TcGlobals
tcState : TcState
tcImports : TcImports
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
(fsi: FsiEvaluationSessionHostConfig,
timeReporter : FsiTimeReporter,
tcConfigB: TcConfigBuilder,
tcLockObject : obj,
outWriter: TextWriter,
tcImports: TcImports,
tcGlobals: TcGlobals,
fsiOptions : FsiCommandLineOptions,
fsiConsoleOutput : FsiConsoleOutput,
fsiCollectible: bool,
niceNameGen,
resolveAssemblyRef) =
let ilGlobals = tcGlobals.ilg
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(fsi, tcGlobals, generateDebugInfo, resolveAssemblyRef, outWriter)
let assemblyBuilder,moduleBuilder = ILRuntimeWriter.mkDynamicAssemblyAndModule (assemblyName, tcConfigB.optSettings.localOpt(), generateDebugInfo, fsiCollectible)
let rangeStdin = rangeN Lexhelp.stdinMockFilename 0
//let _writer = moduleBuilder.GetSymWriter()
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 = CompilerTarget.Dll) tcConfigB.subsystemVersion tcConfigB.useHighEntropyVA (mkILTypeDefs codegenResults.ilTypeDefs) None None 0x0 (mkILExportedTypes []) ""
{ mainModule
with Manifest =
(let man = mainModule.ManifestOfAssembly
Some { man with CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs codegenResults.ilAssemAttrs) }) }
let ProcessInputs (ctok, errorLogger: ErrorLogger, 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 =