1/*
2 * Copyright (c) 2021-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#ifndef ES2PANDA_COMPILER_CHECKER_ETS_FUNCTION_HELPERS_H
17#define ES2PANDA_COMPILER_CHECKER_ETS_FUNCTION_HELPERS_H
18
19#include "checker/ETSchecker.h"
20#include "checker/ets/typeRelationContext.h"
21#include "checker/types/ets/etsObjectType.h"
22#include "checker/types/type.h"
23#include "checker/types/typeFlag.h"
24#include "ir/astNode.h"
25#include "ir/typeNode.h"
26#include "ir/base/catchClause.h"
27#include "ir/base/classDefinition.h"
28#include "ir/base/classProperty.h"
29#include "ir/base/methodDefinition.h"
30#include "ir/base/scriptFunction.h"
31#include "ir/base/spreadElement.h"
32#include "ir/expressions/arrowFunctionExpression.h"
33#include "ir/expressions/callExpression.h"
34#include "ir/expressions/functionExpression.h"
35#include "ir/expressions/memberExpression.h"
36#include "ir/statements/blockStatement.h"
37#include "ir/statements/doWhileStatement.h"
38#include "ir/statements/expressionStatement.h"
39#include "ir/statements/forInStatement.h"
40#include "ir/statements/forOfStatement.h"
41#include "ir/statements/forUpdateStatement.h"
42#include "ir/statements/switchStatement.h"
43#include "ir/statements/whileStatement.h"
44#include "ir/ts/tsTypeParameterInstantiation.h"
45#include "parser/program/program.h"
46#include "utils/arena_containers.h"
47#include "util/helpers.h"
48#include "util/language.h"
49#include "varbinder/declaration.h"
50#include "varbinder/ETSBinder.h"
51#include "varbinder/scope.h"
52#include "varbinder/varbinder.h"
53#include "varbinder/variable.h"
54#include "varbinder/variableFlags.h"
55
56namespace ark::es2panda::checker {
57
58static Type *MaybeBoxedType(ETSChecker *checker, Type *type, ir::Expression *expr)
59{
60    if (!type->HasTypeFlag(TypeFlag::ETS_PRIMITIVE)) {
61        return type;
62    }
63    auto *relation = checker->Relation();
64    auto *oldNode = relation->GetNode();
65    relation->SetNode(expr);
66    auto *res = checker->PrimitiveTypeAsETSBuiltinType(type);
67    relation->SetNode(oldNode);
68    return res;
69}
70
71static void InferUntilFail(Signature const *const signature, const ArenaVector<ir::Expression *> &arguments,
72                           ETSChecker *checker, Substitution *substitution)
73{
74    auto *sigInfo = signature->GetSignatureInfo();
75    auto &sigParams = signature->GetSignatureInfo()->typeParams;
76    ArenaVector<bool> inferStatus(checker->Allocator()->Adapter());
77    inferStatus.assign(arguments.size(), false);
78    bool anyChange = true;
79    size_t lastSubsititutionSize = 0;
80
81    // some ets lib files require type infer from arg index 0,1,... , not fit to build graph
82    while (anyChange && substitution->size() < sigParams.size()) {
83        anyChange = false;
84        for (size_t ix = 0; ix < arguments.size(); ++ix) {
85            if (inferStatus[ix]) {
86                continue;
87            }
88
89            auto *arg = arguments[ix];
90            if (arg->IsObjectExpression()) {
91                continue;
92            }
93
94            auto *const argType = arg->IsSpreadElement()
95                                      ? MaybeBoxedType(checker, arg->AsSpreadElement()->Argument()->Check(checker),
96                                                       arg->AsSpreadElement()->Argument())
97                                      : MaybeBoxedType(checker, arg->Check(checker), arg);
98            auto *const paramType = (ix < signature->MinArgCount()) ? sigInfo->params[ix]->TsType()
99                                    : sigInfo->restVar != nullptr   ? sigInfo->restVar->TsType()
100                                                                    : nullptr;
101
102            if (paramType == nullptr) {
103                continue;
104            }
105
106            if (checker->EnhanceSubstitutionForType(sigInfo->typeParams, paramType, argType, substitution)) {
107                inferStatus[ix] = true;
108            }
109            if (lastSubsititutionSize != substitution->size()) {
110                lastSubsititutionSize = substitution->size();
111                anyChange = true;
112            }
113        }
114    }
115}
116
117static const Substitution *BuildImplicitSubstitutionForArguments(ETSChecker *checker, Signature *signature,
118                                                                 const ArenaVector<ir::Expression *> &arguments)
119{
120    Substitution *substitution = checker->NewSubstitution();
121    auto *sigInfo = signature->GetSignatureInfo();
122    auto &sigParams = signature->GetSignatureInfo()->typeParams;
123
124    InferUntilFail(signature, arguments, checker, substitution);
125
126    if (substitution->size() != sigParams.size()) {
127        for (const auto typeParam : sigParams) {
128            auto newTypeParam = typeParam->AsETSTypeParameter();
129            if (auto it = substitution->find(newTypeParam); it != substitution->cend()) {
130                continue;
131            }
132            if (newTypeParam->GetDefaultType() == nullptr) {
133                return nullptr;
134            }
135            auto dflt = newTypeParam->GetDefaultType()->Substitute(checker->Relation(), substitution);
136            if (!checker->EnhanceSubstitutionForType(sigInfo->typeParams, newTypeParam, dflt, substitution)) {
137                return nullptr;
138            }
139        }
140
141        if (substitution->size() != sigParams.size() &&
142            (signature->Function()->ReturnTypeAnnotation() == nullptr ||
143             !checker->EnhanceSubstitutionForType(sigInfo->typeParams,
144                                                  signature->Function()->ReturnTypeAnnotation()->TsType(),
145                                                  signature->ReturnType(), substitution))) {
146            return nullptr;
147        }
148    }
149
150    return substitution;
151}
152
153static const Substitution *BuildExplicitSubstitutionForArguments(ETSChecker *checker, Signature *signature,
154                                                                 const ArenaVector<ir::TypeNode *> &params,
155                                                                 const lexer::SourcePosition &pos,
156                                                                 TypeRelationFlag flags)
157{
158    auto &sigParams = signature->GetSignatureInfo()->typeParams;
159    auto *substitution = checker->NewSubstitution();
160    auto *constraintsSubstitution = checker->NewSubstitution();
161    ArenaVector<Type *> instArgs {checker->Allocator()->Adapter()};
162
163    for (size_t ix = 0; ix < params.size(); ++ix) {
164        instArgs.push_back(MaybeBoxedType(checker, params[ix]->GetType(checker), params[ix]));
165        if (ix < sigParams.size()) {
166            ETSChecker::EmplaceSubstituted(constraintsSubstitution, sigParams[ix]->AsETSTypeParameter(), instArgs[ix]);
167        }
168    }
169    for (size_t ix = instArgs.size(); ix < sigParams.size(); ++ix) {
170        auto *dflt = sigParams[ix]->AsETSTypeParameter()->GetDefaultType();
171        if (dflt == nullptr) {
172            break;
173        }
174
175        dflt = dflt->Substitute(checker->Relation(), constraintsSubstitution);
176        instArgs.push_back(dflt);
177        ETSChecker::EmplaceSubstituted(constraintsSubstitution, sigParams[ix]->AsETSTypeParameter(), instArgs[ix]);
178    }
179    if (sigParams.size() != instArgs.size()) {
180        if ((flags & TypeRelationFlag::NO_THROW) != 0) {
181            return nullptr;
182        }
183        checker->LogTypeError({"Expected ", sigParams.size(), " type arguments, got ", instArgs.size(), " ."}, pos);
184        return nullptr;
185    }
186
187    for (size_t ix = 0; ix < sigParams.size(); ix++) {
188        if (!checker->IsCompatibleTypeArgument(sigParams[ix]->AsETSTypeParameter(), instArgs[ix],
189                                               constraintsSubstitution)) {
190            return nullptr;
191        }
192        ETSChecker::EmplaceSubstituted(substitution, sigParams[ix]->AsETSTypeParameter(), instArgs[ix]);
193    }
194    return substitution;
195}
196
197static Signature *MaybeSubstituteTypeParameters(ETSChecker *checker, Signature *signature,
198                                                const ir::TSTypeParameterInstantiation *typeArguments,
199                                                const ArenaVector<ir::Expression *> &arguments,
200                                                const lexer::SourcePosition &pos, TypeRelationFlag flags)
201{
202    if (typeArguments == nullptr && signature->GetSignatureInfo()->typeParams.empty()) {
203        return signature;
204    }
205
206    const Substitution *substitution =
207        (typeArguments != nullptr)
208            ? BuildExplicitSubstitutionForArguments(checker, signature, typeArguments->Params(), pos, flags)
209            : BuildImplicitSubstitutionForArguments(checker, signature, arguments);
210
211    return (substitution == nullptr) ? nullptr : signature->Substitute(checker->Relation(), substitution);
212}
213
214static bool CheckInterfaceOverride(ETSChecker *const checker, ETSObjectType *const interface,
215                                   Signature *const signature)
216{
217    bool isOverriding = checker->CheckOverride(signature, interface);
218
219    for (auto *const superInterface : interface->Interfaces()) {
220        isOverriding |= CheckInterfaceOverride(checker, superInterface, signature);
221    }
222
223    return isOverriding;
224}
225
226static varbinder::Scope *NodeScope(ir::AstNode *ast)
227{
228    if (ast->IsBlockStatement()) {
229        return ast->AsBlockStatement()->Scope();
230    }
231    if (ast->IsDoWhileStatement()) {
232        return ast->AsDoWhileStatement()->Scope();
233    }
234    if (ast->IsForInStatement()) {
235        return ast->AsForInStatement()->Scope();
236    }
237    if (ast->IsForOfStatement()) {
238        return ast->AsForOfStatement()->Scope();
239    }
240    if (ast->IsForUpdateStatement()) {
241        return ast->AsForUpdateStatement()->Scope();
242    }
243    if (ast->IsSwitchStatement()) {
244        return ast->AsSwitchStatement()->Scope();
245    }
246    if (ast->IsWhileStatement()) {
247        return ast->AsWhileStatement()->Scope();
248    }
249    if (ast->IsCatchClause()) {
250        return ast->AsCatchClause()->Scope();
251    }
252    if (ast->IsClassDefinition()) {
253        return ast->AsClassDefinition()->Scope();
254    }
255    if (ast->IsScriptFunction()) {
256        return ast->AsScriptFunction()->Scope()->ParamScope();
257    }
258    return nullptr;
259}
260
261}  // namespace ark::es2panda::checker
262
263#endif
264