-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmock_environment.js
435 lines (410 loc) · 19.1 KB
/
mock_environment.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
const parse_flow_src = require('flow-parser');
const flow_remove_types = require('flow-remove-types');
function prepare_current_file_to_act_as_server(file_src, names_of_interest) {
var server_src = `console.log('server would be running here')`
var mock_server_src = `${file_src.replace(/const /g, 'var ')}
/* ----- REPLUGGER MOCK SERVER ----- */
const replugger_circular_json = require('circular-json');
const replugger_undescore = require('underscore');
function replugger_json_replacer(key, value) {
if (typeof value === 'function') {
return value.toLocaleString();
}
return value;
}
var replugger_output = {
${names_of_interest.map(name => `${name}: replugger_circular_json.stringify(${name}, replugger_json_replacer).slice(0, 100)`).join(',\n')}
}
process.stdin.setEncoding('utf-8')
process.stdin.on('data', function(buffer) {
var lines = buffer.toString().split('\\n');
for (var i = 0; i < lines.length; ++i) {
var data = lines[i];
if (data.startsWith('replugger_summary_info:')) {
var name = data.replace(/^replugger_summary_info:/, '');
try {
var output = eval(name)
if (typeof output === 'object' && output !== null && output.isTrusted === false) {
output.isTrusted = true;
}
var json_output = replugger_circular_json.stringify(output, replugger_json_replacer);
if (json_output === undefined) {
process.stdout.write('undefined\\n')
} else {
process.stdout.write(json_output.slice(0, 100).replace(/\\n/g, '__REPLUGGERNL__')+'\\n')
}
} catch(e) {
process.stdout.write('replugger_error:'+e.toString().replace(/\\n/g, '__REPLUGGERNL__')+'\\n')
}
} else if (data.startsWith('replugger_full_info:')) {
var name = data.replace(/^replugger_full_info:/, '');
try {
var output = eval(name);
// why is typeof null an object?!?!?!
if (output !== null && typeof output === 'object') {
var json_output = '{';
_.each(output, function(value, key) {
var value = replugger_circular_json.stringify(value, replugger_json_replacer)
json_output += '"'+ key +'": '+ (value !== undefined ? value.slice(0, 100) : 'undefined') + ',,'
})
json_output += '}'
} else {
try {
json_output = replugger_circular_json.stringify(output, replugger_json_replacer).slice(0,500);
} catch(e) {
json_output = 'undefined'
}
}
process.stdout.write(json_output.replace(/\\n/g, '__REPLUGGERNL__')+'\\n')
} catch(e) {
process.stdout.write('replugger_error:'+e.toString().replace(/\\n/g, '__REPLUGGERNL__')+'\\n')
}
} else if (data.startsWith('replugger_run_code:')) {
var code = data.replace('replugger_run_code:', '').replace(/__REPLUGGERNL__/g, '\\n');
try {
eval(code);
process.stdout.write('ok\\n')
} catch(e) {
process.stdout.write('replugger_error:'+e.toString().replace(/\\n/g, '__REPLUGGERNL__')+'\\n')
}
}
}
});
process.stdout.setEncoding('utf-8')
process.stdout.write('ok\\n');
`
return mock_server_src;
}
module.exports.prepare_current_file_to_act_as_server = prepare_current_file_to_act_as_server;
function scopes_and_names(file_src, line_number) {
var scopes = [];
/* e.g.
[
{scope_name: 'function (evt) {',
line_number: 102,
names_in_scope: ['evt', 'dx', 'dy'],
fill_in_names: ['evt'],
}
]
*/
var lines = file_src.split('\n');
var scope_stack = [{scope_name: 'file', line_number: null, names_in_scope: [], fill_in_names: []}];
for (var i = 0; i < lines.length; ++i) {
if (i >= line_number) {
return scope_stack;
}
var line = lines[i].trim();
if (line.startsWith('const ') || line.startsWith('var ')) {
var name = line.split('=')[0].replace(/(const|var)/g, '').trim();
scope_stack[scope_stack.length-1].names_in_scope.push(name)
// } else if (line.startsWith('function') && scope_stack.length == 1) {
// // defining global function
} else if (line.startsWith('class ') && scope_stack.length == 1) {
var name = line.replace(/ \{.*/, '').replace('class ', '')
scope_stack[0].names_in_scope.push(name);
} else if (line.includes('this.') || line.includes('this,')) {
var current_scope_stack = scope_stack[scope_stack.length-1];
if (!current_scope_stack.names_in_scope.includes('this')) {
current_scope_stack.names_in_scope.push('this')
}
} else if (line.startsWith('function ') && scope_stack.length == 1) {
var name = line.replace(/\(.*\) \{.*/, '').replace('function ', '');
scope_stack[0].names_in_scope.push(name);
} else if (line.startsWith('}')) {
if (scope_stack.length > 1) {
scope_stack.pop();
}
}
if (line.endsWith('{')) {
scope_stack.push({scope_name: line, line_number: i+1, names_in_scope: [], fill_in_names: []})
var current_scope_stack = scope_stack[scope_stack.length-1];
var function_re = /function[\w\s]*\(([\w,\s]+)\)\s?\{$/;
var match_groups = line.match(function_re)
if (match_groups) {
var arguments = match_groups[match_groups.length-1].split(',').map(arg => arg.trim())
arguments.forEach(function(arg) {
current_scope_stack.names_in_scope.push(arg)
current_scope_stack.fill_in_names.push(arg)
})
}
}
}
}
module.exports.scopes_and_names = scopes_and_names;
function add_parens(src) {
// thing.map(function () {
// -> thing.map(function() {})
var length = src.length;
var paren_queue = [];
for (var i = 0; i < length; ++i) {
var character = src[i];
if (character == '(') {
paren_queue.push(')')
} else if (character == '{') {
paren_queue.push('}')
} else if (character == ')' || character == '}') {
paren_queue.pop();
}
}
return src+'\n'+ paren_queue.reverse().join('');
}
module.exports.add_parens = add_parens;
function ast_to_list_of_scopes(node, scope_name, current_line_number, src, output) {
// produce a list of scopes with variable names in each scope:
// [
// {name: 'file': names_in_scope: ['module', 'clamp']},
// {name: 'function initialize_grid() {', names_in_scope: ['width', 'height']}]
// ]
var scope = {name: scope_name, names_in_scope: []}
var nodes = null;
if (node.type == 'Program') {
scope.names_in_scope.push('module')
nodes = node.body;
} else if (node.type == 'FunctionDeclaration' || node.type == 'FunctionExpression') {
node.params.forEach(param => scope.names_in_scope.push(param.name))
nodes = node.body.body;
} else if (node.type == 'BlockStatement') {
nodes = node.body;
} else if (node.type == 'CallExpression') {
nodes = node.arguments; //node.arguments[node.arguments.length-1].body;
} else if (node.type == 'IfStatement') {
nodes = node.consequent.body;
}
if (!nodes) return output;
// find declarations
nodes = nodes.filter(decl => decl.loc.start.line <= current_line_number);
nodes.forEach(decl => {
switch (decl.type) {
case 'VariableDeclaration':
decl.declarations.forEach(inner_decl => {
scope.names_in_scope.push(inner_decl.id.name)
})
return;
// case 'ExpressionStatement':
// return;
case 'ClassDeclaration':
scope.names_in_scope.push(decl.id.name);
return;
case 'FunctionDeclaration':
case 'FunctionExpression':
if (decl.id) {
scope.names_in_scope.push(decl.id.name)
}
return;
}
})
if (scope.names_in_scope.length > 0) {
output.push(scope);
}
const last_node = nodes[nodes.length-1];
if (!last_node) return output;
if (last_node.loc.start.line == current_line_number && last_node.loc.end.line == current_line_number) {
return output;
}
var current_line_src = src.split('\n')[last_node.loc.start.line-1];
if (last_node.type == 'FunctionDeclaration' || last_node.type == 'FunctionExpression') {
ast_to_list_of_scopes(last_node, current_line_src, current_line_number, src, output);
} else if (last_node.type == 'ExpressionStatement') {
ast_to_list_of_scopes(last_node.expression, current_line_src, current_line_number, src, output);
} else if (last_node.type == 'CallExpression') {
ast_to_list_of_scopes(last_node.arguments[last_node.arguments.length-1], current_line_src, current_line_number, src, output);
} else if (last_node.type == 'IfStatement') {
// find which branch of the if statement contains the current line
var test_node = last_node;
while (test_node.type == 'IfStatement') {
if (test_node.consequent.loc.start.line <= current_line_number && test_node.consequent.loc.end.line >= current_line_number) {
break
}
test_node = test_node.alternate;
}
ast_to_list_of_scopes(test_node, src.split('\n')[test_node.loc.start.line-1], current_line_number, src, output);
} else if (last_node.type == 'FunctionExpression') {
ast_to_list_of_scopes(last_node.body, current_line_src, current_line_number, src, output);
} else if (last_node.type == 'BlockStatement') {
ast_to_list_of_scopes(last_node.body, current_line_src, current_line_number, src, output);
} else {
// console.log('error-causing node:', last_node)
// throw 'unhandled AST node type: '+last_node.type;
}
return output;
}
function ast_node_to_js(node, scopes) {
if (!node.type) { // array of nodes
var nodes = node;
var output = '';
var done = false;
nodes.forEach(node => {
if (done) { return; }
if (scopes && node.loc.end.line == current_line_number && node.loc.start.line == current_line_number) {
output += `replugger_values = {};\n${scopes.map(scope => { return scope.names_in_scope.map(name => `try { replugger_values['${name}'] = ${name} } catch(e) { replugger_values['${name}'] = '...' }`).join('\n')}).join('\n')}\n${ast_node_to_js(node, scopes)}`
done = true;
return
}
output += ast_node_to_js(node, scopes)+'\n'
})
return output;
}
switch (node.type) {
case 'Program':
return `try {
${ast_node_to_js(node.body, scopes)}
} catch (e) {
replugger_values = {};
${scopes.map(scope => { return scope.names_in_scope.map(name => `try { replugger_values['${name}'] = ${name} } catch(e) { replugger_values['${name}'] = '...' }`).join('\n')}).join('\n')}
}
`
case 'ExpressionStatement':
if (node.loc.start.line < current_line_number && node.loc.end.line >= current_line_number) {
var test_node = node.expression;
// find the part of this expression that the cursor is in
while (test_node.type == 'CallExpression') {
test_node = test_node.arguments[test_node.arguments.length-1];
}
return `// function as argument
${ast_node_to_js(test_node, scopes)}`
}
return ast_node_to_js(node.expression, scopes);
case 'ClassDeclaration':
return `class ${ast_node_to_js(node.id, scopes)} ${ast_node_to_js(node.body, scopes)}`;
case 'ClassProperty':
return ``;
case 'MethodDefinition':
return `${ast_node_to_js(node.key, scopes)}(${node.value.params.map(param => param.name).join(', ')}) ${ast_node_to_js(node.value.body, scopes)}`;
case 'ClassBody':
case 'BlockStatement':
return `{
${ast_node_to_js(node.body, scopes)}
}`
case 'VariableDeclaration':
var output = ''
node.declarations.forEach((decl,i) => {
output += ast_node_to_js(decl, scopes);
if (i !== node.declarations.length-1) {
output += ',\n'
} else {
output += ';'
}
});
return output;
case 'IfStatement':
if (node.loc.start.line <= current_line_number && node.loc.end.line >= current_line_number) {
// find which branch the cursor is in
var test_node = node;
while (test_node.type == 'IfStatement') {
if (test_node.consequent.loc.start.line <= current_line_number && test_node.consequent.loc.end.line >= current_line_number) {
break
}
test_node = test_node.alternate;
}
return `// if ${ast_node_to_js(test_node.test, scopes)}
${ast_node_to_js(test_node.consequent.body, scopes)}
`
}
var else_clause = '';
if (node.alternate) {
else_clause = `else ${ast_node_to_js(node.alternate, scopes)}`
}
return `if (${ast_node_to_js(node.test, scopes)}) ${ast_node_to_js(node.consequent, scopes)} ${else_clause}`;
case 'ConditionalExpression':
return `${ast_node_to_js(node.test, scopes)} ? ${ast_node_to_js(node.consequent, scopes)} : ${ast_node_to_js(node.alternate, scopes)}`
case 'AssignmentExpression':
return `${ast_node_to_js(node.left, scopes)} ${node.operator} ${ast_node_to_js(node.right, scopes)}`;
case 'MemberExpression':
if (node.computed) {
return `${ast_node_to_js(node.object, scopes)}[${ast_node_to_js(node.property, scopes)}]`
} else {
return `${ast_node_to_js(node.object, scopes)}.${ast_node_to_js(node.property, scopes)}`
}
case 'VariableDeclarator':
if (variable_overrides[current_line_number] && node.id.name in variable_overrides[current_line_number]) {
return `var ${node.id.name} = ${variable_overrides[current_line_number][node.id.name]}`;
}
return `var ${node.id.name} = ${ast_node_to_js(node.init, scopes)}`;
case 'NewExpression':
var arguments_str = '';
node.arguments.forEach((arg,i) => {
arguments_str += ast_node_to_js(arg, scopes)+ (i == node.arguments.length-1 ? '' : ', ');
})
return `new ${ast_node_to_js(node.callee, scopes)}(${arguments_str})`;
case 'CallExpression':
var arguments_str = '';
node.arguments.forEach((arg,i) => {
arguments_str += ast_node_to_js(arg, scopes)+ (i == node.arguments.length-1 ? '' : ', ');
})
return `${ast_node_to_js(node.callee, scopes)}(${arguments_str})`;
case 'FunctionExpression':
if (node.loc.start.line <= current_line_number && node.loc.end.line >= current_line_number) {
return `{
${node.params.map(param => `var ${param.name} = ${variable_overrides[current_line_number] ? variable_overrides[current_line_number][param.name] : 'null'};`).join('\n')}
${ast_node_to_js(node.body, scopes)}
}`
} else {
var params_str = '';
node.params.forEach((param,i) => {
params_str += ast_node_to_js(param, scopes)+ (i == node.params.length-1 ? '' : ', ');
})
return `${node.async ? 'async ':''} function(${params_str}) ${ast_node_to_js(node.body, scopes)}`;
}
case 'FunctionDeclaration':
if (node.loc.start.line <= current_line_number && node.loc.end.line >= current_line_number) {
return `{ // function ${ast_node_to_js(node.id, scopes)}
${node.params.map(param => `var ${param.name} = null;`).join('\n')}
${ast_node_to_js(node.body, scopes)}
}`
} else {
var params_str = '';
node.params.forEach((param,i) => {
params_str += ast_node_to_js(param, scopes)+ (i == node.params.length-1 ? '' : ', ');
})
return `${node.async ? 'async ':''}function ${ast_node_to_js(node.id, scopes)}(${params_str}) ${ast_node_to_js(node.body, scopes)}`;
}
case 'ArrowFunctionExpression':
return `(${node.params.map(param => ast_node_to_js(param, scopes)).join(', ')}) => ${ast_node_to_js(node.body, scopes)}`
case 'ForStatement':
return `for (${ast_node_to_js(node.init, scopes)} ${ast_node_to_js(node.test, scopes)}; ${ast_node_to_js(node.update, scopes)}) ${ast_node_to_js(node.body, scopes)}`
case 'ReturnStatement':
return `return ${node.argument ? ast_node_to_js(node.argument, scopes) : ''};`
case 'UnaryExpression':
return `${node.operator} ${ast_node_to_js(node.argument, scopes)}`
case 'BinaryExpression':
case 'LogicalExpression':
return `${ast_node_to_js(node.left, scopes)} ${node.operator} ${ast_node_to_js(node.right, scopes)}`;
case 'UpdateExpression':
if (node.prefix) {
return `${node.operator}${ast_node_to_js(node.argument, scopes)}`;
}
return `${ast_node_to_js(node.argument, scopes)}${node.operator}`;
case 'TryStatement':
return `try ${ast_node_to_js(node.block, scopes)} ${ast_node_to_js(node.handler, scopes)}`
case 'CatchClause':
return `catch(${node.param.name || ''}) ${ast_node_to_js(node.body, scopes)}`
case 'ArrayExpression':
var output = '';
node.elements.forEach(element => {
output += ast_node_to_js(element, scopes);
if (i !== node.declarations.length-1) {
output += ' ,\n'
}
})
return `[${output}]`
case 'ObjectExpression':
return `{${node.properties.map(prop => ast_node_to_js(prop, scopes))}}`
case 'Property':
return `${ast_node_to_js(node.key, scopes)}: ${ast_node_to_js(node.value, scopes)}`
case 'Identifier':
return node.name;
case 'ThisExpression':
return 'this';
case 'TemplateLiteral':
return '`'+ ast_node_to_js(node.quasis, scopes) + '`'
case 'TemplateElement':
return node.value.raw;
case 'Literal':
return node.raw;
case 'EmptyStatement':
return ''
default:
console.log(node)
return '!!!UH OH!!!'
}
}