1 /**
2 * Copyright (c) 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 "IntlListFormat.h"
17 #include "IntlCommon.h"
18 #include "libpandabase/macros.h"
19 #include "stdlib_ani_helpers.h"
20
21 #include "unicode/locid.h"
22 #include "unicode/listformatter.h"
23
24 #include <array>
25 #include <cassert>
26 #include <sstream>
27 #include <string>
28 #include <tuple>
29
30 namespace ark::ets::stdlib::intl {
31
32 namespace {
33 ani_string g_elementAniStr = nullptr;
34 ani_string g_literalAniStr = nullptr;
35 } // namespace
36
37 template <typename... Args>
ThrowRangeError(ani_env * env,Args &&...args)38 static void ThrowRangeError(ani_env *env, Args &&...args)
39 {
40 std::stringstream message;
41 (message << ... << args);
42 ThrowNewError(env, "Lstd/core/RangeError;", message.str().c_str(), "Lstd/core/String;:V");
43 }
44
GetLocale(const std::string & tag)45 static icu::Locale GetLocale(const std::string &tag)
46 {
47 auto status = UErrorCode::U_ZERO_ERROR;
48 auto locale = icu::Locale::forLanguageTag(tag, status);
49 if (UNLIKELY(U_FAILURE(status))) {
50 return icu::Locale::getDefault();
51 }
52 return locale;
53 }
54
ToIcuStyle(ani_env * env,ani_string aniStyle)55 static UListFormatterWidth ToIcuStyle(ani_env *env, ani_string aniStyle)
56 {
57 auto style = ConvertFromAniString(env, aniStyle);
58 if (style == "short") {
59 return UListFormatterWidth::ULISTFMT_WIDTH_SHORT;
60 }
61 if (style == "narrow") {
62 return UListFormatterWidth::ULISTFMT_WIDTH_NARROW;
63 }
64 return UListFormatterWidth::ULISTFMT_WIDTH_WIDE;
65 }
66
ToIcuType(ani_env * env,ani_string aniType)67 static UListFormatterType ToIcuType(ani_env *env, ani_string aniType)
68 {
69 auto type = ConvertFromAniString(env, aniType);
70 if (type == "disjunction") {
71 return UListFormatterType::ULISTFMT_TYPE_OR;
72 }
73 if (type == "unit") {
74 return UListFormatterType::ULISTFMT_TYPE_UNITS;
75 }
76 return UListFormatterType::ULISTFMT_TYPE_AND;
77 }
78
ToIcuList(ani_env * env,ani_array_ref aniList)79 static std::vector<icu::UnicodeString> ToIcuList(ani_env *env, ani_array_ref aniList)
80 {
81 ani_size len;
82 ANI_FATAL_IF_ERROR(env->Array_GetLength(aniList, &len));
83
84 std::vector<icu::UnicodeString> result;
85 for (ani_size i = 0; i < len; i++) {
86 ani_ref aniRef;
87 ANI_FATAL_IF_ERROR(env->Array_Get_Ref(aniList, i, &aniRef));
88
89 auto item = AniToUnicodeStr(env, reinterpret_cast<ani_string>(aniRef));
90 result.push_back(item);
91 }
92 return result;
93 }
94
ToAniArray(ani_env * env,std::vector<ani_string> strings)95 static ani_array_ref ToAniArray(ani_env *env, std::vector<ani_string> strings)
96 {
97 auto first = strings[0];
98 ani_class stringClass;
99 ANI_FATAL_IF_ERROR(env->FindClass("Lstd/core/String;", &stringClass));
100 ani_array_ref array;
101 ANI_FATAL_IF_ERROR(env->Array_New_Ref(stringClass, strings.size(), first, &array));
102 for (size_t i = 1; i < strings.size(); ++i) {
103 auto item = strings[i];
104 ANI_FATAL_IF_ERROR(env->Array_Set_Ref(array, i, item));
105 }
106 return array;
107 }
108
FormatToParts(ani_env * env,ani_class klass,ani_array_ref aniList,ani_string aniLocale,ani_string aniStyle,ani_string aniType)109 ani_object FormatToParts(ani_env *env, [[maybe_unused]] ani_class klass, ani_array_ref aniList, ani_string aniLocale,
110 ani_string aniStyle, ani_string aniType)
111 {
112 auto list = ToIcuList(env, aniList);
113 auto tag = ConvertFromAniString(env, aniLocale);
114 auto locale = GetLocale(tag);
115 auto style = ToIcuStyle(env, aniStyle);
116 auto type = ToIcuType(env, aniType);
117
118 auto status = UErrorCode::U_ZERO_ERROR;
119 auto formatter =
120 std::unique_ptr<icu::ListFormatter>(icu::ListFormatter::createInstance(locale, type, style, status));
121 if (UNLIKELY(U_FAILURE(status))) {
122 ThrowRangeError(env, "Failed to create ListFormatter: ", u_errorName(status));
123 return nullptr;
124 }
125
126 auto formatted = formatter->formatStringsToValue(list.data(), list.size(), status);
127 if (UNLIKELY(U_FAILURE(status))) {
128 ThrowRangeError(env, "Failed to format list: ", u_errorName(status));
129 return nullptr;
130 }
131
132 auto formattedStr = formatted.toTempString(status);
133 if (UNLIKELY(U_FAILURE(status))) {
134 ThrowRangeError(env, "Failed to get formatted string: ", u_errorName(status));
135 return nullptr;
136 }
137
138 icu::ConstrainedFieldPosition pos;
139 pos.constrainCategory(UFIELD_CATEGORY_LIST);
140
141 std::vector<ani_string> squashed;
142 while (formatted.nextPosition(pos, status) != 0) {
143 if (UNLIKELY(U_FAILURE(status))) {
144 ThrowRangeError(env, "Error while iterating positions: ", u_errorName(status));
145 return nullptr;
146 }
147 auto start = pos.getStart();
148 auto limit = pos.getLimit();
149
150 auto field = pos.getField();
151 if (field == UListFormatterField::ULISTFMT_ELEMENT_FIELD) {
152 squashed.push_back(g_elementAniStr);
153 } else if (field == UListFormatterField::ULISTFMT_LITERAL_FIELD) {
154 squashed.push_back(g_literalAniStr);
155 } else {
156 continue;
157 }
158
159 auto segment = formattedStr.tempSubStringBetween(start, limit);
160 auto value = UnicodeToAniStr(env, segment);
161 squashed.push_back(value);
162 }
163 return ToAniArray(env, squashed);
164 }
165
RegisterIntlListFormat(ani_env * env)166 ani_status RegisterIntlListFormat(ani_env *env)
167 {
168 std::array methods = {
169 ani_native_function {"formatToPartsNative",
170 "[Lstd/core/String;Lstd/core/String;Lstd/core/String;Lstd/core/String;:Lstd/core/Object;",
171 reinterpret_cast<void *>(FormatToParts)}};
172
173 g_elementAniStr = StdStrToAni(env, "element");
174 g_literalAniStr = StdStrToAni(env, "literal");
175
176 ani_class listFormatClass;
177 ANI_FATAL_IF_ERROR(env->FindClass("Lstd/core/Intl/ListFormat;", &listFormatClass));
178
179 return env->Class_BindNativeMethods(listFormatClass, methods.data(), methods.size());
180 }
181
182 } // namespace ark::ets::stdlib::intl
183