From 1d83300d1ac61bfddd2e0563e234d09ad7de38cd Mon Sep 17 00:00:00 2001 From: fcc Date: Thu, 12 Jun 2025 10:59:10 +0800 Subject: [PATCH] fix union type index access Avoid compiler crash when index access for union type. Issue: https://gitee.com/openharmony/arkcompiler_ets_frontend/issues/ICEKQA Signed-off-by: fcc --- ets2panda/checker/ets/typeCheckingHelpers.cpp | 3 +- .../ast/compiler/ets/union_field_access.ets | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 ets2panda/test/ast/compiler/ets/union_field_access.ets diff --git a/ets2panda/checker/ets/typeCheckingHelpers.cpp b/ets2panda/checker/ets/typeCheckingHelpers.cpp index dbb75b798a..515b663e38 100644 --- a/ets2panda/checker/ets/typeCheckingHelpers.cpp +++ b/ets2panda/checker/ets/typeCheckingHelpers.cpp @@ -660,7 +660,8 @@ Type *ETSChecker::GuaranteedTypeForUnionFieldAccess(ir::MemberExpression *member { const auto &types = etsUnionType->ConstituentTypes(); ArenaVector apparentTypes {ProgramAllocator()->Adapter()}; - const auto &propertyName = memberExpression->Property()->AsIdentifier()->Name(); + const auto *prop = memberExpression->Property(); + const auto &propertyName = prop->IsIdentifier() ? prop->AsIdentifier()->Name() : prop->AsStringLiteral()->Str(); for (auto *type : types) { auto searchFlags = PropertySearchFlags::SEARCH_FIELD | PropertySearchFlags::SEARCH_METHOD | PropertySearchFlags::SEARCH_IN_BASE; diff --git a/ets2panda/test/ast/compiler/ets/union_field_access.ets b/ets2panda/test/ast/compiler/ets/union_field_access.ets new file mode 100644 index 0000000000..33cb90075f --- /dev/null +++ b/ets2panda/test/ast/compiler/ets/union_field_access.ets @@ -0,0 +1,31 @@ +/* + * 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. + */ + +type U = TypeA | TypeB; + +interface TypeA { + kind: 'A'; + a: number; +} +interface TypeB { + kind: 'B'; + b: string; +} + +function IfWithString(val: U) { + return /* @@ label */val['kind'] === 'B' +} + +/* @@@ label Error TypeError: Indexed access is not supported for such expression type. */ -- Gitee