/
type.js
82 lines (68 loc) · 2.59 KB
/
type.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
module.exports = function(jsdoc) {
jsdoc
.registerParser('type', function(comment) {
return { jsType : require('./util/js-type').parse(comment) };
})
.registerBuilder('type', function(tag, jsdocNode, _, astNode) {
var res = buildTypeNode(jsdocNode, astNode);
res.jsType = tag.jsType;
return res;
})
.registerBuilder(function(tags, curJsdocNode, parentJsdocNode, astNode) {
if(curJsdocNode === parentJsdocNode) {
return buildTypeNode(curJsdocNode, astNode);
}
});
};
function buildTypeNode(jsdocNode, astNode) {
switch(astNode.type) {
case 'FunctionExpression':
case 'FunctionDeclaration':
return { jsdocType : 'type', jsType : 'Function' };
case 'VariableDeclaration':
return buildTypeNode(jsdocNode, astNode.declarations[0]);
case 'VariableDeclarator':
return astNode.init?
buildTypeNode(jsdocNode, astNode.init) :
buildUnknownTypeNode();
case 'Property':
switch(astNode.value.type) {
case 'FunctionExpression':
return buildTypeNodeInProperty(jsdocNode, astNode, 'Function');
case 'Literal':
var value = astNode.value.value,
typeNode = buildTypeNodeInProperty(jsdocNode, astNode, getLiteralJsType(value));
typeNode.jsValue = value;
return typeNode;
default:
return buildTypeNodeInProperty(jsdocNode, astNode, '*');
}
case 'Literal':
return {
jsdocType : 'type',
jsType : getLiteralJsType(astNode.value),
jsValue : astNode.value
};
case 'ObjectExpression':
return { jsdocType : 'type', jsType : 'Object', props : [] };
default:
return buildUnknownTypeNode();
}
}
function buildTypeNodeInProperty(jsdocNode, astNode, jsType) {
if(jsdocNode.jsdocType !== 'type' || jsdocNode.jsType !== 'Object')
throw Error('Can not add property to non-object node');
var res = { jsdocType : 'type', jsType : jsType };
jsdocNode.props.push({
key : astNode.key.value || astNode.key.name,
val : res
});
return res;
}
function buildUnknownTypeNode() {
return { jsdocType : 'type', jsType : '*' };
}
function getLiteralJsType(value) {
var typeOfValue = typeof value;
return typeOfValue[0].toUpperCase() + typeOfValue.substr(1);
}