-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdoc-builders.ts
More file actions
325 lines (284 loc) · 8.13 KB
/
Copy pathdoc-builders.ts
File metadata and controls
325 lines (284 loc) · 8.13 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import { ExportableType } from "./export-types";
// Helpers to generate Lua or TypeScript definition from objects
export type DocFuncBuilderType = {
type: ExportableType;
description?: string[];
isOptional?: boolean;
};
export type DocFuncBuilderParam = DocFuncBuilderType & {
name: string;
};
const assertCorrectness: MethodDecorator = function (
target,
propertyKey,
descriptor: TypedPropertyDescriptor<any>
) {
const originalMethod = descriptor.value as Function;
descriptor.value = function (this: DocFuncBuilder) {
this.assertCorrectness();
return originalMethod.apply(this, arguments);
};
};
const assertHasName: MethodDecorator = function (
target,
propertyKey: string,
descriptor: TypedPropertyDescriptor<any>
) {
const originalMethod = descriptor.value as Function;
descriptor.value = function (this: DocFuncBuilder) {
if (!this.name) {
throw new Error(`"name" must be supplied to call ${propertyKey}()`);
}
return originalMethod.apply(this, arguments);
};
};
const CORRECT_PARAM_NAME_REGEX = /^[a-zA-Z0-9]+$/;
/**
* Helper class to create function declarations.
*/
export class DocFuncBuilder {
constructor(
public name?: string,
public description: string[] = [],
public parameters: DocFuncBuilderParam[] = [],
public returnType?: DocFuncBuilderType
) {}
/**
* Asserts the correctness of the DocFunc before exporting it. This prevents
* unexpected or invalid output when exporting.
*
* @throws {Error} Unexpected parameters or metadata in the DocFunc.
*/
assertCorrectness() {
for (const p of this.parameters) {
if (!CORRECT_PARAM_NAME_REGEX.test(p.name)) {
throw new Error(
`Parameter name "${p.name}" of document function "${
this.name || "unknown"
}" is invalid. Correct it in the overrides.`
);
}
}
}
/**
* Exports the comment portion of the JSDoc.
*/
@assertCorrectness
exportJsDocCommentLines() {
const lines: string[] = [];
{
// Build jsdoc lines
const jsDocLines: string[] = [];
for (const d of this.description) {
jsDocLines.push(d);
}
for (const p of this.parameters) {
if (!p.description) continue;
jsDocLines.push(`@param ${p.name} ${p.description[0]}`);
for (let i = 1; i < p.description.length; i++) {
jsDocLines.push(p.description[i]);
}
}
if (this.returnType?.description) {
jsDocLines.push(`@returns ${this.returnType.description}`);
}
if (jsDocLines.length > 0) {
lines.push("/**");
for (const s of jsDocLines) {
lines.push(` * ${s}`.trimEnd());
}
lines.push(" */");
}
}
return lines;
}
/**
* Exports the function declaration (without the JSDoc comments).
*
* Requires `name` supplied.
*/
@assertCorrectness
@assertHasName
exportTsFuncDeclare() {
// Build TS function declaration
return `function ${this.name}(${this.parameters
.map((p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type.asTs()}`)
.join(", ")}): ${
this.returnType
? `${this.returnType.type.asTs()}${
this.returnType.isOptional ? " | undefined" : ""
}`
: "void"
}`;
}
/**
* Exports the function in literal TSTL arrow function type.
*
* No function names and descriptions are exported.
*/
@assertCorrectness
exportTsFuncType() {
// Build TSTL function declaration
// It is likely we mean to exclude the self parameter... are there any cases we don't though? :thinking:
const paramsDef = [
"this: void",
...this.parameters.map(
(p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type.asTs()}`
),
].join(", ");
return `(${paramsDef}) => ${
this.returnType
? `${this.returnType.type.asTs()}${
this.returnType.isOptional ? " | undefined" : ""
}`
: "void"
}`;
}
/**
* Exports the function declaration for Lua.
*
* Requires `name` supplied.
*/
@assertCorrectness
@assertHasName
exportLuaDocLines() {
const lines: string[] = [];
// Build luadoc lines
{
const luaDocLines: string[] = [];
for (const d of this.description) {
luaDocLines.push(d);
}
for (const p of this.parameters) {
if (!p.description) continue;
luaDocLines.push(
`@param ${p.name}${p.isOptional ? "?" : ""} ${p.type.asLua()} ${
p.description[0]
}`
);
for (let i = 1; i < p.description.length; i++) {
luaDocLines.push(p.description[i]);
}
}
if (this.returnType) {
luaDocLines.push(
`@return ${this.returnType.type.asLua()}${
this.returnType.isOptional ? "?" : ""
} # ${this.returnType.description}`
);
}
if (luaDocLines.length > 0) {
for (const s of luaDocLines) {
lines.push(`--- ${s}`.trimEnd());
}
}
}
// Build Lua function declaration
lines.push(
`function ${this.name}(${this.parameters
.map((p) => p.name)
.join(", ")}) end`
);
return lines;
}
/**
* Exports the function in Lua literal `fun()` type.
*
* No function names and descriptions are exported.
*/
@assertCorrectness
exportLuaFuncType() {
// Build TS function declaration
return `fun(${this.parameters
.map((p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type.asLua()}`)
.join(", ")})${
this.returnType
? `: ${this.returnType.type.asLua()}${
this.returnType.isOptional ? "?" : ""
}`
: ""
}`;
}
}
// TODO
function isReservedTsKeyword(word: string) {
return word === "enum";
}
/**
* Helper class to create TypeScript namespaces.
*/
export class TSNamespaceBuilder {
children: Map<string, TSNamespaceBuilder>;
contents: { type: "statement" | "content"; value: string[] }[];
singleIndentString: string;
constructor(public name?: string, public parent?: TSNamespaceBuilder) {
this.children = new Map<string, TSNamespaceBuilder>();
this.contents = [];
this.singleIndentString = " ";
}
static createGlobal() {
return new TSNamespaceBuilder("globalThis");
}
get isRoot() {
return this.parent == null;
}
/**
* Navigates to a child
*/
navigate(name: string, createIfNone: boolean = true): TSNamespaceBuilder {
let child = this.children.get(name);
if (createIfNone && !child) {
child = new TSNamespaceBuilder(name, this);
this.children.set(name, child);
}
return child;
}
pushContent(content: string[]) {
this.contents.push({ type: "content", value: content });
}
pushStatement(statement: string[]) {
if (statement.length === 0) {
throw new Error("Tried to push empty statement?");
}
this.contents.push({ type: "statement", value: statement });
}
/**
* Exports the namespace content.
*/
exportTstl(depth = 0) {
const indentStr = this.singleIndentString.repeat(depth);
const newLines: string[] = [];
for (const c of this.children.values()) {
// Avoid reserved words
const isReservedName = isReservedTsKeyword(c.name);
const namespaceName = isReservedName ? "$" + c.name : c.name;
newLines.push(
indentStr +
`${
this.isRoot ? "declare " : isReservedName ? "" : "export "
}namespace ${namespaceName} {`
);
newLines.push(...c.exportTstl(depth + 1));
newLines.push(indentStr + "}");
if (isReservedName) {
newLines.push(indentStr + `export { ${namespaceName} as ${c.name} }`);
}
}
for (const contentMeta of this.contents) {
if (contentMeta.type === "statement") {
newLines.push(
indentStr +
`${this.isRoot ? "declare" : "export"} ${contentMeta.value[0]}`
);
for (let i = 1; i < contentMeta.value.length; i++) {
newLines.push(indentStr + contentMeta.value[i]);
}
} else {
for (const content of contentMeta.value) {
newLines.push(indentStr + content);
}
}
}
return newLines;
}
}