• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024-2025 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
16import { ArkFile, ts } from '..';
17import { ETS_COMPILER_OPTIONS } from '../core/common/EtsConst';
18import * as crypto from 'crypto';
19
20const sourceFileCache: Map<string, ts.SourceFile> = new Map();
21
22export class AstTreeUtils {
23    /**
24     * get source file from code segment
25     * @param fileName source file name
26     * @param code source code
27     * @returns ts.SourceFile
28     */
29    public static getASTNode(fileName: string, code: string): ts.SourceFile {
30        const key = this.getKeyFromCode(code);
31        let sourceFile = sourceFileCache.get(key);
32        if (sourceFile) {
33            return sourceFile;
34        }
35        sourceFile = this.createSourceFile(fileName, code);
36        sourceFileCache.set(key, sourceFile);
37        return sourceFile;
38    }
39
40    /**
41     * get source file from ArkFile
42     * @param arkFile ArkFile
43     * @returns ts.SourceFile
44     */
45    public static getSourceFileFromArkFile(arkFile: ArkFile): ts.SourceFile {
46        const signature = arkFile.getFileSignature().toString();
47        const key = this.getKeyFromCode(signature);
48        let sourceFile = sourceFileCache.get(key);
49        if (sourceFile) {
50            return sourceFile;
51        }
52        sourceFile = this.createSourceFile(arkFile.getName(), arkFile.getCode());
53        sourceFileCache.set(key, sourceFile);
54        return sourceFile;
55    }
56
57    public static createSourceFile(fileName: string, code: string): ts.SourceFile {
58        return ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest, true, undefined, ETS_COMPILER_OPTIONS);
59    }
60
61    /**
62     * convert source code to hash string
63     * @param code source code
64     * @returns string
65     */
66    private static getKeyFromCode(code: string): string {
67        return crypto.createHash('sha256').update(code).digest('hex');
68    }
69}
70