From 07ad669a27f01302f83a9845d73370041943cf79 Mon Sep 17 00:00:00 2001 From: oh-rgx Date: Tue, 12 Aug 2025 10:46:59 +0800 Subject: [PATCH] Fix never type cast crause crash Issue: #ICSHSH Signed-off-by: oh-rgx --- ets2panda/checker/ETSAnalyzer.cpp | 13 ++++++--- .../test/ast/compiler/ets/never_type_cast.ets | 27 +++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 ets2panda/test/ast/compiler/ets/never_type_cast.ets diff --git a/ets2panda/checker/ETSAnalyzer.cpp b/ets2panda/checker/ETSAnalyzer.cpp index 110ba4ec5c..0292a76d20 100644 --- a/ets2panda/checker/ETSAnalyzer.cpp +++ b/ets2panda/checker/ETSAnalyzer.cpp @@ -3850,13 +3850,20 @@ checker::Type *ETSAnalyzer::Check(ir::TSAsExpression *expr) const } } + checker::Type *originType = sourceType; + if (sourceType->IsETSNeverType() && expr->Expr()->Variable() != nullptr) { + // If the sourceType is 'ETSNeverType', + // we should use the original type of the variable to verify whether it can be cast. + originType = expr->Expr()->Variable()->TsType(); + } + const checker::CastingContext ctx( checker->Relation(), - sourceType->IsBuiltinNumeric() && targetType->IsBuiltinNumeric() ? diagnostic::IMPROPER_NUMERIC_CAST + originType->IsBuiltinNumeric() && targetType->IsBuiltinNumeric() ? diagnostic::IMPROPER_NUMERIC_CAST : diagnostic::INVALID_CAST, // CC-OFFNXT(G.FMT.03-CPP) project code style - {sourceType, targetType}, - checker::CastingContext::ConstructorData {expr->Expr(), sourceType, targetType, expr->Expr()->Start()}); + {originType, targetType}, + checker::CastingContext::ConstructorData {expr->Expr(), originType, targetType, expr->Expr()->Start()}); expr->isUncheckedCast_ = ctx.UncheckedCast(); diff --git a/ets2panda/test/ast/compiler/ets/never_type_cast.ets b/ets2panda/test/ast/compiler/ets/never_type_cast.ets new file mode 100644 index 0000000000..fe13b872f6 --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/never_type_cast.ets @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +function foo() { + let input = true; + if (input instanceof Boolean) { + console.log("This is a test function"); + } else { + let b = input as (string | number | null); + console.log("This is a test function with b: " + b); + } +} +foo(); + +/* @@? 21:17 Error TypeError: Cannot cast type 'Boolean' to 'String|Double|null' */ -- Gitee