number_patternstring.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // © 2017 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. #include "unicode/utypes.h"
  4. #if !UCONFIG_NO_FORMATTING
  5. #ifndef __NUMBER_PATTERNSTRING_H__
  6. #define __NUMBER_PATTERNSTRING_H__
  7. #include <cstdint>
  8. #include "unicode/unum.h"
  9. #include "unicode/unistr.h"
  10. #include "number_types.h"
  11. #include "number_decimalquantity.h"
  12. #include "number_decimfmtprops.h"
  13. #include "number_affixutils.h"
  14. U_NAMESPACE_BEGIN namespace number {
  15. namespace impl {
  16. // Forward declaration
  17. class PatternParser;
  18. // Note: the order of fields in this enum matters for parsing.
  19. enum PatternSignType {
  20. /** Render using normal positive subpattern rules */
  21. PATTERN_SIGN_TYPE_POS,
  22. /** Render using rules to force the display of a plus sign */
  23. PATTERN_SIGN_TYPE_POS_SIGN,
  24. /** Render using negative subpattern rules */
  25. PATTERN_SIGN_TYPE_NEG,
  26. /** Count for looping over the possibilities */
  27. PATTERN_SIGN_TYPE_COUNT
  28. };
  29. // Exported as U_I18N_API because it is a public member field of exported ParsedSubpatternInfo
  30. struct U_I18N_API Endpoints {
  31. int32_t start = 0;
  32. int32_t end = 0;
  33. };
  34. // Exported as U_I18N_API because it is a public member field of exported ParsedPatternInfo
  35. struct U_I18N_API ParsedSubpatternInfo {
  36. uint64_t groupingSizes = 0x0000ffffffff0000L;
  37. int32_t integerLeadingHashSigns = 0;
  38. int32_t integerTrailingHashSigns = 0;
  39. int32_t integerNumerals = 0;
  40. int32_t integerAtSigns = 0;
  41. int32_t integerTotal = 0; // for convenience
  42. int32_t fractionNumerals = 0;
  43. int32_t fractionHashSigns = 0;
  44. int32_t fractionTotal = 0; // for convenience
  45. bool hasDecimal = false;
  46. int32_t widthExceptAffixes = 0;
  47. // Note: NullableValue causes issues here with std::move.
  48. bool hasPadding = false;
  49. UNumberFormatPadPosition paddingLocation = UNUM_PAD_BEFORE_PREFIX;
  50. DecimalQuantity rounding;
  51. bool exponentHasPlusSign = false;
  52. int32_t exponentZeros = 0;
  53. bool hasPercentSign = false;
  54. bool hasPerMilleSign = false;
  55. bool hasCurrencySign = false;
  56. bool hasMinusSign = false;
  57. bool hasPlusSign = false;
  58. Endpoints prefixEndpoints;
  59. Endpoints suffixEndpoints;
  60. Endpoints paddingEndpoints;
  61. };
  62. // Exported as U_I18N_API because it is needed for the unit test PatternStringTest
  63. struct U_I18N_API ParsedPatternInfo : public AffixPatternProvider, public UMemory {
  64. UnicodeString pattern;
  65. ParsedSubpatternInfo positive;
  66. ParsedSubpatternInfo negative;
  67. ParsedPatternInfo()
  68. : state(this->pattern), currentSubpattern(nullptr) {}
  69. ~ParsedPatternInfo() U_OVERRIDE = default;
  70. // Need to declare this explicitly because of the destructor
  71. ParsedPatternInfo& operator=(ParsedPatternInfo&& src) U_NOEXCEPT = default;
  72. static int32_t getLengthFromEndpoints(const Endpoints& endpoints);
  73. char16_t charAt(int32_t flags, int32_t index) const U_OVERRIDE;
  74. int32_t length(int32_t flags) const U_OVERRIDE;
  75. UnicodeString getString(int32_t flags) const U_OVERRIDE;
  76. bool positiveHasPlusSign() const U_OVERRIDE;
  77. bool hasNegativeSubpattern() const U_OVERRIDE;
  78. bool negativeHasMinusSign() const U_OVERRIDE;
  79. bool hasCurrencySign() const U_OVERRIDE;
  80. bool containsSymbolType(AffixPatternType type, UErrorCode& status) const U_OVERRIDE;
  81. bool hasBody() const U_OVERRIDE;
  82. private:
  83. struct U_I18N_API ParserState {
  84. const UnicodeString& pattern; // reference to the parent
  85. int32_t offset = 0;
  86. explicit ParserState(const UnicodeString& _pattern)
  87. : pattern(_pattern) {}
  88. ParserState& operator=(ParserState&& src) U_NOEXCEPT {
  89. // Leave pattern reference alone; it will continue to point to the same place in memory,
  90. // which gets overwritten by ParsedPatternInfo's implicit move assignment.
  91. offset = src.offset;
  92. return *this;
  93. }
  94. UChar32 peek();
  95. UChar32 next();
  96. // TODO: We don't currently do anything with the message string.
  97. // This method is here as a shell for Java compatibility.
  98. inline void toParseException(const char16_t* message) { (void) message; }
  99. } state;
  100. // NOTE: In Java, these are written as pure functions.
  101. // In C++, they're written as methods.
  102. // The behavior is the same.
  103. // Mutable transient pointer:
  104. ParsedSubpatternInfo* currentSubpattern;
  105. // In Java, "negative == null" tells us whether or not we had a negative subpattern.
  106. // In C++, we need to remember in another boolean.
  107. bool fHasNegativeSubpattern = false;
  108. const Endpoints& getEndpoints(int32_t flags) const;
  109. /** Run the recursive descent parser. */
  110. void consumePattern(const UnicodeString& patternString, UErrorCode& status);
  111. void consumeSubpattern(UErrorCode& status);
  112. void consumePadding(PadPosition paddingLocation, UErrorCode& status);
  113. void consumeAffix(Endpoints& endpoints, UErrorCode& status);
  114. void consumeLiteral(UErrorCode& status);
  115. void consumeFormat(UErrorCode& status);
  116. void consumeIntegerFormat(UErrorCode& status);
  117. void consumeFractionFormat(UErrorCode& status);
  118. void consumeExponent(UErrorCode& status);
  119. friend class PatternParser;
  120. };
  121. enum IgnoreRounding {
  122. IGNORE_ROUNDING_NEVER = 0, IGNORE_ROUNDING_IF_CURRENCY = 1, IGNORE_ROUNDING_ALWAYS = 2
  123. };
  124. class U_I18N_API PatternParser {
  125. public:
  126. /**
  127. * Runs the recursive descent parser on the given pattern string, returning a data structure with raw information
  128. * about the pattern string.
  129. *
  130. * <p>
  131. * To obtain a more useful form of the data, consider using {@link #parseToProperties} instead.
  132. *
  133. * TODO: Change argument type to const char16_t* instead of UnicodeString?
  134. *
  135. * @param patternString
  136. * The LDML decimal format pattern (Excel-style pattern) to parse.
  137. * @return The results of the parse.
  138. */
  139. static void parseToPatternInfo(const UnicodeString& patternString, ParsedPatternInfo& patternInfo,
  140. UErrorCode& status);
  141. /**
  142. * Parses a pattern string into a new property bag.
  143. *
  144. * @param pattern
  145. * The pattern string, like "#,##0.00"
  146. * @param ignoreRounding
  147. * Whether to leave out rounding information (minFrac, maxFrac, and rounding increment) when parsing the
  148. * pattern. This may be desirable if a custom rounding mode, such as CurrencyUsage, is to be used
  149. * instead.
  150. * @return A property bag object.
  151. * @throws IllegalArgumentException
  152. * If there is a syntax error in the pattern string.
  153. */
  154. static DecimalFormatProperties parseToProperties(const UnicodeString& pattern,
  155. IgnoreRounding ignoreRounding, UErrorCode& status);
  156. static DecimalFormatProperties parseToProperties(const UnicodeString& pattern, UErrorCode& status);
  157. /**
  158. * Parses a pattern string into an existing property bag. All properties that can be encoded into a pattern string
  159. * will be overwritten with either their default value or with the value coming from the pattern string. Properties
  160. * that cannot be encoded into a pattern string, such as rounding mode, are not modified.
  161. *
  162. * @param pattern
  163. * The pattern string, like "#,##0.00"
  164. * @param properties
  165. * The property bag object to overwrite.
  166. * @param ignoreRounding
  167. * See {@link #parseToProperties(String pattern, int ignoreRounding)}.
  168. * @throws IllegalArgumentException
  169. * If there was a syntax error in the pattern string.
  170. */
  171. static void parseToExistingProperties(const UnicodeString& pattern,
  172. DecimalFormatProperties& properties,
  173. IgnoreRounding ignoreRounding, UErrorCode& status);
  174. private:
  175. static void parseToExistingPropertiesImpl(const UnicodeString& pattern,
  176. DecimalFormatProperties& properties,
  177. IgnoreRounding ignoreRounding, UErrorCode& status);
  178. /** Finalizes the temporary data stored in the ParsedPatternInfo to the Properties. */
  179. static void patternInfoToProperties(DecimalFormatProperties& properties,
  180. ParsedPatternInfo& patternInfo, IgnoreRounding _ignoreRounding,
  181. UErrorCode& status);
  182. };
  183. class U_I18N_API PatternStringUtils {
  184. public:
  185. /**
  186. * Determine whether a given roundingIncrement should be ignored for formatting
  187. * based on the current maxFrac value (maximum fraction digits). For example a
  188. * roundingIncrement of 0.01 should be ignored if maxFrac is 1, but not if maxFrac
  189. * is 2 or more. Note that roundingIncrements are rounded up in significance, so
  190. * a roundingIncrement of 0.006 is treated like 0.01 for this determination, i.e.
  191. * it should not be ignored if maxFrac is 2 or more (but a roundingIncrement of
  192. * 0.005 is treated like 0.001 for significance).
  193. *
  194. * This test is needed for both NumberPropertyMapper::oldToNew and
  195. * PatternStringUtils::propertiesToPatternString. In Java it cannot be
  196. * exported by NumberPropertyMapper (package provate) so it is in
  197. * PatternStringUtils, do the same in C.
  198. *
  199. * @param roundIncr
  200. * The roundingIncrement to be checked. Must be non-zero.
  201. * @param maxFrac
  202. * The current maximum fraction digits value.
  203. * @return true if roundIncr should be ignored for formatting.
  204. */
  205. static bool ignoreRoundingIncrement(double roundIncr, int32_t maxFrac);
  206. /**
  207. * Creates a pattern string from a property bag.
  208. *
  209. * <p>
  210. * Since pattern strings support only a subset of the functionality available in a property bag, a new property bag
  211. * created from the string returned by this function may not be the same as the original property bag.
  212. *
  213. * @param properties
  214. * The property bag to serialize.
  215. * @return A pattern string approximately serializing the property bag.
  216. */
  217. static UnicodeString propertiesToPatternString(const DecimalFormatProperties& properties,
  218. UErrorCode& status);
  219. /**
  220. * Converts a pattern between standard notation and localized notation. Localized notation means that instead of
  221. * using generic placeholders in the pattern, you use the corresponding locale-specific characters instead. For
  222. * example, in locale <em>fr-FR</em>, the period in the pattern "0.000" means "decimal" in standard notation (as it
  223. * does in every other locale), but it means "grouping" in localized notation.
  224. *
  225. * <p>
  226. * A greedy string-substitution strategy is used to substitute locale symbols. If two symbols are ambiguous or have
  227. * the same prefix, the result is not well-defined.
  228. *
  229. * <p>
  230. * Locale symbols are not allowed to contain the ASCII quote character.
  231. *
  232. * <p>
  233. * This method is provided for backwards compatibility and should not be used in any new code.
  234. *
  235. * TODO(C++): This method is not yet implemented.
  236. *
  237. * @param input
  238. * The pattern to convert.
  239. * @param symbols
  240. * The symbols corresponding to the localized pattern.
  241. * @param toLocalized
  242. * true to convert from standard to localized notation; false to convert from localized to standard
  243. * notation.
  244. * @return The pattern expressed in the other notation.
  245. */
  246. static UnicodeString convertLocalized(const UnicodeString& input, const DecimalFormatSymbols& symbols,
  247. bool toLocalized, UErrorCode& status);
  248. /**
  249. * This method contains the heart of the logic for rendering LDML affix strings. It handles
  250. * sign-always-shown resolution, whether to use the positive or negative subpattern, permille
  251. * substitution, and plural forms for CurrencyPluralInfo.
  252. */
  253. static void patternInfoToStringBuilder(const AffixPatternProvider& patternInfo, bool isPrefix,
  254. PatternSignType patternSignType,
  255. StandardPlural::Form plural, bool perMilleReplacesPercent,
  256. UnicodeString& output);
  257. static PatternSignType resolveSignDisplay(UNumberSignDisplay signDisplay, Signum signum);
  258. private:
  259. /** @return The number of chars inserted. */
  260. static int escapePaddingString(UnicodeString input, UnicodeString& output, int startIndex,
  261. UErrorCode& status);
  262. };
  263. } // namespace impl
  264. } // namespace number
  265. U_NAMESPACE_END
  266. #endif //__NUMBER_PATTERNSTRING_H__
  267. #endif /* #if !UCONFIG_NO_FORMATTING */