]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_8_1_1/main/classes/core/src/com/ibm/icu/text/RuleBasedNumberFormat.java
Added flags.
[Dictionary.git] / jars / icu4j-4_8_1_1 / main / classes / core / src / com / ibm / icu / text / RuleBasedNumberFormat.java
1 /*
2  *******************************************************************************
3  * Copyright (C) 1996-2011, 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      * A pointer to the formatter's default rule set.  This is always included
528      * in ruleSets.
529      */
530     private transient NFRuleSet defaultRuleSet = null;
531
532     /**
533      * The formatter's locale.  This is used to create DecimalFormatSymbols and
534      * Collator objects.
535      * @serial
536      */
537     private ULocale locale = null;
538
539     /**
540      * Collator to be used in lenient parsing.  This variable is lazy-evaluated:
541      * the collator is actually created the first time the client does a parse
542      * with lenient-parse mode turned on.
543      */
544     private transient RbnfLenientScannerProvider scannerProvider = null;
545
546     // flag to mark whether we've previously looked for a scanner and failed
547     private transient boolean lookedForScanner;
548
549     /**
550      * The DecimalFormatSymbols object that any DecimalFormat objects this
551      * formatter uses should use.  This variable is lazy-evaluated: it isn't
552      * filled in if the rule set never uses a DecimalFormat pattern.
553      */
554     private transient DecimalFormatSymbols decimalFormatSymbols = null;
555
556     /**
557      * The NumberFormat used when lenient parsing numbers.  This needs to reflect
558      * the locale.  This is lazy-evaluated, like decimalFormatSymbols.  It is
559      * here so it can be shared by different NFSubstitutions.
560      */
561     private transient DecimalFormat decimalFormat = null;
562
563     /**
564      * Flag specifying whether lenient parse mode is on or off.  Off by default.
565      * @serial
566      */
567     private boolean lenientParse = false;
568
569     /**
570      * If the description specifies lenient-parse rules, they're stored here until
571      * the collator is created.
572      */
573     private transient String lenientParseRules;
574
575     /**
576      * If the description specifies post-process rules, they're stored here until
577      * post-processing is required.
578      */
579     private transient String postProcessRules;
580
581     /**
582      * Post processor lazily constructed from the postProcessRules.
583      */
584     private transient RBNFPostProcessor postProcessor;
585
586     /**
587      * Localizations for rule set names.
588      * @serial
589      */
590     private Map<String, String[]> ruleSetDisplayNames;
591
592     /**
593      * The public rule set names;
594      * @serial
595      */
596     private String[] publicRuleSetNames;
597
598     private static final boolean DEBUG  =  ICUDebug.enabled("rbnf");
599
600     // Temporary workaround - when noParse is true, do noting in parse.
601     // TODO: We need a real fix - see #6895/#6896
602     private boolean noParse;
603     private static final String[] NO_SPELLOUT_PARSE_LANGUAGES = { "ga" };
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         //TODO: we need a real fix - see #6895 / #6896
790         noParse = false;
791         if (locnames[format-1].equals("SpelloutLocalizations")) {
792             String lang = locale.getLanguage();
793             for (int i = 0; i < NO_SPELLOUT_PARSE_LANGUAGES.length; i++) {
794                 if (NO_SPELLOUT_PARSE_LANGUAGES[i].equals(lang)) {
795                     noParse = true;
796                     break;
797                 }
798             }
799         }
800     }
801
802     private static final String[] rulenames = {
803         "SpelloutRules", "OrdinalRules", "DurationRules", "NumberingSystemRules",
804     };
805     private static final String[] locnames = {
806         "SpelloutLocalizations", "OrdinalLocalizations", "DurationLocalizations", "NumberingSystemLocalizations",
807     };
808
809     /**
810      * Creates a RuleBasedNumberFormat from a predefined description.  Uses the
811      * default <code>FORMAT</code> locale.
812      * @param format A selector code specifying which kind of formatter to create.
813      * There are three legal values: SPELLOUT, which creates a formatter that spells
814      * out a value in words in the default locale's langyage, ORDINAL, which attaches
815      * an ordinal suffix from the default locale's language to a numeral, and
816      * DURATION, which formats a duration in seconds as hours, minutes, and seconds.
817      * or NUMBERING_SYSTEM, which is used for alternate numbering systems such as Hebrew.
818      * @see Category#FORMAT
819      * @stable ICU 2.0
820      */
821     public RuleBasedNumberFormat(int format) {
822         this(ULocale.getDefault(Category.FORMAT), format);
823     }
824
825     //-----------------------------------------------------------------------
826     // boilerplate
827     //-----------------------------------------------------------------------
828
829     /**
830      * Duplicates this formatter.
831      * @return A RuleBasedNumberFormat that is equal to this one.
832      * @stable ICU 2.0
833      */
834     public Object clone() {
835         return super.clone();
836     }
837
838     /**
839      * Tests two RuleBasedNumberFormats for equality.
840      * @param that The formatter to compare against this one.
841      * @return true if the two formatters have identical behavior.
842      * @stable ICU 2.0
843      */
844     public boolean equals(Object that) {
845         // if the other object isn't a RuleBasedNumberFormat, that's
846         // all we need to know
847         if (!(that instanceof RuleBasedNumberFormat)) {
848             return false;
849         } else {
850             // cast the other object's pointer to a pointer to a
851             // RuleBasedNumberFormat
852             RuleBasedNumberFormat that2 = (RuleBasedNumberFormat)that;
853
854             // compare their locales and lenient-parse modes
855             if (!locale.equals(that2.locale) || lenientParse != that2.lenientParse) {
856                 return false;
857             }
858
859             // if that succeeds, then compare their rule set lists
860             if (ruleSets.length != that2.ruleSets.length) {
861                 return false;
862             }
863             for (int i = 0; i < ruleSets.length; i++) {
864                 if (!ruleSets[i].equals(that2.ruleSets[i])) {
865                     return false;
866                 }
867             }
868
869             return true;
870         }
871     }
872
873     /**
874      * Generates a textual description of this formatter.
875      * @return a String containing a rule set that will produce a RuleBasedNumberFormat
876      * with identical behavior to this one.  This won't necessarily be identical
877      * to the rule set description that was originally passed in, but will produce
878      * the same result.
879      * @stable ICU 2.0
880      */
881     public String toString() {
882
883         // accumulate the descriptions of all the rule sets in a
884         // StringBuffer, then cast it to a String and return it
885         StringBuilder result = new StringBuilder();
886         for (int i = 0; i < ruleSets.length; i++) {
887             result.append(ruleSets[i].toString());
888         }
889         return result.toString();
890     }
891
892     /**
893      * Writes this object to a stream.
894      * @param out The stream to write to.
895      */
896     private void writeObject(java.io.ObjectOutputStream out)
897         throws java.io.IOException {
898         // we just write the textual description to the stream, so we
899         // have an implementation-independent streaming format
900         out.writeUTF(this.toString());
901         out.writeObject(this.locale);
902     }
903
904     /**
905      * Reads this object in from a stream.
906      * @param in The stream to read from.
907      */
908     private void readObject(java.io.ObjectInputStream in)
909         throws java.io.IOException {
910
911         // read the description in from the stream
912         String description = in.readUTF();
913         ULocale loc;
914
915         try {
916             loc = (ULocale) in.readObject();
917         } catch (Exception e) {
918             loc = ULocale.getDefault(Category.FORMAT);
919         }
920
921         // build a brand-new RuleBasedNumberFormat from the description,
922         // then steal its substructure.  This object's substructure and
923         // the temporary RuleBasedNumberFormat drop on the floor and
924         // get swept up by the garbage collector
925         RuleBasedNumberFormat temp = new RuleBasedNumberFormat(description, loc);
926         ruleSets = temp.ruleSets;
927         defaultRuleSet = temp.defaultRuleSet;
928         publicRuleSetNames = temp.publicRuleSetNames;
929         decimalFormatSymbols = temp.decimalFormatSymbols;
930         decimalFormat = temp.decimalFormat;
931         locale = temp.locale;
932     }
933
934
935     //-----------------------------------------------------------------------
936     // public API functions
937     //-----------------------------------------------------------------------
938
939     /**
940      * Returns a list of the names of all of this formatter's public rule sets.
941      * @return A list of the names of all of this formatter's public rule sets.
942      * @stable ICU 2.0
943      */
944     public String[] getRuleSetNames() {
945         return publicRuleSetNames.clone();
946     }
947
948     /**
949      * Return a list of locales for which there are locale-specific display names
950      * for the rule sets in this formatter.  If there are no localized display names, return null.
951      * @return an array of the ulocales for which there is rule set display name information
952      * @stable ICU 3.2
953      */
954     public ULocale[] getRuleSetDisplayNameLocales() {
955         if (ruleSetDisplayNames != null) {
956             Set<String> s = ruleSetDisplayNames.keySet();
957             String[] locales = s.toArray(new String[s.size()]);
958             Arrays.sort(locales, String.CASE_INSENSITIVE_ORDER);
959             ULocale[] result = new ULocale[locales.length];
960             for (int i = 0; i < locales.length; ++i) {
961                 result[i] = new ULocale(locales[i]);
962             }
963             return result;
964         }
965         return null;
966     }
967
968     private String[] getNameListForLocale(ULocale loc) {
969         if (loc != null && ruleSetDisplayNames != null) {
970             String[] localeNames = { loc.getBaseName(), ULocale.getDefault(Category.DISPLAY).getBaseName() };
971             for (int i = 0; i < localeNames.length; ++i) {
972                 String lname = localeNames[i];
973                 while (lname.length() > 0) {
974                     String[] names = ruleSetDisplayNames.get(lname);
975                     if (names != null) {
976                         return names;
977                     }
978                     lname = ULocale.getFallback(lname);
979                 }
980             }
981         }
982         return null;
983     }
984
985     /**
986      * Return the rule set display names for the provided locale.  These are in the same order
987      * as those returned by getRuleSetNames.  The locale is matched against the locales for
988      * which there is display name data, using normal fallback rules.  If no locale matches,
989      * the default display names are returned.  (These are the internal rule set names minus
990      * the leading '%'.)
991      * @return an array of the locales that have display name information
992      * @see #getRuleSetNames
993      * @stable ICU 3.2
994      */
995     public String[] getRuleSetDisplayNames(ULocale loc) {
996         String[] names = getNameListForLocale(loc);
997         if (names != null) {
998             return names.clone();
999         }
1000         names = getRuleSetNames();
1001         for (int i = 0; i < names.length; ++i) {
1002             names[i] = names[i].substring(1);
1003         }
1004         return names;
1005     }
1006
1007     /**
1008      * Return the rule set display names for the current default <code>DISPLAY</code> locale.
1009      * @return an array of the display names
1010      * @see #getRuleSetDisplayNames(ULocale)
1011      * @see Category#DISPLAY
1012      * @stable ICU 3.2
1013      */
1014     public String[] getRuleSetDisplayNames() {
1015         return getRuleSetDisplayNames(ULocale.getDefault(Category.DISPLAY));
1016     }
1017
1018     /**
1019      * Return the rule set display name for the provided rule set and locale.
1020      * The locale is matched against the locales for which there is display name data, using
1021      * normal fallback rules.  If no locale matches, the default display name is returned.
1022      * @return the display name for the rule set
1023      * @see #getRuleSetDisplayNames
1024      * @throws IllegalArgumentException if ruleSetName is not a valid rule set name for this format
1025      * @stable ICU 3.2
1026      */
1027     public String getRuleSetDisplayName(String ruleSetName, ULocale loc) {
1028         String[] rsnames = publicRuleSetNames;
1029         for (int ix = 0; ix < rsnames.length; ++ix) {
1030             if (rsnames[ix].equals(ruleSetName)) {
1031                 String[] names = getNameListForLocale(loc);
1032                 if (names != null) {
1033                     return names[ix];
1034                 }
1035                 return rsnames[ix].substring(1);
1036             }
1037         }
1038         throw new IllegalArgumentException("unrecognized rule set name: " + ruleSetName);
1039     }
1040
1041     /**
1042      * Return the rule set display name for the provided rule set in the current default <code>DISPLAY</code> locale.
1043      * @return the display name for the rule set
1044      * @see #getRuleSetDisplayName(String,ULocale)
1045      * @see Category#DISPLAY
1046      * @stable ICU 3.2
1047      */
1048     public String getRuleSetDisplayName(String ruleSetName) {
1049         return getRuleSetDisplayName(ruleSetName, ULocale.getDefault(Category.DISPLAY));
1050     }
1051
1052     /**
1053      * Formats the specified number according to the specified rule set.
1054      * @param number The number to format.
1055      * @param ruleSet The name of the rule set to format the number with.
1056      * This must be the name of a valid public rule set for this formatter.
1057      * @return A textual representation of the number.
1058      * @stable ICU 2.0
1059      */
1060     public String format(double number, String ruleSet) throws IllegalArgumentException {
1061         if (ruleSet.startsWith("%%")) {
1062             throw new IllegalArgumentException("Can't use internal rule set");
1063         }
1064         return format(number, findRuleSet(ruleSet));
1065     }
1066
1067     /**
1068      * Formats the specified number according to the specified rule set.
1069      * (If the specified rule set specifies a master ["x.0"] rule, this function
1070      * ignores it.  Convert the number to a double first if you ned it.)  This
1071      * function preserves all the precision in the long-- it doesn't convert it
1072      * to a double.
1073      * @param number The number to format.
1074      * @param ruleSet The name of the rule set to format the number with.
1075      * This must be the name of a valid public rule set for this formatter.
1076      * @return A textual representation of the number.
1077      * @stable ICU 2.0
1078      */
1079     public String format(long number, String ruleSet) throws IllegalArgumentException {
1080         if (ruleSet.startsWith("%%")) {
1081             throw new IllegalArgumentException("Can't use internal rule set");
1082         }
1083         return format(number, findRuleSet(ruleSet));
1084     }
1085
1086     /**
1087      * Formats the specified number using the formatter's default rule set.
1088      * (The default rule set is the last public rule set defined in the description.)
1089      * @param number The number to format.
1090      * @param toAppendTo A StringBuffer that the result should be appended to.
1091      * @param ignore This function doesn't examine or update the field position.
1092      * @return toAppendTo
1093      * @stable ICU 2.0
1094      */
1095     public StringBuffer format(double number,
1096                                StringBuffer toAppendTo,
1097                                FieldPosition ignore) {
1098         // this is one of the inherited format() methods.  Since it doesn't
1099         // have a way to select the rule set to use, it just uses the
1100         // default one
1101         toAppendTo.append(format(number, defaultRuleSet));
1102         return toAppendTo;
1103     }
1104
1105     /**
1106      * Formats the specified number using the formatter's default rule set.
1107      * (The default rule set is the last public rule set defined in the description.)
1108      * (If the specified rule set specifies a master ["x.0"] rule, this function
1109      * ignores it.  Convert the number to a double first if you ned it.)  This
1110      * function preserves all the precision in the long-- it doesn't convert it
1111      * to a double.
1112      * @param number The number to format.
1113      * @param toAppendTo A StringBuffer that the result should be appended to.
1114      * @param ignore This function doesn't examine or update the field position.
1115      * @return toAppendTo
1116      * @stable ICU 2.0
1117      */
1118     public StringBuffer format(long number,
1119                                StringBuffer toAppendTo,
1120                                FieldPosition ignore) {
1121         // this is one of the inherited format() methods.  Since it doesn't
1122         // have a way to select the rule set to use, it just uses the
1123         // default one
1124         toAppendTo.append(format(number, defaultRuleSet));
1125         return toAppendTo;
1126     }
1127
1128     /**
1129      * <strong><font face=helvetica color=red>NEW</font></strong>
1130      * Implement com.ibm.icu.text.NumberFormat:
1131      * Format a BigInteger.
1132      * @stable ICU 2.0
1133      */
1134     public StringBuffer format(BigInteger number,
1135                                StringBuffer toAppendTo,
1136                                FieldPosition pos) {
1137         return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
1138     }
1139
1140     /**
1141      * <strong><font face=helvetica color=red>NEW</font></strong>
1142      * Implement com.ibm.icu.text.NumberFormat:
1143      * Format a BigDecimal.
1144      * @stable ICU 2.0
1145      */
1146     public StringBuffer format(java.math.BigDecimal number,
1147                                StringBuffer toAppendTo,
1148                                FieldPosition pos) {
1149         return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
1150     }
1151
1152     /**
1153      * <strong><font face=helvetica color=red>NEW</font></strong>
1154      * Implement com.ibm.icu.text.NumberFormat:
1155      * Format a BigDecimal.
1156      * @stable ICU 2.0
1157      */
1158     public StringBuffer format(com.ibm.icu.math.BigDecimal number,
1159                                StringBuffer toAppendTo,
1160                                FieldPosition pos) {
1161         // TEMPORARY:
1162         return format(number.doubleValue(), toAppendTo, pos);
1163     }
1164
1165     /**
1166      * Parses the specfied string, beginning at the specified position, according
1167      * to this formatter's rules.  This will match the string against all of the
1168      * formatter's public rule sets and return the value corresponding to the longest
1169      * parseable substring.  This function's behavior is affected by the lenient
1170      * parse mode.
1171      * @param text The string to parse
1172      * @param parsePosition On entry, contains the position of the first character
1173      * in "text" to examine.  On exit, has been updated to contain the position
1174      * of the first character in "text" that wasn't consumed by the parse.
1175      * @return The number that corresponds to the parsed text.  This will be an
1176      * instance of either Long or Double, depending on whether the result has a
1177      * fractional part.
1178      * @see #setLenientParseMode
1179      * @stable ICU 2.0
1180      */
1181     public Number parse(String text, ParsePosition parsePosition) {
1182
1183         //TODO: We need a real fix.  See #6895 / #6896
1184         if (noParse) {
1185             // skip parsing
1186             return new Long(0);
1187         }
1188
1189         // parsePosition tells us where to start parsing.  We copy the
1190         // text in the string from here to the end inro a new string,
1191         // and create a new ParsePosition and result variable to use
1192         // for the duration of the parse operation
1193         String workingText = text.substring(parsePosition.getIndex());
1194         ParsePosition workingPos = new ParsePosition(0);
1195         Number tempResult = null;
1196
1197         // keep track of the largest number of characters consumed in
1198         // the various trials, and the result that corresponds to it
1199         Number result = new Long(0);
1200         ParsePosition highWaterMark = new ParsePosition(workingPos.getIndex());
1201
1202         // iterate over the public rule sets (beginning with the default one)
1203         // and try parsing the text with each of them.  Keep track of which
1204         // one consumes the most characters: that's the one that determines
1205         // the result we return
1206         for (int i = ruleSets.length - 1; i >= 0; i--) {
1207             // skip private rule sets
1208             if (!ruleSets[i].isPublic() || !ruleSets[i].isParseable()) {
1209                 continue;
1210             }
1211
1212             // try parsing the string with the rule set.  If it gets past the
1213             // high-water mark, update the high-water mark and the result
1214             tempResult = ruleSets[i].parse(workingText, workingPos, Double.MAX_VALUE);
1215             if (workingPos.getIndex() > highWaterMark.getIndex()) {
1216                 result = tempResult;
1217                 highWaterMark.setIndex(workingPos.getIndex());
1218             }
1219             // commented out because this API on ParsePosition doesn't exist in 1.1.x
1220             //            if (workingPos.getErrorIndex() > highWaterMark.getErrorIndex()) {
1221             //                highWaterMark.setErrorIndex(workingPos.getErrorIndex());
1222             //            }
1223
1224             // if we manage to use up all the characters in the string,
1225             // we don't have to try any more rule sets
1226             if (highWaterMark.getIndex() == workingText.length()) {
1227                 break;
1228             }
1229
1230             // otherwise, reset our internal parse position to the
1231             // beginning and try again with the next rule set
1232             workingPos.setIndex(0);
1233         }
1234
1235         // add the high water mark to our original parse position and
1236         // return the result
1237         parsePosition.setIndex(parsePosition.getIndex() + highWaterMark.getIndex());
1238         // commented out because this API on ParsePosition doesn't exist in 1.1.x
1239         //        if (highWaterMark.getIndex() == 0) {
1240         //            parsePosition.setErrorIndex(parsePosition.getIndex() + highWaterMark.getErrorIndex());
1241         //        }
1242         return result;
1243     }
1244
1245     /**
1246      * Turns lenient parse mode on and off.
1247      *
1248      * When in lenient parse mode, the formatter uses an RbnfLenientScanner
1249      * for parsing the text.  Lenient parsing is only in effect if a scanner
1250      * is set.  If a provider is not set, and this is used for parsing,
1251      * a default scanner <code>RbnfLenientScannerProviderImpl</code> will be set if
1252      * it is available on the classpath.  Otherwise this will have no effect.
1253      *
1254      * @param enabled If true, turns lenient-parse mode on; if false, turns it off.
1255      * @see RbnfLenientScanner
1256      * @see RbnfLenientScannerProvider
1257      * @stable ICU 2.0
1258      */
1259     public void setLenientParseMode(boolean enabled) {
1260         lenientParse = enabled;
1261     }
1262
1263     /**
1264      * Returns true if lenient-parse mode is turned on.  Lenient parsing is off
1265      * by default.
1266      * @return true if lenient-parse mode is turned on.
1267      * @see #setLenientParseMode
1268      * @stable ICU 2.0
1269      */
1270     public boolean lenientParseEnabled() {
1271         return lenientParse;
1272     }
1273
1274     /**
1275      * Sets the provider for the lenient scanner.  If this has not been set, 
1276      * {@link #setLenientParseMode}
1277      * has no effect.  This is necessary to decouple collation from format code.
1278      * @param scannerProvider the provider
1279      * @see #setLenientParseMode
1280      * @see #getLenientScannerProvider
1281      * @draft ICU 4.4
1282      * @provisional This API might change or be removed in a future release.
1283      */
1284     public void setLenientScannerProvider(RbnfLenientScannerProvider scannerProvider) {
1285         this.scannerProvider = scannerProvider;
1286     }
1287
1288     /**
1289      * Returns the lenient scanner provider.  If none was set, and lenient parse is
1290      * enabled, this will attempt to instantiate a default scanner, setting it if
1291      * it was successful.  Otherwise this returns false.
1292      *
1293      * @see #setLenientScannerProvider
1294      * @draft ICU 4.4
1295      * @provisional This API might change or be removed in a future release.
1296      */
1297     public RbnfLenientScannerProvider getLenientScannerProvider() {
1298         // there's a potential race condition if two threads try to set/get the scanner at
1299         // the same time, but you get what you get, and you shouldn't be using this from
1300         // multiple threads anyway.
1301         if (scannerProvider == null && lenientParse && !lookedForScanner) {
1302             ///CLOVER:OFF
1303             try {
1304                 lookedForScanner = true;
1305                 Class<?> cls = Class.forName("com.ibm.icu.text.RbnfScannerProviderImpl");
1306                 RbnfLenientScannerProvider provider = (RbnfLenientScannerProvider)cls.newInstance();
1307                 setLenientScannerProvider(provider);
1308             }
1309             catch (Exception e) {
1310                 // any failure, we just ignore and return null
1311             }
1312             ///CLOVER:ON
1313         }
1314
1315         return scannerProvider;
1316     }
1317
1318     /**
1319      * Override the default rule set to use.  If ruleSetName is null, reset
1320      * to the initial default rule set.
1321      * @param ruleSetName the name of the rule set, or null to reset the initial default.
1322      * @throws IllegalArgumentException if ruleSetName is not the name of a public ruleset.
1323      * @stable ICU 2.0
1324      */
1325     public void setDefaultRuleSet(String ruleSetName) {
1326         if (ruleSetName == null) {
1327             if (publicRuleSetNames.length > 0) {
1328                 defaultRuleSet = findRuleSet(publicRuleSetNames[0]);
1329             } else {
1330                 defaultRuleSet = null;
1331                 int n = ruleSets.length;
1332                 while (--n >= 0) {
1333                    String currentName = ruleSets[n].getName();
1334                    if (currentName.equals("%spellout-numbering") ||
1335                        currentName.equals("%digits-ordinal") ||
1336                        currentName.equals("%duration")) {
1337
1338                        defaultRuleSet = ruleSets[n];
1339                        return;
1340                    }
1341                 }
1342
1343                 n = ruleSets.length;
1344                 while (--n >= 0) {
1345                     if (ruleSets[n].isPublic()) {
1346                         defaultRuleSet = ruleSets[n];
1347                         break;
1348                     }
1349                 }
1350             }
1351         } else if (ruleSetName.startsWith("%%")) {
1352             throw new IllegalArgumentException("cannot use private rule set: " + ruleSetName);
1353         } else {
1354             defaultRuleSet = findRuleSet(ruleSetName);
1355         }
1356     }
1357
1358     /**
1359      * Return the name of the current default rule set.
1360      * @return the name of the current default rule set, if it is public, else the empty string.
1361      * @stable ICU 3.0
1362      */
1363     public String getDefaultRuleSetName() {
1364         if (defaultRuleSet != null && defaultRuleSet.isPublic()) {
1365             return defaultRuleSet.getName();
1366         }
1367         return "";
1368     }
1369
1370     //-----------------------------------------------------------------------
1371     // package-internal API
1372     //-----------------------------------------------------------------------
1373
1374     /**
1375      * Returns a reference to the formatter's default rule set.  The default
1376      * rule set is the last public rule set in the description, or the one
1377      * most recently set by setDefaultRuleSet.
1378      * @return The formatter's default rule set.
1379      */
1380     NFRuleSet getDefaultRuleSet() {
1381         return defaultRuleSet;
1382     }
1383
1384     /**
1385      * Returns the scanner to use for lenient parsing.  The scanner is
1386      * provided by the provider.
1387      * @return The collator to use for lenient parsing, or null if lenient parsing
1388      * is turned off.
1389      */
1390     RbnfLenientScanner getLenientScanner() {
1391         if (lenientParse) {
1392             RbnfLenientScannerProvider provider = getLenientScannerProvider();
1393             if (provider != null) {
1394                 return provider.get(locale, lenientParseRules);
1395             }
1396         }
1397         return null;
1398     }
1399
1400     /**
1401      * Returns the DecimalFormatSymbols object that should be used by all DecimalFormat
1402      * instances owned by this formatter.  This object is lazily created: this function
1403      * creates it the first time it's called.
1404      * @return The DecimalFormatSymbols object that should be used by all DecimalFormat
1405      * instances owned by this formatter.
1406      */
1407     DecimalFormatSymbols getDecimalFormatSymbols() {
1408         // lazy-evaluate the DecimalFormatSymbols object.  This object
1409         // is shared by all DecimalFormat instances belonging to this
1410         // formatter
1411         if (decimalFormatSymbols == null) {
1412             decimalFormatSymbols = new DecimalFormatSymbols(locale);
1413         }
1414         return decimalFormatSymbols;
1415     }
1416
1417     DecimalFormat getDecimalFormat() {
1418         if (decimalFormat == null) {
1419             decimalFormat = (DecimalFormat)NumberFormat.getInstance(locale);
1420         }
1421         return decimalFormat;
1422     }
1423
1424     //-----------------------------------------------------------------------
1425     // construction implementation
1426     //-----------------------------------------------------------------------
1427
1428     /**
1429      * This extracts the special information from the rule sets before the
1430      * main parsing starts.  Extra whitespace must have already been removed
1431      * from the description.  If found, the special information is removed from the
1432      * description and returned, otherwise the description is unchanged and null
1433      * is returned.  Note: the trailing semicolon at the end of the special
1434      * rules is stripped.
1435      * @param description the rbnf description with extra whitespace removed
1436      * @param specialName the name of the special rule text to extract
1437      * @return the special rule text, or null if the rule was not found
1438      */
1439     private String extractSpecial(StringBuilder description, String specialName) {
1440         String result = null;
1441         int lp = description.indexOf(specialName);
1442         if (lp != -1) {
1443             // we've got to make sure we're not in the middle of a rule
1444             // (where specialName would actually get treated as
1445             // rule text)
1446             if (lp == 0 || description.charAt(lp - 1) == ';') {
1447                 // locate the beginning and end of the actual special
1448                 // rules (there may be whitespace between the name and
1449                 // the first token in the description)
1450                 int lpEnd = description.indexOf(";%", lp);
1451
1452                 if (lpEnd == -1) {
1453                     lpEnd = description.length() - 1; // later we add 1 back to get the '%'
1454                 }
1455                 int lpStart = lp + specialName.length();
1456                 while (lpStart < lpEnd &&
1457                        PatternProps.isWhiteSpace(description.charAt(lpStart))) {
1458                     ++lpStart;
1459                 }
1460
1461                 // copy out the special rules
1462                 result = description.substring(lpStart, lpEnd);
1463
1464                 // remove the special rule from the description
1465                 description.delete(lp, lpEnd+1); // delete the semicolon but not the '%'
1466             }
1467         }
1468         return result;
1469     }
1470
1471     /**
1472      * This function parses the description and uses it to build all of
1473      * internal data structures that the formatter uses to do formatting
1474      * @param description The description of the formatter's desired behavior.
1475      * This is either passed in by the caller or loaded out of a resource
1476      * by one of the constructors, and is in the description format specified
1477      * in the class docs.
1478      */
1479     private void init(String description, String[][] localizations) {
1480         initLocalizations(localizations);
1481
1482         // start by stripping the trailing whitespace from all the rules
1483         // (this is all the whitespace follwing each semicolon in the
1484         // description).  This allows us to look for rule-set boundaries
1485         // by searching for ";%" without having to worry about whitespace
1486         // between the ; and the %
1487         StringBuilder descBuf = stripWhitespace(description);
1488
1489         // check to see if there's a set of lenient-parse rules.  If there
1490         // is, pull them out into our temporary holding place for them,
1491         // and delete them from the description before the real desciption-
1492         // parsing code sees them
1493
1494         lenientParseRules = extractSpecial(descBuf, "%%lenient-parse:");
1495         postProcessRules = extractSpecial(descBuf, "%%post-process:");
1496
1497         // pre-flight parsing the description and count the number of
1498         // rule sets (";%" marks the end of one rule set and the beginning
1499         // of the next)
1500         int numRuleSets = 0;
1501         for (int p = descBuf.indexOf(";%"); p != -1; p = descBuf.indexOf(";%", p)) {
1502             ++numRuleSets;
1503             ++p;
1504         }
1505         ++numRuleSets;
1506
1507         // our rule list is an array of the apprpriate size
1508         ruleSets = new NFRuleSet[numRuleSets];
1509
1510         // divide up the descriptions into individual rule-set descriptions
1511         // and store them in a temporary array.  At each step, we also
1512         // new up a rule set, but all this does is initialize its name
1513         // and remove it from its description.  We can't actually parse
1514         // the rest of the descriptions and finish initializing everything
1515         // because we have to know the names and locations of all the rule
1516         // sets before we can actually set everything up
1517         String[] ruleSetDescriptions = new String[numRuleSets];
1518
1519         int curRuleSet = 0;
1520         int start = 0;
1521         for (int p = descBuf.indexOf(";%"); p != -1; p = descBuf.indexOf(";%", start)) {
1522             ruleSetDescriptions[curRuleSet] = descBuf.substring(start, p + 1);
1523             ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
1524             ++curRuleSet;
1525             start = p + 1;
1526         }
1527         ruleSetDescriptions[curRuleSet] = descBuf.substring(start);
1528         ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
1529
1530         // now we can take note of the formatter's default rule set, which
1531         // is the last public rule set in the description (it's the last
1532         // rather than the first so that a user can create a new formatter
1533         // from an existing formatter and change its default bevhaior just
1534         // by appending more rule sets to the end)
1535
1536         // {dlf} Initialization of a fraction rule set requires the default rule
1537         // set to be known.  For purposes of initialization, this is always the
1538         // last public rule set, no matter what the localization data says.
1539
1540         // Set the default ruleset to the last public ruleset, unless one of the predefined
1541         // ruleset names %spellout-numbering, %digits-ordinal, or %duration is found
1542
1543         boolean defaultNameFound = false;
1544         int n = ruleSets.length;
1545         defaultRuleSet = ruleSets[ruleSets.length - 1];
1546
1547         while (--n >= 0) {
1548             String currentName = ruleSets[n].getName();
1549             if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {
1550                 defaultRuleSet = ruleSets[n];
1551                 defaultNameFound = true;
1552                 break;
1553             }
1554         }
1555
1556         if ( !defaultNameFound ) {
1557             for (int i = ruleSets.length - 1; i >= 0; --i) {
1558                 if (!ruleSets[i].getName().startsWith("%%")) {
1559                     defaultRuleSet = ruleSets[i];
1560                     break;
1561                 }
1562             }
1563         }
1564
1565         // finally, we can go back through the temporary descriptions
1566         // list and finish seting up the substructure (and we throw
1567         // away the temporary descriptions as we go)
1568         for (int i = 0; i < ruleSets.length; i++) {
1569             ruleSets[i].parseRules(ruleSetDescriptions[i], this);
1570             ruleSetDescriptions[i] = null;
1571         }
1572
1573         // Now that the rules are initialized, the 'real' default rule
1574         // set can be adjusted by the localization data.
1575
1576         // count the number of public rule sets
1577         // (public rule sets have names that begin with % instead of %%)
1578         int publicRuleSetCount = 0;
1579         for (int i = 0; i < ruleSets.length; i++) {
1580             if (!ruleSets[i].getName().startsWith("%%")) {
1581                 ++publicRuleSetCount;
1582             }
1583         }
1584
1585         // prepare an array of the proper size and copy the names into it
1586         String[] publicRuleSetTemp = new String[publicRuleSetCount];
1587         publicRuleSetCount = 0;
1588         for (int i = ruleSets.length - 1; i >= 0; i--) {
1589             if (!ruleSets[i].getName().startsWith("%%")) {
1590                 publicRuleSetTemp[publicRuleSetCount++] = ruleSets[i].getName();
1591             }
1592         }
1593
1594         if (publicRuleSetNames != null) {
1595             // confirm the names, if any aren't in the rules, that's an error
1596             // it is ok if the rules contain public rule sets that are not in this list
1597             loop: for (int i = 0; i < publicRuleSetNames.length; ++i) {
1598                 String name = publicRuleSetNames[i];
1599                 for (int j = 0; j < publicRuleSetTemp.length; ++j) {
1600                     if (name.equals(publicRuleSetTemp[j])) {
1601                         continue loop;
1602                     }
1603                 }
1604                 throw new IllegalArgumentException("did not find public rule set: " + name);
1605             }
1606
1607             defaultRuleSet = findRuleSet(publicRuleSetNames[0]); // might be different
1608         } else {
1609             publicRuleSetNames = publicRuleSetTemp;
1610         }
1611     }
1612
1613     /**
1614      * Take the localizations array and create a Map from the locale strings to
1615      * the localization arrays.
1616      */
1617     private void initLocalizations(String[][] localizations) {
1618         if (localizations != null) {
1619             publicRuleSetNames = localizations[0].clone();
1620
1621             Map<String, String[]> m = new HashMap<String, String[]>();
1622             for (int i = 1; i < localizations.length; ++i) {
1623                 String[] data = localizations[i];
1624                 String loc = data[0];
1625                 String[] names = new String[data.length-1];
1626                 if (names.length != publicRuleSetNames.length) {
1627                     throw new IllegalArgumentException("public name length: " + publicRuleSetNames.length +
1628                                                        " != localized names[" + i + "] length: " + names.length);
1629                 }
1630                 System.arraycopy(data, 1, names, 0, names.length);
1631                 m.put(loc, names);
1632             }
1633
1634             if (!m.isEmpty()) {
1635                 ruleSetDisplayNames = m;
1636             }
1637         }
1638     }
1639
1640     /**
1641      * This function is used by init() to strip whitespace between rules (i.e.,
1642      * after semicolons).
1643      * @param description The formatter description
1644      * @return The description with all the whitespace that follows semicolons
1645      * taken out.
1646      */
1647     private StringBuilder stripWhitespace(String description) {
1648         // since we don't have a method that deletes characters (why?!!)
1649         // create a new StringBuffer to copy the text into
1650         StringBuilder result = new StringBuilder();
1651
1652         // iterate through the characters...
1653         int start = 0;
1654         while (start != -1 && start < description.length()) {
1655             // seek to the first non-whitespace character...
1656             while (start < description.length()
1657                    && PatternProps.isWhiteSpace(description.charAt(start))) {
1658                 ++start;
1659             }
1660
1661             //if the first non-whitespace character is semicolon, skip it and continue
1662             if (start < description.length() && description.charAt(start) == ';') {
1663                 start += 1;
1664                 continue;
1665             }
1666
1667             // locate the next semicolon in the text and copy the text from
1668             // our current position up to that semicolon into the result
1669             int p;
1670             p = description.indexOf(';', start);
1671             if (p == -1) {
1672                 // or if we don't find a semicolon, just copy the rest of
1673                 // the string into the result
1674                 result.append(description.substring(start));
1675                 start = -1;
1676             }
1677             else if (p < description.length()) {
1678                 result.append(description.substring(start, p + 1));
1679                 start = p + 1;
1680             }
1681
1682             // when we get here, we've seeked off the end of the sring, and
1683             // we terminate the loop (we continue until *start* is -1 rather
1684             // than until *p* is -1, because otherwise we'd miss the last
1685             // rule in the description)
1686             else {
1687                 start = -1;
1688             }
1689         }
1690         return result;
1691     }
1692
1693 //    /**
1694 //     * This function is called ONLY DURING CONSTRUCTION to fill in the
1695 //     * defaultRuleSet variable once we've set up all the rule sets.
1696 //     * The default rule set is the last public rule set in the description.
1697 //     * (It's the last rather than the first so that a caller can append
1698 //     * text to the end of an existing formatter description to change its
1699 //     * behavior.)
1700 //     */
1701 //    private void initDefaultRuleSet() {
1702 //        // seek backward from the end of the list until we reach a rule set
1703 //        // whose name DOESN'T begin with %%.  That's the default rule set
1704 //        for (int i = ruleSets.length - 1; i >= 0; --i) {
1705 //            if (!ruleSets[i].getName().startsWith("%%")) {
1706 //                defaultRuleSet = ruleSets[i];
1707 //                return;
1708 //            }
1709 //        }
1710 //        defaultRuleSet = ruleSets[ruleSets.length - 1];
1711 //    }
1712
1713     //-----------------------------------------------------------------------
1714     // formatting implementation
1715     //-----------------------------------------------------------------------
1716
1717     /**
1718      * Bottleneck through which all the public format() methods
1719      * that take a double pass. By the time we get here, we know
1720      * which rule set we're using to do the formatting.
1721      * @param number The number to format
1722      * @param ruleSet The rule set to use to format the number
1723      * @return The text that resulted from formatting the number
1724      */
1725     private String format(double number, NFRuleSet ruleSet) {
1726         // all API format() routines that take a double vector through
1727         // here.  Create an empty string buffer where the result will
1728         // be built, and pass it to the rule set (along with an insertion
1729         // position of 0 and the number being formatted) to the rule set
1730         // for formatting
1731         StringBuffer result = new StringBuffer();
1732         ruleSet.format(number, result, 0);
1733         postProcess(result, ruleSet);
1734         return result.toString();
1735     }
1736
1737     /**
1738      * Bottleneck through which all the public format() methods
1739      * that take a long pass. By the time we get here, we know
1740      * which rule set we're using to do the formatting.
1741      * @param number The number to format
1742      * @param ruleSet The rule set to use to format the number
1743      * @return The text that resulted from formatting the number
1744      */
1745     private String format(long number, NFRuleSet ruleSet) {
1746         // all API format() routines that take a double vector through
1747         // here.  We have these two identical functions-- one taking a
1748         // double and one taking a long-- the couple digits of precision
1749         // that long has but double doesn't (both types are 8 bytes long,
1750         // but double has to borrow some of the mantissa bits to hold
1751         // the exponent).
1752         // Create an empty string buffer where the result will
1753         // be built, and pass it to the rule set (along with an insertion
1754         // position of 0 and the number being formatted) to the rule set
1755         // for formatting
1756         StringBuffer result = new StringBuffer();
1757         ruleSet.format(number, result, 0);
1758         postProcess(result, ruleSet);
1759         return result.toString();
1760     }
1761
1762     /**
1763      * Post-process the rules if we have a post-processor.
1764      */
1765     private void postProcess(StringBuffer result, NFRuleSet ruleSet) {
1766         if (postProcessRules != null) {
1767             if (postProcessor == null) {
1768                 int ix = postProcessRules.indexOf(";");
1769                 if (ix == -1) {
1770                     ix = postProcessRules.length();
1771                 }
1772                 String ppClassName = postProcessRules.substring(0, ix).trim();
1773                 try {
1774                     Class<?> cls = Class.forName(ppClassName);
1775                     postProcessor = (RBNFPostProcessor)cls.newInstance();
1776                     postProcessor.init(this, postProcessRules);
1777                 }
1778                 catch (Exception e) {
1779                     // if debug, print it out
1780                     if (DEBUG) System.out.println("could not locate " + ppClassName + ", error " +
1781                                        e.getClass().getName() + ", " + e.getMessage());
1782                     postProcessor = null;
1783                     postProcessRules = null; // don't try again
1784                     return;
1785                 }
1786             }
1787
1788             postProcessor.process(result, ruleSet);
1789         }
1790     }
1791
1792     /**
1793      * Returns the named rule set.  Throws an IllegalArgumentException
1794      * if this formatter doesn't have a rule set with that name.
1795      * @param name The name of the desired rule set
1796      * @return The rule set with that name
1797      */
1798     NFRuleSet findRuleSet(String name) throws IllegalArgumentException {
1799         for (int i = 0; i < ruleSets.length; i++) {
1800             if (ruleSets[i].getName().equals(name)) {
1801                 return ruleSets[i];
1802             }
1803         }
1804         throw new IllegalArgumentException("No rule set named " + name);
1805     }
1806 }