This is a design note on the FSharpChecker component and its caches. See also the notes on the FSharpChecker operations queue
-
Each FSharpChecker object maintains a set of caches. These are
-
-
-
scriptClosureCache - an MRU cache of default size projectCacheSize that caches the
-computation of GetProjectOptionsFromScript. This computation can be lengthy as it can involve processing the transitive closure
-of all #load directives, which in turn can mean parsing an unbounded number of script files
-
-
-
incrementalBuildersCache - an MRU cache of projects where a handle is being kept to their incremental checking state,
-of default size projectCacheSize (= 3 unless explicitly set as a parameter).
-The "current background project" (see the FSharpChecker operations queue)
-will be one of these projects. When analyzing large collections of projects, this cache usually occupies by far the most memory.
-Increasing the size of this cache can dramatically decrease incremental computation of project-wide checking, or of checking
-individual files within a project, but can very greatly increase memory usage.
-
-
braceMatchCache - an MRU cache of size braceMatchCacheSize (default = 5) keeping the results of calls to MatchBraces, keyed by filename, source and project options.
-
-
parseFileCache - an MRU cache of size parseFileCacheSize (default = 2) keeping the results of ParseFile,
-keyed by filename, source and project options.
-
-
-
checkFileInProjectCache - an MRU cache of size incrementalTypeCheckCacheSize (default = 5) keeping the results of
-ParseAndCheckFileInProject, CheckFileInProject and/or CheckFileInProjectIfReady. This is keyed by filename, file source
-and project options. The results held in this cache are only returned if they would reflect an accurate parse and check of the
-file.
-
-
getToolTipTextCache - an aged lookup cache of strong size getToolTipTextSize (default = 5) computing the results of GetToolTipText.
-
-
ilModuleReaderCache - an aged lookup of weak references to "readers" for references .NET binaries. Because these
-are all weak references, you can generally ignore this cache, since its entries will be automatically collected.
-Strong references to binary readers will be kept by other FCS data structures, e.g. any project checkers, symbols or project checking results.
-
In more detail, the bytes for referenced .NET binaries are read into memory all at once, eagerly. Files are not left
-open or memory-mapped when using FSharpChecker (as opposed to FsiEvaluationSession, which loads assemblies using reflection).
-The purpose of this cache is mainly to ensure that while setting up compilation, the reads of mscorlib, FSharp.Core and so on
-amortize cracking the DLLs.
-
-
-
frameworkTcImportsCache - an aged lookup of strong size 8 which caches the process of setting up type checking against a set of system
-components (e.g. a particular version of mscorlib, FSharp.Core and other system DLLs). These resources are automatically shared between multiple
-project checkers which happen to reference the same set of system assemblies.
-
-
-
Profiling the memory used by the various caches can be done by looking for the corresponding static roots in memory profiling traces.
-
The sizes of some of these caches can be adjusted by giving parameters to FSharpChecker. Unless otherwise noted,
-the cache sizes above indicate the "strong" size of the cache, where memory is held regardless of the memory
-pressure on the system. Some of the caches can also hold "weak" references which can be collected at will by the GC.
-
-
Note: Because of these caches, you should generally use one global, shared FSharpChecker for everything in an IDE application.
Version 1.4.0.8 added a "maximum memory" limit specified by the MaxMemory property on FSharpChecker (in MB). If an FCS project operation
-is performed (see CheckMaxMemoryReached in service.fs) and System.GC.GetTotalMemory(false) reports a figure greater than this, then
-the strong sizes of all FCS caches are reduced to either 0 or 1. This happens for the remainder of the lifetime of the FSharpChecker object.
-In practice this will still make tools like the Visual Studio F# Power Tools usable, but some operations like renaming across multiple
-projects may take substantially longer.
-
By default the maximum memory trigger is disabled, see maxMBDefault in service.fs.
-
Reducing the FCS strong cache sizes does not guarantee there will be enough memory to continue operations - even holding one project
-strongly may exceed a process memory budget. It just means FCS may hold less memory strongly.
-
If you do not want the maximum memory limit to apply then set MaxMemory to System.Int32.MaxValue.
In this design note, you learned that the FSharpChecker component keeps a set of caches in order to support common
-incremental analysis scenarios reasonably efficiently. They correspond roughly to the original caches and sizes
-used by the Visual F# Tools, from which the FSharpChecker component derives.
-
In long running, highly interactive, multi-project scenarios you should carefully
-consider the cache sizes you are using and the tradeoffs involved between incremental multi-project checking and memory usage.
You can also compile to a dynamic assembly, which uses the F# Interactive code generator.
-This can be useful if you are, for example, in a situation where writing to the file system
-is not really an option.
-
You still have to pass the "-o" option to name the output file, but the output file is not actually written to disk.
-
The 'None' option indicates that the initialization code for the assembly is not executed.
-
1:
- 2:
- 3:
- 4:
- 5:
- 6:
- 7:
- 8:
- 9:
-10:
-
-
leterrors2,exitCode2,dynAssembly2=
- checker.CompileToDynamicAssembly([|"-o";fn3;"-a";fn2|],execute=None)
- |>Async.RunSynchronously
-
-(*
-Passing 'Some' for the 'execute' parameter executes the initialization code for the assembly.
-*)
-leterrors3,exitCode3,dynAssembly3=
- checker.CompileToDynamicAssembly([|"-o";fn3;"-a";fn2|],Some(stdout,stderr))
- |>Async.RunSynchronously
-
-
-
-
-
namespace System
-
namespace System.IO
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
When building applications or plug-in components which use FSharp.Compiler.Service.dll, you will normally also
-include a copy of FSharp.Core.dll as part of your application.
-
For example, if you build a HostedCompiler.exe, you will normally place an FSharp.Core.dll (say 4.3.1.0) alongside
-your HostedCompiler.exe.
The FSharp.Compiler.Service.dll component depends on FSharp.Core 4.4.0.0. Normally your application will target
-a later version of FSharp.Core, and you may need a binding redirect to ensure
-that other versions of FSharp.Core forward to the final version of FSharp.Core.dll your application uses.
-Binding redirect files are normally generated automatically by build tools. If not, you can use one like this
-(if your tool is called HostedCompiler.exe, the binding redirect file is called HostedCompiler.exe.config)
-
Some other dependencies may also need to be reconciled and forwarded.
The FSharp.Compiler.Service component can be used to do more or less any sort of F# compilation.
-In particular you can reference an explicit FSharp.Core and/or framework
-assemblies in the command line arguments (different to the FSharp.Core and a .NET Framework being used to run your tool).
-
To target a specific FSharp.Core and/or .NET Framework assemblies, use the --noframework argument
-and the appropriate command-line arguments:
You will need to determine the location of these assemblies. The easiest way to locate these DLLs in a cross-platform way and
-convert them to command-line arguments is to crack an F# project file.
-Alternatively you can compute SDK paths yourself, and some helpers to do this are in the tests for FSharp.Compiler.Service.dll.
If you do not explicitly reference an FSharp.Core.dll from an SDK location, or if you are processing a script
-using FsiEvaluationSession or GetCheckOptionsFromScriptRoot, then an implicit reference to FSharp.Core will be made
-by the following choice:
-
-
The version of FSharp.Core.dll statically referenced by the host assembly returned by System.Reflection.Assembly.GetEntryAssembly().
-
-
If there is no static reference to FSharp.Core in the host assembly, then
-
-
For FSharp.Compiler.Service 1.4.0.x above (F# 4.0 series), a reference to FSharp.Core version 4.4.0.0 is added
There is one main component, FSharp.Compiler.Service.dll.
-The main aim is to have a stable and documented fork of the main compiler that allows various
-tools to share this common code.
-This component allows embedding F# Interactive as a service and contains a number of
-modifications to the source code of fsi.exe that adds EvalExpression and EvalInteraction functions.
-
This repo should be identical to 'fsharp' except:
-
-
-
Changes for building FSharp.Compiler.Service.dll, notably
-
-
Change the assembly name
-
Only build FSharp.Compiler.Service.dll
-
No bootstrap or proto compiler is used - an installed F# compiler is assumed
-
-
-
-
Build script using FAKE that builds everything, produces NuGet package and
-generates documentation, files for publishing NuGet packages etc.
-(following F# project scaffold)
-
-
-
Changes to compiler source code to expose new functionality; Changes to the
-F# Interactive service to implement the evaluation functions.
-
-
Additions to compiler source code which improve the API for the use of F# editing clients
-
Additions to compiler source code which add new functionality to the compiler service API
-
-
If language or compiler additions are committed to fsharp/fsharp, they should be merged into
-this repo and a new NuGet package released.
The build process follows the standard recommended by F# project scaffold
-If you want to build the project yourself then you can follow these instructions:
Now follow build everything by running build.cmd (Windows) or build.sh (Linux + Mac OS).
-The output will be located in the bin directory. If you also wish to build the documentation
-and NuGet package, run build Release (this also attempts to publish the documentation to
-GitHub, which only works if you have access to the GitHub repository).
This tutorial demonstrates how to use the editor services provided by the F# compiler.
-This API is used to provide auto-complete, tool-tips, parameter info help, matching of
-brackets and other functions in F# editors including Visual Studio, Xamarin Studio and Emacs
-(see fsharpbindings project for more information).
-Similarly to the tutorial on using untyped AST, we start by
-getting the InteractiveChecker object.
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
As in the previous tutorial (using untyped AST), we start by referencing
-FSharp.Compiler.Service.dll, opening the relevant namespace and creating an instance
-of InteractiveChecker:
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-8:
-9:
-
-
// Reference F# compiler API
-#r"FSharp.Compiler.Service.dll"
-
-openSystem
-openFSharp.Compiler.SourceCodeServices
-openFSharp.Compiler.Text
-
-// Create an interactive checker instance
-letchecker=FSharpChecker.Create()
-
-
-
-
As previously, we use GetProjectOptionsFromScriptRoot to get a context
-where the specified input is the only file passed to the compiler (and it is treated as a
-script file or stand-alone F# source code).
// Sample input as a multi-line string
-letinput=
- """
- open System
-
- let foo() =
- let msg = String.Concat("Hello"," ","world")
- if true then
- printfn "%s" msg.
- """
-// Split the input & define file name
-letinputLines=input.Split('\n')
-letfile="/home/user/Test.fsx"
-
-letprojOptions,errors=
- checker.GetProjectOptionsFromScript(file,SourceText.ofStringinput)
- |>Async.RunSynchronously
-
-letparsingOptions,_errors=checker.GetParsingOptionsFromProjectOptions(projOptions)
-
-
-
-
To perform type checking, we first need to parse the input using
-ParseFile, which gives us access to the untyped AST. However,
-then we need to call CheckFileInProject to perform the full type checking. This function
-also requires the result of ParseFileInProject, so the two functions are often called
-together.
Before we look at the interesting operations provided by TypeCheckResults, we
-need to run the type checker on a sample input. On F# code with errors, you would get some type checking
-result (but it may contain incorrectly "guessed" results).
-
1:
-2:
-3:
-4:
-
-
// Perform type checking
-letcheckFileAnswer=
- checker.CheckFileInProject(parseFileResults,file,0,SourceText.ofStringinput,projOptions)
- |>Async.RunSynchronously
-
-
-
-
Alternatively you can use ParseAndCheckFileInProject to check both in one step:
The function returns both the untyped parse result (which we do not use in this
-tutorial), but also a CheckFileAnswer value, which gives us access to all
-the interesting functionality...
-
1:
-2:
-3:
-4:
-
-
letcheckFileResults=
- matchcheckFileAnswerwith
- |FSharpCheckFileAnswer.Succeeded(res)->res
- |res->failwithf"Parsing did not finish... (%A)"res
-
-
-
-
Here, we type check a simple function that (conditionally) prints "Hello world".
-On the last line, we leave an additional dot in msg. so that we can get the
-completion list on the msg value (we expect to see various methods on the string
-type there).
Let's now look at some of the API that is exposed by the TypeCheckResults type. In general,
-this is the type that lets you implement most of the interesting F# source code editor services.
To get a tool tip, you can use GetToolTipTextAlternate method. The method takes a line number and character
-offset. Both of the numbers are zero-based. In the sample code, we want to get tooltip for the foo
-function that is defined on line 3 (line 0 is blank) and the letter f starts at index 7 (the tooltip
-would work anywhere inside the identifier).
-
In addition, the method takes a tag of token which is typically IDENT, when getting tooltip for an
-identifier (the other option lets you get tooltip with full assembly location when using #r "...").
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-
-
// Get tag of the IDENT token to be used as the last argument
-openFSharp.Compiler
-letidentToken=FSharpTokenTag.Identifier
-
-// Get tool tip at the specified location
-lettip=checkFileResults.GetToolTipText(4,7,inputLines.[1],["foo"],identToken)
-printfn"%A"tip
-
-
-
-
-
NOTE:GetToolTipTextAlternate is an alternative name for the old GetToolTipText. The old GetToolTipText was
-deprecated because it accepted zero-based line numbers. At some point it will be removed, and GetToolTipTextAlternate will be renamed back to GetToolTipText.
-
-
Aside from the location and token kind, the function also requires the current contents of the line
-(useful when the source code changes) and a Names value, which is a list of strings representing
-the current long name. For example to get tooltip for the Random identifier in a long name
-System.Random, you would use location somewhere in the string Random and you would pass
-["System"; "Random"] as the Names value.
-
The returned value is of type ToolTipText which contains a discriminated union ToolTipElement.
-The union represents different kinds of tool tips that you can get from the compiler.
The next method exposed by TypeCheckResults lets us perform auto-complete on a given location.
-This can be called on any identifier or in any scope (in which case you get a list of names visible
-in the scope) or immediately after . to get a list of members of some object. Here, we get a
-list of members of the string value msg.
-
To do this, we call GetDeclarationListInfo with the location of the . symbol on the last line
-(ending with printfn "%s" msg.). The offsets are one-based, so the location is 7, 23.
-We also need to specify a function that says that the text has not changed and the current identifier
-where we need to perform the completion.
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-8:
-9:
-
-
// Get declarations (autocomplete) for a location
-letdecls=
- checkFileResults.GetDeclarationListInfo
- (SomeparseFileResults,7,inputLines.[6],PartialLongName.Empty23,(fun()->[]),fun_->false)
- |>Async.RunSynchronously
-
-// Print the names of available items
-foritemindecls.Itemsdo
- printfn" - %s"item.Name
-
-
-
-
-
NOTE:v is an alternative name for the old GetDeclarations. The old GetDeclarations was
-deprecated because it accepted zero-based line numbers. At some point it will be removed, and GetDeclarationListInfo will be renamed back to GetDeclarations.
-
-
When you run the code, you should get a list containing the usual string methods such as
-Substring, ToUpper, ToLower etc. The fourth argument of GetDeclarations, here ([], "msg"),
-specifies the context for the auto-completion. Here, we want a completion on a complete name
-msg, but you could for example use (["System"; "Collections"], "Generic") to get a completion list
-for a fully qualified namespace.
The next common feature of editors is to provide information about overloads of a method. In our
-sample code, we use String.Concat which has a number of overloads. We can get the list using
-GetMethods operation. As previously, this takes zero-indexed offset of the location that we are
-interested in (here, right at the end of the String.Concat identifier) and we also need to provide
-the identifier again (so that the compiler can provide up-to-date information when the source code
-changes):
-
1:
- 2:
- 3:
- 4:
- 5:
- 6:
- 7:
- 8:
- 9:
-10:
-
-
// Get overloads of the String.Concat method
-letmethods=
- checkFileResults.GetMethods(5,27,inputLines.[4],Some["String";"Concat"])
- |>Async.RunSynchronously
-
-// Print concatenated parameter lists
-formiinmethods.Methodsdo
- [forpinmi.Parameters->p.Display]
- |>String.concat", "
- |>printfn"%s(%s)"methods.MethodName
-
-
-
-
The code uses the Display property to get the annotation for each parameter. This returns information
-such as arg0: obj or params args: obj[] or str0: string, str1: string. We concatenate the parameters
-and print a type annotation with the method name.
You may have noticed that CheckFileInProject is an asynchronous operation.
-This indicates that type checking of F# code can take some time.
-The F# compiler performs the work in background (automatically) and when
-we call CheckFileInProject method, it returns an asynchronous operation.
-
There is also the CheckFileInProjectIfReady method. This returns immediately if the
-type checking operation can't be started immediately, e.g. if other files in the project
-are not yet type-checked. In this case, a background worker might choose to do other
-work in the meantime, or give up on type checking the file until the FileTypeCheckStateIsDirty event
-is raised.
-
-
The fsharpbinding project has more advanced
-example of handling the background work where all requests are sent through an F# agent.
-This may be a more appropriate for implementing editor support.
The CheckFileAnswer object contains other useful methods that were not covered in this tutorial. You
-can use it to get location of a declaration for a given identifier, additional colorization information
-(the F# 3.1 colorizes computation builder identifiers & query operators) and others.
Finally, if you are implementing an editor support for an editor that cannot directly call .NET API,
-you can call many of the methods discussed here via a command line interface that is available in the
-FSharp.AutoComplete project.
-
-
namespace System
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Text
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
type PartialLongName = { QualifyingIdents: string list PartialIdent: string EndColumn: int LastDotPos: int option } static member Empty : endColumn:int -> PartialLongName
-
static member PartialLongName.Empty : endColumn:int -> PartialLongName
-
val item : FSharpDeclarationListItem
-
property FSharpDeclarationListInfo.Items: FSharpDeclarationListItem [] with get
-
property FSharpDeclarationListItem.Name: string with get
-
val methods : FSharpMethodGroup
-
member FSharpCheckFileResults.GetMethods : line:int * colAtEndOfNames:int * lineText:string * names:string list option * ?userOpName:string -> Async<FSharpMethodGroup>
-
val mi : FSharpMethodGroupItem
-
property FSharpMethodGroup.Methods: FSharpMethodGroupItem [] with get
-
val p : FSharpMethodGroupItemParameter
-
property FSharpMethodGroupItem.Parameters: FSharpMethodGroupItemParameter [] with get
-
property FSharpMethodGroupItemParameter.Display: string with get
-
Multiple items type String = new : value:char[] -> string + 8 overloads member Chars : int -> char member Clone : unit -> obj member CompareTo : value:obj -> int + 1 overload member Contains : value:string -> bool + 3 overloads member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit member EndsWith : value:string -> bool + 3 overloads member Equals : obj:obj -> bool + 2 overloads member GetEnumerator : unit -> CharEnumerator member GetHashCode : unit -> int + 1 overload ...
The FSharp.Compiler.Service component has a global variable
-representing the file system. By setting this variable you can host the compiler in situations where a file system
-is not available.
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published.
In this tutorial, we've seen how to globally customize the view of the file system used by the FSharp.Compiler.Service
-component.
-
At the time of writing, the following System.IO operations are not considered part of the virtualized file system API.
-Future iterations on the compiler service implementation may add these to the API.
-
-
Path.Combine
-
Path.DirectorySeparatorChar
-
Path.GetDirectoryName
-
Path.GetFileName
-
Path.GetFileNameWithoutExtension
-
Path.HasExtension
-
Path.GetRandomFileName (used only in generation compiled win32 resources in assemblies)
-
-
NOTE: Several operations in the SourceCodeServices API accept the contents of a file to parse
-or check as a parameter, in addition to a file name. In these cases, the file name is only used for
-error reporting.
-
NOTE: Type provider components do not use the virtualized file system.
-
NOTE: The compiler service may use MSBuild for assembly resolutions unless --simpleresolution is
-provided. When using the FileSystem API you will normally want to specify --simpleresolution as one
-of your compiler flags. Also specify --noframework. You will need to supply explicit resolutions of all
-referenced .NET assemblies.
-
-
namespace System
-
namespace System.IO
-
namespace System.Collections
-
namespace System.Collections.Generic
-
namespace System.Text
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.AbstractIL
-
namespace FSharp.Compiler.AbstractIL.Internal
-
module Library
from FSharp.Compiler.AbstractIL.Internal
-
val defaultFileSystem : IFileSystem
-
module Shim
from FSharp.Compiler.AbstractIL.Internal.Library
-
val mutable FileSystem : IFileSystem
-
val fileName1 : string
-
val fileName2 : string
-
Multiple items type MyFileSystem = interface IFileSystem new : unit -> MyFileSystem
-------------------- new : unit -> MyFileSystem
-
val file1 : string
-
val file2 : string
-
val files : IDictionary<string,string>
-
val dict : keyValuePairs:seq<'Key * 'Value> -> IDictionary<'Key,'Value> (requires equality)
-
type IFileSystem = interface abstract member AssemblyLoad : assemblyName:AssemblyName -> Assembly abstract member AssemblyLoadFrom : fileName:string -> Assembly abstract member FileDelete : fileName:string -> unit abstract member FileStreamCreateShim : fileName:string -> Stream abstract member FileStreamReadShim : fileName:string -> Stream abstract member FileStreamWriteExistingShim : fileName:string -> Stream abstract member GetFullPathShim : fileName:string -> string abstract member GetLastWriteTimeShim : fileName:string -> DateTime abstract member GetTempPathShim : unit -> string abstract member IsInvalidPathShim : filename:string -> bool ... end
Multiple items type MemoryStream = inherit Stream new : unit -> MemoryStream + 6 overloads member CanRead : bool member CanSeek : bool member CanWrite : bool member Capacity : int with get, set member CopyTo : destination:Stream * bufferSize:int -> unit member CopyToAsync : destination:Stream * bufferSize:int * cancellationToken:CancellationToken -> Task member Flush : unit -> unit member FlushAsync : cancellationToken:CancellationToken -> Task member GetBuffer : unit -> byte[] ...
type Encoding = member BodyName : string member Clone : unit -> obj member CodePage : int member DecoderFallback : DecoderFallback with get, set member EncoderFallback : EncoderFallback with get, set member EncodingName : string member Equals : value:obj -> bool member GetByteCount : chars:char[] -> int + 5 overloads member GetBytes : chars:char[] -> byte[] + 7 overloads member GetCharCount : bytes:byte[] -> int + 3 overloads ...
type Stream = inherit MarshalByRefObject member BeginRead : buffer:byte[] * offset:int * count:int * callback:AsyncCallback * state:obj -> IAsyncResult member BeginWrite : buffer:byte[] * offset:int * count:int * callback:AsyncCallback * state:obj -> IAsyncResult member CanRead : bool member CanSeek : bool member CanTimeout : bool member CanWrite : bool member Close : unit -> unit member CopyTo : destination:Stream -> unit + 1 overload member CopyToAsync : destination:Stream -> Task + 3 overloads member Dispose : unit -> unit ...
-
abstract member IFileSystem.FileStreamReadShim : fileName:string -> Stream
-
val __ : MyFileSystem
-
abstract member IFileSystem.FileStreamCreateShim : fileName:string -> Stream
-
abstract member IFileSystem.FileStreamWriteExistingShim : fileName:string -> Stream
-
abstract member IFileSystem.ReadAllBytesShim : fileName:string -> byte []
-
abstract member IFileSystem.GetTempPathShim : unit -> string
-
abstract member IFileSystem.GetLastWriteTimeShim : fileName:string -> DateTime
-
abstract member IFileSystem.GetFullPathShim : fileName:string -> string
-
abstract member IFileSystem.IsInvalidPathShim : filename:string -> bool
-
abstract member IFileSystem.IsPathRootedShim : path:string -> bool
-
abstract member IFileSystem.IsStableFileHeuristic : fileName:string -> bool
-
IDictionary.ContainsKey(key: string) : bool
-
abstract member IFileSystem.SafeExists : fileName:string -> bool
-
abstract member IFileSystem.FileDelete : fileName:string -> unit
-
abstract member IFileSystem.AssemblyLoadFrom : fileName:string -> Reflection.Assembly
-
val assemblyName : Reflection.AssemblyName
-
abstract member IFileSystem.AssemblyLoad : assemblyName:Reflection.AssemblyName -> Reflection.Assembly
-
val myFileSystem : MyFileSystem
-
namespace FSharp.Compiler.SourceCodeServices
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
type Environment = static member CommandLine : string static member CurrentDirectory : string with get, set static member CurrentManagedThreadId : int static member Exit : exitCode:int -> unit static member ExitCode : int with get, set static member ExpandEnvironmentVariables : name:string -> string static member FailFast : message:string -> unit + 1 overload static member GetCommandLineArgs : unit -> string[] static member GetEnvironmentVariable : variable:string -> string + 1 overload static member GetEnvironmentVariables : unit -> IDictionary + 1 overload ... nested type SpecialFolder nested type SpecialFolderOption
-
property Environment.OSVersion: OperatingSystem with get
-
property OperatingSystem.Platform: PlatformID with get
The F# compiler services package is a component derived from the F# compiler source code that
-exposes additional functionality for implementing F# language bindings, additional
-tools based on the compiler or refactoring tools. The package also includes F#
-interactive service that can be used for embedding F# scripting into your applications.
The project currently exposes the following services that are tested & documented on this page.
-The libraries contain additional public API that can be used, but is not documented here.
-
-
-
F# Language tokenizer - turns any F# source code into a stream of tokens.
-Useful for implementing source code colorization and basic tools. Correctly handle nested
-comments, strings etc.
-
-
-
Processing untyped AST - allows accessing the untyped abstract syntax tree (AST).
-This represents parsed F# syntax without type information and can be used to implement code formatting
-and various simple processing tasks.
-
-
-
Using editor (IDE) services - expose functionality for auto-completion, tool-tips,
-parameter information etc. These functions are useful for implementing F# support for editors
-and for getting some type information for F# code.
Working with resolved expressions - services related to working with
-type-checked expressions and declarations, where names have been resolved to symbols.
Hosting F# interactive - allows calling F# interactive as a .NET library
-from your .NET code. You can use this API to embed F# as a scripting language in your projects.
File system API - the FSharp.Compiler.Service component has a global variable
-representing the file system. By setting this variable you can host the compiler in situations where a file system
-is not available.
-
-
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
This project is a fork of the fsharp/fsharp which has been
-modified to expose additional internals useful for creating editors and F# tools and also for
-embedding F# interactive.
-
The F# source code is copyright by Microsoft Corporation and contributors, the extensions have been
-implemented by Dave Thomas, Anh-Dung Phan, Tomas Petricek and other contributors.
This tutorial demonstrates how to embed F# interactive in your application. F# interactive
-is an interactive scripting environment that compiles F# code into highly efficient IL code
-and executes it on the fly. The F# interactive service allows you to embed F# evaluation in
-your application.
-
-
NOTE: There is a number of options for embedding F# Interactive. The easiest one is to use the
-fsi.exe process and communicate with it using standard input and standard output. In this
-tutorial, we look at calling F# Interactive directly through .NET API. However, if you have
-no control over the input, it is a good idea to run F# interactive in a separate process.
-One reason is that there is no way to handle StackOverflowException and so a poorly written
-script can terminate the host process. Remember that while calling F# Interactive through .NET API,
---shadowcopyreferences option will be ignored. For detailed discussion, please take a look at
-this thread.
-NOTE: If FsiEvaluationSession.Create fails with an error saying that FSharp.Core.dll cannot be found,
-add the FSharp.Core.sigdata and FSharp.Core.optdata files. More info here.
-
-
However, the F# interactive service is still useful, because you might want to wrap it in your
-own executable that is then executed (and communicates with the rest of your application), or
-if you only need to execute limited subset of F# code (e.g. generated by your own DSL).
To communicate with F# interactive, we need to create streams that represent input and
-output. We will use those later to read the output printed as a result of evaluating some
-F# code that prints:
The F# interactive service exposes several methods that can be used for evaluation. The first
-is EvalExpression which evaluates an expression and returns its result. The result contains
-the returned value (as obj) and the statically inferred type of the value:
-
1:
-2:
-3:
-4:
-5:
-
-
/// Evaluate expression & return the result
-letevalExpressiontext=
- matchfsiSession.EvalExpression(text)with
- |Somevalue->printfn"%A"value.ReflectionValue
- |None->printfn"Got no result!"
-
-
-
-
This takes a string as an argument and evaluates (i.e. executes) it as F# code.
-
1:
-
-
evalExpression"42+1"// prints '43'
-
-
-
-
This can be used in a strongly typed way as follows:
The EvalInteraction method can be used to evaluate side-effectful operations
-such as printing, declarations, or other interactions that are not valid F# expressions, but can be entered in
-the F# Interactive console. Such commands include #time "on" (and other directives), open System
-all declarations and other top-level statements. The code
-does not require ;; at the end. Just enter the code that you want to execute:
-
1:
-
-
fsiSession.EvalInteraction"printfn \"bye\""
-
-
-
-
The EvalScript method allows to evaluate a complete .fsx script.
EvalExpression, EvalInteraction and EvalScript are awkward if the
-code has type checking warnings or errors, or if evaluation fails with an exception.
-In these cases you can use EvalExpressionNonThrowing, EvalInteractionNonThrowing
-and EvalScriptNonThrowing. These return a tuple of a result and an array of FSharpErrorInfo values.
-These represent the errors and warnings. The result part is a Choice<_,_> between an actual
-result and an exception.
-
The result part of EvalExpression and EvalExpressionNonThrowing is an optional FSharpValue.
-If that value is not present then it just indicates that the expression didn't have a tangible
-result that could be represented as a .NET object. This situation shouldn't actually
-occur for any normal input expressions, and only for primitives used in libraries.
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-
-
File.WriteAllText("sample.fsx","let twenty = 'a' + 10.0")
-letresult,warnings=fsiSession.EvalScriptNonThrowing"sample.fsx"
-
-// show the result
-matchresultwith
-|Choice1Of2()->printfn"checked and executed ok"
-|Choice2Of2exn->printfn"execution exception: %s"exn.Message
-
openSystem.Threading.Tasks
-
-letsampleLongRunningExpr=
- """
-async {
- // The code of what you want to run
- do System.Threading.Thread.Sleep 5000
- return 10
-}
- |> Async.StartAsTask"""
-
-lettask1=evalExpressionTyped<Task<int>>(sampleLongRunningExpr)
-lettask2=evalExpressionTyped<Task<int>>(sampleLongRunningExpr)
-
-
-
-
Both computations have now started. You can now fetch the results:
-
1:
-2:
-
-
task1.Result// gives the result after completion (up to 5 seconds)
-task2.Result// gives the result after completion (up to 5 seconds)
-
Let's assume you have a situation where you would like to typecheck code
-in the context of the F# Interactive scripting session. For example, you first
-evaluation a declaration:
-
1:
-
-
fsiSession.EvalInteraction"let xxx = 1 + 1"
-
-
-
-
Now you want to typecheck the partially complete code xxx + xx
The parseResults and checkResults have types ParseFileResults and CheckFileResults
-explained in Editor. You can, for example, look at the type errors in the code:
-
1:
-
-
checkResults.Errors.Length// 1
-
-
-
-
The code is checked with respect to the logical type context available in the F# interactive session
-based on the declarations executed so far.
-
You can also request declaration list information, tooltip text and symbol resolution:
-
1:
-2:
-3:
-4:
-5:
-6:
-
-
openFSharp.Compiler
-
-// get a tooltip
-checkResults.GetToolTipText(1,2,"xxx + xx",["xxx"],FSharpTokenTag.IDENT)
-
-checkResults.GetSymbolUseAtLocation(1,2,"xxx + xx",["xxx"])// symbol xxx
-
If you want your scripting code to be able to access the 'fsi' object, you should pass in an implementation of this object explicitly.
-Normally the one from FSharp.Compiler.Interactive.Settings.dll is used.
Evaluating code in using FsiEvaluationSession generates a .NET dynamic assembly and uses other resources.
-You can make generated code collectible by passing collectible=true. However code will only
-be collected if there are no outstanding object references involving types, for example
-FsiValue objects returned by EvalExpression, and you must have disposed the FsiEvaluationSession.
-See also Restrictions on Collectible Assemblies.
-
The example below shows the creation of 200 evaluation sessions. Note that collectible=true and
-use session = ... are both used.
-
If collectible code is working correctly,
-overall resource usage will not increase linearly as the evaluation progresses.
letcollectionTest()=
-
- foriin1..200do
- letdefaultArgs=[|"fsi.exe";"--noninteractive";"--nologo";"--gui-"|]
- useinStream=newStringReader("")
- useoutStream=newStringWriter()
- useerrStream=newStringWriter()
-
- letfsiConfig=FsiEvaluationSession.GetDefaultConfiguration()
- usesession=FsiEvaluationSession.Create(fsiConfig,defaultArgs,inStream,outStream,errStream,collectible=true)
-
- session.EvalInteraction(sprintf"type D = { v : int }")
- letv=session.EvalExpression(sprintf"{ v = 42 * %d }"i)
- printfn"iteration %d, result = %A"iv.Value.ReflectionValue
-
-// collectionTest() <-- run the test like this
-
-
-
-
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Interactive
-
module Shell
from FSharp.Compiler.Interactive
-
namespace System
-
namespace System.IO
-
namespace System.Text
-
val sbOut : StringBuilder
-
Multiple items type StringBuilder = new : unit -> StringBuilder + 5 overloads member Append : value:string -> StringBuilder + 22 overloads member AppendFormat : format:string * arg0:obj -> StringBuilder + 7 overloads member AppendJoin : separator:string * [<ParamArray>] values:obj[] -> StringBuilder + 5 overloads member AppendLine : unit -> StringBuilder + 1 overload member Capacity : int with get, set member Chars : int -> char with get, set member Clear : unit -> StringBuilder member CopyTo : sourceIndex:int * destination:Span<char> * count:int -> unit + 1 overload member EnsureCapacity : capacity:int -> int ...
Multiple items type StringReader = inherit TextReader new : s:string -> StringReader member Close : unit -> unit member Peek : unit -> int member Read : unit -> int + 2 overloads member ReadAsync : buffer:Memory<char> * ?cancellationToken:CancellationToken -> ValueTask<int> + 1 overload member ReadBlock : buffer:Span<char> -> int member ReadBlockAsync : buffer:Memory<char> * ?cancellationToken:CancellationToken -> ValueTask<int> + 1 overload member ReadLine : unit -> string member ReadLineAsync : unit -> Task<string> member ReadToEnd : unit -> string ...
Multiple items type StringWriter = inherit TextWriter new : unit -> StringWriter + 3 overloads member Close : unit -> unit member Encoding : Encoding member FlushAsync : unit -> Task member GetStringBuilder : unit -> StringBuilder member ToString : unit -> string member Write : value:char -> unit + 3 overloads member WriteAsync : value:char -> Task + 3 overloads member WriteLine : buffer:ReadOnlySpan<char> -> unit member WriteLineAsync : value:char -> Task + 3 overloads
type Array = member Clone : unit -> obj member CopyTo : array:Array * index:int -> unit + 1 overload member GetEnumerator : unit -> IEnumerator member GetLength : dimension:int -> int member GetLongLength : dimension:int -> int64 member GetLowerBound : dimension:int -> int member GetUpperBound : dimension:int -> int member GetValue : [<ParamArray>] indices:int[] -> obj + 7 overloads member Initialize : unit -> unit member IsFixedSize : bool ...
member FsiEvaluationSession.EvalExpression : code:string -> FsiValue option
-
union case Option.Some: Value: 'T -> Option<'T>
-
val value : FsiValue
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
property FsiValue.ReflectionValue: obj with get
-
union case Option.None: Option<'T>
-
val evalExpressionTyped : text:string -> 'T
Evaluate expression & return the result, strongly typed
-
val unbox : value:obj -> 'T
-
val failwith : message:string -> 'T
-
Multiple items val int : value:'T -> int (requires member op_Explicit)
-------------------- type int = int32
-------------------- type int<'Measure> = int
-
member FsiEvaluationSession.EvalInteraction : code:string * ?cancellationToken:Threading.CancellationToken -> unit
-
type File = static member AppendAllLines : path:string * contents:IEnumerable<string> -> unit + 1 overload static member AppendAllLinesAsync : path:string * contents:IEnumerable<string> * ?cancellationToken:CancellationToken -> Task + 1 overload static member AppendAllText : path:string * contents:string -> unit + 1 overload static member AppendAllTextAsync : path:string * contents:string * ?cancellationToken:CancellationToken -> Task + 1 overload static member AppendText : path:string -> StreamWriter static member Copy : sourceFileName:string * destFileName:string -> unit + 1 overload static member Create : path:string -> FileStream + 2 overloads static member CreateText : path:string -> StreamWriter static member Decrypt : path:string -> unit static member Delete : path:string -> unit ...
-
File.WriteAllText(path: string, contents: string) : unit File.WriteAllText(path: string, contents: string, encoding: Encoding) : unit
-
member FsiEvaluationSession.EvalScript : filePath:string -> unit
-
val result : Choice<unit,exn>
-
val warnings : FSharpErrorInfo []
-
member FsiEvaluationSession.EvalScriptNonThrowing : filePath:string -> Choice<unit,exn> * FSharpErrorInfo []
-
union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>
-
union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>
-
Multiple items val exn : exn
-------------------- type exn = Exception
-
property Exception.Message: string with get
-
val not : value:bool -> bool
-
val w : FSharpErrorInfo
-
property FSharpErrorInfo.Message: string with get
-
property FSharpErrorInfo.StartLineAlternate: int with get
-
property FSharpErrorInfo.StartColumn: int with get
-
val evalExpressionTyped2 : text:string -> 'T
-
val res : Choice<FsiValue option,exn>
-
member FsiEvaluationSession.EvalExpressionNonThrowing : code:string -> Choice<FsiValue option,exn> * FSharpErrorInfo []
-
val sprintf : format:Printf.StringFormat<'T> -> 'T
-
namespace System.Threading
-
namespace System.Threading.Tasks
-
val sampleLongRunningExpr : string
-
val task1 : Task<int>
-
Multiple items type Task = new : action:Action -> Task + 7 overloads member AsyncState : obj member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable member ContinueWith : continuationAction:Action<Task> -> Task + 19 overloads member CreationOptions : TaskCreationOptions member Dispose : unit -> unit member Exception : AggregateException member GetAwaiter : unit -> TaskAwaiter member Id : int member IsCanceled : bool ...
-------------------- type Task<'TResult> = inherit Task new : function:Func<'TResult> -> Task<'TResult> + 7 overloads member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable<'TResult> member ContinueWith : continuationAction:Action<Task<'TResult>> -> Task + 19 overloads member GetAwaiter : unit -> TaskAwaiter<'TResult> member Result : 'TResult static member Factory : TaskFactory<'TResult>
type FSharpCheckFileAnswer = | Aborted | Succeeded of FSharpCheckFileResults
-
union case FSharpCheckFileAnswer.Succeeded: FSharpCheckFileResults -> FSharpCheckFileAnswer
-
val res : FSharpCheckFileResults
-
val res : FSharpCheckFileAnswer
-
val failwithf : format:Printf.StringFormat<'T,'Result> -> 'T
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
val tip : Async<FSharpToolTipText>
-
member FSharpCheckFileResults.GetToolTipText : line:int * colAtEndOfNames:int * lineText:string * names:string list * tokenTag:int * ?userOpName:string -> Async<FSharpToolTipText>
-
module FSharpTokenTag
from FSharp.Compiler.SourceCodeServices
-
val Identifier : int
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
type PartialLongName = { QualifyingIdents: string list PartialIdent: string EndColumn: int LastDotPos: int option } static member Empty : endColumn:int -> PartialLongName
-
static member PartialLongName.Empty : endColumn:int -> PartialLongName
-
val item : FSharpDeclarationListItem
-
property FSharpDeclarationListInfo.Items: FSharpDeclarationListItem [] with get
-
property FSharpDeclarationListItem.Name: string with get
-
val methods : FSharpMethodGroup
-
member FSharpCheckFileResults.GetMethods : line:int * colAtEndOfNames:int * lineText:string * names:string list option * ?userOpName:string -> Async<FSharpMethodGroup>
-
val mi : FSharpMethodGroupItem
-
property FSharpMethodGroup.Methods: FSharpMethodGroupItem [] with get
-
val p : FSharpMethodGroupItemParameter
-
property FSharpMethodGroupItem.Parameters: FSharpMethodGroupItemParameter [] with get
-
property FSharpMethodGroupItemParameter.Display: string with get
-
Multiple items type String = new : value:char[] -> string + 8 overloads member Chars : int -> char member Clone : unit -> obj member CompareTo : value:obj -> int + 1 overload member Contains : value:string -> bool + 3 overloads member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit member EndsWith : value:string -> bool + 3 overloads member Equals : obj:obj -> bool + 2 overloads member GetEnumerator : unit -> CharEnumerator member GetHashCode : unit -> int + 1 overload ...
Multiple items type MemoryStream = inherit Stream new : unit -> MemoryStream + 6 overloads member CanRead : bool member CanSeek : bool member CanWrite : bool member Capacity : int with get, set member CopyTo : destination:Stream * bufferSize:int -> unit member CopyToAsync : destination:Stream * bufferSize:int * cancellationToken:CancellationToken -> Task member Flush : unit -> unit member FlushAsync : cancellationToken:CancellationToken -> Task member GetBuffer : unit -> byte[] ...
type Encoding = member BodyName : string member Clone : unit -> obj member CodePage : int member DecoderFallback : DecoderFallback with get, set member EncoderFallback : EncoderFallback with get, set member EncodingName : string member Equals : value:obj -> bool member GetByteCount : chars:char[] -> int + 5 overloads member GetBytes : chars:char[] -> byte[] + 7 overloads member GetCharCount : bytes:byte[] -> int + 3 overloads ...
type Stream = inherit MarshalByRefObject member BeginRead : buffer:byte[] * offset:int * count:int * callback:AsyncCallback * state:obj -> IAsyncResult member BeginWrite : buffer:byte[] * offset:int * count:int * callback:AsyncCallback * state:obj -> IAsyncResult member CanRead : bool member CanSeek : bool member CanTimeout : bool member CanWrite : bool member Close : unit -> unit member CopyTo : destination:Stream -> unit + 1 overload member CopyToAsync : destination:Stream -> Task + 3 overloads member Dispose : unit -> unit ...
-
abstract member IFileSystem.FileStreamReadShim : fileName:string -> Stream
-
val __ : MyFileSystem
-
abstract member IFileSystem.FileStreamCreateShim : fileName:string -> Stream
-
abstract member IFileSystem.IsStableFileHeuristic : fileName:string -> bool
-
abstract member IFileSystem.FileStreamWriteExistingShim : fileName:string -> Stream
-
abstract member IFileSystem.ReadAllBytesShim : fileName:string -> byte []
-
abstract member IFileSystem.GetTempPathShim : unit -> string
-
abstract member IFileSystem.GetLastWriteTimeShim : fileName:string -> DateTime
-
abstract member IFileSystem.GetFullPathShim : fileName:string -> string
-
abstract member IFileSystem.IsInvalidPathShim : filename:string -> bool
-
abstract member IFileSystem.IsPathRootedShim : path:string -> bool
-
IDictionary.ContainsKey(key: string) : bool
-
abstract member IFileSystem.SafeExists : fileName:string -> bool
-
abstract member IFileSystem.FileDelete : fileName:string -> unit
-
abstract member IFileSystem.AssemblyLoadFrom : fileName:string -> Reflection.Assembly
-
val assemblyName : Reflection.AssemblyName
-
abstract member IFileSystem.AssemblyLoad : assemblyName:Reflection.AssemblyName -> Reflection.Assembly
-
val myFileSystem : MyFileSystem
-
namespace FSharp.Compiler.SourceCodeServices
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Interactive
-
module Shell
from FSharp.Compiler.Interactive
-
namespace System
-
namespace System.IO
-
namespace System.Text
-
val sbOut : StringBuilder
-
Multiple items type StringBuilder = new : unit -> StringBuilder + 5 overloads member Append : value:string -> StringBuilder + 22 overloads member AppendFormat : format:string * arg0:obj -> StringBuilder + 7 overloads member AppendJoin : separator:string * [<ParamArray>] values:obj[] -> StringBuilder + 5 overloads member AppendLine : unit -> StringBuilder + 1 overload member Capacity : int with get, set member Chars : int -> char with get, set member Clear : unit -> StringBuilder member CopyTo : sourceIndex:int * destination:Span<char> * count:int -> unit + 1 overload member EnsureCapacity : capacity:int -> int ...
Multiple items type StringReader = inherit TextReader new : s:string -> StringReader member Close : unit -> unit member Peek : unit -> int member Read : unit -> int + 2 overloads member ReadAsync : buffer:Memory<char> * ?cancellationToken:CancellationToken -> ValueTask<int> + 1 overload member ReadBlock : buffer:Span<char> -> int member ReadBlockAsync : buffer:Memory<char> * ?cancellationToken:CancellationToken -> ValueTask<int> + 1 overload member ReadLine : unit -> string member ReadLineAsync : unit -> Task<string> member ReadToEnd : unit -> string ...
Multiple items type StringWriter = inherit TextWriter new : unit -> StringWriter + 3 overloads member Close : unit -> unit member Encoding : Encoding member FlushAsync : unit -> Task member GetStringBuilder : unit -> StringBuilder member ToString : unit -> string member Write : value:char -> unit + 3 overloads member WriteAsync : value:char -> Task + 3 overloads member WriteLine : buffer:ReadOnlySpan<char> -> unit member WriteLineAsync : value:char -> Task + 3 overloads
type Array = member Clone : unit -> obj member CopyTo : array:Array * index:int -> unit + 1 overload member GetEnumerator : unit -> IEnumerator member GetLength : dimension:int -> int member GetLongLength : dimension:int -> int64 member GetLowerBound : dimension:int -> int member GetUpperBound : dimension:int -> int member GetValue : [<ParamArray>] indices:int[] -> obj + 7 overloads member Initialize : unit -> unit member IsFixedSize : bool ...
member FsiEvaluationSession.EvalExpression : code:string -> FsiValue option
-
union case Option.Some: Value: 'T -> Option<'T>
-
val value : FsiValue
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
property FsiValue.ReflectionValue: obj with get
-
union case Option.None: Option<'T>
-
val evalExpressionTyped : text:string -> 'T
式を評価して、強く型付けされた結果を返す
-
val unbox : value:obj -> 'T
-
val failwith : message:string -> 'T
-
Multiple items val int : value:'T -> int (requires member op_Explicit)
-------------------- type int = int32
-------------------- type int<'Measure> = int
-
member FsiEvaluationSession.EvalInteraction : code:string * ?cancellationToken:Threading.CancellationToken -> unit
-
type File = static member AppendAllLines : path:string * contents:IEnumerable<string> -> unit + 1 overload static member AppendAllLinesAsync : path:string * contents:IEnumerable<string> * ?cancellationToken:CancellationToken -> Task + 1 overload static member AppendAllText : path:string * contents:string -> unit + 1 overload static member AppendAllTextAsync : path:string * contents:string * ?cancellationToken:CancellationToken -> Task + 1 overload static member AppendText : path:string -> StreamWriter static member Copy : sourceFileName:string * destFileName:string -> unit + 1 overload static member Create : path:string -> FileStream + 2 overloads static member CreateText : path:string -> StreamWriter static member Decrypt : path:string -> unit static member Delete : path:string -> unit ...
-
File.WriteAllText(path: string, contents: string) : unit File.WriteAllText(path: string, contents: string, encoding: Encoding) : unit
-
member FsiEvaluationSession.EvalScript : filePath:string -> unit
-
val result : Choice<unit,exn>
-
val warnings : FSharpErrorInfo []
-
member FsiEvaluationSession.EvalScriptNonThrowing : filePath:string -> Choice<unit,exn> * FSharpErrorInfo []
-
union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>
-
union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>
-
Multiple items val exn : exn
-------------------- type exn = Exception
-
property Exception.Message: string with get
-
val not : value:bool -> bool
-
val w : FSharpErrorInfo
-
property FSharpErrorInfo.Message: string with get
-
property FSharpErrorInfo.StartLineAlternate: int with get
-
property FSharpErrorInfo.StartColumn: int with get
-
val evalExpressionTyped2 : text:string -> 'T
-
val res : Choice<FsiValue option,exn>
-
member FsiEvaluationSession.EvalExpressionNonThrowing : code:string -> Choice<FsiValue option,exn> * FSharpErrorInfo []
-
val sprintf : format:Printf.StringFormat<'T> -> 'T
-
namespace System.Threading
-
namespace System.Threading.Tasks
-
val sampleLongRunningExpr : string
-
val task1 : Task<int>
-
Multiple items type Task = new : action:Action -> Task + 7 overloads member AsyncState : obj member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable member ContinueWith : continuationAction:Action<Task> -> Task + 19 overloads member CreationOptions : TaskCreationOptions member Dispose : unit -> unit member Exception : AggregateException member GetAwaiter : unit -> TaskAwaiter member Id : int member IsCanceled : bool ...
-------------------- type Task<'TResult> = inherit Task new : function:Func<'TResult> -> Task<'TResult> + 7 overloads member ConfigureAwait : continueOnCapturedContext:bool -> ConfiguredTaskAwaitable<'TResult> member ContinueWith : continuationAction:Action<Task<'TResult>> -> Task + 19 overloads member GetAwaiter : unit -> TaskAwaiter<'TResult> member Result : 'TResult static member Factory : TaskFactory<'TResult>
property FSharpCheckProjectResults.Errors: FSharpErrorInfo [] with get
-
property Array.Length: int with get
-
val x : FSharpEntity
-
property FSharpCheckProjectResults.AssemblySignature: FSharpAssemblySignature with get
-
property FSharpAssemblySignature.Entities: IList<FSharpEntity> with get
-
property FSharpEntity.DisplayName: string with get
-
val x : FSharpMemberOrFunctionOrValue
-
property FSharpMemberOrFunctionOrValue.DisplayName: string with get
-
val allSymbolsInEntities : entities:IList<FSharpEntity> -> FSharpSymbol list
-
val entities : IList<FSharpEntity>
-
type IList<'T> = inherit ICollection<'T> inherit IEnumerable<'T> inherit IEnumerable member IndexOf : item:'T -> int member Insert : index:int * item:'T -> unit member Item : int -> 'T with get, set member RemoveAt : index:int -> unit
-
type FSharpEntity = inherit FSharpSymbol private new : SymbolEnv * EntityRef -> FSharpEntity member AbbreviatedType : FSharpType member AccessPath : string member Accessibility : FSharpAccessibility member ActivePatternCases : FSharpActivePatternCase list member AllCompilationPaths : string list member AllInterfaces : IList<FSharpType> member ArrayRank : int member Attributes : IList<FSharpAttribute> ...
-
val e : FSharpEntity
-
type FSharpSymbol = member GetEffectivelySameAsHash : unit -> int member IsAccessible : FSharpAccessibilityRights -> bool member IsEffectivelySameAs : other:FSharpSymbol -> bool member Assembly : FSharpAssembly member DeclarationLocation : range option member DisplayName : string member FullName : string member ImplementationLocation : range option member IsExplicitlySuppressed : bool member private Item : Item ...
-
property FSharpEntity.MembersFunctionsAndValues: IList<FSharpMemberOrFunctionOrValue> with get
-
val x : FSharpUnionCase
-
property FSharpEntity.UnionCases: IList<FSharpUnionCase> with get
-
val x : FSharpField
-
property FSharpEntity.FSharpFields: IList<FSharpField> with get
-
property FSharpEntity.NestedEntities: IList<FSharpEntity> with get
-
val allSymbols : FSharpSymbol list
-
val backgroundParseResults1 : FSharpParseFileResults
-
val backgroundTypedParse1 : FSharpCheckFileResults
fnVal.FullType// int * int -> unit
-fnVal.FullType.IsFunctionType// true
-fnVal.FullType.GenericArguments.[0]// int * int
-fnVal.FullType.GenericArguments.[0].IsTupleType// true
-letargTy1=fnVal.FullType.GenericArguments.[0].GenericArguments.[0]
-
-argTy1.TypeDefinition.DisplayName// int
-
-
-
-
というわけで int * int -> unit という型を表現するオブジェクトが取得できて、
-その1つめの 'int' を確認できたわけです。
-また、以下のようにすると 'int' 型についてのより詳細な情報が取得でき、
-それが名前付きの型であり、F#の型省略形 type int = int32 であることがわかります:
Multiple items type FSharpSourceTokenizer = new : conditionalDefines:string list * fileName:string option -> FSharpSourceTokenizer member CreateBufferTokenizer : bufferFiller:(char [] * int * int -> int) -> FSharpLineTokenizer member CreateLineTokenizer : lineText:string -> FSharpLineTokenizer
-------------------- new : conditionalDefines:string list * fileName:string option -> FSharpSourceTokenizer
-
val tokenizer : FSharpLineTokenizer
-
member FSharpSourceTokenizer.CreateLineTokenizer : lineText:string -> FSharpLineTokenizer
-
val tokenizeLine : tokenizer:FSharpLineTokenizer -> state:FSharpTokenizerLexState -> FSharpTokenizerLexState
F#コード1行をトークン化します
-
type FSharpLineTokenizer = member ScanToken : lexState:FSharpTokenizerLexState -> FSharpTokenInfo option * FSharpTokenizerLexState static member ColorStateOfLexState : FSharpTokenizerLexState -> FSharpTokenizerColorState static member LexStateOfColorState : FSharpTokenizerColorState -> FSharpTokenizerLexState
-
[<Struct>] val state : FSharpTokenizerLexState
-
member FSharpLineTokenizer.ScanToken : lexState:FSharpTokenizerLexState -> FSharpTokenInfo option * FSharpTokenizerLexState
-
union case Option.Some: Value: 'T -> Option<'T>
-
val tok : FSharpTokenInfo
-
val printf : format:Printf.TextWriterFormat<'T> -> 'T
-
FSharpTokenInfo.TokenName: string
-
union case Option.None: Option<'T>
-
[<Struct>] type FSharpTokenizerLexState = { PosBits: int64 OtherBits: int64 } member Equals : FSharpTokenizerLexState -> bool static member Initial : FSharpTokenizerLexState
-
property FSharpTokenizerLexState.Initial: FSharpTokenizerLexState with get
-
val lines : string []
-
val tokenizeLines : state:FSharpTokenizerLexState -> count:int -> lines:string list -> unit
複数行のコードに対してトークンの名前を表示します
-
val count : int
-
val lines : string list
-
val line : string
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
Multiple items module List
from Microsoft.FSharp.Collections
-------------------- type List<'T> = | ( [] ) | ( :: ) of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetSlice : startIndex:int option * endIndex:int option -> 'T list member Head : 'T member IsEmpty : bool member Item : index:int -> 'T with get member Length : int member Tail : 'T list ...
property FSharpParseFileResults.ParseTree: FSharp.Compiler.SyntaxTree.ParsedInput option with get
-
union case Option.Some: Value: 'T -> Option<'T>
-
val tree : FSharp.Compiler.SyntaxTree.ParsedInput
-
union case Option.None: Option<'T>
-
val failwith : message:string -> 'T
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
val visitPattern : (obj -> obj)
パターンの走査 これは let <pat> = <expr> あるいは 'match' 式に対する例です
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
Multiple items type String = new : value:char[] -> string + 8 overloads member Chars : int -> char member Clone : unit -> obj member CompareTo : value:obj -> int + 1 overload member Contains : value:string -> bool + 3 overloads member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit member EndsWith : value:string -> bool + 3 overloads member Equals : obj:obj -> bool + 2 overloads member GetEnumerator : unit -> CharEnumerator member GetHashCode : unit -> int + 1 overload ...
As in the previous tutorial (using untyped AST), we start by referencing
-FSharp.Compiler.Service.dll, opening the relevant namespace and creating an instance
-of InteractiveChecker:
-
1:
- 2:
- 3:
- 4:
- 5:
- 6:
- 7:
- 8:
- 9:
-10:
-
-
// Reference F# compiler API
-#r"FSharp.Compiler.Service.dll"
-
-openSystem
-openSystem.Collections.Generic
-openFSharp.Compiler.SourceCodeServices
-openFSharp.Compiler.Text
-
-// Create an interactive checker instance
-letchecker=FSharpChecker.Create()
-
After checking the whole project, you can access the background results for individual files
-in the project. This will be fast and will not involve any additional checking.
You can find out more about a symbol by doing type checks on various symbol kinds:
-
1:
-2:
-3:
-4:
-5:
-
-
letxSymbolAsValue=
- matchxSymbolwith
- |:?FSharpMemberOrFunctionOrValueasxSymbolAsVal->xSymbolAsVal
- |_->failwith"we expected this to be a member, function or value"
-
-
-
-
-
For each symbol, you can look up the references to that symbol:
You can also request checks of updated versions of files within the project (note that the other files
-in the project are still read from disk, unless you are using the FileSystem API):
If you have multiple F# projects to analyze which include references from some projects to others,
-then the simplest way to do this is to build the projects and specify the cross-project references using
-a -r:path-to-output-of-project.dll argument in the ProjectOptions. However, this requires the build
-of each project to succeed, producing the DLL file on disk which can be referred to.
-
In some situations, e.g. in an IDE, you may wish to allow references to other F# projects prior to successful compilation to
-a DLL. To do this, fill in the ProjectReferences entry in ProjectOptions, which recursively specifies the project
-options for dependent projects. Each project reference still needs a corresponding -r:path-to-output-of-project.dll
-command line argument in ProjectOptions, along with an entry in ProjectReferences.
-The first element of each tuple in the ProjectReferences entry should be the DLL name, i.e. path-to-output-of-project.dll.
-This should be the same as the text used in the -r project reference.
-
When a project reference is used, the analysis will make use of the results of incremental
-analysis of the referenced F# project from source files, without requiring the compilation of these files to DLLs.
-
To efficiently analyze a set of F# projects which include cross-references, you should populate the ProjectReferences
-correctly and then analyze each project in turn.
-
-
NOTE: Project references are disabled if the assembly being referred to contains type provider components -
-specifying the project reference will have no effect beyond forcing the analysis of the project, and the DLL will
-still be required on disk.
As you have seen, the ParseAndCheckProject lets you access results of project-wide analysis
-such as symbol references. To learn more about working with symbols, see Symbols.
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Text
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
type File = static member AppendAllLines : path:string * contents:IEnumerable<string> -> unit + 1 overload static member AppendAllLinesAsync : path:string * contents:IEnumerable<string> * ?cancellationToken:CancellationToken -> Task + 1 overload static member AppendAllText : path:string * contents:string -> unit + 1 overload static member AppendAllTextAsync : path:string * contents:string * ?cancellationToken:CancellationToken -> Task + 1 overload static member AppendText : path:string -> StreamWriter static member Copy : sourceFileName:string * destFileName:string -> unit + 1 overload static member Create : path:string -> FileStream + 2 overloads static member CreateText : path:string -> StreamWriter static member Decrypt : path:string -> unit static member Delete : path:string -> unit ...
-
File.WriteAllText(path: string, contents: string) : unit File.WriteAllText(path: string, contents: string, encoding: Text.Encoding) : unit
-
val fileSource2 : string
-
val projectOptions : FSharpProjectOptions
-
val sysLib : (string -> string)
-
val nm : string
-
type Environment = static member CommandLine : string static member CurrentDirectory : string with get, set static member CurrentManagedThreadId : int static member Exit : exitCode:int -> unit static member ExitCode : int with get, set static member ExpandEnvironmentVariables : name:string -> string static member FailFast : message:string -> unit + 1 overload static member GetCommandLineArgs : unit -> string[] static member GetEnvironmentVariable : variable:string -> string + 1 overload static member GetEnvironmentVariables : unit -> IDictionary + 1 overload ... nested type SpecialFolder nested type SpecialFolderOption
-
property Environment.OSVersion: OperatingSystem with get
-
property OperatingSystem.Platform: PlatformID with get
property FSharpCheckProjectResults.Errors: FSharpErrorInfo [] with get
-
val x : FSharpEntity
-
property FSharpCheckProjectResults.AssemblySignature: FSharpAssemblySignature with get
-
property FSharpAssemblySignature.Entities: IList<FSharpEntity> with get
-
property FSharpEntity.DisplayName: string with get
-
val x : FSharpMemberOrFunctionOrValue
-
property FSharpMemberOrFunctionOrValue.DisplayName: string with get
-
val allSymbolsInEntities : entities:IList<FSharpEntity> -> FSharpSymbol list
-
val entities : IList<FSharpEntity>
-
type IList<'T> = inherit ICollection<'T> inherit IEnumerable<'T> inherit IEnumerable member IndexOf : item:'T -> int member Insert : index:int * item:'T -> unit member Item : int -> 'T with get, set member RemoveAt : index:int -> unit
-
type FSharpEntity = inherit FSharpSymbol private new : SymbolEnv * EntityRef -> FSharpEntity member AbbreviatedType : FSharpType member AccessPath : string member Accessibility : FSharpAccessibility member ActivePatternCases : FSharpActivePatternCase list member AllCompilationPaths : string list member AllInterfaces : IList<FSharpType> member ArrayRank : int member Attributes : IList<FSharpAttribute> ...
-
val e : FSharpEntity
-
type FSharpSymbol = member GetEffectivelySameAsHash : unit -> int member IsAccessible : FSharpAccessibilityRights -> bool member IsEffectivelySameAs : other:FSharpSymbol -> bool member Assembly : FSharpAssembly member DeclarationLocation : range option member DisplayName : string member FullName : string member ImplementationLocation : range option member IsExplicitlySuppressed : bool member private Item : Item ...
-
property FSharpEntity.MembersFunctionsAndValues: IList<FSharpMemberOrFunctionOrValue> with get
-
val x : FSharpUnionCase
-
property FSharpEntity.UnionCases: IList<FSharpUnionCase> with get
-
val x : FSharpField
-
property FSharpEntity.FSharpFields: IList<FSharpField> with get
-
property FSharpEntity.NestedEntities: IList<FSharpEntity> with get
-
val allSymbols : FSharpSymbol list
-
val backgroundParseResults1 : FSharpParseFileResults
-
val backgroundTypedParse1 : FSharpCheckFileResults
This is a design note on the FSharpChecker component and its operations queue. See also the notes on the FSharpChecker caches
-
FSharpChecker maintains an operations queue. Items from the FSharpChecker operations queue are processed
-sequentially and in order.
-
The thread processing these requests can also run a low-priority, interleaved background operation when the
-queue is empty. This can be used to implicitly bring the background check of a project "up-to-date".
-When the operations queue has been empty for 1 second,
-this background work is run in small incremental fragments. This work is cooperatively time-sliced to be approximately <50ms, (see maxTimeShareMilliseconds in
-IncrementalBuild.fs). The project to be checked in the background is set implicitly
-by calls to CheckFileInProject and ParseAndCheckFileInProject.
-To disable implicit background checking completely, set checker.ImplicitlyStartBackgroundWork to false.
-To change the time before background work starts, set checker.PauseBeforeBackgroundWork to the required number of milliseconds.
-
Most calls to the FSharpChecker API enqueue an operation in the FSharpChecker compiler queue. These correspond to the
-calls to EnqueueAndAwaitOpAsync in service.fs.
-
-
-
For example, calling ParseAndCheckProject enqueues a ParseAndCheckProjectImpl operation. The time taken for the
-operation will depend on how much work is required to bring the project analysis up-to-date.
-
-
-
Likewise, calling any of GetUsesOfSymbol, GetAllUsesOfAllSymbols, ParseFileInProject,
-GetBackgroundParseResultsForFileInProject, MatchBraces, CheckFileInProjectIfReady, ParseAndCheckFileInProject, GetBackgroundCheckResultsForFileInProject,
-ParseAndCheckProject, GetProjectOptionsFromScript, InvalidateConfiguration, InvaidateAll and operations
-on FSharpCheckResults will cause an operation to be enqueued. The length of the operation will
-vary - many will be very fast - but they won't be processed until other operations already in the queue are complete.
-
-
-
Some operations do not enqueue anything on the FSharpChecker operations queue - notably any accesses to the Symbol APIs.
-These use cross-threaded access to the TAST data produced by other FSharpChecker operations.
-
Some tools throw a lot of interactive work at the FSharpChecker operations queue.
-If you are writing such a component, consider running your project against a debug build
-of FSharp.Compiler.Service.dll to see the Trace.WriteInformation messages indicating the length of the
-operations queue and the time to process requests.
-
For those writing interactive editors which use FCS, you
-should be cautious about operations that request a check of the entire project.
-For example, be careful about requesting the check of an entire project
-on operations like "Highlight Symbol" or "Find Unused Declarations"
-(which run automatically when the user opens a file or moves the cursor).
-as opposed to operations like "Find All References" (which a user explicitly triggers).
-Project checking can cause long and contention on the FSharpChecker operations queue.
-
Requests to FCS can be cancelled by cancelling the async operation. (Some requests also
-include additional callbacks which can be used to indicate a cancellation condition).
-This cancellation will be effective if the cancellation is performed before the operation
-is executed in the operations queue.
In this design note, you learned that the FSharpChecker component keeps an operations queue. When using FSharpChecker
-in highly interactive situations, you should carefully consider the characteristics of the operations you are
-enqueueing.
This tutorial discusses some technical aspects of how to make sure the F# compiler service is
-providing up-to-date results especially when hosted in an IDE. See also project wide analysis
-for information on project analysis.
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published.
-
-
The logical results of all "Check" routines (ParseAndCheckFileInProject, GetBackgroundCheckResultsForFileInProject,
-TryGetRecentTypeCheckResultsForFile, ParseAndCheckProject) depend on results reported by the file system,
-especially the IFileSystem implementation described in the tutorial on project wide analysis.
-Logically speaking, these results would be different if file system changes occur. For example,
-referenced DLLs may change on disk, or referenced files may change.
-
The FSharpChecker component from FSharp.Compiler.Service does not actively "listen"
-to changes in the file system. However FSharpCheckerdoes repeatedly ask for
-time stamps from the file system which it uses to decide if recomputation is needed.
-FCS doesn't listen for changes directly - for example, it creates no FileWatcher object (and the
-IFileSystem API has no ability to create such objects). This is partly for legacy reasons,
-and partly because some hosts forbid the creation of FileWatcher objects.
-
In most cases the repeated timestamp requests are sufficient. If you don't actively
-listen for changes, then FSharpChecker will still do approximately
-the right thing, because it is asking for time stamps repeatedly. However, some updates on the file system
-(such as a DLL appearing after a build, or the user randomly pasting a file into a folder)
-may not actively be noticed by FSharpChecker until some operation happens to ask for a timestamp.
-By issuing fresh requests, you can ensure that FCS actively reassesses the state of play when
-stays up-to-date when changes are observed.
-
If you want to more actively listen for changes, then you should add watchers for the
-files specified in the DependencyFiles property of FSharpCheckFileResults and FSharpCheckProjectResults.
-Here�s what you need to do:
-
-
-
When your client notices an CHANGE event on a DependencyFile, it should schedule a refresh call to perform the ParseAndCheckFileInProject (or other operation) again.
-This will result in fresh FileSystem calls to compute time stamps.
-
-
-
When your client notices an ADD event on a DependencyFile, it should call checker.InvalidateConfiguration
-for all active projects in which the file occurs. This will result in fresh FileSystem calls to compute time
-stamps, and fresh calls to compute whether files exist.
-
-
-
Generally clients don�t listen for DELETE events on files. Although it would be logically more consistent
-to do so, in practice it�s very irritating for a "project clean" to invalidate all intellisense and
-cause lots of red squiggles. Some source control tools also make a change by removing and adding files, which
-is best noticed as a single change event.
-
-
-
If your host happens to be Visual Studio, then this is one technique you can use:
- Listeners should be associated with a visual source file buffer
- Use fragments like this to watch the DependencyFiles:
// Get the service
- letvsFileWatch=fls.GetService(typeof<SVsFileChangeEx>):?>IVsFileChangeEx
-
- // Watch the Add and Change events
- letfileChangeFlags=
- uint32(_VSFILECHANGEFLAGS.VSFILECHG_Add|||
- // _VSFILECHANGEFLAGS.VSFILECHG_Del ||| // don't listen for deletes - if a file (such as a 'Clean'ed project reference) is deleted, just keep using stale info
- _VSFILECHANGEFLAGS.VSFILECHG_Time)
-
- // Advise on file changes...
- letcookie=Com.ThrowOnFailure1(vsFileWatch.AdviseFileChange(file,fileChangeFlags,changeEvents))
-
- ...
-
- // Unadvised file changes...
- Com.ThrowOnFailure0(vsFileWatch.UnadviseFileChange(cookie))
-
-
-
-
-
val vsFileWatch : obj
-
val typeof<'T> : System.Type
-
val fileChangeFlags : uint32
-
Multiple items val uint32 : value:'T -> uint32 (requires member op_Explicit)
-
- Namespace: FSharp.Compiler.AbstractIL
- Parent Module: IL
-
-
-
The main module of an assembly is a module plus some manifest information.
-
-
-
Record Fields
-
-
-
Record Field
Description
-
-
-
-
-
- AssemblyLongevity
-
-
- Signature: ILAssemblyLongevity
-
-
-
-
-
-
-
-
-
- AuxModuleHashAlgorithm
-
-
- Signature: int32
-
-
-
-
This is the ID of the algorithm used for the hashes of auxiliary
-files in the assembly. These hashes are stored in the
-ILModuleRef.Hash fields of this assembly. These are not
-cryptographic hashes: they are simple file hashes. The algorithm
-is normally 0x00008004 indicating the SHA1 hash algorithm.
-
-
-
-
-
-
-
- CustomAttrsStored
-
-
- Signature: ILAttributesStored
-
-
-
-
-
-
-
-
-
- DisableJitOptimizations
-
-
- Signature: bool
-
-
-
-
-
-
-
-
-
- EntrypointElsewhere
-
-
- Signature: ILModuleRef option
-
-
-
-
Records whether the entrypoint resides in another module.
-
-
-
-
-
-
-
- ExportedTypes
-
-
- Signature: ILExportedTypesAndForwarders
-
-
-
-
Records the types implemented by this assembly in auxiliary
-modules.
-
-
-
-
-
-
-
- IgnoreSymbolStoreSequencePoints
-
-
- Signature: bool
-
-
-
-
-
-
-
-
-
- JitTracking
-
-
- Signature: bool
-
-
-
-
-
-
-
-
-
- Locale
-
-
- Signature: string option
-
-
-
-
-
-
-
-
-
- MetadataIndex
-
-
- Signature: int32
-
-
-
-
-
-
-
-
-
- Name
-
-
- Signature: string
-
-
-
-
-
-
-
-
-
- PublicKey
-
-
- Signature: byte [] option
-
-
-
-
This is the public key used to sign this
-assembly (the signature itself is stored elsewhere: see the
-binary format, and may not have been written if delay signing
-is used). (member Name, member PublicKey) forms the full
-public name of the assembly.
Represents a custom attribute parameter of type 'string'. These may be null, in which case they are encoded in a special
-way as indicated by Ecma-335 Partition II.
-
- Namespace: FSharp.Compiler.AbstractIL
- Parent Module: IL
-
-
-
Custom attribute.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- Decoded(method,fixedArgs,namedArgs)
-
-
- Signature: ILMethodSpec * ILAttribElem list * ILAttributeNamedArg list
-
-
-
-
Attribute with args in decoded form.
-
-
-
-
-
-
-
- Encoded(method,data,elements)
-
-
- Signature: ILMethodSpec * byte [] * ILAttribElem list
-
-
-
-
Attribute with args encoded to a binary blob according to ECMA-335 II.21 and II.23.3.
-'decodeILAttribData' is used to parse the byte[] blob to ILAttribElem's as best as possible.
-
-
-
-
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Elements
-
-
- Signature: ILAttribElem list
-
-
-
-
Decoded arguments. May be empty in encoded attribute form.
A table of common references to items in primary assembly (System.Runtime or mscorlib).
-If a particular version of System.Runtime.dll has been loaded then you should
-reference items from it via an ILGlobals for that specific version built using mkILGlobals.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.IsPossiblePrimaryAssemblyRef(arg1)
-
-
- Signature: ILAssemblyRef -> bool
-
-
-
-
Is the given assembly possibly a primary assembly?
-In practice, a primary assembly is an assembly that contains the System.Object type definition
-and has no referenced assemblies.
-However, we must consider assemblies that forward the System.Object type definition
-to be possible primary assemblies.
-Therefore, this will return true if the given assembly is the real primary assembly or an assembly that forwards
-the System.Object type definition.
-Assembly equivalency ignores the version here.
Indicates that a particular local variable has a particular source
-language name within a given set of ranges. This does not effect local
-variable numbering, which is global over the whole method.
The information is enough to perform name resolution for the F# compiler, probe attributes
-for ExtensionAttribute etc. This is key to the on-demand exploration of .NET metadata.
-This information has to be "Goldilocks" - not too much, not too little, just right.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.GetTypeDef()
-
-
- Signature: unit -> ILTypeDef
- Modifiers: abstract
-
-
- Namespace: FSharp.Compiler.AbstractIL
- Parent Module: IL
-
-
-
"Manifest ILResources" are chunks of resource data, being one of:
-- the data section of the current module (byte[] of resource given directly).
-- in an external file in this assembly (offset given in the ILResourceLocation field).
-- as a resources in another assembly of the same name.
Get some information about the type defs, but do not force the read of the type defs themselves.
-
-
-
CompiledName: get_AsArrayOfPreTypeDefs
-
-
-
-
-
- x.AsList
-
-
- Signature: ILTypeDef list
-
-
-
-
-
CompiledName: get_AsList
-
-
-
-
-
- x.FindByName(arg1)
-
-
- Signature: string -> ILTypeDef
-
-
-
-
Calls to FindByName will result in any laziness in the overall
-set of ILTypeDefs being read in in addition
-to the details for the type found, but the remaining individual
-type definitions will not be read.
A table of common references to items in primary assembly (System.Runtime or mscorlib).
-If a particular version of System.Runtime.dll has been loaded then you should
-reference items from it via an ILGlobals for that specific version built using mkILGlobals.
Indicates that a particular local variable has a particular source
-language name within a given set of ranges. This does not effect local
-variable numbering, which is global over the whole method.
The information is enough to perform name resolution for the F# compiler, probe attributes
-for ExtensionAttribute etc. This is key to the on-demand exploration of .NET metadata.
-This information has to be "Goldilocks" - not too much, not too little, just right.
"Manifest ILResources" are chunks of resource data, being one of:
-- the data section of the current module (byte[] of resource given directly).
-- in an external file in this assembly (offset given in the ILResourceLocation field).
-- as a resources in another assembly of the same name.
Find the full set of assemblies referenced by a module.
-
-
-
-
-
-
-
- decodeILAttribData arg1 arg2
-
-
- Signature: ILGlobals -> ILAttribute -> ILAttribElem list * ILAttributeNamedArg list
-
-
-
-
Not all custom attribute data can be decoded without binding types. In particular
-enums must be bound in order to discover the size of the underlying integer.
-The following assumes enums have size int32.
-
-
-
-
-
-
-
- destILArrTy(arg1)
-
-
- Signature: ILType -> ILArrayShape * ILType
-
-
-
-
-
-
-
-
-
- destTypeDefsWithGlobalFunctionsFirst(...)
-
-
- Signature: ILGlobals -> ILTypeDefs -> ILTypeDef list
-
-
-
-
When writing a binary the fake "toplevel" type definition (called )
-must come first. This function puts it first, and creates it in the returned
-list as an empty typedef if it doesn't already exist.
-
-
-
-
-
-
-
- EcmaMscorlibILGlobals
-
-
- Signature: ILGlobals
-
-
-
-
-
-
-
-
-
- ecmaPublicKey
-
-
- Signature: PublicKey
-
-
-
-
This is a 'vendor neutral' way of referencing mscorlib.
Create table of types which is loaded/computed on-demand, and whose individual
-elements are also loaded/computed on-demand. Any call to tdefs.AsList will
-result in the laziness being forced. Operations can examine the
-custom attributes and name of each type in order to decide whether
-to proceed with examining the other details of the type.
-
Note that individual type definitions may contain further delays
-in their method, field and other tables.
Make a type definition for a value type used to point to raw data.
-These are useful when generating array initialization code
-according to the
-ldtoken field valuetype ''/'\[struct0x6000127-1' '<PrivateImplementationDetails>'::'\]method0x6000127-1'
-call void System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class System.Array,valuetype System.RuntimeFieldHandle)
-idiom.
Generate references to existing type definitions, method definitions
-etc. Useful for generating references, e.g. to a class we're processing
-Also used to reference type definitions that we've generated. ILScopeRef
-is normally ILScopeRef.Local, unless we've generated the ILTypeDef in
-an auxiliary module or are generating multiple assemblies at
-once.
Make some code that is a straight line sequence of instructions.
-The function will add a "return" if the last instruction is not an exiting instruction.
-
-
-
-
-
-
-
- parseILVersion(arg1)
-
-
- Signature: string -> ILVersionInfo
-
-
-
-
Get a version number from a CLR version string, e.g. 1.0.3705.0
Injecting initialization code into a class.
-Add some code to the end of the .cctor for a type. Create a .cctor
-if one doesn't exist already.
-
-
-
-
-
-
-
- prependInstrsToCode arg1 arg2
-
-
- Signature: ILInstr list -> ILCode -> ILCode
-
-
-
-
Injecting code into existing code blocks. A branch will
-be added from the given instructions to the (unique) entry of
-the code, and the first instruction will be the new entry
-of the method. The instructions should be non-branching.
-
-
-
-
-
-
-
- prependInstrsToMethod arg1 arg2
-
-
- Signature: ILInstr list -> ILMethodDef -> ILMethodDef
-
Find the method definition corresponding to the given property or
-event operation. These are always in the same class as the property
-or event. This is useful especially if your code is not using the Ilbind
-API to bind references.
The splitILTypeName utility helps you split a string representing
-a type name into the leading namespace elements (if any), the
-names of any nested types and the type name itself. This function
-memoizes and interns the splitting of the namespace portion of
-the type name.
Only open a metadata reader for the metadata portion of the .NET binary without keeping alive any data associated with the PE reader
-- IL code will not be available (mdBody in ILMethodDef will return NotAvailable)
-- Managed resources will be reported back as ILResourceLocation.LocalIn (as always)
-- Native resources will not be available (none will be returned)
-- Static data associated with fields will not be available
-
-
-
-
-
-
-
- pdbDirPath
-
-
- Signature: string option
-
-
-
-
-
-
-
-
-
- reduceMemoryUsage
-
-
- Signature: ReduceMemoryFlag
-
-
-
-
-
-
-
-
-
- tryGetMetadataSnapshot
-
-
- Signature: ILReaderTryGetMetadataSnapshot
-
-
-
-
A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary,
-and from which we can read the metadata. Only used when metadataOnly=true.
Binary reader. Read a .NET binary and concert it to Abstract IL data
-structures.
-
NOTE:
-- The metadata in the loaded modules will be relative to
-those modules, e.g. ILScopeRef.Local will mean "local to
-that module". You must use [rescopeILType] etc. if you want to include
-(i.e. copy) the metadata into your own module.
-
-
-
PDB (debug info) reading/folding:
-The PDB reader is invoked if you give a PDB path
-This indicates if you want to search for PDB files and have the
-reader fold them in. You cannot currently name the pdb file
-directly - you can only name the path. Giving "None" says
-"do not read the PDB file even if one exists".
-
The debug info appears primarily as I_seqpoint annotations in
-the instruction streams. Unfortunately the PDB information does
-not, for example, tell you how to map back from a class definition
-to a source code line number - you will need to explicitly search
-for a sequence point in the code for one of the methods of the
-class. That is not particularly satisfactory, and it may be
-a good idea to build a small library which extracts the information
-you need.
Represents a cancellable computation with explicit representation of a cancelled result.
-
A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly.
-If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException.
Represents a token that indicates execution on the compilation thread, i.e.
-- we have full access to the (partially mutable) TAST and TcImports data structures
-- compiler execution may result in type provider invocations when resolving types and members
-- we can access various caches in the SourceCodeServices
-
Like other execution tokens this should be passed via argument passing and not captured/stored beyond
-the lifetime of stack-based calls. This is not checked, it is a discipline within the compiler code.
Computations that can cooperatively yield by returning a continuation
-
-
-
Any yield of a NotYetDone should typically be "abandonable" without adverse consequences. No resource release
-will be called when the computation is abandoned.
-
-
-
Computations suspend via a NotYetDone may use local state (mutables), where these are
-captured by the NotYetDone closure. Computations do not need to be restartable.
-
-
-
The key thing is that you can take an Eventually value and run it with
-Eventually.repeatedlyProgressUntilDoneOrTimeShareOverOrCanceled
-
-
Cancellation results in a suspended computation rather than complete abandonment
Keep running the asynchronous computation bit by bit. The runner gets called each time the computation is restarted.
-Can be cancelled as an Async in the normal way.
Just like "Lazy" but EVERY forcer must provide an instance of "ctxt", e.g. to help track errors
-on forcing back to at least one sensible user location
-
-
-
Record Fields
-
-
-
Record Field
Description
-
-
-
-
-
- findOriginalException
-
-
- Signature: exn -> exn
-
-
-
-
A helper to ensure we rethrow the "original" exception
-
-
-
-
-
-
-
- funcOrException
-
-
- Signature: obj
- Modifiers: mutable
-
-
-
-
This field holds either the function to run or a LazyWithContextFailure object recording the exception raised
-from running the function. It is null if the thunk has been evaluated successfully.
-
-
-
-
-
-
-
- value
-
-
- Signature: 'T
- Modifiers: mutable
-
-
-
-
This field holds the result of a successful computation. It's initial value is Unchecked.defaultof
A base type for various types of tokens that must be passed when a lock is taken.
-Each different static lock should declare a new subtype of this type.
Split a ResizeArray into an array of smaller chunks.
-This requires items/chunkSize Array copies of length chunkSize if items/chunkSize % 0 = 0,
-otherwise items/chunkSize + 1 Array copies.
-
-
-
-
-
-
-
- mapToSmallArrayChunks f inp
-
-
- Signature: f:('t -> 'a) -> inp:ResizeArray<'t> -> 'a [] []
- Type parameters: 't, 'a
-
-
-
Split a large ResizeArray into a series of array chunks that are each under the Large Object Heap limit.
-This is done to help prevent a stop-the-world collection of the single large array, instead allowing for a greater
-probability of smaller collections. Stop-the-world is still possible, just less likely.
Take in a filename with an absolute path, and return the same filename
-but canonicalized with respect to extra path separators (e.g. C:\\foo.txt)
-and '..' portions
Represents a cancellable computation with explicit representation of a cancelled result.
-
A cancellable computation is passed may be cancelled via a CancellationToken, which is propagated implicitly.
-If cancellation occurs, it is propagated as data rather than by raising an OperationCanceledException.
Represents a token that indicates execution on the compilation thread, i.e.
-- we have full access to the (partially mutable) TAST and TcImports data structures
-- compiler execution may result in type provider invocations when resolving types and members
-- we can access various caches in the SourceCodeServices
-
Like other execution tokens this should be passed via argument passing and not captured/stored beyond
-the lifetime of stack-based calls. This is not checked, it is a discipline within the compiler code.
Computations that can cooperatively yield by returning a continuation
-
-
-
Any yield of a NotYetDone should typically be "abandonable" without adverse consequences. No resource release
-will be called when the computation is abandoned.
-
-
-
Computations suspend via a NotYetDone may use local state (mutables), where these are
-captured by the NotYetDone closure. Computations do not need to be restartable.
-
-
-
The key thing is that you can take an Eventually value and run it with
-Eventually.repeatedlyProgressUntilDoneOrTimeShareOverOrCanceled
-
-
Cancellation results in a suspended computation rather than complete abandonment
Just like "Lazy" but EVERY forcer must provide an instance of "ctxt", e.g. to help track errors
-on forcing back to at least one sensible user location
A base type for various types of tokens that must be passed when a lock is taken.
-Each different static lock should declare a new subtype of this type.
- Signature: _ctok:CompilationThreadToken -> unit
-
-
-
-
Represents a place in the compiler codebase where we are passed a CompilationThreadToken unnecessarily.
-This represents code that may potentially not need to be executed on the compilation thread.
- Signature: v:'a -> Lazy<'a>
- Type parameters: 'a
-
-
-
-
-
-
-
-
- reportTime
-
-
- Signature: bool -> string -> unit
-
-
-
-
-
-
-
-
-
- RequireCompilationThread(_ctok)
-
-
- Signature: _ctok:CompilationThreadToken -> unit
-
-
-
-
Represents a place where we are stating that execution on the compilation thread is required. The
-reason why will be documented in a comment in the code at the callsite.
Generates compiler-generated names. Each name generated also includes the StartLine number of the range passed in
-at the point of first generation.
-
This type may be accessed concurrently, though in practice it is only used from the compilation thread.
-It is made concurrency-safe since a global instance of the type is allocated in tast.fs, and it is good
-policy to make all globally-allocated objects concurrency safe in case future versions of the compiler
-are used to host multiple concurrent instances of compilation.
Generates compiler-generated names marked up with a source code location, but if given the same unique value then
-return precisely the same name. Each name generated also includes the StartLine number of the range passed in
-at the point of first generation.
-
This type may be accessed concurrently, though in practice it is only used from the compilation thread.
-It is made concurrency-safe since a global instance of the type is allocated in tast.fs.
Generates compiler-generated names. Each name generated also includes the StartLine number of the range passed in
-at the point of first generation.
-
This type may be accessed concurrently, though in practice it is only used from the compilation thread.
-It is made concurrency-safe since a global instance of the type is allocated in tast.fs, and it is good
-policy to make all globally-allocated objects concurrency safe in case future versions of the compiler
-are used to host multiple concurrent instances of compilation.
Generates compiler-generated names marked up with a source code location, but if given the same unique value then
-return precisely the same name. Each name generated also includes the StartLine number of the range passed in
-at the point of first generation.
-
This type may be accessed concurrently, though in practice it is only used from the compilation thread.
-It is made concurrency-safe since a global instance of the type is allocated in tast.fs.
Return true if the textual phase given is from the compile part of the build process.
-This set needs to be equal to the set of subcategories that the language service can produce.
Thrown when immediate, local error recovery is not possible. This indicates
-we've reported an error but need to make a non-local transfer of control.
-Error recovery may catch this and continue (see 'errorRecovery')
-
The exception that caused the report is carried as data because in some
-situations (LazyWithContext) we may need to re-report the original error
-when a lazy thunk is re-evaluated.
Thrown when immediate, local error recovery is not possible. This indicates
-we've reported an error but need to make a non-local transfer of control.
-Error recovery may catch this and continue (see 'errorRecovery')
-
The exception that caused the report is carried as data because in some
-situations (LazyWithContext) we may need to re-report the original error
-when a lazy thunk is re-evaluated.
- Signature: (phasedError:PhasedDiagnostic * isError:bool) -> unit
-
-
-
-
-
-
-
-
-
- DiscardErrorsLogger
-
-
- Signature: ErrorLogger
-
-
-
-
-
-
-
-
-
- error(exn)
-
-
- Signature: exn:exn -> 'a
- Type parameters: 'a
-
-
-
Raises a special exception and returns 'T - can be caught later at an errorRecovery point.
-
-
-
-
-
-
-
- ErrorD(err)
-
-
- Signature: err:exn -> OperationResult<'a>
- Type parameters: 'a
-
-
-
-
-
-
-
-
- errorR(exn)
-
-
- Signature: exn:exn -> unit
-
-
-
-
Raises an exception with error recovery and returns unit.
-
-
-
-
-
-
-
- errorRecovery exn m
-
-
- Signature: exn:exn -> m:range -> unit
-
-
-
-
-
-
-
-
-
- errorRecoveryNoRange(exn)
-
-
- Signature: exn:exn -> unit
-
-
-
-
-
-
-
-
-
- errorSink(pe)
-
-
- Signature: pe:PhasedDiagnostic -> unit
-
-
-
-
-
-
-
-
-
- findOriginalException(err)
-
-
- Signature: err:exn -> exn
-
-
-
-
-
-
-
-
-
- Iterate2D f xs ys
-
-
- Signature: f:('h -> 'i -> OperationResult<unit>) -> xs:'h list -> ys:'i list -> OperationResult<unit>
- Type parameters: 'h, 'i
-
-
-
Stop on first error. Accumulate warnings and continue.
-
-
-
-
-
-
-
- IterateD f xs
-
-
- Signature: f:('h -> OperationResult<unit>) -> xs:'h list -> OperationResult<unit>
- Type parameters: 'h
-
-
-
Stop on first error. Accumulate warnings and continue.
-
-
-
-
-
-
-
- IterateIdxD f xs
-
-
- Signature: f:(int -> 'h -> OperationResult<unit>) -> xs:'h list -> OperationResult<unit>
- Type parameters: 'h
-
-
-
Stop on first error. Report index
-
-
-
-
-
-
-
- libraryOnlyError(m)
-
-
- Signature: m:range -> unit
-
-
-
-
-
-
-
-
-
- libraryOnlyWarning(m)
-
-
- Signature: m:range -> unit
-
-
-
-
-
-
-
-
-
- MapD f xs
-
-
- Signature: f:('?684736 -> OperationResult<'?684737>) -> xs:'?684736 list -> OperationResult<'?684737 list>
- Type parameters: '?684736, '?684737
-
-
-
-
-
-
-
-
- mlCompatWarning s m
-
-
- Signature: s:String -> m:range -> unit
-
-
-
-
-
-
-
-
-
- NewlineifyErrorString(message)
-
-
- Signature: message:string -> string
-
-
-
-
-
-
-
-
-
- NormalizeErrorString(text)
-
-
- Signature: text:string -> string
-
-
-
-
fixes given string by replacing all control chars with spaces.
-NOTE: newlines are recognized and replaced with stringThatIsAProxyForANewlineInFlatErrors (ASCII 29, the 'group separator'),
-which is decoded by the IDE with 'NewlineifyErrorString' back into newlines, so that multi-line errors can be displayed in QuickInfo
Get a handle to the resolved view of the current signature of the incrementally generated assembly.
-
-
-
CompiledName: get_CurrentPartialAssemblySignature
-
-
-
-
-
- x.DynamicAssembly
-
-
- Signature: Assembly
-
-
-
-
Get a handle to the dynamically generated assembly
-
-
-
CompiledName: get_DynamicAssembly
-
-
-
-
-
- x.EvalExpression(code)
-
-
- Signature: code:string -> FsiValue option
-
-
-
-
Execute the code as if it had been entered as one or more interactions, with an
-implicit termination at the end of the input. Stop on first error, discarding the rest
-of the input. Errors are sent to the output writer. Parsing is performed on the current thread, and execution is performed
-synchronously on the 'main' thread.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
Execute the code as if it had been entered as one or more interactions, with an
-implicit termination at the end of the input. Stop on first error, discarding the rest
-of the input. Errors and warnings are collected apart from any exception arising from execution
-which is returned via a Choice. Parsing is performed on the current thread, and execution is performed
-synchronously on the 'main' thread.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
-
-
-
-
-
-
-
- x.EvalInteraction(...)
-
-
- Signature: (code:string * cancellationToken:CancellationToken option) -> unit
-
-
-
-
Execute the code as if it had been entered as one or more interactions, with an
-implicit termination at the end of the input. Stop on first error, discarding the rest
-of the input. Errors are sent to the output writer, a 'true' return value indicates there
-were no errors overall. Execution is performed on the 'Run()' thread.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
Execute the code as if it had been entered as one or more interactions, with an
-implicit termination at the end of the input. Stop on first error, discarding the rest
-of the input. Errors and warnings are collected apart from any exception arising from execution
-which is returned via a Choice. Execution is performed on the 'Run()' thread.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
-
-
-
-
-
-
-
- x.EvalScript(filePath)
-
-
- Signature: filePath:string -> unit
-
-
-
-
Execute the given script. Stop on first error, discarding the rest
-of the script. Errors are sent to the output writer, a 'true' return value indicates there
-were no errors overall. Execution is performed on the 'Run()' thread.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
Execute the given script. Stop on first error, discarding the rest
-of the script. Errors and warnings are collected apart from any exception arising from execution
-which is returned via a Choice. Execution is performed on the 'Run()' thread.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
Typecheck the given script fragment in the type checking context implied by the current state
-of F# Interactive. The results can be used to access intellisense, perform resolutions,
-check brace matching and other information.
-
Operations may be run concurrently with other requests to the InteractiveChecker.
-
Due to a current limitation, it is not fully thread-safe to run this operation concurrently with evaluation triggered
-by input from 'stdin'.
-
-
-
-
-
-
-
- x.PartialAssemblySignatureUpdated
-
-
- Signature: IEvent<unit>
-
-
-
-
Raised when an interaction is successfully typechecked and executed, resulting in an update to the
-type checking state.
-
This event is triggered after parsing and checking, either via input from 'stdin', or via a call to EvalInteraction.
-
-
-
CompiledName: get_PartialAssemblySignatureUpdated
-
-
-
-
-
- x.ReportUnhandledException(exn)
-
-
- Signature: exn:exn -> unit
-
-
-
-
A host calls this to report an unhandled exception in a standard way, e.g. an exception on the GUI thread gets printed to stderr
-
-
-
-
-
-
-
- x.Run()
-
-
- Signature: unit -> unit
-
-
-
-
Load the dummy interaction, load the initial files, and,
-if interacting, start the background thread to read the standard input.
-
Performs these steps:
-- Load the dummy interaction, if any
-- Set up exception handling, if any
-- Load the initial files, if any
-- Start the background thread to read the standard input, if any
-- Sit in the GUI event loop indefinitely, if needed
-
-
-
-
-
-
-
- x.ValueBound
-
-
- Signature: IEvent<obj * Type * string>
-
-
-
-
Event fires when a root-level value is bound to an identifier, e.g., via let x = ....
Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers.
-Create an FsiEvaluationSession, reading from the given text input, writing to the given text output and error writers
-The dynamic configuration of the evaluation session
-The command line arguments for the evaluation session
-Read input from the given reader
-Write output to the given writer
-Optionally make the dynamic assembly for the session collectible
-
-
-
- Signature: unit -> FsiEvaluationSessionHostConfig
-
-
-
-
Get a configuration that uses a private inbuilt implementation of the 'fsi' object and does not
-implicitly reference FSharp.Compiler.Interactive.Settings.dll.
Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll,
-an object from another DLL with identical characteristics) to provide an implementation of the configuration.
-FSharp.Compiler.Interactive.Settings.dll is referenced by default.
Get a configuration that uses the 'fsi' object (normally from FSharp.Compiler.Interactive.Settings.dll,
-an object from another DLL with identical characteristics) to provide an implementation of the configuration.
-The flag indicates if FSharp.Compiler.Interactive.Settings.dll is referenced by default.
Request that the given operation be run synchronously on the event loop.
-
-
-
-
-
-
-
- x.EventLoopRun()
-
-
- Signature: unit -> bool
- Modifiers: abstract
-
-
-
-
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.
-
-
-
-
-
-
-
- x.EventLoopScheduleRestart()
-
-
- Signature: unit -> unit
- Modifiers: abstract
-
-
-
-
Schedule a restart for the event loop.
-
-
-
-
-
-
-
- x.FloatingPointFormat
-
-
- Signature: string
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
Indicate a special console "readline" reader for the evaluation session, if any. A "console" gets used if --readline is specified (the default on Windows + .NET); and --fsi-server is not
-given (always combine with --readline-), and OptionalConsoleReadLine is given.
-When a console is used, special rules apply to "peekahead", which allows early typing on the console.
-Peekahead happens if --peekahead- is not specified (the default).
-In this case, a prompt is printed early, a background thread is created and
-the OptionalConsoleReadLine is used to read the first line.
-If a console is not used, then inReader.Peek() is called early instead.
-Further lines are read using OptionalConsoleReadLine().
-If not provided, lines are read using inReader.ReadLine().
-
-
-
-
-
-
-
- x.OnEvaluation
-
-
- Signature: IEvent<EvaluationEventArgs>
-
-
-
-
Hook for listening for evaluation bindings
-
-
-
CompiledName: get_OnEvaluation
-
-
-
-
-
- x.PrintDepth
-
-
- Signature: int
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_PrintDepth
-
-
-
-
-
- x.PrintLength
-
-
- Signature: int
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_PrintLength
-
-
-
-
-
- x.PrintSize
-
-
- Signature: int
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_PrintSize
-
-
-
-
-
- x.PrintWidth
-
-
- Signature: int
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_PrintWidth
-
-
-
-
-
- x.ReportUserCommandLineArgs(arg1)
-
-
- Signature: (string []) -> unit
- Modifiers: abstract
-
-
-
-
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.
-
-
-
-
-
-
-
- x.ShowDeclarationValues
-
-
- Signature: bool
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_ShowDeclarationValues
-
-
-
-
-
- x.ShowIEnumerable
-
-
- Signature: bool
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_ShowIEnumerable
-
-
-
-
-
- x.ShowProperties
-
-
- Signature: bool
- Modifiers: abstract
-
-
-
-
Called by the evaluation session to ask the host for parameters to format text for output
-
-
-
CompiledName: get_ShowProperties
-
-
-
-
-
- x.StartServer(fsiServerName)
-
-
- Signature: fsiServerName:string -> unit
- Modifiers: abstract
-
-
-
-
The evaluation session calls this at an appropriate point in the startup phase if the --fsi-server parameter was given
Operations supported by the currently executing F# Interactive session.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.AddPrinter(arg1)
-
-
- Signature: (('T -> string)) -> unit
- Type parameters: 'T
-
-
-
Register a printer that controls the output of the interactive session.
-
-
-
-
-
-
-
- x.AddPrintTransformer(arg1)
-
-
- Signature: (('T -> obj)) -> unit
- Type parameters: 'T
-
-
-
Register a print transformer that controls the output of the interactive session.
-
-
-
-
-
-
-
- x.CommandLineArgs()
-
-
- Signature: unit -> string []
-
-
-
-
The command line arguments after ignoring the arguments relevant to the interactive
-environment and replacing the first argument with the name of the last script file,
-if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments
-'test2.fs', 'hello', 'goodbye'. This value will normally be different to those
-returned by System.Environment.GetCommandLineArgs.
-
-
-
CompiledName: set_CommandLineArgs
-
-
-
-
-
- x.CommandLineArgs()
-
-
- Signature: unit -> unit
-
-
-
-
The command line arguments after ignoring the arguments relevant to the interactive
-environment and replacing the first argument with the name of the last script file,
-if any. Thus 'fsi.exe test1.fs test2.fs -- hello goodbye' will give arguments
-'test2.fs', 'hello', 'goodbye'. This value will normally be different to those
-returned by System.Environment.GetCommandLineArgs.
-
-
-
CompiledName: get_CommandLineArgs
-
-
-
-
-
- x.EventLoop()
-
-
- Signature: unit -> IEventLoop
-
-
-
-
Gets or sets a the current event loop being used to process interactions.
-
-
-
CompiledName: set_EventLoop
-
-
-
-
-
- x.EventLoop()
-
-
- Signature: unit -> unit
-
-
-
-
Gets or sets a the current event loop being used to process interactions.
-
-
-
CompiledName: get_EventLoop
-
-
-
-
-
- x.FloatingPointFormat()
-
-
- Signature: unit -> string
-
-
-
-
Get or set the floating point format used in the output of the interactive session.
-
-
-
CompiledName: set_FloatingPointFormat
-
-
-
-
-
- x.FloatingPointFormat()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set the floating point format used in the output of the interactive session.
-
-
-
CompiledName: get_FloatingPointFormat
-
-
-
-
-
- x.FormatProvider()
-
-
- Signature: unit -> IFormatProvider
-
-
-
-
Get or set the format provider used in the output of the interactive session.
-
-
-
CompiledName: set_FormatProvider
-
-
-
-
-
- x.FormatProvider()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set the format provider used in the output of the interactive session.
-
-
-
CompiledName: get_FormatProvider
-
-
-
-
-
- x.PrintDepth()
-
-
- Signature: unit -> int
-
-
-
-
Get or set the print depth of the interactive session.
-
-
-
CompiledName: set_PrintDepth
-
-
-
-
-
- x.PrintDepth()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set the print depth of the interactive session.
-
-
-
CompiledName: get_PrintDepth
-
-
-
-
-
- x.PrintLength()
-
-
- Signature: unit -> int
-
-
-
-
Get or set the total print length of the interactive session.
-
-
-
CompiledName: set_PrintLength
-
-
-
-
-
- x.PrintLength()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set the total print length of the interactive session.
-
-
-
CompiledName: get_PrintLength
-
-
-
-
-
- x.PrintSize()
-
-
- Signature: unit -> int
-
-
-
-
Get or set the total print size of the interactive session.
-
-
-
CompiledName: set_PrintSize
-
-
-
-
-
- x.PrintSize()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set the total print size of the interactive session.
-
-
-
CompiledName: get_PrintSize
-
-
-
-
-
- x.PrintWidth()
-
-
- Signature: unit -> int
-
-
-
-
Get or set the print width of the interactive session.
-
-
-
CompiledName: set_PrintWidth
-
-
-
-
-
- x.PrintWidth()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set the print width of the interactive session.
-
-
-
CompiledName: get_PrintWidth
-
-
-
-
-
- x.ShowDeclarationValues()
-
-
- Signature: unit -> bool
-
-
-
-
When set to 'false', disables the display of declaration values in the output of the interactive session.
-
-
-
CompiledName: set_ShowDeclarationValues
-
-
-
-
-
- x.ShowDeclarationValues()
-
-
- Signature: unit -> unit
-
-
-
-
When set to 'false', disables the display of declaration values in the output of the interactive session.
-
-
-
CompiledName: get_ShowDeclarationValues
-
-
-
-
-
- x.ShowIEnumerable()
-
-
- Signature: unit -> bool
-
-
-
-
When set to 'false', disables the display of sequences in the output of the interactive session.
-
-
-
CompiledName: set_ShowIEnumerable
-
-
-
-
-
- x.ShowIEnumerable()
-
-
- Signature: unit -> unit
-
-
-
-
When set to 'false', disables the display of sequences in the output of the interactive session.
-
-
-
CompiledName: get_ShowIEnumerable
-
-
-
-
-
- x.ShowProperties()
-
-
- Signature: unit -> bool
-
-
-
-
When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session.
-
-
-
CompiledName: set_ShowProperties
-
-
-
-
-
- x.ShowProperties()
-
-
- Signature: unit -> unit
-
-
-
-
When set to 'false', disables the display of properties of evaluated objects in the output of the interactive session.
Operations supported by the currently executing F# Interactive session.
-
-
-
-
-
-
-
-
-
-
Functions and values
-
-
-
Function or value
Description
-
-
-
-
-
- fsi
-
-
- Signature: InteractiveSettings
-
-
-
-
A default implementation of the 'fsi' object, used by GetDefaultConfiguration(). Note this
-is a different object to FSharp.Compiler.Interactive.Settings.fsi in FSharp.Compiler.Interactive.Settings.dll,
-which can be used as an alternative implementation of the interactive settings if passed as a parameter
-to GetDefaultConfiguration(fsiObj).
Specifies how the 'endline' function in the lexer should continue after
-it reaches end of line or eof. The options are to continue with 'token' function
-or to continue with 'skip' function.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- Skip(LexerIfdefStackEntries,int,range)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
The parser defines a number of tokens for whitespace and
-comments eliminated by the lexer. These carry a specification of
-a continuation for the lexer for continued processing after we've dealt with
-the whitespace.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- Comment(ifdef,int,range)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
-
-
-
-
-
-
-
-
- EndLine(LexerEndlineContinuation)
-
-
- Signature: LexerEndlineContinuation
-
-
-
-
-
-
-
-
-
- IfDefSkip(ifdef,int,range)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
-
-
-
-
-
-
-
-
- MLOnly(ifdef,range)
-
-
- Signature: LexerIfdefStackEntries * range
-
-
-
-
-
-
-
-
-
- SingleLineComment(ifdef,int,range)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
-
-
-
-
-
-
-
-
- String(ifdef,range)
-
-
- Signature: LexerIfdefStackEntries * range
-
-
-
-
-
-
-
-
-
- StringInComment(ifdef,int,range)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
-
-
-
-
-
-
-
-
- Token(ifdef)
-
-
- Signature: LexerIfdefStackEntries
-
-
-
-
-
-
-
-
-
- TripleQuoteString(ifdef,range)
-
-
- Signature: LexerIfdefStackEntries * range
-
-
-
-
-
-
-
-
-
- TripleQuoteStringInComment(...)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
-
-
-
-
-
-
-
-
- VerbatimString(ifdef,range)
-
-
- Signature: LexerIfdefStackEntries * range
-
-
-
-
-
-
-
-
-
- VerbatimStringInComment(ifdef,int,range)
-
-
- Signature: LexerIfdefStackEntries * int * range
-
The error raised by the parseerrorrich function, which is called by the parser engine
-when a syntax error occurs. The first object is the ParseErrorContext which contains a dump of
-information about the grammar at the point where the error occurred, e.g. what tokens
-are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs.
Specifies how the 'endline' function in the lexer should continue after
-it reaches end of line or eof. The options are to continue with 'token' function
-or to continue with 'skip' function.
The parser defines a number of tokens for whitespace and
-comments eliminated by the lexer. These carry a specification of
-a continuation for the lexer for continued processing after we've dealt with
-the whitespace.
The error raised by the parseerrorrich function, which is called by the parser engine
-when a syntax error occurs. The first object is the ParseErrorContext which contains a dump of
-information about the grammar at the point where the error occurred, e.g. what tokens
-are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs.
Try to chop "get" or "set" from a string.
-If the string does not start with "get" or "set", this function raises an exception.
-
-
-
-
-
-
-
- CompileOpName
-
-
- Signature: string -> string
-
-
-
-
Compiles an operator into a mangled operator name.
-For example, "!%" becomes "op_DereferencePercent".
-This function accepts both built-in and custom operators.
Decompiles a mangled operator name back into an operator.
-For example, "op_DereferencePercent" becomes "!%".
-This function accepts mangled names for both built-in and custom operators.
Determines if the specified name is a valid name for an active pattern.
-
-
-
-
-
-
-
- IsCompilerGeneratedName(nm)
-
-
- Signature: nm:string -> bool
-
-
-
-
-
-
-
-
-
- IsIdentifierFirstCharacter(c)
-
-
- Signature: c:char -> bool
-
-
-
-
The characters that are allowed to be the first character of an identifier.
-
-
-
-
-
-
-
- IsIdentifierPartCharacter(c)
-
-
- Signature: c:char -> bool
-
-
-
-
The characters that are allowed to be in an identifier.
-
-
-
-
-
-
-
- IsInfixOperator
-
-
- Signature: string -> bool
-
-
-
-
-
-
-
-
-
- IsLongIdentifierPartCharacter(c)
-
-
- Signature: c:char -> bool
-
-
-
-
Is this character a part of a long identifier?
-
-
-
-
-
-
-
- IsMangledOpName(n)
-
-
- Signature: n:string -> bool
-
-
-
-
-
-
-
-
-
- IsOperatorName(name)
-
-
- Signature: name:string -> bool
-
-
-
-
Returns true if given string is an operator display name, e.g. ( |>> )
-
-
-
-
-
-
-
- IsOperatorOrBacktickedName(name)
-
-
- Signature: name:string -> bool
-
-
-
-
Returns true if given string is an operator or double backticked name, e.g. ( |>> ) or ( long identifier ).
-(where ( long identifier ) is the display name for long identifier).
These methods are very old and are mostly to do with extracting "long identifier islands"
-A.B.C
-from F# source code, an approach taken from pre-F# VS samples for implementing intelliense.
-
This code should really no longer be needed since the language service has access to
-parsed F# source code ASTs. However, the long identifiers are still passed back to GetDeclarations and friends in the
-F# Compiler Service and it's annoyingly hard to remove their use completely.
-
In general it is unlikely much progress will be made by fixing this code - it will be better to
-extract more information from the F# ASTs.
-
It's also surprising how hard even the job of getting long identifier islands can be. For example the code
-below is inaccurate for long identifier chains involving ... identifiers. And there are special cases
-for active pattern names and so on.
-
-
-
-
-
-
Functions and values
-
-
-
Function or value
Description
-
-
-
-
-
- CorrectIdentifierToken(...)
-
-
- Signature: tokenText:string -> tokenTag:int -> int
-
Given a string and a position in that string, find an identifier as
-expected by GotoDefinition. This will work when the cursor is
-immediately before the identifier, within the identifier, or immediately
-after the identifier.
-
'tolerateJustAfter' indicates that we tolerate being one character after the identifier, used
-for goto-definition
-
In general, only identifiers composed from upper/lower letters and '.' are supported, but there
-are a couple of explicitly handled exceptions to allow some common scenarios:
-- When the name contains only letters and '|' symbol, it may be an active pattern, so we
-treat it as a valid identifier - e.g. let ( |Identity| ) a = a
-(but other identifiers that include '|' are not allowed - e.g. '||' operator)
-- It searches for double tick () to see if the identifier could be something likea b``
-
REVIEW: Also support, e.g., operators, performing the necessary mangling.
-(i.e., I would like that the name returned here can be passed as-is
-(post .-chopping) to `GetDeclarationLocation.)
-
In addition, return the position where a . would go if we were making
-a call to DeclItemsForNamesAtPosition for intellisense. This will
-allow us to use find the correct qualified items rather than resorting
-to the more expensive and less accurate environment lookup.
Get the partial long name of the identifier to the left of index.
-For example, for System.DateTime.Now it returns PartialLongName ([|"System"; "DateTime"|], "Now", Some 32), where "32" pos of the last dot.
-
-
-
-
-
-
-
- MagicalAdjustmentConstant
-
-
- Signature: int
-
-
-
-
Puts us after the last character.
-
-
-
-
-
-
-
- TestMemberOrOverrideDeclaration(tokens)
-
-
- Signature: tokens:FSharpTokenInfo [] -> bool
-
-
-
-
Tests whether the user is typing something like "member x." or "override (comment) x."
- Namespace: FSharp.Compiler
- Parent Module: Range
-
-
-
-
-
-
-
Functions and values
-
-
-
Function or value
Description
-
-
-
-
-
- fromZ(arg1)
-
-
- Signature: Line0 -> int
-
-
-
-
Convert a line number from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages)
-
-
-
-
-
-
-
- toZ(arg1)
-
-
- Signature: int -> Line0
-
-
-
-
Convert a line number from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio)
- Namespace: FSharp.Compiler
- Parent Module: Range
-
-
-
-
-
-
-
Functions and values
-
-
-
Function or value
Description
-
-
-
-
-
- fromZ line column
-
-
- Signature: line:Line0 -> column:int -> pos
-
-
-
-
Convert a position from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages)
-
-
-
-
-
-
-
- toZ(arg1)
-
-
- Signature: pos -> Pos01
-
-
-
-
Convert a position from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio)
- Namespace: FSharp.Compiler
- Parent Module: Range
-
-
-
-
-
-
-
Functions and values
-
-
-
Function or value
Description
-
-
-
-
-
- comparer
-
-
- Signature: IEqualityComparer<range>
-
-
-
-
Equality comparer for range.
-
-
-
-
-
-
-
- toFileZ(arg1)
-
-
- Signature: range -> string * Range01
-
-
-
-
Convert a range from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio)
-
-
-
-
-
-
-
- toZ(arg1)
-
-
- Signature: range -> Range01
-
-
-
-
Convert a range from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio)
The column number for the end position of the range
-
-
-
CompiledName: get_EndColumn
-
-
-
-
-
- x.EndLine
-
-
- Signature: int
-
-
-
-
The line number for the end position of the range
-
-
-
CompiledName: get_EndLine
-
-
-
-
-
- x.EndRange
-
-
- Signature: range
-
-
-
-
The empty range that is located at the end position of the range
-
-
-
CompiledName: get_EndRange
-
-
-
-
-
- x.FileIndex
-
-
- Signature: int
-
-
-
-
The file index for the range
-
-
-
CompiledName: get_FileIndex
-
-
-
-
-
- x.FileName
-
-
- Signature: string
-
-
-
-
The file name for the file of the range
-
-
-
CompiledName: get_FileName
-
-
-
-
-
- x.IsSynthetic
-
-
- Signature: bool
-
-
-
-
Synthetic marks ranges which are produced by intermediate compilation phases. This
-bit signifies that the range covers something that should not be visible to language
-service operations like dot-completion.
-
-
-
CompiledName: get_IsSynthetic
-
-
-
-
-
- x.MakeSynthetic()
-
-
- Signature: unit -> range
-
-
-
-
Convert a range to be synthetic
-
-
-
-
-
-
-
- x.Start
-
-
- Signature: pos
-
-
-
-
The start position of the range
-
-
-
CompiledName: get_Start
-
-
-
-
-
- x.StartColumn
-
-
- Signature: int
-
-
-
-
The start column of the range
-
-
-
CompiledName: get_StartColumn
-
-
-
-
-
- x.StartLine
-
-
- Signature: int
-
-
-
-
The start line of the range
-
-
-
CompiledName: get_StartLine
-
-
-
-
-
- x.StartRange
-
-
- Signature: range
-
-
-
-
The empty range that is located at the start position of the range
Get the Reference Assemblies directory for the .NET Framework (on Windows)
-This is added to the default resolution path for
-design-time compilations.
- Signature: unit -> string
- Modifiers: abstract
-
-
-
-
Get the "v4.5.1"-style moniker for the highest installed .NET Framework version.
-This is the value passed back to Resolve if no explicit "mscorlib" has been given.
-
Note: If an explicit "mscorlib" is given, then --noframework is being used, and the whole ReferenceResolver logic is essentially
-unused. However in the future an option may be added to allow an explicit specification of
-a .NET Framework version to use for scripts.
Represents type, module, member, function or value in a compiled assembly.
-
-
-
Record Fields
-
-
-
Record Field
Description
-
-
-
-
-
- AutoOpenParent
-
-
- Signature: Idents option
-
-
-
-
Parent module that has AutoOpen attribute.
-
-
-
-
-
-
-
- CleanedIdents
-
-
- Signature: Idents
-
-
-
-
Entity name parts with removed module suffixes (Ns.M1Module.M2Module.M3.entity -> Ns.M1.M2.M3.entity)
-and replaced compiled names with display names (FSharpEntity.DisplayName, FSharpValueOrFunction.DisplayName).
-Note: all parts are cleaned, not the last one.
-
-
-
-
-
-
-
- FullName
-
-
- Signature: string
-
-
-
-
Full entity name as it's seen in compiled code (raw FSharpEntity.FullName, FSharpValueOrFunction.FullName).
VisitExpr(path, traverseSynExpr, defaultTraverse, expr)
-controls the behavior when a SynExpr is reached; it can just do
-defaultTraverse(expr) if you have no special logic for this node, and want the default processing to pick which sub-node to dive deeper into
-or can inject non-default behavior, which might incorporate:
-traverseSynExpr(subExpr) to recurse deeper on some particular sub-expression based on your own logic
-path helps to track AST nodes that were passed during traversal
-
-
-
-
-
-
-
- x.VisitHashDirective(arg1)
-
-
- Signature: range -> 'T option
- Modifiers: abstract
-
-
-
-
VisitHashDirective allows overriding behavior when visiting hash directives in FSX scripts, like #r, #load and #I.
Matches expressions which are the application of function values
-
-
-
CompiledName: |Application|_|
-
-
-
-
-
- ( |BaseValue|_| )(arg1)
-
-
- Signature: FSharpExpr -> FSharpType option
-
-
-
-
Matches expressions which are uses of the 'base' value
-
-
-
CompiledName: |BaseValue|_|
-
-
-
-
-
- ( |Call|_| )(arg1)
-
-
- Signature: FSharpExpr -> (FSharpExpr option * FSharpMemberOrFunctionOrValue * FSharpType list * FSharpType list * FSharpExpr list) option
-
-
-
-
Matches expressions which are calls to members or module-defined functions. When calling curried functions and members the
-arguments are collapsed to a single collection of arguments, as done in the compiled version of these.
Special expressions at the end of a conditional decision structure in the decision expression node of a DecisionTree .
-The given expressions are passed as values to the decision tree target.
-
-
-
CompiledName: |DecisionTreeSuccess|_|
-
-
-
-
-
- ( |DefaultValue|_| )(arg1)
-
-
- Signature: FSharpExpr -> FSharpType option
-
-
-
-
Matches default-value expressions, including null expressions
completion context cannot be determined due to errors
-
-
-
-
-
-
-
- OpenDeclaration
-
-
- Signature:
-
-
-
-
-
-
-
-
-
- ParameterList(pos,HashSet<string>)
-
-
- Signature: pos * HashSet<string>
-
-
-
-
completing named parameters\setters in parameter list of constructor\method calls
-end of name ast node * list of properties\parameters that were already set
Notify the host that the logical type checking context for a file has now been updated internally
-and that the file has become eligible to be re-typechecked for errors.
- Signature: (parsed:FSharpParseFileResults * filename:string * fileversion:int * source:string * options:FSharpProjectOptions * textSnapshotInfo:obj option * userOpName:string option) -> Async<FSharpCheckFileAnswer option>
-
- Attributes:
-[<Obsolete("This member should no longer be used, please use 'CheckFileInProject'")>]
-
-
-
-
-
- WARNING: This API is obsolete
-
This member should no longer be used, please use 'CheckFileInProject'
-
-
Check a source code file, returning a handle to the results of the parse including
-the reconstructed types in the file.All files except the one being checked are read from the FileSystem APINote: returns NoAntecedent if the background builder is not yet done preparing the type check context for the
-file (e.g. loading references and parsing/checking files in the project that this file depends upon).
-In this case, the caller can either retry, or wait for FileTypeCheckStateIsDirty to be raised for this file.
-
-
-
-
-
-
-
- x.CheckProjectInBackground(...)
-
-
- Signature: (options:FSharpProjectOptions * userOpName:string option) -> unit
-
-
-
-
Set the project to be checked in the background. Overrides any previous call to CheckProjectInBackground
Compile using the given flags. Source files names are resolved via the FileSystem API.
-The output file must be given by a -o flag.
-The first argument is ignored and can just be "fsc.exe".
Compiles to a dynamic assembly using the given flags.
-
The first argument is ignored and can just be "fsc.exe".
-
Any source files names are resolved via the FileSystem API. An output file name must be given by a -o flag, but this will not
-be written - instead a dynamic assembly will be created and loaded.
-
If the 'execute' parameter is given the entry points for the code are executed and
-the given TextWriters are used for the stdout and stderr streams respectively. In this
-case, a global setting is modified during the execution.
-
-
-
-
-
-
-
- x.CurrentQueueLength
-
-
- Signature: int
-
-
-
-
Current queue length of the service, for debug purposes.
-In addition, a single async operation or a step of a background build
-may be in progress - such an operation is not counted in the queue length.
-
-
-
CompiledName: get_CurrentQueueLength
-
-
-
-
-
- x.FileChecked
-
-
- Signature: IEvent<string * obj option>
-
-
-
-
Raised after a check of a file in the background analysis.
-
The event will be raised on a background thread.
-
-
-
CompiledName: get_FileChecked
-
-
-
-
-
- x.FileParsed
-
-
- Signature: IEvent<string * obj option>
-
-
-
-
Raised after a parse of a file in the background analysis.
Like CheckFileInProject, but uses the existing results from the background builder.All files are read from the FileSystem API, including the file being checked.
For a given script file, get the FSharpProjectOptions implied by the #load closure.All files are read from the FileSystem API, except the file being checked.
-
-
-
-
-
-
-
- x.ImplicitlyStartBackgroundWork()
-
-
- Signature: unit -> bool
-
-
-
-
Get or set a flag which controls if background work is started implicitly.
-
If true, calls to CheckFileInProject implicitly start a background check of that project, replacing
-any other background checks in progress. This is useful in IDE applications with spare CPU cycles as
-it prepares the project analysis results for use. The default is 'true'.
-
-
-
CompiledName: set_ImplicitlyStartBackgroundWork
-
-
-
-
-
- x.ImplicitlyStartBackgroundWork()
-
-
- Signature: unit -> unit
-
-
-
-
Get or set a flag which controls if background work is started implicitly.
-
If true, calls to CheckFileInProject implicitly start a background check of that project, replacing
-any other background checks in progress. This is useful in IDE applications with spare CPU cycles as
-it prepares the project analysis results for use. The default is 'true'.
-
-
-
CompiledName: get_ImplicitlyStartBackgroundWork
-
-
-
-
-
- x.InvalidateAll()
-
-
- Signature: unit -> unit
-
-
-
-
This function is called when the entire environment is known to have changed for reasons not encoded in the ProjectOptions of any project/compilation.
This function is called when the configuration is known to have changed for reasons not encoded in the ProjectOptions.
-For example, dependent references may have been deleted or created.
-Start a background compile of the project if a project with the same name has already been seen before.
-An optional string used for tracing compiler operations associated with this request.
-
-
-
-
-
-
-
- x.MatchBraces(...)
-
-
- Signature: (filename:string * source:string * options:FSharpProjectOptions * userOpName:string option) -> Async<(range * range) []>
-
- Attributes:
-[<Obsolete("Please pass FSharpParsingOptions to MatchBraces. If necessary generate FSharpParsingOptions from FSharpProjectOptions by calling checker.GetParsingOptionsFromProjectOptions(options)")>]
-
-
-
-
-
- WARNING: This API is obsolete
-
Please pass FSharpParsingOptions to MatchBraces. If necessary generate FSharpParsingOptions from FSharpProjectOptions by calling checker.GetParsingOptionsFromProjectOptions(options)
-
-
Parse a source code file, returning information about brace matching in the file.
-Return an enumeration of the matching parenthetical tokens in the file.
Parse a source code file, returning information about brace matching in the file.
-Return an enumeration of the matching parenthetical tokens in the file.
-
-
-
-
-
-
-
- x.MaxMemory()
-
-
- Signature: unit -> int
-
-
-
-
A maximum number of megabytes of allocated memory. If the figure reported by System.GC.GetTotalMemory(false) goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum.
-
-
-
CompiledName: set_MaxMemory
-
-
-
-
-
- x.MaxMemory()
-
-
- Signature: unit -> unit
-
-
-
-
A maximum number of megabytes of allocated memory. If the figure reported by System.GC.GetTotalMemory(false) goes over this limit, the FSharpChecker object will attempt to free memory and reduce cache sizes to a minimum.
-
-
-
CompiledName: get_MaxMemory
-
-
-
-
-
- x.MaxMemoryReached
-
-
- Signature: IEvent<unit>
-
-
-
-
Raised after the maxMB memory threshold limit is reached
Parses a source code for a file and caches the results. Returns an AST that can be traversed for various features.
-
-
-
-
-
-
-
- x.ParseFileInProject(...)
-
-
- Signature: (filename:string * source:string * options:FSharpProjectOptions * userOpName:string option) -> Async<FSharpParseFileResults>
-
- Attributes:
-[<Obsolete("Please call checker.ParseFile instead. To do this, you must also pass FSharpParsingOptions instead of FSharpProjectOptions. If necessary generate FSharpParsingOptions from FSharpProjectOptions by calling checker.GetParsingOptionsFromProjectOptions(options)")>]
-
-
-
-
-
- WARNING: This API is obsolete
-
Please call checker.ParseFile instead. To do this, you must also pass FSharpParsingOptions instead of FSharpProjectOptions. If necessary generate FSharpParsingOptions from FSharpProjectOptions by calling checker.GetParsingOptionsFromProjectOptions(options)
-
-
Parses a source code for a file. Returns an AST that can be traversed for various features.
Try to get type check results for a file. This looks up the results of recent type checks of the
-same file, regardless of contents. The version tag specified in the original check of the file is returned.
-If the source of the file has changed the results returned by this function may be out of date, though may
-still be usable for generating intellisense menus and information.
Indicates the set of files which must be watched to accurately track changes that affect these results,
-Clients interested in reacting to updates to these files should watch these files and take actions as described
-in the documentation for compiler service.
-
-
-
CompiledName: get_DependencyFiles
-
-
-
-
-
- x.Errors
-
-
- Signature: FSharpErrorInfo []
-
-
-
-
The errors returned by parsing a source file.
-
-
-
CompiledName: get_Errors
-
-
-
-
-
- x.GetAllUsesOfAllSymbolsInFile()
-
-
- Signature: unit -> Async<FSharpSymbolUse []>
-
-
-
-
Get all textual usages of all symbols throughout the file
Compute the Visual Studio F1-help key identifier for the given location, based on name resolution results
-
-
-
-
-
-
-
- x.GetFormatSpecifierLocations()
-
-
- Signature: unit -> range []
-
- Attributes:
-[<Obsolete("This member has been replaced by GetFormatSpecifierLocationsAndArity, which returns both range and arity of specifiers")>]
-
-
-
-
-
- WARNING: This API is obsolete
-
This member has been replaced by GetFormatSpecifierLocationsAndArity, which returns both range and arity of specifiers
-
-
Get the locations of format specifiers
-
-
-
-
-
-
-
- x.GetFormatSpecifierLocationsAndArity()
-
-
- Signature: unit -> (range * int) []
-
-
-
-
Get the locations of and number of arguments associated with format specifiers
Get the textual usages that resolved to the given symbol throughout the file
-
-
-
-
-
-
-
- x.HasFullTypeCheckInfo
-
-
- Signature: bool
-
-
-
-
Indicates whether type checking successfully occurred with some results returned. If false, indicates that
-an unrecoverable error in earlier checking/parsing/resolution steps.
Get a view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false.
-
-
-
CompiledName: get_AssemblyContents
-
-
-
-
-
- x.AssemblySignature
-
-
- Signature: FSharpAssemblySignature
-
-
-
-
Get a view of the overall signature of the assembly. Only valid to use if HasCriticalErrors is false.
-
-
-
CompiledName: get_AssemblySignature
-
-
-
-
-
- x.DependencyFiles
-
-
- Signature: string []
-
-
-
-
Indicates the set of files which must be watched to accurately track changes that affect these results,
-Clients interested in reacting to updates to these files should watch these files and take actions as described
-in the documentation for compiler service.
-
-
-
CompiledName: get_DependencyFiles
-
-
-
-
-
- x.Errors
-
-
- Signature: FSharpErrorInfo []
-
-
-
-
The errors returned by processing the project
-
-
-
CompiledName: get_Errors
-
-
-
-
-
- x.GetAllUsesOfAllSymbols()
-
-
- Signature: unit -> Async<FSharpSymbolUse []>
-
-
-
-
Get all textual usages of all symbols throughout the project
-
-
-
-
-
-
-
- x.GetOptimizedAssemblyContents()
-
-
- Signature: unit -> FSharpAssemblyContents
-
-
-
-
Get an optimized view of the overall contents of the assembly. Only valid to use if HasCriticalErrors is false.
Represents a declaration in F# source code, with information attached ready for display by an editor.
-Returned by GetDeclarations.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Accessibility
-
-
- Signature: FSharpAccessibility option
-
-
-
-
-
CompiledName: get_Accessibility
-
-
-
-
-
- x.DescriptionText
-
-
- Signature: FSharpToolTipText
-
-
-
-
-
CompiledName: get_DescriptionText
-
-
-
-
-
- x.DescriptionTextAsync
-
-
- Signature: Async<FSharpToolTipText>
-
-
-
-
-
CompiledName: get_DescriptionTextAsync
-
-
-
-
-
- x.FullName
-
-
- Signature: string
-
-
-
-
-
CompiledName: get_FullName
-
-
-
-
-
- x.Glyph
-
-
- Signature: FSharpGlyph
-
-
-
-
-
CompiledName: get_Glyph
-
-
-
-
-
- x.IsOwnMember
-
-
- Signature: bool
-
-
-
-
-
CompiledName: get_IsOwnMember
-
-
-
-
-
- x.IsResolved
-
-
- Signature: bool
-
-
-
-
-
CompiledName: get_IsResolved
-
-
-
-
-
- x.Kind
-
-
- Signature: CompletionItemKind
-
-
-
-
-
CompiledName: get_Kind
-
-
-
-
-
- x.MinorPriority
-
-
- Signature: int
-
-
-
-
-
CompiledName: get_MinorPriority
-
-
-
-
-
- x.Name
-
-
- Signature: string
-
-
-
-
Get the display name for the declaration.
-
-
-
CompiledName: get_Name
-
-
-
-
-
- x.NameInCode
-
-
- Signature: string
-
-
-
-
Get the name for the declaration as it's presented in source code.
-
-
-
CompiledName: get_NameInCode
-
-
-
-
-
- x.NamespaceToOpen
-
-
- Signature: string option
-
-
-
-
-
CompiledName: get_NamespaceToOpen
-
-
-
-
-
- x.StructuredDescriptionText
-
-
- Signature: FSharpStructuredToolTipText
-
-
-
-
Get the description text for the declaration. Computing this property may require using compiler
-resources and may trigger execution of a type provider method to retrieve documentation.
-
May return "Loading..." if timeout occurs
-
-
-
CompiledName: get_StructuredDescriptionText
-
-
-
-
-
- x.StructuredDescriptionTextAsync
-
-
- Signature: Async<FSharpStructuredToolTipText>
-
-
-
-
Get the description text, asynchronously. Never returns "Loading...".
Represents the information needed to format types and other information in a style
-suitable for use in F# source text at a particular source location.
-
Acquired via GetDisplayEnvAtLocationAlternate and similar methods. May be passed
-to the Format method on FSharpType and other methods.
A subtype of FSharpSymbol that represents a type definition or module as seen by the F# language
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.AbbreviatedType
-
-
- Signature: FSharpType
-
-
-
-
Get the type abbreviated by an F# type abbreviation
-
-
-
CompiledName: get_AbbreviatedType
-
-
-
-
-
- x.Accessibility
-
-
- Signature: FSharpAccessibility
-
-
-
-
Get the declared accessibility of the type
-
-
-
CompiledName: get_Accessibility
-
-
-
-
-
- x.AccessPath
-
-
- Signature: string
-
-
-
-
Get the path used to address the entity (e.g. "Namespace.Module1.NestedModule2"). Gives
-"global" for items not in a namespace.
-
-
-
CompiledName: get_AccessPath
-
-
-
-
-
- x.ActivePatternCases
-
-
- Signature: FSharpActivePatternCase list
-
-
-
-
Get all active pattern cases defined in all active patterns in the module.
-
-
-
CompiledName: get_ActivePatternCases
-
-
-
-
-
- x.AllCompilationPaths
-
-
- Signature: string list
-
-
-
-
Get all compilation paths, taking Module suffixes into account.
-
-
-
CompiledName: get_AllCompilationPaths
-
-
-
-
-
- x.AllInterfaces
-
-
- Signature: IList<FSharpType>
-
-
-
-
Get all the interface implementations, by walking the type hierarchy
-
-
-
CompiledName: get_AllInterfaces
-
-
-
-
-
- x.ArrayRank
-
-
- Signature: int
-
-
-
-
Get the rank of an array type
-
-
-
CompiledName: get_ArrayRank
-
-
-
-
-
- x.Attributes
-
-
- Signature: IList<FSharpAttribute>
-
-
-
-
Get the declared attributes for the type
-
-
-
CompiledName: get_Attributes
-
-
-
-
-
- x.BaseType
-
-
- Signature: FSharpType option
-
-
-
-
Get the base type, if any
-
-
-
CompiledName: get_BaseType
-
-
-
-
-
- x.CompiledName
-
-
- Signature: string
-
-
-
-
Get the compiled name of the type or module, possibly with `n mangling. This is identical to LogicalName
-unless the CompiledName attribute is used.
-
-
-
CompiledName: get_CompiledName
-
-
-
-
-
- x.DeclarationLocation
-
-
- Signature: range
-
-
-
-
Get the declaration location for the type constructor
-
-
-
CompiledName: get_DeclarationLocation
-
-
-
-
-
- x.DeclaredInterfaces
-
-
- Signature: IList<FSharpType>
-
-
-
-
Get the declared interface implementations
-
-
-
CompiledName: get_DeclaredInterfaces
-
-
-
-
-
- x.DeclaringEntity
-
-
- Signature: FSharpEntity option
-
-
-
-
Get the enclosing entity for the definition
-
-
-
CompiledName: get_DeclaringEntity
-
-
-
-
-
- x.DisplayName
-
-
- Signature: string
-
-
-
-
Get the name of the type or module as displayed in F# code
-
-
-
CompiledName: get_DisplayName
-
-
-
-
-
- x.FSharpDelegateSignature
-
-
- Signature: FSharpDelegateSignature
-
-
-
-
Indicates if the type is a delegate with the given Invoke signature
-
-
-
CompiledName: get_FSharpDelegateSignature
-
-
-
-
-
- x.FSharpFields
-
-
- Signature: IList<FSharpField>
-
-
-
-
Get the fields of a record, class, struct or enum from the perspective of the F# language.
-This includes static fields, the 'val' bindings in classes and structs, and the value definitions in enums.
-For classes, the list may include compiler generated fields implied by the use of primary constructors.
-
-
-
CompiledName: get_FSharpFields
-
-
-
-
-
- x.FullName
-
-
- Signature: string
-
-
-
-
Get the full name of the type or module
-
-
-
CompiledName: get_FullName
-
-
-
-
-
- x.GenericParameters
-
-
- Signature: IList<FSharpGenericParameter>
-
-
-
-
Get the generic parameters, possibly including unit-of-measure parameters
-
-
-
CompiledName: get_GenericParameters
-
-
-
-
-
- x.HasAssemblyCodeRepresentation
-
-
- Signature: bool
-
-
-
-
Indicates if the type is implemented through a mapping to IL assembly code. This is only
-true for types in FSharp.Core.dll
-
-
-
CompiledName: get_HasAssemblyCodeRepresentation
-
-
-
-
-
- x.HasFSharpModuleSuffix
-
-
- Signature: bool
-
-
-
-
Indicates that a module is compiled to a class with the given mangled name. The mangling is reversed during lookup
-
-
-
CompiledName: get_HasFSharpModuleSuffix
-
-
-
-
-
- x.IsArrayType
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is an array type
-
-
-
CompiledName: get_IsArrayType
-
-
-
-
-
- x.IsAttributeType
-
-
- Signature: bool
-
-
-
-
Check if the entity inherits from System.Attribute in its type hierarchy
-
-
-
CompiledName: get_IsAttributeType
-
-
-
-
-
- x.IsByRef
-
-
- Signature: bool
-
-
-
-
Indicates if is the 'byref<_>' type definition used for byref types in F#-compiled assemblies
-
-
-
CompiledName: get_IsByRef
-
-
-
-
-
- x.IsClass
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a class type definition
-
-
-
CompiledName: get_IsClass
-
-
-
-
-
- x.IsDelegate
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a delegate type definition
-
-
-
CompiledName: get_IsDelegate
-
-
-
-
-
- x.IsEnum
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is an enum type definition
-
-
-
CompiledName: get_IsEnum
-
-
-
-
-
- x.IsFSharp
-
-
- Signature: bool
-
-
-
-
Indicates if this is a reference to something in an F#-compiled assembly
-
-
-
CompiledName: get_IsFSharp
-
-
-
-
-
- x.IsFSharpAbbreviation
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a measure, type or exception abbreviation
-
-
-
CompiledName: get_IsFSharpAbbreviation
-
-
-
-
-
- x.IsFSharpExceptionDeclaration
-
-
- Signature: bool
-
-
-
-
Indicates an F# exception declaration
-
-
-
CompiledName: get_IsFSharpExceptionDeclaration
-
-
-
-
-
- x.IsFSharpModule
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is an F# module definition
-
-
-
CompiledName: get_IsFSharpModule
-
-
-
-
-
- x.IsFSharpRecord
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is record type
-
-
-
CompiledName: get_IsFSharpRecord
-
-
-
-
-
- x.IsFSharpUnion
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is union type
-
-
-
CompiledName: get_IsFSharpUnion
-
-
-
-
-
- x.IsInterface
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is an interface type definition
-
-
-
CompiledName: get_IsInterface
-
-
-
-
-
- x.IsMeasure
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a measure definition
-
-
-
CompiledName: get_IsMeasure
-
-
-
-
-
- x.IsNamespace
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a part of a namespace path
-
-
-
CompiledName: get_IsNamespace
-
-
-
-
-
- x.IsOpaque
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a type definition for a reference type where the implementation details are hidden by a signature
-
-
-
CompiledName: get_IsOpaque
-
-
-
-
-
- x.IsProvided
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a provided type
-
-
-
CompiledName: get_IsProvided
-
-
-
-
-
- x.IsProvidedAndErased
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is an erased provided type
-
-
-
CompiledName: get_IsProvidedAndErased
-
-
-
-
-
- x.IsProvidedAndGenerated
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a generated provided type
-
-
-
CompiledName: get_IsProvidedAndGenerated
-
-
-
-
-
- x.IsStaticInstantiation
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a 'fake' symbol related to a static instantiation of a type provider
-
-
-
CompiledName: get_IsStaticInstantiation
-
-
-
-
-
- x.IsUnresolved
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is in an unresolved assembly
-
-
-
CompiledName: get_IsUnresolved
-
-
-
-
-
- x.IsValueType
-
-
- Signature: bool
-
-
-
-
Indicates if the entity is a struct or enum
-
-
-
CompiledName: get_IsValueType
-
-
-
-
-
- x.LogicalName
-
-
- Signature: string
-
-
-
-
Get the name of the type or module, possibly with `n mangling
Represents a checked and reduced expression, as seen by the F# language. The active patterns
-in 'FSharp.Compiler.SourceCodeServices' can be used to analyze information about the expression.
-
Pattern matching is reduced to decision trees and conditional tests. Some other
-constructs may be represented in reduced form.
A subtype of FSharpSymbol that represents a record or union case field as seen by the F# language
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Accessibility
-
-
- Signature: FSharpAccessibility
-
-
-
-
Indicates if the declared visibility of the field, not taking signatures into account
-
-
-
CompiledName: get_Accessibility
-
-
-
-
-
- x.AnonRecordFieldDetails
-
-
- Signature: FSharpAnonRecordTypeDetails * FSharpType [] * int
-
-
-
-
If the field is from an anonymous record type then get the details of the field including the index in the sorted array of fields
-
-
-
CompiledName: get_AnonRecordFieldDetails
-
-
-
-
-
- x.DeclarationLocation
-
-
- Signature: range
-
-
-
-
Get the declaration location of the field
-
-
-
CompiledName: get_DeclarationLocation
-
-
-
-
-
- x.DeclaringEntity
-
-
- Signature: FSharpEntity option
-
-
-
-
Get the declaring entity of this field, if any. Fields from anonymous types do not have a declaring entity
-
-
-
CompiledName: get_DeclaringEntity
-
-
-
-
-
- x.DeclaringUnionCase
-
-
- Signature: FSharpUnionCase option
-
-
-
-
Returns the declaring union case symbol
-
-
-
CompiledName: get_DeclaringUnionCase
-
-
-
-
-
- x.FieldAttributes
-
-
- Signature: IList<FSharpAttribute>
-
-
-
-
Get the attributes attached to generated field
-
-
-
CompiledName: get_FieldAttributes
-
-
-
-
-
- x.FieldType
-
-
- Signature: FSharpType
-
-
-
-
Get the type of the field, w.r.t. the generic parameters of the enclosing type constructor
-
-
-
CompiledName: get_FieldType
-
-
-
-
-
- x.IsAnonRecordField
-
-
- Signature: bool
-
-
-
-
Is this a field from an anonymous record type?
-
-
-
CompiledName: get_IsAnonRecordField
-
-
-
-
-
- x.IsCompilerGenerated
-
-
- Signature: bool
-
-
-
-
Indicates a compiler generated field, not visible to Intellisense or name resolution
-
-
-
CompiledName: get_IsCompilerGenerated
-
-
-
-
-
- x.IsDefaultValue
-
-
- Signature: bool
-
-
-
-
Indicates if the field declared is declared 'DefaultValue'
-
-
-
CompiledName: get_IsDefaultValue
-
-
-
-
-
- x.IsLiteral
-
-
- Signature: bool
-
-
-
-
Indicates if the field has a literal value
-
-
-
CompiledName: get_IsLiteral
-
-
-
-
-
- x.IsMutable
-
-
- Signature: bool
-
-
-
-
Indicates if the field is declared 'static'
-
-
-
CompiledName: get_IsMutable
-
-
-
-
-
- x.IsNameGenerated
-
-
- Signature: bool
-
-
-
-
Indicates if the field name was generated by compiler (e.g. ItemN names in union cases and DataN in exceptions).
-This API returns true for source defined symbols only.
-
-
-
CompiledName: get_IsNameGenerated
-
-
-
-
-
- x.IsStatic
-
-
- Signature: bool
-
-
-
-
Indicates a static field
-
-
-
CompiledName: get_IsStatic
-
-
-
-
-
- x.IsUnionCaseField
-
-
- Signature: bool
-
-
-
-
Indicates if the field is declared in a union case
-
-
-
CompiledName: get_IsUnionCaseField
-
-
-
-
-
- x.IsUnresolved
-
-
- Signature: bool
-
-
-
-
Indicates if the record field is for a type in an unresolved assembly
-
-
-
CompiledName: get_IsUnresolved
-
-
-
-
-
- x.IsVolatile
-
-
- Signature: bool
-
-
-
-
Indicates if the field is declared volatile
-
-
-
CompiledName: get_IsVolatile
-
-
-
-
-
- x.LiteralValue
-
-
- Signature: obj option
-
-
-
-
Get the default initialization info, for static literals
-
-
-
CompiledName: get_LiteralValue
-
-
-
-
-
- x.Name
-
-
- Signature: string
-
-
-
-
Get the name of the field
-
-
-
CompiledName: get_Name
-
-
-
-
-
- x.PropertyAttributes
-
-
- Signature: IList<FSharpAttribute>
-
-
-
-
Get the attributes attached to generated property
-
-
-
CompiledName: get_PropertyAttributes
-
-
-
-
-
- x.XmlDoc
-
-
- Signature: IList<string>
-
-
-
-
Get the in-memory XML documentation for the field, used when code is checked in-memory
-
-
-
CompiledName: get_XmlDoc
-
-
-
-
-
- x.XmlDocSig
-
-
- Signature: string
-
-
-
-
Get the XML documentation signature for .xml file lookup for the field, used for .xml file lookup for compiled code
Indicates the value is aggressively inlined by the .NET runtime
-
-
-
-
-
-
-
- AlwaysInline
-
-
- Signature:
-
-
-
-
Indicates the value is inlined but compiled code for the function still exists, e.g. to satisfy interfaces on objects, but that it is also always inlined
-
-
-
-
-
-
-
- NeverInline
-
-
- Signature:
-
-
-
-
Indicates the value is never inlined
-
-
-
-
-
-
-
- OptionalInline
-
-
- Signature:
-
-
-
-
Indicates the value is optionally inlined
-
-
-
-
-
-
-
- PseudoValue
-
-
- Signature:
-
-
-
-
Indicates the value is inlined and compiled code for the function does not exist
Object to tokenize a line of F# source code, starting with the given lexState. The lexState should be FSharpTokenizerLexState.Initial for
-the first line of text. Returns an array of ranges of the text and two enumerations categorizing the
-tokens and characters covered by that range, i.e. FSharpTokenColorKind and FSharpTokenCharKind. The enumerations
-are somewhat adhoc but useful enough to give good colorization options to the user in an IDE.
-
A new lexState is also returned. An IDE-plugin should in general cache the lexState
-values for each line of the edited code.
A subtype of F# symbol that represents an F# method, property, event, function or value, including extension members.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Accessibility
-
-
- Signature: FSharpAccessibility
-
-
-
-
Get the accessibility information for the member, function or value
-
-
-
CompiledName: get_Accessibility
-
-
-
-
-
- x.ApparentEnclosingEntity
-
-
- Signature: FSharpEntity
-
-
-
-
Get the logical enclosing entity, which for an extension member is type being extended
-
-
-
CompiledName: get_ApparentEnclosingEntity
-
-
-
-
-
- x.Attributes
-
-
- Signature: IList<FSharpAttribute>
-
-
-
-
Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup
-these value references after copying a collection of values.
-
-
-
CompiledName: get_Attributes
-
-
-
-
-
- x.CompiledName
-
-
- Signature: string
-
-
-
-
Get the member name in compiled code
-
-
-
CompiledName: get_CompiledName
-
-
-
-
-
- x.CurriedParameterGroups
-
-
- Signature: IList<IList<FSharpParameter>>
-
-
-
-
-
CompiledName: get_CurriedParameterGroups
-
-
-
-
-
- x.DeclarationLocation
-
-
- Signature: range
-
-
-
-
Get the declaration location of the member, function or value
-
-
-
CompiledName: get_DeclarationLocation
-
-
-
-
-
- x.DeclaringEntity
-
-
- Signature: FSharpEntity option
-
-
-
-
Get the enclosing entity for the definition
-
-
-
CompiledName: get_DeclaringEntity
-
-
-
-
-
- x.DisplayName
-
-
- Signature: string
-
-
-
-
Get the name as presented in F# error messages and documentation
Gets the event symbol implied by the use of a property,
-for the case where the property is actually an F#-declared CLIEvent.
-
Uses of F#-declared events are considered to be properties as far as the language specification
-and this API are concerned.
-
-
-
CompiledName: get_EventForFSharpProperty
-
-
-
-
-
- x.EventIsStandard
-
-
- Signature: bool
-
-
-
-
Indicate if an event can be considered to be a property for the F# type system of type IEvent or IDelegateEvent.
-In this case ReturnParameter will have a type corresponding to the property type. For
-non-standard events, ReturnParameter will have a type corresponding to the delegate type.
- Signature: bool
-
- Attributes:
-[<Obsolete("Renamed to IsPropertyGetterMethod, which returns 'true' only for method symbols, not for property symbols")>]
-
-
-
-
-
- WARNING: This API is obsolete
-
Renamed to IsPropertyGetterMethod, which returns 'true' only for method symbols, not for property symbols
-
-
Indicates if this is a getter method for a property, or a use of a property in getter mode
-
-
-
CompiledName: get_IsGetterMethod
-
-
-
-
-
- x.IsImplicitConstructor
-
-
- Signature: bool
-
-
-
-
Indicates if this is an implicit constructor?
-
-
-
CompiledName: get_IsImplicitConstructor
-
-
-
-
-
- x.IsInstanceMember
-
-
- Signature: bool
-
-
-
-
Indicates if this is an instance member, when seen from F#?
-
-
-
CompiledName: get_IsInstanceMember
-
-
-
-
-
- x.IsInstanceMemberInCompiledCode
-
-
- Signature: bool
-
-
-
-
Indicates if this is an instance member in compiled code.
-
Explanatory note: some members such as IsNone and IsSome on types with UseNullAsTrueValue appear
-as instance members in F# code but are compiled as static members.
-
-
-
CompiledName: get_IsInstanceMemberInCompiledCode
-
-
-
-
-
- x.IsMember
-
-
- Signature: bool
-
-
-
-
Indicates if this is a member, including extension members?
-
-
-
CompiledName: get_IsMember
-
-
-
-
-
- x.IsMemberThisValue
-
-
- Signature: bool
-
-
-
-
Indicates if this is the "x" in "member x.M = ..."
Renamed to IsOverrideOrExplicitInterfaceImplementation
-
-
-
CompiledName: get_IsOverrideOrExplicitMember
-
-
-
-
-
- x.IsProperty
-
-
- Signature: bool
-
-
-
-
Indicates if this is a property member
-
-
-
CompiledName: get_IsProperty
-
-
-
-
-
- x.IsPropertyGetterMethod
-
-
- Signature: bool
-
-
-
-
Indicates if this is a getter method for a property, or a use of a property in getter mode
-
-
-
CompiledName: get_IsPropertyGetterMethod
-
-
-
-
-
- x.IsPropertySetterMethod
-
-
- Signature: bool
-
-
-
-
Indicates if this is a setter method for a property, or a use of a property in setter mode
-
-
-
CompiledName: get_IsPropertySetterMethod
-
-
-
-
-
- x.IsSetterMethod
-
-
- Signature: bool
-
- Attributes:
-[<Obsolete("Renamed to IsPropertySetterMethod, which returns 'true' only for method symbols, not for property symbols")>]
-
-
-
-
-
- WARNING: This API is obsolete
-
Renamed to IsPropertySetterMethod, which returns 'true' only for method symbols, not for property symbols
-
-
Indicates if this is a setter method for a property, or a use of a property in setter mode
-
-
-
CompiledName: get_IsSetterMethod
-
-
-
-
-
- x.IsTypeFunction
-
-
- Signature: bool
-
-
-
-
Indicates if this is an F# type function
-
-
-
CompiledName: get_IsTypeFunction
-
-
-
-
-
- x.IsUnresolved
-
-
- Signature: bool
-
-
-
-
Indicates if the member, function or value is in an unresolved assembly
-
-
-
CompiledName: get_IsUnresolved
-
-
-
-
-
- x.IsValCompiledAsMethod
-
-
- Signature: bool
-
-
-
-
Indicated if this is a value compiled to a method
-
-
-
CompiledName: get_IsValCompiledAsMethod
-
-
-
-
-
- x.IsValue
-
-
- Signature: bool
-
-
-
-
Indicated if this is a value
-
-
-
CompiledName: get_IsValue
-
-
-
-
-
- x.LiteralValue
-
-
- Signature: obj option
-
-
-
-
Indicates if this is a [] value, and if so what value? (may be null)
Gets the overloads for the current method
-matchParameterNumber indicates whether to filter the overloads to match the number of parameters in the current symbol
-
-
-
-
-
-
-
- x.ReturnParameter
-
-
- Signature: FSharpParameter
-
-
-
-
-
CompiledName: get_ReturnParameter
-
-
-
-
-
- x.SetterMethod
-
-
- Signature: FSharpMemberOrFunctionOrValue
-
-
-
-
Get an associated setter method of the property
-
-
-
CompiledName: get_SetterMethod
-
-
-
-
-
- x.XmlDoc
-
-
- Signature: IList<string>
-
-
-
-
Get the in-memory XML documentation for the value, used when code is checked in-memory
-
-
-
CompiledName: get_XmlDoc
-
-
-
-
-
- x.XmlDocSig
-
-
- Signature: string
-
-
-
-
XML documentation signature for the value, used for .xml file lookup for compiled code
Represents one method (or other item) in a method group. The item may represent either a method or
-a single, non-overloaded item such as union case or a named function value.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Description
-
-
- Signature: FSharpToolTipText
-
-
-
-
The formatted description text for the method (or other item)
-
-
-
CompiledName: get_Description
-
-
-
-
-
- x.HasParamArrayArg
-
-
- Signature: bool
-
-
-
-
Does the method support a params list arg?
-
-
-
CompiledName: get_HasParamArrayArg
-
-
-
-
-
- x.HasParameters
-
-
- Signature: bool
-
-
-
-
Does the method support an arguments list? This is always true except for static type instantiations like TP<42,"foo">.
-
-
-
CompiledName: get_HasParameters
-
-
-
-
-
- x.Parameters
-
-
- Signature: FSharpMethodGroupItemParameter []
-
-
-
-
The parameters of the method in the overload set
-
-
-
CompiledName: get_Parameters
-
-
-
-
-
- x.ReturnTypeText
-
-
- Signature: string
-
-
-
-
The formatted type text for the method (or other item)
-
-
-
CompiledName: get_ReturnTypeText
-
-
-
-
-
- x.StaticParameters
-
-
- Signature: FSharpMethodGroupItemParameter []
-
-
-
-
Does the type name or method support a static arguments list, like TP<42,"foo"> or conn.CreateCommand<42, "foo">(arg1, arg2)?
-
-
-
CompiledName: get_StaticParameters
-
-
-
-
-
- x.StructuredDescription
-
-
- Signature: FSharpStructuredToolTipText
-
-
-
-
The structured description representation for the method (or other item)
-
-
-
CompiledName: get_StructuredDescription
-
-
-
-
-
- x.StructuredReturnTypeText
-
-
- Signature: Layout
-
-
-
-
The The structured description representation for the method (or other item)
Represents one parameter for one method (or other item) in a group.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.CanonicalTypeTextForSorting
-
-
- Signature: string
-
-
-
-
A key that can be used for sorting the parameters, used to help sort overloads.
-
-
-
CompiledName: get_CanonicalTypeTextForSorting
-
-
-
-
-
- x.Display
-
-
- Signature: string
-
-
-
-
The text to display for the parameter including its name, its type and visual indicators of other
-information such as whether it is optional.
-
-
-
CompiledName: get_Display
-
-
-
-
-
- x.IsOptional
-
-
- Signature: bool
-
-
-
-
Is the parameter optional
-
-
-
CompiledName: get_IsOptional
-
-
-
-
-
- x.ParameterName
-
-
- Signature: string
-
-
-
-
The name of the parameter.
-
-
-
CompiledName: get_ParameterName
-
-
-
-
-
- x.StructuredDisplay
-
-
- Signature: Layout
-
-
-
-
The structured representation for the parameter including its name, its type and visual indicators of other
-information such as whether it is optional.
Represents result of 'GetNavigationItems' operation - this contains
-all the members and currently selected indices. First level correspond to
-types & modules and second level are methods etc.
A set of information describing a project or script build configuration.
-
-
-
Record Fields
-
-
-
Record Field
Description
-
-
-
-
-
- ExtraProjectInfo
-
-
- Signature: obj option
-
-
-
-
Extra information passed back on event trigger
-
-
-
-
-
-
-
- IsIncompleteTypeCheckEnvironment
-
-
- Signature: bool
-
-
-
-
When true, the typechecking environment is known a priori to be incomplete, for
-example when a .fs file is opened outside of a project. In this case, the number of error
-messages reported is reduced.
-
-
-
-
-
-
-
- LoadTime
-
-
- Signature: DateTime
-
-
-
-
Timestamp of project/script load, used to differentiate between different instances of a project load.
-This ensures that a complete reload of the project or script type checking
-context occurs on project or script unload/reload.
-
-
-
-
-
-
-
- OriginalLoadReferences
-
-
- Signature: (range * string * string) list
-
-
-
-
Unused in this API and should be '[]' when used as user-specified input
-
-
-
-
-
-
-
- OtherOptions
-
-
- Signature: string []
-
-
-
-
Additional command line argument options for the project. These can include additional files and references.
-
-
-
-
-
-
-
- ProjectFileName
-
-
- Signature: string
-
-
-
-
-
-
-
-
-
- ProjectId
-
-
- Signature: string option
-
-
-
-
This is the unique identifier for the project, it is case sensitive. If it's None, will key off of ProjectFileName in our caching.
-
-
-
-
-
-
-
- ReferencedProjects
-
-
- Signature: (string * FSharpProjectOptions) []
-
-
-
-
The command line arguments for the other projects referenced by this project, indexed by the
-exact text used in the "-r:" reference in FSharpProjectOptions.
-
-
-
-
-
-
-
- SourceFiles
-
-
- Signature: string []
-
-
-
-
The files in the project
-
-
-
-
-
-
-
- Stamp
-
-
- Signature: int64 option
-
-
-
-
An optional stamp to uniquely identify this set of options
-If two sets of options both have stamps, then they are considered equal
-if and only if the stamps are equal
-
-
-
-
-
-
-
- UnresolvedReferences
-
-
- Signature: UnresolvedReferencesSet option
-
-
-
-
Unused in this API and should be 'None' when used as user-specified input
-
-
-
-
-
-
-
- UseScriptResolutionRules
-
-
- Signature: bool
-
-
-
-
When true, use the reference resolution rules for scripts rather than the rules for compiler.
Represents a symbol in checked F# source code or a compiled .NET component.
-
The subtype of the symbol may reveal further information and can be one of FSharpEntity, FSharpUnionCase
-FSharpField, FSharpGenericParameter, FSharpStaticParameter, FSharpMemberOrFunctionOrValue, FSharpParameter,
-or FSharpActivePatternCase.
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Assembly
-
-
- Signature: FSharpAssembly
-
-
-
-
Get the assembly declaring this symbol
-
-
-
CompiledName: get_Assembly
-
-
-
-
-
- x.DeclarationLocation
-
-
- Signature: range option
-
-
-
-
Get the declaration location for the symbol
-
-
-
CompiledName: get_DeclarationLocation
-
-
-
-
-
- x.DisplayName
-
-
- Signature: string
-
-
-
-
Gets the short display name for the symbol
-
-
-
CompiledName: get_DisplayName
-
-
-
-
-
- x.FullName
-
-
- Signature: string
-
-
-
-
Get a textual representation of the full name of the symbol. The text returned for some symbols
-may not be a valid identifier path in F# code, but rather a human-readable representation of the symbol.
-
-
-
CompiledName: get_FullName
-
-
-
-
-
- x.GetEffectivelySameAsHash()
-
-
- Signature: unit -> int
-
-
-
-
A hash compatible with the IsEffectivelySameAs relation
-
-
-
-
-
-
-
- x.ImplementationLocation
-
-
- Signature: range option
-
-
-
-
Get the implementation location for the symbol if it was declared in a signature that has an implementation
-
-
-
CompiledName: get_ImplementationLocation
-
-
-
-
-
- x.IsAccessible(arg1)
-
-
- Signature: FSharpAccessibilityRights -> bool
-
-
-
-
Computes if the symbol is accessible for the given accessibility rights
-
-
-
-
-
-
-
- x.IsEffectivelySameAs(other)
-
-
- Signature: other:FSharpSymbol -> bool
-
-
-
-
Return true if two symbols are effectively the same when referred to in F# source code text.
-This sees through signatures (a symbol in a signature will be considered effectively the same as
-the matching symbol in an implementation). In addition, other equivalences are applied
-when the same F# source text implies the same declaration name - for example, constructors
-are considered to be effectively the same symbol as the corresponding type definition.
-
This is the relation used by GetUsesOfSymbol and GetUsesOfSymbolInFile.
-
-
-
-
-
-
-
- x.IsExplicitlySuppressed
-
-
- Signature: bool
-
-
-
-
-
CompiledName: get_IsExplicitlySuppressed
-
-
-
-
-
- x.SignatureLocation
-
-
- Signature: range option
-
-
-
-
Get the signature location for the symbol if it was declared in an implementation
Represents the use of an F# symbol from F# source code
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.DisplayContext
-
-
- Signature: FSharpDisplayContext
-
-
-
-
The display context active at the point where the symbol is used. Can be passed to FSharpType.Format
-and other methods to format items in a way that is suitable for a specific source code location.
-
-
-
CompiledName: get_DisplayContext
-
-
-
-
-
- x.FileName
-
-
- Signature: string
-
-
-
-
The file name the reference occurs in
-
-
-
CompiledName: get_FileName
-
-
-
-
-
- x.IsFromAttribute
-
-
- Signature: bool
-
-
-
-
Indicates if the reference is in an attribute
-
-
-
CompiledName: get_IsFromAttribute
-
-
-
-
-
- x.IsFromComputationExpression
-
-
- Signature: bool
-
-
-
-
Indicates if the reference is either a builder or a custom operation in a computation expression
-
-
-
CompiledName: get_IsFromComputationExpression
-
-
-
-
-
- x.IsFromDefinition
-
-
- Signature: bool
-
-
-
-
Indicates if the reference is a definition for the symbol, either in a signature or implementation
-
-
-
CompiledName: get_IsFromDefinition
-
-
-
-
-
- x.IsFromDispatchSlotImplementation
-
-
- Signature: bool
-
-
-
-
Indicates if the reference is via the member being implemented in a class or object expression
Get all the interface implementations, by walking the type hierarchy, taking into account the instantiation of this type
-if it is an instantiation of a generic type.
-
-
-
CompiledName: get_AllInterfaces
-
-
-
-
-
- x.AnonRecordTypeDetails
-
-
- Signature: FSharpAnonRecordTypeDetails
-
-
-
-
Get the details of the anonymous record type.
-
-
-
CompiledName: get_AnonRecordTypeDetails
-
-
-
-
-
- x.BaseType
-
-
- Signature: FSharpType option
-
-
-
-
Get the base type, if any, taking into account the instantiation of this type
-if it is an instantiation of a generic type.
Adjust the types in a group of curried parameters and return type by removing any occurrences of type inference variables, replacing them
-systematically with lower-case type inference variables such as 'a.
Adjust the types in a group of curried parameters by removing any occurrences of type inference variables, replacing them
-systematically with lower-case type inference variables such as 'a.
Adjust the types in a group of parameters by removing any occurrences of type inference variables, replacing them
-systematically with lower-case type inference variables such as 'a.
Adjust the type in a single parameter by removing any occurrences of type inference variables, replacing them
-systematically with lower-case type inference variables such as 'a.
Adjust a group of types by removing any occurrences of type inference variables, replacing them
-systematically with lower-case type inference variables such as 'a.
-
-
-
-
-
-
-
- FSharpType.Prettify(ty)
-
-
- Signature: ty:FSharpType -> FSharpType
-
-
-
-
Adjust the type by removing any occurrences of type inference variables, replacing them
-systematically with lower-case type inference variables such as 'a.
Get members in the decreasing order of inheritance chain
-
-
-
-
-
-
-
- getMemberNameAndRanges(arg1)
-
-
- Signature: InterfaceData -> (string * range) list
-
-
-
-
Get associated member names and ranges
-In case of properties, intrinsic ranges might not be correct for the purpose of getting
-positions of 'member', which indicate the indentation for generating new members
-
-
-
-
-
-
-
- hasNoInterfaceMember(arg1)
-
-
- Signature: FSharpEntity -> bool
-
-
-
-
Check whether an interface is empty
-
-
-
-
-
-
-
- isInterface(arg1)
-
-
- Signature: FSharpEntity -> bool
-
-
-
-
Check whether an entity is an interface or type abbreviation of an interface
Collapse indicates the way a range/snapshot should be collapsed. Same is for a scope inside
-some kind of scope delimiter, e.g. [| ... |], [ ... ], { ... }, etc. Below is for expressions
-following a binding or the right hand side of a pattern, e.g. let x = ...
Stores the range for a construct, the sub-range that should be collapsed for outlinging,
-a tag for the construct type, and a tag for the collapse style
Collapse indicates the way a range/snapshot should be collapsed. Same is for a scope inside
-some kind of scope delimiter, e.g. [| ... |], [ ... ], { ... }, etc. Below is for expressions
-following a binding or the right hand side of a pattern, e.g. let x = ...
Stores the range for a construct, the sub-range that should be collapsed for outlinging,
-a tag for the construct type, and a tag for the collapse style
Represents whether a debug point should be present for the 'finally' in a 'try .. finally',
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the 'for' in a 'for...' loop,
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for either the
-first or second part of a sequential execution, that is whether the
-construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the 'while' in a 'while...' loop,
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the 'with' in a 'try .. with',
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for a 'let' binding,
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the target
-of a decision tree, that is whether the construct corresponds to a debug
-point in the original source.
Indicates if an expression is an atomic expression.
-
An atomic expression has no whitespace unlessenclosed in parentheses, e.g.
-1, "3", ident, ident.[expr] and (expr). If an atomic expression has type T,
-then the largest expression ending at the same range as the atomic expression
-also has type T.
Represents a long identifier with possible '.' at end.
-
Typically dotms.Length = lid.Length-1, but they may be same if (incomplete) code ends in a dot, e.g. "Foo.Bar."
-The dots mostly matter for parsing, and are typically ignored by the typechecker, but
-if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed
-more freedom about typechecking these expressions.
-LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit)
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- LongIdentWithDots(id,dotms)
-
-
- Signature: LongIdent * range list
-
-
-
-
-
-
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Lid
-
-
- Signature: LongIdent
-
-
-
-
Get the long ident for this construct
-
-
-
CompiledName: get_Lid
-
-
-
-
-
- x.Range
-
-
- Signature: range
-
-
-
-
Gets the syntax range of this constuct
-
-
-
CompiledName: get_Range
-
-
-
-
-
- x.RangeSansAnyExtraDot
-
-
- Signature: range
-
-
-
-
Gets the syntax range for part of this constuct
-
-
-
CompiledName: get_RangeSansAnyExtraDot
-
-
-
-
-
- x.ThereIsAnExtraDotAtTheEnd
-
-
- Signature: bool
-
-
-
-
Indicates if the construct ends in '.' due to error recovery
Represents the syntax tree associated with the name of a type definition or module
-in signature or implementation.
-
This includes the name, attributes, type parameters, constraints, documentation and accessibility
-for a type definition or module. For modules, entries such as the type parameters are
-always empty.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- ComponentInfo(...)
-
-
- Signature: SynAttributes * SynTyparDecl list * SynTypeConstraint list * LongIdent * PreXmlDoc * bool * SynAccess option * range
-
The unchecked abstract syntax tree of constants in F# types and expressions.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- Bool(bool)
-
-
- Signature: bool
-
-
-
-
F# syntax: true, false
-
-
-
-
-
-
-
- Byte(byte)
-
-
- Signature: byte
-
-
-
-
F# syntax: 13uy, 0x40uy, 0oFFuy, 0b0111101uy
-
-
-
-
-
-
-
- Bytes(bytes,range)
-
-
- Signature: byte [] * range
-
-
-
-
F# syntax: verbatim or regular byte string, e.g. "abc"B.
-
Also used internally in the typechecker once an array of unit16 constants
-is detected, to allow more efficient processing of large arrays of uint16 constants.
-
-
-
-
-
-
-
- Char(char)
-
-
- Signature: char
-
-
-
-
F# syntax: 'a'
-
-
-
-
-
-
-
- Decimal(Decimal)
-
-
- Signature: Decimal
-
-
-
-
F# syntax: 23.4M
-
-
-
-
-
-
-
- Double(double)
-
-
- Signature: double
-
-
-
-
F# syntax: 1.30, 1.40e10 etc.
-
-
-
-
-
-
-
- Int16(int16)
-
-
- Signature: int16
-
-
-
-
F# syntax: 13s, 0x4000s, 0o0777s, 0b0111101s
-
-
-
-
-
-
-
- Int32(int32)
-
-
- Signature: int32
-
-
-
-
F# syntax: 13, 0x4000, 0o0777
-
-
-
-
-
-
-
- Int64(int64)
-
-
- Signature: int64
-
-
-
-
F# syntax: 13L
-
-
-
-
-
-
-
- IntPtr(int64)
-
-
- Signature: int64
-
-
-
-
F# syntax: 13n
-
-
-
-
-
-
-
- Measure(constant,SynMeasure)
-
-
- Signature: SynConst * SynMeasure
-
-
-
-
Old comment: "we never iterate, so the const here is not another SynConst.Measure"
-
-
-
-
-
-
-
- SByte(sbyte)
-
-
- Signature: sbyte
-
-
-
-
F# syntax: 13y, 0xFFy, 0o077y, 0b0111101y
-
-
-
-
-
-
-
- Single(single)
-
-
- Signature: single
-
-
-
-
F# syntax: 1.30f, 1.40e10f etc.
-
-
-
-
-
-
-
- String(text,range)
-
-
- Signature: string * range
-
-
-
-
F# syntax: verbatim or regular string, e.g. "abc"
-
-
-
-
-
-
-
- UInt16(uint16)
-
-
- Signature: uint16
-
-
-
-
F# syntax: 13us, 0x4000us, 0o0777us, 0b0111101us
-
-
-
-
-
-
-
- UInt16s(uint16 [])
-
-
- Signature: uint16 []
-
-
-
-
Used internally in the typechecker once an array of unit16 constants
-is detected, to allow more efficient processing of large arrays of uint16 constants.
flag: indicates if the application is syntactically atomic, e.g. f.[1] is atomic, but 'f x' is not
-isInfix is true for the first app of an infix operator, e.g. 1+2
-becomes App(App(+, 1), 2), where the inner node is marked isInfix
First bool indicates if lambda originates from a method. Patterns here are always "simple"
-Second bool indicates if this is a "later" part of an iterated sequence of lambdas
-
F# syntax: fun pat -> expr
-
-
-
-
-
-
-
- Lazy(expr,range)
-
-
- Signature: SynExpr * range
-
-
-
-
F# syntax: lazy expr
-
-
-
-
-
-
-
- LetOrUse(...)
-
-
- Signature: bool * bool * SynBinding list * SynExpr * range
-
-
-
-
F# syntax: let pat = expr in expr
-F# syntax: let f pat1 .. patN = expr in expr
-F# syntax: let rec f pat1 .. patN = expr in expr
-F# syntax: use pat = expr in expr
F# syntax: let! pat = expr in expr
-F# syntax: use! pat = expr in expr
-F# syntax: let! pat = expr and! ... and! ... and! pat = expr in expr
-Computation expressions only
-
-
-
-
-
-
-
- LibraryOnlyILAssembly(...)
-
-
- Signature: ILInstr array * SynType list * SynExpr list * SynType list * range
-
-
-
-
Only used in FSharp.Core
-
-
-
-
-
-
-
- LibraryOnlyStaticOptimization(...)
-
-
- Signature: SynStaticOptimizationConstraint list * SynExpr * SynExpr * range
-
-
-
-
Only used in FSharp.Core
-
-
-
-
-
-
-
- LibraryOnlyUnionCaseFieldGet(...)
-
-
- Signature: SynExpr * LongIdent * int * range
-
-
-
-
Only used in FSharp.Core
-
-
-
-
-
-
-
- LibraryOnlyUnionCaseFieldSet(...)
-
-
- Signature: SynExpr * LongIdent * int * SynExpr * range
-
isOptional: true if preceded by a '?' for an optional named parameter
-altNameRefCell: Normally 'None' except for some compiler-generated
-variables in desugaring pattern matching. See SynSimplePat.Id
-
-
-
-
-
-
-
- LongIdentSet(longDotId,expr,range)
-
-
- Signature: LongIdentWithDots * SynExpr * range
-
-
-
-
F# syntax: ident.ident...ident <- expr
-
-
-
-
-
-
-
- Match(matchSeqPoint,expr,clauses,range)
-
-
- Signature: DebugPointForBinding * SynExpr * SynMatchClause list * range
-
-
-
-
F# syntax: match expr with pat1 -> expr | ... | patN -> exprN
-
-
-
-
-
-
-
- MatchBang(...)
-
-
- Signature: DebugPointForBinding * SynExpr * SynMatchClause list * range
-
Quote(operator, isRaw, quotedSynExpr, isFromQueryExpression, m)
-
-
-
-
-
-
-
- Record(...)
-
-
- Signature: (SynType * SynExpr * range * BlockSeparator option * range) option * (SynExpr * BlockSeparator) option * (RecordFieldName * SynExpr option * BlockSeparator option) list * range
-
-
-
-
F# syntax: { f1=e1; ...; fn=en }
-inherit includes location of separator (for tooling)
-copyOpt contains range of the following WITH part (for tooling)
-every field includes range of separator after the field (for tooling)
Attempt to get the range of the first token or initial portion only - this
-is ad-hoc, just a cheap way to improve a certain 'query custom operation' error range
-
-
-
CompiledName: get_RangeOfFirstPortion
-
-
-
-
-
- x.RangeSansAnyExtraDot
-
-
- Signature: range
-
-
-
-
Get the Range ignoring any (parse error) extra trailing dots
altNameRefCell:
-Normally 'None' except for some compiler-generated variables in desugaring pattern matching.
-Pattern processing sets this reference for hidden variable introduced
-by desugaring pattern matching in arguments. The info indicates an
-alternative (compiler generated) identifier to be used because the
-name of the identifier is already bound.
-
isCompilerGenerated: true if a compiler generated name
-isThisVar: true if 'this' variable in member
-isOptArg: true if a '?' is in front of the name
Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda,
-function definition or other binding point, after the elimination of pattern matching
-from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a
-"fun v -> match v with ..."
Represents the syntax tree for the right-hand-side of a type definition in a signature.
-Note: in practice, using a discriminated union to make a distinction between
-"simple" types and "object oriented" types is not particularly useful.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- Exception(SynExceptionDefnRepr)
-
-
- Signature: SynExceptionDefnRepr
-
-
-
-
-
-
-
-
-
- ObjectModel(kind,memberSigs,range)
-
-
- Signature: SynTypeDefnKind * SynMemberSig list * range
-
-
-
-
Indicates the right right-hand-side is a class, struct, interface or other object-model type
-
-
-
-
-
-
-
- Simple(repr,range)
-
-
- Signature: SynTypeDefnSimpleRepr * range
-
-
-
-
Indicates the right right-hand-side is a record, union or other simple type.
Represents the syntax tree for the core of a simple type definition, in either signature
-or implementation.
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- Enum(cases,range)
-
-
- Signature: SynEnumCase list * range
-
-
-
-
An enum type definition, type X = A = 1 | B = 2
-
-
-
-
-
-
-
- Exception(exnRepr)
-
-
- Signature: SynExceptionDefnRepr
-
-
-
-
An exception definition, "exception E = ..."
-
-
-
-
-
-
-
- General(...)
-
-
- Signature: SynTypeDefnKind * (SynType * range * Ident option) list * (SynValSig * MemberFlags) list * SynField list * bool * bool * SynSimplePats option * range
-
-
-
-
An object oriented type definition. This is not a parse-tree form, but represents the core
-type representation which the type checker splits out from the "ObjectModel" cases of type definitions.
-
-
-
-
-
-
-
- LibraryOnlyILAssembly(ilType,range)
-
-
- Signature: ILType * range
-
-
-
-
A type defined by using an IL assembly representation. Only used in FSharp.Core.
-
F# syntax: "type X = (# "..."#)
-
-
-
-
-
-
-
- None(range)
-
-
- Signature: range
-
-
-
-
An abstract definition, "type X"
-
-
-
-
-
-
-
- Record(accessibility,recordFields,range)
-
-
- Signature: SynAccess option * SynField list * range
-
-
-
-
A record type definition, type X = { A: int; B: int }
-
-
-
-
-
-
-
- TypeAbbrev(detail,rhsType,range)
-
-
- Signature: ParserDetail * SynType * range
-
-
-
-
A type abbreviation, "type X = A.B.C"
-
-
-
-
-
-
-
- Union(accessibility,unionCases,range)
-
-
- Signature: SynAccess option * SynUnionCase list * range
-
Represents whether a debug point should be present for the 'finally' in a 'try .. finally',
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the 'for' in a 'for...' loop,
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for either the
-first or second part of a sequential execution, that is whether the
-construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the 'while' in a 'while...' loop,
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the 'with' in a 'try .. with',
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for a 'let' binding,
-that is whether the construct corresponds to a debug point in the original source.
Represents whether a debug point should be present for the target
-of a decision tree, that is whether the construct corresponds to a debug
-point in the original source.
Indicates if an expression is an atomic expression.
-
An atomic expression has no whitespace unlessenclosed in parentheses, e.g.
-1, "3", ident, ident.[expr] and (expr). If an atomic expression has type T,
-then the largest expression ending at the same range as the atomic expression
-also has type T.
Represents a long identifier with possible '.' at end.
-
Typically dotms.Length = lid.Length-1, but they may be same if (incomplete) code ends in a dot, e.g. "Foo.Bar."
-The dots mostly matter for parsing, and are typically ignored by the typechecker, but
-if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed
-more freedom about typechecking these expressions.
-LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit)
Represents the syntax tree associated with the name of a type definition or module
-in signature or implementation.
-
This includes the name, attributes, type parameters, constraints, documentation and accessibility
-for a type definition or module. For modules, entries such as the type parameters are
-always empty.
Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda,
-function definition or other binding point, after the elimination of pattern matching
-from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a
-"fun v -> match v with ..."
Represents the syntax tree for the right-hand-side of a type definition in a signature.
-Note: in practice, using a discriminated union to make a distinction between
-"simple" types and "object oriented" types is not particularly useful.
Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures.
-
-
-
-
-
-
Functions and values
-
-
-
Function or value
Description
-
-
-
-
-
- AdjustArgsForUnitElimination(...)
-
-
- Signature: infosForArgs:SynArgInfo list list -> SynArgInfo list list
-
-
-
-
Make sure only a solitary unit argument has unit elimination
-
-
-
-
-
-
-
- AdjustMemberArgs memFlags infosForArgs
-
-
- Signature: memFlags:MemberKind -> infosForArgs:'a list list -> 'a list list
- Type parameters: 'a
-
-
-
Transform a property declared using '[static] member P = expr' to a method taking a "unit" argument.
-This is similar to IncorporateEmptyTupledArgForPropertyGetter, but applies to member definitions
-rather than member signatures.
-
-
-
-
-
-
-
- AritiesOfArgs(arg1)
-
-
- Signature: SynValInfo -> int list
-
-
-
-
Get the argument counts for each curried argument group. Used in some adhoc places in tc.fs.
-
-
-
-
-
-
-
- AttribsOfArgData(arg1)
-
-
- Signature: SynArgInfo -> SynAttribute list
-
-
-
-
Get the argument attributes from the syntactic information for an argument.
-
-
-
-
-
-
-
- emptySynValData
-
-
- Signature: SynValData
-
-
-
-
-
-
-
-
-
- HasNoArgs(arg1)
-
-
- Signature: SynValInfo -> bool
-
-
-
-
Determine if a syntactic information represents a member without arguments (which is implicitly a property getter)
-
-
-
-
-
-
-
- HasOptionalArgs(arg1)
-
-
- Signature: SynValInfo -> bool
-
-
-
-
Check if there are any optional arguments in the syntactic argument information. Used when adjusting the
-types of optional arguments for function and member signatures.
Add a parameter entry to the syntactic value information to represent the '()' argument to a property getter. This is
-used for the implicit '()' argument in property getter signature specifications.
-
-
-
-
-
-
-
- IncorporateSelfArg(arg1)
-
-
- Signature: SynValInfo -> SynValInfo
-
-
-
-
Add a parameter entry to the syntactic value information to represent the 'this' argument. This is
-used for the implicit 'this' argument in member signature specifications.
-
-
-
-
-
-
-
- IncorporateSetterArg(arg1)
-
-
- Signature: SynValInfo -> SynValInfo
-
-
-
-
Add a parameter entry to the syntactic value information to represent the value argument for a property setter. This is
-used for the implicit value argument in property setter signature specifications.
-
-
-
-
-
-
-
- InferLambdaArgs(origRhsExpr)
-
-
- Signature: origRhsExpr:SynExpr -> SynArgInfo list list
-
-
-
-
For 'let' definitions, we infer syntactic argument information from the r.h.s. of a definition, if it
-is an immediate 'fun ... -> ...' or 'function ...' expression. This is noted in the F# language specification.
-This does not apply to member definitions.
-
-
-
-
-
-
-
- InferSynArgInfoFromPat(p)
-
-
- Signature: p:SynPat -> SynArgInfo list
-
-
-
-
Infer the syntactic argument info for one or more arguments a pattern.
Infer the syntactic information for a 'let' or 'member' definition, based on the argument pattern,
-any declared return information (e.g. .NET attributes on the return element), and the r.h.s. expression
-in the case of 'let' definitions.
-
-
-
-
-
-
-
- IsOptionalArg(arg1)
-
-
- Signature: SynArgInfo -> bool
-
-
-
-
Check if one particular argument is an optional argument. Used when adjusting the
-types of optional arguments for function and member signatures.
-
-
-
-
-
-
-
- selfMetadata
-
-
- Signature: SynArgInfo list
-
-
-
-
The 'argument' information for the 'this'/'self' parameter in the cases where it is not given explicitly
-
-
-
-
-
-
-
- unitArgData
-
-
- Signature: SynArgInfo list
-
-
-
-
The argument information for a '()' argument
-
-
-
-
-
-
-
- unnamedRetVal
-
-
- Signature: SynArgInfo
-
-
-
-
The 'argument' information for a return value where no attributes are given for the return value (the normal case)
-
-
-
-
-
-
-
- unnamedTopArg
-
-
- Signature: SynArgInfo list
-
-
-
-
The argument information for a curried argument without a name
-
-
-
-
-
-
-
- unnamedTopArg1
-
-
- Signature: SynArgInfo
-
-
-
-
The argument information for an argument without a name
Push non-simple parts of a patten match over onto the r.h.s. of a lambda.
-Return a simple pattern and a function to build a match on the r.h.s. if the pattern is complex
Represents the final form of collected XmlDoc lines
-
-
-
Union Cases
-
-
-
Union Case
Description
-
-
-
-
-
- XmlDoc(string [])
-
-
- Signature: string []
-
-
-
-
-
-
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.NonEmpty
-
-
- Signature: bool
-
-
-
-
-
CompiledName: get_NonEmpty
-
-
-
-
-
Static members
-
-
-
Static member
Description
-
-
-
-
-
- XmlDoc.Empty
-
-
- Signature: XmlDoc
-
-
-
-
-
CompiledName: get_Empty
-
-
-
-
-
- XmlDoc.Merge arg1 arg2
-
-
- Signature: XmlDoc -> XmlDoc -> XmlDoc
-
-
-
-
-
-
-
-
-
- XmlDoc.Process(arg1)
-
-
- Signature: XmlDoc -> XmlDoc
-
-
-
-
This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips,
-see XmlDocumentation.fs in the language service
These methods are very old and are mostly to do with extracting "long identifier islands"
-A.B.C
-from F# source code, an approach taken from pre-F# VS samples for implementing intelliense.
-
This code should really no longer be needed since the language service has access to
-parsed F# source code ASTs. However, the long identifiers are still passed back to GetDeclarations and friends in the
-F# Compiler Service and it's annoyingly hard to remove their use completely.
-
In general it is unlikely much progress will be made by fixing this code - it will be better to
-extract more information from the F# ASTs.
-
It's also surprising how hard even the job of getting long identifier islands can be. For example the code
-below is inaccurate for long identifier chains involving ... identifiers. And there are special cases
-for active pattern names and so on.
Binary reader. Read a .NET binary and concert it to Abstract IL data
-structures.
-
NOTE:
-- The metadata in the loaded modules will be relative to
-those modules, e.g. ILScopeRef.Local will mean "local to
-that module". You must use [rescopeILType] etc. if you want to include
-(i.e. copy) the metadata into your own module.
-
-
-
PDB (debug info) reading/folding:
-The PDB reader is invoked if you give a PDB path
-This indicates if you want to search for PDB files and have the
-reader fold them in. You cannot currently name the pdb file
-directly - you can only name the path. Giving "None" says
-"do not read the PDB file even if one exists".
-
The debug info appears primarily as I_seqpoint annotations in
-the instruction streams. Unfortunately the PDB information does
-not, for example, tell you how to map back from a class definition
-to a source code line number - you will need to explicitly search
-for a sequence point in the code for one of the methods of the
-class. That is not particularly satisfactory, and it may be
-a good idea to build a small library which extracts the information
-you need.
Represents the information needed to format types and other information in a style
-suitable for use in F# source text at a particular source location.
-
Acquired via GetDisplayEnvAtLocationAlternate and similar methods. May be passed
-to the Format method on FSharpType and other methods.
Represents a checked and reduced expression, as seen by the F# language. The active patterns
-in 'FSharp.Compiler.SourceCodeServices' can be used to analyze information about the expression.
-
Pattern matching is reduced to decision trees and conditional tests. Some other
-constructs may be represented in reduced form.
Object to tokenize a line of F# source code, starting with the given lexState. The lexState should be FSharpTokenizerLexState.Initial for
-the first line of text. Returns an array of ranges of the text and two enumerations categorizing the
-tokens and characters covered by that range, i.e. FSharpTokenColorKind and FSharpTokenCharKind. The enumerations
-are somewhat adhoc but useful enough to give good colorization options to the user in an IDE.
-
A new lexState is also returned. An IDE-plugin should in general cache the lexState
-values for each line of the edited code.
Represents one method (or other item) in a method group. The item may represent either a method or
-a single, non-overloaded item such as union case or a named function value.
Represents result of 'GetNavigationItems' operation - this contains
-all the members and currently selected indices. First level correspond to
-types & modules and second level are methods etc.
Represents a symbol in checked F# source code or a compiled .NET component.
-
The subtype of the symbol may reveal further information and can be one of FSharpEntity, FSharpUnionCase
-FSharpField, FSharpGenericParameter, FSharpStaticParameter, FSharpMemberOrFunctionOrValue, FSharpParameter,
-or FSharpActivePatternCase.
A record of options to control structural formatting.
-For F# Interactive properties matching those of this value can be accessed via the 'fsi'
-value.
-
Floating Point format given in the same format accepted by System.Double.ToString,
-e.g. f6 or g15.
-
If ShowProperties is set the printing process will evaluate properties of the values being
-displayed. This may cause additional computation.
-
The ShowIEnumerable is set the printing process will force the evaluation of IEnumerable objects
-to a small, finite depth, as determined by the printing parameters.
-This may lead to additional computation being performed during printing.
-
-From F# Interactive the default settings can be adjusted using, for example,
-
- open FSharp.Compiler.Interactive.Settings;;
- setPrintWidth 120;;
-
A layout is a sequence of strings which have been joined together.
-The strings are classified as words, separators and left and right parenthesis.
-This classification determines where spaces are inserted.
-A joint is either unbreakable, breakable or broken.
-If a joint is broken the RHS layout occurs on the next line with optional indentation.
-A layout can be squashed to for given width which forces breaks as required.
Convert any value to a string using a standard formatter
-Data is typically formatted in a structured format, e.g.
-lists are formatted using the "[1;2]" notation.
-The details of the format are not specified and may change
-from version to version and according to the flags given
-to the F# compiler. The format is intended to be human-readable,
-not machine readable. If alternative generic formats are required
-you should develop your own formatter, using the code in the
-implementation of this file as a starting point.
-
Data from other .NET languages is formatted using a virtual
-call to Object.ToString() on the boxed version of the input.
Convert any value to a layout using the given formatting options. The
-layout can then be processed using formatting display engines such as
-those in the LayoutOps module. anytostring and outputany are
-built using anyto_layout with default format options.
-
-
-
-
-
-
-
- output_any writer (value, arg3)
-
-
- Signature: writer:TextWriter -> (value:'T * Type) -> unit
- Type parameters: 'T
-
-
-
Output any value to a channel using the same set of formatting rules
-as anytostring
-
-
-
-
-
-
-
- output_layout options writer layout
-
-
- Signature: options:FormatOptions -> writer:TextWriter -> layout:Layout -> unit
-
-
-
-
-
-
-
-
-
- output_layout_tagged(...)
-
-
- Signature: options:FormatOptions -> writer:TaggedTextWriter -> layout:Layout -> unit
-
A record of options to control structural formatting.
-For F# Interactive properties matching those of this value can be accessed via the 'fsi'
-value.
-
Floating Point format given in the same format accepted by System.Double.ToString,
-e.g. f6 or g15.
-
If ShowProperties is set the printing process will evaluate properties of the values being
-displayed. This may cause additional computation.
-
The ShowIEnumerable is set the printing process will force the evaluation of IEnumerable objects
-to a small, finite depth, as determined by the printing parameters.
-This may lead to additional computation being performed during printing.
-
-From F# Interactive the default settings can be adjusted using, for example,
-
- open FSharp.Compiler.Interactive.Settings;;
- setPrintWidth 120;;
-
-
-
-
-
Record Fields
-
-
-
Record Field
Description
-
-
-
-
-
- AttributeProcessor
-
-
- Signature: string -> (string * string) list -> bool -> unit
-
-
-
-
-
-
-
-
-
- BindingFlags
-
-
- Signature: BindingFlags
-
-
-
-
-
-
-
-
-
- FloatingPointFormat
-
-
- Signature: string
-
-
-
-
-
-
-
-
-
- FormatProvider
-
-
- Signature: IFormatProvider
-
-
-
-
-
-
-
-
-
- PrintDepth
-
-
- Signature: int
-
-
-
-
-
-
-
-
-
- PrintIntercepts
-
-
- Signature: (IEnvironment -> obj -> Layout option) list
-
A layout is a sequence of strings which have been joined together.
-The strings are classified as words, separators and left and right parenthesis.
-This classification determines where spaces are inserted.
-A joint is either unbreakable, breakable or broken.
-If a joint is broken the RHS layout occurs on the next line with optional indentation.
-A layout can be squashed to for given width which forces breaks as required.
An string which is left parenthesis (no space on the right).
-
-
-
-
-
-
-
- listL selector value
-
-
- Signature: selector:('T -> Layout) -> value:'T list -> Layout
- Type parameters: 'T
-
-
-
Layout like an F# list.
-
-
-
-
-
-
-
- objL(value)
-
-
- Signature: value:obj -> Layout
-
-
-
-
An uninterpreted leaf, to be interpreted into a string
-by the layout engine. This allows leaf layouts for numbers, strings and
-other atoms to be customized according to culture.
For limiting layout of list-like sequences (lists,arrays,etc).
-unfold a list of items using (project and z) making layout list via itemL.
-If reach maxLength (before exhausting) then truncate.
Wraps access to a DependencyManager implementation
-
-
-
Instance members
-
-
-
Instance member
Description
-
-
-
-
-
- x.Key
-
-
- Signature: string
- Modifiers: abstract
-
-
-
-
Key that identifies the types of dependencies that this DependencyManager operates on
-E.g
-nuget: indicates that this DM is for nuget packages
-paket: indicates that this DM is for paket scripts, which manage nuget packages, github source dependencies etc ...
After type checking a file, you can access the inferred signature of a project up to and including the
-checking of the given file through the PartialAssemblySignature property of the TypeCheckResults.
-
The full signature information is available for modules, types, attributes, members, values, functions,
-union cases, record types, units of measure and other F# language constructs.
Now look at the type of the function if used as a first class value. (Aside: the CurriedParameterGroups property contains
-more information like the names of the arguments.)
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-
-
fnVal.FullType// int * int -> unit
-fnVal.FullType.IsFunctionType// int * int -> unit
-fnVal.FullType.GenericArguments.[0]// int * int
-fnVal.FullType.GenericArguments.[0].IsTupleType// int * int
-letargTy1=fnVal.FullType.GenericArguments.[0].GenericArguments.[0]
-
-argTy1.TypeDefinition.DisplayName// int
-
-
-
-
OK, so we got an object representation of the type int * int -> unit, and we have seen the first 'int'. We can find out more about the
-type 'int' as follows, determining that it is a named type, which is an F# type abbreviation, type int = int32:
We can now look at the right-hand-side of the type abbreviation, which is the type int32:
-
1:
-2:
-3:
-
-
letargTy1b=argTy1.TypeDefinition.AbbreviatedType
-argTy1b.TypeDefinition.Namespace// Some "Microsoft.FSharp.Core"
-argTy1b.TypeDefinition.CompiledName// "int32"
-
-
-
-
Again we can now look through the type abbreviation type int32 = System.Int32 to get the
-full information about the type:
-
1:
-2:
-3:
-
-
letargTy1c=argTy1b.TypeDefinition.AbbreviatedType
-argTy1c.TypeDefinition.Namespace// Some "SystemCore"
-argTy1c.TypeDefinition.CompiledName// "Int32"
-
-
-
-
The type checking results for a file also contain information extracted from the project (or script) options
-used in the compilation, called the ProjectContext:
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-
-
letprojectContext=checkFileResults.ProjectContext
-
-forassemblyinprojectContext.GetReferencedAssemblies()do
- matchassembly.FileNamewith
- |None->printfn"compilation referenced an assembly without a file"
- |Somes->printfn"compilation references assembly '%s'"s
-
-
-
-
-
Notes:
-
-
If incomplete code is present, some or all of the attributes may not be quite as expected.
-
-If some assembly references are missing (which is actually very, very common), then 'IsUnresolved' may
-be true on values, members and/or entities related to external assemblies. You should be sure to make your
-code robust against IsUnresolved exceptions.
-
To check whole projects, create a checker, then call parseAndCheckScript. In this case, we just check
-the project for a single script. By specifying a different "projOptions" you can create
-a specification of a larger project.
letassemblySig=projectResults.AssemblySignature
-
-assemblySig.Entities.Count=1// one entity
-assemblySig.Entities.[0].Namespace// one entity
-assemblySig.Entities.[0].DisplayName// "Tmp28D0"
-assemblySig.Entities.[0].MembersFunctionsAndValues.Count// 1
-assemblySig.Entities.[0].MembersFunctionsAndValues.[0].DisplayName// "foo"
-
-
-
-
-
-
namespace System
-
namespace System.IO
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Text
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
This tutorial demonstrates how to call the F# language tokenizer. Given F#
-source code, the tokenizer generates a list of source code lines that contain
-information about tokens on each line. For each token, you can get the type
-of the token, exact location as well as color kind of the token (keyword,
-identifier, number, operator, etc.).
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
Now you can create an instance of FSharpSourceTokenizer. The class takes two
-arguments - the first is the list of defined symbols and the second is the
-file name of the source code. The defined symbols are required because the
-tokenizer handles #if directives. The file name is required only to specify
-locations of the source code (and it does not have to exist):
The tokenizer operates on individual lines rather than on the entire source
-file. After getting a token, the tokenizer also returns new state (as int64 value).
-This can be used to tokenize F# code more efficiently. When source code changes,
-you do not need to re-tokenize the entire file - only the parts that have changed.
To tokenize a single line, we create a FSharpLineTokenizer by calling CreateLineTokenizer
-on the FSharpSourceTokenizer object that we created earlier:
Now, we can write a simple recursive function that calls ScanToken on the tokenizer
-until it returns None (indicating the end of line). When the function succeeds, it
-returns FSharpTokenInfo object with all the interesting details:
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-8:
-9:
-
-
/// Tokenize a single line of F# code
-letrectokenizeLine(tokenizer:FSharpLineTokenizer)state=
- matchtokenizer.ScanToken(state)with
- |Sometok,state->
- // Print token name
- printf"%s "tok.TokenName
- // Tokenize the rest, in the new state
- tokenizeLinetokenizerstate
- |None,state->state
-
-
-
-
The function returns the new state, which is needed if you need to tokenize multiple lines
-and an earlier line ends with a multi-line comment. As an initial state, we can use 0L:
The result is a sequence of tokens with names LET, WHITESPACE, IDENT, EQUALS and INT32.
-There is a number of interesting properties on FSharpTokenInfo including:
-
-
-CharClass and ColorClass return information about the token category that
-can be used for colorizing F# code.
-
-
LeftColumn and RightColumn return the location of the token inside the line.
-
TokenName is the name of the token (as defined in the F# lexer)
-
-
Note that the tokenizer is stateful - if you want to tokenize single line multiple times,
-you need to call CreateLineTokenizer again.
To run the tokenizer on a longer sample code or an entire file, you need to read the
-sample input as a collection of string values:
-
1:
-2:
-3:
-4:
-
-
letlines="""
- // Hello world
- let hello() =
- printfn "Hello world!" """.Split('\r','\n')
-
-
-
-
To tokenize multi-line input, we again need a recursive function that keeps the current
-state. The following function takes the lines as a list of strings (together with line number
-and the current state). We create a new tokenizer for each line and call tokenizeLine
-using the state from the end of the previous line:
/// Print token names for multiple lines of code
-letrectokenizeLinesstatecountlines=
- matchlineswith
- |line::lines->
- // Create tokenizer & tokenize single line
- printfn"\nLine %d"count
- lettokenizer=sourceTok.CreateLineTokenizer(line)
- letstate=tokenizeLinetokenizerstate
- // Tokenize the rest using new state
- tokenizeLinesstate(count+1)lines
- |[]->()
-
-
-
-
The function simply calls tokenizeLine (defined earlier) to print the names of all
-the tokens on each line. We can call it on the previous input with 0L as the initial
-state and 1 as the number of the first line:
Ignoring some unimportant details (like whitespace at the beginning of each line and
-the first line which is just whitespace), the code generates the following output:
It is worth noting that the tokenizer yields multiple LINE_COMMENT tokens and multiple
-STRING_TEXT tokens for each single comment or string (roughly, one for each word), so
-if you want to get the entire text of a comment/string, you need to concatenate the
-tokens.
-
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
val sourceTok : FSharpSourceTokenizer
-
Multiple items type FSharpSourceTokenizer = new : conditionalDefines:string list * fileName:string option -> FSharpSourceTokenizer member CreateBufferTokenizer : bufferFiller:(char [] * int * int -> int) -> FSharpLineTokenizer member CreateLineTokenizer : lineText:string -> FSharpLineTokenizer
-------------------- new : conditionalDefines:string list * fileName:string option -> FSharpSourceTokenizer
-
union case Option.Some: Value: 'T -> Option<'T>
-
val tokenizer : FSharpLineTokenizer
-
member FSharpSourceTokenizer.CreateLineTokenizer : lineText:string -> FSharpLineTokenizer
-
val tokenizeLine : tokenizer:FSharpLineTokenizer -> state:FSharpTokenizerLexState -> FSharpTokenizerLexState
Tokenize a single line of F# code
-
type FSharpLineTokenizer = member ScanToken : lexState:FSharpTokenizerLexState -> FSharpTokenInfo option * FSharpTokenizerLexState static member ColorStateOfLexState : FSharpTokenizerLexState -> FSharpTokenizerColorState static member LexStateOfColorState : FSharpTokenizerColorState -> FSharpTokenizerLexState
-
[<Struct>] val state : FSharpTokenizerLexState
-
member FSharpLineTokenizer.ScanToken : lexState:FSharpTokenizerLexState -> FSharpTokenInfo option * FSharpTokenizerLexState
-
val tok : FSharpTokenInfo
-
val printf : format:Printf.TextWriterFormat<'T> -> 'T
-
FSharpTokenInfo.TokenName: string
-
union case Option.None: Option<'T>
-
[<Struct>] type FSharpTokenizerLexState = { PosBits: int64 OtherBits: int64 } member Equals : FSharpTokenizerLexState -> bool static member Initial : FSharpTokenizerLexState
-
property FSharpTokenizerLexState.Initial: FSharpTokenizerLexState with get
-
val lines : string []
-
val tokenizeLines : state:FSharpTokenizerLexState -> count:int -> lines:string list -> unit
Print token names for multiple lines of code
-
val count : int
-
val lines : string list
-
val line : string
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
Multiple items module List
from Microsoft.FSharp.Collections
-------------------- type List<'T> = | ( [] ) | ( :: ) of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetSlice : startIndex:int option * endIndex:int option -> 'T list member Head : 'T member IsEmpty : bool member Item : index:int -> 'T with get member Length : int member Tail : 'T list ...
This tutorial demonstrates how to get the checked, typed expressions tree (TAST)
-for F# code and how to walk over the tree.
-
This can be used for creating tools such as source code analyzers and refactoring tools.
-You can also combine the information with the API available
-from symbols.
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
letinput2=
- """
-module MyLibrary
-
-open System
-
-let foo(x, y) =
- let msg = String.Concat("Hello", " ", "world")
- if msg.Length > 10 then
- 10
- else
- 20
-
-type MyClass() =
- member x.MyMethod() = 1
- """
-letcheckProjectResults=
- parseAndCheckSingleFile(input2)
-
-checkProjectResults.Errors// should be empty
-
-
-
-
Checked assemblies are made up of a series of checked implementation files. The "file" granularity
-matters in F# because initialization actions are triggered at the granularity of files.
-In this case there is only one implementation file in the project:
Checked assemblies are made up of a series of checked implementation files. The "file" granularity
-matters in F# because initialization actions are triggered at the granularity of files.
-In this case there is only one implementation file in the project:
letrecprintDeclprefixd=
- matchdwith
- |FSharpImplementationFileDeclaration.Entity(e,subDecls)->
- printfn"%sEntity %s was declared and contains %d sub-declarations"prefixe.CompiledNamesubDecls.Length
- forsubDeclinsubDeclsdo
- printDecl(prefix+" ")subDecl
- |FSharpImplementationFileDeclaration.MemberOrFunctionOrValue(v,vs,e)->
- printfn"%sMember or value %s was declared"prefixv.CompiledName
- |FSharpImplementationFileDeclaration.InitAction(e)->
- printfn"%sA top-level expression was declared"prefix
-
-
-fordincheckedFile.Declarationsdo
- printDecl""d
-
-// Entity MyLibrary was declared and contains 4 sub-declarations
-// Member or value foo was declared
-// Entity MyClass was declared and contains 0 sub-declarations
-// Member or value .ctor was declared
-// Member or value MyMethod was declared
-
-
-
-
As can be seen, the only declaration in the implementation file is that of the module MyLibrary, which
-contains fours sub-declarations.
-
-
As an aside, one peculiarity here is that the member declarations (e.g. the "MyMethod" member) are returned as part of the containing module entity, not as part of their class.
-Note that the class constructor is returned as a separate declaration. The class type definition has been "split" into a constructor and the other declarations.
Here 'fooSymbol' is a symbol associated with the declaration of 'foo',
-'fooArgs' represents the formal arguments to the 'foo' function, and 'fooExpression'
-is an expression for the implementation of the 'foo' function.
-
Once you have an expression, you can work with it much like an F# quotation. For example,
-you can find its declaration range and its type:
-
1:
-2:
-
-
fooExpression.Type// shows that the return type of the body expression is 'int'
-fooExpression.Range// shows the declaration range of the expression implementing 'foo'
-
In this tutorial, we looked at basic of working with checked declarations and expressions.
-
In practice, it is also useful to combine the information here
-with some information you can obtain from the symbols
-tutorial.
-
-
namespace System
-
namespace System.IO
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Text
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
member FSharpChecker.ParseAndCheckProject : options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpCheckProjectResults>
-
val input2 : string
-
val checkProjectResults : FSharpCheckProjectResults
-
property FSharpCheckProjectResults.Errors: FSharpErrorInfo [] with get
-
val checkedFile : FSharpImplementationFileContents
-
property FSharpCheckProjectResults.AssemblyContents: FSharpAssemblyContents with get
-
property FSharpAssemblyContents.ImplementationFiles: FSharpImplementationFileContents list with get
-
val printDecl : prefix:string -> d:FSharpImplementationFileDeclaration -> unit
-
val prefix : string
-
val d : FSharpImplementationFileDeclaration
-
type FSharpImplementationFileDeclaration = | Entity of FSharpEntity * FSharpImplementationFileDeclaration list | MemberOrFunctionOrValue of FSharpMemberOrFunctionOrValue * FSharpMemberOrFunctionOrValue list list * FSharpExpr | InitAction of FSharpExpr
-
union case FSharpImplementationFileDeclaration.Entity: FSharpEntity * FSharpImplementationFileDeclaration list -> FSharpImplementationFileDeclaration
-
val e : FSharpEntity
-
val subDecls : FSharpImplementationFileDeclaration list
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
property FSharpEntity.CompiledName: string with get
-
property List.Length: int with get
-
val subDecl : FSharpImplementationFileDeclaration
-
union case FSharpImplementationFileDeclaration.MemberOrFunctionOrValue: FSharpMemberOrFunctionOrValue * FSharpMemberOrFunctionOrValue list list * FSharpExpr -> FSharpImplementationFileDeclaration
-
val v : FSharpMemberOrFunctionOrValue
-
val vs : FSharpMemberOrFunctionOrValue list list
-
val e : FSharpExpr
-
property FSharpMemberOrFunctionOrValue.CompiledName: string with get
-
union case FSharpImplementationFileDeclaration.InitAction: FSharpExpr -> FSharpImplementationFileDeclaration
-
property FSharpImplementationFileContents.Declarations: FSharpImplementationFileDeclaration list with get
-
val myLibraryEntity : FSharpEntity
-
val myLibraryDecls : FSharpImplementationFileDeclaration list
-
val failwith : message:string -> 'T
-
val fooSymbol : FSharpMemberOrFunctionOrValue
-
val fooArgs : FSharpMemberOrFunctionOrValue list list
-
val fooExpression : FSharpExpr
-
property FSharpExpr.Type: FSharpType with get
-
property FSharpExpr.Range: FSharp.Compiler.Range.range with get
-
val visitExpr : f:(FSharpExpr -> unit) -> e:FSharpExpr -> unit
-
val f : (FSharpExpr -> unit)
-
type FSharpExpr = member ImmediateSubExpressions : FSharpExpr list member Range : range member Type : FSharpType
-
module BasicPatterns
from FSharp.Compiler.SourceCodeServices
-
active recognizer AddressOf: FSharpExpr -> FSharpExpr option
-
val lvalueExpr : FSharpExpr
-
active recognizer AddressSet: FSharpExpr -> (FSharpExpr * FSharpExpr) option
-
val rvalueExpr : FSharpExpr
-
active recognizer Application: FSharpExpr -> (FSharpExpr * FSharpType list * FSharpExpr list) option
-
val funcExpr : FSharpExpr
-
val typeArgs : FSharpType list
-
val argExprs : FSharpExpr list
-
val visitExprs : f:(FSharpExpr -> unit) -> exprs:FSharpExpr list -> unit
-
active recognizer Call: FSharpExpr -> (FSharpExpr option * FSharpMemberOrFunctionOrValue * FSharpType list * FSharpType list * FSharpExpr list) option
-
val objExprOpt : FSharpExpr option
-
val memberOrFunc : FSharpMemberOrFunctionOrValue
-
val typeArgs1 : FSharpType list
-
val typeArgs2 : FSharpType list
-
val visitObjArg : f:(FSharpExpr -> unit) -> objOpt:FSharpExpr option -> unit
-
active recognizer Coerce: FSharpExpr -> (FSharpType * FSharpExpr) option
active recognizer LetRec: FSharpExpr -> ((FSharpMemberOrFunctionOrValue * FSharpExpr) list * FSharpExpr) option
-
val recursiveBindings : (FSharpMemberOrFunctionOrValue * FSharpExpr) list
-
Multiple items module List
from Microsoft.FSharp.Collections
-------------------- type List<'T> = | ( [] ) | ( :: ) of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetSlice : startIndex:int option * endIndex:int option -> 'T list member Head : 'T member IsEmpty : bool member Item : index:int -> 'T with get member Length : int member Tail : 'T list ...
-
val iter : action:('T -> unit) -> list:'T list -> unit
-
val snd : tuple:('T1 * 'T2) -> 'T2
-
active recognizer NewArray: FSharpExpr -> (FSharpType * FSharpExpr list) option
-
val arrayType : FSharpType
-
active recognizer NewDelegate: FSharpExpr -> (FSharpType * FSharpExpr) option
-
val delegateType : FSharpType
-
val delegateBodyExpr : FSharpExpr
-
active recognizer NewObject: FSharpExpr -> (FSharpMemberOrFunctionOrValue * FSharpType list * FSharpExpr list) option
-
val objType : FSharpMemberOrFunctionOrValue
-
active recognizer NewRecord: FSharpExpr -> (FSharpType * FSharpExpr list) option
-
val recordType : FSharpType
-
active recognizer NewAnonRecord: FSharpExpr -> (FSharpType * FSharpExpr list) option
-
active recognizer NewTuple: FSharpExpr -> (FSharpType * FSharpExpr list) option
This tutorial demonstrates how to get the untyped abstract syntax tree (AST)
-for F# code and how to walk over the tree. This can be used for creating tools
-such as code formatter, basic refactoring or code navigation tools. The untyped
-syntax tree contains information about the code structure, but does not contain
-types and there are some ambiguities that are resolved only later by the type
-checker. You can also combine the untyped AST information with the API available
-from editor services.
-
-
NOTE: The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
To access the untyped AST, you need to create an instance of FSharpChecker.
-This type represents a context for type checking and parsing and corresponds either
-to a stand-alone F# script file (e.g. opened in Visual Studio) or to a loaded project
-file with multiple files. Once you have an instance of FSharpChecker, you can
-use it to perform "untyped parse" which is the first step of type-checking. The
-second phase is "typed parse" and is used by editor services.
-
To use the interactive checker, reference FSharp.Compiler.Service.dll and open the
-SourceCodeServices namespace:
The untyped parse operation is very fast (compared to type checking, which can
-take notable amount of time) and so we can perform it synchronously. First, we
-need to create FSharpChecker - the constructor takes an argument that
-can be used to notify the checker about file changes (which we ignore).
-
1:
-2:
-
-
// Create an interactive checker instance
-letchecker=FSharpChecker.Create()
-
-
-
-
To get the AST, we define a function that takes file name and the source code
-(the file is only used for location information and does not have to exist).
-We first need to get "interactive checker options" which represents the context.
-For simple tasks, you can use GetProjectOptionsFromScriptRoot which infers
-the context for a script file. Then we use the ParseFile method and
-return the ParseTree property:
/// Get untyped tree for a specified input
-letgetUntypedTree(file,input)=
- // Get compiler options for the 'project' implied by a single script file
- letprojOptions,errors=
- checker.GetProjectOptionsFromScript(file,input)
- |>Async.RunSynchronously
-
- letparsingOptions,_errors=checker.GetParsingOptionsFromProjectOptions(projOptions)
-
- // Run the first phase (untyped parsing) of the compiler
- letparseFileResults=
- checker.ParseFile(file,input,parsingOptions)
- |>Async.RunSynchronously
-
- matchparseFileResults.ParseTreewith
- |Sometree->tree
- |None->failwith"Something went wrong during parsing!"
-
The abstract syntax tree is defined as a number of discriminated unions that represent
-different syntactical elements (such as expressions, patterns, declarations etc.). The best
-way to understand the AST is to look at the definitions in ast.fs in the source
-code.
-
The relevant parts are in the following namespace:
-
1:
-
-
openFSharp.Compiler.Ast
-
-
-
-
When processing the AST, you will typically write a number of mutually recursive functions
-that pattern match on the different syntactical elements. There is a number of elements
-that need to be supported - the top-level element is module or namespace declaration,
-containing declarations inside a module (let bindings, types etc.). A let declaration inside
-a module then contains expression, which can contain patterns.
We start by looking at functions that walk over expressions and patterns - as we walk,
-we print information about the visited elements. For patterns, the input is of type
-SynPat and has a number of cases including Wild (for _ pattern), Named (for
-<pat> as name) and LongIdent (for a Foo.Bar name). Note that the parsed pattern
-is occasionally more complex than what is in the source code (in particular, Named is
-used more often):
/// Walk over a pattern - this is for example used in
-/// let <pat> = <expr> or in the 'match' expression
-letrecvisitPattern=function
- |SynPat.Wild(_)->
- printfn" .. underscore pattern"
- |SynPat.Named(pat,name,_,_,_)->
- visitPatternpat
- printfn" .. named as '%s'"name.idText
- |SynPat.LongIdent(LongIdentWithDots(ident,_),_,_,_,_,_)->
- letnames=String.concat"."[foriinident->i.idText]
- printfn" .. identifier: %s"names
- |pat->printfn" .. other pattern: %A"pat
-
-
-
-
The function is recursive (for nested patterns such as (foo, _) as bar), but it does not
-call any of the functions defined later (because patterns cannot contain other syntactical
-elements).
-
The next function iterates over expressions - this is where most of the work would be and
-there are around 20 cases to cover (type SynExpr. and you'll get completion with other
-options). In the following, we only show how to handle if .. then .. and let .. = ...:
/// Walk over an expression - if expression contains two or three
-/// sub-expressions (two if the 'else' branch is missing), let expression
-/// contains pattern and two sub-expressions
-letrecvisitExpression=function
- |SynExpr.IfThenElse(cond,trueBranch,falseBranchOpt,_,_,_,_)->
- // Visit all sub-expressions
- printfn"Conditional:"
- visitExpressioncond
- visitExpressiontrueBranch
- falseBranchOpt|>Option.itervisitExpression
-
- |SynExpr.LetOrUse(_,_,bindings,body,_)->
- // Visit bindings (there may be multiple
- // for 'let .. = .. and .. = .. in ...'
- printfn"LetOrUse with the following bindings:"
- forbindinginbindingsdo
- let(Binding(access,kind,inlin,mutabl,attrs,xmlDoc,
- data,pat,retInfo,init,m,sp))=binding
- visitPatternpat
- visitExpressioninit
- // Visit the body expression
- printfn"And the following body:"
- visitExpressionbody
- |expr->printfn" - not supported expression: %A"expr
-
-
-
-
The visitExpression function will be called from a function that visits all top-level
-declarations inside a module. In this tutorial, we ignore types and members, but that would
-be another source of calls to visitExpression.
As mentioned earlier, the AST of a file contains a number of module or namespace declarations
-(top-level node) that contain declarations inside a module (let bindings or types) or inside
-a namespace (just types). The following functions walks over declarations - we ignore types,
-nested modules and all other elements and look only at top-level let bindings (values and
-functions):
/// Walk over a list of declarations in a module. This is anything
-/// that you can write as a top-level inside module (let bindings,
-/// nested modules, type declarations etc.)
-letvisitDeclarationsdecls=
- fordeclarationindeclsdo
- matchdeclarationwith
- |SynModuleDecl.Let(isRec,bindings,range)->
- // Let binding as a declaration is similar to let binding
- // as an expression (in visitExpression), but has no body
- forbindinginbindingsdo
- let(Binding(access,kind,inlin,mutabl,attrs,xmlDoc,
- data,pat,retInfo,body,m,sp))=binding
- visitPatternpat
- visitExpressionbody
- |_->printfn" - not supported declaration: %A"declaration
-
-
-
-
The visitDeclarations function will be called from a function that walks over a
-sequence of module or namespace declarations. This corresponds, for example, to a file
-with multiple namespace Foo declarations:
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-8:
-9:
-
-
/// Walk over all module or namespace declarations
-/// (basically 'module Foo =' or 'namespace Foo.Bar')
-/// Note that there is one implicitly, even if the file
-/// does not explicitly define it..
-letvisitModulesAndNamespacesmodulesOrNss=
- formoduleOrNsinmodulesOrNssdo
- let(SynModuleOrNamespace(lid,isRec,isMod,decls,xml,attrs,_,m))=moduleOrNs
- printfn"Namespace or module: %A"lid
- visitDeclarationsdecls
-
-
-
-
Now that we have functions that walk over the elements of the AST (starting from declaration,
-down to expressions and patterns), we can get AST of a sample input and run the above function.
As already discussed, the getUntypedTree function uses FSharpChecker to run the first
-phase (parsing) on the AST and get back the tree. The function requires F# source code together
-with location of the file. The location does not have to exist (it is used only for location
-information) and it can be in both Unix and Windows formats:
// Sample input for the compiler service
-letinput=
- """
- let foo() =
- let msg = "Hello world"
- if true then
- printfn "%s" msg
- """
-
-// File name in Unix format
-letfile="/home/user/Test.fsx"
-
-// Get the AST of sample F# code
-lettree=getUntypedTree(file,SourceText.ofStringinput)
-
-
-
-
When you run the code in F# interactive, you can enter tree;; in the interactive console and
-see pretty printed representation of the data structure - the tree contains a lot of information,
-so this is not particularly readable, but it gives you good idea about how the tree looks.
-
The returned tree value is again a discriminated union that can be two different cases - one case
-is ParsedInput.SigFile which represents F# signature file (*.fsi) and the other one is
-ParsedInput.ImplFile representing regular source code (*.fsx or *.fs). The implementation
-file contains a sequence of modules or namespaces that we can pass to the function implemented
-in the previous step:
-
1:
-2:
-3:
-4:
-5:
-6:
-7:
-
-
// Extract implementation file details
-matchtreewith
-|ParsedInput.ImplFile(implFile)->
- // Extract declarations and walk over them
- let(ParsedImplFileInput(fn,script,name,_,_,modules,_))=implFile
- visitModulesAndNamespacesmodules
-|_->failwith"F# Interface file (*.fsi) not supported."
-
In this tutorial, we looked at basic of working with the untyped abstract syntax tree. This is a
-comprehensive topic, so it is not possible to explain everything in a single article. The
-Fantomas project is a good example of tool based on the untyped
-AST that can help you understand more. In practice, it is also useful to combine the information here
-with some information you can obtain from the editor services discussed in the next
-tutorial.
-
-
namespace System
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-
namespace FSharp.Compiler
-
namespace FSharp.Compiler.SourceCodeServices
-
Multiple items namespace FSharp
-------------------- namespace Microsoft.FSharp
-------------------- type FSharpAttribute = member Format : context:FSharpDisplayContext -> string member AttributeType : FSharpEntity member ConstructorArguments : IList<FSharpType * obj> member IsUnresolved : bool member NamedArguments : IList<FSharpType * string * bool * obj>
-
namespace FSharp.Compiler.Text
-
val checker : FSharpChecker
-
type FSharpChecker = member CheckFileInProject : parsed:FSharpParseFileResults * filename:string * fileversion:int * sourceText:ISourceText * options:FSharpProjectOptions * ?textSnapshotInfo:obj * ?userOpName:string -> Async<FSharpCheckFileAnswer> member CheckProjectInBackground : options:FSharpProjectOptions * ?userOpName:string -> unit member ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients : unit -> unit member Compile : argv:string [] * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member Compile : ast:ParsedInput list * assemblyName:string * outFile:string * dependencies:string list * ?pdbFile:string * ?executable:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int> member CompileToDynamicAssembly : otherFlags:string [] * execute:(TextWriter * TextWriter) option * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member CompileToDynamicAssembly : ast:ParsedInput list * assemblyName:string * dependencies:string list * execute:(TextWriter * TextWriter) option * ?debug:bool * ?noframework:bool * ?userOpName:string -> Async<FSharpErrorInfo [] * int * Assembly option> member FindBackgroundReferencesInFile : filename:string * options:FSharpProjectOptions * symbol:FSharpSymbol * ?userOpName:string -> Async<seq<range>> member GetBackgroundCheckResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults * FSharpCheckFileResults> member GetBackgroundParseResultsForFileInProject : filename:string * options:FSharpProjectOptions * ?userOpName:string -> Async<FSharpParseFileResults> ...
property FSharpParseFileResults.ParseTree: FSharp.Compiler.SyntaxTree.ParsedInput option with get
-
union case Option.Some: Value: 'T -> Option<'T>
-
val tree : FSharp.Compiler.SyntaxTree.ParsedInput
-
union case Option.None: Option<'T>
-
val failwith : message:string -> 'T
-
val visitPattern : (obj -> obj)
Walk over a pattern - this is for example used in let <pat> = <expr> or in the 'match' expression
-
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
-
Multiple items type String = new : value:char[] -> string + 8 overloads member Chars : int -> char member Clone : unit -> obj member CompareTo : value:obj -> int + 1 overload member Contains : value:string -> bool + 3 overloads member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit member EndsWith : value:string -> bool + 3 overloads member Equals : obj:obj -> bool + 2 overloads member GetEnumerator : unit -> CharEnumerator member GetHashCode : unit -> int + 1 overload ...
val concat : sep:string -> strings:seq<string> -> string
-
val visitExpression : (obj -> obj)
Walk over an expression - if expression contains two or three sub-expressions (two if the 'else' branch is missing), let expression contains pattern and two sub-expressions
-
module Option
from Microsoft.FSharp.Core
-
val iter : action:('T -> unit) -> option:'T option -> unit
-
val visitDeclarations : decls:seq<'a> -> unit
Walk over a list of declarations in a module. This is anything that you can write as a top-level inside module (let bindings, nested modules, type declarations etc.)
-
val decls : seq<'a>
-
val declaration : 'a
-
val visitModulesAndNamespaces : modulesOrNss:seq<'a> -> unit
Walk over all module or namespace declarations (basically 'module Foo =' or 'namespace Foo.Bar') Note that there is one implicitly, even if the file does not explicitly define it..
-
-
-
diff --git a/fcs/.config/dotnet-tools.json b/fcs/.config/dotnet-tools.json
index c3e6f5e472..921015529f 100644
--- a/fcs/.config/dotnet-tools.json
+++ b/fcs/.config/dotnet-tools.json
@@ -13,6 +13,12 @@
"commands": [
"paket"
]
+ },
+ "fornax": {
+ "version": "0.13.1",
+ "commands": [
+ "fornax"
+ ]
}
}
}
\ No newline at end of file
diff --git a/fcs/.gitignore b/fcs/.gitignore
index 1ae18f2aa0..0a3b52abf5 100644
--- a/fcs/.gitignore
+++ b/fcs/.gitignore
@@ -11,3 +11,4 @@ FSharp.Compiler.Service.netstandard/pplex.fs
FSharp.Compiler.Service.netstandard/pppars.fs
FSharp.Compiler.Service.netstandard/pppars.fsi
.idea/
+_public
\ No newline at end of file
diff --git a/fcs/build.fsx b/fcs/build.fsx
index 350da96295..1418ed756e 100644
--- a/fcs/build.fsx
+++ b/fcs/build.fsx
@@ -37,6 +37,7 @@ let runDotnet workingDir command args =
let releaseDir = Path.Combine(__SOURCE_DIRECTORY__, "../artifacts/bin/fcs/Release")
let packagesDir = Path.Combine(__SOURCE_DIRECTORY__, "../artifacts/packages/Release/Shipping")
+let docsDir = Path.Combine(__SOURCE_DIRECTORY__, "docsrc", "_public")
// Read release notes & version info from RELEASE_NOTES.md
let release = ReleaseNotes.load (__SOURCE_DIRECTORY__ + "/RELEASE_NOTES.md")
@@ -52,6 +53,7 @@ let buildVersion =
Target.create "Clean" (fun _ ->
Shell.cleanDir releaseDir
+ Shell.cleanDir docsDir
)
Target.create "Restore" (fun _ ->
@@ -90,13 +92,10 @@ Target.create "NuGet" (fun _ ->
}) "FSharp.Compiler.Service.sln"
)
-Target.create "GenerateDocsEn" (fun _ ->
- runDotnet "docsrc/tools" "fake" "run generate.fsx"
+Target.create "GenerateDocs" (fun _ ->
+ runDotnet "docsrc" "fornax" "build"
)
-Target.create "GenerateDocsJa" (fun _ ->
- runDotnet "docsrc/tools" "fake" "run generate.ja.fsx"
-)
open Fake.IO.Globbing.Operators
@@ -169,7 +168,6 @@ Target.create "ValidateVersionBump" (fun _ ->
Target.create "Start" ignore
Target.create "Release" ignore
-Target.create "GenerateDocs" ignore
Target.create "TestAndNuGet" ignore
open Fake.Core.TargetOperators
@@ -177,6 +175,7 @@ open Fake.Core.TargetOperators
"Start"
=?> ("BuildVersion", isAppVeyorBuild)
==> "Restore"
+ ==> "Clean"
==> "Build"
"Build"
@@ -198,11 +197,9 @@ open Fake.Core.TargetOperators
==> "Release"
"Build"
- // ==> "GenerateDocsEn"
==> "GenerateDocs"
"Build"
- // ==> "GenerateDocsJa"
==> "GenerateDocs"
"GenerateDocs"
diff --git a/fcs/docsrc/_lib/Fornax.Core.dll b/fcs/docsrc/_lib/Fornax.Core.dll
new file mode 100644
index 0000000000..b8754840a0
Binary files /dev/null and b/fcs/docsrc/_lib/Fornax.Core.dll differ
diff --git a/fcs/docsrc/config.fsx b/fcs/docsrc/config.fsx
new file mode 100644
index 0000000000..7c8ecd104a
--- /dev/null
+++ b/fcs/docsrc/config.fsx
@@ -0,0 +1,20 @@
+#r "_lib/Fornax.Core.dll"
+
+open Config
+
+let customRename (page: string) =
+ System.IO.Path.ChangeExtension(page.Replace ("content/", ""), ".html")
+
+let isScriptToParse (ap, rp : string) =
+ let folder = System.IO.Path.GetDirectoryName rp
+ folder.Contains "content" && rp.EndsWith ".fsx"
+
+let config = {
+ Generators = [
+ {Script = "page.fsx"; Trigger = OnFileExt ".md"; OutputFile = Custom customRename }
+ {Script = "page.fsx"; Trigger = OnFilePredicate isScriptToParse; OutputFile = Custom customRename }
+ {Script = "apiref.fsx"; Trigger = Once; OutputFile = MultipleFiles (sprintf "reference/%s.html") }
+
+ {Script = "lunr.fsx"; Trigger = Once; OutputFile = NewFileName "index.json" }
+ ]
+}
diff --git a/fcs/docsrc/content/caches.fsx b/fcs/docsrc/content/caches.fsx
index 7f8eaea65f..48b2d0c187 100644
--- a/fcs/docsrc/content/caches.fsx
+++ b/fcs/docsrc/content/caches.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: how-to
+title: Notes on the FSharpChecker caches
+menu_order: 2
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -8,24 +16,24 @@ This is a design note on the FSharpChecker component and its caches. See also t
Each FSharpChecker object maintains a set of caches. These are
-* ``scriptClosureCache`` - an MRU cache of default size ``projectCacheSize`` that caches the
+* ``scriptClosureCache`` - an MRU cache of default size ``projectCacheSize`` that caches the
computation of GetProjectOptionsFromScript. This computation can be lengthy as it can involve processing the transitive closure
of all ``#load`` directives, which in turn can mean parsing an unbounded number of script files
-* ``incrementalBuildersCache`` - an MRU cache of projects where a handle is being kept to their incremental checking state,
- of default size ``projectCacheSize`` (= 3 unless explicitly set as a parameter).
- The "current background project" (see the [FSharpChecker operations queue](queue.html))
+* ``incrementalBuildersCache`` - an MRU cache of projects where a handle is being kept to their incremental checking state,
+ of default size ``projectCacheSize`` (= 3 unless explicitly set as a parameter).
+ The "current background project" (see the [FSharpChecker operations queue](queue.html))
will be one of these projects. When analyzing large collections of projects, this cache usually occupies by far the most memory.
Increasing the size of this cache can dramatically decrease incremental computation of project-wide checking, or of checking
individual files within a project, but can very greatly increase memory usage.
* ``braceMatchCache`` - an MRU cache of size ``braceMatchCacheSize`` (default = 5) keeping the results of calls to MatchBraces, keyed by filename, source and project options.
-* ``parseFileCache`` - an MRU cache of size ``parseFileCacheSize`` (default = 2) keeping the results of ParseFile,
+* ``parseFileCache`` - an MRU cache of size ``parseFileCacheSize`` (default = 2) keeping the results of ParseFile,
keyed by filename, source and project options.
-* ``checkFileInProjectCache`` - an MRU cache of size ``incrementalTypeCheckCacheSize`` (default = 5) keeping the results of
- ParseAndCheckFileInProject, CheckFileInProject and/or CheckFileInProjectIfReady. This is keyed by filename, file source
+* ``checkFileInProjectCache`` - an MRU cache of size ``incrementalTypeCheckCacheSize`` (default = 5) keeping the results of
+ ParseAndCheckFileInProject, CheckFileInProject and/or CheckFileInProjectIfReady. This is keyed by filename, file source
and project options. The results held in this cache are only returned if they would reflect an accurate parse and check of the
file.
@@ -35,8 +43,8 @@ Each FSharpChecker object maintains a set of caches. These are
are all weak references, you can generally ignore this cache, since its entries will be automatically collected.
Strong references to binary readers will be kept by other FCS data structures, e.g. any project checkers, symbols or project checking results.
- In more detail, the bytes for referenced .NET binaries are read into memory all at once, eagerly. Files are not left
- open or memory-mapped when using FSharpChecker (as opposed to FsiEvaluationSession, which loads assemblies using reflection).
+ In more detail, the bytes for referenced .NET binaries are read into memory all at once, eagerly. Files are not left
+ open or memory-mapped when using FSharpChecker (as opposed to FsiEvaluationSession, which loads assemblies using reflection).
The purpose of this cache is mainly to ensure that while setting up compilation, the reads of mscorlib, FSharp.Core and so on
amortize cracking the DLLs.
@@ -46,8 +54,8 @@ Each FSharpChecker object maintains a set of caches. These are
Profiling the memory used by the various caches can be done by looking for the corresponding static roots in memory profiling traces.
-The sizes of some of these caches can be adjusted by giving parameters to FSharpChecker. Unless otherwise noted,
-the cache sizes above indicate the "strong" size of the cache, where memory is held regardless of the memory
+The sizes of some of these caches can be adjusted by giving parameters to FSharpChecker. Unless otherwise noted,
+the cache sizes above indicate the "strong" size of the cache, where memory is held regardless of the memory
pressure on the system. Some of the caches can also hold "weak" references which can be collected at will by the GC.
> Note: Because of these caches, you should generally use one global, shared FSharpChecker for everything in an IDE application.
@@ -58,13 +66,13 @@ Low-Memory Condition
Version 1.4.0.8 added a "maximum memory" limit specified by the `MaxMemory` property on FSharpChecker (in MB). If an FCS project operation
is performed (see `CheckMaxMemoryReached` in `service.fs`) and `System.GC.GetTotalMemory(false)` reports a figure greater than this, then
-the strong sizes of all FCS caches are reduced to either 0 or 1. This happens for the remainder of the lifetime of the FSharpChecker object.
-In practice this will still make tools like the Visual Studio F# Power Tools usable, but some operations like renaming across multiple
+the strong sizes of all FCS caches are reduced to either 0 or 1. This happens for the remainder of the lifetime of the FSharpChecker object.
+In practice this will still make tools like the Visual Studio F# Power Tools usable, but some operations like renaming across multiple
projects may take substantially longer.
-By default the maximum memory trigger is disabled, see `maxMBDefault` in `service.fs`.
+By default the maximum memory trigger is disabled, see `maxMBDefault` in `service.fs`.
-Reducing the FCS strong cache sizes does not guarantee there will be enough memory to continue operations - even holding one project
+Reducing the FCS strong cache sizes does not guarantee there will be enough memory to continue operations - even holding one project
strongly may exceed a process memory budget. It just means FCS may hold less memory strongly.
If you do not want the maximum memory limit to apply then set MaxMemory to System.Int32.MaxValue.
@@ -73,9 +81,9 @@ Summary
-------
In this design note, you learned that the FSharpChecker component keeps a set of caches in order to support common
-incremental analysis scenarios reasonably efficiently. They correspond roughly to the original caches and sizes
+incremental analysis scenarios reasonably efficiently. They correspond roughly to the original caches and sizes
used by the Visual F# Tools, from which the FSharpChecker component derives.
-In long running, highly interactive, multi-project scenarios you should carefully
+In long running, highly interactive, multi-project scenarios you should carefully
consider the cache sizes you are using and the tradeoffs involved between incremental multi-project checking and memory usage.
*)
diff --git a/fcs/docsrc/content/compiler.fsx b/fcs/docsrc/content/compiler.fsx
index dc8d06cbcb..1d0b1527a9 100644
--- a/fcs/docsrc/content/compiler.fsx
+++ b/fcs/docsrc/content/compiler.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Hosted Compiler
+menu_order: 8
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -10,8 +18,8 @@ This tutorial demonstrates how to host the F# compiler.
*)
(**
-> **NOTE:** There are several options for hosting the F# compiler. The easiest one is to use the
-`fsc.exe` process and pass arguments.
+> **NOTE:** There are several options for hosting the F# compiler. The easiest one is to use the
+`fsc.exe` process and pass arguments.
*)
(**
@@ -31,7 +39,7 @@ First, we need to reference the libraries that contain F# interactive service:
open System.IO
open FSharp.Compiler.SourceCodeServices
-// Create an interactive checker instance
+// Create an interactive checker instance
let checker = FSharpChecker.Create()
(**
@@ -45,7 +53,7 @@ let fn3 = Path.ChangeExtension(fn, ".dll")
File.WriteAllText(fn2, """
module M
-type C() =
+type C() =
member x.P = 1
let x = 3 + 4
@@ -55,11 +63,11 @@ let x = 3 + 4
Now invoke the compiler:
*)
-let errors1, exitCode1 =
- checker.Compile([| "fsc.exe"; "-o"; fn3; "-a"; fn2 |])
+let errors1, exitCode1 =
+ checker.Compile([| "fsc.exe"; "-o"; fn3; "-a"; fn2 |])
|> Async.RunSynchronously
-(**
+(**
If errors occur you can see this in the 'exitCode' and the returned array of errors:
@@ -70,7 +78,7 @@ module M
let x = 1.0 + "" // a type error
""")
-let errors1b, exitCode1b =
+let errors1b, exitCode1b =
checker.Compile([| "fsc.exe"; "-o"; fn3; "-a"; fn2 |])
|> Async.RunSynchronously
@@ -85,16 +93,16 @@ is not really an option.
You still have to pass the "-o" option to name the output file, but the output file is not actually written to disk.
-The 'None' option indicates that the initialization code for the assembly is not executed.
+The 'None' option indicates that the initialization code for the assembly is not executed.
*)
-let errors2, exitCode2, dynAssembly2 =
+let errors2, exitCode2, dynAssembly2 =
checker.CompileToDynamicAssembly([| "-o"; fn3; "-a"; fn2 |], execute=None)
|> Async.RunSynchronously
(*
Passing 'Some' for the 'execute' parameter executes the initialization code for the assembly.
*)
-let errors3, exitCode3, dynAssembly3 =
+let errors3, exitCode3, dynAssembly3 =
checker.CompileToDynamicAssembly([| "-o"; fn3; "-a"; fn2 |], Some(stdout,stderr))
|> Async.RunSynchronously
diff --git a/fcs/docsrc/content/corelib.fsx b/fcs/docsrc/content/corelib.fsx
index 8a7f33b16f..3e7dc66c6e 100644
--- a/fcs/docsrc/content/corelib.fsx
+++ b/fcs/docsrc/content/corelib.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: how-to
+title: Notes on FSharp.Core.dll
+menu_order: 3
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
diff --git a/fcs/docsrc/content/devnotes.md b/fcs/docsrc/content/devnotes.md
index 98684f9f35..7cbd0b6d65 100644
--- a/fcs/docsrc/content/devnotes.md
+++ b/fcs/docsrc/content/devnotes.md
@@ -1,3 +1,9 @@
+---
+title: Developer Notes
+category: explanation
+menu_order: 2
+---
+
Developer notes
===============
@@ -6,9 +12,9 @@ and F# interactive as services.
## Components
-There is one main component, `FSharp.Compiler.Service.dll`.
-The main aim is to have a stable and documented fork of the main compiler that allows various
-tools to share this common code.
+There is one main component, `FSharp.Compiler.Service.dll`.
+The main aim is to have a stable and documented fork of the main compiler that allows various
+tools to share this common code.
This component allows embedding F# Interactive as a service and contains a number of
modifications to the source code of `fsi.exe` that adds `EvalExpression` and `EvalInteraction` functions.
@@ -19,7 +25,7 @@ This repo should be _identical_ to 'fsharp' except:
- Only build `FSharp.Compiler.Service.dll`
- No bootstrap or proto compiler is used - an installed F# compiler is assumed
- - Build script using FAKE that builds everything, produces NuGet package and
+ - Build script using FAKE that builds everything, produces NuGet package and
generates documentation, files for publishing NuGet packages etc.
(following [F# project scaffold](https://github.com/fsprojects/FSharp.ProjectScaffold))
diff --git a/fcs/docsrc/content/editor.fsx b/fcs/docsrc/content/editor.fsx
index 26bb465dde..9c0f3fca26 100644
--- a/fcs/docsrc/content/editor.fsx
+++ b/fcs/docsrc/content/editor.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Editor services
+menu_order: 3
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -6,10 +14,10 @@ Compiler Services: Editor services
This tutorial demonstrates how to use the editor services provided by the F# compiler.
This API is used to provide auto-complete, tool-tips, parameter info help, matching of
-brackets and other functions in F# editors including Visual Studio, Xamarin Studio and Emacs
+brackets and other functions in F# editors including Visual Studio, Xamarin Studio and Emacs
(see [fsharpbindings](https://github.com/fsharp/fsharpbinding) project for more information).
-Similarly to [the tutorial on using untyped AST](untypedtree.html), we start by
-getting the `InteractiveChecker` object.
+Similarly to [the tutorial on using untyped AST](untypedtree.html), we start by
+getting the `InteractiveChecker` object.
> **NOTE:** The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
@@ -29,56 +37,56 @@ open System
open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.Text
-// Create an interactive checker instance
+// Create an interactive checker instance
let checker = FSharpChecker.Create()
(**
-As [previously](untypedtree.html), we use `GetProjectOptionsFromScriptRoot` to get a context
+As [previously](untypedtree.html), we use `GetProjectOptionsFromScriptRoot` to get a context
where the specified input is the only file passed to the compiler (and it is treated as a
-script file or stand-alone F# source code).
+script file or stand-alone F# source code).
*)
// Sample input as a multi-line string
-let input =
+let input =
"""
open System
- let foo() =
+ let foo() =
let msg = String.Concat("Hello"," ","world")
- if true then
+ if true then
printfn "%s" msg.
"""
// Split the input & define file name
let inputLines = input.Split('\n')
let file = "/home/user/Test.fsx"
-let projOptions, errors =
+let projOptions, errors =
checker.GetProjectOptionsFromScript(file, SourceText.ofString input)
|> Async.RunSynchronously
let parsingOptions, _errors = checker.GetParsingOptionsFromProjectOptions(projOptions)
(**
-To perform type checking, we first need to parse the input using
+To perform type checking, we first need to parse the input using
`ParseFile`, which gives us access to the [untyped AST](untypedtree.html). However,
then we need to call `CheckFileInProject` to perform the full type checking. This function
-also requires the result of `ParseFileInProject`, so the two functions are often called
-together.
+also requires the result of `ParseFileInProject`, so the two functions are often called
+together.
*)
-// Perform parsing
+// Perform parsing
-let parseFileResults =
+let parseFileResults =
checker.ParseFile(file, SourceText.ofString input, parsingOptions)
|> Async.RunSynchronously
(**
-Before we look at the interesting operations provided by `TypeCheckResults`, we
+Before we look at the interesting operations provided by `TypeCheckResults`, we
need to run the type checker on a sample input. On F# code with errors, you would get some type checking
result (but it may contain incorrectly "guessed" results).
-*)
+*)
// Perform type checking
-let checkFileAnswer =
+let checkFileAnswer =
checker.CheckFileInProject(parseFileResults, file, 0, SourceText.ofString input, projOptions)
|> Async.RunSynchronously
@@ -86,7 +94,7 @@ let checkFileAnswer =
Alternatively you can use `ParseAndCheckFileInProject` to check both in one step:
*)
-let parseResults2, checkFileAnswer2 =
+let parseResults2, checkFileAnswer2 =
checker.ParseAndCheckFileInProject(file, 0, SourceText.ofString input, projOptions)
|> Async.RunSynchronously
@@ -97,7 +105,7 @@ tutorial), but also a `CheckFileAnswer` value, which gives us access to all
the interesting functionality...
*)
-let checkFileResults =
+let checkFileResults =
match checkFileAnswer with
| FSharpCheckFileAnswer.Succeeded(res) -> res
| res -> failwithf "Parsing did not finish... (%A)" res
@@ -145,7 +153,7 @@ deprecated because it accepted zero-based line numbers. At some point it will b
Aside from the location and token kind, the function also requires the current contents of the line
(useful when the source code changes) and a `Names` value, which is a list of strings representing
the current long name. For example to get tooltip for the `Random` identifier in a long name
-`System.Random`, you would use location somewhere in the string `Random` and you would pass
+`System.Random`, you would use location somewhere in the string `Random` and you would pass
`["System"; "Random"]` as the `Names` value.
The returned value is of type `ToolTipText` which contains a discriminated union `ToolTipElement`.
@@ -155,16 +163,16 @@ The union represents different kinds of tool tips that you can get from the comp
The next method exposed by `TypeCheckResults` lets us perform auto-complete on a given location.
This can be called on any identifier or in any scope (in which case you get a list of names visible
-in the scope) or immediately after `.` to get a list of members of some object. Here, we get a
+in the scope) or immediately after `.` to get a list of members of some object. Here, we get a
list of members of the string value `msg`.
-To do this, we call `GetDeclarationListInfo` with the location of the `.` symbol on the last line
+To do this, we call `GetDeclarationListInfo` with the location of the `.` symbol on the last line
(ending with `printfn "%s" msg.`). The offsets are one-based, so the location is `7, 23`.
We also need to specify a function that says that the text has not changed and the current identifier
where we need to perform the completion.
*)
// Get declarations (autocomplete) for a location
-let decls =
+let decls =
checkFileResults.GetDeclarationListInfo
(Some parseFileResults, 7, inputLines.[6], PartialLongName.Empty 23, (fun () -> []), fun _ -> false)
|> Async.RunSynchronously
@@ -180,15 +188,15 @@ deprecated because it accepted zero-based line numbers. At some point it will b
*)
(**
-When you run the code, you should get a list containing the usual string methods such as
-`Substring`, `ToUpper`, `ToLower` etc. The fourth argument of `GetDeclarations`, here `([], "msg")`,
+When you run the code, you should get a list containing the usual string methods such as
+`Substring`, `ToUpper`, `ToLower` etc. The fourth argument of `GetDeclarations`, here `([], "msg")`,
specifies the context for the auto-completion. Here, we want a completion on a complete name
`msg`, but you could for example use `(["System"; "Collections"], "Generic")` to get a completion list
for a fully qualified namespace.
### Getting parameter information
-The next common feature of editors is to provide information about overloads of a method. In our
+The next common feature of editors is to provide information about overloads of a method. In our
sample code, we use `String.Concat` which has a number of overloads. We can get the list using
`GetMethods` operation. As previously, this takes zero-indexed offset of the location that we are
interested in (here, right at the end of the `String.Concat` identifier) and we also need to provide
@@ -197,14 +205,14 @@ changes):
*)
// Get overloads of the String.Concat method
-let methods =
+let methods =
checkFileResults.GetMethods(5, 27, inputLines.[4], Some ["String"; "Concat"])
|> Async.RunSynchronously
// Print concatenated parameter lists
for mi in methods.Methods do
[ for p in mi.Parameters -> p.Display ]
- |> String.concat ", "
+ |> String.concat ", "
|> printfn "%s(%s)" methods.MethodName
(**
The code uses the `Display` property to get the annotation for each parameter. This returns information
@@ -212,7 +220,7 @@ such as `arg0: obj` or `params args: obj[]` or `str0: string, str1: string`. We
and print a type annotation with the method name.
*)
-(**
+(**
## Asynchronous and immediate operations
@@ -229,7 +237,7 @@ is raised.
> The [fsharpbinding](https://github.com/fsharp/fsharpbinding) project has more advanced
example of handling the background work where all requests are sent through an F# agent.
-This may be a more appropriate for implementing editor support.
+This may be a more appropriate for implementing editor support.
*)
diff --git a/fcs/docsrc/content/filesystem.fsx b/fcs/docsrc/content/filesystem.fsx
index b7d4426fbd..f8842e4f2f 100644
--- a/fcs/docsrc/content/filesystem.fsx
+++ b/fcs/docsrc/content/filesystem.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Virtualized File System
+menu_order: 9
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -7,11 +15,11 @@ Compiler Services: Virtualized File System
The `FSharp.Compiler.Service` component has a global variable
representing the file system. By setting this variable you can host the compiler in situations where a file system
is not available.
-
+
> **NOTE:** The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published.
-Setting the FileSystem
+Setting the FileSystem
----------------------
In the example below, we set the file system to an implementation which reads from disk
@@ -28,7 +36,7 @@ let defaultFileSystem = Shim.FileSystem
let fileName1 = @"c:\mycode\test1.fs" // note, the path doesn't exist
let fileName2 = @"c:\mycode\test2.fs" // note, the path doesn't exist
-type MyFileSystem() =
+type MyFileSystem() =
let file1 = """
module File1
@@ -40,62 +48,62 @@ let B = File1.A + File1.A"""
interface IFileSystem with
// Implement the service to open files for reading and writing
- member __.FileStreamReadShim(fileName) =
+ member __.FileStreamReadShim(fileName) =
match files.TryGetValue fileName with
| true, text -> new MemoryStream(Encoding.UTF8.GetBytes(text)) :> Stream
| _ -> defaultFileSystem.FileStreamReadShim(fileName)
- member __.FileStreamCreateShim(fileName) =
+ member __.FileStreamCreateShim(fileName) =
defaultFileSystem.FileStreamCreateShim(fileName)
- member __.FileStreamWriteExistingShim(fileName) =
+ member __.FileStreamWriteExistingShim(fileName) =
defaultFileSystem.FileStreamWriteExistingShim(fileName)
- member __.ReadAllBytesShim(fileName) =
+ member __.ReadAllBytesShim(fileName) =
match files.TryGetValue fileName with
| true, text -> Encoding.UTF8.GetBytes(text)
| _ -> defaultFileSystem.ReadAllBytesShim(fileName)
// Implement the service related to temporary paths and file time stamps
- member __.GetTempPathShim() =
+ member __.GetTempPathShim() =
defaultFileSystem.GetTempPathShim()
- member __.GetLastWriteTimeShim(fileName) =
+ member __.GetLastWriteTimeShim(fileName) =
defaultFileSystem.GetLastWriteTimeShim(fileName)
- member __.GetFullPathShim(fileName) =
+ member __.GetFullPathShim(fileName) =
defaultFileSystem.GetFullPathShim(fileName)
- member __.IsInvalidPathShim(fileName) =
+ member __.IsInvalidPathShim(fileName) =
defaultFileSystem.IsInvalidPathShim(fileName)
- member __.IsPathRootedShim(fileName) =
+ member __.IsPathRootedShim(fileName) =
defaultFileSystem.IsPathRootedShim(fileName)
- member __.IsStableFileHeuristic(fileName) =
+ member __.IsStableFileHeuristic(fileName) =
defaultFileSystem.IsStableFileHeuristic(fileName)
// Implement the service related to file existence and deletion
- member __.SafeExists(fileName) =
+ member __.SafeExists(fileName) =
files.ContainsKey(fileName) || defaultFileSystem.SafeExists(fileName)
- member __.FileDelete(fileName) =
+ member __.FileDelete(fileName) =
defaultFileSystem.FileDelete(fileName)
// Implement the service related to assembly loading, used to load type providers
// and for F# interactive.
- member __.AssemblyLoadFrom(fileName) =
+ member __.AssemblyLoadFrom(fileName) =
defaultFileSystem.AssemblyLoadFrom fileName
- member __.AssemblyLoad(assemblyName) =
- defaultFileSystem.AssemblyLoad assemblyName
+ member __.AssemblyLoad(assemblyName) =
+ defaultFileSystem.AssemblyLoad assemblyName
let myFileSystem = MyFileSystem()
-Shim.FileSystem <- MyFileSystem()
+Shim.FileSystem <- MyFileSystem()
(**
-Doing a compilation with the FileSystem
+Doing a compilation with the FileSystem
---------------------------------------
*)
@@ -103,52 +111,52 @@ open FSharp.Compiler.SourceCodeServices
let checker = FSharpChecker.Create()
-let projectOptions =
- let sysLib nm =
- if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows
+let projectOptions =
+ let sysLib nm =
+ if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) +
@"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\" + nm + ".dll"
else
let sysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()
let (++) a b = System.IO.Path.Combine(a,b)
- sysDir ++ nm + ".dll"
+ sysDir ++ nm + ".dll"
- let fsCore4300() =
- if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows
+ let fsCore4300() =
+ if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then // file references only valid on Windows
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) +
- @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
- else
+ @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
+ else
sysLib "FSharp.Core"
- let allFlags =
- [| yield "--simpleresolution";
- yield "--noframework";
- yield "--debug:full";
- yield "--define:DEBUG";
- yield "--optimize-";
- yield "--doc:test.xml";
- yield "--warn:3";
- yield "--fullpaths";
- yield "--flaterrors";
- yield "--target:library";
+ let allFlags =
+ [| yield "--simpleresolution";
+ yield "--noframework";
+ yield "--debug:full";
+ yield "--define:DEBUG";
+ yield "--optimize-";
+ yield "--doc:test.xml";
+ yield "--warn:3";
+ yield "--fullpaths";
+ yield "--flaterrors";
+ yield "--target:library";
let references =
- [ sysLib "mscorlib"
+ [ sysLib "mscorlib"
sysLib "System"
sysLib "System.Core"
fsCore4300() ]
- for r in references do
+ for r in references do
yield "-r:" + r |]
-
+
{ ProjectFileName = @"c:\mycode\compilation.fsproj" // Make a name that is unique in this directory.
ProjectId = None
SourceFiles = [| fileName1; fileName2 |]
OriginalLoadReferences = []
ExtraProjectInfo=None
Stamp = None
- OtherOptions = allFlags
+ OtherOptions = allFlags
ReferencedProjects = [| |]
IsIncompleteTypeCheckEnvironment = false
- UseScriptResolutionRules = true
+ UseScriptResolutionRules = true
LoadTime = System.DateTime.Now // Note using 'Now' forces reloading
UnresolvedReferences = None }
@@ -179,12 +187,12 @@ Future iterations on the compiler service implementation may add these to the AP
**NOTE:** Several operations in the `SourceCodeServices` API accept the contents of a file to parse
or check as a parameter, in addition to a file name. In these cases, the file name is only used for
error reporting.
-
-**NOTE:** Type provider components do not use the virtualized file system.
+
+**NOTE:** Type provider components do not use the virtualized file system.
**NOTE:** The compiler service may use MSBuild for assembly resolutions unless `--simpleresolution` is
provided. When using the `FileSystem` API you will normally want to specify `--simpleresolution` as one
of your compiler flags. Also specify `--noframework`. You will need to supply explicit resolutions of all
referenced .NET assemblies.
-
+
*)
\ No newline at end of file
diff --git a/fcs/docsrc/content/index.md b/fcs/docsrc/content/index.md
index 13cb0926ab..79e5af2bfd 100644
--- a/fcs/docsrc/content/index.md
+++ b/fcs/docsrc/content/index.md
@@ -1,3 +1,9 @@
+---
+title: F# Compiler Services
+category: explanation
+menu_order: 1
+---
+
F# Compiler Services
====================
diff --git a/fcs/docsrc/content/interactive.fsx b/fcs/docsrc/content/interactive.fsx
index abd1c5761e..97910b2c6c 100644
--- a/fcs/docsrc/content/interactive.fsx
+++ b/fcs/docsrc/content/interactive.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Embedding F# Interactive
+menu_order: 7
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
diff --git a/fcs/docsrc/content/ja/compiler.fsx b/fcs/docsrc/content/ja/compiler.fsx
index c1fdf2ef62..5b2885fac7 100644
--- a/fcs/docsrc/content/ja/compiler.fsx
+++ b/fcs/docsrc/content/ja/compiler.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: コンパイラの組み込み
+menu_order: 8
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -34,7 +43,7 @@ let fn3 = Path.ChangeExtension(fn, ".dll")
File.WriteAllText(fn2, """
module M
-type C() =
+type C() =
member x.P = 1
let x = 3 + 4
@@ -46,7 +55,7 @@ let x = 3 + 4
let errors1, exitCode1 = scs.Compile([| "fsc.exe"; "-o"; fn3; "-a"; fn2 |]) |> Async.RunSynchronously
-(**
+(**
エラーが発生した場合は「終了コード」とエラーの配列から原因を特定できます:
@@ -78,12 +87,12 @@ if exitCode1b <> 0 then
'execute' 引数に 'None' を指定するとアセンブリ用の初期化コードが実行されません。
*)
-let errors2, exitCode2, dynAssembly2 =
+let errors2, exitCode2, dynAssembly2 =
scs.CompileToDynamicAssembly([| "-o"; fn3; "-a"; fn2 |], execute=None) |> Async.RunSynchronously
(**
'Some' を指定するとアセンブリ用の初期化コードが実行されます。
*)
-let errors3, exitCode3, dynAssembly3 =
+let errors3, exitCode3, dynAssembly3 =
scs.CompileToDynamicAssembly([| "-o"; fn3; "-a"; fn2 |], Some(stdout,stderr)) |> Async.RunSynchronously
diff --git a/fcs/docsrc/content/ja/corelib.fsx b/fcs/docsrc/content/ja/corelib.fsx
index ea9ee87f8f..31b9ab2a42 100644
--- a/fcs/docsrc/content/ja/corelib.fsx
+++ b/fcs/docsrc/content/ja/corelib.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: how-to
+title: FSharp.Core.dll についてのメモ
+menu_order: 3
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/net461"
(**
diff --git a/fcs/docsrc/content/ja/devnotes.md b/fcs/docsrc/content/ja/devnotes.md
index 3baa28f4b6..d7398538e5 100644
--- a/fcs/docsrc/content/ja/devnotes.md
+++ b/fcs/docsrc/content/ja/devnotes.md
@@ -1,3 +1,11 @@
+---
+title: 開発者用メモ
+category: explanation
+menu_order: 2
+language: ja
+---
+
+
開発者用メモ
============
diff --git a/fcs/docsrc/content/ja/editor.fsx b/fcs/docsrc/content/ja/editor.fsx
index 7075c15989..70da7c6c5f 100644
--- a/fcs/docsrc/content/ja/editor.fsx
+++ b/fcs/docsrc/content/ja/editor.fsx
@@ -1,3 +1,13 @@
+(**
+---
+category: tutorial
+title: エディタサービス
+menu_order: 3
+language: ja
+
+---
+*)
+
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -43,13 +53,13 @@ let checker = FSharpChecker.Create()
*)
// サンプルの入力となる複数行文字列
-let input =
+let input =
"""
open System
-let foo() =
+let foo() =
let msg = String.Concat("Hello"," ","world")
-if true then
+if true then
printfn "%s" msg.
"""
// 入力値の分割とファイル名の定義
@@ -80,11 +90,11 @@ let parseFileResults =
サンプル入力に対して型チェッカーを実行する必要があります。
F#コードにエラーがあった場合も何らかの型チェックの結果が返されます
(ただし間違って「推測された」結果が含まれることがあります)。
-*)
+*)
// 型チェックを実行
-let checkFileAnswer =
- checker.CheckFileInProject(parseFileResults, file, 0, input, projOptions)
+let checkFileAnswer =
+ checker.CheckFileInProject(parseFileResults, file, 0, input, projOptions)
|> Async.RunSynchronously
(**
@@ -99,7 +109,7 @@ let parseResults2, checkFileAnswer2 =
この返り値は `CheckFileAnswer` 型で、この型に機能的に興味深いものが揃えられています...
*)
-let checkFileResults =
+let checkFileResults =
match checkFileAnswer with
| FSharpCheckFileAnswer.Succeeded(res) -> res
| res -> failwithf "パースが完了していません... (%A)" res
@@ -176,7 +186,7 @@ printfn "%A" tip
現時点において補完する必要がある識別子を指定する必要もあります。
*)
// 特定の位置における宣言(自動補完)を取得する
-let decls =
+let decls =
checkFileResults.GetDeclarationListInfo
(Some parseFileResults, 7, inputLines.[6], PartialLongName.Empty 23, (fun _ -> []), fun _ -> false)
|> Async.RunSynchronously
@@ -212,13 +222,13 @@ for item in decls.Items do
*)
//String.Concatメソッドのオーバーロードを取得する
-let methods =
+let methods =
checkFileResults.GetMethods(5, 27, inputLines.[4], Some ["String"; "Concat"]) |> Async.RunSynchronously
// 連結された引数リストを表示
for mi in methods.Methods do
[ for p in mi.Parameters -> p.Display ]
- |> String.concat ", "
+ |> String.concat ", "
|> printfn "%s(%s)" methods.MethodName
(**
ここでは `Display` プロパティを使用することで各引数に対する
@@ -228,7 +238,7 @@ for mi in methods.Methods do
これらの引数を連結した後、メソッド名とメソッドの型情報とともに表示させています。
*)
-(**
+(**
## 非同期操作と即時操作
diff --git a/fcs/docsrc/content/ja/filesystem.fsx b/fcs/docsrc/content/ja/filesystem.fsx
index eaa1634919..9157ffd1d0 100644
--- a/fcs/docsrc/content/ja/filesystem.fsx
+++ b/fcs/docsrc/content/ja/filesystem.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: ファイルシステム仮想化
+menu_order: 9
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -7,7 +16,7 @@
`FSharp.Compiler.Service` にはファイルシステムを表すグローバル変数があります。
この変数を設定するこにより、ファイルシステムが利用できない状況でも
コンパイラをホストすることができるようになります。
-
+
> **注意:** 以下で使用しているAPIは実験的なもので、
新しいnugetパッケージの公開に伴って変更される可能性があります。
@@ -28,7 +37,7 @@ let defaultFileSystem = Shim.FileSystem
let fileName1 = @"c:\mycode\test1.fs" // 注意: 実際には存在しないファイルのパス
let fileName2 = @"c:\mycode\test2.fs" // 注意: 実際には存在しないファイルのパス
-type MyFileSystem() =
+type MyFileSystem() =
let file1 = """
module File1
@@ -40,58 +49,58 @@ let B = File1.A + File1.A"""
interface IFileSystem with
// 読み取りおよび書き込み用にファイルをオープンする機能を実装
- member __.FileStreamReadShim(fileName) =
+ member __.FileStreamReadShim(fileName) =
match files.TryGetValue fileName with
| true, text -> new MemoryStream(Encoding.UTF8.GetBytes(text)) :> Stream
| _ -> defaultFileSystem.FileStreamReadShim(fileName)
- member __.FileStreamCreateShim(fileName) =
+ member __.FileStreamCreateShim(fileName) =
defaultFileSystem.FileStreamCreateShim(fileName)
- member __.IsStableFileHeuristic(fileName) =
+ member __.IsStableFileHeuristic(fileName) =
defaultFileSystem.IsStableFileHeuristic(fileName)
- member __.FileStreamWriteExistingShim(fileName) =
+ member __.FileStreamWriteExistingShim(fileName) =
defaultFileSystem.FileStreamWriteExistingShim(fileName)
- member __.ReadAllBytesShim(fileName) =
+ member __.ReadAllBytesShim(fileName) =
match files.TryGetValue fileName with
| true, text -> Encoding.UTF8.GetBytes(text)
| _ -> defaultFileSystem.ReadAllBytesShim(fileName)
// 一時パスおよびファイルのタイムスタンプに関連する機能を実装
- member __.GetTempPathShim() =
+ member __.GetTempPathShim() =
defaultFileSystem.GetTempPathShim()
- member __.GetLastWriteTimeShim(fileName) =
+ member __.GetLastWriteTimeShim(fileName) =
defaultFileSystem.GetLastWriteTimeShim(fileName)
- member __.GetFullPathShim(fileName) =
+ member __.GetFullPathShim(fileName) =
defaultFileSystem.GetFullPathShim(fileName)
- member __.IsInvalidPathShim(fileName) =
+ member __.IsInvalidPathShim(fileName) =
defaultFileSystem.IsInvalidPathShim(fileName)
- member __.IsPathRootedShim(fileName) =
+ member __.IsPathRootedShim(fileName) =
defaultFileSystem.IsPathRootedShim(fileName)
// ファイルの存在確認および削除に関連する機能を実装
- member __.SafeExists(fileName) =
+ member __.SafeExists(fileName) =
files.ContainsKey(fileName) || defaultFileSystem.SafeExists(fileName)
- member __.FileDelete(fileName) =
+ member __.FileDelete(fileName) =
defaultFileSystem.FileDelete(fileName)
// アセンブリのロードに関連する機能を実装。
// 型プロバイダやF# Interactiveで使用される。
- member __.AssemblyLoadFrom(fileName) =
+ member __.AssemblyLoadFrom(fileName) =
defaultFileSystem.AssemblyLoadFrom fileName
- member __.AssemblyLoad(assemblyName) =
- defaultFileSystem.AssemblyLoad assemblyName
+ member __.AssemblyLoad(assemblyName) =
+ defaultFileSystem.AssemblyLoad assemblyName
let myFileSystem = MyFileSystem()
-Shim.FileSystem <- MyFileSystem()
+Shim.FileSystem <- MyFileSystem()
(**
@@ -102,36 +111,36 @@ FileSystemによるコンパイルの実行
open FSharp.Compiler.SourceCodeServices
let checker = FSharpChecker.Create()
-let projectOptions =
- let allFlags =
- [| yield "--simpleresolution";
- yield "--noframework";
- yield "--debug:full";
- yield "--define:DEBUG";
- yield "--optimize-";
- yield "--doc:test.xml";
- yield "--warn:3";
- yield "--fullpaths";
- yield "--flaterrors";
- yield "--target:library";
+let projectOptions =
+ let allFlags =
+ [| yield "--simpleresolution";
+ yield "--noframework";
+ yield "--debug:full";
+ yield "--define:DEBUG";
+ yield "--optimize-";
+ yield "--doc:test.xml";
+ yield "--warn:3";
+ yield "--fullpaths";
+ yield "--flaterrors";
+ yield "--target:library";
let references =
- [ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll";
- @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll";
- @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll";
+ [ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll";
+ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll";
+ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll";
@"C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"]
- for r in references do
+ for r in references do
yield "-r:" + r |]
-
+
{ ProjectFileName = @"c:\mycode\compilation.fsproj" // 現在のディレクトリで一意な名前を指定
ProjectId = None
SourceFiles = [| fileName1; fileName2 |]
OriginalLoadReferences = []
ExtraProjectInfo=None
Stamp = None
- OtherOptions = allFlags
+ OtherOptions = allFlags
ReferencedProjects=[| |]
IsIncompleteTypeCheckEnvironment = false
- UseScriptResolutionRules = true
+ UseScriptResolutionRules = true
LoadTime = System.DateTime.Now // 'Now' を指定して強制的に再読込させている点に注意
UnresolvedReferences = None }
@@ -163,7 +172,7 @@ results.AssemblySignature.Entities.[0].MembersFunctionsAndValues.[0].DisplayName
**注意:** `SourceCodeServices` API内の一部の操作では、
引数にファイルの内容だけでなくファイル名を指定する必要があります。
これらのAPIにおいて、ファイル名はエラーの報告のためだけに使用されます。
-
+
**注意:** 型プロバイダーコンポーネントは仮想化されたファイルシステムを使用しません。
**注意:** コンパイラサービスは `--simpleresolution` が指定されていない場合、
diff --git a/fcs/docsrc/content/ja/index.md b/fcs/docsrc/content/ja/index.md
index 5b480ce887..17622c8d7c 100644
--- a/fcs/docsrc/content/ja/index.md
+++ b/fcs/docsrc/content/ja/index.md
@@ -1,3 +1,10 @@
+---
+title: F# コンパイラサービス
+category: explanation
+menu_order: 1
+language: ja
+---
+
F# コンパイラサービス
=====================
@@ -39,11 +46,11 @@ F# インタラクティブサービスも含まれています。
この機能を使うと、F#サポート機能をエディタに追加したり、F#コードから
何らかの型情報を取得したりすることができるようになります。
- * [** シグネチャや型、解決済みのシンボルの処理 **](symbols.html) -
+ * [** シグネチャや型、解決済みのシンボルの処理 **](symbols.html) -
解決済みのシンボルや推測された型の表現、アセンブリ全体のシグネチャなどを
型のチェック時に返すような多数のサービスがあります。
- * [** 複数プロジェクトやプロジェクト全体の処理 **](project.html) -
+ * [** 複数プロジェクトやプロジェクト全体の処理 **](project.html) -
すべてのプロジェクトに対するチェックを実行することにより、
プロジェクト全体の解析結果を使って\[すべての参照の検索\] のような
機能を実現できます。
diff --git a/fcs/docsrc/content/ja/interactive.fsx b/fcs/docsrc/content/ja/interactive.fsx
index 1824eda9ec..34e86dc27e 100644
--- a/fcs/docsrc/content/ja/interactive.fsx
+++ b/fcs/docsrc/content/ja/interactive.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: F# Interactiveの組み込み
+menu_order: 7
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -66,7 +75,7 @@ let argv = [| "C:\\fsi.exe" |]
let allArgs = Array.append argv [|"--noninteractive"|]
let fsiConfig = FsiEvaluationSession.GetDefaultConfiguration()
-let fsiSession = FsiEvaluationSession.Create(fsiConfig, allArgs, inStream, outStream, errStream)
+let fsiSession = FsiEvaluationSession.Create(fsiConfig, allArgs, inStream, outStream, errStream)
(**
コードの評価および実行
@@ -143,7 +152,7 @@ File.WriteAllText("sample.fsx", "let twenty = 'a' + 10.0")
let result, warnings = fsiSession.EvalScriptNonThrowing "sample.fsx"
// 結果を表示する
-match result with
+match result with
| Choice1Of2 () -> printfn "チェックと実行はOKでした"
| Choice2Of2 exn -> printfn "実行例外: %s" exn.Message
@@ -155,7 +164,7 @@ match result with
*)
// エラーと警告を表示する
-for w in warnings do
+for w in warnings do
printfn "警告 %s 場所 %d,%d" w.Message w.StartLineAlternate w.StartColumn
(**
@@ -170,9 +179,9 @@ for w in warnings do
let evalExpressionTyped2<'T> text =
let res, warnings = fsiSession.EvalExpressionNonThrowing(text)
- for w in warnings do
- printfn "警告 %s 場所 %d,%d" w.Message w.StartLineAlternate w.StartColumn
- match res with
+ for w in warnings do
+ printfn "警告 %s 場所 %d,%d" w.Message w.StartLineAlternate w.StartColumn
+ match res with
| Choice1Of2 (Some value) -> value.ReflectionValue |> unbox<'T>
| Choice1Of2 None -> failwith "null または結果がありません"
| Choice2Of2 (exn:exn) -> failwith (sprintf "例外 %s" exn.Message)
@@ -190,16 +199,16 @@ evalExpressionTyped2 "42+1" // '43' になる
open System.Threading.Tasks
-let sampleLongRunningExpr =
+let sampleLongRunningExpr =
"""
-async {
+async {
// 実行したいコード
do System.Threading.Thread.Sleep 5000
- return 10
+ return 10
}
|> Async.StartAsTask"""
-let task1 = evalExpressionTyped>(sampleLongRunningExpr)
+let task1 = evalExpressionTyped>(sampleLongRunningExpr)
let task2 = evalExpressionTyped>(sampleLongRunningExpr)
(**
@@ -226,17 +235,17 @@ fsiSession.EvalInteraction "let xxx = 1 + 1"
次に部分的に完全な `xxx + xx` というコードの型チェックを実行したいとします:
*)
-let parseResults, checkResults, checkProjectResults =
+let parseResults, checkResults, checkProjectResults =
fsiSession.ParseAndCheckInteraction("xxx + xx") |> Async.RunSynchronously
-(**
+(**
`parseResults` と `checkResults` はそれぞれ [エディタ](editor.html)
のページで説明している `ParseFileResults` と `CheckFileResults` 型です。
たとえば以下のようなコードでエラーを確認出来ます:
*)
checkResults.Errors.Length // 1
-(**
+(**
コードはF# Interactiveセッション内において、その時点までに実行された
有効な宣言からなる論理的な型コンテキストと結びつく形でチェックされます。
@@ -247,10 +256,10 @@ checkResults.Errors.Length // 1
open FSharp.Compiler
// ツールチップを取得する
-checkResults.GetToolTipText(1, 2, "xxx + xx", ["xxx"], FSharpTokenTag.IDENT)
+checkResults.GetToolTipText(1, 2, "xxx + xx", ["xxx"], FSharpTokenTag.IDENT)
checkResults.GetSymbolUseAtLocation(1, 2, "xxx + xx", ["xxx"]) // シンボル xxx
-
+
(**
'fsi'オブジェクト
-----------------
@@ -281,7 +290,7 @@ FsiEvaluationSessionを使用してコードを評価すると、
評価が進んでも線形には増加しないでしょう。
*)
-let collectionTest() =
+let collectionTest() =
for i in 1 .. 200 do
let defaultArgs = [|"fsi.exe";"--noninteractive";"--nologo";"--gui-"|]
@@ -291,7 +300,7 @@ let collectionTest() =
let fsiConfig = FsiEvaluationSession.GetDefaultConfiguration()
use session = FsiEvaluationSession.Create(fsiConfig, defaultArgs, inStream, outStream, errStream, collectible=true)
-
+
session.EvalInteraction (sprintf "type D = { v : int }")
let v = session.EvalExpression (sprintf "{ v = 42 * %d }" i)
printfn "その %d, 結果 = %A" i v.Value.ReflectionValue
diff --git a/fcs/docsrc/content/ja/project.fsx b/fcs/docsrc/content/ja/project.fsx
index 47355d9326..2cfc847f48 100644
--- a/fcs/docsrc/content/ja/project.fsx
+++ b/fcs/docsrc/content/ja/project.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: プロジェクトの分析
+menu_order: 6
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -33,7 +42,7 @@ let checker = FSharpChecker.Create()
今回のサンプル入力は以下の通りです:
*)
-module Inputs =
+module Inputs =
open System.IO
let base1 = Path.GetTempFileName()
@@ -45,7 +54,7 @@ module Inputs =
let fileSource1 = """
module M
-type C() =
+type C() =
member x.P = 1
let xxx = 3 + 4
@@ -58,10 +67,10 @@ module N
open M
-type D1() =
+type D1() =
member x.SomeProperty = M.xxx
-type D2() =
+type D2() =
member x.SomeProperty = M.fff()
// 警告を発生させる
@@ -75,27 +84,27 @@ let y2 = match 1 with 1 -> M.xxx
2つのファイルを1つのプロジェクトとして扱えるようにします:
*)
-let projectOptions =
+let projectOptions =
checker.GetProjectOptionsFromCommandLineArgs
(Inputs.projFileName,
- [| yield "--simpleresolution"
- yield "--noframework"
- yield "--debug:full"
- yield "--define:DEBUG"
- yield "--optimize-"
+ [| yield "--simpleresolution"
+ yield "--noframework"
+ yield "--debug:full"
+ yield "--define:DEBUG"
+ yield "--optimize-"
yield "--out:" + Inputs.dllName
- yield "--doc:test.xml"
- yield "--warn:3"
- yield "--fullpaths"
- yield "--flaterrors"
- yield "--target:library"
+ yield "--doc:test.xml"
+ yield "--warn:3"
+ yield "--fullpaths"
+ yield "--flaterrors"
+ yield "--target:library"
yield Inputs.fileName1
yield Inputs.fileName2
- let references =
- [ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll"
- @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll"
- @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll"
- @"C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"]
+ let references =
+ [ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll"
+ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll"
+ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll"
+ @"C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"]
for r in references do
yield "-r:" + r |])
@@ -128,9 +137,9 @@ wholeProjectResults.Errors.[0].EndColumn // 16
(**
プロジェクト内の全シンボルを取得することもできます:
*)
-let rec allSymbolsInEntities (entities: IList) =
- [ for e in entities do
- yield (e :> FSharpSymbol)
+let rec allSymbolsInEntities (entities: IList) =
+ [ for e in entities do
+ yield (e :> FSharpSymbol)
for x in e.MembersFunctionsAndValues do
yield (x :> FSharpSymbol)
for x in e.UnionCases do
@@ -146,8 +155,8 @@ let allSymbols = allSymbolsInEntities wholeProjectResults.AssemblySignature.Enti
この処理は即座に完了し、改めてチェックが実行されることもありません。
*)
-let backgroundParseResults1, backgroundTypedParse1 =
- checker.GetBackgroundCheckResultsForFileInProject(Inputs.fileName1, projectOptions)
+let backgroundParseResults1, backgroundTypedParse1 =
+ checker.GetBackgroundCheckResultsForFileInProject(Inputs.fileName1, projectOptions)
|> Async.RunSynchronously
@@ -155,7 +164,7 @@ let backgroundParseResults1, backgroundTypedParse1 =
そしてそれぞれのファイル内にあるシンボルを解決できます:
*)
-let xSymbol =
+let xSymbol =
backgroundTypedParse1.GetSymbolUseAtLocation(9,9,"",["xxx"])
|> Async.RunSynchronously
@@ -168,8 +177,8 @@ let usesOfXSymbol = wholeProjectResults.GetUsesOfSymbol(xSymbol.Value.Symbol)
推測されたシグネチャ内にあるすべての定義済みシンボルに対して、
それらがどこで使用されているのかを探し出すこともできます:
*)
-let allUsesOfAllSignatureSymbols =
- [ for s in allSymbols do
+let allUsesOfAllSignatureSymbols =
+ [ for s in allSymbols do
yield s.ToString(), wholeProjectResults.GetUsesOfSymbol(s) ]
(**
@@ -186,30 +195,30 @@ let allUsesOfAllSymbols = wholeProjectResults.GetAllUsesOfAllSymbols()
読み取り中であることに注意してください):
*)
-let parseResults1, checkAnswer1 =
- checker.ParseAndCheckFileInProject(Inputs.fileName1, 0, Inputs.fileSource1, projectOptions)
+let parseResults1, checkAnswer1 =
+ checker.ParseAndCheckFileInProject(Inputs.fileName1, 0, Inputs.fileSource1, projectOptions)
|> Async.RunSynchronously
-let checkResults1 =
- match checkAnswer1 with
- | FSharpCheckFileAnswer.Succeeded x -> x
+let checkResults1 =
+ match checkAnswer1 with
+ | FSharpCheckFileAnswer.Succeeded x -> x
| _ -> failwith "想定外の終了状態です"
-let parseResults2, checkAnswer2 =
+let parseResults2, checkAnswer2 =
checker.ParseAndCheckFileInProject(Inputs.fileName2, 0, Inputs.fileSource2, projectOptions)
|> Async.RunSynchronously
-let checkResults2 =
- match checkAnswer2 with
- | FSharpCheckFileAnswer.Succeeded x -> x
+let checkResults2 =
+ match checkAnswer2 with
+ | FSharpCheckFileAnswer.Succeeded x -> x
| _ -> failwith "想定外の終了状態です"
(**
そして再びシンボルを解決したり、参照を検索したりすることができます:
*)
-let xSymbol2 =
- checkResults1.GetSymbolUseAtLocation(9,9,"",["xxx"])
+let xSymbol2 =
+ checkResults1.GetSymbolUseAtLocation(9,9,"",["xxx"])
|> Async.RunSynchronously
let usesOfXSymbol2 = wholeProjectResults.GetUsesOfSymbol(xSymbol2.Value.Symbol)
diff --git a/fcs/docsrc/content/ja/symbols.fsx b/fcs/docsrc/content/ja/symbols.fsx
index 052a9b978c..84bac9e137 100644
--- a/fcs/docsrc/content/ja/symbols.fsx
+++ b/fcs/docsrc/content/ja/symbols.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: シンボルの処理
+menu_order: 4
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -32,14 +41,14 @@ let checker = FSharpChecker.Create()
*)
-let parseAndTypeCheckSingleFile (file, input) =
+let parseAndTypeCheckSingleFile (file, input) =
// スタンドアロンの(スクリプト)ファイルを表すコンテキストを取得
- let projOptions, _errors =
+ let projOptions, _errors =
checker.GetProjectOptionsFromScript(file, input)
|> Async.RunSynchronously
- let parseFileResults, checkFileResults =
- checker.ParseAndCheckFileInProject(file, 0, input, projOptions)
+ let parseFileResults, checkFileResults =
+ checker.ParseAndCheckFileInProject(file, 0, input, projOptions)
|> Async.RunSynchronously
// 型チェックが成功(あるいは100%に到達)するまで待機
@@ -64,19 +73,19 @@ let file = "/home/user/Test.fsx"
*)
-let input2 =
+let input2 =
"""
[]
-let foo(x, y) =
+let foo(x, y) =
let msg = String.Concat("Hello"," ","world")
- if true then
- printfn "x = %d, y = %d" x y
+ if true then
+ printfn "x = %d, y = %d" x y
printfn "%s" msg
-type C() =
+type C() =
member x.P = 1
"""
-let parseFileResults, checkFileResults =
+let parseFileResults, checkFileResults =
parseAndTypeCheckSingleFile(file, input2)
(**
@@ -137,7 +146,7 @@ fnVal.IsTypeFunction // false
*)
fnVal.FullType // int * int -> unit
fnVal.FullType.IsFunctionType // true
-fnVal.FullType.GenericArguments.[0] // int * int
+fnVal.FullType.GenericArguments.[0] // int * int
fnVal.FullType.GenericArguments.[0].IsTupleType // true
let argTy1 = fnVal.FullType.GenericArguments.[0].GenericArguments.[0]
@@ -158,15 +167,15 @@ argTy1.TypeDefinition.IsFSharpAbbreviation // true
*)
let argTy1b = argTy1.TypeDefinition.AbbreviatedType
-argTy1b.TypeDefinition.Namespace // Some "Microsoft.FSharp.Core"
-argTy1b.TypeDefinition.CompiledName // "int32"
+argTy1b.TypeDefinition.Namespace // Some "Microsoft.FSharp.Core"
+argTy1b.TypeDefinition.CompiledName // "int32"
(**
そして再び型省略形 `type int32 = System.Int32` から型に関する完全な情報が取得できます:
*)
let argTy1c = argTy1b.TypeDefinition.AbbreviatedType
-argTy1c.TypeDefinition.Namespace // Some "System"
-argTy1c.TypeDefinition.CompiledName // "Int32"
+argTy1c.TypeDefinition.Namespace // Some "System"
+argTy1c.TypeDefinition.CompiledName // "Int32"
(**
ファイルに対する型チェックの結果には、
@@ -176,7 +185,7 @@ argTy1c.TypeDefinition.CompiledName // "Int32"
let projectContext = checkFileResults.ProjectContext
for assembly in projectContext.GetReferencedAssemblies() do
- match assembly.FileName with
+ match assembly.FileName with
| None -> printfn "コンパイル時にファイルの存在しないアセンブリを参照しました"
| Some s -> printfn "コンパイル時にアセンブリ '%s' を参照しました" s
@@ -202,13 +211,13 @@ for assembly in projectContext.GetReferencedAssemblies() do
異なる "projOptions" を指定すると、巨大なプロジェクトに対する設定を
構成することもできます。
*)
-let parseAndCheckScript (file, input) =
- let projOptions, errors =
+let parseAndCheckScript (file, input) =
+ let projOptions, errors =
checker.GetProjectOptionsFromScript(file, input)
|> Async.RunSynchronously
- let projResults =
- checker.ParseAndCheckProject(projOptions)
+ let projResults =
+ checker.ParseAndCheckProject(projOptions)
|> Async.RunSynchronously
projResults
@@ -232,5 +241,5 @@ let assemblySig = projectResults.AssemblySignature
assemblySig.Entities.Count = 1 // エンティティは1つ
assemblySig.Entities.[0].Namespace // null
assemblySig.Entities.[0].DisplayName // "Tmp28D0"
-assemblySig.Entities.[0].MembersFunctionsAndValues.Count // 1
-assemblySig.Entities.[0].MembersFunctionsAndValues.[0].DisplayName // "foo"
+assemblySig.Entities.[0].MembersFunctionsAndValues.Count // 1
+assemblySig.Entities.[0].MembersFunctionsAndValues.[0].DisplayName // "foo"
diff --git a/fcs/docsrc/content/ja/tokenizer.fsx b/fcs/docsrc/content/ja/tokenizer.fsx
index 729964bad0..6731501088 100644
--- a/fcs/docsrc/content/ja/tokenizer.fsx
+++ b/fcs/docsrc/content/ja/tokenizer.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: F#トークナイザを使用する
+menu_order: 1
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -106,7 +115,7 @@ let lines = """
直前の行における **最後** の状態を使って `tokenizeLine` を呼び出します:
*)
/// 複数行のコードに対してトークンの名前を表示します
-let rec tokenizeLines state count lines =
+let rec tokenizeLines state count lines =
match lines with
| line::lines ->
// トークナイザを作成して1行をトークン化
@@ -131,11 +140,11 @@ lines
[lang=text]
Line 1
- LINE_COMMENT LINE_COMMENT (...) LINE_COMMENT
+ LINE_COMMENT LINE_COMMENT (...) LINE_COMMENT
Line 2
- LET WHITESPACE IDENT LPAREN RPAREN WHITESPACE EQUALS
+ LET WHITESPACE IDENT LPAREN RPAREN WHITESPACE EQUALS
Line 3
- IDENT WHITESPACE STRING_TEXT (...) STRING_TEXT STRING
+ IDENT WHITESPACE STRING_TEXT (...) STRING_TEXT STRING
注目すべきは、単一行コメントや文字列に対して、
トークナイザが複数回(大まかにいって単語単位で) `LINE_COMMENT` や
diff --git a/fcs/docsrc/content/ja/untypedtree.fsx b/fcs/docsrc/content/ja/untypedtree.fsx
index b6974d1306..a558bf132a 100644
--- a/fcs/docsrc/content/ja/untypedtree.fsx
+++ b/fcs/docsrc/content/ja/untypedtree.fsx
@@ -1,3 +1,12 @@
+(**
+---
+category: tutorial
+title: 型無し構文木の処理
+menu_order: 2
+language: ja
+
+---
+*)
(*** hide ***)
#I "../../../../artifacts/bin/fcs/Release/net461"
(**
@@ -66,18 +75,18 @@ ASTを取得するために、ファイル名とソースコードを受け取
*)
/// 特定の入力に対する型無し構文木を取得する
-let getUntypedTree (file, input) =
+let getUntypedTree (file, input) =
// 1つのスクリプトファイルから推測される「プロジェクト」用の
// コンパイラオプションを取得する
let projOptions, errors =
- checker.GetProjectOptionsFromScript(file, input)
+ checker.GetProjectOptionsFromScript(file, input)
|> Async.RunSynchronously
let parsingOptions, _errors = checker.GetParsingOptionsFromProjectOptions(projectOptions)
// コンパイラの第1フェーズを実行する
- let untypedRes =
- checker.ParseFile(file, input, parsingOptions)
+ let untypedRes =
+ checker.ParseFile(file, input, parsingOptions)
|> Async.RunSynchronously
match untypedRes.ParseTree with
@@ -125,7 +134,7 @@ ASTを処理する場合、異なる文法的要素に対するパターンマ
/// パターンの走査
/// これは let = あるいは 'match' 式に対する例です
let rec visitPattern = function
- | SynPat.Wild(_) ->
+ | SynPat.Wild(_) ->
printfn " .. アンダースコアパターン"
| SynPat.Named(pat, name, _, _, _) ->
visitPattern pat
@@ -156,16 +165,16 @@ let rec visitExpression = function
printfn "条件部:"
visitExpression cond
visitExpression trueBranch
- falseBranchOpt |> Option.iter visitExpression
+ falseBranchOpt |> Option.iter visitExpression
| SynExpr.LetOrUse(_, _, bindings, body, _) ->
// バインディングを走査
// ('let .. = .. and .. = .. in ...' に対しては複数回走査されることがある)
printfn "以下のバインディングを含むLetOrUse:"
for binding in bindings do
- let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
+ let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
data, pat, retInfo, init, m, sp)) = binding
- visitPattern pat
+ visitPattern pat
visitExpression init
// 本体の式を走査
printfn "本体は以下:"
@@ -190,7 +199,7 @@ let rec visitExpression = function
/// モジュール内の宣言リストを走査する。
/// モジュール内のトップレベルに記述できるすべての要素
/// (letバインディングやネストされたモジュール、型の宣言など)が対象になる。
-let visitDeclarations decls =
+let visitDeclarations decls =
for declaration in decls do
match declaration with
| SynModuleDecl.Let(isRec, bindings, range) ->
@@ -198,10 +207,10 @@ let visitDeclarations decls =
// (visitExpressionで処理したような)式としてのletバインディングと
// 似ているが、本体を持たない
for binding in bindings do
- let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
+ let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
data, pat, retInfo, body, m, sp)) = binding
- visitPattern pat
- visitExpression body
+ visitPattern pat
+ visitExpression body
| _ -> printfn " - サポート対象外の宣言: %A" declaration
(**
`visitDeclarations` 関数はモジュールや名前空間の宣言のシーケンスを走査する
@@ -234,15 +243,15 @@ UnixとWindowsどちらの形式でも指定できます:
*)
// コンパイラサービスへのサンプル入力
let input = """
- let foo() =
+ let foo() =
let msg = "Hello world"
- if true then
+ if true then
printfn "%s" msg """
// Unix形式のファイル名
let file = "/home/user/Test.fsx"
// サンプルF#コードに対するASTを取得
-let tree = getUntypedTree(file, input)
+let tree = getUntypedTree(file, input)
(**
このコードをF# Interactiveで実行した場合、コンソールに `tree;;` と入力すると、
データ構造に対する文字列表現が表示されることが確認できます。
diff --git a/fcs/docsrc/content/project.fsx b/fcs/docsrc/content/project.fsx
index e85bad35e0..ee0750561d 100644
--- a/fcs/docsrc/content/project.fsx
+++ b/fcs/docsrc/content/project.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Project Analysis
+menu_order: 6
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -29,14 +37,14 @@ open System.Collections.Generic
open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.Text
-// Create an interactive checker instance
+// Create an interactive checker instance
let checker = FSharpChecker.Create()
(**
Here are our sample inputs:
*)
-module Inputs =
+module Inputs =
open System.IO
let base1 = Path.GetTempFileName()
@@ -48,7 +56,7 @@ module Inputs =
let fileSource1 = """
module M
-type C() =
+type C() =
member x.P = 1
let xxx = 3 + 4
@@ -61,10 +69,10 @@ module N
open M
-type D1() =
+type D1() =
member x.SomeProperty = M.xxx
-type D2() =
+type D2() =
member x.SomeProperty = M.fff() + D1().P
// Generate a warning
@@ -77,8 +85,8 @@ let y2 = match 1 with 1 -> M.xxx
We use `GetProjectOptionsFromCommandLineArgs` to treat two files as a project:
*)
-let projectOptions =
- let sysLib nm =
+let projectOptions =
+ let sysLib nm =
if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then
// file references only valid on Windows
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) +
@@ -86,37 +94,37 @@ let projectOptions =
else
let sysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()
let (++) a b = System.IO.Path.Combine(a,b)
- sysDir ++ nm + ".dll"
+ sysDir ++ nm + ".dll"
- let fsCore4300() =
+ let fsCore4300() =
if System.Environment.OSVersion.Platform = System.PlatformID.Win32NT then
// file references only valid on Windows
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) +
- @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
- else
+ @"\Reference Assemblies\Microsoft\FSharp\.NETFramework\v4.0\4.3.0.0\FSharp.Core.dll"
+ else
sysLib "FSharp.Core"
checker.GetProjectOptionsFromCommandLineArgs
(Inputs.projFileName,
- [| yield "--simpleresolution"
- yield "--noframework"
- yield "--debug:full"
- yield "--define:DEBUG"
- yield "--optimize-"
+ [| yield "--simpleresolution"
+ yield "--noframework"
+ yield "--debug:full"
+ yield "--define:DEBUG"
+ yield "--optimize-"
yield "--out:" + Inputs.dllName
- yield "--doc:test.xml"
- yield "--warn:3"
- yield "--fullpaths"
- yield "--flaterrors"
- yield "--target:library"
+ yield "--doc:test.xml"
+ yield "--warn:3"
+ yield "--fullpaths"
+ yield "--flaterrors"
+ yield "--target:library"
yield Inputs.fileName1
yield Inputs.fileName2
let references =
- [ sysLib "mscorlib"
+ [ sysLib "mscorlib"
sysLib "System"
sysLib "System.Core"
fsCore4300() ]
- for r in references do
+ for r in references do
yield "-r:" + r |])
(**
@@ -147,9 +155,9 @@ Now look at the inferred signature for the project:
(**
You can also get all symbols in the project:
*)
-let rec allSymbolsInEntities (entities: IList) =
- [ for e in entities do
- yield (e :> FSharpSymbol)
+let rec allSymbolsInEntities (entities: IList) =
+ [ for e in entities do
+ yield (e :> FSharpSymbol)
for x in e.MembersFunctionsAndValues do
yield (x :> FSharpSymbol)
for x in e.UnionCases do
@@ -164,8 +172,8 @@ After checking the whole project, you can access the background results for indi
in the project. This will be fast and will not involve any additional checking.
*)
-let backgroundParseResults1, backgroundTypedParse1 =
- checker.GetBackgroundCheckResultsForFileInProject(Inputs.fileName1, projectOptions)
+let backgroundParseResults1, backgroundTypedParse1 =
+ checker.GetBackgroundCheckResultsForFileInProject(Inputs.fileName1, projectOptions)
|> Async.RunSynchronously
@@ -173,7 +181,7 @@ let backgroundParseResults1, backgroundTypedParse1 =
You can now resolve symbols in each file:
*)
-let xSymbolUseOpt =
+let xSymbolUseOpt =
backgroundTypedParse1.GetSymbolUseAtLocation(9,9,"",["xxx"])
|> Async.RunSynchronously
@@ -185,63 +193,63 @@ let xSymbol = xSymbolUse.Symbol
You can find out more about a symbol by doing type checks on various symbol kinds:
*)
-let xSymbolAsValue =
- match xSymbol with
+let xSymbolAsValue =
+ match xSymbol with
| :? FSharpMemberOrFunctionOrValue as xSymbolAsVal -> xSymbolAsVal
| _ -> failwith "we expected this to be a member, function or value"
-
+
(**
For each symbol, you can look up the references to that symbol:
*)
-let usesOfXSymbol =
- wholeProjectResults.GetUsesOfSymbol(xSymbol)
+let usesOfXSymbol =
+ wholeProjectResults.GetUsesOfSymbol(xSymbol)
|> Async.RunSynchronously
(**
You can iterate all the defined symbols in the inferred signature and find where they are used:
*)
-let allUsesOfAllSignatureSymbols =
- [ for s in allSymbols do
- let uses = wholeProjectResults.GetUsesOfSymbol(s) |> Async.RunSynchronously
+let allUsesOfAllSignatureSymbols =
+ [ for s in allSymbols do
+ let uses = wholeProjectResults.GetUsesOfSymbol(s) |> Async.RunSynchronously
yield s.ToString(), uses ]
(**
You can also look at all the symbols uses in the whole project (including uses of symbols with local scope)
*)
-let allUsesOfAllSymbols =
+let allUsesOfAllSymbols =
wholeProjectResults.GetAllUsesOfAllSymbols()
|> Async.RunSynchronously
(**
-You can also request checks of updated versions of files within the project (note that the other files
+You can also request checks of updated versions of files within the project (note that the other files
in the project are still read from disk, unless you are using the [FileSystem API](filesystem.html)):
*)
-let parseResults1, checkAnswer1 =
+let parseResults1, checkAnswer1 =
checker.ParseAndCheckFileInProject(Inputs.fileName1, 0, SourceText.ofString Inputs.fileSource1, projectOptions)
|> Async.RunSynchronously
-let checkResults1 =
- match checkAnswer1 with
- | FSharpCheckFileAnswer.Succeeded x -> x
+let checkResults1 =
+ match checkAnswer1 with
+ | FSharpCheckFileAnswer.Succeeded x -> x
| _ -> failwith "unexpected aborted"
-let parseResults2, checkAnswer2 =
+let parseResults2, checkAnswer2 =
checker.ParseAndCheckFileInProject(Inputs.fileName2, 0, SourceText.ofString Inputs.fileSource2, projectOptions)
|> Async.RunSynchronously
-let checkResults2 =
- match checkAnswer2 with
- | FSharpCheckFileAnswer.Succeeded x -> x
+let checkResults2 =
+ match checkAnswer2 with
+ | FSharpCheckFileAnswer.Succeeded x -> x
| _ -> failwith "unexpected aborted"
(**
Again, you can resolve symbols and ask for references:
*)
-let xSymbolUse2Opt =
+let xSymbolUse2Opt =
checkResults1.GetSymbolUseAtLocation(9,9,"",["xxx"])
|> Async.RunSynchronously
@@ -249,26 +257,26 @@ let xSymbolUse2 = xSymbolUse2Opt.Value
let xSymbol2 = xSymbolUse2.Symbol
-let usesOfXSymbol2 =
- wholeProjectResults.GetUsesOfSymbol(xSymbol2)
+let usesOfXSymbol2 =
+ wholeProjectResults.GetUsesOfSymbol(xSymbol2)
|> Async.RunSynchronously
(**
Or ask for all the symbols uses in the file (including uses of symbols with local scope)
*)
-let allUsesOfAllSymbolsInFile1 =
+let allUsesOfAllSymbolsInFile1 =
checkResults1.GetAllUsesOfAllSymbolsInFile()
|> Async.RunSynchronously
(**
Or ask for all the uses of one symbol in one file:
*)
-let allUsesOfXSymbolInFile1 =
+let allUsesOfXSymbolInFile1 =
checkResults1.GetUsesOfSymbolInFile(xSymbol2)
|> Async.RunSynchronously
-let allUsesOfXSymbolInFile2 =
+let allUsesOfXSymbolInFile2 =
checkResults2.GetUsesOfSymbolInFile(xSymbol2)
|> Async.RunSynchronously
@@ -277,8 +285,8 @@ let allUsesOfXSymbolInFile2 =
Analyzing multiple projects
-----------------------------
-If you have multiple F# projects to analyze which include references from some projects to others,
-then the simplest way to do this is to build the projects and specify the cross-project references using
+If you have multiple F# projects to analyze which include references from some projects to others,
+then the simplest way to do this is to build the projects and specify the cross-project references using
a `-r:path-to-output-of-project.dll` argument in the ProjectOptions. However, this requires the build
of each project to succeed, producing the DLL file on disk which can be referred to.
@@ -293,14 +301,14 @@ When a project reference is used, the analysis will make use of the results of i
analysis of the referenced F# project from source files, without requiring the compilation of these files to DLLs.
To efficiently analyze a set of F# projects which include cross-references, you should populate the ProjectReferences
-correctly and then analyze each project in turn.
+correctly and then analyze each project in turn.
*)
(**
-> **NOTE:** Project references are disabled if the assembly being referred to contains type provider components -
- specifying the project reference will have no effect beyond forcing the analysis of the project, and the DLL will
+> **NOTE:** Project references are disabled if the assembly being referred to contains type provider components -
+ specifying the project reference will have no effect beyond forcing the analysis of the project, and the DLL will
still be required on disk.
*)
@@ -309,7 +317,7 @@ correctly and then analyze each project in turn.
Summary
-------
-As you have seen, the `ParseAndCheckProject` lets you access results of project-wide analysis
+As you have seen, the `ParseAndCheckProject` lets you access results of project-wide analysis
such as symbol references. To learn more about working with symbols, see [Symbols](symbols.html).
Using the FSharpChecker component in multi-project, incremental and interactive editing situations may involve
diff --git a/fcs/docsrc/content/queue.fsx b/fcs/docsrc/content/queue.fsx
index 8de84c19e2..1a30a89e88 100644
--- a/fcs/docsrc/content/queue.fsx
+++ b/fcs/docsrc/content/queue.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: how-to
+title: Notes on the FSharpChecker operations queue
+menu_order: 1
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -6,55 +14,55 @@ Compiler Services: Notes on the FSharpChecker operations queue
This is a design note on the FSharpChecker component and its operations queue. See also the notes on the [FSharpChecker caches](caches.html)
-FSharpChecker maintains an operations queue. Items from the FSharpChecker operations queue are processed
-sequentially and in order.
+FSharpChecker maintains an operations queue. Items from the FSharpChecker operations queue are processed
+sequentially and in order.
The thread processing these requests can also run a low-priority, interleaved background operation when the
-queue is empty. This can be used to implicitly bring the background check of a project "up-to-date".
+queue is empty. This can be used to implicitly bring the background check of a project "up-to-date".
When the operations queue has been empty for 1 second,
-this background work is run in small incremental fragments. This work is cooperatively time-sliced to be approximately <50ms, (see `maxTimeShareMilliseconds` in
-IncrementalBuild.fs). The project to be checked in the background is set implicitly
+this background work is run in small incremental fragments. This work is cooperatively time-sliced to be approximately <50ms, (see `maxTimeShareMilliseconds` in
+IncrementalBuild.fs). The project to be checked in the background is set implicitly
by calls to ``CheckFileInProject`` and ``ParseAndCheckFileInProject``.
To disable implicit background checking completely, set ``checker.ImplicitlyStartBackgroundWork`` to false.
To change the time before background work starts, set ``checker.PauseBeforeBackgroundWork`` to the required number of milliseconds.
-Most calls to the FSharpChecker API enqueue an operation in the FSharpChecker compiler queue. These correspond to the
+Most calls to the FSharpChecker API enqueue an operation in the FSharpChecker compiler queue. These correspond to the
calls to EnqueueAndAwaitOpAsync in [service.fs](https://github.com/fsharp/FSharp.Compiler.Service/blob/master/src/fsharp/service/service.fs).
-* For example, calling `ParseAndCheckProject` enqueues a `ParseAndCheckProjectImpl` operation. The time taken for the
+* For example, calling `ParseAndCheckProject` enqueues a `ParseAndCheckProjectImpl` operation. The time taken for the
operation will depend on how much work is required to bring the project analysis up-to-date.
-* Likewise, calling any of `GetUsesOfSymbol`, `GetAllUsesOfAllSymbols`, `ParseFileInProject`,
- `GetBackgroundParseResultsForFileInProject`, `MatchBraces`, `CheckFileInProjectIfReady`, `ParseAndCheckFileInProject`, `GetBackgroundCheckResultsForFileInProject`,
- `ParseAndCheckProject`, `GetProjectOptionsFromScript`, `InvalidateConfiguration`, `InvaidateAll` and operations
- on FSharpCheckResults will cause an operation to be enqueued. The length of the operation will
+* Likewise, calling any of `GetUsesOfSymbol`, `GetAllUsesOfAllSymbols`, `ParseFileInProject`,
+ `GetBackgroundParseResultsForFileInProject`, `MatchBraces`, `CheckFileInProjectIfReady`, `ParseAndCheckFileInProject`, `GetBackgroundCheckResultsForFileInProject`,
+ `ParseAndCheckProject`, `GetProjectOptionsFromScript`, `InvalidateConfiguration`, `InvaidateAll` and operations
+ on FSharpCheckResults will cause an operation to be enqueued. The length of the operation will
vary - many will be very fast - but they won't be processed until other operations already in the queue are complete.
Some operations do not enqueue anything on the FSharpChecker operations queue - notably any accesses to the Symbol APIs.
These use cross-threaded access to the TAST data produced by other FSharpChecker operations.
-Some tools throw a lot of interactive work at the FSharpChecker operations queue.
+Some tools throw a lot of interactive work at the FSharpChecker operations queue.
If you are writing such a component, consider running your project against a debug build
of FSharp.Compiler.Service.dll to see the Trace.WriteInformation messages indicating the length of the
operations queue and the time to process requests.
-For those writing interactive editors which use FCS, you
+For those writing interactive editors which use FCS, you
should be cautious about operations that request a check of the entire project.
For example, be careful about requesting the check of an entire project
-on operations like "Highlight Symbol" or "Find Unused Declarations"
+on operations like "Highlight Symbol" or "Find Unused Declarations"
(which run automatically when the user opens a file or moves the cursor).
-as opposed to operations like "Find All References" (which a user explicitly triggers).
-Project checking can cause long and contention on the FSharpChecker operations queue.
+as opposed to operations like "Find All References" (which a user explicitly triggers).
+Project checking can cause long and contention on the FSharpChecker operations queue.
-Requests to FCS can be cancelled by cancelling the async operation. (Some requests also
-include additional callbacks which can be used to indicate a cancellation condition).
-This cancellation will be effective if the cancellation is performed before the operation
+Requests to FCS can be cancelled by cancelling the async operation. (Some requests also
+include additional callbacks which can be used to indicate a cancellation condition).
+This cancellation will be effective if the cancellation is performed before the operation
is executed in the operations queue.
Summary
-------
In this design note, you learned that the FSharpChecker component keeps an operations queue. When using FSharpChecker
-in highly interactive situations, you should carefully consider the characteristics of the operations you are
+in highly interactive situations, you should carefully consider the characteristics of the operations you are
enqueueing.
*)
diff --git a/fcs/docsrc/content/react.fsx b/fcs/docsrc/content/react.fsx
index f00f83c7d6..3bb8cbb73b 100644
--- a/fcs/docsrc/content/react.fsx
+++ b/fcs/docsrc/content/react.fsx
@@ -1,16 +1,24 @@
+(**
+---
+category: tutorial
+title: Reacting to Changes
+menu_order: 10
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
Compiler Services: Reacting to Changes
============================================
-This tutorial discusses some technical aspects of how to make sure the F# compiler service is
+This tutorial discusses some technical aspects of how to make sure the F# compiler service is
providing up-to-date results especially when hosted in an IDE. See also [project wide analysis](project.html)
for information on project analysis.
> **NOTE:** The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published.
-The logical results of all "Check" routines (``ParseAndCheckFileInProject``, ``GetBackgroundCheckResultsForFileInProject``,
+The logical results of all "Check" routines (``ParseAndCheckFileInProject``, ``GetBackgroundCheckResultsForFileInProject``,
``TryGetRecentTypeCheckResultsForFile``, ``ParseAndCheckProject``) depend on results reported by the file system,
especially the ``IFileSystem`` implementation described in the tutorial on [project wide analysis](project.html).
Logically speaking, these results would be different if file system changes occur. For example,
@@ -24,27 +32,27 @@ FCS doesn't listen for changes directly - for example, it creates no ``FileWatch
and partly because some hosts forbid the creation of FileWatcher objects.
In most cases the repeated timestamp requests are sufficient. If you don't actively
-listen for changes, then ``FSharpChecker`` will still do _approximately_
+listen for changes, then ``FSharpChecker`` will still do _approximately_
the right thing, because it is asking for time stamps repeatedly. However, some updates on the file system
-(such as a DLL appearing after a build, or the user randomly pasting a file into a folder)
+(such as a DLL appearing after a build, or the user randomly pasting a file into a folder)
may not actively be noticed by ``FSharpChecker`` until some operation happens to ask for a timestamp.
By issuing fresh requests, you can ensure that FCS actively reassesses the state of play when
stays up-to-date when changes are observed.
If you want to more actively listen for changes, then you should add watchers for the
files specified in the ``DependencyFiles`` property of ``FSharpCheckFileResults`` and ``FSharpCheckProjectResults``.
-Here�s what you need to do:
+Here�s what you need to do:
* When your client notices an CHANGE event on a DependencyFile, it should schedule a refresh call to perform the ParseAndCheckFileInProject (or other operation) again.
This will result in fresh FileSystem calls to compute time stamps.
-* When your client notices an ADD event on a DependencyFile, it should call ``checker.InvalidateConfiguration``
- for all active projects in which the file occurs. This will result in fresh FileSystem calls to compute time
+* When your client notices an ADD event on a DependencyFile, it should call ``checker.InvalidateConfiguration``
+ for all active projects in which the file occurs. This will result in fresh FileSystem calls to compute time
stamps, and fresh calls to compute whether files exist.
-* Generally clients don�t listen for DELETE events on files. Although it would be logically more consistent
- to do so, in practice it�s very irritating for a "project clean" to invalidate all intellisense and
- cause lots of red squiggles. Some source control tools also make a change by removing and adding files, which
+* Generally clients don�t listen for DELETE events on files. Although it would be logically more consistent
+ to do so, in practice it�s very irritating for a "project clean" to invalidate all intellisense and
+ cause lots of red squiggles. Some source control tools also make a change by removing and adding files, which
is best noticed as a single change event.
@@ -57,8 +65,8 @@ If your host happens to be Visual Studio, then this is one technique you can use
let vsFileWatch = fls.GetService(typeof) :?> IVsFileChangeEx
// Watch the Add and Change events
- let fileChangeFlags =
- uint32 (_VSFILECHANGEFLAGS.VSFILECHG_Add |||
+ let fileChangeFlags =
+ uint32 (_VSFILECHANGEFLAGS.VSFILECHG_Add |||
// _VSFILECHANGEFLAGS.VSFILECHG_Del ||| // don't listen for deletes - if a file (such as a 'Clean'ed project reference) is deleted, just keep using stale info
_VSFILECHANGEFLAGS.VSFILECHG_Time)
@@ -66,7 +74,7 @@ If your host happens to be Visual Studio, then this is one technique you can use
let cookie = Com.ThrowOnFailure1(vsFileWatch.AdviseFileChange(file, fileChangeFlags, changeEvents))
...
-
+
// Unadvised file changes...
Com.ThrowOnFailure0(vsFileWatch.UnadviseFileChange(cookie))
diff --git a/fcs/docsrc/content/symbols.fsx b/fcs/docsrc/content/symbols.fsx
index 50ca938387..426cdf34b5 100644
--- a/fcs/docsrc/content/symbols.fsx
+++ b/fcs/docsrc/content/symbols.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Working with symbols
+menu_order: 4
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -21,7 +29,7 @@ open System.IO
open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.Text
-// Create an interactive checker instance
+// Create an interactive checker instance
let checker = FSharpChecker.Create()
(**
@@ -30,14 +38,14 @@ We now perform type checking on the specified input:
*)
-let parseAndTypeCheckSingleFile (file, input) =
+let parseAndTypeCheckSingleFile (file, input) =
// Get context representing a stand-alone (script) file
- let projOptions, errors =
+ let projOptions, errors =
checker.GetProjectOptionsFromScript(file, input)
|> Async.RunSynchronously
- let parseFileResults, checkFileResults =
- checker.ParseAndCheckFileInProject(file, 0, input, projOptions)
+ let parseFileResults, checkFileResults =
+ checker.ParseAndCheckFileInProject(file, 0, input, projOptions)
|> Async.RunSynchronously
// Wait until type checking succeeds (or 100 attempts)
@@ -53,35 +61,35 @@ let file = "/home/user/Test.fsx"
After type checking a file, you can access the inferred signature of a project up to and including the
checking of the given file through the `PartialAssemblySignature` property of the `TypeCheckResults`.
-The full signature information is available for modules, types, attributes, members, values, functions,
+The full signature information is available for modules, types, attributes, members, values, functions,
union cases, record types, units of measure and other F# language constructs.
The typed expression trees are also available, see [typed tree tutorial](typedtree.html).
*)
-let input2 =
+let input2 =
"""
[]
-let foo(x, y) =
+let foo(x, y) =
let msg = String.Concat("Hello"," ","world")
- if true then
- printfn "x = %d, y = %d" x y
+ if true then
+ printfn "x = %d, y = %d" x y
printfn "%s" msg
-type C() =
+type C() =
member x.P = 1
"""
-let parseFileResults, checkFileResults =
+let parseFileResults, checkFileResults =
parseAndTypeCheckSingleFile(file, SourceText.ofString input2)
(**
Now get the partial assembly signature for the code:
*)
let partialAssemblySignature = checkFileResults.PartialAssemblySignature
-
+
partialAssemblySignature.Entities.Count = 1 // one entity
-
+
(**
Now get the entity that corresponds to the module containing the code:
@@ -133,8 +141,8 @@ more information like the names of the arguments.)
*)
fnVal.FullType // int * int -> unit
fnVal.FullType.IsFunctionType // int * int -> unit
-fnVal.FullType.GenericArguments.[0] // int * int
-fnVal.FullType.GenericArguments.[0].IsTupleType // int * int
+fnVal.FullType.GenericArguments.[0] // int * int
+fnVal.FullType.GenericArguments.[0].IsTupleType // int * int
let argTy1 = fnVal.FullType.GenericArguments.[0].GenericArguments.[0]
argTy1.TypeDefinition.DisplayName // int
@@ -152,28 +160,28 @@ We can now look at the right-hand-side of the type abbreviation, which is the ty
*)
let argTy1b = argTy1.TypeDefinition.AbbreviatedType
-argTy1b.TypeDefinition.Namespace // Some "Microsoft.FSharp.Core"
-argTy1b.TypeDefinition.CompiledName // "int32"
+argTy1b.TypeDefinition.Namespace // Some "Microsoft.FSharp.Core"
+argTy1b.TypeDefinition.CompiledName // "int32"
(**
-Again we can now look through the type abbreviation `type int32 = System.Int32` to get the
+Again we can now look through the type abbreviation `type int32 = System.Int32` to get the
full information about the type:
*)
let argTy1c = argTy1b.TypeDefinition.AbbreviatedType
-argTy1c.TypeDefinition.Namespace // Some "SystemCore"
-argTy1c.TypeDefinition.CompiledName // "Int32"
+argTy1c.TypeDefinition.Namespace // Some "SystemCore"
+argTy1c.TypeDefinition.CompiledName // "Int32"
(**
The type checking results for a file also contain information extracted from the project (or script) options
used in the compilation, called the `ProjectContext`:
*)
let projectContext = checkFileResults.ProjectContext
-
+
for assembly in projectContext.GetReferencedAssemblies() do
- match assembly.FileName with
- | None -> printfn "compilation referenced an assembly without a file"
+ match assembly.FileName with
+ | None -> printfn "compilation referenced an assembly without a file"
| Some s -> printfn "compilation references assembly '%s'" s
-
+
(**
**Notes:**
@@ -189,12 +197,12 @@ for assembly in projectContext.GetReferencedAssemblies() do
## Getting symbolic information about whole projects
-To check whole projects, create a checker, then call `parseAndCheckScript`. In this case, we just check
-the project for a single script. By specifying a different "projOptions" you can create
+To check whole projects, create a checker, then call `parseAndCheckScript`. In this case, we just check
+the project for a single script. By specifying a different "projOptions" you can create
a specification of a larger project.
*)
-let parseAndCheckScript (file, input) =
- let projOptions, errors =
+let parseAndCheckScript (file, input) =
+ let projOptions, errors =
checker.GetProjectOptionsFromScript(file, input)
|> Async.RunSynchronously
@@ -215,10 +223,10 @@ Now look at the results:
*)
let assemblySig = projectResults.AssemblySignature
-
+
assemblySig.Entities.Count = 1 // one entity
assemblySig.Entities.[0].Namespace // one entity
assemblySig.Entities.[0].DisplayName // "Tmp28D0"
-assemblySig.Entities.[0].MembersFunctionsAndValues.Count // 1
-assemblySig.Entities.[0].MembersFunctionsAndValues.[0].DisplayName // "foo"
-
+assemblySig.Entities.[0].MembersFunctionsAndValues.Count // 1
+assemblySig.Entities.[0].MembersFunctionsAndValues.[0].DisplayName // "foo"
+
diff --git a/fcs/docsrc/content/tokenizer.fsx b/fcs/docsrc/content/tokenizer.fsx
index 2af11ad440..b3dfae8cb2 100644
--- a/fcs/docsrc/content/tokenizer.fsx
+++ b/fcs/docsrc/content/tokenizer.fsx
@@ -1,13 +1,21 @@
+(**
+---
+category: tutorial
+title: F# Language Tokenizer
+menu_order: 1
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
Compiler Services: Using the F# tokenizer
=========================================
-This tutorial demonstrates how to call the F# language tokenizer. Given F#
+This tutorial demonstrates how to call the F# language tokenizer. Given F#
source code, the tokenizer generates a list of source code lines that contain
information about tokens on each line. For each token, you can get the type
-of the token, exact location as well as color kind of the token (keyword,
+of the token, exact location as well as color kind of the token (keyword,
identifier, number, operator, etc.).
> **NOTE:** The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
@@ -22,7 +30,7 @@ To use the tokenizer, reference `FSharp.Compiler.Service.dll` and open the
#r "FSharp.Compiler.Service.dll"
open FSharp.Compiler.SourceCodeServices
(**
-Now you can create an instance of `FSharpSourceTokenizer`. The class takes two
+Now you can create an instance of `FSharpSourceTokenizer`. The class takes two
arguments - the first is the list of defined symbols and the second is the
file name of the source code. The defined symbols are required because the
tokenizer handles `#if` directives. The file name is required only to specify
@@ -30,7 +38,7 @@ locations of the source code (and it does not have to exist):
*)
let sourceTok = FSharpSourceTokenizer([], Some "C:\\test.fsx")
(**
-Using the `sourceTok` object, we can now (repeatedly) tokenize lines of
+Using the `sourceTok` object, we can now (repeatedly) tokenize lines of
F# source code.
Tokenizing F# code
@@ -49,7 +57,7 @@ on the `FSharpSourceTokenizer` object that we created earlier:
let tokenizer = sourceTok.CreateLineTokenizer("let answer=42")
(**
Now, we can write a simple recursive function that calls `ScanToken` on the `tokenizer`
-until it returns `None` (indicating the end of line). When the function succeeds, it
+until it returns `None` (indicating the end of line). When the function succeeds, it
returns `FSharpTokenInfo` object with all the interesting details:
*)
/// Tokenize a single line of F# code
@@ -73,7 +81,7 @@ There is a number of interesting properties on `FSharpTokenInfo` including:
- `CharClass` and `ColorClass` return information about the token category that
can be used for colorizing F# code.
- `LeftColumn` and `RightColumn` return the location of the token inside the line.
- - `TokenName` is the name of the token (as defined in the F# lexer)
+ - `TokenName` is the name of the token (as defined in the F# lexer)
Note that the tokenizer is stateful - if you want to tokenize single line multiple times,
you need to call `CreateLineTokenizer` again.
@@ -94,7 +102,7 @@ and the current state). We create a new tokenizer for each line and call `tokeni
using the state from the *end* of the previous line:
*)
/// Print token names for multiple lines of code
-let rec tokenizeLines state count lines =
+let rec tokenizeLines state count lines =
match lines with
| line::lines ->
// Create tokenizer & tokenize single line
@@ -118,14 +126,14 @@ the first line which is just whitespace), the code generates the following outpu
[lang=text]
Line 1
- LINE_COMMENT LINE_COMMENT (...) LINE_COMMENT
+ LINE_COMMENT LINE_COMMENT (...) LINE_COMMENT
Line 2
- LET WHITESPACE IDENT LPAREN RPAREN WHITESPACE EQUALS
+ LET WHITESPACE IDENT LPAREN RPAREN WHITESPACE EQUALS
Line 3
- IDENT WHITESPACE STRING_TEXT (...) STRING_TEXT STRING
+ IDENT WHITESPACE STRING_TEXT (...) STRING_TEXT STRING
It is worth noting that the tokenizer yields multiple `LINE_COMMENT` tokens and multiple
`STRING_TEXT` tokens for each single comment or string (roughly, one for each word), so
-if you want to get the entire text of a comment/string, you need to concatenate the
+if you want to get the entire text of a comment/string, you need to concatenate the
tokens.
*)
\ No newline at end of file
diff --git a/fcs/docsrc/content/typedtree.fsx b/fcs/docsrc/content/typedtree.fsx
index 3a10340a42..81d67baaf0 100644
--- a/fcs/docsrc/content/typedtree.fsx
+++ b/fcs/docsrc/content/typedtree.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Processing typed expression tree
+menu_order: 5
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -5,11 +13,11 @@ Compiler Services: Processing typed expression tree
=================================================
This tutorial demonstrates how to get the checked, typed expressions tree (TAST)
-for F# code and how to walk over the tree.
+for F# code and how to walk over the tree.
This can be used for creating tools such as source code analyzers and refactoring tools.
You can also combine the information with the API available
-from [symbols](symbols.html).
+from [symbols](symbols.html).
> **NOTE:** The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
@@ -35,14 +43,14 @@ We first parse and check some code as in the [symbols](symbols.html) tutorial.
One difference is that we set keepAssemblyContents to true.
*)
-// Create an interactive checker instance
+// Create an interactive checker instance
let checker = FSharpChecker.Create(keepAssemblyContents=true)
-let parseAndCheckSingleFile (input) =
- let file = Path.ChangeExtension(System.IO.Path.GetTempFileName(), "fsx")
+let parseAndCheckSingleFile (input) =
+ let file = Path.ChangeExtension(System.IO.Path.GetTempFileName(), "fsx")
File.WriteAllText(file, input)
// Get context representing a stand-alone (script) file
- let projOptions, _errors =
+ let projOptions, _errors =
checker.GetProjectOptionsFromScript(file, SourceText.ofString input)
|> Async.RunSynchronously
@@ -58,23 +66,23 @@ After type checking a file, you can access the declarations and contents of the
*)
-let input2 =
+let input2 =
"""
-module MyLibrary
+module MyLibrary
open System
-let foo(x, y) =
+let foo(x, y) =
let msg = String.Concat("Hello", " ", "world")
- if msg.Length > 10 then
- 10
- else
+ if msg.Length > 10 then
+ 10
+ else
20
-type MyClass() =
+type MyClass() =
member x.MyMethod() = 1
"""
-let checkProjectResults =
+let checkProjectResults =
parseAndCheckSingleFile(input2)
checkProjectResults.Errors // should be empty
@@ -98,19 +106,19 @@ In this case there is only one implementation file in the project:
*)
-let rec printDecl prefix d =
- match d with
- | FSharpImplementationFileDeclaration.Entity (e, subDecls) ->
+let rec printDecl prefix d =
+ match d with
+ | FSharpImplementationFileDeclaration.Entity (e, subDecls) ->
printfn "%sEntity %s was declared and contains %d sub-declarations" prefix e.CompiledName subDecls.Length
- for subDecl in subDecls do
+ for subDecl in subDecls do
printDecl (prefix+" ") subDecl
- | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue(v, vs, e) ->
+ | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue(v, vs, e) ->
printfn "%sMember or value %s was declared" prefix v.CompiledName
- | FSharpImplementationFileDeclaration.InitAction(e) ->
- printfn "%sA top-level expression was declared" prefix
+ | FSharpImplementationFileDeclaration.InitAction(e) ->
+ printfn "%sA top-level expression was declared" prefix
-for d in checkedFile.Declarations do
+for d in checkedFile.Declarations do
printDecl "" d
// Entity MyLibrary was declared and contains 4 sub-declarations
@@ -121,8 +129,8 @@ for d in checkedFile.Declarations do
(**
-As can be seen, the only declaration in the implementation file is that of the module MyLibrary, which
-contains fours sub-declarations.
+As can be seen, the only declaration in the implementation file is that of the module MyLibrary, which
+contains fours sub-declarations.
> As an aside, one peculiarity here is that the member declarations (e.g. the "MyMethod" member) are returned as part of the containing module entity, not as part of their class.
@@ -130,8 +138,8 @@ contains fours sub-declarations.
*)
-let myLibraryEntity, myLibraryDecls =
- match checkedFile.Declarations.[0] with
+let myLibraryEntity, myLibraryDecls =
+ match checkedFile.Declarations.[0] with
| FSharpImplementationFileDeclaration.Entity (e, subDecls) -> (e, subDecls)
| _ -> failwith "unexpected"
@@ -141,17 +149,17 @@ let myLibraryEntity, myLibraryDecls =
What about the expressions, for example the body of function "foo"? Let's find it:
*)
-let (fooSymbol, fooArgs, fooExpression) =
- match myLibraryDecls.[0] with
+let (fooSymbol, fooArgs, fooExpression) =
+ match myLibraryDecls.[0] with
| FSharpImplementationFileDeclaration.MemberOrFunctionOrValue(v, vs, e) -> (v, vs, e)
| _ -> failwith "unexpected"
-(** Here 'fooSymbol' is a symbol associated with the declaration of 'foo',
-'fooArgs' represents the formal arguments to the 'foo' function, and 'fooExpression'
+(** Here 'fooSymbol' is a symbol associated with the declaration of 'foo',
+'fooArgs' represents the formal arguments to the 'foo' function, and 'fooExpression'
is an expression for the implementation of the 'foo' function.
-Once you have an expression, you can work with it much like an F# quotation. For example,
+Once you have an expression, you can work with it much like an F# quotation. For example,
you can find its declaration range and its type:
*)
@@ -169,90 +177,90 @@ Here is a generic expression visitor:
*)
-let rec visitExpr f (e:FSharpExpr) =
+let rec visitExpr f (e:FSharpExpr) =
f e
- match e with
- | BasicPatterns.AddressOf(lvalueExpr) ->
+ match e with
+ | BasicPatterns.AddressOf(lvalueExpr) ->
visitExpr f lvalueExpr
- | BasicPatterns.AddressSet(lvalueExpr, rvalueExpr) ->
+ | BasicPatterns.AddressSet(lvalueExpr, rvalueExpr) ->
visitExpr f lvalueExpr; visitExpr f rvalueExpr
- | BasicPatterns.Application(funcExpr, typeArgs, argExprs) ->
+ | BasicPatterns.Application(funcExpr, typeArgs, argExprs) ->
visitExpr f funcExpr; visitExprs f argExprs
- | BasicPatterns.Call(objExprOpt, memberOrFunc, typeArgs1, typeArgs2, argExprs) ->
+ | BasicPatterns.Call(objExprOpt, memberOrFunc, typeArgs1, typeArgs2, argExprs) ->
visitObjArg f objExprOpt; visitExprs f argExprs
- | BasicPatterns.Coerce(targetType, inpExpr) ->
+ | BasicPatterns.Coerce(targetType, inpExpr) ->
visitExpr f inpExpr
- | BasicPatterns.FastIntegerForLoop(startExpr, limitExpr, consumeExpr, isUp) ->
+ | BasicPatterns.FastIntegerForLoop(startExpr, limitExpr, consumeExpr, isUp) ->
visitExpr f startExpr; visitExpr f limitExpr; visitExpr f consumeExpr
- | BasicPatterns.ILAsm(asmCode, typeArgs, argExprs) ->
+ | BasicPatterns.ILAsm(asmCode, typeArgs, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.ILFieldGet (objExprOpt, fieldType, fieldName) ->
+ | BasicPatterns.ILFieldGet (objExprOpt, fieldType, fieldName) ->
visitObjArg f objExprOpt
- | BasicPatterns.ILFieldSet (objExprOpt, fieldType, fieldName, valueExpr) ->
+ | BasicPatterns.ILFieldSet (objExprOpt, fieldType, fieldName, valueExpr) ->
visitObjArg f objExprOpt
- | BasicPatterns.IfThenElse (guardExpr, thenExpr, elseExpr) ->
+ | BasicPatterns.IfThenElse (guardExpr, thenExpr, elseExpr) ->
visitExpr f guardExpr; visitExpr f thenExpr; visitExpr f elseExpr
- | BasicPatterns.Lambda(lambdaVar, bodyExpr) ->
+ | BasicPatterns.Lambda(lambdaVar, bodyExpr) ->
visitExpr f bodyExpr
- | BasicPatterns.Let((bindingVar, bindingExpr), bodyExpr) ->
+ | BasicPatterns.Let((bindingVar, bindingExpr), bodyExpr) ->
visitExpr f bindingExpr; visitExpr f bodyExpr
- | BasicPatterns.LetRec(recursiveBindings, bodyExpr) ->
+ | BasicPatterns.LetRec(recursiveBindings, bodyExpr) ->
List.iter (snd >> visitExpr f) recursiveBindings; visitExpr f bodyExpr
- | BasicPatterns.NewArray(arrayType, argExprs) ->
+ | BasicPatterns.NewArray(arrayType, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.NewDelegate(delegateType, delegateBodyExpr) ->
+ | BasicPatterns.NewDelegate(delegateType, delegateBodyExpr) ->
visitExpr f delegateBodyExpr
- | BasicPatterns.NewObject(objType, typeArgs, argExprs) ->
+ | BasicPatterns.NewObject(objType, typeArgs, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.NewRecord(recordType, argExprs) ->
+ | BasicPatterns.NewRecord(recordType, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.NewAnonRecord(recordType, argExprs) ->
+ | BasicPatterns.NewAnonRecord(recordType, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.NewTuple(tupleType, argExprs) ->
+ | BasicPatterns.NewTuple(tupleType, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.NewUnionCase(unionType, unionCase, argExprs) ->
+ | BasicPatterns.NewUnionCase(unionType, unionCase, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.Quote(quotedExpr) ->
+ | BasicPatterns.Quote(quotedExpr) ->
visitExpr f quotedExpr
- | BasicPatterns.FSharpFieldGet(objExprOpt, recordOrClassType, fieldInfo) ->
+ | BasicPatterns.FSharpFieldGet(objExprOpt, recordOrClassType, fieldInfo) ->
visitObjArg f objExprOpt
- | BasicPatterns.AnonRecordGet(objExpr, recordOrClassType, fieldInfo) ->
+ | BasicPatterns.AnonRecordGet(objExpr, recordOrClassType, fieldInfo) ->
visitExpr f objExpr
- | BasicPatterns.FSharpFieldSet(objExprOpt, recordOrClassType, fieldInfo, argExpr) ->
+ | BasicPatterns.FSharpFieldSet(objExprOpt, recordOrClassType, fieldInfo, argExpr) ->
visitObjArg f objExprOpt; visitExpr f argExpr
- | BasicPatterns.Sequential(firstExpr, secondExpr) ->
+ | BasicPatterns.Sequential(firstExpr, secondExpr) ->
visitExpr f firstExpr; visitExpr f secondExpr
- | BasicPatterns.TryFinally(bodyExpr, finalizeExpr) ->
+ | BasicPatterns.TryFinally(bodyExpr, finalizeExpr) ->
visitExpr f bodyExpr; visitExpr f finalizeExpr
- | BasicPatterns.TryWith(bodyExpr, _, _, catchVar, catchExpr) ->
+ | BasicPatterns.TryWith(bodyExpr, _, _, catchVar, catchExpr) ->
visitExpr f bodyExpr; visitExpr f catchExpr
- | BasicPatterns.TupleGet(tupleType, tupleElemIndex, tupleExpr) ->
+ | BasicPatterns.TupleGet(tupleType, tupleElemIndex, tupleExpr) ->
visitExpr f tupleExpr
- | BasicPatterns.DecisionTree(decisionExpr, decisionTargets) ->
+ | BasicPatterns.DecisionTree(decisionExpr, decisionTargets) ->
visitExpr f decisionExpr; List.iter (snd >> visitExpr f) decisionTargets
- | BasicPatterns.DecisionTreeSuccess (decisionTargetIdx, decisionTargetExprs) ->
+ | BasicPatterns.DecisionTreeSuccess (decisionTargetIdx, decisionTargetExprs) ->
visitExprs f decisionTargetExprs
- | BasicPatterns.TypeLambda(genericParam, bodyExpr) ->
+ | BasicPatterns.TypeLambda(genericParam, bodyExpr) ->
visitExpr f bodyExpr
- | BasicPatterns.TypeTest(ty, inpExpr) ->
+ | BasicPatterns.TypeTest(ty, inpExpr) ->
visitExpr f inpExpr
- | BasicPatterns.UnionCaseSet(unionExpr, unionType, unionCase, unionCaseField, valueExpr) ->
+ | BasicPatterns.UnionCaseSet(unionExpr, unionType, unionCase, unionCaseField, valueExpr) ->
visitExpr f unionExpr; visitExpr f valueExpr
- | BasicPatterns.UnionCaseGet(unionExpr, unionType, unionCase, unionCaseField) ->
+ | BasicPatterns.UnionCaseGet(unionExpr, unionType, unionCase, unionCaseField) ->
visitExpr f unionExpr
- | BasicPatterns.UnionCaseTest(unionExpr, unionType, unionCase) ->
+ | BasicPatterns.UnionCaseTest(unionExpr, unionType, unionCase) ->
visitExpr f unionExpr
- | BasicPatterns.UnionCaseTag(unionExpr, unionType) ->
+ | BasicPatterns.UnionCaseTag(unionExpr, unionType) ->
visitExpr f unionExpr
- | BasicPatterns.ObjectExpr(objType, baseCallExpr, overrides, interfaceImplementations) ->
+ | BasicPatterns.ObjectExpr(objType, baseCallExpr, overrides, interfaceImplementations) ->
visitExpr f baseCallExpr
List.iter (visitObjMember f) overrides
List.iter (snd >> List.iter (visitObjMember f)) interfaceImplementations
- | BasicPatterns.TraitCall(sourceTypes, traitName, typeArgs, typeInstantiation, argTypes, argExprs) ->
+ | BasicPatterns.TraitCall(sourceTypes, traitName, typeArgs, typeInstantiation, argTypes, argExprs) ->
visitExprs f argExprs
- | BasicPatterns.ValueSet(valToSet, valueExpr) ->
+ | BasicPatterns.ValueSet(valToSet, valueExpr) ->
visitExpr f valueExpr
- | BasicPatterns.WhileLoop(guardExpr, bodyExpr) ->
+ | BasicPatterns.WhileLoop(guardExpr, bodyExpr) ->
visitExpr f guardExpr; visitExpr f bodyExpr
| BasicPatterns.BaseValue baseType -> ()
| BasicPatterns.DefaultValue defaultType -> ()
@@ -261,13 +269,13 @@ let rec visitExpr f (e:FSharpExpr) =
| BasicPatterns.Value(valueToGet) -> ()
| _ -> failwith (sprintf "unrecognized %+A" e)
-and visitExprs f exprs =
+and visitExprs f exprs =
List.iter (visitExpr f) exprs
-and visitObjArg f objOpt =
+and visitObjArg f objOpt =
Option.iter (visitExpr f) objOpt
-and visitObjMember f memb =
+and visitObjMember f memb =
visitExpr f memb.Body
(**
@@ -292,17 +300,17 @@ fooExpression |> visitExpr (fun e -> printfn "Visiting %A" e)
// Visiting Const ...
(**
-Note that
+Note that
* The visitExpr function is recursive (for nested expressions).
-* Pattern matching is removed from the tree, into a form called 'decision trees'.
+* Pattern matching is removed from the tree, into a form called 'decision trees'.
Summary
-------
-In this tutorial, we looked at basic of working with checked declarations and expressions.
+In this tutorial, we looked at basic of working with checked declarations and expressions.
In practice, it is also useful to combine the information here
-with some information you can obtain from the [symbols](symbols.html)
+with some information you can obtain from the [symbols](symbols.html)
tutorial.
*)
diff --git a/fcs/docsrc/content/untypedtree.fsx b/fcs/docsrc/content/untypedtree.fsx
index a2a823ec3e..3ae02331bf 100644
--- a/fcs/docsrc/content/untypedtree.fsx
+++ b/fcs/docsrc/content/untypedtree.fsx
@@ -1,3 +1,11 @@
+(**
+---
+category: tutorial
+title: Processing untyped AST
+menu_order: 2
+
+---
+*)
(*** hide ***)
#I "../../../artifacts/bin/fcs/Release/netcoreapp3.0"
(**
@@ -10,7 +18,7 @@ such as code formatter, basic refactoring or code navigation tools. The untyped
syntax tree contains information about the code structure, but does not contain
types and there are some ambiguities that are resolved only later by the type
checker. You can also combine the untyped AST information with the API available
-from [editor services](editor.html).
+from [editor services](editor.html).
> **NOTE:** The FSharp.Compiler.Service API is subject to change when later versions of the nuget package are published
@@ -36,13 +44,13 @@ open FSharp.Compiler.Text
### Performing untyped parse
-The untyped parse operation is very fast (compared to type checking, which can
+The untyped parse operation is very fast (compared to type checking, which can
take notable amount of time) and so we can perform it synchronously. First, we
need to create `FSharpChecker` - the constructor takes an argument that
can be used to notify the checker about file changes (which we ignore).
*)
-// Create an interactive checker instance
+// Create an interactive checker instance
let checker = FSharpChecker.Create()
(**
@@ -55,17 +63,17 @@ return the `ParseTree` property:
*)
/// Get untyped tree for a specified input
-let getUntypedTree (file, input) =
+let getUntypedTree (file, input) =
// Get compiler options for the 'project' implied by a single script file
- let projOptions, errors =
+ let projOptions, errors =
checker.GetProjectOptionsFromScript(file, input)
|> Async.RunSynchronously
let parsingOptions, _errors = checker.GetParsingOptionsFromProjectOptions(projOptions)
// Run the first phase (untyped parsing) of the compiler
- let parseFileResults =
- checker.ParseFile(file, input, parsingOptions)
+ let parseFileResults =
+ checker.ParseFile(file, input, parsingOptions)
|> Async.RunSynchronously
match parseFileResults.ParseTree with
@@ -79,17 +87,17 @@ Walking over the AST
The abstract syntax tree is defined as a number of discriminated unions that represent
different syntactical elements (such as expressions, patterns, declarations etc.). The best
-way to understand the AST is to look at the definitions in [`ast.fs` in the source
+way to understand the AST is to look at the definitions in [`ast.fs` in the source
code](https://github.com/fsharp/fsharp/blob/master/src/fsharp/ast.fs#L464).
The relevant parts are in the following namespace:
*)
-open FSharp.Compiler.Ast
+open FSharp.Compiler.SyntaxTree
(**
When processing the AST, you will typically write a number of mutually recursive functions
that pattern match on the different syntactical elements. There is a number of elements
-that need to be supported - the top-level element is module or namespace declaration,
+that need to be supported - the top-level element is module or namespace declaration,
containing declarations inside a module (let bindings, types etc.). A let declaration inside
a module then contains expression, which can contain patterns.
@@ -102,10 +110,10 @@ we print information about the visited elements. For patterns, the input is of t
is occasionally more complex than what is in the source code (in particular, `Named` is
used more often):
*)
-/// Walk over a pattern - this is for example used in
+/// Walk over a pattern - this is for example used in
/// let = or in the 'match' expression
let rec visitPattern = function
- | SynPat.Wild(_) ->
+ | SynPat.Wild(_) ->
printfn " .. underscore pattern"
| SynPat.Named(pat, name, _, _, _) ->
visitPattern pat
@@ -116,14 +124,14 @@ let rec visitPattern = function
| pat -> printfn " .. other pattern: %A" pat
(**
The function is recursive (for nested patterns such as `(foo, _) as bar`), but it does not
-call any of the functions defined later (because patterns cannot contain other syntactical
+call any of the functions defined later (because patterns cannot contain other syntactical
elements).
The next function iterates over expressions - this is where most of the work would be and
-there are around 20 cases to cover (type `SynExpr.` and you'll get completion with other
+there are around 20 cases to cover (type `SynExpr.` and you'll get completion with other
options). In the following, we only show how to handle `if .. then ..` and `let .. = ...`:
*)
-/// Walk over an expression - if expression contains two or three
+/// Walk over an expression - if expression contains two or three
/// sub-expressions (two if the 'else' branch is missing), let expression
/// contains pattern and two sub-expressions
let rec visitExpression = function
@@ -132,16 +140,16 @@ let rec visitExpression = function
printfn "Conditional:"
visitExpression cond
visitExpression trueBranch
- falseBranchOpt |> Option.iter visitExpression
+ falseBranchOpt |> Option.iter visitExpression
| SynExpr.LetOrUse(_, _, bindings, body, _) ->
- // Visit bindings (there may be multiple
+ // Visit bindings (there may be multiple
// for 'let .. = .. and .. = .. in ...'
printfn "LetOrUse with the following bindings:"
for binding in bindings do
- let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
+ let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
data, pat, retInfo, init, m, sp)) = binding
- visitPattern pat
+ visitPattern pat
visitExpression init
// Visit the body expression
printfn "And the following body:"
@@ -157,30 +165,30 @@ be another source of calls to `visitExpression`.
As mentioned earlier, the AST of a file contains a number of module or namespace declarations
(top-level node) that contain declarations inside a module (let bindings or types) or inside
a namespace (just types). The following functions walks over declarations - we ignore types,
-nested modules and all other elements and look only at top-level `let` bindings (values and
+nested modules and all other elements and look only at top-level `let` bindings (values and
functions):
*)
/// Walk over a list of declarations in a module. This is anything
/// that you can write as a top-level inside module (let bindings,
/// nested modules, type declarations etc.)
-let visitDeclarations decls =
+let visitDeclarations decls =
for declaration in decls do
match declaration with
| SynModuleDecl.Let(isRec, bindings, range) ->
// Let binding as a declaration is similar to let binding
// as an expression (in visitExpression), but has no body
for binding in bindings do
- let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
+ let (Binding(access, kind, inlin, mutabl, attrs, xmlDoc,
data, pat, retInfo, body, m, sp)) = binding
- visitPattern pat
- visitExpression body
+ visitPattern pat
+ visitExpression body
| _ -> printfn " - not supported declaration: %A" declaration
(**
-The `visitDeclarations` function will be called from a function that walks over a
-sequence of module or namespace declarations. This corresponds, for example, to a file
+The `visitDeclarations` function will be called from a function that walks over a
+sequence of module or namespace declarations. This corresponds, for example, to a file
with multiple `namespace Foo` declarations:
*)
-/// Walk over all module or namespace declarations
+/// Walk over all module or namespace declarations
/// (basically 'module Foo =' or 'namespace Foo.Bar')
/// Note that there is one implicitly, even if the file
/// does not explicitly define it..
@@ -198,15 +206,15 @@ Putting things together
As already discussed, the `getUntypedTree` function uses `FSharpChecker` to run the first
phase (parsing) on the AST and get back the tree. The function requires F# source code together
-with location of the file. The location does not have to exist (it is used only for location
+with location of the file. The location does not have to exist (it is used only for location
information) and it can be in both Unix and Windows formats:
*)
// Sample input for the compiler service
let input =
"""
- let foo() =
+ let foo() =
let msg = "Hello world"
- if true then
+ if true then
printfn "%s" msg
"""
@@ -221,7 +229,7 @@ see pretty printed representation of the data structure - the tree contains a lo
so this is not particularly readable, but it gives you good idea about how the tree looks.
The returned `tree` value is again a discriminated union that can be two different cases - one case
-is `ParsedInput.SigFile` which represents F# signature file (`*.fsi`) and the other one is
+is `ParsedInput.SigFile` which represents F# signature file (`*.fsi`) and the other one is
`ParsedInput.ImplFile` representing regular source code (`*.fsx` or `*.fs`). The implementation
file contains a sequence of modules or namespaces that we can pass to the function implemented
in the previous step:
@@ -236,10 +244,10 @@ match tree with
(**
Summary
-------
-In this tutorial, we looked at basic of working with the untyped abstract syntax tree. This is a
-comprehensive topic, so it is not possible to explain everything in a single article. The
+In this tutorial, we looked at basic of working with the untyped abstract syntax tree. This is a
+comprehensive topic, so it is not possible to explain everything in a single article. The
[Fantomas project](https://github.com/dungpa/fantomas) is a good example of tool based on the untyped
AST that can help you understand more. In practice, it is also useful to combine the information here
-with some information you can obtain from the [editor services](editor.html) discussed in the next
+with some information you can obtain from the [editor services](editor.html) discussed in the next
tutorial.
*)
diff --git a/fcs/docsrc/files/content/fcs.css b/fcs/docsrc/files/content/fcs.css
deleted file mode 100644
index 3efde86fc5..0000000000
--- a/fcs/docsrc/files/content/fcs.css
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Animated gifs on the homepage */
-#anim-holder {
- overflow:hidden;
- position:relative;
- border-radius:5px;
-}
-
-#wbtn, #jbtn, #cbtn {
- cursor:pointer;
- border-style:none;
- color:#f0f8ff;
- border-radius:5px;
- background:#415d60;
- opacity:0.7;
- width:90px;
- height:23px;
- font-size:80%;
- text-align:center;
- padding-top:2px;
- position:absolute;
- top:10px;
-}
-
-#anim-holder a img {
- min-width:800px;
-}
-
-.nav-list > li > a.nflag {
- float:right;
- padding:0px;
-}
-.nav-list > li > a.nflag2 {
- margin-right:18px;
-}
\ No newline at end of file
diff --git a/fcs/docsrc/files/content/style.ja.css b/fcs/docsrc/files/content/style.ja.css
deleted file mode 100644
index e00bcfe02d..0000000000
--- a/fcs/docsrc/files/content/style.ja.css
+++ /dev/null
@@ -1,190 +0,0 @@
-@import url(http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans+Mono|Gudea);
-
-* { font-family: 'MS Meiryo', Gudea; }
-
-/*--------------------------------------------------------------------------
- Formatting for F# code snippets
-/*--------------------------------------------------------------------------*/
-
-/* identifier */
-span.i { color:#d1d1d1; }
-/* string */
-span.s { color:#d4b43c; }
-/* keywords */
-span.k { color:#4e98dc; }
-/* comment */
-span.c { color:#96C71D; }
-/* operators */
-span.o { color:#af75c1; }
-/* numbers */
-span.n { color:#96C71D; }
-/* line number */
-span.l { color:#80b0b0; }
-
-/* inactive code */
-span.inactive { color:#808080; }
-/* preprocessor */
-span.prep { color:#af75c1; }
-/* fsi output */
-span.fsi { color:#808080; }
-
-/* omitted */
-span.omitted {
- background:#3c4e52;
- border-radius:5px;
- color:#808080;
- padding:0px 0px 1px 0px;
-}
-/* tool tip */
-div.tip {
- background:#475b5f;
- border-radius:4px;
- font:11pt 'Droid Sans', arial, sans-serif, 'MS Meiryo';
- padding:6px 8px 6px 8px;
- display:none;
- color:#d1d1d1;
-}
-table.pre pre {
- padding:0px;
- margin:0px;
- border:none;
-}
-table.pre, pre.fssnip, pre {
- line-height:13pt;
- border:1px solid #d8d8d8;
- border-collapse:separate;
- white-space:pre;
- font: 9pt 'Droid Sans Mono',consolas,monospace,'MS Meiryo';
- width:90%;
- margin:10px 20px 20px 20px;
- background-color:#212d30;
- padding:10px;
- border-radius:5px;
- color:#d1d1d1;
-}
-table.pre pre {
- padding:0px;
- margin:0px;
- border-radius:0px;
- width: 100%;
-}
-table.pre td {
- padding:0px;
- white-space:normal;
- margin:0px;
-}
-table.pre td.lines {
- width:30px;
-}
-
-/*--------------------------------------------------------------------------
- Formatting for page & standard document content
-/*--------------------------------------------------------------------------*/
-
-body {
- font-family: Gudea, serif, 'MS Meiryo';
- padding-top: 0px;
- padding-bottom: 40px;
-}
-
-pre {
- word-wrap: inherit;
-}
-
-/* Format the heading - nicer spacing etc. */
-.masthead {
- overflow: hidden;
-}
-.masthead ul, .masthead li {
- margin-bottom:0px;
-}
-.masthead .nav li {
- margin-top: 15px;
- font-size:110%;
-}
-.masthead h3 {
- margin-bottom:5px;
- font-size:170%;
-}
-hr {
- margin:0px 0px 20px 0px;
-}
-
-/* Make table headings and td.title bold */
-td.title, thead {
- font-weight:bold;
-}
-
-/* Format the right-side menu */
-#menu {
- margin-top:50px;
- font-size:11pt;
- padding-left:20px;
-}
-
-#menu .nav-header {
- font-size:12pt;
- color:#606060;
- margin-top:20px;
-}
-
-#menu li {
- line-height:25px;
-}
-
-/* Change font sizes for headings etc. */
-#main h1 { font-size: 26pt; margin:10px 0px 15px 0px; }
-#main h2 { font-size: 20pt; margin:20px 0px 0px 0px; }
-#main h3 { font-size: 14pt; margin:15px 0px 0px 0px; }
-#main p { font-size: 12pt; margin:5px 0px 15px 0px; }
-#main ul { font-size: 12pt; margin-top:10px; }
-#main li { font-size: 12pt; margin: 5px 0px 5px 0px; }
-
-/*--------------------------------------------------------------------------
- Formatting for API reference
-/*--------------------------------------------------------------------------*/
-
-.type-list .type-name, .module-list .module-name {
- width:25%;
- font-weight:bold;
-}
-.member-list .member-name {
- width:35%;
-}
-#main .xmldoc h2 {
- font-size:14pt;
- margin:10px 0px 0px 0px;
-}
-#main .xmldoc h3 {
- font-size:12pt;
- margin:10px 0px 0px 0px;
-}
-/*--------------------------------------------------------------------------
- Additional formatting for the homepage
-/*--------------------------------------------------------------------------*/
-
-#nuget {
- margin-top:20px;
- font-size: 11pt;
- padding:20px;
-}
-
-#nuget pre {
- font-size:11pt;
- -moz-border-radius: 0px;
- -webkit-border-radius: 0px;
- border-radius: 0px;
- background: #404040;
- border-style:none;
- color: #e0e0e0;
- margin-top:15px;
-}
-
-/* Hide snippets on the home page snippet & nicely format table */
-#hp-snippet td.lines {
- display: none;
-}
-#hp-snippet .table {
- width:80%;
- margin-left:30px;
-}
diff --git a/fcs/docsrc/files/images/en.png b/fcs/docsrc/files/images/en.png
deleted file mode 100644
index a6568bf968..0000000000
Binary files a/fcs/docsrc/files/images/en.png and /dev/null differ
diff --git a/fcs/docsrc/files/images/ja.png b/fcs/docsrc/files/images/ja.png
deleted file mode 100644
index 14639e2db0..0000000000
Binary files a/fcs/docsrc/files/images/ja.png and /dev/null differ
diff --git a/fcs/docsrc/files/images/logo.png b/fcs/docsrc/files/images/logo.png
deleted file mode 100644
index 9d7b823ec9..0000000000
Binary files a/fcs/docsrc/files/images/logo.png and /dev/null differ
diff --git a/fcs/docsrc/generators/apiref.fsx b/fcs/docsrc/generators/apiref.fsx
new file mode 100644
index 0000000000..e0500a8bcb
--- /dev/null
+++ b/fcs/docsrc/generators/apiref.fsx
@@ -0,0 +1,303 @@
+#r "../_lib/Fornax.Core.dll"
+#r "../../packages/docs/Newtonsoft.Json/lib/netstandard2.0/Newtonsoft.Json.dll"
+#r "../../packages/docs/FSharp.Formatting/lib/netstandard2.0/FSharp.CodeFormat.dll"
+#r "../../packages/docs/FSharp.Formatting/lib/netstandard2.0/FSharp.Markdown.dll"
+#r "../../packages/docs/FSharp.Formatting/lib/netstandard2.0/FSharp.Literate.dll"
+#r "../../packages/docs/FSharp.Formatting/lib/netstandard2.0/FSharp.MetadataFormat.dll"
+
+#if !FORNAX
+#load "../loaders/apirefloader.fsx"
+#endif
+
+#load "partials/layout.fsx"
+
+open System
+open FSharp.MetadataFormat
+open Html
+open Apirefloader
+open FSharp.Literate
+open FSharp.CodeFormat
+
+let tokenToCss (x: TokenKind) =
+ match x with
+ | TokenKind.Keyword -> "hljs-keyword"
+ | TokenKind.String -> "hljs-string"
+ | TokenKind.Comment -> "hljs-comment"
+ | TokenKind.Identifier -> "hljs-function"
+ | TokenKind.Inactive -> ""
+ | TokenKind.Number -> "hljs-number"
+ | TokenKind.Operator -> "hljs-keyword"
+ | TokenKind.Punctuation -> "hljs-keyword"
+ | TokenKind.Preprocessor -> "hljs-comment"
+ | TokenKind.Module -> "hljs-type"
+ | TokenKind.ReferenceType -> "hljs-type"
+ | TokenKind.ValueType -> "hljs-type"
+ | TokenKind.Interface -> "hljs-type"
+ | TokenKind.TypeArgument -> "hljs-type"
+ | TokenKind.Property -> "hljs-function"
+ | TokenKind.Enumeration -> "hljs-type"
+ | TokenKind.UnionCase -> "hljs-type"
+ | TokenKind.Function -> "hljs-function"
+ | TokenKind.Pattern -> "hljs-function"
+ | TokenKind.MutableVar -> "hljs-symbol"
+ | TokenKind.Disposable -> "hljs-symbol"
+ | TokenKind.Printf -> "hljs-regexp"
+ | TokenKind.Escaped -> "hljs-regexp"
+ | TokenKind.Default -> ""
+
+
+let getComment (c: Comment) : string =
+ let t =
+ c.RawData
+ |> List.map (fun n -> n.Value)
+ |> String.concat "\n\n"
+ let doc = Literate.ParseMarkdownString t
+ Literate.WriteHtml(doc, lineNumbers = false, tokenKindToCss = tokenToCss)
+ .Replace("lang=\"fsharp", "class=\"language-fsharp")
+
+
+let formatMember (m: Member) =
+ let attributes =
+ m.Attributes
+ |> List.filter (fun a -> a.FullName <> "Microsoft.FSharp.Core.CustomOperationAttribute")
+
+ let hasCustomOp =
+ m.Attributes
+ |> List.exists (fun a -> a.FullName = "Microsoft.FSharp.Core.CustomOperationAttribute")
+
+ let customOp =
+ if hasCustomOp then
+ m.Attributes
+ |> List.tryFind (fun a -> a.FullName = "Microsoft.FSharp.Core.CustomOperationAttribute")
+ |> Option.bind (fun a ->
+ a.ConstructorArguments
+ |> Seq.tryFind (fun x -> x :? string)
+ |> Option.map (fun x -> x.ToString())
+ )
+ |> Option.defaultValue ""
+ else
+ ""
+
+ tr [] [
+ td [] [
+ code [] [!! m.Name]
+ br []
+
+ if hasCustomOp then
+ b [] [!! "CE Custom Operation: "]
+ code [] [!!customOp]
+ br []
+ br []
+ b [] [!! "Signature: "]
+ !!m.Details.Signature
+ br []
+ if not (attributes.IsEmpty) then
+ b [] [!! "Attributes:"]
+ for a in attributes do
+ code [] [!! (a.Name)]
+ ]
+ td [] [!! (getComment m.Comment)]
+ ]
+
+let generateType ctx (page: ApiPageInfo) =
+ let t = page.Info
+ let body =
+ div [Class "api-page"] [
+ h2 [] [!! t.Name]
+ b [] [!! "Namespace: "]
+ a [Href (sprintf "%s.html" page.NamespaceUrlName) ] [!! page.NamespaceName]
+ br []
+ b [] [!! "Parent: "]
+ a [Href (sprintf "%s.html" page.ParentUrlName)] [!! page.ParentName]
+ span [] [!! (getComment t.Comment)]
+ br []
+ if not (String.IsNullOrWhiteSpace t.Category) then
+ b [] [!! "Category:"]
+ !!t.Category
+ br []
+ if not (t.Attributes.IsEmpty) then
+ b [] [!! "Attributes:"]
+ for a in t.Attributes do
+ br []
+ code [] [!! (a.Name)]
+ br []
+
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Name"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ if not t.Constructors.IsEmpty then tr [] [ td [ColSpan 3. ] [ b [] [!! "Constructors"]]]
+ yield! t.Constructors |> List.map formatMember
+
+ if not t.InstanceMembers.IsEmpty then tr [] [ td [ColSpan 3. ] [ b [] [!! "Instance Members"]]]
+ yield! t.InstanceMembers |> List.map formatMember
+
+ if not t.RecordFields.IsEmpty then tr [] [ td [ColSpan 3. ] [ b [] [!! "Record Fields"]]]
+ yield! t.RecordFields |> List.map formatMember
+
+ if not t.StaticMembers.IsEmpty then tr [] [ td [ColSpan 3. ] [ b [] [!! "Static Members"]]]
+ yield! t.StaticMembers |> List.map formatMember
+
+ if not t.StaticParameters.IsEmpty then tr [] [ td [ColSpan 3. ] [ b [] [!! "Static Parameters"]]]
+ yield! t.StaticParameters |> List.map formatMember
+
+ if not t.UnionCases.IsEmpty then tr [] [ td [ColSpan 3. ] [ b [] [!! "Union Cases"]]]
+ yield! t.UnionCases |> List.map formatMember
+ ]
+ ]
+ t.UrlName, Layout.layout ctx [body] t.Name
+
+let generateModule ctx (page: ApiPageInfo) =
+ let m = page.Info
+ let body =
+ div [Class "api-page"] [
+ h2 [] [!!m.Name]
+ b [] [!! "Namespace: "]
+ a [Href (sprintf "%s.html" page.NamespaceUrlName) ] [!! page.NamespaceName]
+ br []
+ b [] [!! "Parent: "]
+ a [Href (sprintf "%s.html" page.ParentUrlName)] [!! page.ParentName]
+ span [] [!! (getComment m.Comment)]
+ br []
+ if not (String.IsNullOrWhiteSpace m.Category) then
+ b [] [!! "Category:"]
+ !!m.Category
+ br []
+
+ if not m.NestedTypes.IsEmpty then
+ b [] [!! "Declared Types"]
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Type"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ for t in m.NestedTypes do
+ tr [] [
+ td [] [a [Href (sprintf "%s.html" t.UrlName )] [!! t.Name ]]
+ td [] [!! (getComment t.Comment)]
+ ]
+ ]
+ br []
+
+ if not m.NestedModules.IsEmpty then
+ b [] [!! "Declared Modules"]
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Module"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ for t in m.NestedModules do
+ tr [] [
+ td [] [a [Href (sprintf "%s.html" t.UrlName )] [!! t.Name ]]
+ td [] [!! (getComment t.Comment)]
+ ]
+ ]
+ br []
+
+ if not m.ValuesAndFuncs.IsEmpty then
+ b [] [!! "Values and Functions"]
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Name"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ yield! m.ValuesAndFuncs |> List.map formatMember
+ ]
+ br []
+
+ if not m.TypeExtensions.IsEmpty then
+ b [] [!! "Type Extensions"]
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Name"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ yield! m.TypeExtensions |> List.map formatMember
+ ]
+ ]
+ m.UrlName, Layout.layout ctx [body] m.Name
+
+let generateNamespace ctx (n: Namespace) =
+ let body =
+ div [Class "api-page"] [
+ h2 [] [!!n.Name]
+
+ if not n.Types.IsEmpty then
+
+ b [] [!! "Declared Types"]
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Type"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ for t in n.Types do
+ tr [] [
+ td [] [a [Href (sprintf "%s.html" t.UrlName )] [!! t.Name ]]
+ td [] [!!(getComment t.Comment)]
+ ]
+ ]
+ br []
+
+ if not n.Modules.IsEmpty then
+
+ b [] [!! "Declared Modules"]
+ table [] [
+ tr [] [
+ th [ Width "35%" ] [!!"Module"]
+ th [ Width "65%"] [!!"Description"]
+ ]
+ for t in n.Modules do
+ tr [] [
+ td [] [a [Href (sprintf "%s.html" t.UrlName )] [!! t.Name ]]
+ td [] [!! (getComment t.Comment)]
+ ]
+ ]
+ ]
+ n.Name, Layout.layout ctx [body] (n.Name)
+
+
+let generate' (ctx : SiteContents) =
+ let all = ctx.TryGetValues()
+ match all with
+ | None -> []
+ | Some all ->
+ all
+ |> Seq.toList
+ |> List.collect (fun n ->
+ let name = n.GeneratorOutput.AssemblyGroup.Name
+ let namespaces =
+ n.GeneratorOutput.AssemblyGroup.Namespaces
+ |> List.map (generateNamespace ctx)
+
+ let modules =
+ n.Modules
+ |> Seq.map (generateModule ctx)
+
+ let types =
+ n.Types
+ |> Seq.map (generateType ctx)
+
+ let ref =
+ Layout.layout ctx [
+ h1 [] [!! name ]
+ b [] [!! "Declared namespaces"]
+ br []
+ for (n, _) in namespaces do
+ a [Href (sprintf "%s.html" n)] [!!n]
+ br []
+ ] n.Label
+
+ [("index" , ref); yield! namespaces; yield! modules; yield! types]
+ |> List.map (fun (x, y) -> (sprintf "%s/%s" n.Label x), y)
+ )
+
+
+let generate (ctx : SiteContents) (projectRoot: string) (page: string) =
+ try
+ generate' ctx
+ |> List.map (fun (n,b) -> n, (Layout.render ctx b))
+ with
+ | ex ->
+ printfn "ERROR IN API REF GENERATION:\n%A" ex
+ []
diff --git a/fcs/docsrc/generators/lunr.fsx b/fcs/docsrc/generators/lunr.fsx
new file mode 100644
index 0000000000..eaceafd3fe
--- /dev/null
+++ b/fcs/docsrc/generators/lunr.fsx
@@ -0,0 +1,83 @@
+#r "../_lib/Fornax.Core.dll"
+#r "../../packages/docs/Newtonsoft.Json/lib/netstandard2.0/Newtonsoft.Json.dll"
+#r "../../packages/docs/FSharp.Formatting/lib/netstandard2.0/FSharp.MetadataFormat.dll"
+#if !FORNAX
+#load "../loaders/contentloader.fsx"
+#load "../loaders/apirefloader.fsx"
+#load "../loaders/globalloader.fsx"
+
+#endif
+
+open Apirefloader
+open FSharp.MetadataFormat
+
+
+type Entry = {
+ uri: string
+ title: string
+ content: string
+}
+let generate (ctx : SiteContents) (projectRoot: string) (page: string) =
+ let siteInfo = ctx.TryGetValue().Value
+ let rootUrl = siteInfo.root_url
+
+ let pages = ctx.TryGetValues () |> Option.defaultValue Seq.empty
+ let entries =
+ pages
+ |> Seq.map (fun n ->
+ {uri = rootUrl + "/" + n.link.Replace("content/", ""); title = n.title; content = n.text}
+ )
+
+ let all = ctx.TryGetValues()
+ let refs =
+ match all with
+ | None -> []
+ | Some all ->
+ all
+ |> Seq.toList
+ |> List.collect (fun n ->
+ let generatorOutput = n.GeneratorOutput
+ let allModules = n.Modules
+ let allTypes = n.Types
+
+ let gen =
+ let ctn =
+ sprintf "%s \n %s" generatorOutput.AssemblyGroup.Name (generatorOutput.AssemblyGroup.Namespaces |> Seq.map (fun n -> n.Name) |> String.concat " ")
+ {uri = (rootUrl + sprintf "/reference/%s/index.html" n.Label ); title = sprintf "%s - API Reference" n.Label; content = ctn }
+
+ let mdlsGen =
+ allModules
+ |> Seq.map (fun m ->
+ let m = m.Info
+ let cnt =
+ sprintf "%s \n %s \n %s \n %s \n %s \n %s"
+ m.Name
+ m.Comment.FullText
+ (m.NestedModules |> List.map (fun m -> m.Name + " " + m.Comment.FullText ) |> String.concat " ")
+ (m.NestedTypes |> List.map (fun m -> m.Name + " " + m.Comment.FullText ) |> String.concat " ")
+ (m.ValuesAndFuncs |> List.map (fun m -> m.Name + " " + m.Comment.FullText ) |> String.concat " ")
+ (m.TypeExtensions |> List.map (fun m -> m.Name + " " + m.Comment.FullText ) |> String.concat " ")
+
+
+ {uri = rootUrl + sprintf "/reference/%s/%s.html" n.Label m.UrlName ; title = m.Name; content = cnt }
+ )
+
+ let tsGen =
+ allTypes
+ |> Seq.map (fun m ->
+ let m = m.Info
+ let cnt =
+ sprintf "%s \n %s \n %s"
+ m.Name
+ m.Comment.FullText
+ (m.AllMembers |> List.map (fun m -> m.Name + " " + m.Comment.FullText ) |> String.concat " ")
+
+
+ {uri = rootUrl + sprintf "/reference/%s/%s.html" n.Label m.UrlName ; title = m.Name; content = cnt }
+ )
+ [yield! entries; gen; yield! mdlsGen; yield! tsGen]
+ )
+
+ [|yield! entries; yield! refs|]
+ |> Newtonsoft.Json.JsonConvert.SerializeObject
+
diff --git a/fcs/docsrc/generators/page.fsx b/fcs/docsrc/generators/page.fsx
new file mode 100644
index 0000000000..e07291238c
--- /dev/null
+++ b/fcs/docsrc/generators/page.fsx
@@ -0,0 +1,16 @@
+#r "../_lib/Fornax.Core.dll"
+#load "partials/layout.fsx"
+
+open Html
+
+
+let generate' (ctx : SiteContents) (page: string) =
+ let posts =
+ ctx.TryGetValues ()
+ |> Option.defaultValue Seq.empty
+ let post = posts |> Seq.find (fun n -> "content/" + n.file = page)
+ Layout.layout ctx [ !! post.content ] post.title
+
+let generate (ctx : SiteContents) (projectRoot: string) (page: string) =
+ generate' ctx page
+ |> Layout.render ctx
diff --git a/fcs/docsrc/generators/partials/footer.fsx b/fcs/docsrc/generators/partials/footer.fsx
new file mode 100644
index 0000000000..486018fb14
--- /dev/null
+++ b/fcs/docsrc/generators/partials/footer.fsx
@@ -0,0 +1,38 @@
+#r "../../_lib/Fornax.Core.dll"
+#if !FORNAX
+#load "../../loaders/contentloader.fsx"
+#load "../../loaders/pageloader.fsx"
+#load "../../loaders/globalloader.fsx"
+#endif
+
+open Html
+
+
+
+let footer (ctx : SiteContents) =
+ let siteInfo = ctx.TryGetValue().Value
+ let rootUrl = siteInfo.root_url
+
+ [
+ div [Custom("style", "left: -1000px; overflow: scroll; position: absolute; top: -1000px; border: none; box-sizing: content-box; height: 200px; margin: 0px; padding: 0px; width: 200px;")] [
+ div [Custom("style", "border: none; box-sizing: content-box; height: 200px; margin: 0px; padding: 0px; width: 200px;")] []
+ ]
+ script [Src (rootUrl + "/static/js/clipboard.min.js")] []
+ script [Src (rootUrl + "/static/js/perfect-scrollbar.min.js")] []
+ script [Src (rootUrl + "/static/js/perfect-scrollbar.jquery.min.js")] []
+ script [Src (rootUrl + "/static/js/jquery.sticky.js")] []
+ script [Src (rootUrl + "/static/js/featherlight.min.js")] []
+
+ script [Src (rootUrl + "/static/js/modernizr.custom-3.6.0.js")] []
+ script [Src (rootUrl + "/static/js/learn.js")] []
+ script [Src (rootUrl + "/static/js/hugo-learn.js")] []
+ link [Rel "stylesheet"; Href (rootUrl + "/static/mermaid/mermaid.css")]
+ script [Src (rootUrl + "/static/mermaid/mermaid.js")] []
+ script [] [!! "mermaid.initialize({ startOnLoad: true });"]
+ script [Src "//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/highlight.min.js"] []
+ script [Src "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/languages/fsharp.min.js"] []
+ script [] [
+ !! "hljs.initHighlightingOnLoad()"
+ ]
+ script [Src (rootUrl + "/static/js/tips.js")] []
+ ]
diff --git a/fcs/docsrc/generators/partials/header.fsx b/fcs/docsrc/generators/partials/header.fsx
new file mode 100644
index 0000000000..5d5fd0ec4f
--- /dev/null
+++ b/fcs/docsrc/generators/partials/header.fsx
@@ -0,0 +1,32 @@
+#r "../../_lib/Fornax.Core.dll"
+#if !FORNAX
+#load "../../loaders/contentloader.fsx"
+#load "../../loaders/pageloader.fsx"
+#load "../../loaders/globalloader.fsx"
+#endif
+
+open Html
+
+let header (ctx : SiteContents) page =
+ let siteInfo = ctx.TryGetValue().Value
+ let rootUrl = siteInfo.root_url
+
+ head [] [
+ meta [CharSet "utf-8"]
+ meta [Name "viewport"; Content "width=device-width, initial-scale=1"]
+ title [] [!! (siteInfo.title + " | " + page)]
+ link [Rel "icon"; Type "image/png"; Sizes "32x32"; Href (rootUrl + "/static/images/favicon.png")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/nucleus.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/fontawesome-all.min.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/hybrid.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/featherlight.min.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/perfect-scrollbar.min.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/auto-complete.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/atom-one-dark-reasonable.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/theme.css")]
+ link [Rel "stylesheet"; Href (rootUrl + "/static/css/tips.css")]
+ link [Rel "stylesheet"; Href "//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.0/styles/atom-one-dark.min.css"]
+ if siteInfo.theme_variant.IsSome then
+ link [Rel "stylesheet"; Href (rootUrl + (sprintf "/static/css/theme-%s.css" siteInfo.theme_variant.Value))]
+ script [Src (rootUrl + "/static/js/jquery-3.3.1.min.js")] []
+ ]
diff --git a/fcs/docsrc/generators/partials/layout.fsx b/fcs/docsrc/generators/partials/layout.fsx
new file mode 100644
index 0000000000..62262c067f
--- /dev/null
+++ b/fcs/docsrc/generators/partials/layout.fsx
@@ -0,0 +1,65 @@
+#r "../../_lib/Fornax.Core.dll"
+#if !FORNAX
+#load "../../loaders/contentloader.fsx"
+#load "../../loaders/pageloader.fsx"
+#load "../../loaders/globalloader.fsx"
+#endif
+#load "menu.fsx"
+#load "header.fsx"
+#load "footer.fsx"
+
+open Html
+
+let injectWebsocketCode (webpage:string) =
+ let websocketScript =
+ """
+
+ """
+ let head = ""
+ let index = webpage.IndexOf head
+ webpage.Insert ( (index + head.Length + 1),websocketScript)
+
+
+let layout (ctx : SiteContents) bodyCnt (page: string) =
+
+ html [Class "js csstransforms3d"] [
+ Header.header ctx page
+ body [] [
+ Menu.menu ctx page
+ section [Id "body"] [
+ div [Id "overlay"] []
+ div [ Class "padding highlightable"] [
+ div [Id "body-inner"] [
+ span [Id "sidebar-toggle-span"] [
+ a [Href "#"; Id "sidebar-toggle"; Custom("data-sidebar-toggle", "") ] [
+ i [Class "fas fa-bars"] []
+ !! " navigation"
+ ]
+ ]
+ yield! bodyCnt
+ ]
+ ]
+ ]
+ yield! Footer.footer ctx
+ ]
+ ]
+
+let render (ctx : SiteContents) cnt =
+ let disableLiveRefresh = ctx.TryGetValue () |> Option.map (fun n -> n.disableLiveRefresh) |> Option.defaultValue false
+ cnt
+ |> HtmlElement.ToString
+ |> fun n -> if disableLiveRefresh then n else injectWebsocketCode n
diff --git a/fcs/docsrc/generators/partials/menu.fsx b/fcs/docsrc/generators/partials/menu.fsx
new file mode 100644
index 0000000000..3d2d431d69
--- /dev/null
+++ b/fcs/docsrc/generators/partials/menu.fsx
@@ -0,0 +1,169 @@
+#r "../../_lib/Fornax.Core.dll"
+#if !FORNAX
+#load "../../loaders/apirefloader.fsx"
+#load "../../loaders/contentloader.fsx"
+#load "../../loaders/pageloader.fsx"
+#load "../../loaders/globalloader.fsx"
+#endif
+
+open Html
+
+
+let menu (ctx : SiteContents) (page: string) =
+ let shortcuts = ctx.GetValues ()
+ let all = ctx.GetValues()
+
+ let content = ctx.GetValues ()
+ let siteInfo = ctx.TryGetValue().Value
+ let rootUrl = siteInfo.root_url
+
+ let language =
+ content
+ |> Seq.tryFind (fun r -> r.title = page)
+ |> Option.bind (fun r -> r.language)
+
+ let group = content |> Seq.tryFind (fun n -> n.title = page) |> Option.map (fun n -> n.category)
+
+ let explenations =
+ content
+ |> Seq.filter (fun n -> n.category = Contentloader.Explanation && not n.hide_menu && n.language = language )
+ |> Seq.sortBy (fun n -> n.menu_order)
+
+ let tutorials =
+ content
+ |> Seq.filter (fun n -> n.category = Contentloader.Tutorial && not n.hide_menu && n.language = language )
+ |> Seq.sortBy (fun n -> n.menu_order)
+
+ let howtos =
+ content
+ |> Seq.filter (fun n -> n.category = Contentloader.HowTo && not n.hide_menu && n.language = language )
+ |> Seq.sortBy (fun n -> n.menu_order)
+
+ let hasTutorials = not (Seq.isEmpty tutorials)
+ let hasExplenations = not (Seq.isEmpty explenations)
+ let hasHowTos = not (Seq.isEmpty howtos)
+
+ let menuHeader =
+ [
+ if hasExplenations then
+ li [Id "menu-explanations"; if group = Some Contentloader.Explanation then Class "dd-item menu-group-link menu-group-link-active" else Class "dd-item menu-group-link"; ] [
+ a [] [!! "Explanation"]
+ ]
+ if hasTutorials then
+ li [Id "menu-tutorials"; if group = Some Contentloader.Tutorial then Class "dd-item menu-group-link menu-group-link-active" else Class "dd-item menu-group-link"; ] [
+ a [] [!! "Tutorials"]
+ ]
+ if hasHowTos then
+ li [Id "menu-howtos"; if group = Some Contentloader.HowTo then Class "dd-item menu-group-link menu-group-link-active" else Class "dd-item menu-group-link"; ] [
+ a [] [!! "How-To Guides"]
+ ]
+ li [ Id "menu-refs"; if group = None then Class "dd-item menu-group-link menu-group-link-active" else Class "dd-item menu-group-link";] [
+ a [] [!! "API References"]
+ ]
+ ]
+
+ let renderExpls =
+ ul [Id "submenu-explanations"; if group = Some Contentloader.Explanation then Class "submenu submenu-active" else Class "submenu"; ] [
+ for r in explenations ->
+ li [] [
+ a [Href (rootUrl + "/" + r.link); if r.title = page then Class "active-link padding" else Class "padding"] [
+ !! r.title
+ ]
+ ]
+ ]
+
+ let renderTuts =
+ ul [Id "submenu-tutorials"; if group = Some Contentloader.Tutorial then Class "submenu submenu-active" else Class "submenu"; ] [
+ for r in tutorials ->
+ li [] [
+ a [ Href (rootUrl + "/" + r.link); if r.title = page then Class "active-link padding" else Class "padding" ] [
+ !! r.title
+ ]
+ ]
+ ]
+
+ let renderHowTos =
+ ul [Id "submenu-howtos"; if group = Some Contentloader.HowTo then Class "submenu submenu-active" else Class "submenu"; ] [
+ for r in howtos ->
+ li [] [
+ a [Href (rootUrl + "/" + r.link); if r.title = page then Class "active-link padding" else Class "padding" ] [
+ !! r.title
+ ]
+ ]
+ ]
+
+ let renderRefs =
+ ul [Id "submenu-refs"; if group = None then Class "submenu submenu-active" else Class "submenu"; ] [
+ for r in all ->
+ li [] [
+ a [Href (rootUrl + "/reference/" + r.Label + "/index.html"); if r.Label = page then Class "active-link padding" else Class "padding" ] [
+ !! r.Label
+ ]
+ ]
+ ]
+
+ let renderLanguages =
+ section [Id "languages"] [
+ h3 [] [!! "Languages"]
+ ul [] [
+ li [] [
+ a [Href (rootUrl + "/index.html"); if language = None then Class "menu-group-link-active padding" else Class "padding" ] [
+ !! "English"
+ ]
+ ]
+ li [] [
+ a [Href (rootUrl + "/ja/index.html"); if language = Some "ja" then Class "menu-group-link-active padding" else Class "padding" ] [
+ !! "Japanese"
+ ]
+ ]
+ ]
+ ]
+
+ let renderShortucuts =
+ section [Id "shortcuts"] [
+ h3 [] [!! "Shortucts"]
+ ul [] [
+ for s in shortcuts do
+ yield
+ li [] [
+ a [Class "padding"; Href s.link ] [
+ i [Class s.icon] []
+ !! s.title
+ ]
+ ]
+ ]
+ ]
+
+ let renderFooter =
+ section [Id "footer"] [
+ !! """
"},onSelect:function(){}};for(var c in e)e.hasOwnProperty(c)&&(l[c]=e[c]);for(var a="object"==typeof l.selector?[l.selector]:document.querySelectorAll(l.selector),u=0;u0?i.sc.scrollTop=n+i.sc.suggestionHeight+s-i.sc.maxHeight:0>n&&(i.sc.scrollTop=n+s)}else i.sc.scrollTop=0},o(window,"resize",i.updateSC),document.body.appendChild(i.sc),n("autocomplete-suggestion","mouseleave",function(){var e=i.sc.querySelector(".autocomplete-suggestion.selected");e&&setTimeout(function(){e.className=e.className.replace("selected","")},20)},i.sc),n("autocomplete-suggestion","mouseover",function(){var e=i.sc.querySelector(".autocomplete-suggestion.selected");e&&(e.className=e.className.replace("selected","")),this.className+=" selected"},i.sc),n("autocomplete-suggestion","mousedown",function(e){if(t(this,"autocomplete-suggestion")){var o=this.getAttribute("data-val");i.value=o,l.onSelect(e,o,this),i.sc.style.display="none"}},i.sc),i.blurHandler=function(){try{var e=document.querySelector(".autocomplete-suggestions:hover")}catch(t){var e=0}e?i!==document.activeElement&&setTimeout(function(){i.focus()},20):(i.last_val=i.value,i.sc.style.display="none",setTimeout(function(){i.sc.style.display="none"},350))},o(i,"blur",i.blurHandler);var r=function(e){var t=i.value;if(i.cache[t]=e,e.length&&t.length>=l.minChars){for(var o="",s=0;st||t>40)&&13!=t&&27!=t){var o=i.value;if(o.length>=l.minChars){if(o!=i.last_val){if(i.last_val=o,clearTimeout(i.timer),l.cache){if(o in i.cache)return void r(i.cache[o]);for(var s=1;s https://github.com/noelboss/featherlight/issues/317
+!function(u){"use strict";if(void 0!==u)if(u.fn.jquery.match(/-ajax/))"console"in window&&window.console.info("Featherlight needs regular jQuery, not the slim version.");else{var r=[],i=function(t){return r=u.grep(r,function(e){return e!==t&&0','
','",'
'+n.loading+"
","
",""].join("")),o="."+n.namespace+"-close"+(n.otherClose?","+n.otherClose:"");return n.$instance=i.clone().addClass(n.variant),n.$instance.on(n.closeTrigger+"."+n.namespace,function(e){if(!e.isDefaultPrevented()){var t=u(e.target);("background"===n.closeOnClick&&t.is("."+n.namespace)||"anywhere"===n.closeOnClick||t.closest(o).length)&&(n.close(e),e.preventDefault())}}),this},getContent:function(){if(!1!==this.persist&&this.$content)return this.$content;var t=this,e=this.constructor.contentFilters,n=function(e){return t.$currentTarget&&t.$currentTarget.attr(e)},r=n(t.targetAttr),i=t.target||r||"",o=e[t.type];if(!o&&i in e&&(o=e[i],i=t.target&&r),i=i||n("href")||"",!o)for(var a in e)t[a]&&(o=e[a],i=t[a]);if(!o){var s=i;if(i=null,u.each(t.contentFilters,function(){return(o=e[this]).test&&(i=o.test(s)),!i&&o.regex&&s.match&&s.match(o.regex)&&(i=s),!i}),!i)return"console"in window&&window.console.error("Featherlight: no content filter found "+(s?' for "'+s+'"':" (no target specified)")),!1}return o.process.call(t,i)},setContent:function(e){return this.$instance.removeClass(this.namespace+"-loading"),this.$instance.toggleClass(this.namespace+"-iframe",e.is("iframe")),this.$instance.find("."+this.namespace+"-inner").not(e).slice(1).remove().end().replaceWith(u.contains(this.$instance[0],e[0])?"":e),this.$content=e.addClass(this.namespace+"-inner"),this},open:function(t){var n=this;if(n.$instance.hide().appendTo(n.root),!(t&&t.isDefaultPrevented()||!1===n.beforeOpen(t))){t&&t.preventDefault();var e=n.getContent();if(e)return r.push(n),s(!0),n.$instance.fadeIn(n.openSpeed),n.beforeContent(t),u.when(e).always(function(e){n.setContent(e),n.afterContent(t)}).then(n.$instance.promise()).done(function(){n.afterOpen(t)})}return n.$instance.detach(),u.Deferred().reject().promise()},close:function(e){var t=this,n=u.Deferred();return!1===t.beforeClose(e)?n.reject():(0===i(t).length&&s(!1),t.$instance.fadeOut(t.closeSpeed,function(){t.$instance.detach(),t.afterClose(e),n.resolve()})),n.promise()},resize:function(e,t){if(e&&t&&(this.$content.css("width","").css("height",""),this.$content.parent().width()');return n.onload=function(){r.naturalWidth=n.width,r.naturalHeight=n.height,t.resolve(r)},n.onerror=function(){t.reject(r)},n.src=e,t.promise()}},html:{regex:/^\s*<[\w!][^<]*>/,process:function(e){return u(e)}},ajax:{regex:/./,process:function(e){var n=u.Deferred(),r=u("").load(e,function(e,t){"error"!==t&&n.resolve(r.contents()),n.fail()});return n.promise()}},iframe:{process:function(e){var t=new u.Deferred,n=u(""),r=function(e,t){var n={},r=new RegExp("^"+t+"([A-Z])(.*)");for(var i in e){var o=i.match(r);o&&(n[(o[1]+o[2].replace(/([A-Z])/g,"-$1")).toLowerCase()]=e[i])}return n}(this,"iframe"),i=function(e,t){var n={};for(var r in e)r in t&&(n[r]=e[r],delete e[r]);return n}(r,o);return n.hide().attr("src",e).attr(i).css(r).on("load",function(){t.resolve(n.show())}).appendTo(this.$instance.find("."+this.namespace+"-content")),t.promise()}},text:{process:function(e){return u("
",{text:e})}}},functionAttributes:["beforeOpen","afterOpen","beforeContent","afterContent","beforeClose","afterClose"],readElementConfig:function(e,t){var r=this,i=new RegExp("^data-"+t+"-(.*)"),o={};return e&&e.attributes&&u.each(e.attributes,function(){var e=this.name.match(i);if(e){var t=this.value,n=u.camelCase(e[1]);if(0<=u.inArray(n,r.functionAttributes))t=new Function(t);else try{t=JSON.parse(t)}catch(e){}o[n]=t}}),o},extend:function(e,t){var n=function(){this.constructor=e};return n.prototype=this.prototype,e.prototype=new n,e.__super__=this.prototype,u.extend(e,this,t),e.defaults=e.prototype,e},attach:function(i,o,a){var s=this;"object"!=typeof o||o instanceof u!=!1||a||(a=o,o=void 0);var c,e=(a=u.extend({},a)).namespace||s.defaults.namespace,l=u.extend({},s.defaults,s.readElementConfig(i[0],e),a),t=function(e){var t=u(e.currentTarget),n=u.extend({$source:i,$currentTarget:t},s.readElementConfig(i[0],l.namespace),s.readElementConfig(e.currentTarget,l.namespace),a),r=c||t.data("featherlight-persisted")||new s(o,n);"shared"===r.persist?c=r:!1!==r.persist&&t.data("featherlight-persisted",r),n.$currentTarget.blur&&n.$currentTarget.blur(),r.open(e)};return i.on(l.openTrigger+"."+l.namespace,l.filter,t),{filter:l.filter,handler:t}},current:function(){var e=this.opened();return e[e.length-1]||null},opened:function(){var t=this;return i(),u.grep(r,function(e){return e instanceof t})},close:function(e){var t=this.current();if(t)return t.close(e)},_onReady:function(){var r=this;if(r.autoBind){var i=u(r.autoBind);i.each(function(){r.attach(u(this))}),u(document).on("click",r.autoBind,function(e){if(!e.isDefaultPrevented()){var t=u(e.currentTarget);if(i.length!==(i=i.add(t)).length){var n=r.attach(t);(!n.filter||0";
+ }
+ }
+});
+
+// Change styles, depending on parameters set to the image
+images.each(function(index){
+ var image = $(this)
+ var o = getUrlParameter(image[0].src);
+ if (typeof o !== "undefined") {
+ var h = o["height"];
+ var w = o["width"];
+ var c = o["classes"];
+ image.css("width", function() {
+ if (typeof w !== "undefined") {
+ return w;
+ } else {
+ return "auto";
+ }
+ });
+ image.css("height", function() {
+ if (typeof h !== "undefined") {
+ return h;
+ } else {
+ return "auto";
+ }
+ });
+ if (typeof c !== "undefined") {
+ var classes = c.split(',');
+ for (i = 0; i < classes.length; i++) {
+ image.addClass(classes[i]);
+ }
+ }
+ }
+});
+
+// Stick the top to the top of the screen when scrolling
+$(document).ready(function(){
+ $("#top-bar").sticky({topSpacing:0, zIndex: 1000});
+});
+
+
+// jQuery(document).ready(function() {
+// // Add link button for every
+// var text, clip = new ClipboardJS('.anchor');
+// $("h1~h2,h1~h3,h1~h4,h1~h5,h1~h6").append(function(index, html){
+// var element = $(this);
+// var url = encodeURI(document.location.origin + document.location.pathname);
+// var link = url + "#"+element[0].id;
+// return " " +
+// "" +
+// ""
+// ;
+// });
+
+// $(".anchor").on('mouseleave', function(e) {
+// $(this).attr('aria-label', null).removeClass('tooltipped tooltipped-s tooltipped-w');
+// });
+
+// clip.on('success', function(e) {
+// e.clearSelection();
+// $(e.trigger).attr('aria-label', 'Link copied to clipboard!').addClass('tooltipped tooltipped-s');
+// });
+// $('code.language-mermaid').each(function(index, element) {
+// var content = $(element).html().replace(/&/g, '&');
+// $(element).parent().replaceWith('