1 /*
2 * Copyright (c) 2021-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 "castingContext.h"
17 #include "checker/types/type.h"
18 #include "checker/ETSchecker.h"
19
20 namespace ark::es2panda::checker {
CastingContext(TypeRelation * relation,const diagnostic::DiagnosticKind & diagKind,const util::DiagnosticMessageParams & list,ConstructorData && data)21 CastingContext::CastingContext(TypeRelation *relation, const diagnostic::DiagnosticKind &diagKind,
22 const util::DiagnosticMessageParams &list, ConstructorData &&data)
23 {
24 flags_ |= data.extraFlags;
25
26 const SavedTypeRelationFlagsContext savedTypeRelationFlags(relation, flags_);
27 relation->SetNode(data.node);
28
29 const bool isLegalBoxedPrimitiveConversion = relation->IsLegalBoxedPrimitiveConversion(data.target, data.source);
30 relation->Result(false);
31 if (!relation->IsSupertypeOf(data.target, data.source) && !isLegalBoxedPrimitiveConversion) {
32 relation->IsCastableTo(data.source, data.target);
33 // #22954 string comparison
34 if (!relation->IsTrue() && data.source->ToString() == data.target->ToString()) {
35 relation->Result(true);
36 }
37 if (!relation->IsTrue() && (flags_ & TypeRelationFlag::NO_THROW) == 0) {
38 relation->RaiseError(diagKind, list, data.pos);
39 }
40 }
41
42 if (isLegalBoxedPrimitiveConversion && !relation->IsTrue()) {
43 auto *const checker = relation->GetChecker()->AsETSChecker();
44 Type *sourceUnboxedType = checker->MaybeUnboxType(data.source);
45 relation->GetNode()->AddBoxingUnboxingFlags(checker->GetUnboxingFlag(sourceUnboxedType));
46 relation->GetNode()->AddBoxingUnboxingFlags(checker->GetBoxingFlag(data.target));
47 }
48
49 uncheckedCast_ = relation->UncheckedCast();
50 relation->SetNode(nullptr);
51 }
52
UncheckedCast() const53 bool CastingContext::UncheckedCast() const noexcept
54 {
55 return uncheckedCast_;
56 }
57 } // namespace ark::es2panda::checker
58