• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "evaluate/evaluateContext.h"
17 #include "ir/base/classDefinition.h"
18 #include "ir/base/methodDefinition.h"
19 #include "ir/base/scriptFunction.h"
20 #include "ir/expressions/functionExpression.h"
21 #include "ir/statements/blockStatement.h"
22 #include "ir/statements/classDeclaration.h"
23 #include "parser/program/program.h"
24 
25 #include <algorithm>
26 
27 namespace ark::es2panda::evaluate {
28 
FindEvaluationMethod(parser::Program * evalMethodProgram)29 void EvaluateContext::FindEvaluationMethod(parser::Program *evalMethodProgram)
30 {
31     ES2PANDA_ASSERT(evalMethodProgram);
32     auto &topLevelStatements = evalMethodProgram->Ast()->Statements();
33 
34     // Find evaluation class.
35     auto evalClassDefIter = std::find_if(topLevelStatements.begin(), topLevelStatements.end(), [](auto *stmt) {
36         return stmt->IsClassDeclaration() && !stmt->AsClassDeclaration()->Definition()->IsGlobal();
37     });
38     ES2PANDA_ASSERT(evalClassDefIter != topLevelStatements.end());
39     auto *methodClass = (*evalClassDefIter)->AsClassDeclaration()->Definition();
40     const auto &expectedMethodName = methodClass->Ident()->Name();
41 
42     // Find evaluation method.
43     auto evalMethodIter =
44         std::find_if(methodClass->Body().begin(), methodClass->Body().end(), [expectedMethodName](auto *iter) {
45             return iter->IsMethodDefinition() &&
46                    iter->AsMethodDefinition()->Key()->AsIdentifier()->Name() == expectedMethodName;
47         });
48     ES2PANDA_ASSERT(evalMethodIter != methodClass->Body().end());
49     auto *method = (*evalMethodIter)->AsMethodDefinition();
50     auto *scriptFunction = method->Value()->AsFunctionExpression()->Function();
51     ES2PANDA_ASSERT(scriptFunction != nullptr);
52 
53     // Extract method statements and last statement.
54     methodStatements = scriptFunction->Body()->AsBlockStatement();
55     ES2PANDA_ASSERT(!methodStatements->Statements().empty());
56     auto *stmt = methodStatements->Statements().back();
57     if (stmt->IsExpressionStatement()) {
58         lastStatement = stmt->AsExpressionStatement();
59     }
60 }
61 
62 }  // namespace ark::es2panda::evaluate
63