idlize

Форк
0
238 строк · 7.0 Кб
1
/*
2
 * Copyright (c) 2022-2023 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 "ohos-typescript"
17
import { filterDecorators } from "./utils"
18

19
export function parameter(
20
    name: string|ts.Identifier,
21
    type: ts.TypeNode | undefined,
22
    initializer?: ts.Expression
23
) {
24
    return ts.factory.createParameterDeclaration(
25
        undefined,
26
        undefined,
27
        undefined,
28
        name,
29
        undefined,
30
        type,
31
        initializer
32
    )
33
}
34

35
export function optionalParameter(
36
    name: string|ts.Identifier,
37
    type: ts.TypeNode | undefined,
38
    initializer?: ts.Expression
39
) {
40
    return ts.factory.createParameterDeclaration(
41
        undefined,
42
        undefined,
43
        undefined,
44
        name,
45
        ts.factory.createToken(ts.SyntaxKind.QuestionToken),
46
        type,
47
        initializer
48
    )
49
}
50

51
export function assignment(left: ts.Expression, right: ts.Expression): ts.ExpressionStatement {
52
    return ts.factory.createExpressionStatement(
53
        ts.factory.createBinaryExpression(
54
            left,
55
            ts.factory.createToken(ts.SyntaxKind.EqualsToken),
56
            right
57
        )
58
    )
59
}
60

61
export function tripleNotEqualsUndefined(left: ts.Expression): ts.Expression {
62
    return ts.factory.createBinaryExpression(
63
        left,
64
        ts.factory.createToken(ts.SyntaxKind.ExclamationEqualsEqualsToken),
65
        undefinedValue()
66
    )
67
}
68

69
export function id(name: string): ts.Identifier {
70
    return ts.factory.createIdentifier(name)
71
}
72

73
export function Any(): ts.TypeNode {
74
    return ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)
75
}
76

77
export function Undefined() {
78
    return ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)
79
}
80

81
export function Void() {
82
    return ts.factory.createToken(ts.SyntaxKind.VoidKeyword)
83
}
84

85
export function Export() {
86
    return ts.factory.createToken(ts.SyntaxKind.ExportKeyword)
87
}
88

89
export function Private() {
90
    return ts.factory.createToken(ts.SyntaxKind.PrivateKeyword)
91
}
92

93
export function Exclamation() {
94
    return ts.factory.createToken(ts.SyntaxKind.ExclamationToken)
95
}
96

97
export function undefinedValue(): ts.Expression {
98
    return ts.factory.createIdentifier("undefined")
99
}
100

101
export function partialForName(className: string) {
102
    return ts.factory.createTypeReferenceNode(
103
        "Partial",
104
        [
105
            ts.factory.createTypeReferenceNode(className)
106
        ]
107
    )
108
}
109

110
export function partial(className: ts.Identifier) {
111
    return ts.factory.createTypeReferenceNode(
112
        "Partial",
113
        [
114
            ts.factory.createTypeReferenceNode(ts.idText(className))
115
        ]
116
    )
117
}
118

119
export function anyIfNoType(type: ts.TypeNode | undefined): ts.TypeNode {
120
    if (!type) return Any()
121
    return type
122
}
123

124

125
export function provideAnyTypeIfNone(parameter: ts.ParameterDeclaration): ts.ParameterDeclaration {
126
    return ts.factory.updateParameterDeclaration(
127
        parameter,
128
        parameter.modifiers,
129
        parameter.dotDotDotToken,
130
        parameter.name,
131
        parameter.questionToken,
132
        anyIfNoType(parameter.type),
133
        parameter.initializer
134
    )
135
}
136

137
export function orUndefined(type: ts.TypeNode): ts.TypeNode {
138
    return ts.factory.createUnionTypeNode([
139
        type,
140
        Undefined()
141
    ])
142
}
143

144
export function isKnownIdentifier(name: ts.Node | undefined, value: string): boolean {
145
    return (name != undefined) &&
146
        (ts.isIdentifier(name) || ts.isPrivateIdentifier(name)) &&
147
        ts.idText(name) == value
148
}
149

150
export function isUndefined(node: ts.Expression): boolean {
151
    return node.kind == ts.SyntaxKind.UndefinedKeyword ||
152
        ts.isIdentifier(node) && ts.idText(node) == "undefined"
153
}
154

155
export function prependComment<T extends ts.Node>(node: T, comment: string): T {
156
    return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment, true);
157
}
158

159
export function isDecorator(modifierLike: ts.ModifierLike, name: string): boolean {
160
    if (!ts.isDecorator(modifierLike)) {
161
        return false
162
    }
163
    return isKnownIdentifier(modifierLike.expression, name) || isCallDecorator(modifierLike, name)
164
}
165

166
export function isCallDecorator(decorator: ts.Decorator, name: string): boolean {
167
    return ts.isCallExpression(decorator.expression) && isKnownIdentifier(decorator.expression.expression, name)
168
}
169

170
export function hasDecorator(node: ts.Node, name: string): boolean {
171
    return getDecorator(node, name) != undefined
172
}
173

174
export function getDecorator(node: ts.Node, name: string): ts.Decorator | undefined {
175
    return filterDecorators(node)?.find(it => isDecorator(it, name))
176
}
177

178
export function findDecoratorArguments(
179
    decorators: ReadonlyArray<ts.Decorator> | undefined,
180
    name: string,
181
    nth: number
182
): ReadonlyArray<ts.Expression> | undefined {
183
    return decorators
184
        ?.filter(it => isCallDecorator(it, name))
185
        ?.map(it => (it.expression as ts.CallExpression).arguments[nth])
186
}
187

188
export function findDecoratorLiterals(
189
    decorators: ReadonlyArray<ts.Decorator> | undefined,
190
    name: string,
191
    nth: number,
192
): ReadonlyArray<string> | undefined {
193
    return findDecoratorArguments(decorators, name, nth)?.map(it => (it as ts.StringLiteral).text)
194
}
195

196
export function findDecoratorArgument(
197
    decorators: ReadonlyArray<ts.Decorator> | undefined,
198
    name: string,
199
    nth: number,
200
): ts.Expression {
201
    const args = findDecoratorArguments(decorators, name, nth)
202
    if (args?.length === 1) return args[0]
203
    throw new Error(name + " must have only one argument, but got " + args?.length)
204
}
205

206
export function createThisFieldAccess(name: string | ts.Identifier | ts.PrivateIdentifier): ts.Expression {
207
    return ts.factory.createPropertyAccessExpression(
208
        ts.factory.createThis(),
209
        name
210
    )
211
}
212

213
export function bindThis(expression: ts.Expression): ts.Expression {
214
    return ts.factory.createCallExpression(
215
        ts.factory.createPropertyAccessExpression(
216
            expression,
217
            "bind"
218
        ),
219
        undefined,
220
        [ts.factory.createThis()]
221
    )
222

223
}
224

225

226
export function getLineNumber(sourceFile: ts.SourceFile, position: number): number {
227
    return ts.getLineAndCharacterOfPosition(sourceFile, position).line + 1 // First line is 1.
228
}
229

230
export function getDeclarationsByNode(typechecker: ts.TypeChecker, node: ts.Node): ts.Declaration[] {
231
    const symbol = typechecker.getSymbolAtLocation(node)
232
    const declarations = symbol?.getDeclarations() ?? []
233
    return declarations
234
}
235

236
export function dropReadonly(modifierLikes: ts.ModifierLike[] | undefined): ts.ModifierLike[] | undefined {
237
    return modifierLikes?.filter(it => it.kind != ts.SyntaxKind.ReadonlyKeyword)
238
}
239

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

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

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

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