idlize

Форк
0
/
dependencies_collector.ts 
193 строки · 7.4 Кб
1
/*
2
 * Copyright (c) 2024 Huawei Device Co., Ltd.
3
 * Licensed under the Apache License, Version 2.0 (the "License");
4
 * you may not use this file except in compliance with the License.
5
 * You may obtain a copy of the License at
6
 *
7
 * http://www.apache.org/licenses/LICENSE-2.0
8
 *
9
 * Unless required by applicable law or agreed to in writing, software
10
 * distributed under the License is distributed on an "AS IS" BASIS,
11
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
 * See the License for the specific language governing permissions and
13
 * limitations under the License.
14
 */
15

16
import * as ts from 'typescript'
17
import { DeclarationConvertor, TypeNodeConvertor, convertDeclaration, convertTypeNode } from "./TypeNodeConvertor";
18
import { getDeclarationsByNode } from '../util';
19
import { mapType } from './TypeNodeNameConvertor';
20

21
export class TypeDependenciesCollector implements TypeNodeConvertor<ts.Declaration[]> {
22
    constructor(protected readonly typeChecker: ts.TypeChecker) {}
23

24
    convertUnion(node: ts.UnionTypeNode): ts.Declaration[] {
25
        return node.types.flatMap(type => convertTypeNode(this, type))
26
    }
27
    convertTypeLiteral(node: ts.TypeLiteralNode): ts.Declaration[] {
28
        return node.members.flatMap(it => {
29
            if (ts.isPropertySignature(it)) {
30
                return convertTypeNode(this, it.type!)
31
            }
32
            if (ts.isIndexSignatureDeclaration(it))
33
                return [
34
                    ...it.parameters.flatMap(it => this.convert(it.type)),
35
                    ...this.convert(it.type),
36
                ]
37
            throw new Error(`Not implemented ${ts.SyntaxKind[it.kind]}`)
38
        })
39
    }
40
    convertLiteralType(node: ts.LiteralTypeNode): ts.Declaration[] {
41
        return []
42
    }
43
    convertTuple(node: ts.TupleTypeNode): ts.Declaration[] {
44
        return node.elements.flatMap(it => {
45
            if (ts.isNamedTupleMember(it))
46
                return convertTypeNode(this, it.type)
47
            return convertTypeNode(this, it)
48
        })
49
    }
50
    convertArray(node: ts.ArrayTypeNode): ts.Declaration[] {
51
        return convertTypeNode(this, node.elementType)
52
    }
53
    convertOptional(node: ts.OptionalTypeNode): ts.Declaration[] {
54
        return convertTypeNode(this, node.type)
55
    }
56
    convertFunction(node: ts.FunctionTypeNode): ts.Declaration[] {
57
        return [
58
            ...node.parameters.flatMap(it => convertTypeNode(this, it.type!)),
59
            ...convertTypeNode(this, node.type),
60
        ]
61
    }
62
    convertTemplateLiteral(node: ts.TemplateLiteralTypeNode): ts.Declaration[] {
63
        return []
64
    }
65
    convertImport(node: ts.ImportTypeNode): ts.Declaration[] {
66
        return []
67
    }
68
    convertTypeReference(node: ts.TypeReferenceNode): ts.Declaration[] {
69
        let declarations = getDeclarationsByNode(this.typeChecker, node.typeName)
70
        if (declarations.length > 1) {
71
            console.log(`WARNING: Duplicate declarations temporary unsupported: ${mapType(node)}`)
72
            declarations = [declarations[0]]
73
        }
74
        return [
75
            ...(node.typeArguments?.flatMap(it => convertTypeNode(this, it)) ?? []),
76
            ...declarations.map(it => {
77
                return ts.isEnumMember(it) ? it.parent : it
78
            }),
79
        ]
80
    }
81
    convertParenthesized(node: ts.ParenthesizedTypeNode): ts.Declaration[] {
82
        return convertTypeNode(this, node.type)
83
    }
84
    convertIndexedAccess(node: ts.IndexedAccessTypeNode): ts.Declaration[] {
85
        throw new Error('Method not implemented.');
86
    }
87
    convertStringKeyword(node: ts.TypeNode): ts.Declaration[] {
88
        return []
89
    }
90
    convertNumberKeyword(node: ts.TypeNode): ts.Declaration[] {
91
        return []
92
    }
93
    convertBooleanKeyword(node: ts.TypeNode): ts.Declaration[] {
94
        return []
95
    }
96
    convertUndefinedKeyword(node: ts.TypeNode): ts.Declaration[] {
97
        return []
98
    }
99
    convertVoidKeyword(node: ts.TypeNode): ts.Declaration[] {
100
        return []
101
    }
102
    convertObjectKeyword(node: ts.TypeNode): ts.Declaration[] {
103
        return []
104
    }
105
    convertAnyKeyword(node: ts.TypeNode): ts.Declaration[] {
106
        return []
107
    }
108
    convertUnknownKeyword(node: ts.TypeNode): ts.Declaration[] {
109
        return []
110
    }
111

112
    convert(node: ts.TypeNode | undefined): ts.Declaration[] {
113
        if (node === undefined)
114
            return []
115
        return convertTypeNode(this, node)
116
    }
117
}
118

