• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 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
16import { isIdentifier } from 'typescript';
17import type { SourceFile, VariableStatement } from 'typescript';
18
19/**
20 * get const declaration variable
21 * @param variableStatement
22 * @param sourceFile
23 * @returns
24 */
25export function getVariableStatementDeclaration(variableStatement: VariableStatement, sourceFile: SourceFile): Array<StatementEntity> {
26  const statementsArray: Array<StatementEntity> = [];
27  variableStatement.declarationList.declarations.forEach(value => {
28    let statementName = '';
29    let initializer = '';
30    let typeName = '';
31    let typeKind = -1;
32
33    if (isIdentifier(value.name)) {
34      statementName = value.name.escapedText.toString();
35    } else {
36      statementName = sourceFile.text.substring(value.pos, value.end).trimStart().trimEnd();
37    }
38    if (value.initializer !== undefined) {
39      initializer = sourceFile.text.substring(value.initializer.pos, value.initializer.end);
40      typeKind = value.initializer.kind;
41    }
42    if (value.type !== undefined) {
43      typeName = sourceFile.text.substring(value.type.pos, value.type.end);
44      typeKind = value.type.kind;
45    }
46    statementsArray.push({ statementName: statementName, typeName: typeName, typeKind: typeKind, initializer: initializer });
47  });
48  return statementsArray;
49}
50
51export interface StatementEntity {
52  statementName: string,
53  typeName: string,
54  typeKind: number,
55  initializer: string
56}
57