/
ModelGenerator.ts
364 lines (334 loc) · 10.5 KB
/
ModelGenerator.ts
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
import * as fs from 'fs'
import * as path from 'path'
import ts from 'typescript'
// import { createWalker } from './ProgramWalker'
import { Project } from '@ts-morph/bootstrap'
import { typeToLinkedSymbolParts } from './LinkedSymbolPartsWriter'
import {
Model,
SymbolData,
DeclarationInfo,
TypeInfo,
SignatureInfo,
NamedSymbolInfo,
SourceFileData,
} from './Model'
export type GenerateOptions = {
debug?: boolean
}
/**
* The result of calling `generateDocs()`.
*/
export interface GenerateDocsResult {
/**
* The documentation data.
*/
model: Model
/**
* The `ts.Program` instance created from generating the documentation.
*/
program: ts.Program
/**
* The `ts.TypeChecker` for the `program`.
*/
checker: ts.TypeChecker
}
/**
* Generates a documentation data.
*
* @param rootFilename An array representing filepaths of public modules.
*/
export function generateDocs(
rootFileNames: string[],
generateOptions: GenerateOptions = {},
): GenerateDocsResult {
rootFileNames = rootFileNames.map(n => fs.realpathSync(n))
const basePath = require('commondir')(rootFileNames.map(f => path.dirname(f)))
const { options } = ts.convertCompilerOptionsFromJson(
{ allowJs: true },
basePath,
)
const project = new Project({
compilerOptions: options,
})
const entrySourceFiles = project.addSourceFilesByPaths(rootFileNames)
const program = project.createProgram()
const typeChecker = program.getTypeChecker()
const languageService = project.getLanguageService()
if (generateOptions.debug) {
void languageService
debugger
}
const entryModuleSymbolIds: string[] = []
const entrySourceFileIds: string[] = []
function main() {
const sourceFilesSet = new Set(entrySourceFiles)
for (const file of entrySourceFiles) {
if (!file) continue
entrySourceFileIds.push(getSourceFileId(file))
const moduleSymbol = typeChecker.getSymbolAtLocation(file)
if (!moduleSymbol) continue
entryModuleSymbolIds.push(visitSymbol(moduleSymbol))
}
if (!entryModuleSymbolIds.length) {
for (const ambientModule of typeChecker.getAmbientModules()) {
if (
ambientModule
.getDeclarations()
?.some(d => sourceFilesSet.has(d.getSourceFile()))
) {
entryModuleSymbolIds.push(visitSymbol(ambientModule))
}
}
}
while (symbolsToElaborate.size > 0) {
const symbols = [...symbolsToElaborate]
symbolsToElaborate = new Set()
for (const symbol of symbols) {
if (!elaboratedSymbols.has(symbol)) {
elaboratedSymbols.add(symbol)
elaborateOnSymbol(symbol)
}
}
}
}
let symbolsToElaborate = new Set<ts.Symbol>()
const elaboratedSymbols = new Set<ts.Symbol>()
const symbolToIdMap = new Map<ts.Symbol, string>()
const symbolDataById: { [id: string]: SymbolData } = {}
let nextSymbolId = 1
const sourceFileToIdMap = new Map<ts.SourceFile, string>()
const sourceFileDataById: { [id: string]: SourceFileData } = {}
let nextSourceFileId = 1
function getSourceFileId(sourceFile: ts.SourceFile): string {
const existingId = sourceFileToIdMap.get(sourceFile)
if (existingId) return existingId
const id = `${nextSourceFileId++}`
sourceFileToIdMap.set(sourceFile, id)
const sourceFileData: SourceFileData = {
id,
fileName: sourceFile.fileName,
}
sourceFileDataById[id] = sourceFileData
return id
}
function getSymbolId(symbol: ts.Symbol): string {
if (symbol.getFlags() & ts.SymbolFlags.Alias) {
const aliasedSymbol = typeChecker.getAliasedSymbol(symbol)
return getSymbolId(aliasedSymbol)
}
const existingId = symbolToIdMap.get(symbol)
if (existingId) return existingId
const name = symbol.getName()
const id = `${nextSymbolId++}_${name}`
symbolToIdMap.set(symbol, id)
const symbolData: SymbolData = {
id,
name: name,
flags: getSymbolFlags(symbol),
documentationComment: symbol.getDocumentationComment(typeChecker),
jsDocTags: symbol.getJsDocTags(),
}
symbolDataById[id] = symbolData
console.log('Reading', id, `[${symbolData.flags}]`)
const declarations = symbol.getDeclarations()
if (declarations) {
symbolData.declarations = []
for (const declaration of declarations) {
const info = getDeclarationInfo(declaration)
if (info) symbolData.declarations.push(info)
}
}
return id
}
function getDeclarationInfo(declaration: ts.Declaration) {
if (!declaration) return
const startPosition = declaration.getStart()
const sourceFile = declaration.getSourceFile()
const start = sourceFile.getLineAndCharacterOfPosition(startPosition)
const declaredAt: DeclarationInfo = {
line: start.line,
character: start.character,
position: startPosition,
sourceFile: getSourceFileId(sourceFile),
}
return declaredAt
}
function visitSymbol(symbol: ts.Symbol): string {
if (symbol.getFlags() & ts.SymbolFlags.Alias) {
const aliasedSymbol = typeChecker.getAliasedSymbol(symbol)
return visitSymbol(aliasedSymbol)
}
const id = getSymbolId(symbol)
symbolsToElaborate.add(symbol)
return id
}
function elaborateOnSymbol(symbol: ts.Symbol) {
const id = getSymbolId(symbol)
const symbolData = symbolDataById[id]
console.log('Elaborating', id)
const declaredType = typeChecker.getDeclaredTypeOfSymbol(symbol)
Object.assign(symbolData, {
_declaredType: typeChecker.typeToString(declaredType),
})
const firstlyDeclared = symbol.getDeclarations()?.[0]
const symbolType =
firstlyDeclared &&
typeChecker.getTypeOfSymbolAtLocation(symbol, firstlyDeclared)
if (symbolType) {
Object.assign(symbolData, {
_symbolType: typeChecker.typeToString(symbolType, firstlyDeclared),
})
}
const symbolFlags = symbol.getFlags()
if (symbolFlags & ts.SymbolFlags.Module) {
const exported = typeChecker.getExportsOfModule(symbol)
symbolData.exports = exported.map(visitNamedSymbol)
}
if (symbolFlags & ts.SymbolFlags.TypeAlias) {
const declarationType =
firstlyDeclared &&
ts.isTypeAliasDeclaration(firstlyDeclared) &&
firstlyDeclared.type
symbolData.type =
declarationType && ts.isTypeLiteralNode(declarationType)
? getElaboratedTypeInfo(declaredType, symbol)
: getBriefTypeInfo(declaredType)
}
if (symbolFlags & ts.SymbolFlags.Variable && symbolType) {
symbolData.type = getBriefTypeInfo(symbolType)
}
if (symbolFlags & ts.SymbolFlags.Function && symbolType) {
symbolData.type = getBriefTypeInfo(symbolType)
}
if (symbolFlags & ts.SymbolFlags.Interface) {
symbolData.type = getElaboratedTypeInfo(declaredType, symbol)
}
if (symbolFlags & ts.SymbolFlags.Class && symbolType) {
symbolData.type = getElaboratedTypeInfo(declaredType, symbol)
symbolData.static = getElaboratedTypeInfo(symbolType, symbol)
}
if (symbolFlags & ts.SymbolFlags.Method && symbolType) {
symbolData.type = getBriefTypeInfo(symbolType)
}
}
function getBriefTypeInfo(type: ts.Type): TypeInfo {
return {
parts: protectFromFailure(
() =>
typeToLinkedSymbolParts(typeChecker, type).map(x =>
x.symbol ? [getSymbolId(x.symbol), x.text] : x.text,
),
e => [`Failed to generate parts: ${e}`],
),
flags: getTypeFlags(type),
}
}
function protectFromFailure<T>(f: () => T, fallback: (e: Error) => T) {
try {
return f()
} catch (e) {
return fallback(e)
}
}
function getElaboratedTypeInfo(
type: ts.Type,
parentSymbol: ts.Symbol,
): TypeInfo {
const parentSymbolDeclarations = new Set<ts.Node>(
parentSymbol.getDeclarations() || [],
)
const properties = typeChecker.getPropertiesOfType(type)
const callSignatures = typeChecker.getSignaturesOfType(
type,
ts.SignatureKind.Call,
)
const constructSignatures = typeChecker.getSignaturesOfType(
type,
ts.SignatureKind.Construct,
)
return {
...getBriefTypeInfo(type),
callSignatures: callSignatures.map(getSignatureInfo),
constructSignatures: constructSignatures.map(getSignatureInfo),
properties: properties.map(property => {
const declaration = property.getDeclarations()?.[0]
let inherited = true
for (
let node: ts.Node | undefined = declaration;
node;
node = node.parent
) {
if (parentSymbolDeclarations.has(node)) {
inherited = false
break
}
}
return {
name: property.getName(),
symbol: visitSymbol(property),
inherited,
}
}),
}
}
function getSignatureInfo(signature: ts.Signature): SignatureInfo {
return {
declaration: getDeclarationInfo(signature.getDeclaration()),
documentationComment: signature.getDocumentationComment(typeChecker),
jsDocTags: signature.getJsDocTags(),
parameters: signature.getParameters().map(visitNamedSymbol),
returnType: getBriefTypeInfo(signature.getReturnType()),
// TODO: getTypeParameters
}
}
function visitNamedSymbol(symbol: ts.Symbol): NamedSymbolInfo {
return { name: symbol.getName(), symbol: visitSymbol(symbol) }
}
function getSymbolFlags(symbol: ts.Symbol): string[] {
const flags = symbol.getFlags()
const out: string[] = []
for (const [key, value] of Object.entries(ts.SymbolFlags)) {
if (
typeof value === 'number' &&
value.toString(2).match(/^10*$/) &&
!key.match(/Excludes/) &&
flags & value
) {
out.push(key)
}
}
return out
}
function getTypeFlags(type: ts.Type): string[] {
const flags = type.getFlags()
const out: string[] = []
for (const [key, value] of Object.entries(ts.TypeFlags)) {
if (
typeof value === 'number' &&
value.toString(2).match(/^10*$/) &&
flags & value
) {
out.push(key)
}
}
return out
}
main()
console.log(
`Symbol stats: ` +
`${program.getSymbolCount()} total, ` +
`${Object.keys(symbolDataById).length} read, ` +
`${elaboratedSymbols.size} elaborated`,
)
return {
model: {
entryModules: entryModuleSymbolIds,
entrySourceFiles: entrySourceFileIds,
symbols: Object.values(symbolDataById),
sourceFiles: Object.values(sourceFileDataById),
},
program,
checker: typeChecker,
}
}