]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-52_1/main/classes/core/src/com/ibm/icu/text/RuleBasedNumberFormat.java
Added flags.
[Dictionary.git] / jars / icu4j-52_1 / main / classes / core / src / com / ibm / icu / text / RuleBasedNumberFormat.java
1 /*
2  *******************************************************************************
3  * Copyright (C) 1996-2013, International Business Machines Corporation and    *
4  * others. All Rights Reserved.                                                *
5  *******************************************************************************
6  */
7
8 package com.ibm.icu.text;
9
10 import java.math.BigInteger;
11 import java.text.FieldPosition;
12 import java.text.ParsePosition;
13 import java.util.Arrays;
14 import java.util.HashMap;
15 import java.util.Locale;
16 import java.util.Map;
17 import java.util.MissingResourceException;
18 import java.util.Set;
19
20 import com.ibm.icu.impl.ICUDebug;
21 import com.ibm.icu.impl.ICUResourceBundle;
22 import com.ibm.icu.impl.PatternProps;
23 import com.ibm.icu.util.ULocale;
24 import com.ibm.icu.util.ULocale.Category;
25 import com.ibm.icu.util.UResourceBundle;
26 import com.ibm.icu.util.UResourceBundleIterator;
27
28
29 /**
30  * <p>A class that formats numbers according to a set of rules. This number formatter is
31  * typically used for spelling out numeric values in words (e.g., 25,3476 as
32  * &quot;twenty-five thousand three hundred seventy-six&quot; or &quot;vingt-cinq mille trois
33  * cents soixante-seize&quot; or
34  * &quot;funfundzwanzigtausenddreihundertsechsundsiebzig&quot;), but can also be used for
35  * other complicated formatting tasks, such as formatting a number of seconds as hours,
36  * minutes and seconds (e.g., 3,730 as &quot;1:02:10&quot;).</p>
37  *
38  * <p>The resources contain three predefined formatters for each locale: spellout, which
39  * spells out a value in words (123 is &quot;one hundred twenty-three&quot;); ordinal, which
40  * appends an ordinal suffix to the end of a numeral (123 is &quot;123rd&quot;); and
41  * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is
42  * &quot;2:03&quot;).&nbsp; The client can also define more specialized <tt>RuleBasedNumberFormat</tt>s
43  * by supplying programmer-defined rule sets.</p>
44  *
45  * <p>The behavior of a <tt>RuleBasedNumberFormat</tt> is specified by a textual description
46  * that is either passed to the constructor as a <tt>String</tt> or loaded from a resource
47  * bundle. In its simplest form, the description consists of a semicolon-delimited list of <em>rules.</em>
48  * Each rule has a string of output text and a value or range of values it is applicable to.
49  * In a typical spellout rule set, the first twenty rules are the words for the numbers from
50  * 0 to 19:</p>
51  *
52  * <pre>zero; one; two; three; four; five; six; seven; eight; nine;
53  * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;</pre>
54  *
55  * <p>For larger numbers, we can use the preceding set of rules to format the ones place, and
56  * we only have to supply the words for the multiples of 10:</p>
57  *
58  * <pre>20: twenty[-&gt;&gt;];
59  * 30: thirty{-&gt;&gt;];
60  * 40: forty[-&gt;&gt;];
61  * 50: fifty[-&gt;&gt;];
62  * 60: sixty[-&gt;&gt;];
63  * 70: seventy[-&gt;&gt;];
64  * 80: eighty[-&gt;&gt;];
65  * 90: ninety[-&gt;&gt;];</pre>
66  *
67  * <p>In these rules, the <em>base value</em> is spelled out explicitly and set off from the
68  * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable
69  * to all numbers from its own base value to one less than the next rule's base value. The
70  * &quot;&gt;&gt;&quot; token is called a <em>substitution</em> and tells the fomatter to
71  * isolate the number's ones digit, format it using this same set of rules, and place the
72  * result at the position of the &quot;&gt;&gt;&quot; token. Text in brackets is omitted if
73  * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24
74  * is &quot;twenty-four,&quot; not &quot;twenty four&quot;).</p>
75  *
76  * <p>For even larger numbers, we can actually look up several parts of the number in the
77  * list:</p>
78  *
79  * <pre>100: &lt;&lt; hundred[ &gt;&gt;];</pre>
80  *
81  * <p>The &quot;&lt;&lt;&quot; represents a new kind of substitution. The &lt;&lt; isolates
82  * the hundreds digit (and any digits to its left), formats it using this same rule set, and
83  * places the result where the &quot;&lt;&lt;&quot; was. Notice also that the meaning of
84  * &gt;&gt; has changed: it now refers to both the tens and the ones digits. The meaning of
85  * both substitutions depends on the rule's base value. The base value determines the rule's <em>divisor,</em>
86  * which is the highest power of 10 that is less than or equal to the base value (the user
87  * can change this). To fill in the substitutions, the formatter divides the number being
88  * formatted by the divisor. The integral quotient is used to fill in the &lt;&lt;
89  * substitution, and the remainder is used to fill in the &gt;&gt; substitution. The meaning
90  * of the brackets changes similarly: text in brackets is omitted if the value being
91  * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so
92  * if a substitution is filled in with text that includes another substitution, that
93  * substitution is also filled in.</p>
94  *
95  * <p>This rule covers values up to 999, at which point we add another rule:</p>
96  *
97  * <pre>1000: &lt;&lt; thousand[ &gt;&gt;];</pre>
98  *
99  * <p>Again, the meanings of the brackets and substitution tokens shift because the rule's
100  * base value is a higher power of 10, changing the rule's divisor. This rule can actually be
101  * used all the way up to 999,999. This allows us to finish out the rules as follows:</p>
102  *
103  * <pre>1,000,000: &lt;&lt; million[ &gt;&gt;];
104  * 1,000,000,000: &lt;&lt; billion[ &gt;&gt;];
105  * 1,000,000,000,000: &lt;&lt; trillion[ &gt;&gt;];
106  * 1,000,000,000,000,000: OUT OF RANGE!;</pre>
107  *
108  * <p>Commas, periods, and spaces can be used in the base values to improve legibility and
109  * are ignored by the rule parser. The last rule in the list is customarily treated as an
110  * &quot;overflow rule,&quot; applying to everything from its base value on up, and often (as
111  * in this example) being used to print out an error message or default representation.
112  * Notice also that the size of the major groupings in large numbers is controlled by the
113  * spacing of the rules: because in English we group numbers by thousand, the higher rules
114  * are separated from each other by a factor of 1,000.</p>
115  *
116  * <p>To see how these rules actually work in practice, consider the following example:
117  * Formatting 25,430 with this rule set would work like this:</p>
118  *
119  * <table border="0" width="630">
120  *   <tr>
121  *     <td width="21"></td>
122  *     <td width="257" valign="top"><strong>&lt;&lt; thousand &gt;&gt;</strong></td>
123  *     <td width="340" valign="top">[the rule whose base value is 1,000 is applicable to 25,340]</td>
124  *   </tr>
125  *   <tr>
126  *     <td width="21"></td>
127  *     <td width="257" valign="top"><strong>twenty-&gt;&gt;</strong> thousand &gt;&gt;</td>
128  *     <td width="340" valign="top">[25,340 over 1,000 is 25. The rule for 20 applies.]</td>
129  *   </tr>
130  *   <tr>
131  *     <td width="21"></td>
132  *     <td width="257" valign="top">twenty-<strong>five</strong> thousand &gt;&gt;</td>
133  *     <td width="340" valign="top">[25 mod 10 is 5. The rule for 5 is &quot;five.&quot;</td>
134  *   </tr>
135  *   <tr>
136  *     <td width="21"></td>
137  *     <td width="257" valign="top">twenty-five thousand <strong>&lt;&lt; hundred &gt;&gt;</strong></td>
138  *     <td width="340" valign="top">[25,340 mod 1,000 is 340. The rule for 100 applies.]</td>
139  *   </tr>
140  *   <tr>
141  *     <td width="21"></td>
142  *     <td width="257" valign="top">twenty-five thousand <strong>three</strong> hundred &gt;&gt;</td>
143  *     <td width="340" valign="top">[340 over 100 is 3. The rule for 3 is &quot;three.&quot;]</td>
144  *   </tr>
145  *   <tr>
146  *     <td width="21"></td>
147  *     <td width="257" valign="top">twenty-five thousand three hundred <strong>forty</strong></td>
148  *     <td width="340" valign="top">[340 mod 100 is 40. The rule for 40 applies. Since 40 divides
149  *     evenly by 10, the hyphen and substitution in the brackets are omitted.]</td>
150  *   </tr>
151  * </table>
152  *
153  * <p>The above syntax suffices only to format positive integers. To format negative numbers,
154  * we add a special rule:</p>
155  *
156  * <pre>-x: minus &gt;&gt;;</pre>
157  *
158  * <p>This is called a <em>negative-number rule,</em> and is identified by &quot;-x&quot;
159  * where the base value would be. This rule is used to format all negative numbers. the
160  * &gt;&gt; token here means &quot;find the number's absolute value, format it with these
161  * rules, and put the result here.&quot;</p>
162  *
163  * <p>We also add a special rule called a <em>fraction rule </em>for numbers with fractional
164  * parts:</p>
165  *
166  * <pre>x.x: &lt;&lt; point &gt;&gt;;</pre>
167  *
168  * <p>This rule is used for all positive non-integers (negative non-integers pass through the
169  * negative-number rule first and then through this rule). Here, the &lt;&lt; token refers to
170  * the number's integral part, and the &gt;&gt; to the number's fractional part. The
171  * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be
172  * formatted as &quot;one hundred twenty-three point four five six&quot;).</p>
173  *
174  * <p>To see how this rule syntax is applied to various languages, examine the resource data.</p>
175  *
176  * <p>There is actually much more flexibility built into the rule language than the
177  * description above shows. A formatter may own multiple rule sets, which can be selected by
178  * the caller, and which can use each other to fill in their substitutions. Substitutions can
179  * also be filled in with digits, using a DecimalFormat object. There is syntax that can be
180  * used to alter a rule's divisor in various ways. And there is provision for much more
181  * flexible fraction handling. A complete description of the rule syntax follows:</p>
182  *
183  * <hr>
184  *
185  * <p>The description of a <tt>RuleBasedNumberFormat</tt>'s behavior consists of one or more <em>rule
186  * sets.</em> Each rule set consists of a name, a colon, and a list of <em>rules.</em> A rule
187  * set name must begin with a % sign. Rule sets with names that begin with a single % sign
188  * are <em>public:</em> the caller can specify that they be used to format and parse numbers.
189  * Rule sets with names that begin with %% are <em>private:</em> they exist only for the use
190  * of other rule sets. If a formatter only has one rule set, the name may be omitted.</p>
191  *
192  * <p>The user can also specify a special &quot;rule set&quot; named <tt>%%lenient-parse</tt>.
193  * The body of <tt>%%lenient-parse</tt> isn't a set of number-formatting rules, but a <tt>RuleBasedCollator</tt>
194  * description which is used to define equivalences for lenient parsing. For more information
195  * on the syntax, see <tt>RuleBasedCollator</tt>. For more information on lenient parsing,
196  * see <tt>setLenientParse()</tt>. <em>Note:</em> symbols that have syntactic meaning
197  * in collation rules, such as '&amp;', have no particular meaning when appearing outside
198  * of the <tt>lenient-parse</tt> rule set.</p>
199  *
200  * <p>The body of a rule set consists of an ordered, semicolon-delimited list of <em>rules.</em>
201  * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two <em>substitutions.</em>
202  * These parameters are controlled by the description syntax, which consists of a <em>rule
203  * descriptor,</em> a colon, and a <em>rule body.</em></p>
204  *
205  * <p>A rule descriptor can take one of the following forms (text in <em>italics</em> is the
206  * name of a token):</p>
207  *
208  * <table border="0" width="100%">
209  *   <tr>
210  *     <td width="5%" valign="top"></td>
211  *     <td width="8%" valign="top"><em>bv</em>:</td>
212  *     <td valign="top"><em>bv</em> specifies the rule's base value. <em>bv</em> is a decimal
213  *     number expressed using ASCII digits. <em>bv</em> may contain spaces, period, and commas,
214  *     which are irgnored. The rule's divisor is the highest power of 10 less than or equal to
215  *     the base value.</td>
216  *   </tr>
217  *   <tr>
218  *     <td width="5%" valign="top"></td>
219  *     <td width="8%" valign="top"><em>bv</em>/<em>rad</em>:</td>
220  *     <td valign="top"><em>bv</em> specifies the rule's base value. The rule's divisor is the
221  *     highest power of <em>rad</em> less than or equal to the base value.</td>
222  *   </tr>
223  *   <tr>
224  *     <td width="5%" valign="top"></td>
225  *     <td width="8%" valign="top"><em>bv</em>&gt;:</td>
226  *     <td valign="top"><em>bv</em> specifies the rule's base value. To calculate the divisor,
227  *     let the radix be 10, and the exponent be the highest exponent of the radix that yields a
228  *     result less than or equal to the base value. Every &gt; character after the base value
229  *     decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
230  *     raised to the power of the exponent; otherwise, the divisor is 1.</td>
231  *   </tr>
232  *   <tr>
233  *     <td width="5%" valign="top"></td>
234  *     <td width="8%" valign="top"><em>bv</em>/<em>rad</em>&gt;:</td>
235  *     <td valign="top"><em>bv</em> specifies the rule's base value. To calculate the divisor,
236  *     let the radix be <em>rad</em>, and the exponent be the highest exponent of the radix that
237  *     yields a result less than or equal to the base value. Every &gt; character after the radix
238  *     decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
239  *     raised to the power of the exponent; otherwise, the divisor is 1.</td>
240  *   </tr>
241  *   <tr>
242  *     <td width="5%" valign="top"></td>
243  *     <td width="8%" valign="top">-x:</td>
244  *     <td valign="top">The rule is a negative-number rule.</td>
245  *   </tr>
246  *   <tr>
247  *     <td width="5%" valign="top"></td>
248  *     <td width="8%" valign="top">x.x:</td>
249  *     <td valign="top">The rule is an <em>improper fraction rule.</em></td>
250  *   </tr>
251  *   <tr>
252  *     <td width="5%" valign="top"></td>
253  *     <td width="8%" valign="top">0.x:</td>
254  *     <td valign="top">The rule is a <em>proper fraction rule.</em></td>
255  *   </tr>
256  *   <tr>
257  *     <td width="5%" valign="top"></td>
258  *     <td width="8%" valign="top">x.0:</td>
259  *     <td valign="top">The rule is a <em>master rule.</em></td>
260  *   </tr>
261  *   <tr>
262  *     <td width="5%" valign="top"></td>
263  *     <td width="8%" valign="top"><em>nothing</em></td>
264  *     <td valign="top">If the rule's rule descriptor is left out, the base value is one plus the
265  *     preceding rule's base value (or zero if this is the first rule in the list) in a normal
266  *     rule set.&nbsp; In a fraction rule set, the base value is the same as the preceding rule's
267  *     base value.</td>
268  *   </tr>
269  * </table>
270  *
271  * <p>A rule set may be either a regular rule set or a <em>fraction rule set,</em> depending
272  * on whether it is used to format a number's integral part (or the whole number) or a
273  * number's fractional part. Using a rule set to format a rule's fractional part makes it a
274  * fraction rule set.</p>
275  *
276  * <p>Which rule is used to format a number is defined according to one of the following
277  * algorithms: If the rule set is a regular rule set, do the following:
278  *
279  * <ul>
280  *   <li>If the rule set includes a master rule (and the number was passed in as a <tt>double</tt>),
281  *     use the master rule.&nbsp; (If the number being formatted was passed in as a <tt>long</tt>,
282  *     the master rule is ignored.)</li>
283  *   <li>If the number is negative, use the negative-number rule.</li>
284  *   <li>If the number has a fractional part and is greater than 1, use the improper fraction
285  *     rule.</li>
286  *   <li>If the number has a fractional part and is between 0 and 1, use the proper fraction
287  *     rule.</li>
288  *   <li>Binary-search the rule list for the rule with the highest base value less than or equal
289  *     to the number. If that rule has two substitutions, its base value is not an even multiple
290  *     of its divisor, and the number <em>is</em> an even multiple of the rule's divisor, use the
291  *     rule that precedes it in the rule list. Otherwise, use the rule itself.</li>
292  * </ul>
293  *
294  * <p>If the rule set is a fraction rule set, do the following:
295  *
296  * <ul>
297  *   <li>Ignore negative-number and fraction rules.</li>
298  *   <li>For each rule in the list, multiply the number being formatted (which will always be
299  *     between 0 and 1) by the rule's base value. Keep track of the distance between the result
300  *     the nearest integer.</li>
301  *   <li>Use the rule that produced the result closest to zero in the above calculation. In the
302  *     event of a tie or a direct hit, use the first matching rule encountered. (The idea here is
303  *     to try each rule's base value as a possible denominator of a fraction. Whichever
304  *     denominator produces the fraction closest in value to the number being formatted wins.) If
305  *     the rule following the matching rule has the same base value, use it if the numerator of
306  *     the fraction is anything other than 1; if the numerator is 1, use the original matching
307  *     rule. (This is to allow singular and plural forms of the rule text without a lot of extra
308  *     hassle.)</li>
309  * </ul>
310  *
311  * <p>A rule's body consists of a string of characters terminated by a semicolon. The rule
312  * may include zero, one, or two <em>substitution tokens,</em> and a range of text in
313  * brackets. The brackets denote optional text (and may also include one or both
314  * substitutions). The exact meanings of the substitution tokens, and under what conditions
315  * optional text is omitted, depend on the syntax of the substitution token and the context.
316  * The rest of the text in a rule body is literal text that is output when the rule matches
317  * the number being formatted.</p>
318  *
319  * <p>A substitution token begins and ends with a <em>token character.</em> The token
320  * character and the context together specify a mathematical operation to be performed on the
321  * number being formatted. An optional <em>substitution descriptor </em>specifies how the
322  * value resulting from that operation is used to fill in the substitution. The position of
323  * the substitution token in the rule body specifies the location of the resultant text in
324  * the original rule text.</p>
325  *
326  * <p>The meanings of the substitution token characters are as follows:</p>
327  *
328  * <table border="0" width="100%">
329  *   <tr>
330  *     <td width="37"></td>
331  *     <td width="23">&gt;&gt;</td>
332  *     <td width="165" valign="top">in normal rule</td>
333  *     <td>Divide the number by the rule's divisor and format the remainder</td>
334  *   </tr>
335  *   <tr>
336  *     <td width="37"></td>
337  *     <td width="23"></td>
338  *     <td width="165" valign="top">in negative-number rule</td>
339  *     <td>Find the absolute value of the number and format the result</td>
340  *   </tr>
341  *   <tr>
342  *     <td width="37"></td>
343  *     <td width="23"></td>
344  *     <td width="165" valign="top">in fraction or master rule</td>
345  *     <td>Isolate the number's fractional part and format it.</td>
346  *   </tr>
347  *   <tr>
348  *     <td width="37"></td>
349  *     <td width="23"></td>
350  *     <td width="165" valign="top">in rule in fraction rule set</td>
351  *     <td>Not allowed.</td>
352  *   </tr>
353  *   <tr>
354  *     <td width="37"></td>
355  *     <td width="23">&gt;&gt;&gt;</td>
356  *     <td width="165" valign="top">in normal rule</td>
357  *     <td>Divide the number by the rule's divisor and format the remainder,
358  *       but bypass the normal rule-selection process and just use the
359  *       rule that precedes this one in this rule list.</td>
360  *   </tr>
361  *   <tr>
362  *     <td width="37"></td>
363  *     <td width="23"></td>
364  *     <td width="165" valign="top">in all other rules</td>
365  *     <td>Not allowed.</td>
366  *   </tr>
367  *   <tr>
368  *     <td width="37"></td>
369  *     <td width="23">&lt;&lt;</td>
370  *     <td width="165" valign="top">in normal rule</td>
371  *     <td>Divide the number by the rule's divisor and format the quotient</td>
372  *   </tr>
373  *   <tr>
374  *     <td width="37"></td>
375  *     <td width="23"></td>
376  *     <td width="165" valign="top">in negative-number rule</td>
377  *     <td>Not allowed.</td>
378  *   </tr>
379  *   <tr>
380  *     <td width="37"></td>
381  *     <td width="23"></td>
382  *     <td width="165" valign="top">in fraction or master rule</td>
383  *     <td>Isolate the number's integral part and format it.</td>
384  *   </tr>
385  *   <tr>
386  *     <td width="37"></td>
387  *     <td width="23"></td>
388  *     <td width="165" valign="top">in rule in fraction rule set</td>
389  *     <td>Multiply the number by the rule's base value and format the result.</td>
390  *   </tr>
391  *   <tr>
392  *     <td width="37"></td>
393  *     <td width="23">==</td>
394  *     <td width="165" valign="top">in all rule sets</td>
395  *     <td>Format the number unchanged</td>
396  *   </tr>
397  *   <tr>
398  *     <td width="37"></td>
399  *     <td width="23">[]</td>
400  *     <td width="165" valign="top">in normal rule</td>
401  *     <td>Omit the optional text if the number is an even multiple of the rule's divisor</td>
402  *   </tr>
403  *   <tr>
404  *     <td width="37"></td>
405  *     <td width="23"></td>
406  *     <td width="165" valign="top">in negative-number rule</td>
407  *     <td>Not allowed.</td>
408  *   </tr>
409  *   <tr>
410  *     <td width="37"></td>
411  *     <td width="23"></td>
412  *     <td width="165" valign="top">in improper-fraction rule</td>
413  *     <td>Omit the optional text if the number is between 0 and 1 (same as specifying both an
414  *     x.x rule and a 0.x rule)</td>
415  *   </tr>
416  *   <tr>
417  *     <td width="37"></td>
418  *     <td width="23"></td>
419  *     <td width="165" valign="top">in master rule</td>
420  *     <td>Omit the optional text if the number is an integer (same as specifying both an x.x
421  *     rule and an x.0 rule)</td>
422  *   </tr>
423  *   <tr>
424  *     <td width="37"></td>
425  *     <td width="23"></td>
426  *     <td width="165" valign="top">in proper-fraction rule</td>
427  *     <td>Not allowed.</td>
428  *   </tr>
429  *   <tr>
430  *     <td width="37"></td>
431  *     <td width="23"></td>
432  *     <td width="165" valign="top">in rule in fraction rule set</td>
433  *     <td>Omit the optional text if multiplying the number by the rule's base value yields 1.</td>
434  *   </tr>
435  * </table>
436  *
437  * <p>The substitution descriptor (i.e., the text between the token characters) may take one
438  * of three forms:</p>
439  *
440  * <table border="0" width="100%">
441  *   <tr>
442  *     <td width="42"></td>
443  *     <td width="166" valign="top">a rule set name</td>
444  *     <td>Perform the mathematical operation on the number, and format the result using the
445  *     named rule set.</td>
446  *   </tr>
447  *   <tr>
448  *     <td width="42"></td>
449  *     <td width="166" valign="top">a DecimalFormat pattern</td>
450  *     <td>Perform the mathematical operation on the number, and format the result using a
451  *     DecimalFormat with the specified pattern.&nbsp; The pattern must begin with 0 or #.</td>
452  *   </tr>
453  *   <tr>
454  *     <td width="42"></td>
455  *     <td width="166" valign="top">nothing</td>
456  *     <td>Perform the mathematical operation on the number, and format the result using the rule
457  *     set containing the current rule, except:<ul>
458  *       <li>You can't have an empty substitution descriptor with a == substitution.</li>
459  *       <li>If you omit the substitution descriptor in a &gt;&gt; substitution in a fraction rule,
460  *         format the result one digit at a time using the rule set containing the current rule.</li>
461  *       <li>If you omit the substitution descriptor in a &lt;&lt; substitution in a rule in a
462  *         fraction rule set, format the result using the default rule set for this formatter.</li>
463  *     </ul>
464  *     </td>
465  *   </tr>
466  * </table>
467  *
468  * <p>Whitespace is ignored between a rule set name and a rule set body, between a rule
469  * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe,
470  * the apostrophe is ignored, but all text after it becomes significant (this is how you can
471  * have a rule's rule text begin with whitespace). There is no escape function: the semicolon
472  * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set
473  * names. The characters beginning a substitution token are always treated as the beginning
474  * of a substitution token.</p>
475  *
476  * <p>See the resource data and the demo program for annotated examples of real rule sets
477  * using these features.</p>
478  *
479  * @author Richard Gillam
480  * @see NumberFormat
481  * @see DecimalFormat
482  * @stable ICU 2.0
483  */
484 public class RuleBasedNumberFormat extends NumberFormat {
485
486     //-----------------------------------------------------------------------
487     // constants
488     //-----------------------------------------------------------------------
489
490     // Generated by serialver from JDK 1.4.1_01
491     static final long serialVersionUID = -7664252765575395068L;
492
493     /**
494      * Selector code that tells the constructor to create a spellout formatter
495      * @stable ICU 2.0
496      */
497     public static final int SPELLOUT = 1;
498
499     /**
500      * Selector code that tells the constructor to create an ordinal formatter
501      * @stable ICU 2.0
502      */
503     public static final int ORDINAL = 2;
504
505     /**
506      * Selector code that tells the constructor to create a duration formatter
507      * @stable ICU 2.0
508      */
509     public static final int DURATION = 3;
510
511     /**
512      * Selector code that tells the constructor to create a numbering system formatter
513      * @stable ICU 4.2
514      */
515     public static final int NUMBERING_SYSTEM = 4;
516
517     //-----------------------------------------------------------------------
518     // data members
519     //-----------------------------------------------------------------------
520
521     /**
522      * The formatter's rule sets.
523      */
524     private transient NFRuleSet[] ruleSets = null;
525     
526     /**
527      * The formatter's rule sets' descriptions.
528      */
529     private transient String[] ruleSetDescriptions = null;
530     
531     /**
532      * A pointer to the formatter's default rule set.  This is always included
533      * in ruleSets.
534      */
535     private transient NFRuleSet defaultRuleSet = null;
536
537     /**
538      * The formatter's locale.  This is used to create DecimalFormatSymbols and
539      * Collator objects.
540      * @serial
541      */
542     private ULocale locale = null;
543
544     /**
545      * Collator to be used in lenient parsing.  This variable is lazy-evaluated:
546      * the collator is actually created the first time the client does a parse
547      * with lenient-parse mode turned on.
548      */
549     private transient RbnfLenientScannerProvider scannerProvider = null;
550
551     // flag to mark whether we've previously looked for a scanner and failed
552     private transient boolean lookedForScanner;
553
554     /**
555      * The DecimalFormatSymbols object that any DecimalFormat objects this
556      * formatter uses should use.  This variable is lazy-evaluated: it isn't
557      * filled in if the rule set never uses a DecimalFormat pattern.
558      */
559     private transient DecimalFormatSymbols decimalFormatSymbols = null;
560
561     /**
562      * The NumberFormat used when lenient parsing numbers.  This needs to reflect
563      * the locale.  This is lazy-evaluated, like decimalFormatSymbols.  It is
564      * here so it can be shared by different NFSubstitutions.
565      */
566     private transient DecimalFormat decimalFormat = null;
567
568     /**
569      * Flag specifying whether lenient parse mode is on or off.  Off by default.
570      * @serial
571      */
572     private boolean lenientParse = false;
573
574     /**
575      * If the description specifies lenient-parse rules, they're stored here until
576      * the collator is created.
577      */
578     private transient String lenientParseRules;
579
580     /**
581      * If the description specifies post-process rules, they're stored here until
582      * post-processing is required.
583      */
584     private transient String postProcessRules;
585
586     /**
587      * Post processor lazily constructed from the postProcessRules.
588      */
589     private transient RBNFPostProcessor postProcessor;
590
591     /**
592      * Localizations for rule set names.
593      * @serial
594      */
595     private Map<String, String[]> ruleSetDisplayNames;
596
597     /**
598      * The public rule set names;
599      * @serial
600      */
601     private String[] publicRuleSetNames;
602
603     private static final boolean DEBUG  =  ICUDebug.enabled("rbnf");
604
605     //-----------------------------------------------------------------------
606     // constructors
607     //-----------------------------------------------------------------------
608
609     /**
610      * Creates a RuleBasedNumberFormat that behaves according to the description
611      * passed in.  The formatter uses the default <code>FORMAT</code> locale.
612      * @param description A description of the formatter's desired behavior.
613      * See the class documentation for a complete explanation of the description
614      * syntax.
615      * @see Category#FORMAT
616      * @stable ICU 2.0
617      */
618     public RuleBasedNumberFormat(String description) {
619         locale = ULocale.getDefault(Category.FORMAT);
620         init(description, null);
621     }
622
623     /**
624      * Creates a RuleBasedNumberFormat that behaves according to the description
625      * passed in.  The formatter uses the default <code>FORMAT</code> locale.
626      * <p>
627      * The localizations data provides information about the public
628      * rule sets and their localized display names for different
629      * locales. The first element in the list is an array of the names
630      * of the public rule sets.  The first element in this array is
631      * the initial default ruleset.  The remaining elements in the
632      * list are arrays of localizations of the names of the public
633      * rule sets.  Each of these is one longer than the initial array,
634      * with the first String being the ULocale ID, and the remaining
635      * Strings being the localizations of the rule set names, in the
636      * same order as the initial array.
637      * @param description A description of the formatter's desired behavior.
638      * See the class documentation for a complete explanation of the description
639      * syntax.
640      * @param localizations a list of localizations for the rule set
641      * names in the description.
642      * @see Category#FORMAT
643      * @stable ICU 3.2
644      */
645     public RuleBasedNumberFormat(String description, String[][] localizations) {
646         locale = ULocale.getDefault(Category.FORMAT);
647         init(description, localizations);
648     }
649
650     /**
651      * Creates a RuleBasedNumberFormat that behaves according to the description
652      * passed in.  The formatter uses the specified locale to determine the
653      * characters to use when formatting in numerals, and to define equivalences
654      * for lenient parsing.
655      * @param description A description of the formatter's desired behavior.
656      * See the class documentation for a complete explanation of the description
657      * syntax.
658      * @param locale A locale, which governs which characters are used for
659      * formatting values in numerals, and which characters are equivalent in
660      * lenient parsing.
661      * @stable ICU 2.0
662      */
663     public RuleBasedNumberFormat(String description, Locale locale) {
664         this(description, ULocale.forLocale(locale));
665     }
666
667     /**
668      * Creates a RuleBasedNumberFormat that behaves according to the description
669      * passed in.  The formatter uses the specified locale to determine the
670      * characters to use when formatting in numerals, and to define equivalences
671      * for lenient parsing.
672      * @param description A description of the formatter's desired behavior.
673      * See the class documentation for a complete explanation of the description
674      * syntax.
675      * @param locale A locale, which governs which characters are used for
676      * formatting values in numerals, and which characters are equivalent in
677      * lenient parsing.
678      * @stable ICU 3.2
679      */
680     public RuleBasedNumberFormat(String description, ULocale locale) {
681         this.locale = locale;
682         init(description, null);
683     }
684
685     /**
686      * Creates a RuleBasedNumberFormat that behaves according to the description
687      * passed in.  The formatter uses the specified locale to determine the
688      * characters to use when formatting in numerals, and to define equivalences
689      * for lenient parsing.
690      * <p>
691      * The localizations data provides information about the public
692      * rule sets and their localized display names for different
693      * locales. The first element in the list is an array of the names
694      * of the public rule sets.  The first element in this array is
695      * the initial default ruleset.  The remaining elements in the
696      * list are arrays of localizations of the names of the public
697      * rule sets.  Each of these is one longer than the initial array,
698      * with the first String being the ULocale ID, and the remaining
699      * Strings being the localizations of the rule set names, in the
700      * same order as the initial array.
701      * @param description A description of the formatter's desired behavior.
702      * See the class documentation for a complete explanation of the description
703      * syntax.
704      * @param localizations a list of localizations for the rule set names in the description.
705      * @param locale A ulocale that governs which characters are used for
706      * formatting values in numerals, and determines which characters are equivalent in
707      * lenient parsing.
708      * @stable ICU 3.2
709      */
710     public RuleBasedNumberFormat(String description, String[][] localizations, ULocale locale) {
711         this.locale = locale;
712         init(description, localizations);
713     }
714
715     /**
716      * Creates a RuleBasedNumberFormat from a predefined description.  The selector
717      * code choosed among three possible predefined formats: spellout, ordinal,
718      * and duration.
719      * @param locale The locale for the formatter.
720      * @param format A selector code specifying which kind of formatter to create for that
721      * locale.  There are three legal values: SPELLOUT, which creates a formatter that
722      * spells out a value in words in the desired language, ORDINAL, which attaches
723      * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
724      * and DURATION, which formats a duration in seconds as hours, minutes, and seconds.
725      * @stable ICU 2.0
726      */
727     public RuleBasedNumberFormat(Locale locale, int format) {
728         this(ULocale.forLocale(locale), format);
729     }
730
731     /**
732      * Creates a RuleBasedNumberFormat from a predefined description.  The selector
733      * code choosed among three possible predefined formats: spellout, ordinal,
734      * and duration.
735      * @param locale The locale for the formatter.
736      * @param format A selector code specifying which kind of formatter to create for that
737      * locale.  There are four legal values: SPELLOUT, which creates a formatter that
738      * spells out a value in words in the desired language, ORDINAL, which attaches
739      * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
740      * DURATION, which formats a duration in seconds as hours, minutes, and seconds, and
741      * NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering
742      * systems such as the Hebrew numbering system, or for Roman numerals, etc..
743      * @stable ICU 3.2
744      */
745     public RuleBasedNumberFormat(ULocale locale, int format) {
746         this.locale = locale;
747
748         ICUResourceBundle bundle = (ICUResourceBundle)UResourceBundle.
749             getBundleInstance(ICUResourceBundle.ICU_RBNF_BASE_NAME, locale);
750
751         // TODO: determine correct actual/valid locale.  Note ambiguity
752         // here -- do actual/valid refer to pattern, DecimalFormatSymbols,
753         // or Collator?
754         ULocale uloc = bundle.getULocale();
755         setLocale(uloc, uloc);
756
757         String description = "";
758         String[][] localizations = null;
759
760         try {
761             // For backwards compatability - If we have a pre-4.2 style RBNF resource, attempt to read it.
762             description = bundle.getString(rulenames[format-1]);
763         }
764         catch (MissingResourceException e) {
765             try {
766                 ICUResourceBundle rules = bundle.getWithFallback("RBNFRules/"+rulenames[format-1]);
767                 UResourceBundleIterator it = rules.getIterator();
768                 while (it.hasNext()) {
769                    description = description.concat(it.nextString());
770                 }
771             }
772             catch (MissingResourceException e1) {
773             }
774         }
775
776         try {
777             UResourceBundle locb = bundle.get(locnames[format-1]);
778             localizations = new String[locb.getSize()][];
779             for (int i = 0; i < localizations.length; ++i) {
780                 localizations[i] = locb.get(i).getStringArray();
781             }
782         }
783         catch (MissingResourceException e) {
784             // might have description and no localizations, or no description...
785         }
786
787         init(description, localizations);
788
789     }
790
791     private static final String[] rulenames = {
792         "SpelloutRules", "OrdinalRules", "DurationRules", "NumberingSystemRules",
793     };
794     private static final String[] locnames = {
795         "SpelloutLocalizations", "OrdinalLocalizations", "DurationLocalizations", "NumberingSystemLocalizations",
796     };
797
798     /**
799      * Creates a RuleBasedNumberFormat from a predefined description.  Uses the
800      * default <code>FORMAT</code> locale.
801      * @param format A selector code specifying which kind of formatter to create.
802      * There are three legal values: SPELLOUT, which creates a formatter that spells
803      * out a value in words in the default locale's langyage, ORDINAL, which attaches
804      * an ordinal suffix from the default locale's language to a numeral, and
805      * DURATION, which formats a duration in seconds as hours, minutes, and seconds.
806      * or NUMBERING_SYSTEM, which is used for alternate numbering systems such as Hebrew.
807      * @see Category#FORMAT
808      * @stable ICU 2.0
809      */
810     public RuleBasedNumberFormat(int format) {
811         this(ULocale.getDefault(Category.FORMAT), format);
812     }
813
814     //-----------------------------------------------------------------------
815     // boilerplate
816     //-----------------------------------------------------------------------
817
818     /**
819      * Duplicates this formatter.
820      * @return A RuleBasedNumberFormat that is equal to this one.
821      * @stable ICU 2.0
822      */
823     public Object clone() {
824         return super.clone();
825     }
826
827     /**
828      * Tests two RuleBasedNumberFormats for equality.
829      * @param that The formatter to compare against this one.
830      * @return true if the two formatters have identical behavior.
831      * @stable ICU 2.0
832      */
833     public boolean equals(Object that) {
834         // if the other object isn't a RuleBasedNumberFormat, that's
835         // all we need to know
836         if (!(that instanceof RuleBasedNumberFormat)) {
837             return false;
838         } else {
839             // cast the other object's pointer to a pointer to a
840             // RuleBasedNumberFormat
841             RuleBasedNumberFormat that2 = (RuleBasedNumberFormat)that;
842
843             // compare their locales and lenient-parse modes
844             if (!locale.equals(that2.locale) || lenientParse != that2.lenientParse) {
845                 return false;
846             }
847
848             // if that succeeds, then compare their rule set lists
849             if (ruleSets.length != that2.ruleSets.length) {
850                 return false;
851             }
852             for (int i = 0; i < ruleSets.length; i++) {
853                 if (!ruleSets[i].equals(that2.ruleSets[i])) {
854                     return false;
855                 }
856             }
857
858             return true;
859         }
860     }
861     
862     /**
863      * Mock implementation of hashCode(). This implementation always returns a constant
864      * value. When Java assertion is enabled, this method triggers an assertion failure.
865      * @internal
866      * @deprecated This API is ICU internal only.
867      */
868     public int hashCode() {
869         return super.hashCode();
870     }
871
872     /**
873      * Generates a textual description of this formatter.
874      * @return a String containing a rule set that will produce a RuleBasedNumberFormat
875      * with identical behavior to this one.  This won't necessarily be identical
876      * to the rule set description that was originally passed in, but will produce
877      * the same result.
878      * @stable ICU 2.0
879      */
880     public String toString() {
881
882         // accumulate the descriptions of all the rule sets in a
883         // StringBuffer, then cast it to a String and return it
884         StringBuilder result = new StringBuilder();
885         for (int i = 0; i < ruleSets.length; i++) {
886             result.append(ruleSets[i].toString());
887         }
888         return result.toString();
889     }
890
891     /**
892      * Writes this object to a stream.
893      * @param out The stream to write to.
894      */
895     private void writeObject(java.io.ObjectOutputStream out)
896         throws java.io.IOException {
897         // we just write the textual description to the stream, so we
898         // have an implementation-independent streaming format
899         out.writeUTF(this.toString());
900         out.writeObject(this.locale);
901     }
902
903     /**
904      * Reads this object in from a stream.
905      * @param in The stream to read from.
906      */
907     private void readObject(java.io.ObjectInputStream in)
908         throws java.io.IOException {
909
910         // read the description in from the stream
911         String description = in.readUTF();
912         ULocale loc;
913
914         try {
915             loc = (ULocale) in.readObject();
916         } catch (Exception e) {
917             loc = ULocale.getDefault(Category.FORMAT);
918         }
919
920         // build a brand-new RuleBasedNumberFormat from the description,
921         // then steal its substructure.  This object's substructure and
922         // the temporary RuleBasedNumberFormat drop on the floor and
923         // get swept up by the garbage collector
924         RuleBasedNumberFormat temp = new RuleBasedNumberFormat(description, loc);
925         ruleSets = temp.ruleSets;
926         defaultRuleSet = temp.defaultRuleSet;
927         publicRuleSetNames = temp.publicRuleSetNames;
928         decimalFormatSymbols = temp.decimalFormatSymbols;
929         decimalFormat = temp.decimalFormat;
930         locale = temp.locale;
931     }
932
933
934     //-----------------------------------------------------------------------
935     // public API functions
936     //-----------------------------------------------------------------------
937
938     /**
939      * Returns a list of the names of all of this formatter's public rule sets.
940      * @return A list of the names of all of this formatter's public rule sets.
941      * @stable ICU 2.0
942      */
943     public String[] getRuleSetNames() {
944         return publicRuleSetNames.clone();
945     }
946
947     /**
948      * Return a list of locales for which there are locale-specific display names
949      * for the rule sets in this formatter.  If there are no localized display names, return null.
950      * @return an array of the ulocales for which there is rule set display name information
951      * @stable ICU 3.2
952      */
953     public ULocale[] getRuleSetDisplayNameLocales() {
954         if (ruleSetDisplayNames != null) {
955             Set<String> s = ruleSetDisplayNames.keySet();
956             String[] locales = s.toArray(new String[s.size()]);
957             Arrays.sort(locales, String.CASE_INSENSITIVE_ORDER);
958             ULocale[] result = new ULocale[locales.length];
959             for (int i = 0; i < locales.length; ++i) {
960                 result[i] = new ULocale(locales[i]);
961             }
962             return result;
963         }
964         return null;
965     }
966
967     private String[] getNameListForLocale(ULocale loc) {
968         if (loc != null && ruleSetDisplayNames != null) {
969             String[] localeNames = { loc.getBaseName(), ULocale.getDefault(Category.DISPLAY).getBaseName() };
970             for (int i = 0; i < localeNames.length; ++i) {
971                 String lname = localeNames[i];
972                 while (lname.length() > 0) {
973                     String[] names = ruleSetDisplayNames.get(lname);
974                     if (names != null) {
975                         return names;
976                     }
977                     lname = ULocale.getFallback(lname);
978                 }
979             }
980         }
981         return null;
982     }
983
984     /**
985      * Return the rule set display names for the provided locale.  These are in the same order
986      * as those returned by getRuleSetNames.  The locale is matched against the locales for
987      * which there is display name data, using normal fallback rules.  If no locale matches,
988      * the default display names are returned.  (These are the internal rule set names minus
989      * the leading '%'.)
990      * @return an array of the locales that have display name information
991      * @see #getRuleSetNames
992      * @stable ICU 3.2
993      */
994     public String[] getRuleSetDisplayNames(ULocale loc) {
995         String[] names = getNameListForLocale(loc);
996         if (names != null) {
997             return names.clone();
998         }
999         names = getRuleSetNames();
1000         for (int i = 0; i < names.length; ++i) {
1001             names[i] = names[i].substring(1);
1002         }
1003         return names;
1004     }
1005
1006     /**
1007      * Return the rule set display names for the current default <code>DISPLAY</code> locale.
1008      * @return an array of the display names
1009      * @see #getRuleSetDisplayNames(ULocale)
1010      * @see Category#DISPLAY
1011      * @stable ICU 3.2
1012      */
1013     public String[] getRuleSetDisplayNames() {
1014         return getRuleSetDisplayNames(ULocale.getDefault(Category.DISPLAY));
1015     }
1016
1017     /**
1018      * Return the rule set display name for the provided rule set and locale.
1019      * The locale is matched against the locales for which there is display name data, using
1020      * normal fallback rules.  If no locale matches, the default display name is returned.
1021      * @return the display name for the rule set
1022      * @see #getRuleSetDisplayNames
1023      * @throws IllegalArgumentException if ruleSetName is not a valid rule set name for this format
1024      * @stable ICU 3.2
1025      */
1026     public String getRuleSetDisplayName(String ruleSetName, ULocale loc) {
1027         String[] rsnames = publicRuleSetNames;
1028         for (int ix = 0; ix < rsnames.length; ++ix) {
1029             if (rsnames[ix].equals(ruleSetName)) {
1030                 String[] names = getNameListForLocale(loc);
1031                 if (names != null) {
1032                     return names[ix];
1033                 }
1034                 return rsnames[ix].substring(1);
1035             }
1036         }
1037         throw new IllegalArgumentException("unrecognized rule set name: " + ruleSetName);
1038     }
1039
1040     /**
1041      * Return the rule set display name for the provided rule set in the current default <code>DISPLAY</code> locale.
1042      * @return the display name for the rule set
1043      * @see #getRuleSetDisplayName(String,ULocale)
1044      * @see Category#DISPLAY
1045      * @stable ICU 3.2
1046      */
1047     public String getRuleSetDisplayName(String ruleSetName) {
1048         return getRuleSetDisplayName(ruleSetName, ULocale.getDefault(Category.DISPLAY));
1049     }
1050
1051     /**
1052      * Formats the specified number according to the specified rule set.
1053      * @param number The number to format.
1054      * @param ruleSet The name of the rule set to format the number with.
1055      * This must be the name of a valid public rule set for this formatter.
1056      * @return A textual representation of the number.
1057      * @stable ICU 2.0
1058      */
1059     public String format(double number, String ruleSet) throws IllegalArgumentException {
1060         if (ruleSet.startsWith("%%")) {
1061             throw new IllegalArgumentException("Can't use internal rule set");
1062         }
1063         return format(number, findRuleSet(ruleSet));
1064     }
1065
1066     /**
1067      * Formats the specified number according to the specified rule set.
1068      * (If the specified rule set specifies a master ["x.0"] rule, this function
1069      * ignores it.  Convert the number to a double first if you ned it.)  This
1070      * function preserves all the precision in the long-- it doesn't convert it
1071      * to a double.
1072      * @param number The number to format.
1073      * @param ruleSet The name of the rule set to format the number with.
1074      * This must be the name of a valid public rule set for this formatter.
1075      * @return A textual representation of the number.
1076      * @stable ICU 2.0
1077      */
1078     public String format(long number, String ruleSet) throws IllegalArgumentException {
1079         if (ruleSet.startsWith("%%")) {
1080             throw new IllegalArgumentException("Can't use internal rule set");
1081         }
1082         return format(number, findRuleSet(ruleSet));
1083     }
1084
1085     /**
1086      * Formats the specified number using the formatter's default rule set.
1087      * (The default rule set is the last public rule set defined in the description.)
1088      * @param number The number to format.
1089      * @param toAppendTo A StringBuffer that the result should be appended to.
1090      * @param ignore This function doesn't examine or update the field position.
1091      * @return toAppendTo
1092      * @stable ICU 2.0
1093      */
1094     public StringBuffer format(double number,
1095                                StringBuffer toAppendTo,
1096                                FieldPosition ignore) {
1097         // this is one of the inherited format() methods.  Since it doesn't
1098         // have a way to select the rule set to use, it just uses the
1099         // default one
1100         toAppendTo.append(format(number, defaultRuleSet));
1101         return toAppendTo;
1102     }
1103
1104     /**
1105      * Formats the specified number using the formatter's default rule set.
1106      * (The default rule set is the last public rule set defined in the description.)
1107      * (If the specified rule set specifies a master ["x.0"] rule, this function
1108      * ignores it.  Convert the number to a double first if you ned it.)  This
1109      * function preserves all the precision in the long-- it doesn't convert it
1110      * to a double.
1111      * @param number The number to format.
1112      * @param toAppendTo A StringBuffer that the result should be appended to.
1113      * @param ignore This function doesn't examine or update the field position.
1114      * @return toAppendTo
1115      * @stable ICU 2.0
1116      */
1117     public StringBuffer format(long number,
1118                                StringBuffer toAppendTo,
1119                                FieldPosition ignore) {
1120         // this is one of the inherited format() methods.  Since it doesn't
1121         // have a way to select the rule set to use, it just uses the
1122         // default one
1123         toAppendTo.append(format(number, defaultRuleSet));
1124         return toAppendTo;
1125     }
1126
1127     /**
1128      * <strong><font face=helvetica color=red>NEW</font></strong>
1129      * Implement com.ibm.icu.text.NumberFormat:
1130      * Format a BigInteger.
1131      * @stable ICU 2.0
1132      */
1133     public StringBuffer format(BigInteger number,
1134                                StringBuffer toAppendTo,
1135                                FieldPosition pos) {
1136         return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
1137     }
1138
1139     /**
1140      * <strong><font face=helvetica color=red>NEW</font></strong>
1141      * Implement com.ibm.icu.text.NumberFormat:
1142      * Format a BigDecimal.
1143      * @stable ICU 2.0
1144      */
1145     public StringBuffer format(java.math.BigDecimal number,
1146                                StringBuffer toAppendTo,
1147                                FieldPosition pos) {
1148         return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
1149     }
1150
1151     /**
1152      * <strong><font face=helvetica color=red>NEW</font></strong>
1153      * Implement com.ibm.icu.text.NumberFormat:
1154      * Format a BigDecimal.
1155      * @stable ICU 2.0
1156      */
1157     public StringBuffer format(com.ibm.icu.math.BigDecimal number,
1158                                StringBuffer toAppendTo,
1159                                FieldPosition pos) {
1160         // TEMPORARY:
1161         return format(number.doubleValue(), toAppendTo, pos);
1162     }
1163
1164     /**
1165      * Parses the specfied string, beginning at the specified position, according
1166      * to this formatter's rules.  This will match the string against all of the
1167      * formatter's public rule sets and return the value corresponding to the longest
1168      * parseable substring.  This function's behavior is affected by the lenient
1169      * parse mode.
1170      * @param text The string to parse
1171      * @param parsePosition On entry, contains the position of the first character
1172      * in "text" to examine.  On exit, has been updated to contain the position
1173      * of the first character in "text" that wasn't consumed by the parse.
1174      * @return The number that corresponds to the parsed text.  This will be an
1175      * instance of either Long or Double, depending on whether the result has a
1176      * fractional part.
1177      * @see #setLenientParseMode
1178      * @stable ICU 2.0
1179      */
1180     public Number parse(String text, ParsePosition parsePosition) {
1181
1182         // parsePosition tells us where to start parsing.  We copy the
1183         // text in the string from here to the end inro a new string,
1184         // and create a new ParsePosition and result variable to use
1185         // for the duration of the parse operation
1186         String workingText = text.substring(parsePosition.getIndex());
1187         ParsePosition workingPos = new ParsePosition(0);
1188         Number tempResult = null;
1189
1190         // keep track of the largest number of characters consumed in
1191         // the various trials, and the result that corresponds to it
1192         Number result = Long.valueOf(0);
1193         ParsePosition highWaterMark = new ParsePosition(workingPos.getIndex());
1194
1195         // iterate over the public rule sets (beginning with the default one)
1196         // and try parsing the text with each of them.  Keep track of which
1197         // one consumes the most characters: that's the one that determines
1198         // the result we return
1199         for (int i = ruleSets.length - 1; i >= 0; i--) {
1200             // skip private or unparseable rule sets
1201             if (!ruleSets[i].isPublic() || !ruleSets[i].isParseable()) {
1202                 continue;
1203             }
1204
1205             // try parsing the string with the rule set.  If it gets past the
1206             // high-water mark, update the high-water mark and the result
1207             tempResult = ruleSets[i].parse(workingText, workingPos, Double.MAX_VALUE);
1208             if (workingPos.getIndex() > highWaterMark.getIndex()) {
1209                 result = tempResult;
1210                 highWaterMark.setIndex(workingPos.getIndex());
1211             }
1212             // commented out because this API on ParsePosition doesn't exist in 1.1.x
1213             //            if (workingPos.getErrorIndex() > highWaterMark.getErrorIndex()) {
1214             //                highWaterMark.setErrorIndex(workingPos.getErrorIndex());
1215             //            }
1216
1217             // if we manage to use up all the characters in the string,
1218             // we don't have to try any more rule sets
1219             if (highWaterMark.getIndex() == workingText.length()) {
1220                 break;
1221             }
1222
1223             // otherwise, reset our internal parse position to the
1224             // beginning and try again with the next rule set
1225             workingPos.setIndex(0);
1226         }
1227
1228         // add the high water mark to our original parse position and
1229         // return the result
1230         parsePosition.setIndex(parsePosition.getIndex() + highWaterMark.getIndex());
1231         // commented out because this API on ParsePosition doesn't exist in 1.1.x
1232         //        if (highWaterMark.getIndex() == 0) {
1233         //            parsePosition.setErrorIndex(parsePosition.getIndex() + highWaterMark.getErrorIndex());
1234         //        }
1235         return result;
1236     }
1237
1238     /**
1239      * Turns lenient parse mode on and off.
1240      *
1241      * When in lenient parse mode, the formatter uses an RbnfLenientScanner
1242      * for parsing the text.  Lenient parsing is only in effect if a scanner
1243      * is set.  If a provider is not set, and this is used for parsing,
1244      * a default scanner <code>RbnfLenientScannerProviderImpl</code> will be set if
1245      * it is available on the classpath.  Otherwise this will have no effect.
1246      *
1247      * @param enabled If true, turns lenient-parse mode on; if false, turns it off.
1248      * @see RbnfLenientScanner
1249      * @see RbnfLenientScannerProvider
1250      * @stable ICU 2.0
1251      */
1252     public void setLenientParseMode(boolean enabled) {
1253         lenientParse = enabled;
1254     }
1255
1256     /**
1257      * Returns true if lenient-parse mode is turned on.  Lenient parsing is off
1258      * by default.
1259      * @return true if lenient-parse mode is turned on.
1260      * @see #setLenientParseMode
1261      * @stable ICU 2.0
1262      */
1263     public boolean lenientParseEnabled() {
1264         return lenientParse;
1265     }
1266
1267     /**
1268      * Sets the provider for the lenient scanner.  If this has not been set, 
1269      * {@link #setLenientParseMode}
1270      * has no effect.  This is necessary to decouple collation from format code.
1271      * @param scannerProvider the provider
1272      * @see #setLenientParseMode
1273      * @see #getLenientScannerProvider
1274      * @stable ICU 4.4
1275      */
1276     public void setLenientScannerProvider(RbnfLenientScannerProvider scannerProvider) {
1277         this.scannerProvider = scannerProvider;
1278     }
1279
1280     /**
1281      * Returns the lenient scanner provider.  If none was set, and lenient parse is
1282      * enabled, this will attempt to instantiate a default scanner, setting it if
1283      * it was successful.  Otherwise this returns false.
1284      *
1285      * @see #setLenientScannerProvider
1286      * @stable ICU 4.4
1287      */
1288     public RbnfLenientScannerProvider getLenientScannerProvider() {
1289         // there's a potential race condition if two threads try to set/get the scanner at
1290         // the same time, but you get what you get, and you shouldn't be using this from
1291         // multiple threads anyway.
1292         if (scannerProvider == null && lenientParse && !lookedForScanner) {
1293             ///CLOVER:OFF
1294             try {
1295                 lookedForScanner = true;
1296                 Class<?> cls = Class.forName("com.ibm.icu.text.RbnfScannerProviderImpl");
1297                 RbnfLenientScannerProvider provider = (RbnfLenientScannerProvider)cls.newInstance();
1298                 setLenientScannerProvider(provider);
1299             }
1300             catch (Exception e) {
1301                 // any failure, we just ignore and return null
1302             }
1303             ///CLOVER:ON
1304         }
1305
1306         return scannerProvider;
1307     }
1308
1309     /**
1310      * Override the default rule set to use.  If ruleSetName is null, reset
1311      * to the initial default rule set.
1312      * @param ruleSetName the name of the rule set, or null to reset the initial default.
1313      * @throws IllegalArgumentException if ruleSetName is not the name of a public ruleset.
1314      * @stable ICU 2.0
1315      */
1316     public void setDefaultRuleSet(String ruleSetName) {
1317         if (ruleSetName == null) {
1318             if (publicRuleSetNames.length > 0) {
1319                 defaultRuleSet = findRuleSet(publicRuleSetNames[0]);
1320             } else {
1321                 defaultRuleSet = null;
1322                 int n = ruleSets.length;
1323                 while (--n >= 0) {
1324                    String currentName = ruleSets[n].getName();
1325                    if (currentName.equals("%spellout-numbering") ||
1326                        currentName.equals("%digits-ordinal") ||
1327                        currentName.equals("%duration")) {
1328
1329                        defaultRuleSet = ruleSets[n];
1330                        return;
1331                    }
1332                 }
1333
1334                 n = ruleSets.length;
1335                 while (--n >= 0) {
1336                     if (ruleSets[n].isPublic()) {
1337                         defaultRuleSet = ruleSets[n];
1338                         break;
1339                     }
1340                 }
1341             }
1342         } else if (ruleSetName.startsWith("%%")) {
1343             throw new IllegalArgumentException("cannot use private rule set: " + ruleSetName);
1344         } else {
1345             defaultRuleSet = findRuleSet(ruleSetName);
1346         }
1347     }
1348
1349     /**
1350      * Return the name of the current default rule set.
1351      * @return the name of the current default rule set, if it is public, else the empty string.
1352      * @stable ICU 3.0
1353      */
1354     public String getDefaultRuleSetName() {
1355         if (defaultRuleSet != null && defaultRuleSet.isPublic()) {
1356             return defaultRuleSet.getName();
1357         }
1358         return "";
1359     }
1360     
1361     /**
1362      * Sets the decimal format symbols used by this formatter. The formatter uses a copy of the
1363      * provided symbols.
1364      * 
1365      * @param newSymbols desired DecimalFormatSymbols
1366      * @see DecimalFormatSymbols
1367      * @stable ICU 49
1368      */
1369     public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) {
1370         if (newSymbols != null) {
1371             decimalFormatSymbols = (DecimalFormatSymbols) newSymbols.clone();
1372             if (decimalFormat != null) {
1373                 decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
1374             }
1375             
1376             // Apply the new decimalFormatSymbols by reparsing the rulesets
1377             for (int i = 0; i < ruleSets.length; i++) {
1378                 ruleSets[i].parseRules(ruleSetDescriptions[i], this);
1379             }
1380         }
1381     }
1382
1383     //-----------------------------------------------------------------------
1384     // package-internal API
1385     //-----------------------------------------------------------------------
1386
1387     /**
1388      * Returns a reference to the formatter's default rule set.  The default
1389      * rule set is the last public rule set in the description, or the one
1390      * most recently set by setDefaultRuleSet.
1391      * @return The formatter's default rule set.
1392      */
1393     NFRuleSet getDefaultRuleSet() {
1394         return defaultRuleSet;
1395     }
1396
1397     /**
1398      * Returns the scanner to use for lenient parsing.  The scanner is
1399      * provided by the provider.
1400      * @return The collator to use for lenient parsing, or null if lenient parsing
1401      * is turned off.
1402      */
1403     RbnfLenientScanner getLenientScanner() {
1404         if (lenientParse) {
1405             RbnfLenientScannerProvider provider = getLenientScannerProvider();
1406             if (provider != null) {
1407                 return provider.get(locale, lenientParseRules);
1408             }
1409         }
1410         return null;
1411     }
1412
1413     /**
1414      * Returns the DecimalFormatSymbols object that should be used by all DecimalFormat
1415      * instances owned by this formatter.  This object is lazily created: this function
1416      * creates it the first time it's called.
1417      * @return The DecimalFormatSymbols object that should be used by all DecimalFormat
1418      * instances owned by this formatter.
1419      */
1420     DecimalFormatSymbols getDecimalFormatSymbols() {
1421         // lazy-evaluate the DecimalFormatSymbols object.  This object
1422         // is shared by all DecimalFormat instances belonging to this
1423         // formatter
1424         if (decimalFormatSymbols == null) {
1425             decimalFormatSymbols = new DecimalFormatSymbols(locale);
1426         }
1427         return decimalFormatSymbols;
1428     }
1429
1430     DecimalFormat getDecimalFormat() {
1431         if (decimalFormat == null) {
1432             decimalFormat = (DecimalFormat)NumberFormat.getInstance(locale);
1433             
1434             if (decimalFormatSymbols != null) {
1435                 decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
1436             }
1437         }
1438         return decimalFormat;
1439     }
1440
1441     //-----------------------------------------------------------------------
1442     // construction implementation
1443     //-----------------------------------------------------------------------
1444
1445     /**
1446      * This extracts the special information from the rule sets before the
1447      * main parsing starts.  Extra whitespace must have already been removed
1448      * from the description.  If found, the special information is removed from the
1449      * description and returned, otherwise the description is unchanged and null
1450      * is returned.  Note: the trailing semicolon at the end of the special
1451      * rules is stripped.
1452      * @param description the rbnf description with extra whitespace removed
1453      * @param specialName the name of the special rule text to extract
1454      * @return the special rule text, or null if the rule was not found
1455      */
1456     private String extractSpecial(StringBuilder description, String specialName) {
1457         String result = null;
1458         int lp = description.indexOf(specialName);
1459         if (lp != -1) {
1460             // we've got to make sure we're not in the middle of a rule
1461             // (where specialName would actually get treated as
1462             // rule text)
1463             if (lp == 0 || description.charAt(lp - 1) == ';') {
1464                 // locate the beginning and end of the actual special
1465                 // rules (there may be whitespace between the name and
1466                 // the first token in the description)
1467                 int lpEnd = description.indexOf(";%", lp);
1468
1469                 if (lpEnd == -1) {
1470                     lpEnd = description.length() - 1; // later we add 1 back to get the '%'
1471                 }
1472                 int lpStart = lp + specialName.length();
1473                 while (lpStart < lpEnd &&
1474                        PatternProps.isWhiteSpace(description.charAt(lpStart))) {
1475                     ++lpStart;
1476                 }
1477
1478                 // copy out the special rules
1479                 result = description.substring(lpStart, lpEnd);
1480
1481                 // remove the special rule from the description
1482                 description.delete(lp, lpEnd+1); // delete the semicolon but not the '%'
1483             }
1484         }
1485         return result;
1486     }
1487
1488     /**
1489      * This function parses the description and uses it to build all of
1490      * internal data structures that the formatter uses to do formatting
1491      * @param description The description of the formatter's desired behavior.
1492      * This is either passed in by the caller or loaded out of a resource
1493      * by one of the constructors, and is in the description format specified
1494      * in the class docs.
1495      */
1496     private void init(String description, String[][] localizations) {
1497         initLocalizations(localizations);
1498
1499         // start by stripping the trailing whitespace from all the rules
1500         // (this is all the whitespace follwing each semicolon in the
1501         // description).  This allows us to look for rule-set boundaries
1502         // by searching for ";%" without having to worry about whitespace
1503         // between the ; and the %
1504         StringBuilder descBuf = stripWhitespace(description);
1505
1506         // check to see if there's a set of lenient-parse rules.  If there
1507         // is, pull them out into our temporary holding place for them,
1508         // and delete them from the description before the real desciption-
1509         // parsing code sees them
1510
1511         lenientParseRules = extractSpecial(descBuf, "%%lenient-parse:");
1512         postProcessRules = extractSpecial(descBuf, "%%post-process:");
1513
1514         // pre-flight parsing the description and count the number of
1515         // rule sets (";%" marks the end of one rule set and the beginning
1516         // of the next)
1517         int numRuleSets = 0;
1518         for (int p = descBuf.indexOf(";%"); p != -1; p = descBuf.indexOf(";%", p)) {
1519             ++numRuleSets;
1520             ++p;
1521         }
1522         ++numRuleSets;
1523
1524         // our rule list is an array of the apprpriate size
1525         ruleSets = new NFRuleSet[numRuleSets];
1526
1527         // divide up the descriptions into individual rule-set descriptions
1528         // and store them in a temporary array.  At each step, we also
1529         // new up a rule set, but all this does is initialize its name
1530         // and remove it from its description.  We can't actually parse
1531         // the rest of the descriptions and finish initializing everything
1532         // because we have to know the names and locations of all the rule
1533         // sets before we can actually set everything up
1534         ruleSetDescriptions = new String[numRuleSets];
1535
1536         int curRuleSet = 0;
1537         int start = 0;
1538         for (int p = descBuf.indexOf(";%"); p != -1; p = descBuf.indexOf(";%", start)) {
1539             ruleSetDescriptions[curRuleSet] = descBuf.substring(start, p + 1);
1540             ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
1541             ++curRuleSet;
1542             start = p + 1;
1543         }
1544         ruleSetDescriptions[curRuleSet] = descBuf.substring(start);
1545         ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
1546
1547         // now we can take note of the formatter's default rule set, which
1548         // is the last public rule set in the description (it's the last
1549         // rather than the first so that a user can create a new formatter
1550         // from an existing formatter and change its default bevhaior just
1551         // by appending more rule sets to the end)
1552
1553         // {dlf} Initialization of a fraction rule set requires the default rule
1554         // set to be known.  For purposes of initialization, this is always the
1555         // last public rule set, no matter what the localization data says.
1556
1557         // Set the default ruleset to the last public ruleset, unless one of the predefined
1558         // ruleset names %spellout-numbering, %digits-ordinal, or %duration is found
1559
1560         boolean defaultNameFound = false;
1561         int n = ruleSets.length;
1562         defaultRuleSet = ruleSets[ruleSets.length - 1];
1563
1564         while (--n >= 0) {
1565             String currentName = ruleSets[n].getName();
1566             if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {
1567                 defaultRuleSet = ruleSets[n];
1568                 defaultNameFound = true;
1569                 break;
1570             }
1571         }
1572
1573         if ( !defaultNameFound ) {
1574             for (int i = ruleSets.length - 1; i >= 0; --i) {
1575                 if (!ruleSets[i].getName().startsWith("%%")) {
1576                     defaultRuleSet = ruleSets[i];
1577                     break;
1578                 }
1579             }
1580         }
1581
1582         // finally, we can go back through the temporary descriptions
1583         // list and finish seting up the substructure
1584         for (int i = 0; i < ruleSets.length; i++) {
1585             ruleSets[i].parseRules(ruleSetDescriptions[i], this);
1586         }
1587
1588         // Now that the rules are initialized, the 'real' default rule
1589         // set can be adjusted by the localization data.
1590
1591         // count the number of public rule sets
1592         // (public rule sets have names that begin with % instead of %%)
1593         int publicRuleSetCount = 0;
1594         for (int i = 0; i < ruleSets.length; i++) {
1595             if (!ruleSets[i].getName().startsWith("%%")) {
1596                 ++publicRuleSetCount;
1597             }
1598         }
1599
1600         // prepare an array of the proper size and copy the names into it
1601         String[] publicRuleSetTemp = new String[publicRuleSetCount];
1602         publicRuleSetCount = 0;
1603         for (int i = ruleSets.length - 1; i >= 0; i--) {
1604             if (!ruleSets[i].getName().startsWith("%%")) {
1605                 publicRuleSetTemp[publicRuleSetCount++] = ruleSets[i].getName();
1606             }
1607         }
1608
1609         if (publicRuleSetNames != null) {
1610             // confirm the names, if any aren't in the rules, that's an error
1611             // it is ok if the rules contain public rule sets that are not in this list
1612             loop: for (int i = 0; i < publicRuleSetNames.length; ++i) {
1613                 String name = publicRuleSetNames[i];
1614                 for (int j = 0; j < publicRuleSetTemp.length; ++j) {
1615                     if (name.equals(publicRuleSetTemp[j])) {
1616                         continue loop;
1617                     }
1618                 }
1619                 throw new IllegalArgumentException("did not find public rule set: " + name);
1620             }
1621
1622             defaultRuleSet = findRuleSet(publicRuleSetNames[0]); // might be different
1623         } else {
1624             publicRuleSetNames = publicRuleSetTemp;
1625         }
1626     }
1627
1628     /**
1629      * Take the localizations array and create a Map from the locale strings to
1630      * the localization arrays.
1631      */
1632     private void initLocalizations(String[][] localizations) {
1633         if (localizations != null) {
1634             publicRuleSetNames = localizations[0].clone();
1635
1636             Map<String, String[]> m = new HashMap<String, String[]>();
1637             for (int i = 1; i < localizations.length; ++i) {
1638                 String[] data = localizations[i];
1639                 String loc = data[0];
1640                 String[] names = new String[data.length-1];
1641                 if (names.length != publicRuleSetNames.length) {
1642                     throw new IllegalArgumentException("public name length: " + publicRuleSetNames.length +
1643                                                        " != localized names[" + i + "] length: " + names.length);
1644                 }
1645                 System.arraycopy(data, 1, names, 0, names.length);
1646                 m.put(loc, names);
1647             }
1648
1649             if (!m.isEmpty()) {
1650                 ruleSetDisplayNames = m;
1651             }
1652         }
1653     }
1654
1655     /**
1656      * This function is used by init() to strip whitespace between rules (i.e.,
1657      * after semicolons).
1658      * @param description The formatter description
1659      * @return The description with all the whitespace that follows semicolons
1660      * taken out.
1661      */
1662     private StringBuilder stripWhitespace(String description) {
1663         // since we don't have a method that deletes characters (why?!!)
1664         // create a new StringBuffer to copy the text into
1665         StringBuilder result = new StringBuilder();
1666
1667         // iterate through the characters...
1668         int start = 0;
1669         while (start != -1 && start < description.length()) {
1670             // seek to the first non-whitespace character...
1671             while (start < description.length()
1672                    && PatternProps.isWhiteSpace(description.charAt(start))) {
1673                 ++start;
1674             }
1675
1676             //if the first non-whitespace character is semicolon, skip it and continue
1677             if (start < description.length() && description.charAt(start) == ';') {
1678                 start += 1;
1679                 continue;
1680             }
1681
1682             // locate the next semicolon in the text and copy the text from
1683             // our current position up to that semicolon into the result
1684             int p;
1685             p = description.indexOf(';', start);
1686             if (p == -1) {
1687                 // or if we don't find a semicolon, just copy the rest of
1688                 // the string into the result
1689                 result.append(description.substring(start));
1690                 start = -1;
1691             }
1692             else if (p < description.length()) {
1693                 result.append(description.substring(start, p + 1));
1694                 start = p + 1;
1695             }
1696
1697             // when we get here, we've seeked off the end of the sring, and
1698             // we terminate the loop (we continue until *start* is -1 rather
1699             // than until *p* is -1, because otherwise we'd miss the last
1700             // rule in the description)
1701             else {
1702                 start = -1;
1703             }
1704         }
1705         return result;
1706     }
1707
1708 //    /**
1709 //     * This function is called ONLY DURING CONSTRUCTION to fill in the
1710 //     * defaultRuleSet variable once we've set up all the rule sets.
1711 //     * The default rule set is the last public rule set in the description.
1712 //     * (It's the last rather than the first so that a caller can append
1713 //     * text to the end of an existing formatter description to change its
1714 //     * behavior.)
1715 //     */
1716 //    private void initDefaultRuleSet() {
1717 //        // seek backward from the end of the list until we reach a rule set
1718 //        // whose name DOESN'T begin with %%.  That's the default rule set
1719 //        for (int i = ruleSets.length - 1; i >= 0; --i) {
1720 //            if (!ruleSets[i].getName().startsWith("%%")) {
1721 //                defaultRuleSet = ruleSets[i];
1722 //                return;
1723 //            }
1724 //        }
1725 //        defaultRuleSet = ruleSets[ruleSets.length - 1];
1726 //    }
1727
1728     //-----------------------------------------------------------------------
1729     // formatting implementation
1730     //-----------------------------------------------------------------------
1731
1732     /**
1733      * Bottleneck through which all the public format() methods
1734      * that take a double pass. By the time we get here, we know
1735      * which rule set we're using to do the formatting.
1736      * @param number The number to format
1737      * @param ruleSet The rule set to use to format the number
1738      * @return The text that resulted from formatting the number
1739      */
1740     private String format(double number, NFRuleSet ruleSet) {
1741         // all API format() routines that take a double vector through
1742         // here.  Create an empty string buffer where the result will
1743         // be built, and pass it to the rule set (along with an insertion
1744         // position of 0 and the number being formatted) to the rule set
1745         // for formatting
1746         StringBuffer result = new StringBuffer();
1747         ruleSet.format(number, result, 0);
1748         postProcess(result, ruleSet);
1749         return result.toString();
1750     }
1751
1752     /**
1753      * Bottleneck through which all the public format() methods
1754      * that take a long pass. By the time we get here, we know
1755      * which rule set we're using to do the formatting.
1756      * @param number The number to format
1757      * @param ruleSet The rule set to use to format the number
1758      * @return The text that resulted from formatting the number
1759      */
1760     private String format(long number, NFRuleSet ruleSet) {
1761         // all API format() routines that take a double vector through
1762         // here.  We have these two identical functions-- one taking a
1763         // double and one taking a long-- the couple digits of precision
1764         // that long has but double doesn't (both types are 8 bytes long,
1765         // but double has to borrow some of the mantissa bits to hold
1766         // the exponent).
1767         // Create an empty string buffer where the result will
1768         // be built, and pass it to the rule set (along with an insertion
1769         // position of 0 and the number being formatted) to the rule set
1770         // for formatting
1771         StringBuffer result = new StringBuffer();
1772         ruleSet.format(number, result, 0);
1773         postProcess(result, ruleSet);
1774         return result.toString();
1775     }
1776
1777     /**
1778      * Post-process the rules if we have a post-processor.
1779      */
1780     private void postProcess(StringBuffer result, NFRuleSet ruleSet) {
1781         if (postProcessRules != null) {
1782             if (postProcessor == null) {
1783                 int ix = postProcessRules.indexOf(";");
1784                 if (ix == -1) {
1785                     ix = postProcessRules.length();
1786                 }
1787                 String ppClassName = postProcessRules.substring(0, ix).trim();
1788                 try {
1789                     Class<?> cls = Class.forName(ppClassName);
1790                     postProcessor = (RBNFPostProcessor)cls.newInstance();
1791                     postProcessor.init(this, postProcessRules);
1792                 }
1793                 catch (Exception e) {
1794                     // if debug, print it out
1795                     if (DEBUG) System.out.println("could not locate " + ppClassName + ", error " +
1796                                        e.getClass().getName() + ", " + e.getMessage());
1797                     postProcessor = null;
1798                     postProcessRules = null; // don't try again
1799                     return;
1800                 }
1801             }
1802
1803             postProcessor.process(result, ruleSet);
1804         }
1805     }
1806
1807     /**
1808      * Returns the named rule set.  Throws an IllegalArgumentException
1809      * if this formatter doesn't have a rule set with that name.
1810      * @param name The name of the desired rule set
1811      * @return The rule set with that name
1812      */
1813     NFRuleSet findRuleSet(String name) throws IllegalArgumentException {
1814         for (int i = 0; i < ruleSets.length; i++) {
1815             if (ruleSets[i].getName().equals(name)) {
1816                 return ruleSets[i];
1817             }
1818         }
1819         throw new IllegalArgumentException("No rule set named " + name);
1820     }
1821 }