Debian Codegraph @

packages/babel-types/scripts/generators/docs.js

raw
1 import util from "util";
2 import stringifyValidator from "../utils/stringifyValidator.js";
3 import toFunctionName from "../utils/toFunctionName.js";
4
5 import * as t from "../../lib/index.js";
6
7 const readme = [
8 `---
9 id: babel-types
10 title: @babel/types
11 ---
12 <!-- Do not modify! This file is automatically generated by
13 github.com/babel/babel/babel-types/scripts/generators/docs.js !-->
14
15 > This module contains methods for building ASTs manually and for checking the types of AST nodes.
16
17 ## Install
18
19 \`\`\`sh
20 npm install --save-dev @babel/types
21 \`\`\`
22
23 ## API`,
24 ];
25
26 const customTypes = {
27 ClassMethod: {
28 key: "if computed then `Expression` else `Identifier | Literal`",
29 },
30 Identifier: {
31 name: "`string`",
32 },
33 MemberExpression: {
34 property: "if computed then `Expression` else `Identifier`",
35 },
36 ObjectMethod: {
37 key: "if computed then `Expression` else `Identifier | Literal`",
38 },
39 ObjectProperty: {
40 key: "if computed then `Expression` else `Identifier | Literal`",
41 },
42 ClassPrivateMethod: {
43 computed: "'false'",
44 },
45 ClassPrivateProperty: {
46 computed: "'false'",
47 },
48 };
49 const APIHistory = {
50 ClassProperty: [["v7.6.0", "Supports `static`"]],
51 };
52 function formatHistory(historyItems) {
53 const lines = historyItems.map(
54 item => "| `" + item[0] + "` | " + item[1] + " |"
55 );
56 return [
57 "<details>",
58 " <summary>History</summary>",
59 "| Version | Changes |",
60 "| --- | --- |",
61 ...lines,
62 "</details>",
63 ];
64 }
65 function printAPIHistory(key, readme) {
66 if (APIHistory[key]) {
67 readme.push("");
68 readme.push(...formatHistory(APIHistory[key]));
69 }
70 }
71 function printNodeFields(key, readme) {
72 if (Object.keys(t.NODE_FIELDS[key]).length > 0) {
73 readme.push("");
74 readme.push("AST Node `" + key + "` shape:");
75 Object.keys(t.NODE_FIELDS[key])
76 .sort(function (fieldA, fieldB) {
77 const indexA = t.BUILDER_KEYS[key].indexOf(fieldA);
78 const indexB = t.BUILDER_KEYS[key].indexOf(fieldB);
79 if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
80 if (indexA === -1) return 1;
81 if (indexB === -1) return -1;
82 return indexA - indexB;
83 })
84 .forEach(function (field) {
85 const defaultValue = t.NODE_FIELDS[key][field].default;
86 const fieldDescription = ["`" + field + "`"];
87 const validator = t.NODE_FIELDS[key][field].validate;
88 if (customTypes[key] && customTypes[key][field]) {
89 fieldDescription.push(`: ${customTypes[key][field]}`);
90 } else if (validator) {
91 try {
92 fieldDescription.push(
93 ": `" + stringifyValidator(validator, "") + "`"
94 );
95 } catch (ex) {
96 if (ex.code === "UNEXPECTED_VALIDATOR_TYPE") {
97 console.log(
98 "Unrecognised validator type for " + key + "." + field
99 );
100 console.dir(ex.validator, { depth: 10, colors: true });
101 }
102 }
103 }
104 if (defaultValue !== null || t.NODE_FIELDS[key][field].optional) {
105 fieldDescription.push(
106 " (default: `" + util.inspect(defaultValue) + "`"
107 );
108 if (t.BUILDER_KEYS[key].indexOf(field) < 0) {
109 fieldDescription.push(", excluded from builder function");
110 }
111 fieldDescription.push(")");
112 } else {
113 fieldDescription.push(" (required)");
114 }
115 readme.push("- " + fieldDescription.join(""));
116 });
117 }
118 }
119
120 function printAliasKeys(key, readme) {
121 if (t.ALIAS_KEYS[key] && t.ALIAS_KEYS[key].length) {
122 readme.push("");
123 readme.push(
124 "Aliases: " +
125 t.ALIAS_KEYS[key]
126 .map(function (key) {
127 return "[`" + key + "`](#" + key.toLowerCase() + ")";
128 })
129 .join(", ")
130 );
131 }
132 }
133 readme.push("### Node Builders");
134 readme.push("");
135 Object.keys(t.BUILDER_KEYS)
136 .sort()
137 .forEach(function (key) {
138 readme.push("#### " + toFunctionName(key));
139 readme.push("");
140 readme.push("```javascript");
141 readme.push(
142 "t." + toFunctionName(key) + "(" + t.BUILDER_KEYS[key].join(", ") + ");"
143 );
144 readme.push("```");
145 printAPIHistory(key, readme);
146 readme.push("");
147 readme.push(
148 "See also `t.is" +
149 key +
150 "(node, opts)` and `t.assert" +
151 key +
152 "(node, opts)`."
153 );
154
155 printNodeFields(key, readme);
156 printAliasKeys(key, readme);
157
158 readme.push("");
159 readme.push("---");
160 readme.push("");
161 });
162
163 function generateMapAliasToNodeTypes() {
164 const result = new Map();
165 for (const nodeType of Object.keys(t.ALIAS_KEYS)) {
166 const aliases = t.ALIAS_KEYS[nodeType];
167 if (!aliases) continue;
168 for (const alias of aliases) {
169 if (!result.has(alias)) {
170 result.set(alias, []);
171 }
172 const nodeTypes = result.get(alias);
173 nodeTypes.push(nodeType);
174 }
175 }
176 return result;
177 }
178 const aliasDescriptions = {
179 Accessor: "Deprecated. Will be removed in Babel 8.",
180 Binary:
181 "A cover of BinaryExpression and LogicalExpression, which share the same AST shape.",
182 Block: "Deprecated. Will be removed in Babel 8.",
183 BlockParent:
184 "A cover of AST nodes that start an execution context with new [LexicalEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `let` and `const` declarations.",
185 Class:
186 "A cover of ClassExpression and ClassDeclaration, which share the same AST shape.",
187 CompletionStatement:
188 "A statement that indicates the [completion records](https://tc39.es/ecma262/#sec-completion-record-specification-type). In other words, they define the control flow of the program, such as when should a loop break or an action throws critical errors.",
189 Conditional:
190 "A cover of ConditionalExpression and IfStatement, which share the same AST shape.",
191 Declaration:
192 "A cover of any [Declaration](https://tc39.es/ecma262/#prod-Declaration)s.",
193 EnumBody: "A cover of Flow enum bodies.",
194 EnumMember: "A cover of Flow enum membors.",
195 ExportDeclaration:
196 "A cover of any [ExportDeclaration](https://tc39.es/ecma262/#prod-ExportDeclaration)s.",
197 Expression:
198 "A cover of any [Expression](https://tc39.es/ecma262/#sec-ecmascript-language-expressions)s.",
199 ExpressionWrapper:
200 "A wrapper of expression that does not have runtime semantics.",
201 Flow: "A cover of AST nodes defined for Flow.",
202 FlowBaseAnnotation: "A cover of primary Flow type annotations.",
203 FlowDeclaration: "A cover of Flow declarations.",
204 FlowPredicate: "A cover of Flow predicates.",
205 FlowType: "A cover of Flow type annotations.",
206 For: "A cover of [ForStatement](https://tc39.es/ecma262/#sec-for-statement)s and [ForXStatement](#forxstatement)s.",
207 ForXStatement:
208 "A cover of [ForInStatements and ForOfStatements](https://tc39.es/ecma262/#sec-for-in-and-for-of-statements).",
209 Function:
210 "A cover of functions and [method](#method)s, the must have `body` and `params`. Note: `Function` is different to `FunctionParent`. For example, a `StaticBlock` is a `FunctionParent` but not `Function`.",
211 FunctionParent:
212 "A cover of AST nodes that start an execution context with new [VariableEnvironment](https://tc39.es/ecma262/#table-additional-state-components-for-ecmascript-code-execution-contexts). In other words, they define the scope of `var` declarations. FunctionParent did not include `Program` since Babel 7.",
213 Immutable:
214 "A cover of immutable objects and JSX elements. An object is [immutable](https://tc39.es/ecma262/#immutable-prototype-exotic-object) if no other properties can be defined once created.",
215 JSX: "A cover of AST nodes defined for [JSX](https://facebook.github.io/jsx/).",
216 LVal: "A cover of left hand side expressions used in the `left` of assignment expressions and [ForXStatement](#forxstatement)s. ",
217 Literal:
218 "A cover of [Literal](https://tc39.es/ecma262/#sec-primary-expression-literals)s, [Regular Expression Literal](https://tc39.es/ecma262/#sec-primary-expression-regular-expression-literals)s and [Template Literal](https://tc39.es/ecma262/#sec-template-literals)s.",
219 Loop: "A cover of loop statements.",
220 Method: "A cover of object methods and class methods.",
221 Miscellaneous:
222 "A cover of non-standard AST types that are sometimes useful for development.",
223 ModuleDeclaration:
224 "A cover of ImportDeclaration and [ExportDeclaration](#exportdeclaration)",
225 ModuleSpecifier:
226 "A cover of import and export specifiers. Note: It is _not_ the [ModuleSpecifier](https://tc39.es/ecma262/#prod-ModuleSpecifier) defined in the spec.",
227 ObjectMember:
228 "A cover of [members](https://tc39.es/ecma262/#prod-PropertyDefinitionList) in an object literal.",
229 Pattern:
230 "A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern) except Identifiers.",
231 PatternLike:
232 "A cover of [BindingPattern](https://tc39.es/ecma262/#prod-BindingPattern)s. ",
233 Private: "A cover of private class elements and private identifiers.",
234 Property: "A cover of object properties and class properties.",
235 Pureish:
236 "A cover of AST nodes which do not have side-effects. In other words, there is no observable behaviour changes if they are evaluated more than once.",
237 Scopable:
238 "A cover of [FunctionParent](#functionparent) and [BlockParent](#blockparent).",
239 Standardized:
240 "A cover of AST nodes which are part of an official ECMAScript specification.",
241 Statement:
242 "A cover of any [Statement](https://tc39.es/ecma262/#prod-Statement)s.",
243 TSBaseType: "A cover of primary TypeScript type annotations.",
244 TSEntityName: "A cover of ts entities.",
245 TSType: "A cover of TypeScript type annotations.",
246 TSTypeElement: "A cover of TypeScript type declarations.",
247 TypeScript: "A cover of AST nodes defined for TypeScript.",
248 Terminatorless:
249 "A cover of AST nodes whose semantic will change when a line terminator is inserted between the operator and the operand.",
250 UnaryLike: "A cover of UnaryExpression and SpreadElement.",
251 UserWhitespacable: "Deprecated. Will be removed in Babel 8.",
252 While:
253 "A cover of DoWhileStatement and WhileStatement, which share the same AST shape.",
254 };
255 const mapAliasToNodeTypes = generateMapAliasToNodeTypes();
256 readme.push("### Aliases");
257 readme.push("");
258 for (const alias of [...mapAliasToNodeTypes.keys()].sort()) {
259 const nodeTypes = mapAliasToNodeTypes.get(alias);
260 nodeTypes.sort();
261 if (!(alias in aliasDescriptions)) {
262 throw new Error(
263 'Missing alias descriptions of "' +
264 alias +
265 ", which covers " +
266 nodeTypes.join(",")
267 );
268 }
269 readme.push("#### " + alias);
270 readme.push("");
271 readme.push(aliasDescriptions[alias]);
272 readme.push("```javascript");
273 readme.push("t.is" + alias + "(node);");
274 readme.push("```");
275 readme.push("");
276 readme.push("Covered nodes: ");
277 for (const nodeType of nodeTypes) {
278 readme.push("- [`" + nodeType + "`](#" + nodeType.toLowerCase() + ")");
279 }
280 readme.push("");
281 }
282
283 process.stdout.write(readme.join("\n"));