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