1/*
2 * Copyright (c) 2022-2024 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 * as ts from 'typescript';
17
18function scopeContainsThisVisitor(tsNode: ts.Node): boolean {
19  if (tsNode.kind === ts.SyntaxKind.ThisKeyword) {
20    return true;
21  }
22
23  /*
24   * Visit children nodes. Skip any local declaration that defines
25   * its own scope as it needs to be checked separately.
26   */
27  const isClassLike = ts.isClassDeclaration(tsNode) || ts.isClassExpression(tsNode);
28  const isFunctionLike = ts.isFunctionDeclaration(tsNode) || ts.isFunctionExpression(tsNode);
29  const isModuleDecl = ts.isModuleDeclaration(tsNode);
30  if (isClassLike || isFunctionLike || isModuleDecl) {
31    return false;
32  }
33
34  for (const child of tsNode.getChildren()) {
35    if (scopeContainsThisVisitor(child)) {
36      return true;
37    }
38  }
39
40  return false;
41}
42
43export function scopeContainsThis(tsNode: ts.Expression | ts.Block): boolean {
44  return scopeContainsThisVisitor(tsNode);
45}
46