-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
babel_v1_3_clean.js
412 lines (318 loc) · 11.9 KB
/
babel_v1_3_clean.js
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
// ChatGPT Refs:
// https://chat.openai.com/c/e65996fc-6607-4209-a082-6bc086c4f043
// https://chat.openai.com/c/b8596908-5e17-4aac-941b-aa95962de9c2
// https://chat.openai.com/c/4fc379b2-2760-43ef-9b1b-9b0d2e25768b
// https://chat.openai.com/c/174c4c91-8a4f-4acf-b605-59f22ce03bad
// Refs:
// - https://babeljs.io/
// - https://babeljs.io/docs/babel-parser
// - > The Babel parser (previously Babylon) is a JavaScript parser used in Babel
// - > Heavily based on `acorn` and `acorn-jsx`
// - https://babeljs.io/docs/babel-parser#api
// - https://babeljs.io/docs/babel-parser#output
// - > The Babel parser generates AST according to Babel AST format. It is based on ESTree spec with the following deviations...
// - https://github.com/babel/babel/blob/main/packages/babel-parser/ast/spec.md
// - > AST for JSX code is based on Facebook JSX AST
// - https://github.com/facebook/jsx/blob/main/AST.md
// - https://babeljs.io/docs/babel-parser#plugins
// - https://babeljs.io/docs/babel-parser#language-extensions
// - > Language extensions
// - https://babeljs.io/docs/babel-parser#ecmascript-proposals
// - > ECMAScript proposals
// - https://babeljs.io/docs/babel-parser#latest-ecmascript-features
// - > The following features are already enabled on the latest version of `@babel/parser`, and cannot be disabled because they are part of the language. You should enable these features only if you are using an older version.
// - https://babeljs.io/docs/babel-traverse
// - > We can use it alongside the `babel` parser to traverse and update nodes
// - https://babeljs.io/docs/babel-types
// - https://babeljs.io/docs/babel-types#aliases
// - https://babeljs.io/docs/babel-types#scopable
// - > A cover of `FunctionParent` and `BlockParent`.
// - https://babeljs.io/docs/babel-types#functionparent
// - > A cover of AST nodes that start an execution context with new `VariableEnvironment`. In other words, they define the scope of `var` declarations. `FunctionParent` did not include `Program` since Babel 7.
// - https://babeljs.io/docs/babel-types#blockparent
// - > A cover of AST nodes that start an execution context with new `LexicalEnvironment`. In other words, they define the scope of `let` and `const` declarations.
const babel = require("@babel/core");
const generate = require("@babel/generator").default;
const DEBUG = true;
const DEBUG_SHOW_EXTRA_BINDING_DETAILS = false;
const MAX_CODE_CONTEXT_LENGTH = 500;
const code = `
const aa = 5;
function foo(a) {
var b = a + aa + 1;
b = 7;
return b;
}
function bar(a) {
var c = a - aa - 1;
return c;
}
const baz = (a = 123) => {
let d = a * aa * 2;
return d;
}
`;
// const code = `
// const aa = 5;
// function foo(a) {
// var b = a + aa + 1;
// b = 7;
// return b;
// }
// function bar(a) {
// var c = a - aa - 1;
// return c;
// }
// const baz = (a = 123) => {
// let d = a * aa * 2;
// return d;
// }
// let boink = function(a) {
// let e = a * aa * 2;
// return e;
// }
// foo(111)
// const xx = {
// foo: () => { "foo" }
// }
// console.log(xx.foo);
// class Foo {}
// `;
const prefixCounts = new Map();
const makeDebugLog = (path) => (...messages) => {
if (!DEBUG) return;
// console.log(`[DEBUG::${path.getPathLocation()}::${path.type}]`, ...messages);
const name = getNameFromPath(path) || 'NO_NAME';
console.log(`[DEBUG::${name}::${path.type}]`, ...messages);
}
const debugShowProperties = (obj, label = '') => {
if (!DEBUG) return
console.group('[DEBUG] debugShowProperties', label ? `(${label})` : undefined);
console.group('Object.getOwnPropertyNames');
console.log(Object.getOwnPropertyNames(obj))
console.groupEnd();
console.group('Object.getOwnPropertyNames(Object.getPrototypeOf)');
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)))
console.groupEnd();
console.groupEnd();
}
const debugLogScopeBindings = ({ path }) => {
if (!DEBUG) return
const debugLog = makeDebugLog(path);
const scopeBindings = path.scope.bindings;
const allBindings = path.scope.getAllBindings();
const nameFromPath = getNameFromPath(path);
console.group(`[DEBUG] Path (type=${path.type}, nameFromPath=${nameFromPath}, pathLocation=${path.getPathLocation()})`);
console.group('Code');
console.log(path.toString().slice(0, MAX_CODE_CONTEXT_LENGTH));
console.groupEnd();
console.group(`Scope Dump (uid=${path.scope.uid})`);
path.scope.dump();
console.groupEnd();
console.group('Scope Bindings');
console.table(
Object.entries(scopeBindings).map(([bindingName, binding]) => {
return {
name: bindingName,
kind: binding.kind,
references: binding.references,
scopeUid: binding.scope.uid,
scopeType: binding.scope.path.type,
}
})
);
console.groupEnd();
console.group('All Bindings');
console.table(
Object.entries(allBindings).map(([bindingName, binding]) => {
return {
name: bindingName,
kind: binding.kind,
references: binding.references,
scopeUid: binding.scope.uid,
scopeType: binding.scope.path.type,
}
})
);
console.groupEnd();
console.group('Extra Binding Details');
if (DEBUG_SHOW_EXTRA_BINDING_DETAILS) {
Object.entries(scopeBindings).forEach(([bindingName, binding]) => {
console.group(bindingName);
// console.log('Binding', binding)
// debugLog('binding Keys', Object.keys(binding))
console.log('[DEBUG] binding.{various chosen bits}', {
bindingCode: binding.path.toString(),
identifierName: binding.identifier.name,
identifierLocName: binding.identifier.loc.identifierName,
identifierLocFilename: binding.identifier.loc.filename,
// hasDeoptedValue: binding.hasDeoptedValue,
// hasValue: binding.hasValue,
// value: binding.value,
bindingPathLocation: binding.path.getPathLocation(),
referencePaths: binding.referencePaths.map(path => ({
pathLocation: path.getPathLocation(),
nodeName: path.node.name,
nodeLoc: path.node.loc,
state: path.state,
})),
});
console.groupEnd();
});
} else {
console.log('Disabled by DEBUG_SHOW_EXTRA_BINDING_DETAILS')
}
console.groupEnd();
console.groupEnd();
}
// TODO: do we want to add some context from the node.path.type as well? (eg. instead of a func just being "foo" it might be "func foo")
function getNameFromPath(path) {
if (!path) return undefined;
const { parentPath } = path;
const node = path.node ? path.node : path
switch (node.type) {
case 'Program':
return '[[Program]]'
case 'Identifier':
return node.name;
case 'VariableDeclarator':
case 'FunctionDeclaration':
case 'ClassDeclaration':
return getNameFromPath(node.id);
case 'FunctionExpression':
case 'ArrowFunctionExpression':
return getNameFromPath(parentPath);
case 'BlockStatement':
const blockParentName = getNameFromPath(parentPath);
return `${blockParentName}::block{}`
case 'CallExpression':
return getNameFromPath(node.callee);
case 'ObjectProperty':
return getNameFromPath(node.key);
case 'MemberExpression':
const memberObjectName = getNameFromPath(node.object)
const memberPropertyName = getNameFromPath(node.property)
return `${memberObjectName}.${memberPropertyName}`;
default:
console.log('[getNameFromPath]: Unhandled node.type', node.type)
return undefined;
}
}
// OLD GETPREFIX/ETC CODE START
// // TODO: We might want to refactor this so that we can check the parent/etc as well?
// // Eg. for a function's arguments we probably want to look at:
// // Identifier that has a parent of FunctionDeclaration
// const getTypePrefix = (type) => {
// switch (type) {
// case 'Program':
// return '';
// case 'FunctionDeclaration':
// return 'func';
// case 'BlockStatement':
// '';
// case 'VariableDeclaration':
// return 'var';
// case 'Identifier':
// return 'arg';
// default:
// return type;
// }
// };
//
// function getPrefix(path) {
// const parentPrefix = path.parentPath ? getPrefix(path.parentPath) : '';
// const typePrefix = getTypePrefix(path.type);
// const combinedPrefix = parentPrefix ? `${parentPrefix}_${typePrefix}` : typePrefix;
// // const combinedPrefix = parentPrefix && typePrefix ? `${parentPrefix}_${typePrefix}` : `${parentPrefix}${typePrefix}`;
// const count = (prefixCounts.get(combinedPrefix) || 0) + 1;
// prefixCounts.set(combinedPrefix, count);
// const combinedPrefixWithCount = combinedPrefix ? `${combinedPrefix}_${count}` : '';
//
// // TODO: remove debug log
// console.log(
// '[DEBUG] getPrefix',
// { parentPrefix, typePrefix, combinedPrefix, combinedPrefixWithCount }
// );
//
// return combinedPrefixWithCount;
// }
// OLD GETPREFIX/ETC CODE END
function getPrefix({ path, binding, bindingName }) {
const debugLog = makeDebugLog(path);
const prefix = (() => {
switch (path.type) {
case 'Program':
return ''
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
const funcName = getNameFromPath(path);
return `${funcName}_${binding.kind}`
// TODO: Do we want to name this based on it's parent scope's name?
// case 'VariableDeclarator':
// // ???
// TODO: Do we want to name this based on it's parent scope's name?
// case 'ClassDeclaration':
// // ???
case 'BlockStatement':
const isParentFunction = [
'FunctionDeclaration',
'FunctionExpression',
'ArrowFunctionExpression'
].includes(path.parent.type);
return isParentFunction ? "" : getNameFromPath(path.parent);
// TODO: does this actually need handling here?
// case 'ObjectProperty':
// return getNameFromPath(node.key);
default:
return path.type;
}
})()
debugLog(`binding[${bindingName}].prefix=${prefix}`);
return prefix;
}
const ast = babel.parse(code);
let scopableCount = 0;
babel.traverse(ast, {
Scopable(path) {
scopableCount++;
const debugLog = makeDebugLog(path);
console.group(`=== Scopable ${scopableCount} (scopeUid=${path.scope.uid}) ===`);
console.group('[DEBUG] Debug Context');
// debugShowProperties(path, 'path');
console.log('[DEBUG] path.{various chosen bits}', {
key: path.key,
type: path.type,
hub: path.hub,
state: path.state,
data: path.data,
});
console.groupEnd();
const bindings = path.scope.bindings;
debugLogScopeBindings({ path });
Object.entries(bindings).forEach(([name, binding]) => {
const prefix = getPrefix({ path, binding, bindingName: name });
const newName = prefix ? `${prefix}_${name}` : name;
// const isBlockStatement = path.type === 'BlockStatement';
// const isParentFunction = ['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'].includes(path.parent.type);
// const shouldRename = !isBlockStatement || (isBlockStatement && !isParentFunction)
// if (shouldRename) {
if (name !== newName) {
console.log(`Renaming ${name} to ${newName} in scope ${path.scope.uid} (${path.scope.path.type})`);
path.scope.rename(name, newName);
} else {
// console.log(`Skipping rename from ${name} to ${newName} in scope ${path.scope.uid} (${path.scope.path.type})`);
console.log(`No need to rename ${name} in scope ${path.scope.uid} (${path.scope.path.type})`);
}
});
console.groupEnd();
},
});
const output = generate(ast, {}, code);
console.log('------------');
console.group('Before:');
console.log(code);
console.groupEnd();
console.group('After:');
console.log(output.code);
console.groupEnd();