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