idlize

Форк
0
311 строк · 10.3 Кб
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 { id } from './ApiUtils'
18

19
let knownPrefixes = ["@ohos", "@system"]
20

21
export function isOhosImport(literal: string): boolean {
22
    for (let prefix of knownPrefixes) {
23
        if (literal.startsWith(prefix)) return true
24
    }
25
    return false
26
}
27

28
interface ArkUIVariance {
29
    koalaCommon: string
30
    koalaFramework: string
31
    koalaRuntime: string
32
    koalaArkuiCommon: string
33
    arkoala: string
34
    koalaAdaptor: string
35
}
36

37
const KoalaArkui: ArkUIVariance = {
38
    koalaCommon: "@koalaui/common",
39
    koalaFramework: "@koalaui/framework",
40
    koalaRuntime: "@koalaui/runtime",
41
    koalaArkuiCommon: "@koalaui/arkui-common",
42
    arkoala: "@koalaui/arkoala",
43
    koalaAdaptor: "@koalaui/arkui"
44
}
45

46
const ArkoalaArkui: ArkUIVariance = {
47
    koalaCommon: "@koalaui/common",
48
    koalaFramework: "@koalaui/framework",
49
    koalaRuntime: "@koalaui/runtime",
50
    koalaArkuiCommon: "@koalaui/arkui-common",
51
    arkoala: "@koalaui/arkoala",
52
    koalaAdaptor: "@koalaui/arkoala-arkui"
53
}
54

55
// Everything re-exported through arkoala-arkui
56
const ArkoalaSdkArkui: ArkUIVariance = {
57
    koalaCommon: "@koalaui/arkoala-arkui",
58
    koalaFramework: "@koalaui/arkoala-arkui",
59
    koalaRuntime: "@koalaui/arkoala-arkui",
60
    koalaArkuiCommon: "@koalaui/arkoala-arkui",
61
    arkoala: "@koalaui/arkoala-arkui",
62
    koalaAdaptor: "@koalaui/arkoala-arkui",
63
}
64

65

