-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcreate_import_list.js
243 lines (224 loc) · 7.39 KB
/
create_import_list.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
import fs from 'fs'
import ts from 'typescript'
const createEntrypoint = async () => {
let code = `import Matrix from './util/matrix.js'
import Tensor from './util/tensor.js'
import Graph from './util/graph.js'
import Complex from './util/complex.js'
`
const getComment = async (filename, name) => {
const text = (await fs.promises.readFile(`./lib/${filename}`)).toString()
const source = ts.createSourceFile(`./lib/${filename}`, text, ts.ScriptTarget.Latest)
let comment = ''
source.forEachChild(node => {
if (node.name?.escapedText === name) {
const commentRanges = ts.getLeadingCommentRanges(text, node.getFullStart())
if (!commentRanges || commentRanges.length === 0) {
return
}
const commentRange = commentRanges[commentRanges.length - 1]
comment += text.slice(commentRange.pos, commentRange.end)
}
})
comment = comment.replaceAll(/^\s*(\/\*\*|\*(\/)?)/gm, '')
const comments = comment.split(/\r|\r\n|\n/).map(v => v.trim())
let com = ''
for (let i = 0; i < comments.length; i++) {
if (comments[i].length === 0) {
if (com.length === 0) {
continue
}
break
} else if (comments[i].startsWith('@')) {
continue
}
com += ' ' + comments[i]
}
return com
}
const createImportStatement = async filename => {
const mod = await import(`./lib/${filename}`)
let d = null
const named = []
for (const name of Object.keys(mod)) {
if (name === 'default') {
d = mod.default
} else {
const comment = await getComment(filename, name)
named.push({ name, comment })
}
}
if (d) {
if (named.length === 0) {
code += `import ${d.name} from './${filename}'\n`
} else {
code += `import ${d.name}, { ${named.map(v => v.name).join(', ')} } from './${filename}'\n`
}
const comment = await getComment(filename, d.name)
named.push({ name: d.name, comment })
} else if (named.length > 0) {
code += `import { ${named.map(v => v.name).join(', ')} } from './${filename}'\n`
}
return named
}
const importNames = async dirname => {
const files = await fs.promises.readdir(`./lib/${dirname}`, { withFileTypes: true })
const names = []
for (const file of files) {
if (file.isFile() && file.name.endsWith('.js')) {
const named = await createImportStatement(`${dirname}/${file.name}`)
names.push(...named)
}
}
return names
}
const modelNames = await importNames('model')
const rlNames = await importNames('rl')
const evaluateNames = await importNames('evaluate')
code += `
/**
* Default export object.
* @module default
* @property {Tensor} Tensor Tensor class
* @property {Matrix} Matrix Matrix class
* @property {Graph} Graph Graph class
* @property {Complex} Complex Complex number
*/
export default {
Tensor,
Matrix,
Graph,
Complex,
`
const addExports = (key, names) => {
code += ' /**\n * @memberof default\n'
for (const name of names) {
code += ` * @property {${name.name}} ${name.name}${name.comment}\n`
}
code += ` */\n ${key}: {\n`
for (const name of names) {
code += ` ${name.name},\n`
}
code += ' },\n'
}
addExports('models', modelNames)
addExports('rl', rlNames)
addExports('evaluate', evaluateNames)
code += '}'
await fs.promises.writeFile('./lib/index.js', '// This file is generated automatically.\n' + code)
}
const createLayerlist = async () => {
const layerDir = './lib/model/nns/layer'
const files = await fs.promises.readdir(layerDir)
let code = ''
const types = []
for (const file of files) {
if (file === 'base.js') {
const text = (await fs.promises.readFile(`${layerDir}/${file}`)).toString()
const source = ts.createSourceFile(`${layerDir}/${file}`, text, ts.ScriptTarget.Latest)
source.forEachChild(node => {
if (
ts.isVariableStatement(node) &&
['unaryLayers', 'binaryLayers', 'compareLayers'].includes(
node.declarationList.declarations[0].name.escapedText
)
) {
const init = node.declarationList.declarations[0].initializer
for (const property of init.properties) {
types.push({ type: property.name.escapedText })
}
}
})
} else if (file !== 'index.js' && file.endsWith('.js')) {
const text = (await fs.promises.readFile(`${layerDir}/${file}`)).toString()
const source = ts.createSourceFile(`${layerDir}/${file}`, text, ts.ScriptTarget.Latest)
let className = null
let typeName = null
const params = []
source.forEachChild(node => {
if (ts.isClassDeclaration(node) && !className) {
className = node.name.escapedText
node.forEachChild(cnode => {
if (ts.isConstructorDeclaration(cnode)) {
const commentRanges = ts.getLeadingCommentRanges(text, cnode.getFullStart())
if (!commentRanges || commentRanges.length === 0) {
return
}
const commentRange = commentRanges[commentRanges.length - 1]
const comment = text.slice(commentRange.pos, commentRange.end)
for (const param of comment.matchAll(
/@param \{(?<type>.*)\} (?<optional>\[?)(?<name>[0-9a-zA-Z._]+)(=?(?<default>.*)\])? (?<description>.*)/g
)) {
if (param.groups.name.startsWith('config.')) {
const name = param.groups.name.slice('config.'.length)
params.push({ name, type: param.groups.type, optional: param.groups.optional })
}
}
}
})
}
if (ts.isExpressionStatement(node) && node.expression.expression.expression.escapedText === className) {
const args = node.expression.arguments
if (args.length === 0) {
typeName = className
.replace(/Layer$/, '')
.replace(/[A-Z]/g, s => '_' + s.toLowerCase())
.slice(1)
} else {
typeName = args[0].text
}
}
})
code += `export { default as ${className} } from './${file}'\n`
types.push({ type: typeName, params })
}
}
types.sort((a, b) => (a.type < b.type ? -1 : 1))
let typeCode = `
/**
* @ignore
* @typedef {import("../../../util/matrix").default} Matrix
* @ignore
* @typedef {import("../../../util/tensor").default} Tensor
* @ignore
* @typedef {import("../../neuralnetwork").default} NeuralNetwork
*/
/**
* @typedef {(
`
for (const type of types) {
typeCode += ` * { type: '${type.type}'`
type.params?.forEach(param => {
typeCode += `, ${param.name}${param.optional ? '?' : ''}: ${param.type}`
})
typeCode += ' } |\n'
}
typeCode = typeCode.slice(0, typeCode.length - 3) + '\n * )} PlainLayerObject\n */\n'
await fs.promises.writeFile(layerDir + '/index.js', '// This file is generated automatically.\n' + code + typeCode)
}
const createONNXOperatorlist = async () => {
const operatorsDir = './lib/model/nns/onnx/operators'
const files = await fs.promises.readdir(operatorsDir)
let code = ''
for (const file of files) {
if (file !== 'index.js' && file.endsWith('.js')) {
code += `export { default as ${file.slice(0, -3)} } from './${file}'\n`
}
}
await fs.promises.writeFile(operatorsDir + '/index.js', '// This file is generated automatically.\n' + code)
}
const createONNXLayerlist = async () => {
const layerDir = './lib/model/nns/onnx/layer'
const files = await fs.promises.readdir(layerDir)
let code = ''
for (const file of files) {
if (file !== 'index.js' && file.endsWith('.js')) {
code += `export { default as ${file.slice(0, -3)} } from './${file}'\n`
}
}
await fs.promises.writeFile(layerDir + '/index.js', '// This file is generated automatically.\n' + code)
}
await createLayerlist()
await createONNXLayerlist()
await createONNXOperatorlist()
await createEntrypoint()