import * as ts from "typescript" import * as fs from "fs" import * as pathModule from "path" export const Kinds = ts.SyntaxKind export type KindTree = { name: string children: KindTree[] } export class TSHost implements ts.LanguageServiceHost { constructor(public readonly rootFileNames: string[]) { rootFileNames.forEach(fileName => { this.files[fileName] = { version: 0 }; }); } files: ts.MapLike<{ version: number }> = {}; getScriptFileNames() { return this.rootFileNames } getScriptVersion(fileName) { return this.files[fileName] && this.files[fileName].version.toString() } getScriptSnapshot(fileName) { if (!fs.existsSync(fileName)) { return undefined; } return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString()); } getCurrentDirectory() { return process.cwd() } getCompilationSettings() { return {} } getDefaultLibFileName(options) { return ts.getDefaultLibFilePath(options) } fileExists = ts.sys.fileExists readFile = ts.sys.readFile readDirectory = ts.sys.readDirectory }; export class TSProject { host = new TSHost(this.files) language = ts.createLanguageService(this.host, ts.createDocumentRegistry()) program = this.language.getProgram() constructor(public files: string[]) { } getFile(name): TSFile { let source = this.program.getSourceFile(name) if (!source) return null return new TSFile(this, source) } } export class TSFile { constructor(public readonly project: TSProject, public readonly source: ts.SourceFile) { } private getKindTree(node: ts.Node, depth: number = 1): KindTree { let tree: KindTree = { name: this.getSyntaxKindName(node.kind) , children: [] } if (depth === 0) { tree.children = null return tree } ts.forEachChild(node, (child) => { tree.children.push(this.getKindTree(child, depth - 1)) }) return tree } inspectKind(node: ts.Node, depth: number = 3) { let tree = this.getKindTree(node, depth) this.printKindTree(tree) } private getSyntaxKindName(kind) { for (let name in ts.SyntaxKind) { if (ts.SyntaxKind[name] === kind) { return name } } return "Unknown" } private printKindTree(tree: KindTree, indent = "") { console.error(indent + tree.name) for (let child of tree.children || []) { this.printKindTree(child, indent + " ") } } getClasses(node: ts.Node = this.source): ClassSpec[] { let specs: ClassSpec[] = [] ts.forEachChild(node, (child) => { if (child.kind == Kinds.ClassDeclaration) { specs.push(this.parseClass(child as ts.ClassDeclaration)) } else { specs.push(...this.getClasses(child)) } }) return specs } getClass(name: string, node: ts.Node = this.source) { let classes = this.getClasses(node) for (let cla of classes) { if (cla.name == name) return cla } return null } getNamespaces(node: ts.Node = this.source): NamespaceSpec[] { let specs: NamespaceSpec[] = [] ts.forEachChild(node, (child) => { if (child.kind == Kinds.ModuleDeclaration) { specs.push(this.parseNamespace(child as ts.ModuleDeclaration)) } else { //this.inspectKind(node, 5) specs.push(...this.getNamespaces(child)) } }) return specs } getNamespace(name: string, node: ts.Node = this.source) { let namespacees = this.getNamespaces(node) for (let ns of namespacees) { if (ns.name == name) return ns } return null } parseClass(node: ts.ClassDeclaration | ts.ClassExpression): ClassSpec { let spec: ClassSpec = { name: null, constructor: null, methods: {}, properties: {}, generics: [], base: null, node, children: [] } ts.forEachChild(node, (child) => { spec.children.push(node) if (child.kind == Kinds.ExportKeyword) { spec.export = true } else if (child.kind == Kinds.AbstractKeyword) { spec.abstract = true } else if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else if (child.kind == Kinds.Constructor) { let cons = child as ts.ConstructorDeclaration let info = this.parseMethod(child as ts.MethodDeclaration) spec.constructor = info } else if (child.kind == Kinds.MethodDeclaration) { let method = child as ts.MethodDeclaration let info = this.parseMethod(child as ts.MethodDeclaration) spec.methods[info.name] = info } else if (child.kind == Kinds.PropertyDeclaration) { let prop = child as ts.PropertyDeclaration let info = this.parseProperty(child as ts.PropertyDeclaration) spec.properties[info.name] = info } else if (child.kind == Kinds.HeritageClause) { let base = child as ts.HeritageClause spec.base = this.parseHeritage(base) } else if (child.kind == Kinds.TypeParameter) { spec.generics.push(this.parseTypeParameter(child as ts.TypeParameterDeclaration)) } else { console.trace() console.error("Unknown kind", this.getSyntaxKindName(child.kind), this.getSyntaxKindName(node.kind)) console.error(child.getText()) console.error(node.getText()) this.inspectKind(child, 8) } }) return spec } parseTypeParameter(node: ts.TypeParameterDeclaration) { let spec: TypeParamSpec = { name: null, default: null } ts.forEachChild(node, child => { if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } }) return spec } parseFunction(node: ts.FunctionExpression): FunctionSpec { let spec: FunctionSpec = { parameters: [], node, block: null } ts.forEachChild(node, (child) => { if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else if (child.kind == Kinds.Parameter) { let param = child as ts.ParameterDeclaration let info = this.parseParam(param) spec.parameters.push(info) } else { spec.block = this.parseBlock(child as ts.Block) } }) return spec } parseMethod(node: ts.MethodDeclaration): MethodSpec { let spec: MethodSpec = { name: null, parameters: [], permission: "public", node, block: null } ts.forEachChild(node, (child) => { if (child.kind == Kinds.PublicKeyword) { spec.permission = "public" } else if (child.kind == Kinds.PrivateKeyword) { spec.permission = "private" } else if (child.kind == Kinds.ProtectedKeyword) { spec.permission = "protected" } else if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else if (child.kind == Kinds.Parameter) { let param = child as ts.ParameterDeclaration let info = this.parseParam(param) spec.parameters.push(info) } else { spec.block = this.parseBlock(child as ts.Block) } }) return spec } parseProperty(node: ts.PropertyDeclaration): PropertySpec { let spec: PropertySpec = { name: null, permission: "public", node, } ts.forEachChild(node, (child) => { if (child.kind == Kinds.AbstractKeyword) { spec.abstract = true } else if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else if (child.kind == Kinds.ReadonlyKeyword) { spec.readonly = true } else if (child.kind == Kinds.PublicKeyword) { spec.permission = "public" } else if (child.kind == Kinds.PrivateKeyword) { spec.permission = "private" } else if (child.kind == Kinds.ProtectedKeyword) { spec.permission = "protected" } else if (child.kind == Kinds.TypeLiteral) { spec.type = this.parseTypeLiteral(child as ts.TypeLiteralNode) } else if (child.kind == Kinds.TypeReference) { spec.type = this.parseTypeReference(child as ts.TypeReferenceNode) } else if (child.kind == Kinds.FunctionExpression) { spec.type = this.parseTypeReference(child as ts.TypeReferenceNode) } else if (child.kind == Kinds.ArrayType) { let arr = child as ts.ArrayTypeNode spec.type = this.parseTypeReference(arr) } else { spec.value = this.parseValue(child) } }) return spec } parseParam(node: ts.ParameterDeclaration): ParameterSpec { let spec: ParameterSpec = { name: null, type: null, node, } ts.forEachChild(node, (child) => { if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else if (child.kind == Kinds.TypeReference) { let ref = child as any as ts.TypeReferenceNode spec.type = this.parseTypeReference(ref) } else if (child.kind == Kinds.TypeLiteral) { let ref = child as ts.TypeLiteralNode spec.type = this.parseTypeLiteral(ref) } }) return spec } parseTypeLiteral(node: ts.TypeLiteralNode): TypeAnnotationSpec { let spec: TypeAnnotationSpec = { literal: null, base: null, reference: null, genericLiteral: null, node, } spec.literal = node.getText(this.source) return spec } parseTypeReference(node: ts.TypeReferenceNode | ts.ArrayTypeNode): TypeAnnotationSpec { let spec: TypeAnnotationSpec = { literal: null, base: null, reference: null, genericLiteral: null, node, } spec.literal = node.getText(this.source) return spec } parseNamespace(node: ts.ModuleDeclaration): NamespaceSpec { let spec: NamespaceSpec = { name: null, node: node, block: null, } ts.forEachChild(node, (child) => { if (child.kind == Kinds.ExportKeyword) { spec.export = true } else if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else if (child.kind == Kinds.ModuleBlock) { spec.block = this.parseBlock(child as ts.BlockLike) } else { console.error("Unknown name space kind", this.getSyntaxKindName(child.kind)) } }) return spec } parseBlock(node: ts.BlockLike = this.source): BlockSpec { let spec: BlockSpec = { node, variables: {}, classes: {}, namespaces: {}, children: [], } ts.forEachChild(node, child => { spec.children.push(child) if (child.kind == Kinds.VariableStatement) { let vars = this.parseVariableStatement(child as ts.VariableStatement) for (let va of vars) { spec.variables[va.name] = va } } else if (child.kind == Kinds.ModuleDeclaration) { let mod = child as ts.ModuleDeclaration let modSpec = this.parseNamespace(mod) spec.namespaces[modSpec.name] = modSpec } else if (child.kind == Kinds.ClassDeclaration) { let claSpec = this.parseClass(child as ts.ClassDeclaration) spec.classes[claSpec.name] = claSpec } }) return spec } parseVariableStatement(node: ts.VariableStatement): VariableSpec[] { let specs: VariableSpec[] = [] let exp = false ts.forEachChild(node, (child) => { if (child.kind == Kinds.ExportKeyword) { exp = true } else if (child.kind == Kinds.VariableDeclarationList) { let list = child as ts.VariableDeclarationList for (let dec of list.declarations) { let spec = this.parseVariableDeclaration(dec) spec.export = exp specs.push(spec) } } }) return specs } parseVariableDeclaration(node: ts.VariableDeclaration) { let id = node.exclamationToken let spec: VariableSpec = { name: null, value: null } ts.forEachChild(node, child => { if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.name = id.text } else { spec.value = this.parseValue(child) } }) return spec } parseStatement(node: ts.Statement): StatementSpec { let spec: StatementSpec = { type: null, } if (node.kind == Kinds.VariableStatement) { let vs = node as ts.VariableStatement ts.forEachChild(vs, child => { if (child.kind == Kinds.ExportKeyword) { spec.export = true } else if (child.kind == Kinds.VariableDeclarationList) { let list = child as ts.VariableDeclarationList list.declarations } }) } return spec } explain(depth = 10) { this.inspectKind(this.source, depth) } parseHeritage(node: ts.HeritageClause): HeritageSpec { let spec: HeritageSpec = { name: null, class: null, node, generics: [] } let id: ts.Identifier = null // We may find many identifier, we use the last one ts.forEachChild(node, child => { if (child.kind == Kinds.ExpressionWithTypeArguments) { let exp = child as ts.ExpressionWithTypeArguments ts.forEachChild(child, child => { if (child.kind == Kinds.PropertyAccessExpression) { let acc = this.resolvePropertyAccess(child as ts.PropertyAccessExpression) let last = acc.nodes[acc.nodes.length - 1] if (last) { id = last as ts.Identifier spec.name = id.text } else { console.error("Unknown access expression") this.inspectKind(child, 3) } } }) } else if (child.kind == Kinds.PropertyAccessExpression) { let acc = this.resolvePropertyAccess(child as ts.PropertyAccessExpression) let last = acc.nodes[acc.nodes.length - 1] if (last) { id = last as ts.Identifier spec.name = id.text } else { console.error("Unknown access expression") this.inspectKind(child, 3) } } }) if (!id) { //this.inspectKind(node, 8) //console.log("Missing hist id", node.getText()) } if (id) { spec.name let def = this.project.language.getDefinitionAtPosition(this.source.fileName, id.getStart()) let checker = this.project.program.getTypeChecker() let symbol = checker.getSymbolAtLocation(id) let type = checker.getTypeOfSymbolAtLocation(symbol, id) if (type && type.symbol) { let cla = type.symbol.declarations[0] spec.class = this.parseClass(cla as ts.ClassDeclaration) } else { console.log("Missing symbol", id.text) } } return spec } resolve(symbol: ts.Symbol) { let node = symbol.declarations[0] let checker = this.project.program.getTypeChecker() return checker.getSymbolAtLocation(node) } shouldSkipAlias(node: ts.Node, declaration: ts.Node): boolean { if (node.kind !== Kinds.Identifier) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { case Kinds.ImportClause: case Kinds.ImportEqualsDeclaration: return true; case Kinds.ImportSpecifier: return declaration.parent.kind === Kinds.NamedImports; default: return false; } } private resolvePropertyAccess(node: ts.PropertyAccessExpression): PropertyAccessSpec { let spec: PropertyAccessSpec = { accesses: [], nodes: [] } ts.forEachChild(node, child => { if (child.kind == Kinds.PropertyAccessExpression) { spec = this.resolvePropertyAccess(child as ts.PropertyAccessExpression) } else if (child.kind == Kinds.Identifier) { let id = child as ts.Identifier spec.accesses.push(id.text) spec.nodes.push(id) } else if (child.kind == Kinds.ThisKeyword) { spec.accesses.push("this") spec.nodes.push(child) } else if (child.kind == Kinds.SuperKeyword) { spec.accesses.push("super") spec.nodes.push(child) } else if (child.kind == Kinds.CallExpression) { spec.accesses.push(child.getFullText()) spec.nodes.push(child) spec.anonymous = true } else { console.error("Unknown access element") this.inspectKind(node) } }) return spec } parseValue(node: ts.Node) { let value: ValueSpec = { type: "literal", node } if (node.kind == Kinds.StringLiteral) { let str = node as ts.StringLiteral value.literal = str.getText() value.literalType = "string" value.literalValue = JSON.parse(value.literal) } else if (node.kind == Kinds.NumericLiteral) { let num = node as ts.NumericLiteral value.literal = num.text value.literalType = "number" value.literalValue = JSON.parse(num.text) } else if (node.kind == Kinds.TrueKeyword) { let yes = node as ts.BooleanLiteral value.literal = "true" value.literalType = "boolean" value.literalValue = true } else if (node.kind == Kinds.FalseKeyword) { let no = node as ts.BooleanLiteral value.literal = "false" value.literalType = "boolean" value.literalValue = false } else if (node.kind == Kinds.ObjectLiteralExpression) { } else if (node.kind == Kinds.PropertyAccessExpression) { value.type = "reference" value.access = this.resolvePropertyAccess(node as ts.PropertyAccessExpression) } else if (node.kind == Kinds.CallExpression) { value.type = "invoke" value.invoke = this.parseInvoke(node as ts.CallExpression) } return value } parseInvoke(node: ts.CallExpression): InvokeSpec { let spec: InvokeSpec = { node, invoke: null, params: [] } let stack: ValueSpec[] = [] ts.forEachChild(node, child => { stack.push(this.parseValue(child)) }) spec.invoke = stack.shift() spec.params = stack return spec } querySelect(node: ts.Node, route: string[] | string): ts.Node { if (route.length == 0) return node if (!node) return null if (typeof route == "string") { route = [route] } let first = route.shift() let children = node.getChildren() for (let child of children) { if (this.getSyntaxKindName(child.kind) == first) { return this.querySelect(child, route) } } return null } } export type ClassSpec = { name: string constructor: MethodSpec methods: { [name: string]: MethodSpec } properties: { [name: string]: PropertySpec } export?: boolean abstract?: boolean node: ts.ClassDeclaration | ts.ClassExpression base: HeritageSpec generics: TypeParamSpec[] children: ts.Node[] } export type TypeParamSpec = { name: string default: TypeAnnotationSpec } export type NamespaceSpec = { name: string node: ts.Node block: BlockSpec export?: boolean } export type BlockSpec = { node: ts.BlockLike children: ts.Node[], variables: { [name: string]: VariableSpec } classes: { [name: string]: ClassSpec } namespaces: { [name: string]: NamespaceSpec } } export type StatementSpec = { type: "variable" export?: boolean declarations?: { [name: string]: { value: ValueSpec } } } export type VariableSpec = { export?: boolean const?: boolean name: string value: ValueSpec } export type HeritageSpec = { name: string class: ClassSpec node: ts.HeritageClause generics: TypeAnnotationSpec[] } export type FunctionSpec = { name?: string parameters: ParameterSpec[] export?: boolean node: ts.Node block: BlockSpec } export type ParameterSpec = { name: string type: TypeAnnotationSpec value?: ValueSpec node: ts.Node } export type MethodSpec = FunctionSpec & { abstract?: boolean permission: "public" | "private" | "protected" node: ts.Node } export type PropertySpec = { name: string permission: "public" | "private" | "protected" abstract?: boolean readonly?: boolean type?: TypeAnnotationSpec value?: ValueSpec node: ts.Node } export type ValueSpec = { type: "reference" | "literal" | "function" | "invoke" literal?: string literalType?: "number" | "string" | "object" | "boolean" | "null" literalValue?: any access?: PropertyAccessSpec invoke?: InvokeSpec node: ts.Node } export type TypeAnnotationSpec = { // ABC.FooType literal: string // FooType base: string // ABC.FooType reference: string // [a,b,c] genericLiteral: string[] node: ts.Node } export type InvokeSpec = { node: ts.Node invoke: ValueSpec params: ValueSpec[] } export type PropertyAccessSpec = { accesses: string[] nodes: ts.Node[] anonymous?: boolean }