forked from josdejong/mathjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocgenerator.js
More file actions
732 lines (624 loc) · 20.1 KB
/
Copy pathdocgenerator.js
File metadata and controls
732 lines (624 loc) · 20.1 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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/**
* This is a little tool to generate reference documentation of all math.js
* functions under ./lib/functions. This is NO generic solution.
*
* The tool can parse documentation information from the block comment in the
* functions code, and generate a markdown file with the documentation.
*/
import fs from 'node:fs'
import { glob } from 'glob'
import { mkdirp } from 'mkdirp'
import { deleteSync } from 'del'
import log from 'fancy-log'
// special cases for function syntax
const SYNTAX = {
cbrt: 'math.cbrt(x [, allRoots])',
createUnit: 'math.createUnit(units)',
gcd: 'math.gcd(a, b)',
log: 'math.log(x [, base])',
lcm: 'math.lcm(a, b)',
norm: 'math.norm(x [, p])',
round: 'math.round(x [, n])',
complex: 'math.complex(re, im)',
matrix: 'math.matrix(x)',
sparse: 'math.sparse(x)',
unit: 'math.unit(x)',
evaluate: 'math.evaluate(expr [, scope])',
parse: 'math.parse(expr [, scope])',
concat: 'math.concat(a, b, c, ... [, dim])',
ones: 'math.ones(m, n, p, ...)',
range: 'math.range(start, end [, step])',
resize: 'math.resize(x, size [, defaultValue])',
subset: 'math.subset(x, index [, replacement])',
splitUnit: 'math.splitUnit(unit, parts)',
zeros: 'math.zeros(m, n, p, ...)',
permutations: 'math.permutations(n [, k])',
random: 'math.random([min, max])',
randomInt: 'math.randomInt([min, max])',
format: 'math.format(value [, precision])',
import: 'math.import(object, override)',
print: 'math.print(template, values [, precision])'
}
const IGNORE_FUNCTIONS = {
addScalar: true,
subtractScalar: true,
divideScalar: true,
multiplyScalar: true,
equalScalar: true,
eval: true
}
const IGNORE_WARNINGS = {
seeAlso: ['help', 'intersect', 'clone', 'typeOf', 'chain', 'import', 'config', 'typed',
'distance', 'kldivergence', 'erf'],
parameters: ['parser'],
returns: ['forEach', 'import']
}
/**
* Extract JSON documentation from the comments in a file with JavaScript code
* @param {String} name Function name
* @param {String} code javascript code containing a block comment
* describing a math.js function
* @return {Object} doc json document
*/
export function generateDoc (name, code) {
// get block comment from code
const commentRegex = /\/\*\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//g
// const match = commentRegex.exec(code)
const comments = findAll(code, commentRegex).map(match => getCommentContents(match[0]))
// Find the right comment.
// First search a comment containing the text "Syntax:" and "Examples:".
// If not found, select the first comment
const comment = comments.find(comment => {
return /\n *syntax: *\n/i.exec(comment) && /\n *examples: *\n/i.exec(comment)
}) || comments[0]
if (!comment) {
return null
}
// get text content inside block comment
function getCommentContents (comment) {
return comment.replace('/**', '')
.replace('*/', '')
.replace(/\n\s*\* ?/g, '\n')
.replace(/\r/g, '')
}
const lines = comment.split('\n')
let line = ''
// get next line
function next () {
line = lines.shift()
}
// returns true if current line is empty
function empty () {
return !line || !line.trim()
}
// returns true if there still is a current line
function exists () {
return line !== undefined
}
// returns true if current line is a header like 'Syntax:'
function isHeader () {
return /^(Name|Syntax|Description|Examples|See also)/i.test(line)
}
// returns true if the current line starts with an annotation like @param
function isAnnotation () {
return /^@/.test(line)
}
function skipEmptyLines () {
while (exists() && empty()) next()
}
function stripLeadingSpaces (lines) {
let spaces = null
lines.forEach(function (line) {
const match = /^ +/.exec(line)
const s = match && match[0] && match[0].length
if (s > 0 && (spaces === null || s < spaces)) {
spaces = s
}
})
if (spaces) {
lines.forEach(function (line, index) {
lines[index] = line.substring(spaces)
})
}
}
function parseDescription () {
let description = ''
while (exists() && !isHeader() && !isAnnotation()) {
description += line + '\n'
next()
}
// remove trailing returns
while (description.charAt(description.length - 1) === '\n') {
description = description.substring(0, description.length - 1)
}
doc.description = description
}
function parseSyntax () {
if (/^syntax/i.test(line)) {
next()
skipEmptyLines()
while (exists() && !empty()) {
doc.syntax.push(line)
next()
}
stripLeadingSpaces(doc.syntax)
skipEmptyLines()
return true
}
return false
}
function parseWhere () {
if (/^where/i.test(line)) {
next()
skipEmptyLines()
while (exists() && !empty()) {
doc.where.push(line)
next()
}
skipEmptyLines()
return true
}
return false
}
function parseExamples () {
if (/^example/i.test(line)) {
next()
skipEmptyLines()
while (exists() && (empty() || line.charAt(0) === ' ')) {
doc.examples.push(line)
next()
}
stripLeadingSpaces(doc.examples)
if (doc.examples.length > 0 && doc.examples[doc.examples.length - 1].trim() === '') {
doc.examples.pop()
}
skipEmptyLines()
return true
}
return false
}
function parseSeeAlso () {
if (/^see also/i.test(line)) {
next()
skipEmptyLines()
while (exists() && !empty()) {
const names = line.split(',')
doc.seeAlso = doc.seeAlso.concat(names.map(function (name) {
return name.trim()
}))
next()
}
skipEmptyLines()
return true
}
return false
}
function trim (text) {
return text.trim()
}
// replace characters like '<' with HTML entities like '<'
function escapeTags (text) {
return text.replace(/</g, '<').replace(/>/g, '>')
}
function parseParameters () {
let count = 0
let match
do {
match = /\s*@param\s*\{(.*)}\s*\[?(\w*)]?\s*(.*)?$/.exec(line)
if (match) {
next()
count++
const annotation = {
name: match[2] || '',
description: (match[3] || '').trim(),
types: match[1].split('|').map(trim).map(escapeTags)
}
doc.parameters.push(annotation)
// TODO: this is an ugly hack to extract the default value
const index = annotation.description.indexOf(']')
let defaultValue = null
if (index !== -1) {
defaultValue = annotation.description.substring(1, index).trim()
annotation.description = annotation.description.substring(index + 1).trim()
}
// multi line description (must be non-empty and not start with @param or @return)
while (exists() && !empty() && !/^\s*@/.test(line)) {
const lineTrim = line.trim()
const separator = (lineTrim[0] === '-' ? '</br>' : ' ')
annotation.description += separator + lineTrim
next()
}
if (defaultValue !== null) {
annotation.description += ' Default value: ' + defaultValue + '.'
}
}
} while (match)
return count > 0
}
function parseThrows () {
let count = 0
let match
do {
match = /\s*@throws\s*\{(.*)}\s*(.*)?$/.exec(line)
if (match) {
next()
count++
const annotation = {
description: (match[2] || '').trim(),
type: (match[1] || '').trim()
}
doc.mayThrow.push(annotation)
// multi line description (must be non-empty and not start with @param or @return)
while (exists() && !empty() && !/^\s*@/.test(line)) {
const lineTrim = line.trim()
const separator = (lineTrim[0] === '-' ? '</br>' : ' ')
annotation.description += separator + lineTrim
next()
}
}
} while (match)
return count > 0
}
function parseReturns () {
const match = /\s*@returns?\s*\{(.*)}\s*(.*)?$/.exec(line)
if (match) {
next()
doc.returns = {
description: match[2] || '',
types: match[1].split('|').map(trim).map(escapeTags)
}
// multi line description
while (exists() && !empty() && !/^\s*@/.test(line)) {
doc.returns.description += ' ' + line.trim()
next()
}
return true
}
return false
}
// initialize doc
const doc = {
name: name,
description: '',
syntax: [],
where: [],
examples: [],
seeAlso: [],
parameters: [],
returns: null,
mayThrow: []
}
next()
skipEmptyLines()
parseDescription()
do {
skipEmptyLines()
const handled = parseSyntax() ||
parseWhere() ||
parseExamples() ||
parseSeeAlso() ||
parseParameters() ||
parseReturns() ||
parseThrows()
if (!handled) {
// skip this line, no one knows what to do with it
next()
}
} while (exists())
return doc
}
/**
* Validate whether all required fields are available in given doc
* @param {Object} doc
* @return {String[]} issues
*/
export function validateDoc (doc) {
const issues = []
function ignore (field) {
return IGNORE_WARNINGS[field].includes(doc.name)
}
if (!doc.name) {
issues.push('name missing in document')
}
if (!doc.description) {
issues.push('function "' + doc.name + '": description missing')
}
if (!doc.syntax || doc.syntax.length === 0) {
issues.push('function "' + doc.name + '": syntax missing')
}
if (!doc.examples || doc.examples.length === 0) {
issues.push('function "' + doc.name + '": examples missing')
}
if (doc.parameters && doc.parameters.length) {
doc.parameters.forEach(function (param, index) {
if (!param.name || !param.name.trim()) {
issues.push('function "' + doc.name + '": name missing of parameter ' + index + '')
}
if (!param.description || !param.description.trim()) {
issues.push('function "' + doc.name + '": description missing for parameter ' + (param.name || index))
}
if (!param.types || !param.types.length) {
issues.push('function "' + doc.name + '": types missing for parameter ' + (param.name || index))
}
})
} else {
if (!ignore('parameters')) {
issues.push('function "' + doc.name + '": parameters missing')
}
}
if (doc.mayThrow && doc.mayThrow.length) {
doc.mayThrow.forEach(function (err, index) {
if (!err.type) {
issues.push(
'function "' + doc.name + '": error type missing for throw ' + index)
}
})
}
if (doc.returns) {
if (!doc.returns.description || !doc.returns.description.trim()) {
issues.push('function "' + doc.name + '": description missing of returns')
}
if (!doc.returns.types || !doc.returns.types.length) {
issues.push('function "' + doc.name + '": types missing of returns')
}
} else {
if (!ignore('returns')) {
issues.push('function "' + doc.name + '": returns missing')
}
}
if (!doc.seeAlso || doc.seeAlso.length === 0) {
if (!ignore('seeAlso')) {
issues.push('function "' + doc.name + '": seeAlso missing')
}
}
return issues
}
/**
* Generate markdown
* @param {Object} doc A JSON object generated with generateDoc()
* @param {Object} functions All functions, used to generate correct links
* under seeAlso
* @returns {string} markdown Markdown contents
*/
export function generateMarkdown (doc, functions) {
let text = ''
// TODO: should escape HTML characters in text
text += '<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->\n\n'
text += '# Function ' + doc.name + '\n\n'
text += doc.description + '\n\n\n'
if (doc.syntax && doc.syntax.length) {
text += '## Syntax\n\n' +
'```js\n' +
doc.syntax.join('\n') +
'\n```\n\n'
}
if (doc.where && doc.where.length) {
text += '### Where\n\n' + doc.where.join('\n') + '\n\n'
}
text += '### Parameters\n\n' +
'Parameter | Type | Description\n' +
'--------- | ---- | -----------\n' +
doc.parameters.map(function (p) {
return '`' + p.name + '` | ' +
(p.types ? p.types.join(' | ') : '') + ' | ' +
p.description
}).join('\n') +
'\n\n'
if (doc.returns) {
text += '### Returns\n\n' +
'Type | Description\n' +
'---- | -----------\n' +
(doc.returns.types ? doc.returns.types.join(' | ') : '') + ' | ' + doc.returns.description +
'\n\n\n'
}
if (doc.mayThrow) {
text += '### Throws\n\n' +
'Type | Description\n' +
'---- | -----------\n' +
doc.mayThrow.map(function (t) {
return (t.type || '') + ' | ' + t.description
}).join('\n') +
'\n\n'
}
if (doc.examples && doc.examples.length) {
text += '## Examples\n\n' +
'```js\n' +
doc.examples.join('\n') +
'\n```\n\n\n'
}
if (doc.seeAlso && doc.seeAlso.length) {
text += '## See also\n\n' +
doc.seeAlso.map(function (name) {
return '[' + name + '](' + name + '.md)'
}).join(',\n') +
'\n'
}
return text
}
/**
* Delete all generated function docs (*.md)
* @param {String} outputPath Path to /docs/reference/functions
* @param {String} outputRoot Path to /docs/reference
*/
export function cleanup (outputPath, outputRoot) {
// cleanup previous docs
deleteSync([
outputPath + '/*.md',
outputRoot + '/functions.md'
])
}
/**
* Iterate over all source files and produce an object with information on
* all in-line documentation.
* @param {String[]} functionNames List with all functions exported from the main instance of mathjs
* @param {String} inputPath Path to location of source files
* @returns {object} docinfo
* Object whose keys are function names, and whose values are objects with
* keys name, category, fullPath, doc, and issues
* giving the relevant information
*/
export function collectDocs (functionNames, inputPath) {
function normalizeWindowsPath(path) {
return path.replace(/\\/g, '/')
}
// glob doesn't work on Windows, which has \ separators instead of /
const linuxInputPath = normalizeWindowsPath(inputPath + '**/*.js')
const files = glob.sync(linuxInputPath).sort().map(normalizeWindowsPath)
// generate path information for each of the files
const functions = {} // TODO: change to array
files.forEach(function (fullPath) {
const path = fullPath.split('/')
const name = path.pop().replace(/.js$/, '')
const functionIndex = path.indexOf('function')
let category
// Note: determining whether a file is a function and what it's category
// is a bit tricky and quite specific to the structure of the code,
// we reckon with some edge cases here.
if (!path.includes('docs') && functionIndex !== -1) {
if (path.includes('expression')) {
category = 'expression'
} else if (/\/lib\/cjs\/type\/[a-zA-Z0-9_]*\/function/.test(fullPath)) {
// for type/bignumber/function/bignumber.js, type/fraction/function/fraction.js, etc
category = 'construction'
} else if (/\/lib\/cjs\/core\/function/.test(fullPath)) {
category = 'core'
} else {
category = path[functionIndex + 1]
}
} else if (fullPath.endsWith('/lib/cjs/expression/parse.js')) {
// TODO: this is an ugly special case
category = 'expression'
} else if (path.join('/').endsWith('/lib/cjs/type')) {
// for boolean.js, number.js, string.js
category = 'construction'
}
if (!functionNames.includes(name) || IGNORE_FUNCTIONS[name]) {
category = null
}
if (category) {
functions[name] = {
name,
category,
fullPath
}
} else {
// TODO: throw a warning that no category could be found (instead of silently ignoring it).
// Right now, this matches too many functions, so to do that, we first must make the glob matching relevant
// files more specific, and we need to extend the list with functions we want to ignore.
}
})
// loop over all files, generate a doc for each of them
Object.keys(functions).forEach(name => {
const fn = functions[name]
const code = String(fs.readFileSync(fn.fullPath))
const isFunction = (functionNames.includes(name)) && !IGNORE_FUNCTIONS[name]
const doc = isFunction ? generateDoc(name, code) : null
if (isFunction && doc) {
fn.doc = doc
fn.issues = validateDoc(doc)
} else {
// log('Ignoring', fn.fullPath)
delete functions[name]
}
})
return functions
}
/**
* Iterate over all source files and generate markdown documents for each of them
* @param {String[]} functionNames List with all functions exported from the main instance of mathjs
* @param {String} inputPath Path to /lib/
* @param {String} outputPath Path to /docs/reference/functions
* @param {String} outputRoot Path to /docs/reference
*/
export function iteratePath (functionNames, inputPath, outputPath, outputRoot) {
if (!fs.existsSync(outputPath)) {
mkdirp.sync(outputPath)
}
const functions = collectDocs(functionNames, inputPath)
let issues = []
for (const fn of Object.values(functions)) {
issues = issues.concat(fn.issues)
const markdown = generateMarkdown(fn.doc, functions)
fs.writeFileSync(outputPath + '/' + fn.name + '.md', markdown)
}
/**
* Helper function to generate a markdown list entry for a function.
* Used to generate both alphabetical and categorical index pages.
* @param {string} name Function name
* @returns {string} Returns a markdown list entry
*/
function functionEntry (name) {
const fn = functions[name]
let syntax = SYNTAX[name] || (fn.doc && fn.doc.syntax && fn.doc.syntax[0]) || name
syntax = syntax
// .replace(/^math\./, '')
.replace(/\s+\/\/.*$/, '')
.replace(/;$/, '')
if (syntax.length < 40) {
syntax = syntax.replace(/ /g, ' ')
}
let description = ''
if (fn.doc.description) {
description = fn.doc.description.replace(/\n/g, ' ').split('.')[0] + '.'
}
return '[' + syntax + '](functions/' + name + '.md) | ' + description
}
/**
* Change the first letter of the given string to upper case
* @param {string} text
*/
function toCapital (text) {
return text[0].toUpperCase() + text.slice(1)
}
const order = ['core', 'construction', 'expression'] // and then the rest
function categoryIndex (entry) {
const index = order.indexOf(entry)
return index === -1 ? Infinity : index
}
function compareAsc (a, b) {
return a > b ? 1 : (a < b ? -1 : 0)
}
function compareCategory (a, b) {
const indexA = categoryIndex(a)
const indexB = categoryIndex(b)
return (indexA > indexB) ? 1 : (indexA < indexB ? -1 : compareAsc(a, b))
}
// generate categorical page with all functions
const categories = {}
Object.keys(functions).forEach(function (name) {
const fn = functions[name]
const category = categories[fn.category]
if (!category) {
categories[fn.category] = {}
}
categories[fn.category][name] = fn
})
let categorical = '# Function reference\n\n'
categorical += Object.keys(categories).sort(compareCategory).map(function (category) {
const functions = categories[category]
return '## ' + toCapital(category) + ' functions\n\n' +
'Function | Description\n' +
'---- | -----------\n' +
Object.keys(functions).sort().map(functionEntry).join('\n') + '\n'
}).join('\n')
categorical += '\n\n\n<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->\n'
fs.writeFileSync(outputRoot + '/' + 'functions.md', categorical)
// output all issues
if (issues.length) {
issues.forEach(function (issue) {
log('Warning: ' + issue)
})
log(issues.length + ' warnings')
}
}
function findAll (text, regex) {
const matches = []
let match
do {
match = regex.exec(text)
if (match) {
matches.push(match)
}
} while (match)
return matches
}