1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 * Copyright (C) 1997-2015, International Business Machines Corporation and others.
6 * All Rights Reserved.
7 *******************************************************************************
8 */
9
10 #ifndef RBNF_H
11 #define RBNF_H
12
13 #include "unicode/utypes.h"
14
15 #if U_SHOW_CPLUSPLUS_API
16
17 /**
18 * \file
19 * \brief C++ API: Rule Based Number Format
20 */
21
22 /**
23 * \def U_HAVE_RBNF
24 * This will be 0 if RBNF support is not included in ICU
25 * and 1 if it is.
26 *
27 * @stable ICU 2.4
28 */
29 #if UCONFIG_NO_FORMATTING
30 #define U_HAVE_RBNF 0
31 #else
32 #define U_HAVE_RBNF 1
33
34 #include "unicode/dcfmtsym.h"
35 #include "unicode/fmtable.h"
36 #include "unicode/locid.h"
37 #include "unicode/numfmt.h"
38 #include "unicode/unistr.h"
39 #include "unicode/strenum.h"
40 #include "unicode/brkiter.h"
41 #include "unicode/upluralrules.h"
42
43 U_NAMESPACE_BEGIN
44
45 class NFRule;
46 class NFRuleSet;
47 class LocalizationInfo;
48 class PluralFormat;
49 class RuleBasedCollator;
50
51 /**
52 * Tags for the predefined rulesets.
53 *
54 * @stable ICU 2.2
55 */
56 enum URBNFRuleSetTag {
57 /**
58 * Requests predefined ruleset for spelling out numeric values in words.
59 * @stable ICU 2.2
60 */
61 URBNF_SPELLOUT,
62 /**
63 * Requests predefined ruleset for the ordinal form of a number.
64 * @stable ICU 2.2
65 */
66 URBNF_ORDINAL,
67 /**
68 * Requests predefined ruleset for formatting a value as a duration in hours, minutes, and seconds.
69 * @stable ICU 2.2
70 */
71 URBNF_DURATION,
72 /**
73 * Requests predefined ruleset for various non-place-value numbering systems.
74 * WARNING: The same resource contains rule sets for a variety of different numbering systems.
75 * You need to call setDefaultRuleSet() on the formatter to choose the actual numbering system.
76 * @stable ICU 2.2
77 */
78 URBNF_NUMBERING_SYSTEM,
79 #ifndef U_HIDE_DEPRECATED_API
80 /**
81 * One more than the highest normal URBNFRuleSetTag value.
82 * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420.
83 */
84 URBNF_COUNT
85 #endif // U_HIDE_DEPRECATED_API
86 };
87
88 /**
89 * The RuleBasedNumberFormat class formats numbers according to a set of rules. This number formatter is
90 * typically used for spelling out numeric values in words (e.g., 25,3476 as
91 * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois
92 * cents soixante-seize" or
93 * "fünfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for
94 * other complicated formatting tasks, such as formatting a number of seconds as hours,
95 * minutes and seconds (e.g., 3,730 as "1:02:10").
96 *
97 * <p>The resources contain three predefined formatters for each locale: spellout, which
98 * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which
99 * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and
100 * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is
101 * "2:03"). The client can also define more specialized <tt>RuleBasedNumberFormat</tt>s
102 * by supplying programmer-defined rule sets.</p>
103 *
104 * <p>The behavior of a <tt>RuleBasedNumberFormat</tt> is specified by a textual description
105 * that is either passed to the constructor as a <tt>String</tt> or loaded from a resource
106 * bundle. In its simplest form, the description consists of a semicolon-delimited list of <em>rules.</em>
107 * Each rule has a string of output text and a value or range of values it is applicable to.
108 * In a typical spellout rule set, the first twenty rules are the words for the numbers from
109 * 0 to 19:</p>
110 *
111 * <pre>zero; one; two; three; four; five; six; seven; eight; nine;
112 * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;</pre>
113 *
114 * <p>For larger numbers, we can use the preceding set of rules to format the ones place, and
115 * we only have to supply the words for the multiples of 10:</p>
116 *
117 * <pre> 20: twenty[->>];
118 * 30: thirty[->>];
119 * 40: forty[->>];
120 * 50: fifty[->>];
121 * 60: sixty[->>];
122 * 70: seventy[->>];
123 * 80: eighty[->>];
124 * 90: ninety[->>];</pre>
125 *
126 * <p>In these rules, the <em>base value</em> is spelled out explicitly and set off from the
127 * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable
128 * to all numbers from its own base value to one less than the next rule's base value. The
129 * ">>" token is called a <em>substitution</em> and tells the formatter to
130 * isolate the number's ones digit, format it using this same set of rules, and place the
131 * result at the position of the ">>" token. Text in brackets is omitted if
132 * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24
133 * is "twenty-four," not "twenty four").</p>
134 *
135 * <p>For even larger numbers, we can actually look up several parts of the number in the
136 * list:</p>
137 *
138 * <pre>100: << hundred[ >>];</pre>
139 *
140 * <p>The "<<" represents a new kind of substitution. The << isolates
141 * the hundreds digit (and any digits to its left), formats it using this same rule set, and
142 * places the result where the "<<" was. Notice also that the meaning of
143 * >> has changed: it now refers to both the tens and the ones digits. The meaning of
144 * both substitutions depends on the rule's base value. The base value determines the rule's <em>divisor,</em>
145 * which is the highest power of 10 that is less than or equal to the base value (the user
146 * can change this). To fill in the substitutions, the formatter divides the number being
147 * formatted by the divisor. The integral quotient is used to fill in the <<
148 * substitution, and the remainder is used to fill in the >> substitution. The meaning
149 * of the brackets changes similarly: text in brackets is omitted if the value being
150 * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so
151 * if a substitution is filled in with text that includes another substitution, that
152 * substitution is also filled in.</p>
153 *
154 * <p>This rule covers values up to 999, at which point we add another rule:</p>
155 *
156 * <pre>1000: << thousand[ >>];</pre>
157 *
158 * <p>Again, the meanings of the brackets and substitution tokens shift because the rule's
159 * base value is a higher power of 10, changing the rule's divisor. This rule can actually be
160 * used all the way up to 999,999. This allows us to finish out the rules as follows:</p>
161 *
162 * <pre> 1,000,000: << million[ >>];
163 * 1,000,000,000: << billion[ >>];
164 * 1,000,000,000,000: << trillion[ >>];
165 * 1,000,000,000,000,000: OUT OF RANGE!;</pre>
166 *
167 * <p>Commas, periods, and spaces can be used in the base values to improve legibility and
168 * are ignored by the rule parser. The last rule in the list is customarily treated as an
169 * "overflow rule," applying to everything from its base value on up, and often (as
170 * in this example) being used to print out an error message or default representation.
171 * Notice also that the size of the major groupings in large numbers is controlled by the
172 * spacing of the rules: because in English we group numbers by thousand, the higher rules
173 * are separated from each other by a factor of 1,000.</p>
174 *
175 * <p>To see how these rules actually work in practice, consider the following example:
176 * Formatting 25,430 with this rule set would work like this:</p>
177 *
178 * <table border="0" width="100%">
179 * <tr>
180 * <td><strong><< thousand >></strong></td>
181 * <td>[the rule whose base value is 1,000 is applicable to 25,340]</td>
182 * </tr>
183 * <tr>
184 * <td><strong>twenty->></strong> thousand >></td>
185 * <td>[25,340 over 1,000 is 25. The rule for 20 applies.]</td>
186 * </tr>
187 * <tr>
188 * <td>twenty-<strong>five</strong> thousand >></td>
189 * <td>[25 mod 10 is 5. The rule for 5 is "five."</td>
190 * </tr>
191 * <tr>
192 * <td>twenty-five thousand <strong><< hundred >></strong></td>
193 * <td>[25,340 mod 1,000 is 340. The rule for 100 applies.]</td>
194 * </tr>
195 * <tr>
196 * <td>twenty-five thousand <strong>three</strong> hundred >></td>
197 * <td>[340 over 100 is 3. The rule for 3 is "three."]</td>
198 * </tr>
199 * <tr>
200 * <td>twenty-five thousand three hundred <strong>forty</strong></td>
201 * <td>[340 mod 100 is 40. The rule for 40 applies. Since 40 divides
202 * evenly by 10, the hyphen and substitution in the brackets are omitted.]</td>
203 * </tr>
204 * </table>
205 *
206 * <p>The above syntax suffices only to format positive integers. To format negative numbers,
207 * we add a special rule:</p>
208 *
209 * <pre>-x: minus >>;</pre>
210 *
211 * <p>This is called a <em>negative-number rule,</em> and is identified by "-x"
212 * where the base value would be. This rule is used to format all negative numbers. the
213 * >> token here means "find the number's absolute value, format it with these
214 * rules, and put the result here."</p>
215 *
216 * <p>We also add a special rule called a <em>fraction rule </em>for numbers with fractional
217 * parts:</p>
218 *
219 * <pre>x.x: << point >>;</pre>
220 *
221 * <p>This rule is used for all positive non-integers (negative non-integers pass through the
222 * negative-number rule first and then through this rule). Here, the << token refers to
223 * the number's integral part, and the >> to the number's fractional part. The
224 * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be
225 * formatted as "one hundred twenty-three point four five six").</p>
226 *
227 * <p>To see how this rule syntax is applied to various languages, examine the resource data.</p>
228 *
229 * <p>There is actually much more flexibility built into the rule language than the
230 * description above shows. A formatter may own multiple rule sets, which can be selected by
231 * the caller, and which can use each other to fill in their substitutions. Substitutions can
232 * also be filled in with digits, using a DecimalFormat object. There is syntax that can be
233 * used to alter a rule's divisor in various ways. And there is provision for much more
234 * flexible fraction handling. A complete description of the rule syntax follows:</p>
235 *
236 * <hr>
237 *
238 * <p>The description of a <tt>RuleBasedNumberFormat</tt>'s behavior consists of one or more <em>rule
239 * sets.</em> Each rule set consists of a name, a colon, and a list of <em>rules.</em> A rule
240 * set name must begin with a % sign. Rule sets with names that begin with a single % sign
241 * are <em>public:</em> the caller can specify that they be used to format and parse numbers.
242 * Rule sets with names that begin with %% are <em>private:</em> they exist only for the use
243 * of other rule sets. If a formatter only has one rule set, the name may be omitted.</p>
244 *
245 * <p>The user can also specify a special "rule set" named <tt>%%lenient-parse</tt>.
246 * The body of <tt>%%lenient-parse</tt> isn't a set of number-formatting rules, but a <tt>RuleBasedCollator</tt>
247 * description which is used to define equivalences for lenient parsing. For more information
248 * on the syntax, see <tt>RuleBasedCollator</tt>. For more information on lenient parsing,
249 * see <tt>setLenientParse()</tt>. <em>Note:</em> symbols that have syntactic meaning
250 * in collation rules, such as '&', have no particular meaning when appearing outside
251 * of the <tt>lenient-parse</tt> rule set.</p>
252 *
253 * <p>The body of a rule set consists of an ordered, semicolon-delimited list of <em>rules.</em>
254 * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two <em>substitutions.</em>
255 * These parameters are controlled by the description syntax, which consists of a <em>rule
256 * descriptor,</em> a colon, and a <em>rule body.</em></p>
257 *
258 * <p>A rule descriptor can take one of the following forms (text in <em>italics</em> is the
259 * name of a token):</p>
260 *
261 * <table border="0" width="100%">
262 * <tr>
263 * <td><em>bv</em>:</td>
264 * <td><em>bv</em> specifies the rule's base value. <em>bv</em> is a decimal
265 * number expressed using ASCII digits. <em>bv</em> may contain spaces, period, and commas,
266 * which are ignored. The rule's divisor is the highest power of 10 less than or equal to
267 * the base value.</td>
268 * </tr>
269 * <tr>
270 * <td><em>bv</em>/<em>rad</em>:</td>
271 * <td><em>bv</em> specifies the rule's base value. The rule's divisor is the
272 * highest power of <em>rad</em> less than or equal to the base value.</td>
273 * </tr>
274 * <tr>
275 * <td><em>bv</em>>:</td>
276 * <td><em>bv</em> specifies the rule's base value. To calculate the divisor,
277 * let the radix be 10, and the exponent be the highest exponent of the radix that yields a
278 * result less than or equal to the base value. Every > character after the base value
279 * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
280 * raised to the power of the exponent; otherwise, the divisor is 1.</td>
281 * </tr>
282 * <tr>
283 * <td><em>bv</em>/<em>rad</em>>:</td>
284 * <td><em>bv</em> specifies the rule's base value. To calculate the divisor,
285 * let the radix be <em>rad</em>, and the exponent be the highest exponent of the radix that
286 * yields a result less than or equal to the base value. Every > character after the radix
287 * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
288 * raised to the power of the exponent; otherwise, the divisor is 1.</td>
289 * </tr>
290 * <tr>
291 * <td>-x:</td>
292 * <td>The rule is a negative-number rule.</td>
293 * </tr>
294 * <tr>
295 * <td>x.x:</td>
296 * <td>The rule is an <em>improper fraction rule</em>. If the full stop in
297 * the middle of the rule name is replaced with the decimal point
298 * that is used in the language or DecimalFormatSymbols, then that rule will
299 * have precedence when formatting and parsing this rule. For example, some
300 * languages use the comma, and can thus be written as x,x instead. For example,
301 * you can use "x.x: << point >>;x,x: << comma >>;" to
302 * handle the decimal point that matches the language's natural spelling of
303 * the punctuation of either the full stop or comma.</td>
304 * </tr>
305 * <tr>
306 * <td>0.x:</td>
307 * <td>The rule is a <em>proper fraction rule</em>. If the full stop in
308 * the middle of the rule name is replaced with the decimal point
309 * that is used in the language or DecimalFormatSymbols, then that rule will
310 * have precedence when formatting and parsing this rule. For example, some
311 * languages use the comma, and can thus be written as 0,x instead. For example,
312 * you can use "0.x: point >>;0,x: comma >>;" to
313 * handle the decimal point that matches the language's natural spelling of
314 * the punctuation of either the full stop or comma.</td>
315 * </tr>
316 * <tr>
317 * <td>x.0:</td>
318 * <td>The rule is a <em>default rule</em>. If the full stop in
319 * the middle of the rule name is replaced with the decimal point
320 * that is used in the language or DecimalFormatSymbols, then that rule will
321 * have precedence when formatting and parsing this rule. For example, some
322 * languages use the comma, and can thus be written as x,0 instead. For example,
323 * you can use "x.0: << point;x,0: << comma;" to
324 * handle the decimal point that matches the language's natural spelling of
325 * the punctuation of either the full stop or comma.</td>
326 * </tr>
327 * <tr>
328 * <td>Inf:</td>
329 * <td>The rule for infinity.</td>
330 * </tr>
331 * <tr>
332 * <td>NaN:</td>
333 * <td>The rule for an IEEE 754 NaN (not a number).</td>
334 * </tr>
335 * <tr>
336 * <td><em>nothing</em></td>
337 * <td>If the rule's rule descriptor is left out, the base value is one plus the
338 * preceding rule's base value (or zero if this is the first rule in the list) in a normal
339 * rule set. In a fraction rule set, the base value is the same as the preceding rule's
340 * base value.</td>
341 * </tr>
342 * </table>
343 *
344 * <p>A rule set may be either a regular rule set or a <em>fraction rule set,</em> depending
345 * on whether it is used to format a number's integral part (or the whole number) or a
346 * number's fractional part. Using a rule set to format a rule's fractional part makes it a
347 * fraction rule set.</p>
348 *
349 * <p>Which rule is used to format a number is defined according to one of the following
350 * algorithms: If the rule set is a regular rule set, do the following:
351 *
352 * <ul>
353 * <li>If the rule set includes a default rule (and the number was passed in as a <tt>double</tt>),
354 * use the default rule. (If the number being formatted was passed in as a <tt>long</tt>,
355 * the default rule is ignored.)</li>
356 * <li>If the number is negative, use the negative-number rule.</li>
357 * <li>If the number has a fractional part and is greater than 1, use the improper fraction
358 * rule.</li>
359 * <li>If the number has a fractional part and is between 0 and 1, use the proper fraction
360 * rule.</li>
361 * <li>Binary-search the rule list for the rule with the highest base value less than or equal
362 * to the number. If that rule has two substitutions, its base value is not an even multiple
363 * of its divisor, and the number <em>is</em> an even multiple of the rule's divisor, use the
364 * rule that precedes it in the rule list. Otherwise, use the rule itself.</li>
365 * </ul>
366 *
367 * <p>If the rule set is a fraction rule set, do the following:
368 *
369 * <ul>
370 * <li>Ignore negative-number and fraction rules.</li>
371 * <li>For each rule in the list, multiply the number being formatted (which will always be
372 * between 0 and 1) by the rule's base value. Keep track of the distance between the result
373 * the nearest integer.</li>
374 * <li>Use the rule that produced the result closest to zero in the above calculation. In the
375 * event of a tie or a direct hit, use the first matching rule encountered. (The idea here is
376 * to try each rule's base value as a possible denominator of a fraction. Whichever
377 * denominator produces the fraction closest in value to the number being formatted wins.) If
378 * the rule following the matching rule has the same base value, use it if the numerator of
379 * the fraction is anything other than 1; if the numerator is 1, use the original matching
380 * rule. (This is to allow singular and plural forms of the rule text without a lot of extra
381 * hassle.)</li>
382 * </ul>
383 *
384 * <p>A rule's body consists of a string of characters terminated by a semicolon. The rule
385 * may include zero, one, or two <em>substitution tokens,</em> and a range of text in
386 * brackets. The brackets denote optional text (and may also include one or both
387 * substitutions). The exact meanings of the substitution tokens, and under what conditions
388 * optional text is omitted, depend on the syntax of the substitution token and the context.
389 * The rest of the text in a rule body is literal text that is output when the rule matches
390 * the number being formatted.</p>
391 *
392 * <p>A substitution token begins and ends with a <em>token character.</em> The token
393 * character and the context together specify a mathematical operation to be performed on the
394 * number being formatted. An optional <em>substitution descriptor </em>specifies how the
395 * value resulting from that operation is used to fill in the substitution. The position of
396 * the substitution token in the rule body specifies the location of the resultant text in
397 * the original rule text.</p>
398 *
399 * <p>The meanings of the substitution token characters are as follows:</p>
400 *
401 * <table border="0" width="100%">
402 * <tr>
403 * <td>>></td>
404 * <td>in normal rule</td>
405 * <td>Divide the number by the rule's divisor and format the remainder</td>
406 * </tr>
407 * <tr>
408 * <td></td>
409 * <td>in negative-number rule</td>
410 * <td>Find the absolute value of the number and format the result</td>
411 * </tr>
412 * <tr>
413 * <td></td>
414 * <td>in fraction or default rule</td>
415 * <td>Isolate the number's fractional part and format it.</td>
416 * </tr>
417 * <tr>
418 * <td></td>
419 * <td>in rule in fraction rule set</td>
420 * <td>Not allowed.</td>
421 * </tr>
422 * <tr>
423 * <td>>>></td>
424 * <td>in normal rule</td>
425 * <td>Divide the number by the rule's divisor and format the remainder,
426 * but bypass the normal rule-selection process and just use the
427 * rule that precedes this one in this rule list.</td>
428 * </tr>
429 * <tr>
430 * <td></td>
431 * <td>in all other rules</td>
432 * <td>Not allowed.</td>
433 * </tr>
434 * <tr>
435 * <td><<</td>
436 * <td>in normal rule</td>
437 * <td>Divide the number by the rule's divisor and format the quotient</td>
438 * </tr>
439 * <tr>
440 * <td></td>
441 * <td>in negative-number rule</td>
442 * <td>Not allowed.</td>
443 * </tr>
444 * <tr>
445 * <td></td>
446 * <td>in fraction or default rule</td>
447 * <td>Isolate the number's integral part and format it.</td>
448 * </tr>
449 * <tr>
450 * <td></td>
451 * <td>in rule in fraction rule set</td>
452 * <td>Multiply the number by the rule's base value and format the result.</td>
453 * </tr>
454 * <tr>
455 * <td>==</td>
456 * <td>in all rule sets</td>
457 * <td>Format the number unchanged</td>
458 * </tr>
459 * <tr>
460 * <td>[]</td>
461 * <td>in normal rule</td>
462 * <td>Omit the optional text if the number is an even multiple of the rule's divisor</td>
463 * </tr>
464 * <tr>
465 * <td></td>
466 * <td>in negative-number rule</td>
467 * <td>Not allowed.</td>
468 * </tr>
469 * <tr>
470 * <td></td>
471 * <td>in improper-fraction rule</td>
472 * <td>Omit the optional text if the number is between 0 and 1 (same as specifying both an
473 * x.x rule and a 0.x rule)</td>
474 * </tr>
475 * <tr>
476 * <td></td>
477 * <td>in default rule</td>
478 * <td>Omit the optional text if the number is an integer (same as specifying both an x.x
479 * rule and an x.0 rule)</td>
480 * </tr>
481 * <tr>
482 * <td></td>
483 * <td>in proper-fraction rule</td>
484 * <td>Not allowed.</td>
485 * </tr>
486 * <tr>
487 * <td></td>
488 * <td>in rule in fraction rule set</td>
489 * <td>Omit the optional text if multiplying the number by the rule's base value yields 1.</td>
490 * </tr>
491 * <tr>
492 * <td width="37">$(cardinal,<i>plural syntax</i>)$</td>
493 * <td width="23"></td>
494 * <td width="165" valign="top">in all rule sets</td>
495 * <td>This provides the ability to choose a word based on the number divided by the radix to the power of the
496 * exponent of the base value for the specified locale, which is normally equivalent to the << value.
497 * This uses the cardinal plural rules from PluralFormat. All strings used in the plural format are treated
498 * as the same base value for parsing.</td>
499 * </tr>
500 * <tr>
501 * <td width="37">$(ordinal,<i>plural syntax</i>)$</td>
502 * <td width="23"></td>
503 * <td width="165" valign="top">in all rule sets</td>
504 * <td>This provides the ability to choose a word based on the number divided by the radix to the power of the
505 * exponent of the base value for the specified locale, which is normally equivalent to the << value.
506 * This uses the ordinal plural rules from PluralFormat. All strings used in the plural format are treated
507 * as the same base value for parsing.</td>
508 * </tr>
509 * </table>
510 *
511 * <p>The substitution descriptor (i.e., the text between the token characters) may take one
512 * of three forms:</p>
513 *
514 * <table border="0" width="100%">
515 * <tr>
516 * <td>a rule set name</td>
517 * <td>Perform the mathematical operation on the number, and format the result using the
518 * named rule set.</td>
519 * </tr>
520 * <tr>
521 * <td>a DecimalFormat pattern</td>
522 * <td>Perform the mathematical operation on the number, and format the result using a
523 * DecimalFormat with the specified pattern. The pattern must begin with 0 or #.</td>
524 * </tr>
525 * <tr>
526 * <td>nothing</td>
527 * <td>Perform the mathematical operation on the number, and format the result using the rule
528 * set containing the current rule, except:
529 * <ul>
530 * <li>You can't have an empty substitution descriptor with a == substitution.</li>
531 * <li>If you omit the substitution descriptor in a >> substitution in a fraction rule,
532 * format the result one digit at a time using the rule set containing the current rule.</li>
533 * <li>If you omit the substitution descriptor in a << substitution in a rule in a
534 * fraction rule set, format the result using the default rule set for this formatter.</li>
535 * </ul>
536 * </td>
537 * </tr>
538 * </table>
539 *
540 * <p>Whitespace is ignored between a rule set name and a rule set body, between a rule
541 * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe,
542 * the apostrophe is ignored, but all text after it becomes significant (this is how you can
543 * have a rule's rule text begin with whitespace). There is no escape function: the semicolon
544 * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set
545 * names. The characters beginning a substitution token are always treated as the beginning
546 * of a substitution token.</p>
547 *
548 * <p>See the resource data and the demo program for annotated examples of real rule sets
549 * using these features.</p>
550 *
551 * <p><em>User subclasses are not supported.</em> While clients may write
552 * subclasses, such code will not necessarily work and will not be
553 * guaranteed to work stably from release to release.
554 *
555 * <p><b>Localizations</b></p>
556 * <p>Constructors are available that allow the specification of localizations for the
557 * public rule sets (and also allow more control over what public rule sets are available).
558 * Localization data is represented as a textual description. The description represents
559 * an array of arrays of string. The first element is an array of the public rule set names,
560 * each of these must be one of the public rule set names that appear in the rules. Only
561 * names in this array will be treated as public rule set names by the API. Each subsequent
562 * element is an array of localizations of these names. The first element of one of these
563 * subarrays is the locale name, and the remaining elements are localizations of the
564 * public rule set names, in the same order as they were listed in the first array.</p>
565 * <p>In the syntax, angle brackets '<', '>' are used to delimit the arrays, and comma ',' is used
566 * to separate elements of an array. Whitespace is ignored, unless quoted.</p>
567 * <p>For example:<pre>
568 * < < %foo, %bar, %baz >,
569 * < en, Foo, Bar, Baz >,
570 * < fr, 'le Foo', 'le Bar', 'le Baz' >
571 * < zh, \\u7532, \\u4e59, \\u4e19 > >
572 * </pre></p>
573 * @author Richard Gillam
574 * @see NumberFormat
575 * @see DecimalFormat
576 * @see PluralFormat
577 * @see PluralRules
578 * @stable ICU 2.0
579 */
580 class U_I18N_API RuleBasedNumberFormat : public NumberFormat {
581 public:
582
583 //-----------------------------------------------------------------------
584 // constructors
585 //-----------------------------------------------------------------------
586
587 /**
588 * Creates a RuleBasedNumberFormat that behaves according to the description
589 * passed in. The formatter uses the default locale.
590 * @param rules A description of the formatter's desired behavior.
591 * See the class documentation for a complete explanation of the description
592 * syntax.
593 * @param perror The parse error if an error was encountered.
594 * @param status The status indicating whether the constructor succeeded.
595 * @stable ICU 3.2
596 */
597 RuleBasedNumberFormat(const UnicodeString& rules, UParseError& perror, UErrorCode& status);
598
599 /**
600 * Creates a RuleBasedNumberFormat that behaves according to the description
601 * passed in. The formatter uses the default locale.
602 * <p>
603 * The localizations data provides information about the public
604 * rule sets and their localized display names for different
605 * locales. The first element in the list is an array of the names
606 * of the public rule sets. The first element in this array is
607 * the initial default ruleset. The remaining elements in the
608 * list are arrays of localizations of the names of the public
609 * rule sets. Each of these is one longer than the initial array,
610 * with the first String being the ULocale ID, and the remaining
611 * Strings being the localizations of the rule set names, in the
612 * same order as the initial array. Arrays are NULL-terminated.
613 * @param rules A description of the formatter's desired behavior.
614 * See the class documentation for a complete explanation of the description
615 * syntax.
616 * @param localizations the localization information.
617 * names in the description. These will be copied by the constructor.
618 * @param perror The parse error if an error was encountered.
619 * @param status The status indicating whether the constructor succeeded.
620 * @stable ICU 3.2
621 */
622 RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations,
623 UParseError& perror, UErrorCode& status);
624
625 /**
626 * Creates a RuleBasedNumberFormat that behaves according to the rules
627 * passed in. The formatter uses the specified locale to determine the
628 * characters to use when formatting numerals, and to define equivalences
629 * for lenient parsing.
630 * @param rules The formatter rules.
631 * See the class documentation for a complete explanation of the rule
632 * syntax.
633 * @param locale A locale that governs which characters are used for
634 * formatting values in numerals and which characters are equivalent in
635 * lenient parsing.
636 * @param perror The parse error if an error was encountered.
637 * @param status The status indicating whether the constructor succeeded.
638 * @stable ICU 2.0
639 */
640 RuleBasedNumberFormat(const UnicodeString& rules, const Locale& locale,
641 UParseError& perror, UErrorCode& status);
642
643 /**
644 * Creates a RuleBasedNumberFormat that behaves according to the description
645 * passed in. The formatter uses the default locale.
646 * <p>
647 * The localizations data provides information about the public
648 * rule sets and their localized display names for different
649 * locales. The first element in the list is an array of the names
650 * of the public rule sets. The first element in this array is
651 * the initial default ruleset. The remaining elements in the
652 * list are arrays of localizations of the names of the public
653 * rule sets. Each of these is one longer than the initial array,
654 * with the first String being the ULocale ID, and the remaining
655 * Strings being the localizations of the rule set names, in the
656 * same order as the initial array. Arrays are NULL-terminated.
657 * @param rules A description of the formatter's desired behavior.
658 * See the class documentation for a complete explanation of the description
659 * syntax.
660 * @param localizations a list of localizations for the rule set
661 * names in the description. These will be copied by the constructor.
662 * @param locale A locale that governs which characters are used for
663 * formatting values in numerals and which characters are equivalent in
664 * lenient parsing.
665 * @param perror The parse error if an error was encountered.
666 * @param status The status indicating whether the constructor succeeded.
667 * @stable ICU 3.2
668 */
669 RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations,
670 const Locale& locale, UParseError& perror, UErrorCode& status);
671
672 /**
673 * Creates a RuleBasedNumberFormat from a predefined ruleset. The selector
674 * code chose among three possible predefined formats: spellout, ordinal,
675 * and duration.
676 * @param tag A selector code specifying which kind of formatter to create for that
677 * locale. There are four legal values: URBNF_SPELLOUT, which creates a formatter that
678 * spells out a value in words in the desired language, URBNF_ORDINAL, which attaches
679 * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
680 * URBNF_DURATION, which formats a duration in seconds as hours, minutes, and seconds always rounding down,
681 * and URBNF_NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering
682 * systems such as the Hebrew numbering system, or for Roman Numerals, etc.
683 * NOTE: If you use URBNF_NUMBERING_SYSTEM, you must also call setDefaultRuleSet() to
684 * specify the exact numbering system you want to use. If you want the default numbering system
685 * for the locale, call NumberFormat::createInstance() instead of creating a RuleBasedNumberFormat directly.
686 * @param locale The locale for the formatter.
687 * @param status The status indicating whether the constructor succeeded.
688 * @stable ICU 2.0
689 */
690 RuleBasedNumberFormat(URBNFRuleSetTag tag, const Locale& locale, UErrorCode& status);
691
692 //-----------------------------------------------------------------------
693 // boilerplate
694 //-----------------------------------------------------------------------
695
696 /**
697 * Copy constructor
698 * @param rhs the object to be copied from.
699 * @stable ICU 2.6
700 */
701 RuleBasedNumberFormat(const RuleBasedNumberFormat& rhs);
702
703 /**
704 * Assignment operator
705 * @param rhs the object to be copied from.
706 * @stable ICU 2.6
707 */
708 RuleBasedNumberFormat& operator=(const RuleBasedNumberFormat& rhs);
709
710 /**
711 * Release memory allocated for a RuleBasedNumberFormat when you are finished with it.
712 * @stable ICU 2.6
713 */
714 virtual ~RuleBasedNumberFormat();
715
716 /**
717 * Clone this object polymorphically. The caller is responsible
718 * for deleting the result when done.
719 * @return A copy of the object.
720 * @stable ICU 2.6
721 */
722 virtual RuleBasedNumberFormat* clone() const override;
723
724 /**
725 * Return true if the given Format objects are semantically equal.
726 * Objects of different subclasses are considered unequal.
727 * @param other the object to be compared with.
728 * @return true if the given Format objects are semantically equal.
729 * @stable ICU 2.6
730 */
731 virtual bool operator==(const Format& other) const override;
732
733 //-----------------------------------------------------------------------
734 // public API functions
735 //-----------------------------------------------------------------------
736
737 /**
738 * return the rules that were provided to the RuleBasedNumberFormat.
739 * @return the result String that was passed in
740 * @stable ICU 2.0
741 */
742 virtual UnicodeString getRules() const;
743
744 /**
745 * Return the number of public rule set names.
746 * @return the number of public rule set names.
747 * @stable ICU 2.0
748 */
749 virtual int32_t getNumberOfRuleSetNames() const;
750
751 /**
752 * Return the name of the index'th public ruleSet. If index is not valid,
753 * the function returns null.
754 * @param index the index of the ruleset
755 * @return the name of the index'th public ruleSet.
756 * @stable ICU 2.0
757 */
758 virtual UnicodeString getRuleSetName(int32_t index) const;
759
760 /**
761 * Return the number of locales for which we have localized rule set display names.
762 * @return the number of locales for which we have localized rule set display names.
763 * @stable ICU 3.2
764 */
765 virtual int32_t getNumberOfRuleSetDisplayNameLocales(void) const;
766
767 /**
768 * Return the index'th display name locale.
769 * @param index the index of the locale
770 * @param status set to a failure code when this function fails
771 * @return the locale
772 * @see #getNumberOfRuleSetDisplayNameLocales
773 * @stable ICU 3.2
774 */
775 virtual Locale getRuleSetDisplayNameLocale(int32_t index, UErrorCode& status) const;
776
777 /**
778 * Return the rule set display names for the provided locale. These are in the same order
779 * as those returned by getRuleSetName. The locale is matched against the locales for
780 * which there is display name data, using normal fallback rules. If no locale matches,
781 * the default display names are returned. (These are the internal rule set names minus
782 * the leading '%'.)
783 * @param index the index of the rule set
784 * @param locale the locale (returned by getRuleSetDisplayNameLocales) for which the localized
785 * display name is desired
786 * @return the display name for the given index, which might be bogus if there is an error
787 * @see #getRuleSetName
788 * @stable ICU 3.2
789 */
790 virtual UnicodeString getRuleSetDisplayName(int32_t index,
791 const Locale& locale = Locale::getDefault());
792
793 /**
794 * Return the rule set display name for the provided rule set and locale.
795 * The locale is matched against the locales for which there is display name data, using
796 * normal fallback rules. If no locale matches, the default display name is returned.
797 * @return the display name for the rule set
798 * @stable ICU 3.2
799 * @see #getRuleSetDisplayName
800 */
801 virtual UnicodeString getRuleSetDisplayName(const UnicodeString& ruleSetName,
802 const Locale& locale = Locale::getDefault());
803
804
805 using NumberFormat::format;
806
807 /**
808 * Formats the specified 32-bit number using the default ruleset.
809 * @param number The number to format.
810 * @param toAppendTo the string that will hold the (appended) result
811 * @param pos the fieldposition
812 * @return A textual representation of the number.
813 * @stable ICU 2.0
814 */
815 virtual UnicodeString& format(int32_t number,
816 UnicodeString& toAppendTo,
817 FieldPosition& pos) const override;
818
819 /**
820 * Formats the specified 64-bit number using the default ruleset.
821 * @param number The number to format.
822 * @param toAppendTo the string that will hold the (appended) result
823 * @param pos the fieldposition
824 * @return A textual representation of the number.
825 * @stable ICU 2.1
826 */
827 virtual UnicodeString& format(int64_t number,
828 UnicodeString& toAppendTo,
829 FieldPosition& pos) const override;
830 /**
831 * Formats the specified number using the default ruleset.
832 * @param number The number to format.
833 * @param toAppendTo the string that will hold the (appended) result
834 * @param pos the fieldposition
835 * @return A textual representation of the number.
836 * @stable ICU 2.0
837 */
838 virtual UnicodeString& format(double number,
839 UnicodeString& toAppendTo,
840 FieldPosition& pos) const override;
841
842 /**
843 * Formats the specified number using the named ruleset.
844 * @param number The number to format.
845 * @param ruleSetName The name of the rule set to format the number with.
846 * This must be the name of a valid public rule set for this formatter.
847 * @param toAppendTo the string that will hold the (appended) result
848 * @param pos the fieldposition
849 * @param status the status
850 * @return A textual representation of the number.
851 * @stable ICU 2.0
852 */
853 virtual UnicodeString& format(int32_t number,
854 const UnicodeString& ruleSetName,
855 UnicodeString& toAppendTo,
856 FieldPosition& pos,
857 UErrorCode& status) const;
858 /**
859 * Formats the specified 64-bit number using the named ruleset.
860 * @param number The number to format.
861 * @param ruleSetName The name of the rule set to format the number with.
862 * This must be the name of a valid public rule set for this formatter.
863 * @param toAppendTo the string that will hold the (appended) result
864 * @param pos the fieldposition
865 * @param status the status
866 * @return A textual representation of the number.
867 * @stable ICU 2.1
868 */
869 virtual UnicodeString& format(int64_t number,
870 const UnicodeString& ruleSetName,
871 UnicodeString& toAppendTo,
872 FieldPosition& pos,
873 UErrorCode& status) const;
874 /**
875 * Formats the specified number using the named ruleset.
876 * @param number The number to format.
877 * @param ruleSetName The name of the rule set to format the number with.
878 * This must be the name of a valid public rule set for this formatter.
879 * @param toAppendTo the string that will hold the (appended) result
880 * @param pos the fieldposition
881 * @param status the status
882 * @return A textual representation of the number.
883 * @stable ICU 2.0
884 */
885 virtual UnicodeString& format(double number,
886 const UnicodeString& ruleSetName,
887 UnicodeString& toAppendTo,
888 FieldPosition& pos,
889 UErrorCode& status) const;
890
891 protected:
892 /**
893 * Format a decimal number.
894 * The number is a DigitList wrapper onto a floating point decimal number.
895 * The default implementation in NumberFormat converts the decimal number
896 * to a double and formats that. Subclasses of NumberFormat that want
897 * to specifically handle big decimal numbers must override this method.
898 * class DecimalFormat does so.
899 *
900 * @param number The number, a DigitList format Decimal Floating Point.
901 * @param appendTo Output parameter to receive result.
902 * Result is appended to existing contents.
903 * @param pos On input: an alignment field, if desired.
904 * On output: the offsets of the alignment field.
905 * @param status Output param filled with success/failure status.
906 * @return Reference to 'appendTo' parameter.
907 * @internal
908 */
909 virtual UnicodeString& format(const number::impl::DecimalQuantity &number,
910 UnicodeString& appendTo,
911 FieldPosition& pos,
912 UErrorCode& status) const override;
913 public:
914
915 using NumberFormat::parse;
916
917 /**
918 * Parses the specified string, beginning at the specified position, according
919 * to this formatter's rules. This will match the string against all of the
920 * formatter's public rule sets and return the value corresponding to the longest
921 * parseable substring. This function's behavior is affected by the lenient
922 * parse mode.
923 * @param text The string to parse
924 * @param result the result of the parse, either a double or a long.
925 * @param parsePosition On entry, contains the position of the first character
926 * in "text" to examine. On exit, has been updated to contain the position
927 * of the first character in "text" that wasn't consumed by the parse.
928 * @see #setLenient
929 * @stable ICU 2.0
930 */
931 virtual void parse(const UnicodeString& text,
932 Formattable& result,
933 ParsePosition& parsePosition) const override;
934
935 #if !UCONFIG_NO_COLLATION
936
937 /**
938 * Turns lenient parse mode on and off.
939 *
940 * When in lenient parse mode, the formatter uses a Collator for parsing the text.
941 * Only primary differences are treated as significant. This means that case
942 * differences, accent differences, alternate spellings of the same letter
943 * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in
944 * matching the text. In many cases, numerals will be accepted in place of words
945 * or phrases as well.
946 *
947 * For example, all of the following will correctly parse as 255 in English in
948 * lenient-parse mode:
949 * <br>"two hundred fifty-five"
950 * <br>"two hundred fifty five"
951 * <br>"TWO HUNDRED FIFTY-FIVE"
952 * <br>"twohundredfiftyfive"
953 * <br>"2 hundred fifty-5"
954 *
955 * The Collator used is determined by the locale that was
956 * passed to this object on construction. The description passed to this object
957 * on construction may supply additional collation rules that are appended to the
958 * end of the default collator for the locale, enabling additional equivalences
959 * (such as adding more ignorable characters or permitting spelled-out version of
960 * symbols; see the demo program for examples).
961 *
962 * It's important to emphasize that even strict parsing is relatively lenient: it
963 * will accept some text that it won't produce as output. In English, for example,
964 * it will correctly parse "two hundred zero" and "fifteen hundred".
965 *
966 * @param enabled If true, turns lenient-parse mode on; if false, turns it off.
967 * @see RuleBasedCollator
968 * @stable ICU 2.0
969 */
970 virtual void setLenient(UBool enabled) override;
971
972 /**
973 * Returns true if lenient-parse mode is turned on. Lenient parsing is off
974 * by default.
975 * @return true if lenient-parse mode is turned on.
976 * @see #setLenient
977 * @stable ICU 2.0
978 */
979 virtual inline UBool isLenient(void) const override;
980
981 #endif
982
983 /**
984 * Override the default rule set to use. If ruleSetName is null, reset
985 * to the initial default rule set. If the rule set is not a public rule set name,
986 * U_ILLEGAL_ARGUMENT_ERROR is returned in status.
987 * @param ruleSetName the name of the rule set, or null to reset the initial default.
988 * @param status set to failure code when a problem occurs.
989 * @stable ICU 2.6
990 */
991 virtual void setDefaultRuleSet(const UnicodeString& ruleSetName, UErrorCode& status);
992
993 /**
994 * Return the name of the current default rule set. If the current rule set is
995 * not public, returns a bogus (and empty) UnicodeString.
996 * @return the name of the current default rule set
997 * @stable ICU 3.0
998 */
999 virtual UnicodeString getDefaultRuleSetName() const;
1000
1001 /**
1002 * Set a particular UDisplayContext value in the formatter, such as
1003 * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. Note: For getContext, see
1004 * NumberFormat.
1005 * @param value The UDisplayContext value to set.
1006 * @param status Input/output status. If at entry this indicates a failure
1007 * status, the function will do nothing; otherwise this will be
1008 * updated with any new status from the function.
1009 * @stable ICU 53
1010 */
1011 virtual void setContext(UDisplayContext value, UErrorCode& status) override;
1012
1013 /**
1014 * Get the rounding mode.
1015 * @return A rounding mode
1016 * @stable ICU 60
1017 */
1018 virtual ERoundingMode getRoundingMode(void) const override;
1019
1020 /**
1021 * Set the rounding mode.
1022 * @param roundingMode A rounding mode
1023 * @stable ICU 60
1024 */
1025 virtual void setRoundingMode(ERoundingMode roundingMode) override;
1026
1027 public:
1028 /**
1029 * ICU "poor man's RTTI", returns a UClassID for this class.
1030 *
1031 * @stable ICU 2.8
1032 */
1033 static UClassID U_EXPORT2 getStaticClassID(void);
1034
1035 /**
1036 * ICU "poor man's RTTI", returns a UClassID for the actual class.
1037 *
1038 * @stable ICU 2.8
1039 */
1040 virtual UClassID getDynamicClassID(void) const override;
1041
1042 /**
1043 * Sets the decimal format symbols, which is generally not changed
1044 * by the programmer or user. The formatter takes ownership of
1045 * symbolsToAdopt; the client must not delete it.
1046 *
1047 * @param symbolsToAdopt DecimalFormatSymbols to be adopted.
1048 * @stable ICU 49
1049 */
1050 virtual void adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt);
1051
1052 /**
1053 * Sets the decimal format symbols, which is generally not changed
1054 * by the programmer or user. A clone of the symbols is created and
1055 * the symbols is _not_ adopted; the client is still responsible for
1056 * deleting it.
1057 *
1058 * @param symbols DecimalFormatSymbols.
1059 * @stable ICU 49
1060 */
1061 virtual void setDecimalFormatSymbols(const DecimalFormatSymbols& symbols);
1062
1063 private:
1064 RuleBasedNumberFormat() = delete; // default constructor not implemented
1065
1066 // this will ref the localizations if they are not NULL
1067 // caller must deref to get adoption
1068 RuleBasedNumberFormat(const UnicodeString& description, LocalizationInfo* localizations,
1069 const Locale& locale, UParseError& perror, UErrorCode& status);
1070
1071 void init(const UnicodeString& rules, LocalizationInfo* localizations, UParseError& perror, UErrorCode& status);
1072 void initCapitalizationContextInfo(const Locale& thelocale);
1073 void dispose();
1074 void stripWhitespace(UnicodeString& src);
1075 void initDefaultRuleSet();
1076 NFRuleSet* findRuleSet(const UnicodeString& name, UErrorCode& status) const;
1077
1078 /* friend access */
1079 friend class NFSubstitution;
1080 friend class NFRule;
1081 friend class NFRuleSet;
1082 friend class FractionalPartSubstitution;
1083
1084 inline NFRuleSet * getDefaultRuleSet() const;
1085 const RuleBasedCollator * getCollator() const;
1086 DecimalFormatSymbols * initializeDecimalFormatSymbols(UErrorCode &status);
1087 const DecimalFormatSymbols * getDecimalFormatSymbols() const;
1088 NFRule * initializeDefaultInfinityRule(UErrorCode &status);
1089 const NFRule * getDefaultInfinityRule() const;
1090 NFRule * initializeDefaultNaNRule(UErrorCode &status);
1091 const NFRule * getDefaultNaNRule() const;
1092 PluralFormat *createPluralFormat(UPluralType pluralType, const UnicodeString &pattern, UErrorCode& status) const;
1093 UnicodeString& adjustForCapitalizationContext(int32_t startPos, UnicodeString& currentResult, UErrorCode& status) const;
1094 UnicodeString& format(int64_t number, NFRuleSet *ruleSet, UnicodeString& toAppendTo, UErrorCode& status) const;
1095 void format(double number, NFRuleSet& rs, UnicodeString& toAppendTo, UErrorCode& status) const;
1096
1097 private:
1098 NFRuleSet **fRuleSets;
1099 UnicodeString* ruleSetDescriptions;
1100 int32_t numRuleSets;
1101 NFRuleSet *defaultRuleSet;
1102 Locale locale;
1103 RuleBasedCollator* collator;
1104 DecimalFormatSymbols* decimalFormatSymbols;
1105 NFRule *defaultInfinityRule;
1106 NFRule *defaultNaNRule;
1107 ERoundingMode fRoundingMode;
1108 UBool lenient;
1109 UnicodeString* lenientParseRules;
1110 LocalizationInfo* localizations;
1111 UnicodeString originalDescription;
1112 UBool capitalizationInfoSet;
1113 UBool capitalizationForUIListMenu;
1114 UBool capitalizationForStandAlone;
1115 BreakIterator* capitalizationBrkIter;
1116 };
1117
1118 // ---------------
1119
1120 #if !UCONFIG_NO_COLLATION
1121
1122 inline UBool
isLenient(void)1123 RuleBasedNumberFormat::isLenient(void) const {
1124 return lenient;
1125 }
1126
1127 #endif
1128
1129 inline NFRuleSet*
getDefaultRuleSet()1130 RuleBasedNumberFormat::getDefaultRuleSet() const {
1131 return defaultRuleSet;
1132 }
1133
1134 U_NAMESPACE_END
1135
1136 /* U_HAVE_RBNF */
1137 #endif
1138
1139 #endif /* U_SHOW_CPLUSPLUS_API */
1140
1141 /* RBNF_H */
1142 #endif
1143