Debian Codegraph @

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

raw
1 import * as t from "../../lib/index.js";
2 import stringifyValidator, {
3 isValueType,
4 } from "../utils/stringifyValidator.js";
5
6 const parentMaps = new Map([["File", new Set(["null"])]]);
7
8 function registerParentMaps(parent, nodes) {
9 for (const node of nodes) {
10 if (!parentMaps.has(node)) {
11 parentMaps.set(node, new Set());
12 }
13 parentMaps.get(node).add(parent);
14 }
15 }
16
17 function getNodeTypesFromValidator(validator) {
18 if (validator === undefined) return [];
19 if (validator.each) {
20 return getNodeTypesFromValidator(validator.each);
21 }
22 if (validator.chainOf) {
23 return getNodeTypesFromValidator(validator.chainOf[1]);
24 }
25 let nodeTypes = [];
26 if (validator.oneOfNodeTypes) {
27 nodeTypes = validator.oneOfNodeTypes;
28 }
29 if (validator.oneOfNodeOrValueTypes) {
30 nodeTypes = validator.oneOfNodeOrValueTypes.filter(
31 type => !isValueType(type)
32 );
33 }
34 return nodeTypes.flatMap(type => t.FLIPPED_ALIAS_KEYS[type] ?? type);
35 }
36
37 export default function generateAstTypes() {
38 let code = `// NOTE: This file is autogenerated. Do not modify.
39 // See packages/babel-types/scripts/generators/ast-types.js for script used.
40
41 interface BaseComment {
42 value: string;
43 start?: number;
44 end?: number;
45 loc?: SourceLocation;
46 // generator will skip the comment if ignore is true
47 ignore?: boolean;
48 type: "CommentBlock" | "CommentLine";
49 }
50
51 export interface CommentBlock extends BaseComment {
52 type: "CommentBlock";
53 }
54
55 export interface CommentLine extends BaseComment {
56 type: "CommentLine";
57 }
58
59 export type Comment = CommentBlock | CommentLine;
60
61 export interface SourceLocation {
62 start: {
63 line: number;
64 column: number;
65 };
66
67 end: {
68 line: number;
69 column: number;
70 };
71 }
72
73 interface BaseNode {
74 type: Node["type"];
75 leadingComments?: Comment[] | null;
76 innerComments?: Comment[] | null;
77 trailingComments?: Comment[] | null;
78 start?: number | null;
79 end?: number | null;
80 loc?: SourceLocation | null;
81 range?: [number, number];
82 extra?: Record<string, unknown>;
83 }
84
85 export type CommentTypeShorthand = "leading" | "inner" | "trailing";
86
87 export type Node = ${t.TYPES.filter(k => !t.FLIPPED_ALIAS_KEYS[k])
88 .sort()
89 .join(" | ")};\n\n`;
90
91 const deprecatedAlias = {};
92 for (const type in t.DEPRECATED_KEYS) {
93 deprecatedAlias[t.DEPRECATED_KEYS[type]] = type;
94 }
95 for (const type in t.NODE_FIELDS) {
96 const fields = t.NODE_FIELDS[type];
97 const fieldNames = sortFieldNames(Object.keys(t.NODE_FIELDS[type]), type);
98 const struct = [];
99
100 fieldNames.forEach(fieldName => {
101 const field = fields[fieldName];
102 // Future / annoying TODO:
103 // MemberExpression.property, ObjectProperty.key and ObjectMethod.key need special cases; either:
104 // - convert the declaration to chain() like ClassProperty.key and ClassMethod.key,
105 // - declare an alias type for valid keys, detect the case and reuse it here,
106 // - declare a disjoint union with, for example, ObjectPropertyBase,
107 // ObjectPropertyLiteralKey and ObjectPropertyComputedKey, and declare ObjectProperty
108 // as "ObjectPropertyBase & (ObjectPropertyLiteralKey | ObjectPropertyComputedKey)"
109 let typeAnnotation = stringifyValidator(field.validate, "");
110
111 if (isNullable(field) && !hasDefault(field)) {
112 typeAnnotation += " | null";
113 }
114
115 const alphaNumeric = /^\w+$/;
116 const optional = field.optional ? "?" : "";
117
118 if (t.isValidIdentifier(fieldName) || alphaNumeric.test(fieldName)) {
119 struct.push(`${fieldName}${optional}: ${typeAnnotation};`);
120 } else {
121 struct.push(`"${fieldName}"${optional}: ${typeAnnotation};`);
122 }
123
124 registerParentMaps(type, getNodeTypesFromValidator(field.validate));
125 });
126
127 code += `export interface ${type} extends BaseNode {
128 type: "${type}";
129 ${struct.join("\n ").trim()}
130 }\n\n`;
131
132 if (deprecatedAlias[type]) {
133 code += `/**
134 * @deprecated Use \`${type}\`
135 */
136 export interface ${deprecatedAlias[type]} extends BaseNode {
137 type: "${deprecatedAlias[type]}";
138 ${struct.join("\n ").trim()}
139 }\n\n
140 `;
141 }
142 }
143
144 for (const type in t.FLIPPED_ALIAS_KEYS) {
145 const types = t.FLIPPED_ALIAS_KEYS[type];
146 code += `export type ${type} = ${types
147 .map(type => `${type}`)
148 .join(" | ")};\n`;
149 }
150 code += "\n";
151
152 code += "export interface Aliases {\n";
153 for (const type in t.FLIPPED_ALIAS_KEYS) {
154 code += ` ${type}: ${type};\n`;
155 }
156 code += "}\n\n";
157 code += `export type DeprecatedAliases = ${Object.keys(
158 t.DEPRECATED_KEYS
159 ).join(" | ")}\n\n`;
160
161 code += "export interface ParentMaps {\n";
162
163 registerParentMaps("null", [...Object.keys(t.DEPRECATED_KEYS)]);
164 // todo: provide a better parent type for Placeholder, currently it acts
165 // as a catch-all parent type for an abstract NodePath, s.t NodePath.parent must
166 // be a Node if type has not been specified
167 registerParentMaps("Node", ["Placeholder"]);
168
169 const parentMapsKeys = [...parentMaps.keys()].sort();
170 for (const type of parentMapsKeys) {
171 const deduplicated = [...parentMaps.get(type)].sort();
172 code += ` ${type}: ${deduplicated.join(" | ")};\n`;
173 }
174 code += "}\n\n";
175
176 return code;
177 }
178
179 function hasDefault(field) {
180 return field.default != null;
181 }
182
183 function isNullable(field) {
184 return field.optional || hasDefault(field);
185 }
186
187 function sortFieldNames(fields, type) {
188 return fields.sort((fieldA, fieldB) => {
189 const indexA = t.BUILDER_KEYS[type].indexOf(fieldA);
190 const indexB = t.BUILDER_KEYS[type].indexOf(fieldB);
191 if (indexA === indexB) return fieldA < fieldB ? -1 : 1;
192 if (indexA === -1) return 1;
193 if (indexB === -1) return -1;
194 return indexA - indexB;
195 });
196 }