UNPKG

2.98 kBJavaScriptView Raw
1"use strict";
2
3const t = require('@babel/types');
4
5function rename(scope, oldName, newName) {
6 if (oldName === newName) {
7 return;
8 }
9
10 let binding = scope.getBinding(oldName);
11
12 if (!binding) {
13 throw new Error("'" + oldName + "' is not defined");
14 } // Rename all constant violations
15
16
17 var _iteratorNormalCompletion = true;
18 var _didIteratorError = false;
19 var _iteratorError = undefined;
20
21 try {
22 for (var _iterator = binding.constantViolations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
23 let violation = _step.value;
24 let bindingIds = violation.getBindingIdentifierPaths(true, false);
25
26 for (let name in bindingIds) {
27 if (name === oldName) {
28 var _iteratorNormalCompletion3 = true;
29 var _didIteratorError3 = false;
30 var _iteratorError3 = undefined;
31
32 try {
33 for (var _iterator3 = bindingIds[name][Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
34 let idPath = _step3.value;
35 idPath.node.name = newName;
36 }
37 } catch (err) {
38 _didIteratorError3 = true;
39 _iteratorError3 = err;
40 } finally {
41 try {
42 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
43 _iterator3.return();
44 }
45 } finally {
46 if (_didIteratorError3) {
47 throw _iteratorError3;
48 }
49 }
50 }
51 }
52 }
53 } // Rename all references
54
55 } catch (err) {
56 _didIteratorError = true;
57 _iteratorError = err;
58 } finally {
59 try {
60 if (!_iteratorNormalCompletion && _iterator.return != null) {
61 _iterator.return();
62 }
63 } finally {
64 if (_didIteratorError) {
65 throw _iteratorError;
66 }
67 }
68 }
69
70 var _iteratorNormalCompletion2 = true;
71 var _didIteratorError2 = false;
72 var _iteratorError2 = undefined;
73
74 try {
75 for (var _iterator2 = binding.referencePaths[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
76 let path = _step2.value;
77
78 if (t.isExportSpecifier(path.parent) && path.parentPath.parent.source) {
79 continue;
80 }
81
82 if (path.node.name === oldName) {
83 path.node.name = newName;
84 }
85 } // Rename binding identifier, and update scope.
86
87 } catch (err) {
88 _didIteratorError2 = true;
89 _iteratorError2 = err;
90 } finally {
91 try {
92 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
93 _iterator2.return();
94 }
95 } finally {
96 if (_didIteratorError2) {
97 throw _iteratorError2;
98 }
99 }
100 }
101
102 scope.removeOwnBinding(oldName);
103 scope.bindings[newName] = binding;
104 binding.identifier.name = newName;
105}
106
107module.exports = rename;
\No newline at end of file