• 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 {
17  forEachChild,
18  getLeadingCommentRangesOfNode,
19  isCallExpression,
20  isExpressionStatement,
21  isIdentifier,
22  SyntaxKind,
23  visitEachChild
24} from 'typescript';
25
26import type {
27  CommentRange,
28  Identifier,
29  Node,
30  SourceFile,
31  TransformationContext
32} from 'typescript';
33
34/**
35 * collect exist identifier names in current source file
36 * @param sourceFile
37 */
38export function collectExistNames(sourceFile: SourceFile): Set<string> {
39  const identifiers: Set<string> = new Set<string>();
40
41  let visit = (node: Node): void => {
42    if (isIdentifier(node)) {
43      identifiers.add(node.text);
44    }
45
46    forEachChild(node, visit);
47  };
48
49  forEachChild(sourceFile, visit);
50  return identifiers;
51}
52
53/**
54 * collect exist identifiers in current source file
55 * @param sourceFile
56 * @param context
57 */
58export function collectIdentifiers(sourceFile: SourceFile, context: TransformationContext): Identifier[] {
59  const identifiers: Identifier[] = [];
60
61  let visit = (node: Node): Node => {
62    if (!isIdentifier(node) || !node.parent) {
63      return visitEachChild(node, visit, context);
64    }
65
66    identifiers.push(node);
67    return node;
68  };
69
70  visit(sourceFile);
71  return identifiers;
72}
73
74export enum OhPackType {
75  NONE,
76  JS_BUNDLE,
77  ES_MODULE
78}
79
80export function isCommentedNode(node: Node, sourceFile: SourceFile): boolean {
81  const ranges: CommentRange[] = getLeadingCommentRangesOfNode(node, sourceFile);
82  return ranges !== undefined;
83}
84
85export function isSuperCallStatement(node: Node): boolean {
86  return isExpressionStatement(node) &&
87    isCallExpression(node.expression) &&
88    node.expression.expression.kind === SyntaxKind.SuperKeyword;
89}
90