13af6ab5fSopenharmony_ci/*
23af6ab5fSopenharmony_ci * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
33af6ab5fSopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License");
43af6ab5fSopenharmony_ci * you may not use this file except in compliance with the License.
53af6ab5fSopenharmony_ci * You may obtain a copy of the License at
63af6ab5fSopenharmony_ci *
73af6ab5fSopenharmony_ci * http://www.apache.org/licenses/LICENSE-2.0
83af6ab5fSopenharmony_ci *
93af6ab5fSopenharmony_ci * Unless required by applicable law or agreed to in writing, software
103af6ab5fSopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS,
113af6ab5fSopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
123af6ab5fSopenharmony_ci * See the License for the specific language governing permissions and
133af6ab5fSopenharmony_ci * limitations under the License.
143af6ab5fSopenharmony_ci */
153af6ab5fSopenharmony_ci
163af6ab5fSopenharmony_ci//
173af6ab5fSopenharmony_ci//  desc:   For-of-loop syntax is translated to the while-loop syntax by calling of special method
183af6ab5fSopenharmony_ci//          providing predefined 'iterator' interface:
193af6ab5fSopenharmony_ci//  for (let x of c) {    // c is an object of 'iterable' class
203af6ab5fSopenharmony_ci//    <body>
213af6ab5fSopenharmony_ci//  }
223af6ab5fSopenharmony_ci//  ...
233af6ab5fSopenharmony_ci//  let_ci_=_c.$_iterator()
243af6ab5fSopenharmony_ci//  let_it_=_ci.next()
253af6ab5fSopenharmony_ci//  while_(!it.done)_{
263af6ab5fSopenharmony_ci//    x_=_it.value!
273af6ab5fSopenharmony_ci//    <body>
283af6ab5fSopenharmony_ci//    it_=_ci.next()
293af6ab5fSopenharmony_ci//  }
303af6ab5fSopenharmony_ci//
313af6ab5fSopenharmony_ci
323af6ab5fSopenharmony_ci#include "objectIterator.h"
333af6ab5fSopenharmony_ci
343af6ab5fSopenharmony_ci#include "parser/ETSparser.h"
353af6ab5fSopenharmony_ci#include "compiler/lowering/util.h"
363af6ab5fSopenharmony_ci#include "compiler/lowering/scopesInit/scopesInitPhase.h"
373af6ab5fSopenharmony_ci#include "checker/ETSchecker.h"
383af6ab5fSopenharmony_ci
393af6ab5fSopenharmony_cinamespace ark::es2panda::compiler {
403af6ab5fSopenharmony_ci
413af6ab5fSopenharmony_cistatic constexpr std::size_t const WHILE_LOOP_POSITION = 2U;
423af6ab5fSopenharmony_cistatic constexpr std::size_t const WHILE_LOOP_SIZE = 2U;
433af6ab5fSopenharmony_ci
443af6ab5fSopenharmony_cistd::string_view ObjectIteratorLowering::Name() const
453af6ab5fSopenharmony_ci{
463af6ab5fSopenharmony_ci    static std::string const NAME = "ObjectIteratorLowering";
473af6ab5fSopenharmony_ci    return NAME;
483af6ab5fSopenharmony_ci}
493af6ab5fSopenharmony_ci
503af6ab5fSopenharmony_civoid ObjectIteratorLowering::TransferForOfLoopBody(ir::Statement *const forBody, ir::BlockStatement *const whileBody,
513af6ab5fSopenharmony_ci                                                   bool const needCleaning) const noexcept
523af6ab5fSopenharmony_ci{
533af6ab5fSopenharmony_ci    ASSERT(forBody != nullptr && whileBody != nullptr);
543af6ab5fSopenharmony_ci    auto &whileStatements = whileBody->Statements();
553af6ab5fSopenharmony_ci
563af6ab5fSopenharmony_ci    //  Currently while loop body consists of 2 statements: 'x = it.value!' and 'it = ci.next()'
573af6ab5fSopenharmony_ci    //  We need to insert the body of original for-of-loop between them, change their parent and
583af6ab5fSopenharmony_ci    //  probably clean types for expressions and variables for identifier for subsequent re-check.
593af6ab5fSopenharmony_ci    if (forBody->IsBlockStatement()) {
603af6ab5fSopenharmony_ci        auto &forStatements = forBody->AsBlockStatement()->Statements();
613af6ab5fSopenharmony_ci        std::size_t const forSize = forStatements.size();
623af6ab5fSopenharmony_ci
633af6ab5fSopenharmony_ci        whileStatements.resize(WHILE_LOOP_SIZE + forSize);
643af6ab5fSopenharmony_ci        whileStatements[WHILE_LOOP_SIZE + forSize - 1U] = whileStatements[WHILE_LOOP_SIZE - 1U];
653af6ab5fSopenharmony_ci
663af6ab5fSopenharmony_ci        for (std::size_t i = 0U; i < forSize; ++i) {
673af6ab5fSopenharmony_ci            auto &statement = forStatements[i];
683af6ab5fSopenharmony_ci            statement->SetParent(whileBody);
693af6ab5fSopenharmony_ci            if (needCleaning) {
703af6ab5fSopenharmony_ci                // Note: we don't need to clean top-level statement itself because it doesn't have type.
713af6ab5fSopenharmony_ci                ClearTypesVariablesAndScopes(statement);
723af6ab5fSopenharmony_ci            }
733af6ab5fSopenharmony_ci            whileStatements[WHILE_LOOP_SIZE + i - 1U] = statement;
743af6ab5fSopenharmony_ci        }
753af6ab5fSopenharmony_ci    } else {
763af6ab5fSopenharmony_ci        whileStatements.resize(WHILE_LOOP_SIZE + 1U);
773af6ab5fSopenharmony_ci        whileStatements[WHILE_LOOP_SIZE] = whileStatements[WHILE_LOOP_SIZE - 1U];
783af6ab5fSopenharmony_ci
793af6ab5fSopenharmony_ci        forBody->SetParent(whileBody);
803af6ab5fSopenharmony_ci        if (needCleaning) {
813af6ab5fSopenharmony_ci            ClearTypesVariablesAndScopes(forBody);
823af6ab5fSopenharmony_ci        }
833af6ab5fSopenharmony_ci        whileStatements[WHILE_LOOP_SIZE - 1U] = forBody;
843af6ab5fSopenharmony_ci    }
853af6ab5fSopenharmony_ci}
863af6ab5fSopenharmony_ci
873af6ab5fSopenharmony_ciir::Statement *ObjectIteratorLowering::ProcessObjectIterator(parser::ETSParser *parser, checker::ETSChecker *checker,
883af6ab5fSopenharmony_ci                                                             varbinder::ETSBinder *varbinder,
893af6ab5fSopenharmony_ci                                                             ir::ForOfStatement *forOfStatement) const
903af6ab5fSopenharmony_ci{
913af6ab5fSopenharmony_ci    //  Note! We assume that parser, varbinder and checker phases have been already passed correctly, thus the
923af6ab5fSopenharmony_ci    //  class has required accessible iterator method and all the types and scopes are properly resolved.
933af6ab5fSopenharmony_ci
943af6ab5fSopenharmony_ci    auto *const allocator = checker->Allocator();
953af6ab5fSopenharmony_ci    auto statementScope = varbinder::LexicalScope<varbinder::Scope>::Enter(varbinder, NearestScope(forOfStatement));
963af6ab5fSopenharmony_ci
973af6ab5fSopenharmony_ci    ir::Identifier *const iterIdent = Gensym(allocator);
983af6ab5fSopenharmony_ci    ir::Identifier *const nextIdent = Gensym(allocator);
993af6ab5fSopenharmony_ci    std::string loopVariableName;
1003af6ab5fSopenharmony_ci    bool declared = true;
1013af6ab5fSopenharmony_ci
1023af6ab5fSopenharmony_ci    //  Replace the for-of loop with the while loop using the provided iterator interface
1033af6ab5fSopenharmony_ci    std::string whileStatement = "let @@I1 = (@@E2)." + std::string {compiler::Signatures::ITERATOR_METHOD} + "(); ";
1043af6ab5fSopenharmony_ci    whileStatement += "let @@I3 = @@I4.next(); ";
1053af6ab5fSopenharmony_ci    whileStatement += "while (!@@I5.done) { ";
1063af6ab5fSopenharmony_ci
1073af6ab5fSopenharmony_ci    if (auto *const left = forOfStatement->Left(); left->IsVariableDeclaration()) {
1083af6ab5fSopenharmony_ci        auto *const declaration = left->AsVariableDeclaration();
1093af6ab5fSopenharmony_ci        whileStatement +=
1103af6ab5fSopenharmony_ci            declaration->Kind() != ir::VariableDeclaration::VariableDeclarationKind::CONST ? "let " : "const ";
1113af6ab5fSopenharmony_ci        loopVariableName = declaration->Declarators().at(0U)->Id()->AsIdentifier()->Name().Mutf8();
1123af6ab5fSopenharmony_ci    } else if (left->IsIdentifier()) {
1133af6ab5fSopenharmony_ci        declared = false;
1143af6ab5fSopenharmony_ci        loopVariableName = left->AsIdentifier()->Name().Mutf8();
1153af6ab5fSopenharmony_ci    } else {
1163af6ab5fSopenharmony_ci        UNREACHABLE();
1173af6ab5fSopenharmony_ci    }
1183af6ab5fSopenharmony_ci
1193af6ab5fSopenharmony_ci    whileStatement += loopVariableName + " = @@I6.value!; ";
1203af6ab5fSopenharmony_ci    //  later on here we will insert the current for-of-loop body.
1213af6ab5fSopenharmony_ci    whileStatement += "@@I7 = @@I8.next(); }";
1223af6ab5fSopenharmony_ci
1233af6ab5fSopenharmony_ci    // Parse ArkTS code string and create corresponding AST nodes
1243af6ab5fSopenharmony_ci    auto *const loweringResult = parser->CreateFormattedStatement(
1253af6ab5fSopenharmony_ci        whileStatement, iterIdent, forOfStatement->Right(), nextIdent, iterIdent->Clone(allocator, nullptr),
1263af6ab5fSopenharmony_ci        nextIdent->Clone(allocator, nullptr), nextIdent->Clone(allocator, nullptr),
1273af6ab5fSopenharmony_ci        nextIdent->Clone(allocator, nullptr), iterIdent->Clone(allocator, nullptr));
1283af6ab5fSopenharmony_ci    loweringResult->SetParent(forOfStatement->Parent());
1293af6ab5fSopenharmony_ci
1303af6ab5fSopenharmony_ci    TransferForOfLoopBody(forOfStatement->Body(),
1313af6ab5fSopenharmony_ci                          loweringResult->AsBlockStatement()
1323af6ab5fSopenharmony_ci                              ->Statements()[WHILE_LOOP_POSITION]
1333af6ab5fSopenharmony_ci                              ->AsWhileStatement()
1343af6ab5fSopenharmony_ci                              ->Body()
1353af6ab5fSopenharmony_ci                              ->AsBlockStatement(),
1363af6ab5fSopenharmony_ci                          declared);
1373af6ab5fSopenharmony_ci
1383af6ab5fSopenharmony_ci    InitScopesPhaseETS::RunExternalNode(loweringResult, varbinder);
1393af6ab5fSopenharmony_ci    loweringResult->Check(checker);
1403af6ab5fSopenharmony_ci
1413af6ab5fSopenharmony_ci    return loweringResult;
1423af6ab5fSopenharmony_ci}
1433af6ab5fSopenharmony_ci
1443af6ab5fSopenharmony_cibool ObjectIteratorLowering::Perform(public_lib::Context *ctx, parser::Program *program)
1453af6ab5fSopenharmony_ci{
1463af6ab5fSopenharmony_ci    const auto &options = ctx->config->options->CompilerOptions();
1473af6ab5fSopenharmony_ci    if (options.compilationMode == CompilationMode::GEN_STD_LIB) {
1483af6ab5fSopenharmony_ci        for (auto &[_, extPrograms] : program->ExternalSources()) {
1493af6ab5fSopenharmony_ci            (void)_;
1503af6ab5fSopenharmony_ci            for (auto *extProg : extPrograms) {
1513af6ab5fSopenharmony_ci                Perform(ctx, extProg);
1523af6ab5fSopenharmony_ci            }
1533af6ab5fSopenharmony_ci        }
1543af6ab5fSopenharmony_ci    }
1553af6ab5fSopenharmony_ci
1563af6ab5fSopenharmony_ci    auto *const parser = ctx->parser->AsETSParser();
1573af6ab5fSopenharmony_ci    ASSERT(parser != nullptr);
1583af6ab5fSopenharmony_ci    auto *const checker = ctx->checker->AsETSChecker();
1593af6ab5fSopenharmony_ci    ASSERT(checker != nullptr);
1603af6ab5fSopenharmony_ci    auto *const varbinder = ctx->checker->VarBinder()->AsETSBinder();
1613af6ab5fSopenharmony_ci    ASSERT(varbinder != nullptr);
1623af6ab5fSopenharmony_ci
1633af6ab5fSopenharmony_ci    auto hasIterator = [](checker::Type const *const exprType) -> bool {
1643af6ab5fSopenharmony_ci        return exprType != nullptr &&
1653af6ab5fSopenharmony_ci               ((exprType->IsETSObjectType() && !exprType->IsETSStringType()) || exprType->IsETSTypeParameter());
1663af6ab5fSopenharmony_ci    };
1673af6ab5fSopenharmony_ci
1683af6ab5fSopenharmony_ci    program->Ast()->TransformChildrenRecursively(
1693af6ab5fSopenharmony_ci        // clang-format off
1703af6ab5fSopenharmony_ci        [this, parser, checker, varbinder, &hasIterator](ir::AstNode *ast) -> ir::AstNode* {
1713af6ab5fSopenharmony_ci            // clang-format on
1723af6ab5fSopenharmony_ci            if (ast->IsForOfStatement()) {
1733af6ab5fSopenharmony_ci                if (auto const *const exprType = ast->AsForOfStatement()->Right()->TsType();
1743af6ab5fSopenharmony_ci                    hasIterator(exprType) || (exprType != nullptr && exprType->IsETSUnionType() &&
1753af6ab5fSopenharmony_ci                                              exprType->AsETSUnionType()->AllOfConstituentTypes(hasIterator))) {
1763af6ab5fSopenharmony_ci                    return ProcessObjectIterator(parser, checker, varbinder, ast->AsForOfStatement());
1773af6ab5fSopenharmony_ci                }
1783af6ab5fSopenharmony_ci            }
1793af6ab5fSopenharmony_ci            return ast;
1803af6ab5fSopenharmony_ci        },
1813af6ab5fSopenharmony_ci        Name());
1823af6ab5fSopenharmony_ci
1833af6ab5fSopenharmony_ci    return true;
1843af6ab5fSopenharmony_ci}
1853af6ab5fSopenharmony_ci}  // namespace ark::es2panda::compiler
186