| 1 | // © 2024 and later: Unicode, Inc. and others. |
| 2 | // License & terms of use: http://www.unicode.org/copyright.html |
| 3 | |
| 4 | #include "unicode/utypes.h" |
| 5 | |
| 6 | #if !UCONFIG_NO_NORMALIZATION |
| 7 | |
| 8 | #if !UCONFIG_NO_FORMATTING |
| 9 | |
| 10 | #if !UCONFIG_NO_MF2 |
| 11 | |
| 12 | #include "unicode/messageformat2.h" |
| 13 | #include "messageformat2_allocation.h" |
| 14 | #include "messageformat2_checker.h" |
| 15 | #include "messageformat2_errors.h" |
| 16 | #include "messageformat2_evaluation.h" |
| 17 | #include "messageformat2_function_registry_internal.h" |
| 18 | #include "messageformat2_macros.h" |
| 19 | #include "messageformat2_parser.h" |
| 20 | #include "messageformat2_serializer.h" |
| 21 | #include "uvector.h" // U_ASSERT |
| 22 | |
| 23 | U_NAMESPACE_BEGIN |
| 24 | |
| 25 | namespace message2 { |
| 26 | |
| 27 | // MessageFormatter::Builder |
| 28 | |
| 29 | // ------------------------------------- |
| 30 | // Creates a MessageFormat instance based on the pattern. |
| 31 | |
| 32 | void MessageFormatter::Builder::clearState() { |
| 33 | normalizedInput.remove(); |
| 34 | delete errors; |
| 35 | errors = nullptr; |
| 36 | } |
| 37 | |
| 38 | MessageFormatter::Builder& MessageFormatter::Builder::setPattern(const UnicodeString& pat, |
| 39 | UParseError& parseError, |
| 40 | UErrorCode& errorCode) { |
| 41 | clearState(); |
| 42 | // Create errors |
| 43 | errors = create<StaticErrors>(StaticErrors(errorCode), errorCode); |
| 44 | THIS_ON_ERROR(errorCode); |
| 45 | |
| 46 | // Parse the pattern |
| 47 | MFDataModel::Builder tree(errorCode); |
| 48 | Parser(pat, tree, *errors, normalizedInput, errorCode) |
| 49 | .parse(parseError, errorCode); |
| 50 | |
| 51 | // Fail on syntax errors |
| 52 | if (errors->hasSyntaxError()) { |
| 53 | errors->checkErrors(errorCode); |
| 54 | // Check that the checkErrors() method set the error code |
| 55 | U_ASSERT(U_FAILURE(errorCode)); |
| 56 | } |
| 57 | |
| 58 | // Build the data model based on what was parsed |
| 59 | dataModel = tree.build(errorCode); |
| 60 | hasDataModel = true; |
| 61 | hasPattern = true; |
| 62 | pattern = pat; |
| 63 | |
| 64 | return *this; |
| 65 | } |
| 66 | |
| 67 | // Precondition: `reg` is non-null |
| 68 | // Does not adopt `reg` |
| 69 | MessageFormatter::Builder& MessageFormatter::Builder::setFunctionRegistry(const MFFunctionRegistry& reg) { |
| 70 | customMFFunctionRegistry = ® |
| 71 | return *this; |
| 72 | } |
| 73 | |
| 74 | MessageFormatter::Builder& MessageFormatter::Builder::setLocale(const Locale& loc) { |
| 75 | locale = loc; |
| 76 | return *this; |
| 77 | } |
| 78 | |
| 79 | MessageFormatter::Builder& MessageFormatter::Builder::setDataModel(MFDataModel&& newDataModel) { |
| 80 | clearState(); |
| 81 | hasPattern = false; |
| 82 | hasDataModel = true; |
| 83 | dataModel = std::move(newDataModel); |
| 84 | |
| 85 | return *this; |
| 86 | } |
| 87 | |
| 88 | MessageFormatter::Builder& |
| 89 | MessageFormatter::Builder::setErrorHandlingBehavior( |
| 90 | MessageFormatter::UMFErrorHandlingBehavior type) { |
| 91 | signalErrors = type == U_MF_STRICT; |
| 92 | return *this; |
| 93 | } |
| 94 | |
| 95 | /* |
| 96 | This build() method is non-destructive, which entails the risk that |
| 97 | its borrowed MFFunctionRegistry and (if the setDataModel() method was called) |
| 98 | MFDataModel pointers could become invalidated. |
| 99 | */ |
| 100 | MessageFormatter MessageFormatter::Builder::build(UErrorCode& errorCode) const { |
| 101 | return MessageFormatter(*this, errorCode); |
| 102 | } |
| 103 | |
| 104 | MessageFormatter::Builder::Builder(UErrorCode& errorCode) : locale(Locale::getDefault()), customMFFunctionRegistry(nullptr) { |
| 105 | // Initialize errors |
| 106 | errors = new StaticErrors(errorCode); |
| 107 | CHECK_ERROR(errorCode); |
| 108 | if (errors == nullptr) { |
| 109 | errorCode = U_MEMORY_ALLOCATION_ERROR; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | MessageFormatter::Builder::~Builder() { |
| 114 | if (errors != nullptr) { |
| 115 | delete errors; |
| 116 | errors = nullptr; |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | // MessageFormatter |
| 121 | |
| 122 | // Returns the NFC-normalized version of s, returning s itself |
| 123 | // if it's already normalized. |
| 124 | UnicodeString MessageFormatter::normalizeNFC(const UnicodeString& s) const { |
| 125 | UErrorCode status = U_ZERO_ERROR; |
| 126 | // Check if string is already normalized |
| 127 | UNormalizationCheckResult result = nfcNormalizer->quickCheck(s, status); |
| 128 | // If so, return it |
| 129 | if (U_SUCCESS(status) && result == UNORM_YES) { |
| 130 | return s; |
| 131 | } |
| 132 | // Otherwise, normalize it |
| 133 | UnicodeString normalized = nfcNormalizer->normalize(s, status); |
| 134 | if (U_FAILURE(status)) { |
| 135 | return {}; |
| 136 | } |
| 137 | return normalized; |
| 138 | } |
| 139 | |
| 140 | MessageFormatter::MessageFormatter(const MessageFormatter::Builder& builder, UErrorCode &success) : locale(builder.locale), customMFFunctionRegistry(builder.customMFFunctionRegistry) { |
| 141 | CHECK_ERROR(success); |
| 142 | |
| 143 | // Set up the standard function registry |
| 144 | MFFunctionRegistry::Builder standardFunctionsBuilder(success); |
| 145 | |
| 146 | FormatterFactory* dateTime = StandardFunctions::DateTimeFactory::dateTime(success); |
| 147 | FormatterFactory* date = StandardFunctions::DateTimeFactory::date(success); |
| 148 | FormatterFactory* time = StandardFunctions::DateTimeFactory::time(success); |
| 149 | FormatterFactory* number = new StandardFunctions::NumberFactory(); |
| 150 | FormatterFactory* integer = new StandardFunctions::IntegerFactory(); |
| 151 | standardFunctionsBuilder.adoptFormatter(FunctionName(UnicodeString("datetime")), dateTime, success) |
| 152 | .adoptFormatter(FunctionName(UnicodeString("date")), date, success) |
| 153 | .adoptFormatter(FunctionName(UnicodeString("time")), time, success) |
| 154 | .adoptFormatter(FunctionName(UnicodeString("number")), number, success) |
| 155 | .adoptFormatter(FunctionName(UnicodeString("integer")), integer, success) |
| 156 | .adoptFormatter(FunctionName(UnicodeString("test:function")), new StandardFunctions::TestFormatFactory(), success) |
| 157 | .adoptFormatter(FunctionName(UnicodeString("test:format")), new StandardFunctions::TestFormatFactory(), success) |
| 158 | .adoptSelector(FunctionName(UnicodeString("number")), new StandardFunctions::PluralFactory(UPLURAL_TYPE_CARDINAL), success) |
| 159 | .adoptSelector(FunctionName(UnicodeString("integer")), new StandardFunctions::PluralFactory(StandardFunctions::PluralFactory::integer()), success) |
| 160 | .adoptSelector(FunctionName(UnicodeString("string")), new StandardFunctions::TextFactory(), success) |
| 161 | .adoptSelector(FunctionName(UnicodeString("test:function")), new StandardFunctions::TestSelectFactory(), success) |
| 162 | .adoptSelector(FunctionName(UnicodeString("test:select")), new StandardFunctions::TestSelectFactory(), success); |
| 163 | CHECK_ERROR(success); |
| 164 | standardMFFunctionRegistry = standardFunctionsBuilder.build(); |
| 165 | CHECK_ERROR(success); |
| 166 | standardMFFunctionRegistry.checkStandard(); |
| 167 | |
| 168 | normalizedInput = builder.normalizedInput; |
| 169 | signalErrors = builder.signalErrors; |
| 170 | |
| 171 | // Build data model |
| 172 | // First, check that there is a data model |
| 173 | // (which might have been set by setDataModel(), or to |
| 174 | // the data model parsed from the pattern by setPattern()) |
| 175 | |
| 176 | if (!builder.hasDataModel) { |
| 177 | success = U_INVALID_STATE_ERROR; |
| 178 | return; |
| 179 | } |
| 180 | |
| 181 | dataModel = builder.dataModel; |
| 182 | if (builder.errors != nullptr) { |
| 183 | errors = new StaticErrors(*builder.errors, success); |
| 184 | } else { |
| 185 | // Initialize errors |
| 186 | LocalPointer<StaticErrors> errorsNew(new StaticErrors(success)); |
| 187 | CHECK_ERROR(success); |
| 188 | errors = errorsNew.orphan(); |
| 189 | } |
| 190 | |
| 191 | nfcNormalizer = Normalizer2::getNFCInstance(success); |
| 192 | |
| 193 | // Note: we currently evaluate variables lazily, |
| 194 | // without memoization. This call is still necessary |
| 195 | // to check out-of-scope uses of local variables in |
| 196 | // right-hand sides (unresolved variable errors can |
| 197 | // only be checked when arguments are known) |
| 198 | |
| 199 | // Check for resolution errors |
| 200 | Checker(dataModel, *errors, *this).check(success); |
| 201 | } |
| 202 | |
| 203 | void MessageFormatter::cleanup() noexcept { |
| 204 | if (errors != nullptr) { |
| 205 | delete errors; |
| 206 | errors = nullptr; |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | MessageFormatter& MessageFormatter::operator=(MessageFormatter&& other) noexcept { |
| 211 | cleanup(); |
| 212 | |
| 213 | locale = std::move(other.locale); |
| 214 | standardMFFunctionRegistry = std::move(other.standardMFFunctionRegistry); |
| 215 | customMFFunctionRegistry = other.customMFFunctionRegistry; |
| 216 | dataModel = std::move(other.dataModel); |
| 217 | normalizedInput = std::move(other.normalizedInput); |
| 218 | signalErrors = other.signalErrors; |
| 219 | errors = other.errors; |
| 220 | other.errors = nullptr; |
| 221 | nfcNormalizer = other.nfcNormalizer; |
| 222 | return *this; |
| 223 | } |
| 224 | |
| 225 | const MFDataModel& MessageFormatter::getDataModel() const { return dataModel; } |
| 226 | |
| 227 | UnicodeString MessageFormatter::getPattern() const { |
| 228 | // Converts the current data model back to a string |
| 229 | UnicodeString result; |
| 230 | Serializer serializer(getDataModel(), result); |
| 231 | serializer.serialize(); |
| 232 | return result; |
| 233 | } |
| 234 | |
| 235 | // Precondition: custom function registry exists |
| 236 | const MFFunctionRegistry& MessageFormatter::getCustomMFFunctionRegistry() const { |
| 237 | U_ASSERT(hasCustomMFFunctionRegistry()); |
| 238 | return *customMFFunctionRegistry; |
| 239 | } |
| 240 | |
| 241 | MessageFormatter::~MessageFormatter() { |
| 242 | cleanup(); |
| 243 | } |
| 244 | |
| 245 | // Selector and formatter lookup |
| 246 | // ----------------------------- |
| 247 | |
| 248 | // Postcondition: selector != nullptr || U_FAILURE(status) |
| 249 | Selector* MessageFormatter::getSelector(MessageContext& context, const FunctionName& functionName, UErrorCode& status) const { |
| 250 | NULL_ON_ERROR(status); |
| 251 | U_ASSERT(isSelector(functionName)); |
| 252 | |
| 253 | const SelectorFactory* selectorFactory = lookupSelectorFactory(context, functionName, status); |
| 254 | NULL_ON_ERROR(status); |
| 255 | if (selectorFactory == nullptr) { |
| 256 | status = U_MEMORY_ALLOCATION_ERROR; |
| 257 | return nullptr; |
| 258 | } |
| 259 | // Create a specific instance of the selector |
| 260 | auto result = selectorFactory->createSelector(getLocale(), status); |
| 261 | NULL_ON_ERROR(status); |
| 262 | return result; |
| 263 | } |
| 264 | |
| 265 | // Returns an owned pointer |
| 266 | Formatter* MessageFormatter::getFormatter(const FunctionName& functionName, UErrorCode& status) const { |
| 267 | NULL_ON_ERROR(status); |
| 268 | |
| 269 | // Create the formatter |
| 270 | |
| 271 | // First, look up the formatter factory for this function |
| 272 | FormatterFactory* formatterFactory = lookupFormatterFactory(functionName, status); |
| 273 | NULL_ON_ERROR(status); |
| 274 | |
| 275 | U_ASSERT(formatterFactory != nullptr); |
| 276 | |
| 277 | // Create a specific instance of the formatter |
| 278 | Formatter* formatter = formatterFactory->createFormatter(locale, status); |
| 279 | NULL_ON_ERROR(status); |
| 280 | if (formatter == nullptr) { |
| 281 | status = U_MEMORY_ALLOCATION_ERROR; |
| 282 | return nullptr; |
| 283 | } |
| 284 | return formatter; |
| 285 | } |
| 286 | |
| 287 | bool MessageFormatter::getDefaultFormatterNameByType(const UnicodeString& type, |
| 288 | FunctionName& name) const { |
| 289 | if (!hasCustomMFFunctionRegistry()) { |
| 290 | return false; |
| 291 | } |
| 292 | const MFFunctionRegistry& reg = getCustomMFFunctionRegistry(); |
| 293 | return reg.getDefaultFormatterNameByType(type, name); |
| 294 | } |
| 295 | |
| 296 | // --------------------------------------------------- |
| 297 | // Function registry |
| 298 | |
| 299 | bool MessageFormatter::isBuiltInSelector(const FunctionName& functionName) const { |
| 300 | return standardMFFunctionRegistry.hasSelector(functionName); |
| 301 | } |
| 302 | |
| 303 | bool MessageFormatter::isBuiltInFormatter(const FunctionName& functionName) const { |
| 304 | return standardMFFunctionRegistry.hasFormatter(functionName); |
| 305 | } |
| 306 | |
| 307 | // https://github.com/unicode-org/message-format-wg/issues/409 |
| 308 | // Unknown function = unknown function error |
| 309 | // Formatter used as selector = selector error |
| 310 | // Selector used as formatter = formatting error |
| 311 | const SelectorFactory* MessageFormatter::lookupSelectorFactory(MessageContext& context, const FunctionName& functionName, UErrorCode& status) const { |
| 312 | DynamicErrors& err = context.getErrors(); |
| 313 | |
| 314 | if (isBuiltInSelector(functionName)) { |
| 315 | return standardMFFunctionRegistry.getSelector(functionName); |
| 316 | } |
| 317 | if (isBuiltInFormatter(functionName)) { |
| 318 | err.setSelectorError(functionName, status); |
| 319 | return nullptr; |
| 320 | } |
| 321 | if (hasCustomMFFunctionRegistry()) { |
| 322 | const MFFunctionRegistry& customMFFunctionRegistry = getCustomMFFunctionRegistry(); |
| 323 | const SelectorFactory* selectorFactory = customMFFunctionRegistry.getSelector(functionName); |
| 324 | if (selectorFactory != nullptr) { |
| 325 | return selectorFactory; |
| 326 | } |
| 327 | if (customMFFunctionRegistry.getFormatter(functionName) != nullptr) { |
| 328 | err.setSelectorError(functionName, status); |
| 329 | return nullptr; |
| 330 | } |
| 331 | } |
| 332 | // Either there is no custom function registry and the function |
| 333 | // isn't built-in, or the function doesn't exist in either the built-in |
| 334 | // or custom registry. |
| 335 | // Unknown function error |
| 336 | err.setUnknownFunction(functionName, status); |
| 337 | return nullptr; |
| 338 | } |
| 339 | |
| 340 | FormatterFactory* MessageFormatter::lookupFormatterFactory(const FunctionName& functionName, |
| 341 | UErrorCode& status) const { |
| 342 | NULL_ON_ERROR(status); |
| 343 | |
| 344 | if (isBuiltInFormatter(functionName)) { |
| 345 | return standardMFFunctionRegistry.getFormatter(functionName); |
| 346 | } |
| 347 | if (isBuiltInSelector(functionName)) { |
| 348 | status = U_MF_FORMATTING_ERROR; |
| 349 | return nullptr; |
| 350 | } |
| 351 | if (hasCustomMFFunctionRegistry()) { |
| 352 | const MFFunctionRegistry& customMFFunctionRegistry = getCustomMFFunctionRegistry(); |
| 353 | FormatterFactory* formatterFactory = customMFFunctionRegistry.getFormatter(functionName); |
| 354 | if (formatterFactory != nullptr) { |
| 355 | return formatterFactory; |
| 356 | } |
| 357 | if (customMFFunctionRegistry.getSelector(functionName) != nullptr) { |
| 358 | status = U_MF_FORMATTING_ERROR; |
| 359 | return nullptr; |
| 360 | } |
| 361 | } |
| 362 | // Either there is no custom function registry and the function |
| 363 | // isn't built-in, or the function doesn't exist in either the built-in |
| 364 | // or custom registry. |
| 365 | // Unknown function error |
| 366 | status = U_MF_UNKNOWN_FUNCTION_ERROR; |
| 367 | return nullptr; |
| 368 | } |
| 369 | |
| 370 | bool MessageFormatter::isCustomFormatter(const FunctionName& fn) const { |
| 371 | return hasCustomMFFunctionRegistry() && getCustomMFFunctionRegistry().getFormatter(fn) != nullptr; |
| 372 | } |
| 373 | |
| 374 | |
| 375 | bool MessageFormatter::isCustomSelector(const FunctionName& fn) const { |
| 376 | return hasCustomMFFunctionRegistry() && getCustomMFFunctionRegistry().getSelector(fn) != nullptr; |
| 377 | } |
| 378 | |
| 379 | } // namespace message2 |
| 380 | |
| 381 | U_NAMESPACE_END |
| 382 | |
| 383 | #endif /* #if !UCONFIG_NO_MF2 */ |
| 384 | |
| 385 | #endif /* #if !UCONFIG_NO_FORMATTING */ |
| 386 | |
| 387 | #endif /* #if !UCONFIG_NO_NORMALIZATION */ |