119
export class DeclarationDependenciesCollector implements DeclarationConvertor<ts.Declaration[]> {
120
    constructor(
121
        private readonly typeChecker: ts.TypeChecker,
122
        private readonly typeDepsCollector: TypeDependenciesCollector,
123
    ) {}
124

125
    convertClass(node: ts.ClassDeclaration): ts.Declaration[] {
126
        return [
127
            ...(node.heritageClauses?.flatMap(heritage => this.convertHeritageClause(heritage)) ?? []),
128
            ...node.members.flatMap(member => this.convertMember(member)),
129
        ]
130
    }
131
    convertInterface(node: ts.InterfaceDeclaration): ts.Declaration[] {
132
        return [
133
            ...(node.heritageClauses?.flatMap(heritage => this.convertHeritageClause(heritage)) ?? []),
134
            ...node.members.flatMap(member => this.convertMember(member)),
135
        ]
136
    }
137
    protected convertHeritageClause(clause: ts.HeritageClause): ts.Declaration[] {
138
        return clause.types.flatMap(expression => this.convertExpression(expression))       
139
    }
140
    private convertMember(member: ts.TypeElement | ts.ClassElement): ts.Declaration[] {
141
        if (ts.isPropertyDeclaration(member) ||
142
            ts.isPropertySignature(member))
143
            return this.typeDepsCollector.convert(member.type)
144
        if (ts.isMethodDeclaration(member) ||
145
            ts.isMethodSignature(member) ||
146
            ts.isCallSignatureDeclaration(member) ||
147
            ts.isGetAccessorDeclaration(member) ||
148
            ts.isSetAccessorDeclaration(member))
149
            return [
150
                ...member.parameters.flatMap(param => this.typeDepsCollector.convert(param.type)),
151
                ...this.typeDepsCollector.convert(member.type)
152
            ]
153
        if (ts.isConstructorDeclaration(member) || ts.isConstructSignatureDeclaration(member))
154
            return member.parameters.flatMap(param => this.typeDepsCollector.convert(param.type))
155

156
        throw new Error(`Not implemented ${ts.SyntaxKind[member.kind]}`)
157
    }
158
    private convertExpression(expression: ts.ExpressionWithTypeArguments) {
159
        return [
160
            ...getDeclarationsByNode(this.typeChecker, expression.expression),
161
            ...expression.typeArguments?.flatMap(type => this.typeDepsCollector.convert(type)) ?? []
162
        ]
163
    }
164
    convertEnum(node: ts.EnumDeclaration): ts.Declaration[] {
165
        return []
166
    }
167
    convertTypeAlias(node: ts.TypeAliasDeclaration): ts.Declaration[] {
168
        return convertTypeNode(this.typeDepsCollector, node.type)
169
    }
170

171
    convert(node: ts.Declaration | undefined): ts.Declaration[] {
172
        if (node === undefined)
173
            return []
174
        return convertDeclaration(this, node)
175
    }
176
}
177

178
export class DeclarationNameConvertor implements DeclarationConvertor<string> {
179
    convertClass(node: ts.ClassDeclaration): string {
180
        return node.name!.text
181
    }
182
    convertInterface(node: ts.InterfaceDeclaration): string {
183
        return node.name!.text
184
    }
185
    convertEnum(node: ts.EnumDeclaration): string {
186
        return node.name!.text
187
    }
188
    convertTypeAlias(node: ts.TypeAliasDeclaration): string {
189
        return node.name!.text
190
    }
191

192
    static readonly I = new DeclarationNameConvertor()
193
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.