Debian Codegraph @

bin/make-builder

raw
1 #!/usr/bin/env node
2
3 /* jshint node:true, unused:true, undef:true */
4
5 var recast = require('recast');
6 var types = recast.types;
7 var b = types.builders;
8 var n = types.namedTypes;
9 var assert = require('assert');
10 var vm = require('vm');
11
12 var BUILD_PARAMS_CACHE = {
13 'ThisExpression': [],
14 'BreakStatement': []
15 };
16
17 /**
18 * Get the named parameters to pass the named builder.
19 *
20 * @param {!string} type
21 * @return {[string]}
22 */
23 function buildParamsForType(type) {
24 var entry = BUILD_PARAMS_CACHE[type];
25 if (entry) {
26 return entry;
27 }
28
29 try {
30 b[builderNameForType(type)]();
31 assert.ok(false, 'should have failed to build ' + type + ' with no params');
32 } catch (ex) {
33 var message = ex.message;
34 var typeIndex = message.indexOf(type);
35 var openParenIndex = message.indexOf('(', typeIndex);
36 var closeParenIndex = message.indexOf(')', openParenIndex);
37
38 assert.ok(
39 closeParenIndex >= 0,
40 'unexpected exception format trying to parse build params: ' + message
41 );
42
43 var paramsList = message.slice(openParenIndex, closeParenIndex);
44 var result = [];
45 paramsList.replace(/"([^"]+)"/g, function(_, name) {
46 result.push(name);
47 });
48 BUILD_PARAMS_CACHE[type] = result;
49 return result;
50 }
51 }
52
53 /**
54 * Get the name of the builder given a node type. For example, "ThisExpression"
55 * becomes "thisExpression".
56 *
57 * @param {!string} type
58 * @return {!string}
59 */
60 function builderNameForType(type) {
61 return type[0].toLowerCase() + type.slice(1);
62 }
63
64 /**
65 * Read all the contents of STDIN and call back with it.
66 *
67 * @param {function(!string)} callback
68 */
69 function readStdin(callback) {
70 var stdin = '';
71
72 process.stdin.setEncoding('utf8');
73
74 process.stdin.on('readable', function() {
75 var chunk = process.stdin.read();
76 if (chunk !== null) {
77 stdin += chunk;
78 }
79 });
80
81 process.stdin.on('end', function() {
82 callback(stdin);
83 });
84 }
85
86 /**
87 * Makes the AST for a JavaScript program that will build the given node using
88 * the builder functions from the ast-types package.
89 *
90 * @param {ast-types.Node} node
91 * @param {{string: string}} replacements
92 * @return {ast-types.Node}
93 */
94 function makeBuilder(node, replacements) {
95 if (n.File.check(node)) {
96 return b.expressionStatement(makeBuilder(node.program, replacements));
97 } else if (n.Program.check(node)) {
98 return b.callExpression(
99 b.memberExpression(
100 b.identifier('b'),
101 b.identifier('program'),
102 false
103 ),
104 [b.arrayExpression(node.body.map(function(statement) {
105 return makeBuilder(statement, replacements);
106 }))]
107 );
108 } else if (Array.isArray(node)) {
109 return b.arrayExpression(
110 node.map(function(item) { return makeBuilder(item, replacements); })
111 );
112 } else if (node && node.constructor === RegExp) {
113 return b.literal(node);
114 }
115
116 assert.ok(
117 n.Node.check(node),
118 'unexpected node type: ' + JSON.stringify(node)
119 );
120
121 if (n.Identifier.check(node)) {
122 var replacement = replacements[node.name];
123 if (replacement) {
124 var newReplacements = Object.create(replacements);
125 newReplacements[node.name] = undefined;
126 return recast.parse(replacement).program.body[0].expression;
127 }
128 }
129
130 return b.callExpression(
131 b.memberExpression(
132 b.identifier('b'),
133 b.identifier(node.type[0].toLowerCase() + node.type.slice(1)),
134 false
135 ),
136 buildParamsForType(node.type).reduce(function(result, key) {
137 if (key !== 'type' && key !== 'loc') {
138 var value;
139 if (node[key] !== null && typeof node[key] === 'object') {
140 value = makeBuilder(node[key], replacements);
141 } else if (node[key] !== undefined) {
142 value = b.literal(node[key]);
143 }
144
145 if (value) {
146 result.push(value);
147 }
148 }
149
150 return result;
151 }, [])
152 );
153 }
154
155 /**
156 * Determines whether, when printed, the node should be on multiple lines.
157 *
158 * @param {ast-types.Node}
159 * @param {boolean}
160 */
161 function isMultiline(node) {
162 switch (node.type) {
163 case 'ExpressionStatement':
164 return isMultiline(node.expression);
165
166 case 'CallExpression':
167 return node.arguments.length > 1 || node.arguments.some(isMultiline);
168
169 case 'MemberExpression':
170 return isMultiline(node.object) || isMultiline(node.property);
171
172 case 'Identifier':
173 return false;
174
175 case 'ArrayExpression':
176 return node.elements.length > 1 || (node.elements.length === 1 && isMultiline(node.elements[0]));
177
178 case 'Literal':
179 return (node.raw || JSON.stringify(node.value)).indexOf('\n') >= 0;
180
181 default:
182 throw new Error('unexpected node type: ' + node.type);
183 }
184 }
185
186 /**
187 * @const
188 */
189 var INDENT = ' ';
190
191 /**
192 * Prints the given list of AST nodes as JavaScript as part of a list of array
193 * elements or function arguments.
194 *
195 * @param {[ast-types.Node]} list
196 * @param {string=} indent
197 */
198 function printListLines(list, indent) {
199 if (!indent) { indent = ''; }
200
201 var output = '';
202
203 list.forEach(function(item, i) {
204 output += indent + print(item, indent);
205 if (i !== list.length - 1) {
206 output += ',';
207 }
208 output += '\n';
209 });
210
211 return output;
212 }
213
214 /**
215 * Prints the given AST node as JavaScript, formatted so as to favor shorter
216 * lines. For example, this:
217 *
218 * b.callExpression(b.identifier('a'), [b.literal(1), b.literal(2)]);
219 *
220 * Would be printed as:
221 *
222 * b.callExpression(
223 * b.identifier('a'),
224 * [
225 * b.literal(1),
226 * b.literal(2)
227 * ]
228 * )
229 *
230 * @param {ast-types.Node} node
231 * @param {string=} indent
232 * @return {string}
233 */
234 function print(node, indent) {
235 if (!indent) { indent = ''; }
236
237 switch (node.type) {
238 case 'ExpressionStatement':
239 return print(node.expression, indent) + ';';
240
241 case 'CallExpression':
242 if (isMultiline(node)) {
243 if (node.arguments.length === 1 && node.arguments[0].type === 'ArrayExpression') {
244 return print(node.callee, indent) + '([\n' +
245 printListLines(node.arguments[0].elements, indent + INDENT) +
246 indent + '])';
247 } else {
248 return print(node.callee, indent) + '(\n' +
249 printListLines(node.arguments, indent + INDENT) +
250 indent + ')';
251 }
252 }
253
254 return print(node.callee, indent) + '(' +
255 node.arguments.map(function(arg) { return print(arg, indent); }).join(', ') +
256 ')';
257
258 case 'MemberExpression':
259 if (node.computed) {
260 return print(node.object, indent) + '[' + print(node.property, indent) + ']';
261 } else {
262 return print(node.object, indent) + '.' + print(node.property, indent);
263 }
264 break;
265
266 case 'Identifier':
267 return node.name;
268
269 case 'ArrayExpression':
270 if (isMultiline(node)) {
271 return '[\n' +
272 printListLines(node.elements, indent + INDENT) +
273 indent + ']';
274 } else {
275 return '[' +
276 node.elements.map(function(element) { return print(element, indent); }).join(', ') +
277 ']';
278 }
279 break;
280
281 case 'Literal':
282 if (typeof node.value === 'string') {
283 return "'" + node.value.replace(/'/g, "\\'") + "'";
284 } else {
285 return node.raw || JSON.stringify(node.value);
286 }
287 break;
288
289 default:
290 throw new Error('unexpected node type: ' + node.type);
291 }
292 }
293
294 var replacements = process.argv.slice(2).reduce(function(map, arg) {
295 var parts = arg.split('=');
296 if (parts.length === 2) {
297 map[parts[0]] = parts[1];
298 }
299 return map;
300 }, {});
301
302 var TEST = process.argv.indexOf('--test') >= 0;
303
304 readStdin(function(stdin) {
305 var inputSource = stdin;
306 var inputAST = recast.parse(inputSource);
307 var body = inputAST.program.body;
308 var ast = inputAST.program;
309
310 if (body.length === 1) {
311 var statement = body[0];
312 // Favor processing just an expression if possible.
313 ast = n.ExpressionStatement.check(statement) ?
314 statement.expression : statement;
315 }
316
317 var code = print(makeBuilder(ast, replacements));
318
319 if (TEST) {
320 // verify the result
321 var context = { b: b };
322 vm.runInNewContext('result = ' + code, context);
323 var normalizedInputSource = recast.prettyPrint(inputAST).code;
324 var normalizedBuiltSource = recast.prettyPrint(context.result).code;
325 assert.equal(
326 normalizedBuiltSource,
327 normalizedInputSource
328 );
329 }
330
331 process.stdout.write(code);
332 });