ICU4C 79
Loading...
Searching...
No Matches
messageformat2.h
Go to the documentation of this file.
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#ifndef MESSAGEFORMAT2_H
7#define MESSAGEFORMAT2_H
8
9#if U_SHOW_CPLUSPLUS_API
10
11#if !UCONFIG_NO_NORMALIZATION
12
13#if !UCONFIG_NO_FORMATTING
14
15#if !UCONFIG_NO_MF2
16
21
23#include "unicode/messageformat2_data_model.h"
24#include "unicode/messageformat2_function_registry.h"
25#include "unicode/normalizer2.h"
26#include "unicode/unistr.h"
27
28#ifndef U_HIDE_DEPRECATED_API
29
30U_NAMESPACE_BEGIN
31
32namespace message2 {
33
34 class Environment;
35 class MessageContext;
36 class StaticErrors;
37 class InternalValue;
38 class BaseValue;
39
55 class U_I18N_API_CLASS MessageFormatter : public UObject {
56 // Note: This class does not currently inherit from the existing
57 // `Format` class.
58 public:
66 U_I18N_API MessageFormatter& operator=(MessageFormatter&&) noexcept;
73 U_I18N_API virtual ~MessageFormatter();
74
94 U_I18N_API UnicodeString formatToString(const MessageArguments& arguments, UErrorCode& status);
95
111 U_I18N_API FormattedMessage format(const MessageArguments& arguments, UErrorCode& status) const {
112 (void) arguments;
113 if (U_SUCCESS(status)) {
114 status = U_UNSUPPORTED_ERROR;
115 }
116 return FormattedMessage(status);
117 }
118
127 U_I18N_API const Locale& getLocale() const { return locale; }
128
139
150
174 } UMFErrorHandlingBehavior;
175
215 private:
216 friend class MessageFormatter;
217
218 // The pattern to be parsed to generate the formatted message
219 UnicodeString pattern;
220 bool hasPattern = false;
221 bool hasDataModel = false;
222 // The data model to be used to generate the formatted message
223 // Initialized either by `setDataModel()`, or by the parser
224 // through a call to `setPattern()`
225 MFDataModel dataModel;
226 // Normalized representation of the pattern;
227 // ignored if `setPattern()` wasn't called
228 UnicodeString normalizedInput;
229 // Errors (internal representation of parse errors)
230 // Ignored if `setPattern()` wasn't called
231 StaticErrors* errors;
232 Locale locale;
233 // Not owned
234 const MFFunctionRegistry* customMFFunctionRegistry;
235 // Error behavior; see comment in `MessageFormatter` class
236 bool signalErrors = false;
237 // Bidi isolation strategy
238 UMFBidiIsolationStrategy bidiIsolationStrategy = U_MF_BIDI_DEFAULT;
239 // Message directionality
240 MessageFormatter::UMFBidiContext msgdir = U_MF_BIDI_CONTEXT_DEFAULT;
241 // Bidi isolation style
242 UMFBidiIsolationStyle bidiStyle = U_MF_BIDI_STYLE_DEFAULT;
243
244 void clearState();
245 public:
272 UParseError& parseError,
273 UErrorCode& status);
400 U_I18N_API MessageFormatter build(UErrorCode& status) const;
420 }; // class MessageFormatter::Builder
421
429 U_I18N_API const UnicodeString& getNormalizedPattern() const { return normalizedInput; }
430
431 private:
432 friend class Builder;
433 friend class Checker;
434 friend class MessageArguments;
435 friend class MessageContext;
436
438
439 MessageFormatter() = delete; // default constructor not implemented
440
441 // Do not define default assignment operator
442 const MessageFormatter &operator=(const MessageFormatter &) = delete;
443
444 // Selection methods
445
446 // Takes a vector of FormattedPlaceholders
447 void resolveSelectors(MessageContext&, Environment& env, UErrorCode&, UVector&) const;
448 // Takes a vector of vectors of strings (input) and a vector of PrioritizedVariants (output)
449 void filterVariants(const UVector&, UVector&, UErrorCode&) const;
450 // Takes a vector of vectors of strings (input) and a vector of PrioritizedVariants (input/output)
451 void sortVariants(const UVector&, UVector&, UErrorCode&) const;
452 // Takes a vector of strings (input) and a vector of strings (output)
453 void matchSelectorKeys(const UVector&, MessageContext&, InternalValue&& rv, UVector&, UErrorCode&) const;
454 // Takes a vector of FormattedPlaceholders (input),
455 // and a vector of vectors of strings (output)
456 void resolvePreferences(MessageContext&, UVector&, UVector&, UErrorCode&) const;
457
458 bool checkSelectOption(const FunctionValue&) const;
459
460 // Formatting methods
461 [[nodiscard]] InternalValue evalLiteral(const UnicodeString&, const data_model::Literal&, UErrorCode&) const;
462 [[nodiscard]] UnicodeString& bidiIsolate(UMFBidiOption, UMFDirectionality, UnicodeString&) const;
463 void formatPattern(MessageContext&, Environment&, const data_model::Pattern&, UErrorCode&, UnicodeString&) const;
464 FunctionContext makeFunctionContext(const FunctionOptions&, const FunctionName&) const;
465 [[nodiscard]] InternalValue& apply(Environment&, const FunctionName&, InternalValue&, FunctionOptions&&,
466 MessageContext&, UErrorCode&) const;
467 [[nodiscard]] InternalValue& evalExpression(const UnicodeString&, Environment&, const data_model::Expression&, MessageContext&, UErrorCode&) const;
468 [[nodiscard]] FunctionOptions resolveOptions(Environment& env, const OptionMap&, MessageContext&, UErrorCode&) const;
469 [[nodiscard]] InternalValue& evalOperand(const UnicodeString&, Environment&, const data_model::Operand&, MessageContext&, UErrorCode&) const;
470 bool operandToStringWithBadOptionError(MessageContext&, Environment&, const Operand&, UnicodeString&, UErrorCode&) const;
471 void validateUOptionsOnMarkup(MessageContext&, Environment&, const Markup&, UErrorCode&) const;
472 [[nodiscard]] InternalValue& evalVariableReference(const UnicodeString&, Environment&, const data_model::VariableName&, MessageContext&, UErrorCode&) const;
473 [[nodiscard]] InternalValue evalArgument(const UnicodeString&, const data_model::VariableName&, MessageContext&, UErrorCode&) const;
474 void formatSelectors(MessageContext& context, Environment& env, UErrorCode &status, UnicodeString& result) const;
475
476 // Function registry methods
477 bool hasCustomMFFunctionRegistry() const {
478 return (customMFFunctionRegistry != nullptr);
479 }
480
481 // Precondition: custom function registry exists
482 // Note: this is non-const because the values in the MFFunctionRegistry are mutable
483 // (a FormatterFactory can have mutable state)
484 const MFFunctionRegistry& getCustomMFFunctionRegistry() const;
485
486 bool isCustomFunction(const FunctionName&) const;
487 bool isBuiltInFunction(const FunctionName&) const;
488 bool isFunction(const FunctionName& fn) const { return isBuiltInFunction(fn) || isCustomFunction(fn); }
489 void setNotSelectableError(MessageContext&, const InternalValue&, UErrorCode&) const;
490 const Function* lookupFunction(const FunctionName&, UErrorCode&) const;
491 bool getDefaultFormatterNameByType(const UnicodeString&, FunctionName&) const;
492
493 // Checking for resolution errors
494 void checkDeclarations(MessageContext&, Environment*&, UErrorCode&) const;
495 void check(MessageContext&, const Environment&, const data_model::Expression&, UErrorCode&) const;
496 void check(MessageContext&, const Environment&, const data_model::Operand&, UErrorCode&) const;
497 void check(MessageContext&, const Environment&, const OptionMap&, UErrorCode&) const;
498
499 void initErrors(UErrorCode&);
500 void clearErrors() const;
501 void cleanup() noexcept;
502
503 // The locale this MessageFormatter was created with
504 /* const */ Locale locale;
505
506 // Registry for built-in functions
507 const MFFunctionRegistry *standardMFFunctionRegistry;
508 // Registry for custom functions; may be null if no custom registry supplied
509 // Note: this is *not* owned by the MessageFormatter object
510 // The reason for this choice is to have a non-destructive MessageFormatter::Builder,
511 // while also not requiring the function registry to be deeply-copyable. Making the
512 // function registry copyable would impose a requirement on any implementations
513 // of the FormatterFactory and SelectorFactory interfaces to implement a custom
514 // clone() method, which is necessary to avoid sharing between copies of the
515 // function registry (and thus double-frees)
516 // Not deeply immutable (the values in the function registry are mutable,
517 // as a FormatterFactory can have mutable state
518 const MFFunctionRegistry* customMFFunctionRegistry;
519
520 // Data model, representing the parsed message
521 MFDataModel dataModel;
522
523 // Normalized version of the input string (optional whitespace removed)
524 UnicodeString normalizedInput;
525
526 // Errors -- only used while parsing and checking for data model errors; then
527 // the MessageContext keeps track of errors
528 // Must be a raw pointer to avoid including the internal header file
529 // defining StaticErrors
530 // Owned by `this`
531 StaticErrors* errors = nullptr;
532
533 // Error handling behavior.
534 // If true, then formatting methods set their UErrorCode arguments
535 // to signal MessageFormat errors, and no useful output is returned.
536 // If false, then MessageFormat errors are not signaled and the
537 // formatting methods return best-effort output.
538 // The default is false.
539 bool signalErrors = false;
540
541 // Bidi isolation strategy.
542 UMFBidiIsolationStrategy bidiIsolationStrategy = U_MF_BIDI_DEFAULT;
543
544 // Message directionality
545 // Inferred from locale by default
546 UMFDirectionality msgdir = U_MF_DIRECTIONALITY_DEFAULT;
547
548 // Bidi isolation style
549 UMFBidiIsolationStyle bidiIsolationStyle = U_MF_BIDI_STYLE_DEFAULT;
550
551 }; // class MessageFormatter
552
553} // namespace message2
554
555U_NAMESPACE_END
556
557#endif // U_HIDE_DEPRECATED_API
558
559#endif /* #if !UCONFIG_NO_MF2 */
560
561#endif /* #if !UCONFIG_NO_FORMATTING */
562
563#endif /* #if !UCONFIG_NO_NORMALIZATION */
564
565#endif /* U_SHOW_CPLUSPLUS_API */
566
567#endif // MESSAGEFORMAT2_H
568
569// eof
A Locale object represents a specific geographical, political, or cultural region.
Definition locid.h:198
UObject is the common ICU "boilerplate" class.
Definition uobject.h:222
UnicodeString is a string class that stores Unicode characters directly and provides similar function...
Definition unistr.h:303
Not yet implemented: The result of a message formatting operation.
Class implementing data from contextual options.
Structure encapsulating named options passed to a custom selector or formatter.
Type representing argument and return values for custom functions.
Defines mappings from names of formatters and selectors to functions implementing them.
The MessageArguments class represents the named arguments to a message.
The mutable Builder class allows each part of the MessageFormatter to be initialized separately; call...
U_I18N_API Builder & setErrorHandlingBehavior(UMFErrorHandlingBehavior type)
Set the error handling behavior for this formatter.
U_I18N_API Builder & setPattern(const UnicodeString &pattern, UParseError &parseError, UErrorCode &status)
Sets the pattern (contents of the message) and parses it into a data model.
U_I18N_API Builder & setBidiIsolationStrategy(UMFBidiIsolationStrategy strategy)
Set the bidi isolation behavior for this formatter.
U_I18N_API Builder & setDataModel(MFDataModel &&dataModel)
Sets a data model.
U_I18N_API Builder & setLocale(const Locale &locale)
Sets the locale to use for formatting.
U_I18N_API Builder & setFunctionRegistry(const MFFunctionRegistry &functionRegistry)
Sets a custom function registry.
U_I18N_API Builder & setBidiContext(UMFBidiContext dir)
Set the directionality context of the input message.
virtual U_I18N_API ~Builder()
Destructor.
U_I18N_API Builder(UErrorCode &status)
Default constructor.
U_I18N_API Builder & setBidiIsolationStyle(UMFBidiIsolationStyle style)
Set the bidi isolation style for this formatter.
U_I18N_API MessageFormatter build(UErrorCode &status) const
Constructs a new immutable MessageFormatter using the pattern or data model that was previously set,...
U_I18N_API UnicodeString formatToString(const MessageArguments &arguments, UErrorCode &status)
Formats the message to a string, using the data model that was previously set or parsed,...
U_I18N_API FormattedMessage format(const MessageArguments &arguments, UErrorCode &status) const
Not yet implemented; formats the message to a FormattedMessage object, using the data model that was ...
U_I18N_API const UnicodeString & getNormalizedPattern() const
Returns a string consisting of the input with optional spaces removed.
U_I18N_API const Locale & getLocale() const
Accesses the locale that this MessageFormatter object was created with.
U_I18N_API const MFDataModel & getDataModel() const
Accesses the data model referred to by this MessageFormatter object.
U_I18N_API UnicodeString getPattern() const
Serializes the data model as a string in MessageFormat 2.0 syntax.
UMFErrorHandlingBehavior
Used in conjunction with the MessageFormatter::Builder::setErrorHandlingBehavior() method.
@ U_MF_BEST_EFFORT
Suppress errors and return best-effort output.
@ U_MF_STRICT
Signal all MessageFormat errors using the UErrorCode argument.
UMFBidiContext
Used in conjunction with the MessageFormatter::Builder::setBidiContext() method.
@ U_MF_BIDI_CONTEXT_RTL
Denotes a right-to-left message.
@ U_MF_BIDI_CONTEXT_AUTO
Indicates that the message directionality should be inferred from the locale.
@ U_MF_BIDI_CONTEXT_LTR
Denotes a left-to-right message.
U_I18N_API MessageFormatter & operator=(MessageFormatter &&) noexcept
Move assignment operator: The source MessageFormatter will be left in a valid but undefined state.
The Expression class corresponds to the expression nonterminal in the MessageFormat 2 grammar and the...
The Literal class corresponds to the literal nonterminal in the MessageFormat 2 grammar,...
The MFDataModel class describes a parsed representation of the text of a message.
The Markup class corresponds to the markup nonterminal in the MessageFormat 2 grammar and the markup ...
The Operand class corresponds to the operand nonterminal in the MessageFormat 2 grammar,...
A Pattern is a sequence of formattable parts.
C++ API: Formats messages using the draft MessageFormat 2.0.
UMFBidiIsolationStrategy
Used in conjunction with the MessageFormatter::Builder::setBidiIsolationStrategy() method.
Definition ubidi.h:2298
UMFBidiIsolationStyle
Used in conjunction with the MessageFormatter::Builder::setBidiIsolationStyle() method.
Definition ubidi.h:2325
UMFBidiOption
Used to denote the directionality of the input to a function.
Definition ubidi.h:2226
UMFDirectionality
Used to represent the directionality of a message, where the AUTO setting has been resolved based on ...
Definition ubidi.h:2266
C++ API: New API for Unicode Normalization.
A UParseError struct is used to returned detailed information about parsing errors.
Definition parseerr.h:58
C++ API: Unicode String.
Basic definitions for ICU, for both C and C++ APIs.
UErrorCode
Standard ICU4C error code type, a substitute for exceptions.
Definition utypes.h:509
@ U_UNSUPPORTED_ERROR
Requested operation not supported in current context.
Definition utypes.h:561
#define U_SUCCESS(x)
Does the error code indicate success?
Definition utypes.h:822
#define U_I18N_API_CLASS
Set to export library symbols from inside the i18n library, and to import them from outside,...
Definition utypes.h:457
#define U_I18N_API
Set to export library symbols from inside the i18n library, and to import them from outside.
Definition utypes.h:316