| 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_arguments.h" |
| 13 |
#include "unicode/messageformat2_data_model.h" |
| 14 |
#include "unicode/messageformat2_formattable.h" |
| 15 |
#include "unicode/messageformat2.h" |
| 16 |
#include "unicode/normalizer2.h" |
| 17 |
#include "unicode/unistr.h" |
| 18 |
#include "messageformat2_allocation.h" |
| 19 |
#include "messageformat2_checker.h" |
| 20 |
#include "messageformat2_evaluation.h" |
| 21 |
#include "messageformat2_macros.h" |
| 22 |
|
| 23 |
|
| 24 |
U_NAMESPACE_BEGIN |
| 25 |
|
| 26 |
namespace message2 { |
| 27 |
|
| 28 |
using namespace data_model; |
| 29 |
|
| 30 |
// ------------------------------------------------------ |
| 31 |
// Formatting |
| 32 |
|
| 33 |
// The result of formatting a literal is just itself. |
| 34 |
static Formattable evalLiteral(const Literal& lit) { |
| 35 |
return Formattable(lit.unquoted()); |
| 36 |
} |
| 37 |
|
| 38 |
// Assumes that `var` is a message argument; returns the argument's value. |
| 39 |
[[nodiscard]] FormattedPlaceholder MessageFormatter::evalArgument(const VariableName& var, MessageContext& context, UErrorCode& errorCode) const { |
| 40 |
if (U_SUCCESS(errorCode)) { |
| 41 |
// The fallback for a variable name is itself. |
| 42 |
UnicodeString str(DOLLAR); |
| 43 |
str += var; |
| 44 |
const Formattable* val = context.getGlobal(*this, var, errorCode); |
| 45 |
if (U_SUCCESS(errorCode)) { |
| 46 |
return (FormattedPlaceholder(*val, str)); |
| 47 |
} |
| 48 |
} |
| 49 |
return {}; |
| 50 |
} |
| 51 |
|
| 52 |
// Returns the contents of the literal |
| 53 |
[[nodiscard]] FormattedPlaceholder MessageFormatter::formatLiteral(const Literal& lit) const { |
| 54 |
// The fallback for a literal is itself. |
| 55 |
return FormattedPlaceholder(evalLiteral(lit), lit.quoted()); |
| 56 |
} |
| 57 |
|
| 58 |
[[nodiscard]] InternalValue* MessageFormatter::formatOperand(const Environment& env, |
| 59 |
const Operand& rand, |
| 60 |
MessageContext& context, |
| 61 |
UErrorCode &status) const { |
| 62 |
if (U_FAILURE(status)) { |
| 63 |
return {}; |
| 64 |
} |
| 65 |
|
| 66 |
if (rand.isNull()) { |
| 67 |
return create<InternalValue>(InternalValue(FormattedPlaceholder()), status); |
| 68 |
} |
| 69 |
if (rand.isVariable()) { |
| 70 |
// Check if it's local or global |
| 71 |
// Note: there is no name shadowing; this is enforced by the parser |
| 72 |
const VariableName& var = rand.asVariable(); |
| 73 |
// TODO: Currently, this code implements lazy evaluation of locals. |
| 74 |
// That is, the environment binds names to a closure, not a resolved value. |
| 75 |
// Eager vs. lazy evaluation is an open issue: |
| 76 |
// see https://github.com/unicode-org/message-format-wg/issues/299 |
| 77 |
|
| 78 |
// NFC-normalize the variable name. See |
| 79 |
// https://github.com/unicode-org/message-format-wg/blob/main/spec/syntax.md#names-and-identifiers |
| 80 |
const VariableName normalized = normalizeNFC(var); |
| 81 |
|
| 82 |
// Look up the variable in the environment |
| 83 |
if (env.has(normalized)) { |
| 84 |
// `var` is a local -- look it up |
| 85 |
const Closure& rhs = env.lookup(normalized); |
| 86 |
// Format the expression using the environment from the closure |
| 87 |
return formatExpression(rhs.getEnv(), rhs.getExpr(), context, status); |
| 88 |
} |
| 89 |
// Variable wasn't found in locals -- check if it's global |
| 90 |
FormattedPlaceholder result = evalArgument(normalized, context, status); |
| 91 |
if (status == U_ILLEGAL_ARGUMENT_ERROR) { |
| 92 |
status = U_ZERO_ERROR; |
| 93 |
// Unbound variable -- set a resolution error |
| 94 |
context.getErrors().setUnresolvedVariable(var, status); |
| 95 |
// Use fallback per |
| 96 |
// https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#fallback-resolution |
| 97 |
UnicodeString str(DOLLAR); |
| 98 |
str += var; |
| 99 |
return create<InternalValue>(InternalValue(FormattedPlaceholder(str)), status); |
| 100 |
} |
| 101 |
return create<InternalValue>(InternalValue(std::move(result)), status); |
| 102 |
} else { |
| 103 |
U_ASSERT(rand.isLiteral()); |
| 104 |
return create<InternalValue>(InternalValue(formatLiteral(rand.asLiteral())), status); |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
// Resolves a function's options |
| 109 |
FunctionOptions MessageFormatter::resolveOptions(const Environment& env, const OptionMap& options, MessageContext& context, UErrorCode& status) const { |
| 110 |
LocalPointer<UVector> optionsVector(createUVector(status)); |
| 111 |
if (U_FAILURE(status)) { |
| 112 |
return {}; |
| 113 |
} |
| 114 |
LocalPointer<ResolvedFunctionOption> resolvedOpt; |
| 115 |
for (int i = 0; i < options.size(); i++) { |
| 116 |
const Option& opt = options.getOption(i, status); |
| 117 |
if (U_FAILURE(status)) { |
| 118 |
return {}; |
| 119 |
} |
| 120 |
const UnicodeString& k = opt.getName(); |
| 121 |
const Operand& v = opt.getValue(); |
| 122 |
|
| 123 |
// Options are fully evaluated before calling the function |
| 124 |
// Format the operand |
| 125 |
LocalPointer<InternalValue> rhsVal(formatOperand(env, v, context, status)); |
| 126 |
if (U_FAILURE(status)) { |
| 127 |
return {}; |
| 128 |
} |
| 129 |
// Note: this means option values are "eagerly" evaluated. |
| 130 |
// Currently, options don't have options. This will be addressed by the |
| 131 |
// full FormattedPlaceholder redesign. |
| 132 |
FormattedPlaceholder optValue = rhsVal->forceFormatting(context.getErrors(), status); |
| 133 |
resolvedOpt.adoptInstead(create<ResolvedFunctionOption> |
| 134 |
(ResolvedFunctionOption(k, |
| 135 |
optValue.asFormattable()), |
| 136 |
status)); |
| 137 |
if (U_FAILURE(status)) { |
| 138 |
return {}; |
| 139 |
} |
| 140 |
optionsVector->adoptElement(resolvedOpt.orphan(), status); |
| 141 |
} |
| 142 |
return FunctionOptions(std::move(*optionsVector), status); |
| 143 |
} |
| 144 |
|
| 145 |
// Overload that dispatches on argument type. Syntax doesn't provide for options in this case. |
| 146 |
[[nodiscard]] InternalValue* MessageFormatter::evalFunctionCall(FormattedPlaceholder&& argument, |
| 147 |
MessageContext& context, |
| 148 |
UErrorCode& status) const { |
| 149 |
if (U_FAILURE(status)) { |
| 150 |
return nullptr; |
| 151 |
} |
| 152 |
|
| 153 |
// These cases should have been checked for already |
| 154 |
U_ASSERT(!argument.isFallback() && !argument.isNullOperand()); |
| 155 |
|
| 156 |
const Formattable& toFormat = argument.asFormattable(); |
| 157 |
switch (toFormat.getType()) { |
| 158 |
case UFMT_OBJECT: { |
| 159 |
const FormattableObject* obj = toFormat.getObject(status); |
| 160 |
U_ASSERT(U_SUCCESS(status)); |
| 161 |
U_ASSERT(obj != nullptr); |
| 162 |
const UnicodeString& type = obj->tag(); |
| 163 |
FunctionName functionName; |
| 164 |
if (!getDefaultFormatterNameByType(type, functionName)) { |
| 165 |
// No formatter for this type -- follow default behavior |
| 166 |
break; |
| 167 |
} |
| 168 |
return evalFunctionCall(functionName, |
| 169 |
create<InternalValue>(std::move(argument), status), |
| 170 |
FunctionOptions(), |
| 171 |
context, |
| 172 |
status); |
| 173 |
} |
| 174 |
default: { |
| 175 |
// TODO: The array case isn't handled yet; not sure whether it's desirable |
| 176 |
// to have a default list formatter |
| 177 |
break; |
| 178 |
} |
| 179 |
} |
| 180 |
// No formatter for this type, or it's a primitive type (which will be formatted later) |
| 181 |
// -- just return the argument itself |
| 182 |
return create<InternalValue>(std::move(argument), status); |
| 183 |
} |
| 184 |
|
| 185 |
// Overload that dispatches on function name |
| 186 |
// Adopts `arg` |
| 187 |
[[nodiscard]] InternalValue* MessageFormatter::evalFunctionCall(const FunctionName& functionName, |
| 188 |
InternalValue* arg_, |
| 189 |
FunctionOptions&& options, |
| 190 |
MessageContext& context, |
| 191 |
UErrorCode& status) const { |
| 192 |
if (U_FAILURE(status)) { |
| 193 |
return {}; |
| 194 |
} |
| 195 |
|
| 196 |
LocalPointer<InternalValue> arg(arg_); |
| 197 |
|
| 198 |
// Look up the formatter or selector |
| 199 |
LocalPointer<Formatter> formatterImpl(nullptr); |
| 200 |
LocalPointer<Selector> selectorImpl(nullptr); |
| 201 |
if (isFormatter(functionName)) { |
| 202 |
formatterImpl.adoptInstead(getFormatter(functionName, status)); |
| 203 |
U_ASSERT(U_SUCCESS(status)); |
| 204 |
} |
| 205 |
if (isSelector(functionName)) { |
| 206 |
selectorImpl.adoptInstead(getSelector(context, functionName, status)); |
| 207 |
U_ASSERT(U_SUCCESS(status)); |
| 208 |
} |
| 209 |
if (formatterImpl == nullptr && selectorImpl == nullptr) { |
| 210 |
// Unknown function error |
| 211 |
context.getErrors().setUnknownFunction(functionName, status); |
| 212 |
|
| 213 |
if (arg->hasNullOperand()) { |
| 214 |
// Non-selector used as selector; an error would have been recorded earlier |
| 215 |
UnicodeString fallback(COLON); |
| 216 |
fallback += functionName; |
| 217 |
return new InternalValue(FormattedPlaceholder(fallback)); |
| 218 |
} else { |
| 219 |
return new InternalValue(FormattedPlaceholder(arg->getFallback())); |
| 220 |
} |
| 221 |
} |
| 222 |
return new InternalValue(arg.orphan(), |
| 223 |
std::move(options), |
| 224 |
functionName, |
| 225 |
formatterImpl.isValid() ? formatterImpl.orphan() : nullptr, |
| 226 |
selectorImpl.isValid() ? selectorImpl.orphan() : nullptr); |
| 227 |
} |
| 228 |
|
| 229 |
// Formats an expression using `globalEnv` for the values of variables |
| 230 |
[[nodiscard]] InternalValue* MessageFormatter::formatExpression(const Environment& globalEnv, |
| 231 |
const Expression& expr, |
| 232 |
MessageContext& context, |
| 233 |
UErrorCode &status) const { |
| 234 |
if (U_FAILURE(status)) { |
| 235 |
return {}; |
| 236 |
} |
| 237 |
|
| 238 |
const Operand& rand = expr.getOperand(); |
| 239 |
// Format the operand (formatOperand handles the case of a null operand) |
| 240 |
LocalPointer<InternalValue> randVal(formatOperand(globalEnv, rand, context, status)); |
| 241 |
|
| 242 |
FormattedPlaceholder maybeRand = randVal->takeArgument(status); |
| 243 |
|
| 244 |
if (!expr.isFunctionCall() && U_SUCCESS(status)) { |
| 245 |
// Dispatch based on type of `randVal` |
| 246 |
if (maybeRand.isFallback()) { |
| 247 |
return randVal.orphan(); |
| 248 |
} |
| 249 |
return evalFunctionCall(std::move(maybeRand), context, status); |
| 250 |
} else if (expr.isFunctionCall()) { |
| 251 |
status = U_ZERO_ERROR; |
| 252 |
const Operator* rator = expr.getOperator(status); |
| 253 |
U_ASSERT(U_SUCCESS(status)); |
| 254 |
const FunctionName& functionName = rator->getFunctionName(); |
| 255 |
const OptionMap& options = rator->getOptionsInternal(); |
| 256 |
// Resolve the options |
| 257 |
FunctionOptions resolvedOptions = resolveOptions(globalEnv, options, context, status); |
| 258 |
|
| 259 |
// Call the formatter function |
| 260 |
return evalFunctionCall(functionName, |
| 261 |
randVal.orphan(), |
| 262 |
std::move(resolvedOptions), |
| 263 |
context, |
| 264 |
status); |
| 265 |
} else { |
| 266 |
status = U_ZERO_ERROR; |
| 267 |
return randVal.orphan(); |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
// Formats each text and expression part of a pattern, appending the results to `result` |
| 272 |
void MessageFormatter::formatPattern(MessageContext& context, const Environment& globalEnv, const Pattern& pat, UErrorCode &status, UnicodeString& result) const { |
| 273 |
CHECK_ERROR(status); |
| 274 |
|
| 275 |
for (int32_t i = 0; i < pat.numParts(); i++) { |
| 276 |
const PatternPart& part = pat.getPart(i); |
| 277 |
if (part.isText()) { |
| 278 |
result += part.asText(); |
| 279 |
} else if (part.isMarkup()) { |
| 280 |
// Markup is ignored |
| 281 |
} else { |
| 282 |
// Format the expression |
| 283 |
LocalPointer<InternalValue> partVal( |
| 284 |
formatExpression(globalEnv, part.contents(), context, status)); |
| 285 |
FormattedPlaceholder partResult = partVal->forceFormatting(context.getErrors(), |
| 286 |
status); |
| 287 |
// Force full evaluation, e.g. applying default formatters to |
| 288 |
// unformatted input (or formatting numbers as strings) |
| 289 |
result += partResult.formatToString(locale, status); |
| 290 |
// Handle formatting errors. `formatToString()` can't take a context and thus can't |
| 291 |
// register an error directly |
| 292 |
if (status == U_MF_FORMATTING_ERROR) { |
| 293 |
status = U_ZERO_ERROR; |
| 294 |
// TODO: The name of the formatter that failed is unavailable. |
| 295 |
// Not ideal, but it's hard for `formatToString()` |
| 296 |
// to pass along more detailed diagnostics |
| 297 |
context.getErrors().setFormattingError(status); |
| 298 |
} |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
// ------------------------------------------------------ |
| 304 |
// Selection |
| 305 |
|
| 306 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#resolve-selectors |
| 307 |
// `res` is a vector of ResolvedSelectors |
| 308 |
void MessageFormatter::resolveSelectors(MessageContext& context, const Environment& env, UErrorCode &status, UVector& res) const { |
| 309 |
CHECK_ERROR(status); |
| 310 |
U_ASSERT(!dataModel.hasPattern()); |
| 311 |
|
| 312 |
const VariableName* selectors = dataModel.getSelectorsInternal(); |
| 313 |
// 1. Let res be a new empty list of resolved values that support selection. |
| 314 |
// (Implicit, since `res` is an out-parameter) |
| 315 |
// 2. For each expression exp of the message's selectors |
| 316 |
for (int32_t i = 0; i < dataModel.numSelectors(); i++) { |
| 317 |
// 2i. Let rv be the resolved value of exp. |
| 318 |
LocalPointer<InternalValue> rv(formatOperand(env, Operand(selectors[i]), context, status)); |
| 319 |
if (rv->canSelect()) { |
| 320 |
// 2ii. If selection is supported for rv: |
| 321 |
// (True if this code has been reached) |
| 322 |
} else { |
| 323 |
// 2iii. Else: |
| 324 |
// Let nomatch be a resolved value for which selection always fails. |
| 325 |
// Append nomatch as the last element of the list res. |
| 326 |
// Emit a Selection Error. |
| 327 |
// (Note: in this case, rv, being a fallback, serves as `nomatch`) |
| 328 |
DynamicErrors& err = context.getErrors(); |
| 329 |
err.setSelectorError(rv->getFunctionName(), status); |
| 330 |
rv.adoptInstead(new InternalValue(FormattedPlaceholder(rv->getFallback()))); |
| 331 |
if (!rv.isValid()) { |
| 332 |
status = U_MEMORY_ALLOCATION_ERROR; |
| 333 |
return; |
| 334 |
} |
| 335 |
} |
| 336 |
// 2ii(a). Append rv as the last element of the list res. |
| 337 |
// (Also fulfills 2iii) |
| 338 |
res.adoptElement(rv.orphan(), status); |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#resolve-preferences |
| 343 |
// `keys` and `matches` are vectors of strings |
| 344 |
void MessageFormatter::matchSelectorKeys(const UVector& keys, |
| 345 |
MessageContext& context, |
| 346 |
InternalValue* rv, // Does not adopt `rv` |
| 347 |
UVector& keysOut, |
| 348 |
UErrorCode& status) const { |
| 349 |
CHECK_ERROR(status); |
| 350 |
|
| 351 |
if (U_FAILURE(status)) { |
| 352 |
// Return an empty list of matches |
| 353 |
status = U_ZERO_ERROR; |
| 354 |
return; |
| 355 |
} |
| 356 |
|
| 357 |
UErrorCode savedStatus = status; |
| 358 |
|
| 359 |
// Convert `keys` to an array |
| 360 |
int32_t keysLen = keys.size(); |
| 361 |
UnicodeString* keysArr = new UnicodeString[keysLen]; |
| 362 |
if (keysArr == nullptr) { |
| 363 |
status = U_MEMORY_ALLOCATION_ERROR; |
| 364 |
return; |
| 365 |
} |
| 366 |
for (int32_t i = 0; i < keysLen; i++) { |
| 367 |
const UnicodeString* k = static_cast<UnicodeString*>(keys[i]); |
| 368 |
U_ASSERT(k != nullptr); |
| 369 |
keysArr[i] = *k; |
| 370 |
} |
| 371 |
LocalArray<UnicodeString> adoptedKeys(keysArr); |
| 372 |
|
| 373 |
// Create an array to hold the output |
| 374 |
UnicodeString* prefsArr = new UnicodeString[keysLen]; |
| 375 |
if (prefsArr == nullptr) { |
| 376 |
status = U_MEMORY_ALLOCATION_ERROR; |
| 377 |
return; |
| 378 |
} |
| 379 |
LocalArray<UnicodeString> adoptedPrefs(prefsArr); |
| 380 |
int32_t prefsLen = 0; |
| 381 |
|
| 382 |
// Call the selector |
| 383 |
FunctionName name = rv->getFunctionName(); |
| 384 |
rv->forceSelection(context.getErrors(), |
| 385 |
adoptedKeys.getAlias(), keysLen, |
| 386 |
adoptedPrefs.getAlias(), prefsLen, |
| 387 |
status); |
| 388 |
|
| 389 |
// Update errors |
| 390 |
if (savedStatus != status) { |
| 391 |
if (U_FAILURE(status)) { |
| 392 |
status = U_ZERO_ERROR; |
| 393 |
context.getErrors().setSelectorError(name, status); |
| 394 |
} else { |
| 395 |
// Ignore warnings |
| 396 |
status = savedStatus; |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
CHECK_ERROR(status); |
| 401 |
|
| 402 |
// Copy the resulting keys (if there was no error) |
| 403 |
keysOut.removeAllElements(); |
| 404 |
for (int32_t i = 0; i < prefsLen; i++) { |
| 405 |
UnicodeString* k = message2::create<UnicodeString>(std::move(prefsArr[i]), status); |
| 406 |
if (k == nullptr) { |
| 407 |
status = U_MEMORY_ALLOCATION_ERROR; |
| 408 |
return; |
| 409 |
} |
| 410 |
keysOut.adoptElement(k, status); |
| 411 |
CHECK_ERROR(status); |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#resolve-preferences |
| 416 |
// `res` is a vector of FormattedPlaceholders; |
| 417 |
// `pref` is a vector of vectors of strings |
| 418 |
void MessageFormatter::resolvePreferences(MessageContext& context, UVector& res, UVector& pref, UErrorCode &status) const { |
| 419 |
CHECK_ERROR(status); |
| 420 |
|
| 421 |
// 1. Let pref be a new empty list of lists of strings. |
| 422 |
// (Implicit, since `pref` is an out-parameter) |
| 423 |
UnicodeString ks; |
| 424 |
LocalPointer<UnicodeString> ksP; |
| 425 |
int32_t numVariants = dataModel.numVariants(); |
| 426 |
const Variant* variants = dataModel.getVariantsInternal(); |
| 427 |
// 2. For each index i in res |
| 428 |
for (int32_t i = 0; i < res.size(); i++) { |
| 429 |
// 2i. Let keys be a new empty list of strings. |
| 430 |
LocalPointer<UVector> keys(createUVector(status)); |
| 431 |
CHECK_ERROR(status); |
| 432 |
// 2ii. For each variant `var` of the message |
| 433 |
for (int32_t variantNum = 0; variantNum < numVariants; variantNum++) { |
| 434 |
const SelectorKeys& selectorKeys = variants[variantNum].getKeys(); |
| 435 |
|
| 436 |
// Note: Here, `var` names the key list of `var`, |
| 437 |
// not a Variant itself |
| 438 |
const Key* var = selectorKeys.getKeysInternal(); |
| 439 |
// 2ii(a). Let `key` be the `var` key at position i. |
| 440 |
U_ASSERT(i < selectorKeys.len); // established by semantic check in formatSelectors() |
| 441 |
const Key& key = var[i]; |
| 442 |
// 2ii(b). If `key` is not the catch-all key '*' |
| 443 |
if (!key.isWildcard()) { |
| 444 |
// 2ii(b)(a) Assert that key is a literal. |
| 445 |
// (Not needed) |
| 446 |
// 2ii(b)(b) Let `ks` be the resolved value of `key` in Unicode Normalization Form C. |
| 447 |
ks = normalizeNFC(key.asLiteral().unquoted()); |
| 448 |
// 2ii(b)(c) Append `ks` as the last element of the list `keys`. |
| 449 |
ksP.adoptInstead(create<UnicodeString>(std::move(ks), status)); |
| 450 |
CHECK_ERROR(status); |
| 451 |
keys->adoptElement(ksP.orphan(), status); |
| 452 |
} |
| 453 |
} |
| 454 |
// 2iii. Let `rv` be the resolved value at index `i` of `res`. |
| 455 |
U_ASSERT(i < res.size()); |
| 456 |
InternalValue* rv = static_cast<InternalValue*>(res[i]); |
| 457 |
// 2iv. Let matches be the result of calling the method MatchSelectorKeys(rv, keys) |
| 458 |
LocalPointer<UVector> matches(createUVector(status)); |
| 459 |
matchSelectorKeys(*keys, context, std::move(rv), *matches, status); |
| 460 |
// 2v. Append `matches` as the last element of the list `pref` |
| 461 |
pref.adoptElement(matches.orphan(), status); |
| 462 |
} |
| 463 |
} |
| 464 |
|
| 465 |
// `v` is assumed to be a vector of strings |
| 466 |
static int32_t vectorFind(const UVector& v, const UnicodeString& k) { |
| 467 |
for (int32_t i = 0; i < v.size(); i++) { |
| 468 |
if (*static_cast<UnicodeString*>(v[i]) == k) { |
| 469 |
return i; |
| 470 |
} |
| 471 |
} |
| 472 |
return -1; |
| 473 |
} |
| 474 |
|
| 475 |
static UBool vectorContains(const UVector& v, const UnicodeString& k) { |
| 476 |
return (vectorFind(v, k) != -1); |
| 477 |
} |
| 478 |
|
| 479 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#filter-variants |
| 480 |
// `pref` is a vector of vectors of strings. `vars` is a vector of PrioritizedVariants |
| 481 |
void MessageFormatter::filterVariants(const UVector& pref, UVector& vars, UErrorCode& status) const { |
| 482 |
const Variant* variants = dataModel.getVariantsInternal(); |
| 483 |
|
| 484 |
// 1. Let `vars` be a new empty list of variants. |
| 485 |
// (Not needed since `vars` is an out-parameter) |
| 486 |
// 2. For each variant `var` of the message: |
| 487 |
for (int32_t j = 0; j < dataModel.numVariants(); j++) { |
| 488 |
const SelectorKeys& selectorKeys = variants[j].getKeys(); |
| 489 |
const Pattern& p = variants[j].getPattern(); |
| 490 |
|
| 491 |
// Note: Here, `var` names the key list of `var`, |
| 492 |
// not a Variant itself |
| 493 |
const Key* var = selectorKeys.getKeysInternal(); |
| 494 |
// 2i. For each index `i` in `pref`: |
| 495 |
bool noMatch = false; |
| 496 |
for (int32_t i = 0; i < pref.size(); i++) { |
| 497 |
// 2i(a). Let `key` be the `var` key at position `i`. |
| 498 |
U_ASSERT(i < selectorKeys.len); |
| 499 |
const Key& key = var[i]; |
| 500 |
// 2i(b). If key is the catch-all key '*': |
| 501 |
if (key.isWildcard()) { |
| 502 |
// 2i(b)(a). Continue the inner loop on pref. |
| 503 |
continue; |
| 504 |
} |
| 505 |
// 2i(c). Assert that `key` is a literal. |
| 506 |
// (Not needed) |
| 507 |
// 2i(d). Let `ks` be the resolved value of `key`. |
| 508 |
UnicodeString ks = normalizeNFC(key.asLiteral().unquoted()); |
| 509 |
// 2i(e). Let `matches` be the list of strings at index `i` of `pref`. |
| 510 |
const UVector& matches = *(static_cast<UVector*>(pref[i])); // `matches` is a vector of strings |
| 511 |
// 2i(f). If `matches` includes `ks` |
| 512 |
if (vectorContains(matches, ks)) { |
| 513 |
// 2i(f)(a). Continue the inner loop on `pref`. |
| 514 |
continue; |
| 515 |
} |
| 516 |
// 2i(g). Else: |
| 517 |
// 2i(g)(a). Continue the outer loop on message variants. |
| 518 |
noMatch = true; |
| 519 |
break; |
| 520 |
} |
| 521 |
if (!noMatch) { |
| 522 |
// Append `var` as the last element of the list `vars`. |
| 523 |
PrioritizedVariant* tuple = create<PrioritizedVariant>(PrioritizedVariant(-1, selectorKeys, p), status); |
| 524 |
CHECK_ERROR(status); |
| 525 |
vars.adoptElement(tuple, status); |
| 526 |
} |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#sort-variants |
| 531 |
// Leaves the preferred variant as element 0 in `sortable` |
| 532 |
// Note: this sorts in-place, so `sortable` is just `vars` |
| 533 |
// `pref` is a vector of vectors of strings; `vars` is a vector of PrioritizedVariants |
| 534 |
void MessageFormatter::sortVariants(const UVector& pref, UVector& vars, UErrorCode& status) const { |
| 535 |
CHECK_ERROR(status); |
| 536 |
|
| 537 |
// Note: steps 1 and 2 are omitted since we use `vars` as `sortable` (we sort in-place) |
| 538 |
// 1. Let `sortable` be a new empty list of (integer, variant) tuples. |
| 539 |
// (Not needed since `sortable` is an out-parameter) |
| 540 |
// 2. For each variant `var` of `vars` |
| 541 |
// 2i. Let tuple be a new tuple (-1, var). |
| 542 |
// 2ii. Append `tuple` as the last element of the list `sortable`. |
| 543 |
|
| 544 |
// 3. Let `len` be the integer count of items in `pref`. |
| 545 |
int32_t len = pref.size(); |
| 546 |
// 4. Let `i` be `len` - 1. |
| 547 |
int32_t i = len - 1; |
| 548 |
// 5. While i >= 0: |
| 549 |
while (i >= 0) { |
| 550 |
// 5i. Let `matches` be the list of strings at index `i` of `pref`. |
| 551 |
U_ASSERT(pref[i] != nullptr); |
| 552 |
const UVector& matches = *(static_cast<UVector*>(pref[i])); // `matches` is a vector of strings |
| 553 |
// 5ii. Let `minpref` be the integer count of items in `matches`. |
| 554 |
int32_t minpref = matches.size(); |
| 555 |
// 5iii. For each tuple `tuple` of `sortable`: |
| 556 |
for (int32_t j = 0; j < vars.size(); j++) { |
| 557 |
U_ASSERT(vars[j] != nullptr); |
| 558 |
PrioritizedVariant& tuple = *(static_cast<PrioritizedVariant*>(vars[j])); |
| 559 |
// 5iii(a). Let matchpref be an integer with the value minpref. |
| 560 |
int32_t matchpref = minpref; |
| 561 |
// 5iii(b). Let `key` be the tuple variant key at position `i`. |
| 562 |
const Key* tupleVariantKeys = tuple.keys.getKeysInternal(); |
| 563 |
U_ASSERT(i < tuple.keys.len); // Given by earlier semantic checking |
| 564 |
const Key& key = tupleVariantKeys[i]; |
| 565 |
// 5iii(c) If `key` is not the catch-all key '*': |
| 566 |
if (!key.isWildcard()) { |
| 567 |
// 5iii(c)(a). Assert that `key` is a literal. |
| 568 |
// (Not needed) |
| 569 |
// 5iii(c)(b). Let `ks` be the resolved value of `key`. |
| 570 |
UnicodeString ks = normalizeNFC(key.asLiteral().unquoted()); |
| 571 |
// 5iii(c)(c) Let matchpref be the integer position of ks in `matches`. |
| 572 |
matchpref = vectorFind(matches, ks); |
| 573 |
U_ASSERT(matchpref >= 0); |
| 574 |
} |
| 575 |
// 5iii(d) Set the `tuple` integer value as matchpref. |
| 576 |
tuple.priority = matchpref; |
| 577 |
} |
| 578 |
// 5iv. Set `sortable` to be the result of calling the method SortVariants(`sortable`) |
| 579 |
vars.sort(comparePrioritizedVariants, status); |
| 580 |
CHECK_ERROR(status); |
| 581 |
// 5v. Set `i` to be `i` - 1. |
| 582 |
i--; |
| 583 |
} |
| 584 |
// The caller is responsible for steps 6 and 7 |
| 585 |
// 6. Let `var` be the `variant` element of the first element of `sortable`. |
| 586 |
// 7. Select the pattern of `var` |
| 587 |
} |
| 588 |
|
| 589 |
void MessageFormatter::formatSelectors(MessageContext& context, const Environment& env, UErrorCode &status, UnicodeString& result) const { |
| 590 |
CHECK_ERROR(status); |
| 591 |
|
| 592 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#pattern-selection |
| 593 |
|
| 594 |
// Resolve Selectors |
| 595 |
// res is a vector of InternalValues |
| 596 |
LocalPointer<UVector> res(createUVector(status)); |
| 597 |
CHECK_ERROR(status); |
| 598 |
resolveSelectors(context, env, status, *res); |
| 599 |
|
| 600 |
// Resolve Preferences |
| 601 |
// pref is a vector of vectors of strings |
| 602 |
LocalPointer<UVector> pref(createUVector(status)); |
| 603 |
CHECK_ERROR(status); |
| 604 |
resolvePreferences(context, *res, *pref, status); |
| 605 |
|
| 606 |
// Filter Variants |
| 607 |
// vars is a vector of PrioritizedVariants |
| 608 |
LocalPointer<UVector> vars(createUVector(status)); |
| 609 |
CHECK_ERROR(status); |
| 610 |
filterVariants(*pref, *vars, status); |
| 611 |
|
| 612 |
// Sort Variants and select the final pattern |
| 613 |
// Note: `sortable` in the spec is just `vars` here, |
| 614 |
// which is sorted in-place |
| 615 |
sortVariants(*pref, *vars, status); |
| 616 |
|
| 617 |
CHECK_ERROR(status); |
| 618 |
|
| 619 |
// 6. Let `var` be the `variant` element of the first element of `sortable`. |
| 620 |
U_ASSERT(vars->size() > 0); // This should have been checked earlier (having 0 variants would be a data model error) |
| 621 |
const PrioritizedVariant& var = *(static_cast<PrioritizedVariant*>(vars->elementAt(0))); |
| 622 |
// 7. Select the pattern of `var` |
| 623 |
const Pattern& pat = var.pat; |
| 624 |
|
| 625 |
// Format the pattern |
| 626 |
formatPattern(context, env, pat, status, result); |
| 627 |
} |
| 628 |
|
| 629 |
// Note: this is non-const due to the function registry being non-const, which is in turn |
| 630 |
// due to the values (`FormatterFactory` objects in the map) having mutable state. |
| 631 |
// In other words, formatting a message can mutate the underlying `MessageFormatter` by changing |
| 632 |
// state within the factory objects that represent custom formatters. |
| 633 |
UnicodeString MessageFormatter::formatToString(const MessageArguments& arguments, UErrorCode &status) { |
| 634 |
EMPTY_ON_ERROR(status); |
| 635 |
|
| 636 |
// Create a new context with the given arguments and the `errors` structure |
| 637 |
MessageContext context(arguments, *errors, status); |
| 638 |
UnicodeString result; |
| 639 |
|
| 640 |
if (!(errors->hasSyntaxError() || errors->hasDataModelError())) { |
| 641 |
// Create a new environment that will store closures for all local variables |
| 642 |
// Check for unresolved variable errors |
| 643 |
// checkDeclarations needs a reference to the pointer to the environment |
| 644 |
// since it uses its `env` argument as an out-parameter. So it needs to be |
| 645 |
// temporarily not a LocalPointer... |
| 646 |
Environment* env(Environment::create(status)); |
| 647 |
checkDeclarations(context, env, status); |
| 648 |
// ...and then it's adopted to avoid leaks |
| 649 |
LocalPointer<Environment> globalEnv(env); |
| 650 |
|
| 651 |
if (dataModel.hasPattern()) { |
| 652 |
formatPattern(context, *globalEnv, dataModel.getPattern(), status, result); |
| 653 |
} else { |
| 654 |
// Check for errors/warnings -- if so, then the result of pattern selection is the fallback value |
| 655 |
// See https://github.com/unicode-org/message-format-wg/blob/main/spec/formatting.md#pattern-selection |
| 656 |
const DynamicErrors& err = context.getErrors(); |
| 657 |
if (err.hasSyntaxError() || err.hasDataModelError()) { |
| 658 |
result += REPLACEMENT; |
| 659 |
} else { |
| 660 |
formatSelectors(context, *globalEnv, status, result); |
| 661 |
} |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
// Update status according to all errors seen while formatting |
| 666 |
if (signalErrors) { |
| 667 |
context.checkErrors(status); |
| 668 |
} |
| 669 |
if (U_FAILURE(status)) { |
| 670 |
result.remove(); |
| 671 |
} |
| 672 |
return result; |
| 673 |
} |
| 674 |
|
| 675 |
// ---------------------------------------- |
| 676 |
// Checking for resolution errors |
| 677 |
|
| 678 |
void MessageFormatter::check(MessageContext& context, const Environment& localEnv, const OptionMap& options, UErrorCode& status) const { |
| 679 |
// Check the RHS of each option |
| 680 |
for (int32_t i = 0; i < options.size(); i++) { |
| 681 |
const Option& opt = options.getOption(i, status); |
| 682 |
CHECK_ERROR(status); |
| 683 |
check(context, localEnv, opt.getValue(), status); |
| 684 |
} |
| 685 |
} |
| 686 |
|
| 687 |
void MessageFormatter::check(MessageContext& context, const Environment& localEnv, const Operand& rand, UErrorCode& status) const { |
| 688 |
// Nothing to check for literals |
| 689 |
if (rand.isLiteral() || rand.isNull()) { |
| 690 |
return; |
| 691 |
} |
| 692 |
|
| 693 |
// Check that variable is in scope |
| 694 |
const VariableName& var = rand.asVariable(); |
| 695 |
UnicodeString normalized = normalizeNFC(var); |
| 696 |
|
| 697 |
// Check local scope |
| 698 |
if (localEnv.has(normalized)) { |
| 699 |
return; |
| 700 |
} |
| 701 |
// Check global scope |
| 702 |
context.getGlobal(*this, normalized, status); |
| 703 |
if (status == U_ILLEGAL_ARGUMENT_ERROR) { |
| 704 |
status = U_ZERO_ERROR; |
| 705 |
context.getErrors().setUnresolvedVariable(var, status); |
| 706 |
} |
| 707 |
// Either `var` is a global, or some other error occurred. |
| 708 |
// Nothing more to do either way |
| 709 |
return; |
| 710 |
} |
| 711 |
|
| 712 |
void MessageFormatter::check(MessageContext& context, const Environment& localEnv, const Expression& expr, UErrorCode& status) const { |
| 713 |
// Check for unresolved variable errors |
| 714 |
if (expr.isFunctionCall()) { |
| 715 |
const Operator* rator = expr.getOperator(status); |
| 716 |
U_ASSERT(U_SUCCESS(status)); |
| 717 |
const Operand& rand = expr.getOperand(); |
| 718 |
check(context, localEnv, rand, status); |
| 719 |
check(context, localEnv, rator->getOptionsInternal(), status); |
| 720 |
} |
| 721 |
} |
| 722 |
|
| 723 |
// Check for resolution errors |
| 724 |
void MessageFormatter::checkDeclarations(MessageContext& context, Environment*& env, UErrorCode &status) const { |
| 725 |
CHECK_ERROR(status); |
| 726 |
|
| 727 |
const Binding* decls = getDataModel().getLocalVariablesInternal(); |
| 728 |
U_ASSERT(env != nullptr && (decls != nullptr || getDataModel().bindingsLen == 0)); |
| 729 |
|
| 730 |
for (int32_t i = 0; i < getDataModel().bindingsLen; i++) { |
| 731 |
const Binding& decl = decls[i]; |
| 732 |
const Expression& rhs = decl.getValue(); |
| 733 |
check(context, *env, rhs, status); |
| 734 |
|
| 735 |
// Add a closure to the global environment, |
| 736 |
// memoizing the value of localEnv up to this point |
| 737 |
|
| 738 |
// Add the LHS to the environment for checking the next declaration |
| 739 |
env = Environment::create(normalizeNFC(decl.getVariable()), |
| 740 |
Closure(rhs, *env), |
| 741 |
env, |
| 742 |
status); |
| 743 |
CHECK_ERROR(status); |
| 744 |
} |
| 745 |
} |
| 746 |
} // namespace message2 |
| 747 |
|
| 748 |
U_NAMESPACE_END |
| 749 |
|
| 750 |
#endif /* #if !UCONFIG_NO_MF2 */ |
| 751 |
|
| 752 |
#endif /* #if !UCONFIG_NO_FORMATTING */ |
| 753 |
|
| 754 |
#endif /* #if !UCONFIG_NO_NORMALIZATION */ |