-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathSharedTypes.ml
645 lines (555 loc) · 17.5 KB
/
SharedTypes.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
let str s = if s = "" then "\"\"" else s
let list l = "[" ^ (l |> List.map str |> String.concat ", ") ^ "]"
let ident l = l |> List.map str |> String.concat "."
type path = string list
let pathToString (path : path) = path |> String.concat "."
module ModulePath = struct
type t =
| File of Uri.t * string
| NotVisible
| IncludedModule of Path.t * t
| ExportedModule of {name: string; modulePath: t; isType: bool}
let toPath modulePath tipName : path =
let rec loop modulePath current =
match modulePath with
| File _ -> current
| IncludedModule (_, inner) -> loop inner current
| ExportedModule {name; modulePath = inner} -> loop inner (name :: current)
| NotVisible -> current
in
loop modulePath [tipName]
end
type field = {stamp: int; fname: string Location.loc; typ: Types.type_expr}
module Constructor = struct
type t = {
stamp: int;
cname: string Location.loc;
args: (Types.type_expr * Location.t) list;
res: Types.type_expr option;
typeDecl: string * Types.type_declaration;
}
end
module Type = struct
type kind =
| Abstract of (Path.t * Types.type_expr list) option
| Open
| Tuple of Types.type_expr list
| Record of field list
| Variant of Constructor.t list
type t = {kind: kind; decl: Types.type_declaration}
end
module Exported = struct
type namedStampMap = (string, int) Hashtbl.t
type t = {
types_: namedStampMap;
values_: namedStampMap;
modules_: namedStampMap;
}
type kind = Type | Value | Module
let init () =
{
types_ = Hashtbl.create 10;
values_ = Hashtbl.create 10;
modules_ = Hashtbl.create 10;
}
let add t kind name x =
let tbl =
match kind with
| Type -> t.types_
| Value -> t.values_
| Module -> t.modules_
in
if Hashtbl.mem tbl name then false
else
let () = Hashtbl.add tbl name x in
true
let find t kind name =
let tbl =
match kind with
| Type -> t.types_
| Value -> t.values_
| Module -> t.modules_
in
Hashtbl.find_opt tbl name
let iter t kind f =
let tbl =
match kind with
| Type -> t.types_
| Value -> t.values_
| Module -> t.modules_
in
Hashtbl.iter f tbl
end
module Module = struct
type kind =
| Value of Types.type_expr
| Type of Type.t * Types.rec_status
| Module of t
and item = {kind: kind; name: string}
and structure = {
name: string;
docstring: string list;
exported: Exported.t;
items: item list;
}
and t = Ident of Path.t | Structure of structure | Constraint of t * t
end
module Declared = struct
type 'item t = {
name: string Location.loc;
extentLoc: Location.t;
stamp: int;
modulePath: ModulePath.t;
isExported: bool;
deprecated: string option;
docstring: string list;
item: 'item;
}
end
module Stamps : sig
type t
val addConstructor : t -> int -> Constructor.t Declared.t -> unit
val addModule : t -> int -> Module.t Declared.t -> unit
val addType : t -> int -> Type.t Declared.t -> unit
val addValue : t -> int -> Types.type_expr Declared.t -> unit
val findModule : t -> int -> Module.t Declared.t option
val findType : t -> int -> Type.t Declared.t option
val findValue : t -> int -> Types.type_expr Declared.t option
val init : unit -> t
val iterConstructors : (int -> Constructor.t Declared.t -> unit) -> t -> unit
val iterModules : (int -> Module.t Declared.t -> unit) -> t -> unit
val iterTypes : (int -> Type.t Declared.t -> unit) -> t -> unit
val iterValues : (int -> Types.type_expr Declared.t -> unit) -> t -> unit
end = struct
type 't stampMap = (int, 't Declared.t) Hashtbl.t
type kind =
| KType of Type.t Declared.t
| KValue of Types.type_expr Declared.t
| KModule of Module.t Declared.t
| KConstructor of Constructor.t Declared.t
type t = (int, kind) Hashtbl.t
let init () = Hashtbl.create 10
let addConstructor (stamps : t) stamp declared =
Hashtbl.add stamps stamp (KConstructor declared)
let addModule stamps stamp declared =
Hashtbl.add stamps stamp (KModule declared)
let addType stamps stamp declared = Hashtbl.add stamps stamp (KType declared)
let addValue stamps stamp declared =
Hashtbl.add stamps stamp (KValue declared)
let findModule stamps stamp =
match Hashtbl.find_opt stamps stamp with
| Some (KModule declared) -> Some declared
| _ -> None
let findType stamps stamp =
match Hashtbl.find_opt stamps stamp with
| Some (KType declared) -> Some declared
| _ -> None
let findValue stamps stamp =
match Hashtbl.find_opt stamps stamp with
| Some (KValue declared) -> Some declared
| _ -> None
let iterModules f stamps =
Hashtbl.iter
(fun stamp d ->
match d with
| KModule d -> f stamp d
| _ -> ())
stamps
let iterTypes f stamps =
Hashtbl.iter
(fun stamp d ->
match d with
| KType d -> f stamp d
| _ -> ())
stamps
let iterValues f stamps =
Hashtbl.iter
(fun stamp d ->
match d with
| KValue d -> f stamp d
| _ -> ())
stamps
let iterConstructors f stamps =
Hashtbl.iter
(fun stamp d ->
match d with
| KConstructor d -> f stamp d
| _ -> ())
stamps
end
module File = struct
type t = {
uri: Uri.t;
stamps: Stamps.t;
moduleName: string;
structure: Module.structure;
}
let create moduleName uri =
{
uri;
stamps = Stamps.init ();
moduleName;
structure =
{
name = moduleName;
docstring = [];
exported = Exported.init ();
items = [];
};
}
end
module QueryEnv : sig
type t = private {
file: File.t;
exported: Exported.t;
pathRev: path;
parent: t option;
}
val fromFile : File.t -> t
val enterStructure : t -> Module.structure -> t
(* Express a path starting from the module represented by the env.
E.g. the env is at A.B.C and the path is D.
The result is A.B.C.D if D is inside C.
Or A.B.D or A.D or D if it's in one of its parents. *)
val pathFromEnv : t -> path -> path
end = struct
type t = {file: File.t; exported: Exported.t; pathRev: path; parent: t option}
let fromFile (file : File.t) =
{file; exported = file.structure.exported; pathRev = []; parent = None}
(* Prune a path and find a parent environment that contains the module name *)
let rec prunePath pathRev env name =
if Exported.find env.exported Module name <> None then pathRev
else
match (pathRev, env.parent) with
| _ :: rest, Some env -> prunePath rest env name
| _ -> []
let pathFromEnv env path =
match path with
| [] -> env.pathRev |> List.rev
| name :: _ ->
let prunedPathRev = prunePath env.pathRev env name in
List.rev_append prunedPathRev path
let enterStructure env (structure : Module.structure) =
let name = structure.name in
let pathRev = name :: prunePath env.pathRev env name in
{env with exported = structure.exported; pathRev; parent = Some env}
end
module Completion = struct
type kind =
| Module of Module.t
| Value of Types.type_expr
| ObjLabel of Types.type_expr
| Label of string
| Type of Type.t
| Constructor of Constructor.t * string
| Field of field * string
| FileModule of string
type t = {
name: string;
env: QueryEnv.t;
deprecated: string option;
docstring: string list;
kind: kind;
}
let create ~name ~kind ~env =
{name; env; deprecated = None; docstring = []; kind}
(* https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion *)
(* https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#completionItemKind *)
let kindToInt kind =
match kind with
| Module _ -> 9
| FileModule _ -> 9
| Constructor (_, _) -> 4
| ObjLabel _ -> 4
| Label _ -> 4
| Field (_, _) -> 5
| Type _ -> 22
| Value _ -> 12
end
module Env = struct
type t = {stamps: Stamps.t; modulePath: ModulePath.t}
let addExportedModule ~name ~isType env =
{
env with
modulePath = ExportedModule {name; modulePath = env.modulePath; isType};
}
let addModule ~name env = env |> addExportedModule ~name ~isType:false
let addModuleType ~name env = env |> addExportedModule ~name ~isType:true
end
type filePath = string
type paths =
| Impl of {cmt: filePath; res: filePath}
| Namespace of {cmt: filePath}
| IntfAndImpl of {
cmti: filePath;
resi: filePath;
cmt: filePath;
res: filePath;
}
let showPaths paths =
match paths with
| Impl {cmt; res} ->
Printf.sprintf "Impl cmt:%s res:%s" (Utils.dumpPath cmt)
(Utils.dumpPath res)
| Namespace {cmt} -> Printf.sprintf "Namespace cmt:%s" (Utils.dumpPath cmt)
| IntfAndImpl {cmti; resi; cmt; res} ->
Printf.sprintf "IntfAndImpl cmti:%s resi:%s cmt:%s res:%s"
(Utils.dumpPath cmti) (Utils.dumpPath resi) (Utils.dumpPath cmt)
(Utils.dumpPath res)
let getSrc p =
match p with
| Impl {res} -> [res]
| Namespace _ -> []
| IntfAndImpl {resi; res} -> [resi; res]
let getUri p =
match p with
| Impl {res} -> Uri.fromPath res
| Namespace {cmt} -> Uri.fromPath cmt
| IntfAndImpl {resi} -> Uri.fromPath resi
let getUris p =
match p with
| Impl {res} -> [Uri.fromPath res]
| Namespace {cmt} -> [Uri.fromPath cmt]
| IntfAndImpl {res; resi} -> [Uri.fromPath res; Uri.fromPath resi]
let getCmtPath ~uri p =
match p with
| Impl {cmt} -> cmt
| Namespace {cmt} -> cmt
| IntfAndImpl {cmti; cmt} ->
let interface = Utils.endsWith (Uri.toPath uri) "i" in
if interface then cmti else cmt
module Tip = struct
type t = Value | Type | Field of string | Constructor of string | Module
let toString tip =
match tip with
| Value -> "Value"
| Type -> "Type"
| Field f -> "Field(" ^ f ^ ")"
| Constructor a -> "Constructor(" ^ a ^ ")"
| Module -> "Module"
end
let rec pathIdentToString (p : Path.t) =
match p with
| Pident {name} -> name
| Pdot (nextPath, id, _) ->
Printf.sprintf "%s.%s" (pathIdentToString nextPath) id
| Papply _ -> ""
type locKind =
| LocalReference of int * Tip.t
| GlobalReference of string * string list * Tip.t
| NotFound
| Definition of int * Tip.t
type locType =
| Typed of string * Types.type_expr * locKind
| Constant of Asttypes.constant
| LModule of locKind
| TopLevelModule of string
| TypeDefinition of string * Types.type_declaration * int
type locItem = {loc: Location.t; locType: locType}
module LocationSet = Set.Make (struct
include Location
let compare loc1 loc2 = compare loc2 loc1
(* polymorphic compare should be OK *)
end)
type extra = {
internalReferences: (int, Location.t list) Hashtbl.t;
externalReferences:
(string, (string list * Tip.t * Location.t) list) Hashtbl.t;
fileReferences: (string, LocationSet.t) Hashtbl.t;
mutable locItems: locItem list;
}
type file = string
module FileSet = Set.Make (String)
type builtInCompletionModules = {
arrayModulePath: string list;
optionModulePath: string list;
stringModulePath: string list;
intModulePath: string list;
floatModulePath: string list;
promiseModulePath: string list;
listModulePath: string list;
resultModulePath: string list;
}
type package = {
rootPath: filePath;
projectFiles: FileSet.t;
dependenciesFiles: FileSet.t;
pathsForModule: (file, paths) Hashtbl.t;
namespace: string option;
builtInCompletionModules: builtInCompletionModules;
opens: path list;
}
type full = {extra: extra; file: File.t; package: package}
let initExtra () =
{
internalReferences = Hashtbl.create 10;
externalReferences = Hashtbl.create 10;
fileReferences = Hashtbl.create 10;
locItems = [];
}
type state = {
packagesByRoot: (string, package) Hashtbl.t;
rootForUri: (Uri.t, string) Hashtbl.t;
cmtCache: (filePath, File.t) Hashtbl.t;
}
(* There's only one state, so it can as well be global *)
let state =
{
packagesByRoot = Hashtbl.create 1;
rootForUri = Hashtbl.create 30;
cmtCache = Hashtbl.create 30;
}
let locKindToString = function
| LocalReference (_, tip) -> "(LocalReference " ^ Tip.toString tip ^ ")"
| GlobalReference _ -> "GlobalReference"
| NotFound -> "NotFound"
| Definition (_, tip) -> "(Definition " ^ Tip.toString tip ^ ")"
let locTypeToString = function
| Typed (name, e, locKind) ->
"Typed " ^ name ^ " " ^ Shared.typeToString e ^ " "
^ locKindToString locKind
| Constant _ -> "Constant"
| LModule locKind -> "LModule " ^ locKindToString locKind
| TopLevelModule _ -> "TopLevelModule"
| TypeDefinition _ -> "TypeDefinition"
let locItemToString {loc = {Location.loc_start; loc_end}; locType} =
let pos1 = Utils.cmtPosToPosition loc_start in
let pos2 = Utils.cmtPosToPosition loc_end in
Printf.sprintf "%d:%d-%d:%d %s" pos1.line pos1.character pos2.line
pos2.character (locTypeToString locType)
(* needed for debugging *)
let _ = locItemToString
module Completable = struct
(* Completion context *)
type completionContext = Type | Value | Module | Field
type argumentLabel =
| Unlabelled of {argumentPosition: int}
| Labelled of string
type contextPath =
| CPString
| CPArray
| CPInt
| CPFloat
| CPApply of contextPath * Asttypes.arg_label list
| CPId of string list * completionContext
| CPField of contextPath * string
| CPObj of contextPath * string
| CPPipe of {
contextPath: contextPath;
id: string;
lhsLoc: Location.t;
(** The loc item for the left hand side of the pipe. *)
}
type t =
| Cdecorator of string (** e.g. @module *)
| CnamedArg of contextPath * string * string list
(** e.g. (..., "label", ["l1", "l2"]) for ...(...~l1...~l2...~label...) *)
| Cnone (** e.g. don't complete inside strings *)
| Cpath of contextPath
| Cjsx of string list * string * string list
(** E.g. (["M", "Comp"], "id", ["id1", "id2"]) for <M.Comp id1=... id2=... ... id *)
| Cargument of {
contextPath: contextPath;
argumentLabel: argumentLabel;
prefix: string;
}
let toString =
let completionContextToString = function
| Value -> "Value"
| Type -> "Type"
| Module -> "Module"
| Field -> "Field"
in
let rec contextPathToString = function
| CPString -> "string"
| CPInt -> "int"
| CPFloat -> "float"
| CPApply (cp, labels) ->
contextPathToString cp ^ "("
^ (labels
|> List.map (function
| Asttypes.Nolabel -> "Nolabel"
| Labelled s -> "~" ^ s
| Optional s -> "?" ^ s)
|> String.concat ", ")
^ ")"
| CPArray -> "array"
| CPId (sl, completionContext) ->
completionContextToString completionContext ^ list sl
| CPField (cp, s) -> contextPathToString cp ^ "." ^ str s
| CPObj (cp, s) -> contextPathToString cp ^ "[\"" ^ s ^ "\"]"
| CPPipe {contextPath; id} -> contextPathToString contextPath ^ "->" ^ id
in
function
| Cpath cp -> "Cpath " ^ contextPathToString cp
| Cdecorator s -> "Cdecorator(" ^ str s ^ ")"
| CnamedArg (cp, s, sl2) ->
"CnamedArg("
^ (cp |> contextPathToString)
^ ", " ^ str s ^ ", " ^ (sl2 |> list) ^ ")"
| Cnone -> "Cnone"
| Cjsx (sl1, s, sl2) ->
"Cjsx(" ^ (sl1 |> list) ^ ", " ^ str s ^ ", " ^ (sl2 |> list) ^ ")"
| Cargument {contextPath; argumentLabel; prefix} ->
contextPathToString contextPath
^ "("
^ (match argumentLabel with
| Unlabelled {argumentPosition} -> "$" ^ string_of_int argumentPosition
| Labelled name -> "~" ^ name)
^ (if prefix <> "" then "=" ^ prefix else "")
^ ")"
end
module CursorPosition = struct
type t = NoCursor | HasCursor | EmptyLoc
let classifyLoc loc ~pos =
if loc |> Loc.hasPos ~pos then HasCursor
else if loc |> Loc.end_ = (Location.none |> Loc.end_) then EmptyLoc
else NoCursor
let classifyLocationLoc (loc : 'a Location.loc) ~pos =
if Loc.start loc.Location.loc <= pos && pos <= Loc.end_ loc.loc then
HasCursor
else if loc.loc |> Loc.end_ = (Location.none |> Loc.end_) then EmptyLoc
else NoCursor
let classifyPositions pos ~posStart ~posEnd =
if posStart <= pos && pos <= posEnd then HasCursor
else if posEnd = (Location.none |> Loc.end_) then EmptyLoc
else NoCursor
end
type labelled = {
name: string;
opt: bool;
posStart: int * int;
posEnd: int * int;
}
type label = labelled option
type arg = {label: label; exp: Parsetree.expression}
let extractExpApplyArgs ~args =
let rec processArgs ~acc args =
match args with
| (((Asttypes.Labelled s | Optional s) as label), (e : Parsetree.expression))
:: rest -> (
let namedArgLoc =
e.pexp_attributes
|> List.find_opt (fun ({Asttypes.txt}, _) -> txt = "ns.namedArgLoc")
in
match namedArgLoc with
| Some ({loc}, _) ->
let labelled =
{
name = s;
opt =
(match label with
| Optional _ -> true
| _ -> false);
posStart = Loc.start loc;
posEnd = Loc.end_ loc;
}
in
processArgs ~acc:({label = Some labelled; exp = e} :: acc) rest
| None -> processArgs ~acc rest)
| (Asttypes.Nolabel, (e : Parsetree.expression)) :: rest ->
if e.pexp_loc.loc_ghost then processArgs ~acc rest
else processArgs ~acc:({label = None; exp = e} :: acc) rest
| [] -> List.rev acc
in
args |> processArgs ~acc:[]