summaryrefslogtreecommitdiff
path: root/node_modules/babel-plugin-minify-mangle-names/lib/fixup-var-scoping.js
blob: 2945315d955d77fa5a6fde60e807d0fb12c48a43 (plain)
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
"use strict";

// this fixes a bug where converting let to var
// doesn't change the binding's scope to function scope
// https://github.com/babel/babel/issues/4818
module.exports = function (mangler) {
  mangler.program.traverse({
    VariableDeclaration(path) {
      if (path.node.kind !== "var") {
        return;
      }

      const fnScope = path.scope.getFunctionParent() || path.scope.getProgramParent();
      const bindingIds = path.getOuterBindingIdentifierPaths();

      for (const name in bindingIds) {
        const binding = path.scope.getBinding(name); // var isn't hoisted to fnScope

        if (binding.scope !== fnScope) {
          const existingBinding = fnScope.bindings[name]; // make sure we are clear that the fnScope doesn't already have
          // an existing binding

          if (!existingBinding) {
            // move binding to the function scope
            // update our scopeTracker first before
            // we mutate the scope
            mangler.scopeTracker.moveBinding(binding, fnScope);
            fnScope.bindings[name] = binding;
            binding.scope = fnScope;
            delete binding.scope.bindings[name];
          } else {
            // we need a new binding that's valid in both the scopes
            // binding.scope and fnScope
            const newName = fnScope.generateUid(binding.scope.generateUid(name)); // rename binding in the original scope

            mangler.rename(binding.scope, binding, name, newName); // move binding to fnScope as newName
            // update our scopeTracker first before
            // we mutate the scope

            mangler.scopeTracker.moveBinding(binding, fnScope);
            fnScope.bindings[newName] = binding;
            binding.scope = fnScope;
            delete binding.scope.bindings[newName];
          }
        }
      }
    }

  });
};