66
export class Importer {
67
    // TODO: Every use of this property is a bad HACK!
68
    // Think hard how to eliminate it!
69
    public __isArkoalaImplementation: boolean = false
70
    private allImports: Map<string, Set<string>>
71
    private implementedPackages: Set<string>
72

73
    static koalaCommon = "@koalaui/common"
74
    static koalaFramework = "@koalaui/framework"
75
    static koalaRuntime = "@koalaui/runtime"
76
    static koalaArkuiCommon = "@koalaui/arkui-common"
77
    static arkoala = "@koalaui/arkoala"
78

79
    subproject: ArkUIVariance
80
    
81
    constructor(koalaAdaptor: string = "@koalaui/arkui", public moduleInfo?: (moduleName: string)=>any) {
82
        this.__isArkoalaImplementation = (koalaAdaptor == "@koalaui/arkoala-arkui")
83
        this.subproject = this.__isArkoalaImplementation ? ArkoalaSdkArkui : KoalaArkui
84

85
        this.implementedPackages = new Set(
86
            this.__isArkoalaImplementation ?
87
                [
88
                    'ohos.arkui.testing',
89
                    'ohos.matrix4',
90
                    'ohos.router',
91
                    'system.router'
92
                ] :
93
                [
94
                    'ohos.curves',
95
                    'ohos.events.emitter',
96
                    'ohos.matrix44',
97
                    'ohos.router',
98
                    'ohos.data.preferences',
99
                    'ohos.hilog',
100
                    'ohos.mediaquery',
101
                    'ohos.UiTest',
102
                    'ohos.display',
103
                    'ohos/hypium',
104
                    'ohos.net.http',
105
                    'system.router'
106
                ]
107
        )
108

109
        // TODO Add special handling for ForEach imports
110
        this.allImports = new Map([
111
            [
112
                this.subproject.koalaAdaptor, new Set(
113
                    this.__isArkoalaImplementation ? [
114
                        "ForEach",
115
                        "LazyForEach",
116
                        "IDataSource",
117
                        "SwiperController",
118
                        "Scroller",
119
                        "VideoController",
120
                        "TabsController",
121
                        "SearchController",
122
                        "PatternLockController",
123
                        "AppStorage",
124
                        "LocalStorage",
125
                        "animateTo",
126
                        "TransitionEffect",
127
                        "TapGesture",
128
                        "LongPressGesture",
129
                        "PanGestureOptions",
130
                        "PanGesture",
131
                        "PinchGesture",
132
                        "GestureGroup",
133
                        "LinearGradient",
134
                        "TextClockController",
135
                        "TextTimerController",
136
                        "RichEditorController",
137
                        "TextAreaController",
138
                        "CanvasRenderingContext2D",
139
                        "OffscreenCanvasRenderingContext2D",
140
                        "ImageBitmap",
141
                        "RenderingContextSettings",
142
                        "XComponentController",
143
                        "Indicator",
144
                        "TextInputOptions",
145
                        "TextInputController",
146
                        "WebController",
147
                        "ESObject",
148
                    ] : [
149
                        "PanGestureOptions",
150
                        "TapGesture",
151
                        "LongPressGesture",
152
                        "PanGesture",
153
                        "SwipeGesture",
154
                        "PinchGesture",
155
                        "RotationGesture",
156
                        "GestureGroup",
157
                        "DataChangeListener",
158
                        "ForEach",
159
                        "IDataSource",
160
                        "Scroller",
161
                        "CustomDialogController",
162
                        "SwiperController",
163
                        "RenderingContextSettings",
164
                        "CanvasRenderingContext2D",
165
                        "VideoController",
166
                        "TabsController",
167
                        "TextAreaController",
168
                        // generated classes do not see common_ts_ets_api.d.ts
169
                        // so, import next five classes from Storage.ts
170
                        "AppStorage",
171
                        "PersistentStorage",
172
                        "Environment",
173
                        "SubscribedAbstractProperty",
174
                        "LocalStorage",
175

176
                        "Observed",
177
                        "$r",
178
                        "$rawfile",
179
                        "getContext",
180
                        "getInspectorByKey",
181
                        "vp2px",
182
                        "px2vp",
183
                        "fp2px",
184
                        "px2fp",
185
                        "lpx2px",
186
                        "px2lpx",
187
                        "animateTo",
188
                    ])
189
            ]
190
        ])
191
    }
192

193

194
    addImport(pkg: string, subpackage: string | undefined, name: string) {
195
        const from = subpackage ? `${pkg}/${subpackage}` : pkg
196
        if (this.allImports.has(from)) {
197
            this.allImports.get(from)?.add(name)
198
        } else {
199
            this.allImports.set(from, new Set([name]))
200
        }
201
    }
202

203
    addCommonImport(name: string) {
204
        this.addImport(this.subproject.koalaCommon, undefined, name)
205
    }
206
    addFrameworkImport(name: string) {
207
        this.addImport(this.subproject.koalaFramework, undefined, name)
208
    }
209
    addArkoalaImport(name: string) {
210
        this.addImport(this.subproject.arkoala, undefined, name)
211
    }
212
    addRuntimeImport(name: string) {
213
        this.addImport(this.subproject.koalaRuntime, undefined, name)
214
    }
215
    addAdaptorImport(name: string) {
216
        this.addImport(this.subproject.koalaAdaptor, undefined, name)
217
    }
218
    addArkuiCommonImport(name: string) {
219
        this.addImport(this.subproject.koalaArkuiCommon, undefined, name)
220
    }
221
    addOhosImport(pkg: string, name: string) {
222
        this.addImport(this.subproject.koalaAdaptor, pkg, name)
223
    }
224
    allImportsSorted(from: string): string[] {
225
        const nameSet: Set<string> | undefined = this.allImports.get(from)
226
        if (!nameSet) return []
227
        return Array.from(nameSet).sort()
228
    }
229

230
    withCommonImport(name: string): string {
231
        this.addCommonImport(name)
232
        return name
233
    }
234

235
    withAdaptorImport(name: string): string {
236
        this.addAdaptorImport(name)
237
        return name
238
    }
239

240
    withArkuiCommonImport(name: string): string {
241
        this.addArkuiCommonImport(name)
242
        return name
243
    }
244

245
    withOhosImport(pkg: string, name: string): string {
246
        this.addOhosImport(pkg, name)
247
        return name
248
    }
249

250
    withFrameworkImport(name: string): string {
251
        this.addFrameworkImport(name)
252
        return name
253
    }
254

255
    withArkoalaImport(name: string): string {
256
        this.addArkoalaImport(name)
257
        return name
258
    }
259

260
    withRuntimeImport(name: string): string {
261
        this.addRuntimeImport(name)
262
        return name
263
    }
264

265
    generateAllImports(array: string[], from: string): ts.ImportDeclaration {
266
        const namedImports = array.map(it => ts.factory.createImportSpecifier(
267
            false,
268
            undefined,
269
            id(it)
270
        ))
271

272
        return ts.factory.createImportDeclaration(
273
            undefined,
274
            undefined,
275
            ts.factory.createImportClause(
276
                false,
277
                undefined,
278
                ts.factory.createNamedImports(
279
                    namedImports
280
                )
281
            ),
282
            ts.factory.createStringLiteral(from),
283
        )
284
    }
285

286
    generate(): ts.ImportDeclaration[] {
287
        const allImports = Array.from(this.allImports.keys()).map(from =>
288
            this.generateAllImports(this.allImportsSorted(from), from)
289
        )
290

291
        return allImports
292
    }
293

294
    translateOhosImport(node: ts.ImportDeclaration, oldPackage: string, oldDefaultName: string): ts.ImportDeclaration {
295
        if (!oldPackage.startsWith("@")) return node
296
        const stringName = oldPackage.substring(1)
297
        if (!this.implementedPackages.has(stringName)) return node
298

299
        return ts.factory.updateImportDeclaration(
300
            node,
301
            node.modifiers,
302
            (oldDefaultName.length == 0) ? node.importClause : ts.factory.createImportClause(
303
                false,
304
                id(oldDefaultName),
305
                undefined
306
            ),
307
            ts.factory.createStringLiteral(`${this.subproject.koalaAdaptor}/${stringName}`),
308
            undefined
309
        )
310
    }
311
}
312

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

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

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

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