Debian Codegraph @

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

raw
1 import {
2 BUILDER_KEYS,
3 DEPRECATED_KEYS,
4 NODE_FIELDS,
5 toBindingIdentifierName,
6 } from "../../lib/index.js";
7 import formatBuilderName from "../utils/formatBuilderName.js";
8 import lowerFirst from "../utils/lowerFirst.js";
9 import stringifyValidator from "../utils/stringifyValidator.js";
10
11 function areAllRemainingFieldsNullable(fieldName, fieldNames, fields) {
12 const index = fieldNames.indexOf(fieldName);
13 return fieldNames.slice(index).every(_ => isNullable(fields[_]));
14 }
15
16 function hasDefault(field) {
17 return field.default != null;
18 }
19
20 function isNullable(field) {
21 return field.optional || hasDefault(field);
22 }
23
24 function sortFieldNames(fields, type) {
25 return fields.sort((fieldA, fieldB) => {
26 const indexA = BUILDER_KEYS[type].indexOf(fieldA);
27 const indexB = BUILDER_KEYS[type].indexOf(fieldB);
28 if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
29 if (indexA === -1) return 1;
30 if (indexB === -1) return -1;
31 return indexA - indexB;
32 });
33 }
34
35 function generateBuilderArgs(type) {
36 const fields = NODE_FIELDS[type];
37 const fieldNames = sortFieldNames(Object.keys(NODE_FIELDS[type]), type);
38 const builderNames = BUILDER_KEYS[type];
39
40 const args = [];
41
42 fieldNames.forEach(fieldName => {
43 const field = fields[fieldName];
44 // Future / annoying TODO:
45 // MemberExpression.property, ObjectProperty.key and ObjectMethod.key need special cases; either:
46 // - convert the declaration to chain() like ClassProperty.key and ClassMethod.key,
47 // - declare an alias type for valid keys, detect the case and reuse it here,
48 // - declare a disjoint union with, for example, ObjectPropertyBase,
49 // ObjectPropertyLiteralKey and ObjectPropertyComputedKey, and declare ObjectProperty
50 // as "ObjectPropertyBase & (ObjectPropertyLiteralKey | ObjectPropertyComputedKey)"
51 let typeAnnotation = stringifyValidator(field.validate, "t.");
52
53 if (isNullable(field) && !hasDefault(field)) {
54 typeAnnotation += " | null";
55 }
56
57 if (builderNames.includes(fieldName)) {
58 const field = NODE_FIELDS[type][fieldName];
59 const def = JSON.stringify(field.default);
60 const bindingIdentifierName = toBindingIdentifierName(fieldName);
61 let arg;
62 if (areAllRemainingFieldsNullable(fieldName, builderNames, fields)) {
63 arg = `${bindingIdentifierName}${
64 isNullable(field) && !def ? "?:" : ":"
65 } ${typeAnnotation}`;
66 } else {
67 arg = `${bindingIdentifierName}: ${typeAnnotation}${
68 isNullable(field) ? " | undefined" : ""
69 }`;
70 }
71 if (def !== "null" || isNullable(field)) {
72 arg += `= ${def}`;
73 }
74 args.push(arg);
75 }
76 });
77
78 return args;
79 }
80
81 export default function generateBuilders(kind) {
82 return kind === "uppercase.js"
83 ? generateUppercaseBuilders()
84 : generateLowercaseBuilders();
85 }
86
87 function generateLowercaseBuilders() {
88 let output = `/*
89 * This file is auto-generated! Do not modify it directly.
90 * To re-generate run 'make build'
91 */
92 import validateNode from "../validateNode";
93 import type * as t from "../..";
94 `;
95
96 const reservedNames = new Set(["super", "import"]);
97 Object.keys(BUILDER_KEYS).forEach(type => {
98 const defArgs = generateBuilderArgs(type);
99 const formatedBuilderName = formatBuilderName(type);
100 const formatedBuilderNameLocal = reservedNames.has(formatedBuilderName)
101 ? `_${formatedBuilderName}`
102 : formatedBuilderName;
103
104 const fieldNames = sortFieldNames(Object.keys(NODE_FIELDS[type]), type);
105 const builderNames = BUILDER_KEYS[type];
106 const objectFields = [["type", JSON.stringify(type)]];
107 fieldNames.forEach(fieldName => {
108 const field = NODE_FIELDS[type][fieldName];
109 if (builderNames.includes(fieldName)) {
110 const bindingIdentifierName = toBindingIdentifierName(fieldName);
111 objectFields.push([fieldName, bindingIdentifierName]);
112 } else if (!field.optional) {
113 const def = JSON.stringify(field.default);
114 objectFields.push([fieldName, def]);
115 }
116 });
117
118 output += `${
119 formatedBuilderNameLocal === formatedBuilderName ? "export " : ""
120 }function ${formatedBuilderNameLocal}(${defArgs.join(", ")}): t.${type} {`;
121
122 const nodeObjectExpression = `{\n${objectFields
123 .map(([k, v]) => (k === v ? ` ${k},` : ` ${k}: ${v},`))
124 .join("\n")}\n }`;
125
126 if (builderNames.length > 0) {
127 output += `\n return validateNode<t.${type}>(${nodeObjectExpression});`;
128 } else {
129 output += `\n return ${nodeObjectExpression};`;
130 }
131 output += `\n}\n`;
132
133 if (formatedBuilderNameLocal !== formatedBuilderName) {
134 output += `export { ${formatedBuilderNameLocal} as ${formatedBuilderName} };\n`;
135 }
136
137 // This is needed for backwards compatibility.
138 // It should be removed in the next major version.
139 // JSXIdentifier -> jSXIdentifier
140 if (/^[A-Z]{2}/.test(type)) {
141 output += `export { ${formatedBuilderNameLocal} as ${lowerFirst(
142 type
143 )} }\n`;
144 }
145 });
146
147 Object.keys(DEPRECATED_KEYS).forEach(type => {
148 const newType = DEPRECATED_KEYS[type];
149 const formatedBuilderName = formatBuilderName(type);
150 const formatedNewBuilderName = formatBuilderName(newType);
151 output += `/** @deprecated */
152 function ${type}(${generateBuilderArgs(newType).join(", ")}) {
153 console.trace("The node type ${type} has been renamed to ${newType}");
154 return ${formatedNewBuilderName}(${BUILDER_KEYS[newType].join(", ")});
155 }
156 export { ${type} as ${formatedBuilderName} };\n`;
157 // This is needed for backwards compatibility.
158 // It should be removed in the next major version.
159 // JSXIdentifier -> jSXIdentifier
160 if (/^[A-Z]{2}/.test(type)) {
161 output += `export { ${type} as ${lowerFirst(type)} }\n`;
162 }
163 });
164
165 return output;
166 }
167
168 function generateUppercaseBuilders() {
169 let output = `/*
170 * This file is auto-generated! Do not modify it directly.
171 * To re-generate run 'make build'
172 */
173
174 /**
175 * This file is written in JavaScript and not TypeScript because uppercase builders
176 * conflict with AST types. TypeScript reads the uppercase.d.ts file instead.
177 */
178
179 export {\n`;
180
181 Object.keys(BUILDER_KEYS).forEach(type => {
182 const formatedBuilderName = formatBuilderName(type);
183 output += ` ${formatedBuilderName} as ${type},\n`;
184 });
185
186 Object.keys(DEPRECATED_KEYS).forEach(type => {
187 const formatedBuilderName = formatBuilderName(type);
188 output += ` ${formatedBuilderName} as ${type},\n`;
189 });
190
191 output += ` } from './index';\n`;
192 return output;
193 }