forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 2
/
validators.js
107 lines (93 loc) 路 2.67 KB
/
validators.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
import {
DEPRECATED_ALIASES,
DEPRECATED_KEYS,
FLIPPED_ALIAS_KEYS,
NODE_FIELDS,
PLACEHOLDERS,
PLACEHOLDERS_FLIPPED_ALIAS,
VISITOR_KEYS,
} from "../../lib/index.js";
const has = Function.call.bind(Object.prototype.hasOwnProperty);
function buildCases(arr) {
return arr.map(key => `case ${JSON.stringify(key)}:`).join("") + "break;";
}
function addIsHelper(type, aliasKeys, deprecated) {
const targetType = JSON.stringify(type);
let cases = "";
if (aliasKeys) {
cases = buildCases(aliasKeys);
}
const placeholderTypes = [];
if (PLACEHOLDERS.includes(type) && has(FLIPPED_ALIAS_KEYS, type)) {
placeholderTypes.push(type);
}
if (has(PLACEHOLDERS_FLIPPED_ALIAS, type)) {
placeholderTypes.push(...PLACEHOLDERS_FLIPPED_ALIAS[type]);
}
if (placeholderTypes.length > 0) {
cases += `
case "Placeholder":
switch ((node as t.Placeholder).expectedNode) {
${buildCases(placeholderTypes)}
default:
return false;
}
break;`;
}
const result =
NODE_FIELDS[type] || FLIPPED_ALIAS_KEYS[type]
? `node is t.${type}`
: "boolean";
return `export function is${type}(node: object | null | undefined, opts?: object | null): ${result} {
${deprecated || ""}
if (!node) return false;
${
cases
? `
switch((node as t.Node).type){
${cases}
default:
return false;
}`
: `if ((node as t.Node).type !== ${targetType}) return false;`
}
return opts == null || shallowEqual(node, opts);
}
`;
}
export default function generateValidators() {
let output = `/*
* This file is auto-generated! Do not modify it directly.
* To re-generate run 'make build'
*/
import shallowEqual from "../../utils/shallowEqual";
import type * as t from "../..";
import deprecationWarning from "../../utils/deprecationWarning";
\n`;
Object.keys(VISITOR_KEYS).forEach(type => {
output += addIsHelper(type);
});
Object.keys(FLIPPED_ALIAS_KEYS)
.filter(
type => !Object.prototype.hasOwnProperty.call(DEPRECATED_ALIASES, type)
)
.forEach(type => {
output += addIsHelper(type, FLIPPED_ALIAS_KEYS[type]);
});
Object.keys(DEPRECATED_KEYS).forEach(type => {
output += addIsHelper(
type,
null,
`deprecationWarning("is${type}", "is${DEPRECATED_KEYS[type]}")`
);
});
Object.keys(DEPRECATED_ALIASES).forEach(type => {
const newType = DEPRECATED_ALIASES[type];
output += `export function is${type}(node: object | null | undefined, opts?: object | null): node is t.${newType} {
deprecationWarning("is${type}", "is${newType}");
return is${newType}(node, opts);
}
`;
});
return output;
}