-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathXform.ml
More file actions
474 lines (449 loc) · 16.8 KB
/
Xform.ml
File metadata and controls
474 lines (449 loc) · 16.8 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
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
(** Code transformations using the parser/printer and ast operations *)
let isBracedExpr = Res_parsetree_viewer.isBracedExpr
let mkPosition (pos : Pos.t) =
let line, character = pos in
{Protocol.line; character}
let rangeOfLoc (loc : Location.t) =
let start = loc |> Loc.start |> mkPosition in
let end_ = loc |> Loc.end_ |> mkPosition in
{Protocol.start; end_}
module IfThenElse = struct
(* Convert if-then-else to switch *)
let rec listToPat ~itemToPat = function
| [] -> Some []
| x :: xList -> (
match (itemToPat x, listToPat ~itemToPat xList) with
| Some p, Some pList -> Some (p :: pList)
| _ -> None)
let rec expToPat (exp : Parsetree.expression) =
let mkPat ppat_desc =
Ast_helper.Pat.mk ~loc:exp.pexp_loc ~attrs:exp.pexp_attributes ppat_desc
in
match exp.pexp_desc with
| Pexp_construct (lid, None) -> Some (mkPat (Ppat_construct (lid, None)))
| Pexp_construct (lid, Some e1) -> (
match expToPat e1 with
| None -> None
| Some p1 -> Some (mkPat (Ppat_construct (lid, Some p1))))
| Pexp_variant (label, None) -> Some (mkPat (Ppat_variant (label, None)))
| Pexp_variant (label, Some e1) -> (
match expToPat e1 with
| None -> None
| Some p1 -> Some (mkPat (Ppat_variant (label, Some p1))))
| Pexp_constant c -> Some (mkPat (Ppat_constant c))
| Pexp_tuple eList -> (
match listToPat ~itemToPat:expToPat eList with
| None -> None
| Some patList -> Some (mkPat (Ppat_tuple patList)))
| Pexp_record (items, None) -> (
let itemToPat (x, e) =
match expToPat e with
| None -> None
| Some p -> Some (x, p)
in
match listToPat ~itemToPat items with
| None -> None
| Some patItems -> Some (mkPat (Ppat_record (patItems, Closed))))
| Pexp_record (_, Some _) -> None
| _ -> None
let mkIterator ~pos ~changed =
let expr (iterator : Ast_iterator.iterator) (e : Parsetree.expression) =
let newExp =
match e.pexp_desc with
| Pexp_ifthenelse
( {
pexp_desc =
Pexp_apply
( {
pexp_desc =
Pexp_ident {txt = Lident (("=" | "<>") as op)};
},
[(Nolabel, arg1); (Nolabel, arg2)] );
},
e1,
Some e2 )
when Loc.hasPos ~pos e.pexp_loc -> (
let e1, e2 = if op = "=" then (e1, e2) else (e2, e1) in
let mkMatch ~arg ~pat =
let cases =
[
Ast_helper.Exp.case pat e1;
Ast_helper.Exp.case (Ast_helper.Pat.any ()) e2;
]
in
Ast_helper.Exp.match_ ~loc:e.pexp_loc ~attrs:e.pexp_attributes arg
cases
in
match expToPat arg2 with
| None -> (
match expToPat arg1 with
| None -> None
| Some pat1 ->
let newExp = mkMatch ~arg:arg2 ~pat:pat1 in
Some newExp)
| Some pat2 ->
let newExp = mkMatch ~arg:arg1 ~pat:pat2 in
Some newExp)
| _ -> None
in
match newExp with
| Some newExp -> changed := Some newExp
| None -> Ast_iterator.default_iterator.expr iterator e
in
{Ast_iterator.default_iterator with expr}
let xform ~pos ~codeActions ~printExpr ~path structure =
let changed = ref None in
let iterator = mkIterator ~pos ~changed in
iterator.structure iterator structure;
match !changed with
| None -> ()
| Some newExpr ->
let range = rangeOfLoc newExpr.pexp_loc in
let newText = printExpr ~range newExpr in
let uri = Uri.fromPath path |> Uri.toString in
let codeAction =
CodeActions.make ~title:"Replace with switch" ~kind:RefactorRewrite
~edit:
{
documentChanges =
[
TextDocumentEdit
{
textDocument = {version = None; uri};
edits = [{newText; range}];
};
];
}
in
codeActions := codeAction :: !codeActions
end
module AddBracesToFn = struct
(* Add braces to fn without braces *)
let mkIterator ~pos ~changed =
(* While iterating the AST, keep info on which structure item we are in.
Printing from the structure item, rather than the body of the function,
gives better local pretty printing *)
let currentStructureItem = ref None in
let structure_item (iterator : Ast_iterator.iterator)
(item : Parsetree.structure_item) =
let saved = !currentStructureItem in
currentStructureItem := Some item;
Ast_iterator.default_iterator.structure_item iterator item;
currentStructureItem := saved
in
let expr (iterator : Ast_iterator.iterator) (e : Parsetree.expression) =
let bracesAttribute =
let loc =
{
Location.none with
loc_start = Lexing.dummy_pos;
loc_end =
{
Lexing.dummy_pos with
pos_lnum = Lexing.dummy_pos.pos_lnum + 1 (* force line break *);
};
}
in
(Location.mkloc "ns.braces" loc, Parsetree.PStr [])
in
let isFunction = function
| {Parsetree.pexp_desc = Pexp_fun _} -> true
| _ -> false
in
(match e.pexp_desc with
| Pexp_fun (_, _, _, bodyExpr)
when Loc.hasPos ~pos bodyExpr.pexp_loc
&& isBracedExpr bodyExpr = false
&& isFunction bodyExpr = false ->
bodyExpr.pexp_attributes <- bracesAttribute :: bodyExpr.pexp_attributes;
changed := !currentStructureItem
| _ -> ());
Ast_iterator.default_iterator.expr iterator e
in
{Ast_iterator.default_iterator with expr; structure_item}
let xform ~pos ~codeActions ~path ~printStructureItem structure =
let changed = ref None in
let iterator = mkIterator ~pos ~changed in
iterator.structure iterator structure;
match !changed with
| None -> ()
| Some newStructureItem ->
let range = rangeOfLoc newStructureItem.pstr_loc in
let newText = printStructureItem ~range newStructureItem in
let uri = Uri.fromPath path |> Uri.toString in
let codeAction =
CodeActions.make ~title:"Add braces to function" ~kind:RefactorRewrite
~edit:
{
documentChanges =
[
TextDocumentEdit
{
textDocument = {version = None; uri};
edits = [{newText; range}];
};
];
}
in
codeActions := codeAction :: !codeActions
end
module AddTypeAnnotation = struct
(* Add type annotation to value declaration *)
type annotation = Plain | WithParens
let mkIterator ~pos ~result =
let processPattern ?(isUnlabeledOnlyArg = false) (pat : Parsetree.pattern) =
match pat.ppat_desc with
| Ppat_var {loc} when Loc.hasPos ~pos loc ->
result := Some (if isUnlabeledOnlyArg then WithParens else Plain)
| _ -> ()
in
let rec processFunction ~argNum (e : Parsetree.expression) =
match e.pexp_desc with
| Pexp_fun (argLabel, _, pat, e) ->
let isUnlabeledOnlyArg =
argNum = 1 && argLabel = Nolabel
&&
match e.pexp_desc with
| Pexp_fun _ -> false
| _ -> true
in
processPattern ~isUnlabeledOnlyArg pat;
processFunction ~argNum:(argNum + 1) e
| _ -> ()
in
let structure_item (iterator : Ast_iterator.iterator)
(si : Parsetree.structure_item) =
match si.pstr_desc with
| Pstr_value (_recFlag, bindings) ->
let processBinding (vb : Parsetree.value_binding) =
let isReactComponent =
(* Can't add a type annotation to a react component, or the compiler crashes *)
vb.pvb_attributes
|> List.exists (function
| {Location.txt = "react.component"}, _payload -> true
| _ -> false)
in
if not isReactComponent then processPattern vb.pvb_pat;
processFunction vb.pvb_expr
in
bindings |> List.iter (processBinding ~argNum:1);
Ast_iterator.default_iterator.structure_item iterator si
| _ -> Ast_iterator.default_iterator.structure_item iterator si
in
{Ast_iterator.default_iterator with structure_item}
let xform ~path ~pos ~full ~structure ~codeActions ~debug =
let result = ref None in
let iterator = mkIterator ~pos ~result in
iterator.structure iterator structure;
match !result with
| None -> ()
| Some annotation -> (
match References.getLocItem ~full ~pos ~debug with
| None -> ()
| Some locItem -> (
match locItem.locType with
| Typed (name, typ, _) ->
let range, newText =
match annotation with
| Plain ->
( rangeOfLoc {locItem.loc with loc_start = locItem.loc.loc_end},
": " ^ (typ |> Shared.typeToString) )
| WithParens ->
( rangeOfLoc locItem.loc,
"(" ^ name ^ ": " ^ (typ |> Shared.typeToString) ^ ")" )
in
let uri = Uri.fromPath path |> Uri.toString in
let codeAction =
CodeActions.make ~title:"Add type annotation" ~kind:RefactorRewrite
~edit:
{
documentChanges =
[
TextDocumentEdit
{
textDocument = {version = None; uri};
edits = [{newText; range}];
};
];
}
in
codeActions := codeAction :: !codeActions
| _ -> ()))
end
module TypeToModule = struct
(* Convert type definition into its own module *)
let mkIterator ~pos ~result ~newTypeName =
let changeTypeDecl (typ : Parsetree.type_declaration) ~txt =
match typ.ptype_manifest with
| None ->
Ast_helper.Type.mk
{txt; loc = typ.ptype_name.loc}
~loc:typ.ptype_loc ~attrs:typ.ptype_attributes
~params:typ.ptype_params ~cstrs:typ.ptype_cstrs ~kind:typ.ptype_kind
~priv:typ.ptype_private
| Some manifest ->
Ast_helper.Type.mk
{txt; loc = typ.ptype_name.loc}
~loc:typ.ptype_loc ~attrs:typ.ptype_attributes
~params:typ.ptype_params ~cstrs:typ.ptype_cstrs ~kind:typ.ptype_kind
~priv:typ.ptype_private ~manifest
in
let structure_item (iterator : Ast_iterator.iterator)
(si : Parsetree.structure_item) =
match si.pstr_desc with
| Pstr_type (Nonrecursive, firstypeDec :: rest)
when Loc.hasPos ~pos si.pstr_loc ->
let loc = si.pstr_loc in
let firsLetterOfModule =
String.get firstypeDec.ptype_name.txt 0
|> Char.uppercase_ascii |> String.make 1
in
let restName =
String.sub firstypeDec.ptype_name.txt 1
(String.length firstypeDec.ptype_name.txt - 1)
in
let modName = firsLetterOfModule ^ restName in
let newFistType = changeTypeDecl firstypeDec ~txt:newTypeName in
let restStrucTypes =
Ast_helper.Str.type_ ~loc Nonrecursive ([newFistType] @ rest)
in
let pmb_expr = Ast_helper.Mod.structure ~loc [restStrucTypes] in
let mod_expr =
Parsetree.Pstr_module
{
pmb_name = {txt = modName; loc};
pmb_expr;
pmb_attributes = [];
pmb_loc = loc;
}
in
let processTypeKind (typeDec : Parsetree.type_declaration) =
match typeDec.ptype_kind with
| Ptype_record [{pld_name = {loc; txt}}; _] -> Some (loc, txt)
| Ptype_variant [{pcd_name = {loc; txt}}; _] -> Some (loc, txt)
| _ -> None
in
let references =
let referencesInfo =
[firstypeDec] @ rest |> List.filter_map processTypeKind
in
[(firstypeDec.ptype_name.loc, newTypeName)] @ referencesInfo
in
result := Some (Ast_helper.Str.mk ~loc mod_expr, references, modName);
Ast_iterator.default_iterator.structure_item iterator si
| _ -> ()
in
{Ast_iterator.default_iterator with structure_item}
let xform ~path ~pos ~codeActions ~printStructureItem structure ~debug =
let result = ref None in
let newTypeName = "t" in
let iterator = mkIterator ~pos ~result ~newTypeName in
iterator.structure iterator structure;
match !result with
| None -> ()
| Some (newStructureItem, references, modName) ->
let range = rangeOfLoc newStructureItem.pstr_loc in
let newText = printStructureItem ~range newStructureItem in
let uri = Uri.fromPath path |> Uri.toString in
let typeToModuleEdit =
Protocol.TextDocumentEdit
{textDocument = {version = None; uri}; edits = [{newText; range}]}
in
(* Before apply code action find all references and rename with new name *)
let relatedChanges =
references
|> List.filter_map (fun (loc, txt) ->
let range = rangeOfLoc loc in
let newName = modName ^ "." ^ txt in
match
Rename.command ~path
~pos:(range.start.line, range.start.character)
~newName ~debug
with
| Some workspaceEdit ->
let result =
workspaceEdit.documentChanges
|> List.map
(fun (documentChange : Protocol.documentChange) ->
match documentChange with
| TextDocumentEdit textEdit ->
let textDocument = textEdit.textDocument in
let edits =
if textEdit.textDocument.uri = uri then
(* Ignores first edit as it is within range of code action *)
match textEdit.edits with
| _ :: rest -> rest
| _ -> []
else textEdit.edits
in
Protocol.TextDocumentEdit {textDocument; edits}
| _ -> documentChange)
in
Some result
| None -> None)
|> List.flatten
in
let edit : Protocol.workspaceEdit =
{documentChanges = [typeToModuleEdit] @ relatedChanges}
in
let codeAction =
CodeActions.make ~title:"Move type definition into its own module"
~kind:RefactorRewrite ~edit
in
codeActions := codeAction :: !codeActions
end
let indent n text =
let spaces = String.make n ' ' in
let len = String.length text in
let text =
if len != 0 && text.[len - 1] = '\n' then String.sub text 0 (len - 1)
else text
in
let lines = String.split_on_char '\n' text in
match lines with
| [] -> ""
| [line] -> line
| line :: lines ->
line ^ "\n"
^ (lines |> List.map (fun line -> spaces ^ line) |> String.concat "\n")
let parse ~filename =
let {Res_driver.parsetree = structure; comments} =
Res_driver.parsingEngine.parseImplementation ~forPrinter:false ~filename
in
let filterComments ~loc comments =
(* Relevant comments in the range of the expression *)
let filter comment =
Loc.hasPos ~pos:(Loc.start (Res_comment.loc comment)) loc
in
comments |> List.filter filter
in
let printExpr ~(range : Protocol.range) (expr : Parsetree.expression) =
let structure = [Ast_helper.Str.eval ~loc:expr.pexp_loc expr] in
structure
|> Res_printer.printImplementation ~width:!Res_cli.ResClflags.width
~comments:(comments |> filterComments ~loc:expr.pexp_loc)
|> indent range.start.character
in
let printStructureItem ~(range : Protocol.range)
(item : Parsetree.structure_item) =
let structure = [item] in
structure
|> Res_printer.printImplementation ~width:!Res_cli.ResClflags.width
~comments:(comments |> filterComments ~loc:item.pstr_loc)
|> indent range.start.character
in
(structure, printExpr, printStructureItem)
let extractCodeActions ~path ~pos ~currentFile ~debug =
match Cmt.fullFromPath ~path with
| Some full when Filename.check_suffix currentFile ".res" ->
let structure, printExpr, printStructureItem =
parse ~filename:currentFile
in
let codeActions = ref [] in
AddTypeAnnotation.xform ~path ~pos ~full ~structure ~codeActions ~debug;
IfThenElse.xform ~pos ~codeActions ~printExpr ~path structure;
AddBracesToFn.xform ~pos ~codeActions ~path ~printStructureItem structure;
TypeToModule.xform ~path ~pos ~codeActions ~printStructureItem structure
~debug;
!codeActions
| _ -> []