-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathState.fs
More file actions
392 lines (326 loc) · 15 KB
/
Copy pathState.fs
File metadata and controls
392 lines (326 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
module Fable.Transforms.State
open Fable
open Fable.AST
open System.Collections.Concurrent
open System.Collections.Generic
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.Symbols
open System
type PluginRef =
{
DllPath: string
TypeFullName: string
}
type Assemblies(getPlugin, fsharpAssemblies: FSharpAssembly list, addLog: Severity -> string -> unit) =
let assemblies = Dictionary()
let coreAssemblies = Dictionary()
let entities = ConcurrentDictionary<string, Fable.Entity>()
let plugins =
let plugins = Dictionary<Fable.EntityRef, System.Type>()
let mutable hasSkippedAssembly = false
for asm in fsharpAssemblies do
match asm.FileName with
| Some path ->
let path = Path.normalizePath path
let asmName = path.Substring(path.LastIndexOf('/') + 1)
let asmName = asmName.Substring(0, asmName.Length - 4) // Remove .dll extension
if Compiler.CoreAssemblyNames.Contains(asmName) then
coreAssemblies.Add(asmName, asm)
else
let scanForPlugins =
if Metadata.isSystemPackage asmName then
false
else
try
asm.Contents.Attributes
|> Seq.exists (fun attr ->
attr.AttributeType.TryFullName = Some "Fable.ScanForPluginsAttribute"
)
with error ->
// To help identify problem, log information about the exception
// but keep the process going to mimic previous Fable behavior
// and because these exception seems harmless
let errorMessage =
$"Could not scan %s{path} for Fable plugins, skipping this assembly. Original error: %s{error.Message}"
addLog Severity.Info errorMessage
hasSkippedAssembly <- true
false
if scanForPlugins then
for e in asm.Contents.Entities do
if e.IsAttributeType && FSharp2Fable.Util.inherits e "Fable.PluginAttribute" then
try
let plugin =
getPlugin
{
DllPath = path
TypeFullName = e.FullName
}
plugins.Add(FSharp2Fable.FsEnt.Ref e, plugin)
with ex ->
let errorMessage =
[
$"Error while loading plugin: {e.FullName}"
""
"This error often happens if you are trying to use a plugin that is not compatible with the current version of Fable."
"If you see this error please open an issue at https://github.com/fable-compiler/Fable/"
"so we can check if we can improve the plugin detection mechanism."
]
|> String.concat Environment.NewLine
addLog Severity.Error errorMessage
raise ex
assemblies.Add(path, asm)
| None -> ()
// Add a blank line to separate the error message from the rest of the output
if hasSkippedAssembly then
addLog Severity.Info "" // or Environment.NewLine
({ MemberDeclarationPlugins = Map.empty }, plugins)
||> Seq.fold (fun acc kv ->
if kv.Value.IsSubclassOf(typeof<MemberDeclarationPluginAttribute>) then
{ MemberDeclarationPlugins = Map.add kv.Key kv.Value acc.MemberDeclarationPlugins }
else
acc
)
let tryFindEntityByPath (entityFullName: string) (asm: FSharpAssembly) =
let key = asm.SimpleName + "|" + entityFullName
match entities.TryGetValue(key) with
| true, v -> Some v
| false, _ ->
let entPath = List.ofArray (entityFullName.Split('.'))
asm.Contents.FindEntityByPath(entPath)
|> Option.map (fun e ->
let fableEnt = FSharp2Fable.FsEnt e :> Fable.Entity
entities[key] <- fableEnt
fableEnt
)
member _.TryGetEntityByAssemblyPath(asmPath, entityFullName) =
assemblies
|> Dictionary.tryFind asmPath
|> Option.bind (tryFindEntityByPath entityFullName)
member _.TryGetEntityByCoreAssemblyName(asmName, entityFullName) =
coreAssemblies
|> Dictionary.tryFind asmName
|> Option.bind (tryFindEntityByPath entityFullName)
member _.Plugins = plugins
type ImplFile =
{
Declarations: FSharpImplementationFileDeclaration list
RootModule: string
RootComment: FSharpXmlDoc option
Entities: IReadOnlyDictionary<string, Fable.Entity>
InlineExprs: (string * InlineExprLazy) list
}
static member From(file: FSharpImplementationFileContents) =
let rec loop (entities: IDictionary<_, _>) (ents: FSharpEntity seq) =
for e in ents do
let fullName = FSharp2Fable.FsEnt.FullName e
if not e.IsFSharpAbbreviation || not (entities.ContainsKey(fullName)) then
entities[fullName] <- FSharp2Fable.FsEnt e :> Fable.Entity
loop entities e.NestedEntities
// add all entities to the entity cache
let entities = Dictionary()
let declarations =
try
file.Declarations // this may throw
with _ex ->
[]
FSharp2Fable.Compiler.getRootFSharpEntities declarations |> loop entities
let rootModule, rootComment = FSharp2Fable.Compiler.getRootModule declarations
{
Declarations = declarations
Entities = entities
RootModule = rootModule
RootComment = rootComment
InlineExprs = FSharp2Fable.Compiler.getInlineExprs file.FileName declarations
}
type PrecompiledInfo =
abstract DllPath: string
abstract TryGetRootModule: normalizedFullPath: string -> string option
abstract TryGetInlineExpr: memberUniqueName: string -> InlineExpr option
type Project
private
(
projectFile: string,
projectOptions: FSharpProjectOptions,
implFiles: Map<string, ImplFile>,
assemblies: Assemblies,
?precompiledInfo: PrecompiledInfo
)
=
let inlineExprsDic =
implFiles |> Map.values |> Seq.collect (fun f -> f.InlineExprs) |> dict
let precompiledInfo =
precompiledInfo
|> Option.defaultWith (fun () ->
{ new PrecompiledInfo with
member _.DllPath = ""
member _.TryGetRootModule(_) = None
member _.TryGetInlineExpr(_) = None
}
)
static member From
(
projectFile: string,
projectOptions: FSharpProjectOptions,
fsharpFiles: FSharpImplementationFileContents list,
fsharpAssemblies: FSharpAssembly list,
addLog: Severity -> string -> unit,
?getPlugin: PluginRef -> System.Type,
?precompiledInfo: PrecompiledInfo
)
=
let checknulls = projectOptions.OtherOptions |> Array.exists ((=) "--checknulls+")
Compiler.SetCheckNullsUnsafe checknulls // set it one time only as early as possible
let getPlugin = defaultArg getPlugin (fun _ -> failwith "Plugins are not supported")
let assemblies = Assemblies(getPlugin, fsharpAssemblies, addLog)
let implFilesMap =
fsharpFiles
|> List.toArray
|> Array.Parallel.map (fun file ->
let key = Path.normalizePathAndEnsureFsExtension file.FileName
key, ImplFile.From(file)
)
|> Map
Project(projectFile, projectOptions, implFilesMap, assemblies, ?precompiledInfo = precompiledInfo)
member this.Update(files: FSharpImplementationFileContents list) =
let implFiles =
(this.ImplementationFiles, files)
||> List.fold (fun implFiles file ->
let key = Path.normalizePathAndEnsureFsExtension file.FileName
let file = ImplFile.From(file)
Map.add key file implFiles
)
Project(this.ProjectFile, this.ProjectOptions, implFiles, this.Assemblies, this.PrecompiledInfo)
member _.TryGetInlineExpr(com: Compiler, memberUniqueName: string) =
inlineExprsDic
|> Dictionary.tryFind memberUniqueName
|> Option.map (fun e -> e.Calculate(com))
member _.GetFileInlineExprs(com: Compiler) : (string * InlineExpr)[] =
match Map.tryFind com.CurrentFile implFiles with
| None -> [||]
| Some implFile ->
implFile.InlineExprs
|> List.mapToArray (fun (uniqueName, expr) -> uniqueName, expr.Calculate(com))
member _.ProjectFile = projectFile
member _.ProjectOptions = projectOptions
member _.ImplementationFiles = implFiles
member _.Assemblies = assemblies
member _.PrecompiledInfo = precompiledInfo
type LogEntry =
{
Message: string
Tag: string
Severity: Severity
Range: SourceLocation option
FileName: string option
}
static member Make(severity, msg, ?fileName, ?range, ?tag) =
{
Message = msg
Tag = defaultArg tag "FABLE"
Severity = severity
Range = range
FileName = fileName
}
static member MakeError(msg, ?fileName, ?range, ?tag) =
LogEntry.Make(Severity.Error, msg, ?fileName = fileName, ?range = range, ?tag = tag)
/// Type with utilities for compiling F# files to JS.
/// Not thread-safe, an instance must be created per file
type CompilerImpl
(
currentFile,
project: Project,
options,
fableLibDir: string,
?outType: OutputType,
?outDir: string,
?watchDependencies: HashSet<string>,
?logs: ResizeArray<LogEntry>,
?isPrecompilingInlineFunction: bool
)
=
let mutable counter = -1
let outType = defaultArg outType OutputType.Exe
let logs = Option.defaultWith ResizeArray logs
let fableLibraryDir = fableLibDir.TrimEnd('/')
member _.Logs = logs.ToArray()
member _.WatchDependencies =
match watchDependencies with
| Some w -> Array.ofSeq w
| None -> [||]
interface Compiler with
member _.Options = options
member _.Plugins = project.Assemblies.Plugins
member _.LibraryDir = fableLibraryDir
member _.CurrentFile = currentFile
member _.OutputDir = outDir
member _.OutputType = outType
member _.ProjectFile = project.ProjectFile
member _.ProjectOptions = project.ProjectOptions
member _.SourceFiles = project.ProjectOptions.SourceFiles
member _.IncrementCounter() =
counter <- counter + 1
counter
member _.IsPrecompilingInlineFunction = defaultArg isPrecompilingInlineFunction false
member _.WillPrecompileInlineFunction(file) =
let fableLibraryDir =
if Path.isRelativePath fableLibraryDir then
Path.Combine(Path.GetDirectoryName(currentFile), fableLibraryDir)
else
fableLibraryDir
|> Path.getRelativeFileOrDirPath false file true
CompilerImpl(
file,
project,
options,
fableLibraryDir,
outType,
?outDir = outDir,
?watchDependencies = watchDependencies,
logs = logs,
isPrecompilingInlineFunction = true
)
member _.GetImplementationFile(fileName) =
let fileName = Path.normalizePathAndEnsureFsExtension fileName
match Map.tryFind fileName project.ImplementationFiles with
| Some file -> file.Declarations
| None -> failwith ("Cannot find implementation file " + fileName)
member this.GetRootModule(fileName) =
let fileName = Path.normalizePathAndEnsureFsExtension fileName
match Dictionary.tryFind fileName project.ImplementationFiles with
| Some file -> file.RootModule, file.RootComment
| None ->
match project.PrecompiledInfo.TryGetRootModule(fileName) with
| Some r -> r, None
| None ->
let msg =
$"Cannot find root module for {fileName}. If this belongs to a package, make sure it includes the source files."
(this :> Compiler).AddLog(msg, Severity.Warning, fileName = currentFile)
"", None // failwith msg
member _.TryGetEntity(entRef: Fable.EntityRef) =
match entRef.Path with
| Fable.CoreAssemblyName name -> project.Assemblies.TryGetEntityByCoreAssemblyName(name, entRef.FullName)
| Fable.AssemblyPath path
| Fable.PrecompiledLib(_, path) -> project.Assemblies.TryGetEntityByAssemblyPath(path, entRef.FullName)
| Fable.SourcePath fileName ->
// let fileName = Path.normalizePathAndEnsureFsExtension fileName
project.ImplementationFiles
|> Dictionary.tryFind fileName
|> Option.bind (fun file -> ReadOnlyDictionary.tryFind entRef.FullName file.Entities)
|> Option.orElseWith (fun () ->
// Check also the precompiled dll because this may come from a precompiled inline expr
project.Assemblies.TryGetEntityByAssemblyPath(project.PrecompiledInfo.DllPath, entRef.FullName)
)
member this.GetInlineExpr(memberUniqueName) =
match project.TryGetInlineExpr(this, memberUniqueName) with
| Some e -> e
| None ->
match project.PrecompiledInfo.TryGetInlineExpr(memberUniqueName) with
| Some e -> e
| None -> failwith ("Cannot find inline member: " + memberUniqueName)
member _.AddWatchDependency(file) =
match watchDependencies with
| Some watchDependencies when file <> currentFile -> watchDependencies.Add(file) |> ignore
| _ -> ()
member _.AddLog(msg, severity, ?range, ?fileName: string, ?tag: string) =
LogEntry.Make(severity, msg, ?range = range, ?fileName = fileName, ?tag = tag)
|> logs.Add