package js_of_ocaml-compiler

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file js_assign.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
(* Js_of_ocaml compiler
 * http://www.ocsigen.org/js_of_ocaml/
 * Copyright (C) 2013 Jérôme Vouillon
 * Copyright (C) 2013 Hugo Heuzard
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, with linking exception;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *)
open! Stdlib
open Javascript

let debug = Debug.find "shortvar"

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 -> catch:bool -> Javascript.ident list -> unit

  val allocate_variables : t -> count:int Javascript.IdentMap.t -> string array
end

module Min : Strategy = struct
  (*
We are trying to achieve the following goals:
(1) variable names should be as short as possible
(2) one should reuse as much as possible a small subsets of variable
    names
(3) function parameters should be: function(a,b,...){...}
(4) for longer variable names, variable which are closed from one
    another should share a same prefix

Point (1) minimizes the size of uncompressed files, while point (2) to
(4) improve compression.

We use the following strategy. We maintain the constraint that
variables occurring in a function should keep different names.
We first assign names a, b, ... (in order) to function parameters,
starting from inner functions, skipping variables which have a
conflict with a previously names variable (goal 3). Then, we order
the remaining variables by their number of occurrences, then by
their index (goal 4), and greedily assigned name to them. For that,
we use for each variable the smallest possible name still available
(goal 1/2).

This algorithm seems effective. Here are some statistics gathered
while compiling the OCaml toplevel:
(1) We get 132025 occurrences of one-char variables out of 169728
    occurrences while the optimal number (determined using a mixed
    integer linear programming solver) is 132105 occurrences (80 more
    occurrences).
(2) Variable names are heavily biased toward character a: among
    variables, we have about 34000 occurrences of character a, less
    than 5000 occurrences of character i (9th character, out of the 54
    characters that can start an identifier), and about 1500
    occurrences of character A.
(3) About 6% of the function parameters are not assigned as wanted;
    it is not clear we can do any better: there are a lot of nested
    functions.
(4) We save 8181 bytes on the compressed file (1.8%) by sorting
    variables using their index as a secondary key rather that just
    based on their weights (the size of the uncompressed file remains
    unchanged)
*)

  type alloc =
    { mutable first_free : int
    ; mutable used : BitSet.t
    }

  let make_alloc_table () = { first_free = 0; used = BitSet.create () }

  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 i = List.for_all l ~f:(fun a -> BitSet.mem a.used i)

  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
    ; (* Constraints on variables *)
      mutable parameters : Var.t list array
    ; (* Function parameters *)
      mutable constraints : S.t list
    }

  (* For debugging *)

  let create nv = { constr = Array.make nv []; parameters = [| [] |]; constraints = [] }

  (* let output_debug_information t count =
   *
   *
   *   let weight v = (IdentMap.find (V v) count) in
   *
   *   let usage =
   *     List.fold_left
   *       (fun u s ->
   *          S.fold
   *            (fun v u -> VM.add v (try 1 + VM.find v u with Not_found -> 1) u)
   *            s u)
   *       VM.empty t.constraints
   *   in
   *
   *   let l = List.map fst (VM.bindings usage) in
   *
   *   let ch = open_out "/tmp/weights.txt" in
   *   List.iter
   *     (fun v ->
   *        Printf.fprintf ch "%d / %d / %d\n" (weight v)
   *          (VM.find v usage) (Var.idx v))
   *     l;
   *   close_out ch;
   *
   *   let ch = open_out "/tmp/problem.txt" in
   *   Printf.fprintf ch "Maximize\n";
   *   let a = Array.of_list l in
   *   Printf.fprintf ch "  ";
   *   for i = 0 to Array.length a - 1 do
   *     let v = a.(i) in
   *     let w = weight v in
   *     if i > 0 then Printf.fprintf ch " + ";
   *     Printf.fprintf ch "%d x%d" w (Var.idx v)
   *   done;
   *   Printf.fprintf ch "\n";
   *   Printf.fprintf ch "Subject To\n";
   *   List.iter
   *     (fun s ->
   *        if S.cardinal s > 0 then begin
   *          Printf.fprintf ch "  ";
   *          let a = Array.of_list (S.elements s) in
   *          for i = 0 to Array.length a - 1 do
   *            if i > 0 then Printf.fprintf ch " + ";
   *            Printf.fprintf ch "x%d" (Var.idx a.(i))
   *          done;
   *          Printf.fprintf ch "<= 54\n"
   *        end)
   *     t.constraints;
   *   Printf.fprintf ch "Binary\n  ";
   *   List.iter (fun v -> Printf.fprintf ch " x%d" (Var.idx v)) l;
   *   Printf.fprintf ch "\nEnd\n";
   *   close_out ch;
   *
   *   let ch = open_out "/tmp/problem2" in
   *   let var x = string_of_int (Var.idx x) in
   *   let a = List.map (fun v -> (var v, weight v)) l in
   *   let b =
   *     List.map (fun s -> List.map var (S.elements s)) t.constraints in
   *   let c = List.map var l in
   *   output_value ch
   *     ((a, b, c) : (string * int) list * string list list * string list);
   *   close_out ch *)

  let allocate_variables t ~count =
    let weight v = try IdentMap.find (V (Var.of_idx v)) count with Not_found -> 0 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 name = 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 nm ~origin n =
      name.(origin) <- Var.to_string ~origin:(Var.of_idx origin) (Var.of_idx n)
    in
    let total = ref 0 in
    let bad = ref 0 in
    for i = 0 to Array.length t.parameters - 1 do
      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 i
          then (
            nm ~origin:idx i;
            mark_allocated l i;
            stats idx i)
          else incr bad)
    done;
    if debug ()
    then
      Format.eprintf
        "Function parameter properly assigned: %d/%d@."
        (!total - !bad)
        !total;
    for i = 0 to len - 1 do
      let l = constr.(idx.(i)) in
      if (not (List.is_empty l)) && String.length name.(idx.(i)) = 0
      then (
        let n = first_available l in
        let idx = idx.(i) in
        nm ~origin:idx n;
        mark_allocated l n;
        stats idx n);
      if List.is_empty l then assert (weight idx.(i) = 0)
    done;
    if debug ()
    then (
      Format.eprintf "short variable count: %d/%d@." !n1 !n0;
      Format.eprintf "short variable occurrences: %d/%d@." !n2 !n3);
    name

  let add_constraints global u ?(offset = 0) params =
    let constr = global.constr in
    let c = make_alloc_table () in
    S.iter
      (fun 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;
    global.constraints <- u :: global.constraints

  let record_block state scope ~catch params =
    let offset = if catch then 5 else 0 in
    let all = S.union scope.Js_traverse.def scope.Js_traverse.use in
    add_constraints state all ~offset params
end

module Preserve : Strategy = struct
  (* Try to preserve variable names.
     - Assign the origin name if present: "{original_name}"
     - If present but not available, derive a similar name: "{original_name}${n}" (eg. result$3).
     - If not present, make up a name: "$${n}"

     Color variables one scope/block at a time - outer scope first.
  *)

  type t =
    { size : int
    ; mutable scopes : (S.t * Js_traverse.t) list
    }

  let create size = { size; scopes = [] }

  let record_block t scope ~catch param =
    let defs =
      match catch, param with
      | true, [ V x ] -> S.singleton x
      | true, [ S _ ] -> S.empty
      | true, _ -> assert false
      | false, _ -> scope.Js_traverse.def
    in
    t.scopes <- (defs, scope) :: t.scopes

  let allocate_variables t ~count:_ =
    let names = Array.make t.size "" in
    List.iter t.scopes ~f:(fun (defs, state) ->
        let assigned =
          List.fold_left
            ~f:StringSet.union
            ~init:StringSet.empty
            [ state.Js_traverse.def_name; state.Js_traverse.use_name; Reserved.keyword ]
        in
        let assigned =
          S.fold
            (fun var acc ->
              let name = names.(Var.idx var) in
              if not (String.is_empty name) then StringSet.add name acc else acc)
            (S.union state.Js_traverse.use state.Js_traverse.def)
            assigned
        in
        let _assigned =
          S.fold
            (fun var assigned ->
              assert (String.is_empty names.(Var.idx var));
              let name =
                match Var.get_name var with
                | Some expected_name ->
                    assert (not (String.is_empty expected_name));
                    if not (StringSet.mem expected_name assigned)
                    then expected_name
                    else
                      let i = ref 0 in
                      while
                        StringSet.mem (Printf.sprintf "%s$%d" expected_name !i) assigned
                      do
                        incr i
                      done;
                      Printf.sprintf "%s$%d" expected_name !i
                | None -> Var.to_string var
              in
              names.(Var.idx var) <- name;
              StringSet.add name assigned)
            defs
            assigned
        in
        ());
    names
end

class traverse record_block =
  object (m)
    inherit Js_traverse.free as super

    method! block ?(catch = false) params =
      record_block m#state ~catch params;
      super#block params
  end

let program' (module Strategy : Strategy) p =
  let nv = Var.count () in
  let state = Strategy.create nv in
  let mapper = new traverse (Strategy.record_block state) in
  let p = mapper#program p in
  mapper#block [];
  if S.cardinal mapper#get_free <> 0
  then
    if true
    then failwith_ "Some variables escaped (#%d)" (S.cardinal mapper#get_free)
    else (
      Format.eprintf "Some variables escaped (#%d)" (S.cardinal mapper#get_free);
      S.iter (fun s -> Format.eprintf "%s@." (Var.to_string s)) mapper#get_free);
  let names = Strategy.allocate_variables state ~count:mapper#state.Js_traverse.count in
  (* if debug () then output_debug_information state coloring#state.Js_traverse.count; *)
  let color = function
    | V v ->
        let name = names.(Var.idx v) in
        assert (not (String.is_empty name));
        ident ~var:v name
    | x -> x
  in
  (new Js_traverse.subst color)#program p

let program p =
  if Config.Flag.shortvar ()
  then program' (module Min) p
  else program' (module Preserve) p
OCaml

Innovation. Community. Security.