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