-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.js
96 lines (91 loc) · 2.52 KB
/
parse.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
const recast = require('recast')
const { variableDeclaration, variableDeclarator, functionExpression } = recast.types.builders // "moulds: for changing code"
const code = `
function multiply(a, b) {
// return the result of a multiply b
return (a * b)
}
`
// parse code
const ast = recast.parse(code)
// get parse code
const multiply = ast.program.body[0]
// print
console.log(multiply)
/**
* print result like this: FunctionDeclaration
*/
// FunctionDeclaration {
// type: 'FunctionDeclaration',
// id:
// Identifier {
// type: 'Identifier',
// name: 'multiply',
// loc:
// { start: [Object],
// end: [Object],
// lines: [Lines],
// tokens: [Array],
// indent: 4 } },
// params:
// [ Identifier { type: 'Identifier', name: 'a', loc: [Object] },
// Identifier { type: 'Identifier', name: 'b', loc: [Object] } ],
// body:
// BlockStatement {
// type: 'BlockStatement',
// body: [ [ReturnStatement] ],
// loc:
// { start: [Object],
// end: [Object],
// lines: [Lines],
// tokens: [Array],
// indent: 4 } },
// generator: false,
// expression: false,
// async: false,
// loc:
// { start: { line: 2, column: 4, token: 0 },
// end: { line: 5, column: 5, token: 15 },
// lines:
// Lines {
// infos: [Array],
// mappings: [],
// cachedSourceMap: null,
// cachedTabWidth: undefined,
// length: 6,
// name: null },
// tokens:
// [ [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object],
// [Object]
// ],
// indent: 4
// }
// }
// use ast to convert function declaration to function expression,
// like const multiply = function(a, b) { return (a * b) }
ast.program.body[0] = variableDeclaration("const", [
variableDeclarator(multiply.id, functionExpression(
null, // Anonymize the function expression.
multiply.params,
multiply.body
))
])
// revert to source code
const output = recast.print(ast).code
// beauty ouptput code with two tab width
const formatOutput = recast.prettyPrint(ast, { tabWidth: 2 }).code
console.log(output)
console.log(formatOutput)