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