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
open! Stdlib
open Javascript
let debug_shortvar = Debug.find "shortvar"
let debug = Debug.find "js_assign"
module S = Code.Var.Set
module Var = Code.Var
module type Strategy = sig
type t
val create : int -> t
val record_block : t -> Js_traverse.t -> Js_traverse.block -> unit
val allocate_variables : t -> count:int array -> string array
end
module Min : Strategy = struct
type alloc =
{ mutable first_free : int
; used : BitSet.t
; existing_names : StringSet.t
}
let make_alloc_table existing_names =
{ first_free = 0; used = BitSet.create (); existing_names }
let next_available a i = BitSet.next_free a.used (max i a.first_free)
let allocate a i =
BitSet.set a.used i;
if a.first_free = i then a.first_free <- BitSet.next_free a.used a.first_free
let is_available l name i =
List.for_all l ~f:(fun a ->
(not (BitSet.mem a.used i)) && not (StringSet.mem name a.existing_names))
let first_available l =
let rec find_rec n l =
let n' = List.fold_left l ~init:n ~f:(fun n a -> next_available a n) in
if n = n' then n else find_rec n' l
in
find_rec 0 l
let mark_allocated l i = List.iter l ~f:(fun a -> allocate a i)
type t =
{ constr : alloc list array
; mutable parameters : Var.t list array
; printer : Var_printer.t
}
let create nv =
{ constr = Array.make nv []
; parameters = [| [] |]
; printer = Var_printer.create Var_printer.Alphabet.javascript
}
let allocate_variables t ~count =
let weight v = count.(v) in
let constr = t.constr in
let len = Array.length constr in
let idx = Array.make len 0 in
for i = 0 to len - 1 do
idx.(i) <- i
done;
Array.stable_sort idx ~cmp:(fun i j -> compare (weight j) (weight i));
let names = Array.make len "" in
let n0 = ref 0 in
let n1 = ref 0 in
let n2 = ref 0 in
let n3 = ref 0 in
let stats i n =
incr n0;
if n < 54
then (
incr n1;
n2 := !n2 + weight i);
n3 := !n3 + weight i
in
let total = ref 0 in
let bad = ref 0 in
for i = 0 to Array.length t.parameters - 1 do
let name = Var_printer.to_string t.printer i in
List.iter
(List.rev t.parameters.(i))
~f:(fun x ->
incr total;
let idx = Var.idx x in
let l = constr.(idx) in
if is_available l name i
then (
names.(idx) <- name;
mark_allocated l i;
stats idx i)
else incr bad)
done;
if debug_shortvar ()
then
Format.eprintf
"Function parameter properly assigned: %d/%d@."
(!total - !bad)
!total;
for i = 0 to len - 1 do
let idx = idx.(i) in
let l = constr.(idx) in
(if (not (List.is_empty l)) && String.length names.(idx) = 0
then
let rec loop () =
let n = first_available l in
let name = Var_printer.to_string t.printer n in
if List.for_all l ~f:(fun a -> not (StringSet.mem name a.existing_names))
then (
names.(idx) <- name;
mark_allocated l n;
stats idx n)
else (
mark_allocated l n;
loop ())
in
loop ());
if List.is_empty l then assert (weight idx = 0)
done;
if debug_shortvar ()
then (
Format.eprintf "short variable count: %d/%d@." !n1 !n0;
Format.eprintf "short variable occurrences: %d/%d@." !n2 !n3);
names
let add_constraints global u ~offset (params : ident list) =
let constr = global.constr in
let existing_names =
Javascript.IdentSet.fold
(fun x acc ->
match x with
| V _ -> acc
| S { name = Utf8 name; _ } -> StringSet.add name acc)
u
StringSet.empty
in
let c = make_alloc_table existing_names in
Javascript.IdentSet.iter
(function
| S _ -> ()
| V v ->
let i = Var.idx v in
constr.(i) <- c :: constr.(i))
u;
let params = Array.of_list params in
let len = Array.length params in
let len_max = len + offset in
if Array.length global.parameters < len_max
then (
let a = Array.make (2 * len_max) [] in
Array.blit
~src:global.parameters
~src_pos:0
~dst:a
~dst_pos:0
~len:(Array.length global.parameters);
global.parameters <- a);
for i = 0 to len - 1 do
match params.(i) with
| V x -> global.parameters.(i + offset) <- x :: global.parameters.(i + offset)
| _ -> ()
done
let record_block state scope (block : Js_traverse.block) =
let all =
Javascript.IdentSet.union
(Javascript.IdentSet.union scope.Js_traverse.def_var scope.Js_traverse.def_local)
scope.Js_traverse.use
in
let all =
match block with
| Normal -> all
| Params _ -> all
| Catch (p, _) ->
let ids = bound_idents_of_binding p in
List.fold_left ids ~init:all ~f:(fun all i -> Javascript.IdentSet.add i all)
in
match block with
| Normal -> add_constraints state all ~offset:0 []
| Catch (v, _) -> add_constraints state all ~offset:5 (bound_idents_of_binding v)
| Params p -> add_constraints state all ~offset:0 (bound_idents_of_params p)
end
module Preserve : Strategy = struct
type t =
{ size : int
; mutable scopes : (S.t * Javascript.IdentSet.t) list
}
let create size = { size; scopes = [] }
let record_block t scope (b : Js_traverse.block) =
let defs =
match b with
| Catch (p, _) ->
bound_idents_of_binding p
@ Javascript.IdentSet.elements scope.Js_traverse.def_local
| Normal -> Javascript.IdentSet.elements scope.Js_traverse.def_local
| Params _ ->
Javascript.IdentSet.elements
(IdentSet.union scope.Js_traverse.def_var scope.Js_traverse.def_local)
in
let all =
Javascript.IdentSet.union
(Javascript.IdentSet.union scope.Js_traverse.def_var scope.Js_traverse.def_local)
scope.Js_traverse.use
in
let defs =
List.fold_left
~init:S.empty
~f:(fun acc x ->
match (x : Javascript.ident) with
| V i -> S.add i acc
| S _ -> acc)
defs
in
t.scopes <- (defs, all) :: t.scopes
let uniq_var = Debug.find "var"
let allocate_variables t ~count =
let names = Array.make t.size "" in
let uniq_var = uniq_var () in
let unamed = ref 0 in
let create_unamed =
if uniq_var
then
fun i ->
"_" ^ Var_printer.Alphabet.to_string Var_printer.Alphabet.javascript i ^ "_"
else fun i -> Var_printer.Alphabet.to_string Var_printer.Alphabet.javascript i
in
List.iter t.scopes ~f:(fun (defs, all) ->
let reserved =
IdentSet.fold
(fun var acc ->
match var with
| S { name = Utf8 s; _ } -> StringSet.add s acc
| V v ->
let name = names.(Var.idx v) in
if not (String.is_empty name) then StringSet.add name acc else acc)
all
StringSet.empty
in
let reserved, others =
S.fold
(fun var (reserved, others) ->
assert (String.is_empty names.(Var.idx var));
match Var.get_name var with
| Some expected_name ->
assert (not (String.is_empty expected_name));
assert (not (StringSet.mem expected_name Reserved.keyword));
let name =
if not (StringSet.mem expected_name reserved)
then expected_name
else
let expected_name =
if Char.equal expected_name.[String.length expected_name - 1] '$'
then expected_name
else expected_name ^ "$"
in
let i = ref 0 in
while
StringSet.mem (Printf.sprintf "%s%d" expected_name !i) reserved
do
incr i
done;
Printf.sprintf "%s%d" expected_name !i
in
names.(Var.idx var) <- name;
StringSet.add name reserved, others
| None -> reserved, var :: others)
defs
(reserved, [])
in
if not uniq_var then unamed := 0;
let _reserved =
let weight v = count.(Var.idx v) in
List.stable_sort others ~cmp:(fun i j ->
match compare (weight j) (weight i) with
| 0 -> Var.compare i j
| c -> c)
|> List.fold_left ~init:reserved ~f:(fun reserved var ->
let name =
while
let name = create_unamed !unamed in
StringSet.mem name reserved || StringSet.mem name Reserved.keyword
do
incr unamed
done;
create_unamed !unamed
in
names.(Var.idx var) <- name;
StringSet.add name reserved)
in
());
names
end
class traverse record_block =
object (m)
inherit Js_traverse.free as super
method! record_block b =
record_block m#state b;
super#record_block b
end
class traverse_idents_and_labels ~idents ~labels =
object
inherit Js_traverse.iter as super
val ldepth = 0
method fun_decl (_k, _params, body, _loc) =
let m = {<ldepth = 0>} in
m#function_body body
method statement =
function
| Labelled_statement (L l, (s, _)) ->
let m = {<ldepth = ldepth + 1>} in
Var.Hashtbl.add labels l ldepth;
m#statement s
| s -> super#statement s
method ident i =
match i with
| S _ -> ()
| V v ->
let idx = Code.Var.idx v in
idents.(idx) <- idents.(idx) + 1
end
class name ident label =
object (m)
inherit Js_traverse.map as super
method ident x = ident x
method statement =
function
| Labelled_statement (l, (s, loc)) ->
Labelled_statement (label l, (m#statement s, loc))
| Break_statement (Some l) -> Break_statement (Some (label l))
| Continue_statement (Some l) -> Continue_statement (Some (label l))
| s -> super#statement s
end
let program' (module Strategy : Strategy) p =
let nv = Var.count () in
let state = Strategy.create nv in
let labels = Var.Hashtbl.create 20 in
let mapper = new traverse (Strategy.record_block state) in
let p = mapper#program p in
let count = Array.make nv 0 in
let () =
let o = new traverse_idents_and_labels ~idents:count ~labels in
o#program p
in
mapper#record_block Normal;
let freevar =
IdentSet.fold
(fun ident acc ->
match ident with
| V v -> Var.Set.add v acc
| S _ -> acc)
mapper#get_free
Var.Set.empty
in
let has_free_var = not (Var.Set.is_empty freevar) in
let unallocated_names = ref Var.Set.empty in
let names = Strategy.allocate_variables state ~count in
Var.Set.iter (fun x -> names.(Var.idx x) <- "") freevar;
let ident =
if Config.Flag.stable_var ()
then
function
| S _ as x -> x
| V v ->
let name = Printf.sprintf "v%d" (Code.Var.idx v) in
ident ~var:v (Utf8_string.of_string_exn name)
else
function
| S _ as x -> x
| V v as x -> (
let name = names.(Var.idx v) in
match name with
| "" ->
unallocated_names := Var.Set.add v !unallocated_names;
x
| _ -> ident ~var:v (Utf8_string.of_string_exn name))
in
let label_printer = Var_printer.create Var_printer.Alphabet.javascript in
let max_label_depth = Var.Hashtbl.fold (fun _ d acc -> max d acc) labels 0 in
let lname_per_depth =
Array.init (max_label_depth + 1) ~f:(fun i -> Var_printer.to_string label_printer i)
in
let label = function
| Label.S _ as l -> l
| L v ->
let i = Var.Hashtbl.find labels v in
S (Utf8_string.of_string_exn lname_per_depth.(i))
in
let p = (new name ident label)#program p in
(if has_free_var || Var.Set.cardinal !unallocated_names > 0
then
let () =
if not (debug_shortvar () || debug ())
then
Format.eprintf
"Some variables escaped (#%d). Use [--debug js_assign] for more info.@."
(Var.Set.cardinal freevar)
else
let (_ : Source_map.info) =
Js_output.program
~accept_unnamed_var:true
(Pretty_print.to_out_channel stderr)
p
in
Format.eprintf "Some variables escaped:";
Var.Set.iter (fun v -> Format.eprintf " <%a>" Var.print v) freevar;
Format.eprintf "@."
in
assert false);
p
let program p =
if Config.Flag.shortvar ()
then program' (module Min) p
else program' (module Preserve) p