• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 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 
16 #include "ast_verifier_test.h"
17 #include "ir/astNode.h"
18 #include "ir/base/classProperty.h"
19 #include <gtest/gtest.h>
20 #include "checker/ETSchecker.h"
21 
22 using ark::es2panda::compiler::ast_verifier::ASTVerifier;
23 using ark::es2panda::compiler::ast_verifier::InvariantNameSet;
24 using ark::es2panda::ir::AstNode;
25 
26 namespace {
27 
TEST_F(ASTVerifierTest,CheckConstProperties)28 TEST_F(ASTVerifierTest, CheckConstProperties)
29 {
30     ark::es2panda::checker::ETSChecker checker;
31     ASTVerifier verifier {Allocator()};
32 
33     char const *text = R"(
34         class Test
35         {
36             readonly value = "readonly";
37         }
38 
39         function main(): void {
40             const test = new Test();
41             console.log(test.value);
42         }
43     )";
44 
45     es2panda_Context *ctx = impl_->CreateContextFromString(cfg_, text, "dummy.sts");
46     impl_->ProceedToState(ctx, ES2PANDA_STATE_LOWERED);
47     ASSERT_EQ(impl_->ContextState(ctx), ES2PANDA_STATE_LOWERED);
48 
49     auto *ast = reinterpret_cast<AstNode *>(impl_->ProgramAst(impl_->ContextProgram(ctx)));
50 
51     ast->IterateRecursively([](ark::es2panda::ir::AstNode *node) {
52         if (node->IsClassProperty()) {
53             auto property = node->AsClassProperty();
54             if (property->IsReadonly()) {
55                 property->AddModifier(ark::es2panda::ir::ModifierFlags::CONST);
56             }
57         }
58     });
59 
60     InvariantNameSet checks;
61     checks.insert("CheckConstPropertiesForAll");
62     const auto &messages = verifier.Verify(ast, checks);
63 
64     ASSERT_EQ(messages.size(), 1);
65     auto invariant = messages[0].Invariant();
66     auto cause = messages[0].Cause();
67     ASSERT_EQ(invariant, "CheckConstPropertiesForAll");
68     ASSERT_EQ(cause, "Class property cannot be const");
69 
70     impl_->DestroyContext(ctx);
71 }
72 
73 }  // namespace