forked from markwpearce/brighterscript-jsdocs-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert-brighterscript-docs.js
569 lines (509 loc) · 17.6 KB
/
convert-brighterscript-docs.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
'use strict';
const bs = require('brighterscript');
const path = require('path');
const jsCommentStartRegex = /^[\s]*(?:\/\*+)?[\s]*(.*)/g
const bsMeaningfulCommentRegex = /^[\s]*(?:'|REM)[\s]*\**[\s]*(.*)/g
const paramRegex = /@param\s+(?:{([^}]*)})?\s+(?:\[(\w+).*\]|(\w+))[\s-\s|\s]*(.*)/
const returnRegex = /@returns?\s*({(?:[^}]*)})?\s*(.*)/
const extendsRegex = /@extends/
const moduleRegex = /@module ([^\*\s]+)/
const opts = env && env.opts || {}
const pluginOpts = opts['brighterscript-jsdocs-plugin'] || {};
if (pluginOpts.addModule === undefined || pluginOpts.addModule === null) {
pluginOpts.addModule = true
}
if (pluginOpts.addModule === undefined || pluginOpts.addModule === null) {
pluginOpts.addModule = true
}
/** @type {string[]} */
const namespacesCreated = []
/** @type {string[]} */
const modulesCreated = []
/** @type {string[]} */
let parserLines = []
/** @type{{}} */
const escapeCharEntities = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
/**
* Groups Statements into comments, functions, classes and namespaces
*
* @param {bs.Statement[]} statements
* @returns {{functions:bs.FunctionStatement[],classes:bs.ClassStatement[],namespaces:bs.NamespaceStatement[],comments:bs.CommentStatement[]}}
*/
function groupStatements(statements) {
/** @type{bs.CommentStatement[]} */
const comments = []
/** @type{bs.FunctionStatement[]} */
const functions = []
/** @type{bs.ClassStatement[]} */
const classes = []
/** @type{bs.NamespaceStatement[]} */
const namespaces = []
statements.forEach(statement => {
if (statement instanceof bs.CommentStatement) {
comments.push(statement)
}
if (statement instanceof bs.FunctionStatement) {
functions.push(statement);
}
if (statement instanceof bs.ClassStatement) {
classes.push(statement);
}
if (statement instanceof bs.NamespaceStatement) {
namespaces.push(statement);
}
});
return { comments, functions, classes, namespaces }
}
/**
* Gets the type name for the given type
* Defaults to "dynamic" if it can't decide
*
* @param {bs.BscType} type the type
* @returns {string} the name for the type id given
*/
function getTypeName(type) {
if (!type) {
return "dynamic"
}
if (bs.isCustomType(type)) {
return type.name;
}
if (type.toTypeString) {
return type.toTypeString()
}
return "dynamic"
}
/**
* Helper to clean up param or return description strings
*
* @param {string} [desc=""]
* @return {string} cleaned up string
*/
function paramOrReturnDescriptionHelper(desc = "") {
desc = (desc || "").trim()
if (desc.startsWith("-")) {
return desc;
}
if (desc.startsWith(",")) {
desc = desc.substring(1);
}
if (desc) {
return "- " + desc;
}
return ""
}
/**
* Finds the comment that ends the line above the given statement
* If the statement has annotations, the comment should be BEFORE the annotations
*
* @param {bs.CommentStatement[]} comments List of comments to search
* @param {bs.Statement} stmt The statement in question
* @returns {bs.CommentStatement} the correct comment, if found, otherwise undefined
*/
function getCommentForStatement(comments, stmt) {
return comments.find((comment) => {
const commentEndLine = comment.range.end.line;
let targetStartLine = stmt.range.start.line
if (stmt.annotations && stmt.annotations.length > 0) {
targetStartLine = stmt.annotations[0].range.start.line;
}
return commentEndLine + 1 === targetStartLine || commentEndLine === stmt.range.start.line
})
}
function getMemberOf(moduleName = "", namespaceName = "") {
const memberOf = namespaceName || moduleName.replace(/\./g, '/');
const memberType = /*namespaceName ? "" : */ "module:"
if (memberOf) {
return ` * @memberof! ${memberType}${memberOf.replace(/\./g, '/')}`;
}
return ""
}
/**
*
* @param {string} moduleName
* @returns
*/
function getModuleLineComment(moduleName = "") {
const modifiedModuleName = moduleName.replace(/\./g, '/')
if (!modifiedModuleName || modulesCreated.includes(modifiedModuleName)) {
return ""
}
modulesCreated.push(modifiedModuleName);
return [`/**`, ` * @module ${modifiedModuleName}`, ` */`].join('\n');
}
/**
*
* @param {string} line input string
* @return {string} the same string with HTML special characters escaped
*/
function escapeHTMLCharacters(line) {
let outLine = line;
for (const char in escapeCharEntities) {
outLine = outLine.replace(new RegExp(char, 'g'), escapeCharEntities[char])
}
return outLine;
}
/**
* Convert a comment statement text to Js Doc Lines
* This will return a string[] with each line of a block comment
* But - it does not include comment closing tag (ie. asterisk-slash)
*
* @param {bs.CommentStatement} comment
* @returns {string[]} Array of comment lines in JSDoc format -
*/
function convertCommentTextToJsDocLines(comment) {
const commentLines = ['/**'];
if (comment && comment.text) {
// Replace brighterscript comment format with jsdoc - eg.
// ' Comment here
// to
// * Comment here
commentLines.push(...comment.text.split('\n').map((line, i) => {
return line.replace(bsMeaningfulCommentRegex, '$1');
}).map(line => line.trim())
.filter((line) => {
return !line.includes('@module')
}).map((line, i, lines) => {
if (i === 0) {
line = line.replace(jsCommentStartRegex, '$1');
}
line = line.replace(/\*+\/\s*/g, "")
if (pluginOpts.escapeHTMLCharacters) {
line = escapeHTMLCharacters(line);
}
return " * " + line;
}))
}
return commentLines
}
/**
* Helper function to display a statement for debugging
* (Not used)
*
* @param {bs.Statement} stmt
* @returns {void}
*/
function displayStatement(stmt) {
if (stmt instanceof bs.CommentStatement) {
console.log(`Comment`)
}
else if (stmt instanceof bs.FunctionStatement) {
console.log(`Function`)
}
else if (stmt instanceof bs.ClassStatement) {
console.log(`Class`)
}
else if (stmt instanceof bs.NamespaceStatement) {
console.log(`Namespace`)
}
else if (stmt instanceof bs.ClassMethodStatement) {
console.log(`Method`)
}
else if (stmt instanceof bs.ClassFieldStatement) {
console.log(`Field`)
}
else if (stmt.constructor) {
console.log(`${stmt.constructor.toString()}`)
}
if (stmt.text) {
console.log(stmt.text)
}
console.log(`Range:`, stmt.range)
}
/**
* Processes a function or a class method
* For class methods, the "new()" function is outputed as "constructor()"
*
* @param {bs.CommentStatement} comment The comment appearing above this function in bs/brs code
* @param {bs.ClassMethodStatement} func teh actual function or class method
* @param {string} moduleName [moduleName=""] the module name this function is in
* @param {string} namespaceName [namespaceName=""] the namespace this function is in
* @return {string} the jsdoc string for the function provided
*/
function processFunction(comment, func, moduleName = "", namespaceName = "") {
const output = []
let commentLines = convertCommentTextToJsDocLines(comment);
const paramNameList = []
// Find the param line in the comments that match each param
for (const param of func.func.parameters) {
let paramName = param.name.text;
paramNameList.push(paramName)
let paramType = getTypeName(param.type);
let paramDescription = "";
// remove @param lines for the current param
commentLines = commentLines.filter(commentLine => {
let commentMatch = commentLine.match(paramRegex);
if (commentMatch) {
const commentParamName = (commentMatch[2] || commentMatch[3]) || ""
const commentParamType = commentMatch[1] || ""
if (paramName.trim().toLowerCase() === commentParamName.trim().toLowerCase()) {
// same parameter name - use these details
if (commentParamType) {
paramType = commentParamType.trim();
paramDescription = commentMatch[4] || paramDescription
}
return false
}
}
return true
})
let paramLine = ` * @param {${paramType}} `
if (param.defaultValue) {
let start = param.defaultValue.range.start;
let end = param.defaultValue.range.end;
let defaultValue = parserLines[start.line].slice(start.character, end.character);
paramLine += `[${paramName}=${defaultValue}]`
}
else {
paramLine += paramName
}
if (paramDescription) {
paramLine += ` ${paramOrReturnDescriptionHelper(paramDescription)}`;
}
output.push(paramLine);
}
if (func.name.text[0] === '_' || func.accessModifier?.kind === "Private") {
output.push(' * @access private');
}
let returnLine = ` * @return {${getTypeName(func.func.returnType)}}`
// Find the return line in the comments
for (var i = 0; i < commentLines.length; i++) {
let commentMatch = commentLines[i].match(returnRegex);
if (commentMatch) {
let commentReturnType = getTypeName(func.func.returnType)
if (commentMatch[1] && commentMatch[1].trim().toLowerCase() == commentReturnType.toLowerCase()) {
// there is a return type given, and it matches the type of the function
commentReturnType = commentMatch[1].trim()
}
returnLine = ` * @return {${commentReturnType}}`;
if (commentMatch[2]) {
returnLine += " " + paramOrReturnDescriptionHelper(commentMatch[2])
}
// remove the original comment @return line
commentLines.splice(i, 1);
}
}
const totalOutput = [...commentLines, ...output]
totalOutput.push(returnLine);
totalOutput.push(getMemberOf(moduleName, namespaceName));
if (func.overrides) {
totalOutput.push(` * @override`);
}
const funcName = func.name.text
let funcDeclaration = `function ${funcName} (${paramNameList.join(", ")}) { }; \n`
if (func instanceof bs.ClassMethodStatement) {
if (funcName.toLowerCase() === "new") {
totalOutput.push(" * @constructor")
funcDeclaration = `constructor(${paramNameList.join(", ")}) { }; \n`
}
else {
funcDeclaration = `${funcName} (${paramNameList.join(", ")}) { }; \n`
}
}
totalOutput.push(' */');
totalOutput.push(funcDeclaration);
if (namespaceName) {
totalOutput.push(`${namespaceName}.${funcName} = ${funcName}; `)
}
return totalOutput.join('\n')
}
/**
* Processed a Class Field
* These are added as property tags in the class's jsdoc comment
* Private fields are ignored
*
* @param {bs.CommentStatement} comment the comment in the line above this field
* @param {bs.ClassFieldStatement} field the field to process
* @return {string} the property tag for the class this field is in
*/
function processClassField(comment, field) {
if (field.accessModifier?.kind === "Private") {
return ""
}
let description = "";
if (comment) {
description = comment.text.replace(bsMeaningfulCommentRegex, '$1');
}
return ` * @property { ${getTypeName(field.getType())} } ${field.name.text} ${description} `;
}
/**
* Processes a class
* Classes can have member fields (properties or member methods)
* Note: the new() method is renamed to constructor()
*
* @param {bs.CommentStatement} comment The comment that appeared above this class in bs/brs
* @param {bs.ClassStatement} klass the actual class statement
* @param {string} moduleName [moduleName=""] the module name this class is in
* @param {string} namespaceName [namespaceName=""] the namespace this class is in
* @return {string} the jsdoc string for the class provided
*/
function processClass(comment, klass, moduleName = "", namespaceName = "") {
const output = []
let commentLines = convertCommentTextToJsDocLines(comment);
const klassCode = groupStatements(klass.body)
let parentClassName = "", extendsLine = ""
if (klass.parentClassName) {
parentClassName = klass.parentClassName.getName()
extendsLine = ` * @extends ${klass.parentClassName.getName(bs.ParseMode.BrighterScript)} `
}
for (var i = 0; i < commentLines.length; i++) {
let commentMatch = commentLines[i].match(extendsRegex);
if (commentMatch && commentMatch[1]) {
commentLines.splice(i, 1);
break;
}
}
if (extendsLine) {
commentLines.push(extendsLine);
}
// get properties
commentLines.push(getMemberOf(moduleName, namespaceName));
klass.fields.forEach(field => {
const fieldComment = getCommentForStatement(klassCode.comments, field)
commentLines.push(processClassField(fieldComment, field))
});
commentLines.push(' */');
output.push(commentLines.join('\n'));
const klassName = klass.name.text
if (parentClassName) {
output.push(`class ${klassName} extends ${parentClassName} {\n`);
}
else {
output.push(`class ${klassName} {\n`);
}
klass.methods.forEach(method => {
const methodComment = getCommentForStatement(klassCode.comments, method)
output.push(processFunction(methodComment, method))
})
output.push('}\n')
if (namespaceName) {
// output.push(...['/**', ' * @class', ' */']);
output.push(`${namespaceName}.${klassName} = ${klassName}; `)
}
return output.join('\n')
}
/**
* Processes a namespace
* Namespaces are recursive - they can contain other functions, classes or namespaces
*
* @param {bs.CommentStatement} comment The comment that appeared above this namespace in bs/brs
* @param {bs.NamespaceStatement} namespace the actual namespace statement
* @param {string} moduleName [moduleName=""] the module name this namespace is in
* @param {string} parentNamespaceName [parentNamespaceName=""] the namespace this namespace is in
* @return {string} the jsdoc string for the namespace provided
*/
function processNamespace(comment, namespace, moduleName = "", parentNamespaceName) {
const output = [];
const namespaceParts = namespace.name.split('.');
const namespaceNames = []
let namespaceNameChain = ""
for (const namespacePart of namespaceParts) {
if (namespaceNameChain.length > 0) {
namespaceNameChain += '.'
}
namespaceNameChain += namespacePart;
namespaceNames.push(namespaceNameChain)
}
let index = 0
let previousNamespace = ""
for (const namespaceName of namespaceNames) {
let subNamespace = namespaceName
if (parentNamespaceName) {
subNamespace = parentNamespaceName + "." + namespaceName
}
if (!namespacesCreated.includes(subNamespace)) {
// have not created this namespace yet
output.push(getModuleLineComment(subNamespace));
let commentLines = convertCommentTextToJsDocLines(comment);
if (subNamespace != moduleName) {
commentLines.push(getMemberOf(previousNamespace));
}
//commentLines.push(` * @namespace {object} ${subNamespace} `)
commentLines.push(' */');
output.push(commentLines.join('\n'));
/*
if (parentNamespaceName || index > 0) {
output.push(`${subNamespace} = {}`)
}
else {
output.push(`var ${subNamespace} = {}; `);
}*/
namespacesCreated.push(subNamespace)
}
previousNamespace = subNamespace
index++
}
let totalNamespace = namespace.name
if (parentNamespaceName) {
totalNamespace = parentNamespaceName + "." + totalNamespace
}
output.push(processStatements(namespace.body.statements, moduleName, totalNamespace))
return output.join('\n');
}
/**
* Process bright(er)script statements. Handles functions, namespace or class statements
* Namespaces are recursive - they can contain other functions, classes or namespaces
*
* @param {bs.Statement[]} statements an array of statements
* @param {string} [moduleName=""] the module name these statements are in
* @param {string} namespaceName [namespaceName=""] the namespace these statements are in
* @returns {string} the jsdoc string for the statements provided
*/
function processStatements(statements, moduleName = "", namespaceName = "") {
const output = [];
const code = groupStatements(statements)
if (code.comments.length === 0 && code.functions.length === 0 && code.classes.length === 0 && code.namespaces.length === 0) {
return '';
}
code.functions.forEach(func => {
const comment = getCommentForStatement(code.comments, func)
const functionOutput = processFunction(comment, func, moduleName, namespaceName)
output.push(functionOutput);
});
code.classes.forEach(klass => {
const comment = getCommentForStatement(code.comments, klass)
const classOutput = processClass(comment, klass, moduleName, namespaceName)
output.push(classOutput);
});
code.namespaces.forEach(namespace => {
const comment = getCommentForStatement(code.comments, namespace)
const namespaceOutput = processNamespace(comment, namespace, moduleName, namespaceName)
output.push(namespaceOutput);
});
return output.join('\n');
}
exports.handlers = {
beforeParse(e) {
parserLines = e.source.split('\n');
const parserOptions = {};
const fileExt = path.extname(e.filename);
if (fileExt.toLowerCase() === ".bs") {
parserOptions.mode = bs.ParseMode.BrighterScript;
}
const lexResult = bs.Lexer.scan(e.source);
const parser = new bs.Parser();
const parseResult = parser.parse(lexResult.tokens, parserOptions);
const statements = parseResult.statements
// Add our module to the top of the file if it doesn't exist. If it does find out the name
const moduleMatch = e.source.match(moduleRegex);
const output = [];
let moduleName = "";
if (pluginOpts.addModule) {
if (moduleMatch) {
moduleName = moduleMatch[1];
} else {
moduleName = path.parse(e.filename).name.split('.')[0].replace(/\./g, '_');
}
output.push(getModuleLineComment(moduleName));
}
output.push(processStatements(statements, moduleName))
e.source = output.join('\n');
// console.log(e.source)
}
};