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
16 #include "ast_verifier_test.h"
17 #include "ir/astNode.h"
18
19 #include <gtest/gtest.h>
20
21 using ark::es2panda::compiler::ast_verifier::VariableHasEnclosingScope;
22
23 namespace {
TEST_F(ASTVerifierTest,CatchClause)24 TEST_F(ASTVerifierTest, CatchClause)
25 {
26 char const *text = R"(
27 let a = 10;
28 try {
29 a / 0;
30 } catch (e) {
31 if (e instanceof Error) {
32 }
33 }
34 )";
35
36 CONTEXT(ES2PANDA_STATE_CHECKED, text)
37 {
38 EXPECT_TRUE(Verify<VariableHasEnclosingScope>());
39 }
40 }
41
TEST_F(ASTVerifierTest,LambdasHaveCorrectScope)42 TEST_F(ASTVerifierTest, LambdasHaveCorrectScope)
43 {
44 char const *text = R"(
45 type BenchmarkFunc = () => void;
46
47 function main() {
48 const arr: number[] = [1, 2, 3, 4];
49 const ITERATE_FUNC: BenchmarkFunc = () => {
50 const length = arr.length;
51 };
52 }
53 )";
54
55 CONTEXT(ES2PANDA_STATE_CHECKED, text)
56 {
57 EXPECT_TRUE(Verify<VariableHasEnclosingScope>());
58 }
59 }
60
TEST_F(ASTVerifierTest,ParametersInArrowFunctionExpression)61 TEST_F(ASTVerifierTest, ParametersInArrowFunctionExpression)
62 {
63 char const *text = R"(
64 let b = 1;
65 let f = (p: double) => b + p;
66 function main () {
67 assertEQ(f(42), 43)
68 }
69 )";
70
71 CONTEXT(ES2PANDA_STATE_CHECKED, text)
72 {
73 EXPECT_TRUE(Verify<VariableHasEnclosingScope>());
74 }
75 }
76
TEST_F(ASTVerifierTest,LambdaAsParameter)77 TEST_F(ASTVerifierTest, LambdaAsParameter)
78 {
79 char const *text = R"(
80 function foo(callback: (resolve: (val: int) => void) => void): void {}
81
82 function main(): void {
83 foo((resolve: (val: int) => void): void => {});
84 }
85 )";
86
87 CONTEXT(ES2PANDA_STATE_LOWERED, text)
88 {
89 EXPECT_TRUE(Verify<VariableHasEnclosingScope>());
90 }
91 }
92
TEST_F(ASTVerifierTest,PartialClassDeclaration)93 TEST_F(ASTVerifierTest, PartialClassDeclaration)
94 {
95 char const *text = R"(
96 export class IncrementalNode {
97 protected onChildInserted: ((node: IncrementalNode) => void) | undefined = undefined
98 private static readonly ESCAPED_CHARS: char[] = [c'\"', c'\\']
99 }
100 )";
101
102 CONTEXT(ES2PANDA_STATE_LOWERED, text)
103 {
104 EXPECT_TRUE(Verify<VariableHasEnclosingScope>());
105 }
106 }
107 } // namespace
108