-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.js
225 lines (190 loc) · 6.34 KB
/
generate.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
var escodegen = require("escodegen");
var FOLLOW = "F";
var END = "_end";
var DEPTH = 4;
var singleElementLists = false;
var nodeFeatures =
{
'VariableDeclaration':['declarations',['kind','var']],
'VariableDeclarator':['init', 'id'],
'BinaryExpression':['left','right','operator'],
'UnaryExpression':['left','argument','operator'],
'LogicalExpression':['left','right','operator'],
'AssignmentExpression':['left','right',['operator','=']],
'NewExpression':['callee','arguments'],
'CallExpression':['arguments','callee'],
'Identifier':['name'],
'Literal':['raw'],
'ReturnStatement':['argument'],
'UnaryExpression':['operator','argument',['prefix',true]],
'MemberExpression':['computed','object','property'],
'IfStatement':['test','consequent','alternate'],
'ForStatement':['init','test','update','body'],
'ForInStatement':['left','right','body'],
'WhileStatement':['test','body'],
'BlockStatement':['body'],
'FunctionDeclaration':['params','id','body'],
'FunctionExpression':['params','body'],
'ConditionalExpression':['test','consequent','alternate'],
'ArrayExpression':['elements'],
'ObjectExpression':['properties'],
'Property':['key','value',['kind','init']],
'TryStatement':['block','guardedHandlers','handlers','finalizer'],
'CatchClause':['body',['param',{'type':'Identifier','name':'e'}]],
'ThrowStatement':['argument'],
'Program':['body'],
'UpdateExpression':['operator','argument'],
'ThisExpression':[],
'EmptyStatement': [],
'ContinueStatement':[],
'BreakStatement':[],
'SequenceExpression':['expressions'],
'_end':[]
};
function generateProgram(model)
{
return {
"type":"Program",
"body":generateList(model, ['Program', 'body'])
};
}
function generateList(model, path)
{
var nodes = [];
var node = generateNode(model, path);
if (singleElementLists)
{
if (node.type == END)
return [];
//while (node.type == END)
//node = generateNode(model, path);
return [node];
}
while (node.type != END) {
var type = (node.type == "ExpressionStatement" ? node.expression.type : node.type);
nodes.push(node);
path = path.concat(type, FOLLOW);
node = generateNode(model, path);
}
return nodes;
}
function generateNode(model, path, sel, depth)
{
if (depth) DEPTH = depth;
if (sel != undefined)
singleElementLists = sel;
if (!path || path.length == 0)
{
return generateProgram(model);
}
//cut off the path at given depth
var maxPathLength = -(DEPTH)*2;
path = path.slice(maxPathLength);
// console.log("generating with path "+path);
var prevTransition = path[path.length-1];
var prevNodeType = path[path.length-2];
var map = model;
//walk the model
for (var i = 0; i < path.length; i++) {
map = map[path[i]];
}
//skip past all the _nulls if there are any (ie path isn't long enough)
while (map._null) {
map = map._null;
}
var newType = pickNodeType(map);
if (newType == null) {
//console.log("Unable to pick node type at", path, " map = ", map);
throw new Error("Unable to pick node type at [" + path.join(", ") + "]");
}
//with operators/identifier names, the type is the literal thing
if (prevTransition == 'operator' ||
prevTransition == 'raw' ||
(prevNodeType == 'Identifier' && prevTransition == 'name'))
//escape any variables that use underscores with two, our reserved variables use only one
return newType.replace(/__/g, "_");
//'computed' (for member expressions) should be a boolean
if (prevTransition == 'computed')
return (newType === "true");
//means the value for this new node is literally null, not a literal which happens to be "null"
if (newType == "null")
return null;
var node = instantiateNode(newType, model, path);
//wrap an expression statement around it if it was flagged by parse to require
if (map._expr && newType in map._expr) {
node = {
type: "ExpressionStatement",
expression: node
};
}
return node;
}
function pickNodeType(map)
{
var type;
var total = map._total || 0;
var pick = Math.random() * total;
var sum = 0;
for (var key in map) {
if (key == "_total") continue;
if (key == "_expr") continue;
var count = map[key];
sum += count;
if (sum >= pick) {
type = key;
break;
}
}
return type;
}
function instantiateNode(type, model, path)
{
var node = {'type':type};
var features = nodeFeatures[type];
if (!features)
{
throw new Error("No known features for node type "+type+". path = "+path);
}
for (var i = 0; i < features.length; i++)
{
var feature = features[i];
var feature_append = '';
if (type == 'MemberExpression' && feature == 'property' && !node.computed)
feature_append = '_id';
//key with a default value, ie, it shouldn't be generated. form is feature = [key, value]
if (feature instanceof Array)
{
node[feature[0]] = feature[1];
}
else
{
var newPath = path.concat(type, feature+feature_append);
if (feature == "properties" || feature == "arguments" ||
feature == "params" || feature == "declarations" ||
feature == "elements" || feature == "guardedHandlers" ||
feature == "handlers" || feature == "expressions" ||
(feature == "body" && type == "BlockStatement")) //only BlockStatement's body is a list, Program's body is a BlockStatement
{
node[feature] = generateList(model, newPath);
}
else
{
node[feature] = generateNode(model, newPath);
}
}
}
if (type == "Literal")
{
//turn raw into a value, needed by escodegen, with eval
node["value"] = eval(node.raw);
var my_escape = function (string) {
if (typeof string != "string") return string;
return string.replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&");
};
if (typeof node.value == "string")
node.value = my_escape(node.value);
}
return node;
}
module.exports.generateProgram = generateProgram;
module.exports.generateNode = generateNode;