-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsxtypercore.ts
573 lines (512 loc) · 19.5 KB
/
jsxtypercore.ts
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// Uses esprima-fb to generate syntax tree of supplied JSX file, then traverses
// the syntax tree to generate TypeScript interfaces for props and state.
/// <reference path="Scripts/typings/node/node.d.ts" />
// To get estree.d.ts open Package Manager Console and type:
// Install-Package estree.TypeScript.DefinitelyTyped
/// <reference path="packages/estree.TypeScript.DefinitelyTyped.0.0.1/Content/Scripts/typings/estree/estree.d.ts" />
/// <reference path="Scripts/typings/estree/jsxtree.d.ts" />
var fs = require('fs'),
esprima = require('esprima-fb'),
estraverse = require('estraverse-fb');
// ------------------------------------------------------------------------------------------------
// Find React.createClass() statements.
// ------------------------------------------------------------------------------------------------
function traverseProgram(program: ESTree.Program): void {
for (var i = 0; i < program.body.length; i++) {
// Look for statements of the form: var MyClass = React.createClass({ ... });
if (program.body[i].type === "VariableDeclaration") {
var statement = <ESTree.VariableDeclaration>program.body[i];
var declarator = statement.declarations[0];
if (declarator.init.type == "CallExpression") {
var callExpression = <ESTree.CallExpression>declarator.init;
if (calleeIsReactCreateClass(callExpression.callee)) {
var id = <ESTree.Identifier>declarator.id;
addComponentClass(id.name);
traverseCreateClassCallExpression(callExpression);
}
}
}
}
}
/** Checks whether callee is React.createClass */
function calleeIsReactCreateClass(callee: ESTree.Expression): boolean {
if (callee.type != "MemberExpression") {
return false;
}
var memberExpression = <ESTree.MemberExpression>callee;
if (memberExpression.object.type != "Identifier" || memberExpression.property.type != "Identifier") {
return false;
}
var objIdentifier = <ESTree.Identifier>memberExpression.object;
var propIdentifier = <ESTree.Identifier>memberExpression.property;
if (objIdentifier.name != "React" || propIdentifier.name != "createClass") {
return false;
}
return true;
}
function traverseCreateClassCallExpression(callExpression: ESTree.CallExpression): void {
if (callExpression.arguments.length < 1 || callExpression.arguments[0].type != "ObjectExpression") {
throw constructError(302, "React.createClass() must be passed an object expression.", callExpression.loc);
}
var objectExpression = <ESTree.ObjectExpression>callExpression.arguments[0];
traverse(objectExpression);
extractCssNames(objectExpression);
}
function extractCssNames(node: ESTree.Node): void {
estraverse.traverse(node, {
enter: node => {
if (node.type === 'JSXElement') {
var jsxElement = <ESTree.JSXElement>node;
var attributes = jsxElement.openingElement.attributes;
for (var i = 0; i < attributes.length; i++) {
if (!attributes[i].name) {
continue;
}
var attrName = attributes[i].name.name;
if (attrName === 'class') {
throw constructError(303, "Use 'className' to specify css class, not 'class'.", attributes[i].name.loc);
}
else if (attrName === 'className' && attributes[i].value.type === "Literal") {
var literal = <ESTree.Literal>attributes[i].value;
addCssClassNames(<string>literal.value);
}
}
}
}
});
}
// ------------------------------------------------------------------------------------------------
// Traverse various types of nodes.
// The actual traverse happens in estraverse library. We only eavesdrop on that traverse here.
// ------------------------------------------------------------------------------------------------
function traverse(ast: ESTree.Node): void {
estraverse.traverse(ast, {
enter: node => {
switch (node.type) {
case 'MemberExpression':
case 'CallExpression':
var memberPath = traverseMemberExpression(node);
addMemberPath(memberPath);
return estraverse.VisitorOption.Skip;
case 'VariableDeclaration':
traverseVariableDeclaration(node);
return estraverse.VisitorOption.Skip;
case 'FunctionDeclaration':
case 'FunctionExpression':
pushScope();
break;
}
},
leave: node => {
switch (node.type) {
case 'FunctionDeclaration':
case 'FunctionExpression':
popScope();
break;
}
}
});
}
function traverseVariableDeclaration(declaration: ESTree.VariableDeclaration): void {
for (var i = 0; i < declaration.declarations.length; i++) {
var declarator = declaration.declarations[i];
if (declarator.id.type === 'Identifier' && declarator.init &&
(declarator.init.type === 'MemberExpression' ||
declarator.init.type === 'CallExpression')) {
var identifer = <ESTree.Identifier>declarator.id;
var memberExpression = <ESTree.MemberExpression>declarator.init;
var memberPath = traverseMemberExpression(memberExpression);
processVariableDeclaration(identifer, memberPath);
}
else if (declarator.init) {
traverse(declarator.init);
}
}
}
function traverseMemberExpression(expression: ESTree.MemberExpression): MemberPath {
var members: Member[] = [];
for (var node = <ESTree.Expression>expression; ;) {
if (node.type === 'MemberExpression') {
var memberExpression = <ESTree.MemberExpression>node;
if (memberExpression.computed) {
traverse(memberExpression.property);
}
members.unshift(new Member(memberExpression.property, memberExpression.computed));
node = memberExpression.object;
}
else if (node.type === 'CallExpression') {
members.unshift(new Member(node));
var callExpression = <ESTree.CallExpression>node;
if (callExpression.callee.type === 'FunctionExpression') {
var functionExpression = <ESTree.FunctionExpression>callExpression.callee;
pushScope();
traverse(functionExpression.body);
popScope();
}
for (var i = 0; i < callExpression.arguments.length; i++) {
traverse(callExpression.arguments[i]);
}
node = callExpression.callee;
}
else {
members.unshift(new Member(node));
break;
}
}
return new MemberPath(members);
}
// ------------------------------------------------------------------------------------------------
/** Represents a node in a member expression path */
class Member {
constructor(public node: ESTree.Expression, public isComputed = false) {
}
public isArrayIndexer(): boolean {
if (this.isComputed) {
return !isLiteralString(this.node);
}
else {
return false;
}
}
}
/** Represents a member expression path */
class MemberPath {
constructor(public path: Member[]) {
}
/** This is very limited, but works for the common case of copying an array element to a temp variable. */
public resolvePath(): Member[] {
if (this.path.length && this.path[0].node.type == 'Identifier') {
var identifier = <ESTree.Identifier>this.path[0].node;
var memberPath = resolve(identifier.name);
if (memberPath) {
var p = this.path.slice(1);
return memberPath.path.concat(p);
}
}
return this.path;
}
/** (For debugging) Reconstructs source code for the member path. */
public debug_getCode(): string {
var path = this.resolvePath();
var output: string[] = [];
for (var i = 0; i < path.length; i++) {
var node = path[i].node;
if (path[i].isComputed) {
if (path[i].isArrayIndexer()) {
output.push('[]');
}
else {
break;
}
}
else {
switch (node.type) {
case 'Identifier':
var identifier = <ESTree.Identifier>node;
output.push(identifier.name);
break;
case 'ThisExpression':
output.push('this');
break;
case 'CallExpression':
output.push('()');
break;
default:
output.push('~' + node.type + '~');
break;
}
}
if (i < path.length - 1) {
var nextMember = path[i + 1];
if (nextMember.node.type !== 'CallExpression' && !nextMember.isComputed) {
output.push('.');
}
}
}
return output.join('');
}
public addToFieldDict(propsDict: Field, stateDict: Field): void {
var path = this.resolvePath();
if (path.length >= 3 &&
path[0].node.type === 'ThisExpression' &&
path[1].node.type === 'Identifier') {
var identifier = <ESTree.Identifier>path[1].node;
var d: Field;
if (identifier.name === 'props')
d = propsDict;
else if (identifier.name === 'state')
d = stateDict;
else
return;
var key: string;
var field: Field;
for (var i = 2; i < path.length; i++) {
var node = path[i].node;
if (path[i].isComputed) {
if (path[i].isArrayIndexer()) {
key = 'Indexer';
field = { "nodeType": nodeTypes.Indexer };
}
else {
break;
}
}
else {
switch (node.type) {
case 'Identifier':
var identifier = <ESTree.Identifier>node;
key = '.' + identifier.name;
field = { "nodeType": nodeTypes.Identifier };
break;
case 'CallExpression':
key = 'CallExpression';
field = { "nodeType": nodeTypes.CallExpression };
break;
}
}
d = d[key] || (d[key] = field);
}
}
}
}
function isLiteralString(node: ESTree.Expression): boolean {
if (node.type === 'Literal') {
var literal = <ESTree.Literal>node;
return (typeof literal.value === 'string');
}
return false;
}
var nodeTypes = {
Identifier: 'Identifier',
CallExpression: 'CallExpression',
Indexer: 'Indexer'
};
interface Field {
nodeType?: string;
identifier?: string;
}
interface FieldDict { [fieldName: string]: FieldDict; };
function constructError(errorCode: number, errorMessage: string, loc?: ESTree.SourceLocation): Error {
if (loc) {
return new Error(`Error ${errorCode} near line ${loc.start.line}, column ${loc.start.column}: ${errorMessage}`);
}
else {
return new Error(`Error ${errorCode}: ${errorMessage}`);
}
}
// ------------------------------------------------------------------------------------------------
// Simple scope implementation
// Intended to handle the common case of copying an array element to a temp variable.
// ------------------------------------------------------------------------------------------------
interface Scope { [symbol: string]: MemberPath };
var scopeChain: Scope[] = [{}];
function pushScope(): void {
scopeChain.push({});
}
function popScope(): void {
scopeChain.pop();
}
function addToCurrentScope(name: string, value: MemberPath): void {
var scope = scopeChain[scopeChain.length - 1];
scope[name] = value;
}
function resolve(name: string): MemberPath {
for (var i = scopeChain.length - 1; i >= 0; i--) {
if (name in scopeChain[i]) {
return scopeChain[i][name];
}
}
return null;
}
function debug_printScopeChain(): void {
console.log();
for (var i = 0; i < scopeChain.length; i++) {
var scope = scopeChain[i];
console.log("scope");
console.log("=====");
for (var symbol in scope) {
console.log(symbol + " = " + scope[symbol].debug_getCode());
}
console.log();
}
}
// ------------------------------------------------------------------------------------------------
// TypeScript generation
// ------------------------------------------------------------------------------------------------
enum FieldType { Object, Scalar, FunctionCall };
interface ComponentClass {
className: string;
propsDict: FieldDict;
stateDict: FieldDict;
cssClassNames: { [cssClass: string]: string };
}
var componentClasses: ComponentClass[] = [];
function addComponentClass(className: string): void {
componentClasses.push({
className: className,
propsDict: {},
stateDict: {},
cssClassNames: {}
});
}
function addMemberPath(memberPath: MemberPath): void {
var c = componentClasses[componentClasses.length - 1];
memberPath.addToFieldDict(c.propsDict, c.stateDict);
}
function processVariableDeclaration(identifier: ESTree.Identifier, memberPath: MemberPath) {
addToCurrentScope(identifier.name, memberPath);
var c = componentClasses[componentClasses.length - 1];
memberPath.addToFieldDict(c.propsDict, c.stateDict);
}
function addCssClassNames(cssClassNames: string): void {
var c = componentClasses[componentClasses.length - 1];
var names = cssClassNames.split(' ');
for (var i = 0; i < names.length; i++) {
c.cssClassNames[names[i]] = '';
}
}
function getFieldType(dict: any): FieldType {
if (dict.CallExpression) {
return FieldType.FunctionCall;
}
var fieldCount = 0;
for (var key in dict) {
if (key[0] === '.') {
fieldCount++;
}
}
return fieldCount > 0 ? FieldType.Object : FieldType.Scalar;
}
function findArrayIndexerKey(dict: any): string {
for (var key in dict) {
var field = <Field>dict[key];
if (field.nodeType === nodeTypes.Indexer) {
return key;
}
}
return null;
}
function constructCssNameForTS(cssClassName: string): string {
var parts = cssClassName.split('-');
for (var i = 1; i < parts.length; i++) {
parts[i] = parts[i].substr(0, 1).toUpperCase() + parts[i].substr(1);
}
return parts.join('');
}
function outputInterfaces(output: string[], component: ComponentClass): void {
// Uncomment next two lines for debugging.
// console.log('props = ' + JSON.stringify(component.propsDict));
// console.log('state = ' + JSON.stringify(component.stateDict));
output.push(`interface ${component.className}Props {`);
outputFields(output, component.propsDict, 1);
output.push(`}`);
output.push('');
output.push(`interface ${component.className}State {`);
outputFields(output, component.stateDict, 1);
output.push(`}`);
output.push('');
output.push(`declare var ${component.className}: React.ComponentClass<${component.className}Props>;`);
output.push('');
output.push(`var ${component.className}Selectors = {`);
var cssClassNames = Object.keys(component.cssClassNames);
for (var i = 0; i < cssClassNames.length; i++) {
var cssName = cssClassNames[i];
var tsName = constructCssNameForTS(cssName);
var sep = (i < cssClassNames.length - 1) ? ',' : '';
output.push(` ${tsName}: '.${cssName}'${sep}`);
}
output.push('};');
output.push('');
}
function outputFields(output: string[], dict: FieldDict, indentationLevel: number): void {
for (var key in dict) {
if (key[0] !== '.') {
continue;
}
var indent = '';
for (var i = 0; i < indentationLevel; i++) {
indent = indent + ' ';
}
var field = <Field>dict[key];
var name = key.substr(1);
var arrayIndexerKey = findArrayIndexerKey(dict[key]);
var arrayNotation = arrayIndexerKey ? '[]' : '';
var fieldsDict = dict[key];
if (arrayIndexerKey) {
fieldsDict = fieldsDict[arrayIndexerKey];
}
var fieldType = getFieldType(fieldsDict);
if (fieldType === FieldType.Object) {
output.push(`${indent}${name}: {`);
outputFields(output, fieldsDict, indentationLevel + 1);
output.push(`${indent}}${arrayNotation};`);
}
else if (fieldType === FieldType.FunctionCall) {
var returnType = getFunctionReturnType(fieldsDict['CallExpression']);
output.push(`${indent}${name}: { (...args: any[]): ${returnType} }${arrayNotation};`);
}
else if (fieldType === FieldType.Scalar) {
output.push(`${indent}${name}: any${arrayNotation};`);
}
}
}
function getFunctionReturnType(dict: FieldDict): string {
var arrayNotation = '';
var arrayIndexerKey = findArrayIndexerKey(dict);
if (arrayIndexerKey) {
dict = dict[arrayIndexerKey];
arrayNotation = '[]';
}
var returnType = getFieldType(dict);
if (returnType === FieldType.Scalar) {
return `any${arrayNotation}`;
}
else if (returnType === FieldType.FunctionCall) {
return `{ (...args: any[]): any }${arrayNotation}`;
}
else {
var output: string[] = [];
output.push('{');
outputFields(output, dict, -1000);
output.push(`}${arrayNotation}`);
return output.join(' ');
}
}
function generateTypeScript(jsxText: string, callback: (err: Error, tsText: string) => void): void {
try {
var program = esprima.parse(jsxText, { loc: true });
}
catch (ex) {
callback(new Error(`parser error: ${ex.message}`), null);
return;
}
try {
traverseProgram(program);
}
catch (ex) {
callback(ex, null);
return;
}
var output: string[] = [];
output.push('// This file was automatically generated by jsxtyper. Do not modify by hand!');
output.push('');
var count = 0;
for (var i = 0; i < componentClasses.length; i++) {
if (componentClasses[i].className) {
outputInterfaces(output, componentClasses[i]);
count++;
}
}
if (!count) {
var messages = <string[]>[];
messages.push("Did not find any valid React components.");
messages.push("Only class definitions in the following format are recognized: ");
messages.push(" var MyClass = React.createClass({ ... });");
messages.push("");
callback(new Error(messages.join('\n')), null);
}
else {
callback(null, output.join('\n'));
}
}
module.exports.generateTypeScript = generateTypeScript;