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