/* ******************************************************************************* * Copyright (C) 1996-2010, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.text; import java.math.BigInteger; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Set; import com.ibm.icu.impl.ICUDebug; import com.ibm.icu.impl.ICUResourceBundle; import com.ibm.icu.impl.UCharacterProperty; import com.ibm.icu.util.ULocale; import com.ibm.icu.util.UResourceBundle; import com.ibm.icu.util.UResourceBundleIterator; /** *
A class that formats numbers according to a set of rules. This number formatter is * typically used for spelling out numeric values in words (e.g., 25,3476 as * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois * cents soixante-seize" or * "funfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for * other complicated formatting tasks, such as formatting a number of seconds as hours, * minutes and seconds (e.g., 3,730 as "1:02:10").
* *The resources contain three predefined formatters for each locale: spellout, which * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is * "2:03"). The client can also define more specialized RuleBasedNumberFormats * by supplying programmer-defined rule sets.
* *The behavior of a RuleBasedNumberFormat is specified by a textual description * that is either passed to the constructor as a String or loaded from a resource * bundle. In its simplest form, the description consists of a semicolon-delimited list of rules. * Each rule has a string of output text and a value or range of values it is applicable to. * In a typical spellout rule set, the first twenty rules are the words for the numbers from * 0 to 19:
* *zero; one; two; three; four; five; six; seven; eight; nine; * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;* *
For larger numbers, we can use the preceding set of rules to format the ones place, and * we only have to supply the words for the multiples of 10:
* *20: twenty[->>]; * 30: thirty{->>]; * 40: forty[->>]; * 50: fifty[->>]; * 60: sixty[->>]; * 70: seventy[->>]; * 80: eighty[->>]; * 90: ninety[->>];* *
In these rules, the base value is spelled out explicitly and set off from the * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable * to all numbers from its own base value to one less than the next rule's base value. The * ">>" token is called a substitution and tells the fomatter to * isolate the number's ones digit, format it using this same set of rules, and place the * result at the position of the ">>" token. Text in brackets is omitted if * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24 * is "twenty-four," not "twenty four").
* *For even larger numbers, we can actually look up several parts of the number in the * list:
* *100: << hundred[ >>];* *
The "<<" represents a new kind of substitution. The << isolates * the hundreds digit (and any digits to its left), formats it using this same rule set, and * places the result where the "<<" was. Notice also that the meaning of * >> has changed: it now refers to both the tens and the ones digits. The meaning of * both substitutions depends on the rule's base value. The base value determines the rule's divisor, * which is the highest power of 10 that is less than or equal to the base value (the user * can change this). To fill in the substitutions, the formatter divides the number being * formatted by the divisor. The integral quotient is used to fill in the << * substitution, and the remainder is used to fill in the >> substitution. The meaning * of the brackets changes similarly: text in brackets is omitted if the value being * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so * if a substitution is filled in with text that includes another substitution, that * substitution is also filled in.
* *This rule covers values up to 999, at which point we add another rule:
* *1000: << thousand[ >>];* *
Again, the meanings of the brackets and substitution tokens shift because the rule's * base value is a higher power of 10, changing the rule's divisor. This rule can actually be * used all the way up to 999,999. This allows us to finish out the rules as follows:
* *1,000,000: << million[ >>]; * 1,000,000,000: << billion[ >>]; * 1,000,000,000,000: << trillion[ >>]; * 1,000,000,000,000,000: OUT OF RANGE!;* *
Commas, periods, and spaces can be used in the base values to improve legibility and * are ignored by the rule parser. The last rule in the list is customarily treated as an * "overflow rule," applying to everything from its base value on up, and often (as * in this example) being used to print out an error message or default representation. * Notice also that the size of the major groupings in large numbers is controlled by the * spacing of the rules: because in English we group numbers by thousand, the higher rules * are separated from each other by a factor of 1,000.
* *To see how these rules actually work in practice, consider the following example: * Formatting 25,430 with this rule set would work like this:
* ** | << thousand >> | *[the rule whose base value is 1,000 is applicable to 25,340] | *
* | twenty->> thousand >> | *[25,340 over 1,000 is 25. The rule for 20 applies.] | *
* | twenty-five thousand >> | *[25 mod 10 is 5. The rule for 5 is "five." | *
* | twenty-five thousand << hundred >> | *[25,340 mod 1,000 is 340. The rule for 100 applies.] | *
* | twenty-five thousand three hundred >> | *[340 over 100 is 3. The rule for 3 is "three."] | *
* | twenty-five thousand three hundred forty | *[340 mod 100 is 40. The rule for 40 applies. Since 40 divides * evenly by 10, the hyphen and substitution in the brackets are omitted.] | *
The above syntax suffices only to format positive integers. To format negative numbers, * we add a special rule:
* *-x: minus >>;* *
This is called a negative-number rule, and is identified by "-x" * where the base value would be. This rule is used to format all negative numbers. the * >> token here means "find the number's absolute value, format it with these * rules, and put the result here."
* *We also add a special rule called a fraction rule for numbers with fractional * parts:
* *x.x: << point >>;* *
This rule is used for all positive non-integers (negative non-integers pass through the * negative-number rule first and then through this rule). Here, the << token refers to * the number's integral part, and the >> to the number's fractional part. The * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be * formatted as "one hundred twenty-three point four five six").
* *To see how this rule syntax is applied to various languages, examine the resource data.
* *There is actually much more flexibility built into the rule language than the * description above shows. A formatter may own multiple rule sets, which can be selected by * the caller, and which can use each other to fill in their substitutions. Substitutions can * also be filled in with digits, using a DecimalFormat object. There is syntax that can be * used to alter a rule's divisor in various ways. And there is provision for much more * flexible fraction handling. A complete description of the rule syntax follows:
* *The description of a RuleBasedNumberFormat's behavior consists of one or more rule * sets. Each rule set consists of a name, a colon, and a list of rules. A rule * set name must begin with a % sign. Rule sets with names that begin with a single % sign * are public: the caller can specify that they be used to format and parse numbers. * Rule sets with names that begin with %% are private: they exist only for the use * of other rule sets. If a formatter only has one rule set, the name may be omitted.
* *The user can also specify a special "rule set" named %%lenient-parse. * The body of %%lenient-parse isn't a set of number-formatting rules, but a RuleBasedCollator * description which is used to define equivalences for lenient parsing. For more information * on the syntax, see RuleBasedCollator. For more information on lenient parsing, * see setLenientParse(). Note: symbols that have syntactic meaning * in collation rules, such as '&', have no particular meaning when appearing outside * of the lenient-parse rule set.
* *The body of a rule set consists of an ordered, semicolon-delimited list of rules. * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two substitutions. * These parameters are controlled by the description syntax, which consists of a rule * descriptor, a colon, and a rule body.
* *A rule descriptor can take one of the following forms (text in italics is the * name of a token):
* ** | bv: | *bv specifies the rule's base value. bv is a decimal * number expressed using ASCII digits. bv may contain spaces, period, and commas, * which are irgnored. The rule's divisor is the highest power of 10 less than or equal to * the base value. | *
* | bv/rad: | *bv specifies the rule's base value. The rule's divisor is the * highest power of rad less than or equal to the base value. | *
* | bv>: | *bv specifies the rule's base value. To calculate the divisor, * let the radix be 10, and the exponent be the highest exponent of the radix that yields a * result less than or equal to the base value. Every > character after the base value * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix * raised to the power of the exponent; otherwise, the divisor is 1. | *
* | bv/rad>: | *bv specifies the rule's base value. To calculate the divisor, * let the radix be rad, and the exponent be the highest exponent of the radix that * yields a result less than or equal to the base value. Every > character after the radix * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix * raised to the power of the exponent; otherwise, the divisor is 1. | *
* | -x: | *The rule is a negative-number rule. | *
* | x.x: | *The rule is an improper fraction rule. | *
* | 0.x: | *The rule is a proper fraction rule. | *
* | x.0: | *The rule is a master rule. | *
* | nothing | *If the rule's rule descriptor is left out, the base value is one plus the * preceding rule's base value (or zero if this is the first rule in the list) in a normal * rule set. In a fraction rule set, the base value is the same as the preceding rule's * base value. | *
A rule set may be either a regular rule set or a fraction rule set, depending * on whether it is used to format a number's integral part (or the whole number) or a * number's fractional part. Using a rule set to format a rule's fractional part makes it a * fraction rule set.
* *Which rule is used to format a number is defined according to one of the following * algorithms: If the rule set is a regular rule set, do the following: * *
If the rule set is a fraction rule set, do the following: * *
A rule's body consists of a string of characters terminated by a semicolon. The rule * may include zero, one, or two substitution tokens, and a range of text in * brackets. The brackets denote optional text (and may also include one or both * substitutions). The exact meanings of the substitution tokens, and under what conditions * optional text is omitted, depend on the syntax of the substitution token and the context. * The rest of the text in a rule body is literal text that is output when the rule matches * the number being formatted.
* *A substitution token begins and ends with a token character. The token * character and the context together specify a mathematical operation to be performed on the * number being formatted. An optional substitution descriptor specifies how the * value resulting from that operation is used to fill in the substitution. The position of * the substitution token in the rule body specifies the location of the resultant text in * the original rule text.
* *The meanings of the substitution token characters are as follows:
* ** | >> | *in normal rule | *Divide the number by the rule's divisor and format the remainder | *
* | * | in negative-number rule | *Find the absolute value of the number and format the result | *
* | * | in fraction or master rule | *Isolate the number's fractional part and format it. | *
* | * | in rule in fraction rule set | *Not allowed. | *
* | >>> | *in normal rule | *Divide the number by the rule's divisor and format the remainder, * but bypass the normal rule-selection process and just use the * rule that precedes this one in this rule list. | *
* | * | in all other rules | *Not allowed. | *
* | << | *in normal rule | *Divide the number by the rule's divisor and format the quotient | *
* | * | in negative-number rule | *Not allowed. | *
* | * | in fraction or master rule | *Isolate the number's integral part and format it. | *
* | * | in rule in fraction rule set | *Multiply the number by the rule's base value and format the result. | *
* | == | *in all rule sets | *Format the number unchanged | *
* | [] | *in normal rule | *Omit the optional text if the number is an even multiple of the rule's divisor | *
* | * | in negative-number rule | *Not allowed. | *
* | * | in improper-fraction rule | *Omit the optional text if the number is between 0 and 1 (same as specifying both an * x.x rule and a 0.x rule) | *
* | * | in master rule | *Omit the optional text if the number is an integer (same as specifying both an x.x * rule and an x.0 rule) | *
* | * | in proper-fraction rule | *Not allowed. | *
* | * | in rule in fraction rule set | *Omit the optional text if multiplying the number by the rule's base value yields 1. | *
The substitution descriptor (i.e., the text between the token characters) may take one * of three forms:
* ** | a rule set name | *Perform the mathematical operation on the number, and format the result using the * named rule set. | *
* | a DecimalFormat pattern | *Perform the mathematical operation on the number, and format the result using a * DecimalFormat with the specified pattern. The pattern must begin with 0 or #. | *
* | nothing | *Perform the mathematical operation on the number, and format the result using the rule
* set containing the current rule, except:
|
*
Whitespace is ignored between a rule set name and a rule set body, between a rule * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe, * the apostrophe is ignored, but all text after it becomes significant (this is how you can * have a rule's rule text begin with whitespace). There is no escape function: the semicolon * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set * names. The characters beginning a substitution token are always treated as the beginning * of a substitution token.
* *See the resource data and the demo program for annotated examples of real rule sets * using these features.
* * @author Richard Gillam * @see NumberFormat * @see DecimalFormat * @stable ICU 2.0 */ public class RuleBasedNumberFormat extends NumberFormat { //----------------------------------------------------------------------- // constants //----------------------------------------------------------------------- // Generated by serialver from JDK 1.4.1_01 static final long serialVersionUID = -7664252765575395068L; /** * Selector code that tells the constructor to create a spellout formatter * @stable ICU 2.0 */ public static final int SPELLOUT = 1; /** * Selector code that tells the constructor to create an ordinal formatter * @stable ICU 2.0 */ public static final int ORDINAL = 2; /** * Selector code that tells the constructor to create a duration formatter * @stable ICU 2.0 */ public static final int DURATION = 3; /** * Selector code that tells the constructor to create a numbering system formatter * @stable ICU 4.2 */ public static final int NUMBERING_SYSTEM = 4; //----------------------------------------------------------------------- // data members //----------------------------------------------------------------------- /** * The formatter's rule sets. */ private transient NFRuleSet[] ruleSets = null; /** * A pointer to the formatter's default rule set. This is always included * in ruleSets. */ private transient NFRuleSet defaultRuleSet = null; /** * The formatter's locale. This is used to create DecimalFormatSymbols and * Collator objects. * @serial */ private ULocale locale = null; /** * Collator to be used in lenient parsing. This variable is lazy-evaluated: * the collator is actually created the first time the client does a parse * with lenient-parse mode turned on. */ private transient RbnfLenientScannerProvider scannerProvider = null; // flag to mark whether we've previously looked for a scanner and failed private transient boolean lookedForScanner; /** * The DecimalFormatSymbols object that any DecimalFormat objects this * formatter uses should use. This variable is lazy-evaluated: it isn't * filled in if the rule set never uses a DecimalFormat pattern. */ private transient DecimalFormatSymbols decimalFormatSymbols = null; /** * The NumberFormat used when lenient parsing numbers. This needs to reflect * the locale. This is lazy-evaluated, like decimalFormatSymbols. It is * here so it can be shared by different NFSubstitutions. */ private transient DecimalFormat decimalFormat = null; /** * Flag specifying whether lenient parse mode is on or off. Off by default. * @serial */ private boolean lenientParse = false; /** * If the description specifies lenient-parse rules, they're stored here until * the collator is created. */ private transient String lenientParseRules; /** * If the description specifies post-process rules, they're stored here until * post-processing is required. */ private transient String postProcessRules; /** * Post processor lazily constructed from the postProcessRules. */ private transient RBNFPostProcessor postProcessor; /** * Localizations for rule set names. * @serial */ private Map* The localizations data provides information about the public * rule sets and their localized display names for different * locales. The first element in the list is an array of the names * of the public rule sets. The first element in this array is * the initial default ruleset. The remaining elements in the * list are arrays of localizations of the names of the public * rule sets. Each of these is one longer than the initial array, * with the first String being the ULocale ID, and the remaining * Strings being the localizations of the rule set names, in the * same order as the initial array. * @param description A description of the formatter's desired behavior. * See the class documentation for a complete explanation of the description * syntax. * @param localizations a list of localizations for the rule set * names in the description. * @stable ICU 3.2 */ public RuleBasedNumberFormat(String description, String[][] localizations) { locale = ULocale.getDefault(); init(description, localizations); } /** * Creates a RuleBasedNumberFormat that behaves according to the description * passed in. The formatter uses the specified locale to determine the * characters to use when formatting in numerals, and to define equivalences * for lenient parsing. * @param description A description of the formatter's desired behavior. * See the class documentation for a complete explanation of the description * syntax. * @param locale A locale, which governs which characters are used for * formatting values in numerals, and which characters are equivalent in * lenient parsing. * @stable ICU 2.0 */ public RuleBasedNumberFormat(String description, Locale locale) { this(description, ULocale.forLocale(locale)); } /** * Creates a RuleBasedNumberFormat that behaves according to the description * passed in. The formatter uses the specified locale to determine the * characters to use when formatting in numerals, and to define equivalences * for lenient parsing. * @param description A description of the formatter's desired behavior. * See the class documentation for a complete explanation of the description * syntax. * @param locale A locale, which governs which characters are used for * formatting values in numerals, and which characters are equivalent in * lenient parsing. * @stable ICU 3.2 */ public RuleBasedNumberFormat(String description, ULocale locale) { this.locale = locale; init(description, null); } /** * Creates a RuleBasedNumberFormat that behaves according to the description * passed in. The formatter uses the specified locale to determine the * characters to use when formatting in numerals, and to define equivalences * for lenient parsing. *
* The localizations data provides information about the public
* rule sets and their localized display names for different
* locales. The first element in the list is an array of the names
* of the public rule sets. The first element in this array is
* the initial default ruleset. The remaining elements in the
* list are arrays of localizations of the names of the public
* rule sets. Each of these is one longer than the initial array,
* with the first String being the ULocale ID, and the remaining
* Strings being the localizations of the rule set names, in the
* same order as the initial array.
* @param description A description of the formatter's desired behavior.
* See the class documentation for a complete explanation of the description
* syntax.
* @param localizations a list of localizations for the rule set names in the description.
* @param locale A ulocale that governs which characters are used for
* formatting values in numerals, and determines which characters are equivalent in
* lenient parsing.
* @stable ICU 3.2
*/
public RuleBasedNumberFormat(String description, String[][] localizations, ULocale locale) {
this.locale = locale;
init(description, localizations);
}
/**
* Creates a RuleBasedNumberFormat from a predefined description. The selector
* code choosed among three possible predefined formats: spellout, ordinal,
* and duration.
* @param locale The locale for the formatter.
* @param format A selector code specifying which kind of formatter to create for that
* locale. There are three legal values: SPELLOUT, which creates a formatter that
* spells out a value in words in the desired language, ORDINAL, which attaches
* an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
* and DURATION, which formats a duration in seconds as hours, minutes, and seconds.
* @stable ICU 2.0
*/
public RuleBasedNumberFormat(Locale locale, int format) {
this(ULocale.forLocale(locale), format);
}
/**
* Creates a RuleBasedNumberFormat from a predefined description. The selector
* code choosed among three possible predefined formats: spellout, ordinal,
* and duration.
* @param locale The locale for the formatter.
* @param format A selector code specifying which kind of formatter to create for that
* locale. There are four legal values: SPELLOUT, which creates a formatter that
* spells out a value in words in the desired language, ORDINAL, which attaches
* an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
* DURATION, which formats a duration in seconds as hours, minutes, and seconds, and
* NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering
* systems such as the Hebrew numbering system, or for Roman numerals, etc..
* @stable ICU 3.2
*/
public RuleBasedNumberFormat(ULocale locale, int format) {
this.locale = locale;
ICUResourceBundle bundle = (ICUResourceBundle)UResourceBundle.
getBundleInstance(ICUResourceBundle.ICU_RBNF_BASE_NAME, locale);
// TODO: determine correct actual/valid locale. Note ambiguity
// here -- do actual/valid refer to pattern, DecimalFormatSymbols,
// or Collator?
ULocale uloc = bundle.getULocale();
setLocale(uloc, uloc);
String description = "";
String[][] localizations = null;
try {
// For backwards compatability - If we have a pre-4.2 style RBNF resource, attempt to read it.
description = bundle.getString(rulenames[format-1]);
}
catch (MissingResourceException e) {
try {
ICUResourceBundle rules = bundle.getWithFallback("RBNFRules/"+rulenames[format-1]);
UResourceBundleIterator it = rules.getIterator();
while (it.hasNext()) {
description = description.concat(it.nextString());
}
}
catch (MissingResourceException e1) {
}
}
try {
UResourceBundle locb = bundle.get(locnames[format-1]);
localizations = new String[locb.getSize()][];
for (int i = 0; i < localizations.length; ++i) {
localizations[i] = locb.get(i).getStringArray();
}
}
catch (MissingResourceException e) {
// might have description and no localizations, or no description...
}
init(description, localizations);
//TODO: we need a real fix - see #6895 / #6896
noParse = false;
if (locnames[format-1].equals("SpelloutLocalizations")) {
String lang = locale.getLanguage();
for (int i = 0; i < NO_SPELLOUT_PARSE_LANGUAGES.length; i++) {
if (NO_SPELLOUT_PARSE_LANGUAGES[i].equals(lang)) {
noParse = true;
break;
}
}
}
}
private static final String[] rulenames = {
"SpelloutRules", "OrdinalRules", "DurationRules", "NumberingSystemRules",
};
private static final String[] locnames = {
"SpelloutLocalizations", "OrdinalLocalizations", "DurationLocalizations", "NumberingSystemLocalizations",
};
/**
* Creates a RuleBasedNumberFormat from a predefined description. Uses the
* default locale.
* @param format A selector code specifying which kind of formatter to create.
* There are three legal values: SPELLOUT, which creates a formatter that spells
* out a value in words in the default locale's langyage, ORDINAL, which attaches
* an ordinal suffix from the default locale's language to a numeral, and
* DURATION, which formats a duration in seconds as hours, minutes, and seconds.
* or NUMBERING_SYSTEM, which is used for alternate numbering systems such as Hebrew.
* @stable ICU 2.0
*/
public RuleBasedNumberFormat(int format) {
this(ULocale.getDefault(), format);
}
//-----------------------------------------------------------------------
// boilerplate
//-----------------------------------------------------------------------
/**
* Duplicates this formatter.
* @return A RuleBasedNumberFormat that is equal to this one.
* @stable ICU 2.0
*/
public Object clone() {
return super.clone();
}
/**
* Tests two RuleBasedNumberFormats for equality.
* @param that The formatter to compare against this one.
* @return true if the two formatters have identical behavior.
* @stable ICU 2.0
*/
public boolean equals(Object that) {
// if the other object isn't a RuleBasedNumberFormat, that's
// all we need to know
if (!(that instanceof RuleBasedNumberFormat)) {
return false;
} else {
// cast the other object's pointer to a pointer to a
// RuleBasedNumberFormat
RuleBasedNumberFormat that2 = (RuleBasedNumberFormat)that;
// compare their locales and lenient-parse modes
if (!locale.equals(that2.locale) || lenientParse != that2.lenientParse) {
return false;
}
// if that succeeds, then compare their rule set lists
if (ruleSets.length != that2.ruleSets.length) {
return false;
}
for (int i = 0; i < ruleSets.length; i++) {
if (!ruleSets[i].equals(that2.ruleSets[i])) {
return false;
}
}
return true;
}
}
/**
* Generates a textual description of this formatter.
* @return a String containing a rule set that will produce a RuleBasedNumberFormat
* with identical behavior to this one. This won't necessarily be identical
* to the rule set description that was originally passed in, but will produce
* the same result.
* @stable ICU 2.0
*/
public String toString() {
// accumulate the descriptions of all the rule sets in a
// StringBuffer, then cast it to a String and return it
StringBuilder result = new StringBuilder();
for (int i = 0; i < ruleSets.length; i++) {
result.append(ruleSets[i].toString());
}
return result.toString();
}
/**
* Writes this object to a stream.
* @param out The stream to write to.
*/
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
// we just write the textual description to the stream, so we
// have an implementation-independent streaming format
out.writeUTF(this.toString());
out.writeObject(this.locale);
}
/**
* Reads this object in from a stream.
* @param in The stream to read from.
*/
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException {
// read the description in from the stream
String description = in.readUTF();
ULocale loc;
try {
loc = (ULocale) in.readObject();
} catch (Exception e) {
loc = ULocale.getDefault();
}
// build a brand-new RuleBasedNumberFormat from the description,
// then steal its substructure. This object's substructure and
// the temporary RuleBasedNumberFormat drop on the floor and
// get swept up by the garbage collector
RuleBasedNumberFormat temp = new RuleBasedNumberFormat(description, loc);
ruleSets = temp.ruleSets;
defaultRuleSet = temp.defaultRuleSet;
publicRuleSetNames = temp.publicRuleSetNames;
decimalFormatSymbols = temp.decimalFormatSymbols;
decimalFormat = temp.decimalFormat;
locale = temp.locale;
}
//-----------------------------------------------------------------------
// public API functions
//-----------------------------------------------------------------------
/**
* Returns a list of the names of all of this formatter's public rule sets.
* @return A list of the names of all of this formatter's public rule sets.
* @stable ICU 2.0
*/
public String[] getRuleSetNames() {
return publicRuleSetNames.clone();
}
/**
* Return a list of locales for which there are locale-specific display names
* for the rule sets in this formatter. If there are no localized display names, return null.
* @return an array of the ulocales for which there is rule set display name information
* @stable ICU 3.2
*/
public ULocale[] getRuleSetDisplayNameLocales() {
if (ruleSetDisplayNames != null) {
SetRbnfLenientScannerProviderImpl
will be set if
* it is available on the classpath. Otherwise this will have no effect.
*
* @param enabled If true, turns lenient-parse mode on; if false, turns it off.
* @see RbnfLenientScanner
* @see RbnfLenientScannerProvider
* @stable ICU 2.0
*/
public void setLenientParseMode(boolean enabled) {
lenientParse = enabled;
}
/**
* Returns true if lenient-parse mode is turned on. Lenient parsing is off
* by default.
* @return true if lenient-parse mode is turned on.
* @see #setLenientParseMode
* @stable ICU 2.0
*/
public boolean lenientParseEnabled() {
return lenientParse;
}
/**
* Sets the provider for the lenient scanner. If this has not been set,
* {@link #setLenientParseMode}
* has no effect. This is necessary to decouple collation from format code.
* @param scannerProvider the provider
* @see #setLenientParseMode
* @see #getLenientScannerProvider
* @draft ICU 4.4
* @provisional This API might change or be removed in a future release.
*/
public void setLenientScannerProvider(RbnfLenientScannerProvider scannerProvider) {
this.scannerProvider = scannerProvider;
}
/**
* Returns the lenient scanner provider. If none was set, and lenient parse is
* enabled, this will attempt to instantiate a default scanner, setting it if
* it was successful. Otherwise this returns false.
*
* @see #setLenientScannerProvider
* @draft ICU 4.4
* @provisional This API might change or be removed in a future release.
*/
public RbnfLenientScannerProvider getLenientScannerProvider() {
// there's a potential race condition if two threads try to set/get the scanner at
// the same time, but you get what you get, and you shouldn't be using this from
// multiple threads anyway.
if (scannerProvider == null && lenientParse && !lookedForScanner) {
///CLOVER:OFF
try {
lookedForScanner = true;
Class> cls = Class.forName("com.ibm.icu.text.RbnfScannerProviderImpl");
RbnfLenientScannerProvider provider = (RbnfLenientScannerProvider)cls.newInstance();
setLenientScannerProvider(provider);
}
catch (Exception e) {
// any failure, we just ignore and return null
}
///CLOVER:ON
}
return scannerProvider;
}
/**
* Override the default rule set to use. If ruleSetName is null, reset
* to the initial default rule set.
* @param ruleSetName the name of the rule set, or null to reset the initial default.
* @throws IllegalArgumentException if ruleSetName is not the name of a public ruleset.
* @stable ICU 2.0
*/
public void setDefaultRuleSet(String ruleSetName) {
if (ruleSetName == null) {
if (publicRuleSetNames.length > 0) {
defaultRuleSet = findRuleSet(publicRuleSetNames[0]);
} else {
defaultRuleSet = null;
int n = ruleSets.length;
while (--n >= 0) {
String currentName = ruleSets[n].getName();
if (currentName.equals("%spellout-numbering") ||
currentName.equals("%digits-ordinal") ||
currentName.equals("%duration")) {
defaultRuleSet = ruleSets[n];
return;
}
}
n = ruleSets.length;
while (--n >= 0) {
if (ruleSets[n].isPublic()) {
defaultRuleSet = ruleSets[n];
break;
}
}
}
} else if (ruleSetName.startsWith("%%")) {
throw new IllegalArgumentException("cannot use private rule set: " + ruleSetName);
} else {
defaultRuleSet = findRuleSet(ruleSetName);
}
}
/**
* Return the name of the current default rule set.
* @return the name of the current default rule set, if it is public, else the empty string.
* @stable ICU 3.0
*/
public String getDefaultRuleSetName() {
if (defaultRuleSet != null && defaultRuleSet.isPublic()) {
return defaultRuleSet.getName();
}
return "";
}
//-----------------------------------------------------------------------
// package-internal API
//-----------------------------------------------------------------------
/**
* Returns a reference to the formatter's default rule set. The default
* rule set is the last public rule set in the description, or the one
* most recently set by setDefaultRuleSet.
* @return The formatter's default rule set.
*/
NFRuleSet getDefaultRuleSet() {
return defaultRuleSet;
}
/**
* Returns the scanner to use for lenient parsing. The scanner is
* provided by the provider.
* @return The collator to use for lenient parsing, or null if lenient parsing
* is turned off.
*/
RbnfLenientScanner getLenientScanner() {
if (lenientParse) {
RbnfLenientScannerProvider provider = getLenientScannerProvider();
if (provider != null) {
return provider.get(locale, lenientParseRules);
}
}
return null;
}
/**
* Returns the DecimalFormatSymbols object that should be used by all DecimalFormat
* instances owned by this formatter. This object is lazily created: this function
* creates it the first time it's called.
* @return The DecimalFormatSymbols object that should be used by all DecimalFormat
* instances owned by this formatter.
*/
DecimalFormatSymbols getDecimalFormatSymbols() {
// lazy-evaluate the DecimalFormatSymbols object. This object
// is shared by all DecimalFormat instances belonging to this
// formatter
if (decimalFormatSymbols == null) {
decimalFormatSymbols = new DecimalFormatSymbols(locale);
}
return decimalFormatSymbols;
}
DecimalFormat getDecimalFormat() {
if (decimalFormat == null) {
decimalFormat = (DecimalFormat)NumberFormat.getInstance(locale);
}
return decimalFormat;
}
//-----------------------------------------------------------------------
// construction implementation
//-----------------------------------------------------------------------
/**
* This extracts the special information from the rule sets before the
* main parsing starts. Extra whitespace must have already been removed
* from the description. If found, the special information is removed from the
* description and returned, otherwise the description is unchanged and null
* is returned. Note: the trailing semicolon at the end of the special
* rules is stripped.
* @param description the rbnf description with extra whitespace removed
* @param specialName the name of the special rule text to extract
* @return the special rule text, or null if the rule was not found
*/
private String extractSpecial(StringBuilder description, String specialName) {
String result = null;
int lp = description.indexOf(specialName);
if (lp != -1) {
// we've got to make sure we're not in the middle of a rule
// (where specialName would actually get treated as
// rule text)
if (lp == 0 || description.charAt(lp - 1) == ';') {
// locate the beginning and end of the actual special
// rules (there may be whitespace between the name and
// the first token in the description)
int lpEnd = description.indexOf(";%", lp);
if (lpEnd == -1) {
lpEnd = description.length() - 1; // later we add 1 back to get the '%'
}
int lpStart = lp + specialName.length();
while (lpStart < lpEnd &&
UCharacterProperty.isRuleWhiteSpace(description.charAt(lpStart))) {
++lpStart;
}
// copy out the special rules
result = description.substring(lpStart, lpEnd);
// remove the special rule from the description
description.delete(lp, lpEnd+1); // delete the semicolon but not the '%'
}
}
return result;
}
/**
* This function parses the description and uses it to build all of
* internal data structures that the formatter uses to do formatting
* @param description The description of the formatter's desired behavior.
* This is either passed in by the caller or loaded out of a resource
* by one of the constructors, and is in the description format specified
* in the class docs.
*/
private void init(String description, String[][] localizations) {
initLocalizations(localizations);
// start by stripping the trailing whitespace from all the rules
// (this is all the whitespace follwing each semicolon in the
// description). This allows us to look for rule-set boundaries
// by searching for ";%" without having to worry about whitespace
// between the ; and the %
StringBuilder descBuf = stripWhitespace(description);
// check to see if there's a set of lenient-parse rules. If there
// is, pull them out into our temporary holding place for them,
// and delete them from the description before the real desciption-
// parsing code sees them
lenientParseRules = extractSpecial(descBuf, "%%lenient-parse:");
postProcessRules = extractSpecial(descBuf, "%%post-process:");
// pre-flight parsing the description and count the number of
// rule sets (";%" marks the end of one rule set and the beginning
// of the next)
int numRuleSets = 0;
for (int p = descBuf.indexOf(";%"); p != -1; p = descBuf.indexOf(";%", p)) {
++numRuleSets;
++p;
}
++numRuleSets;
// our rule list is an array of the apprpriate size
ruleSets = new NFRuleSet[numRuleSets];
// divide up the descriptions into individual rule-set descriptions
// and store them in a temporary array. At each step, we also
// new up a rule set, but all this does is initialize its name
// and remove it from its description. We can't actually parse
// the rest of the descriptions and finish initializing everything
// because we have to know the names and locations of all the rule
// sets before we can actually set everything up
String[] ruleSetDescriptions = new String[numRuleSets];
int curRuleSet = 0;
int start = 0;
for (int p = descBuf.indexOf(";%"); p != -1; p = descBuf.indexOf(";%", start)) {
ruleSetDescriptions[curRuleSet] = descBuf.substring(start, p + 1);
ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
++curRuleSet;
start = p + 1;
}
ruleSetDescriptions[curRuleSet] = descBuf.substring(start);
ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
// now we can take note of the formatter's default rule set, which
// is the last public rule set in the description (it's the last
// rather than the first so that a user can create a new formatter
// from an existing formatter and change its default bevhaior just
// by appending more rule sets to the end)
// {dlf} Initialization of a fraction rule set requires the default rule
// set to be known. For purposes of initialization, this is always the
// last public rule set, no matter what the localization data says.
// Set the default ruleset to the last public ruleset, unless one of the predefined
// ruleset names %spellout-numbering, %digits-ordinal, or %duration is found
boolean defaultNameFound = false;
int n = ruleSets.length;
defaultRuleSet = ruleSets[ruleSets.length - 1];
while (--n >= 0) {
String currentName = ruleSets[n].getName();
if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {
defaultRuleSet = ruleSets[n];
defaultNameFound = true;
break;
}
}
if ( !defaultNameFound ) {
for (int i = ruleSets.length - 1; i >= 0; --i) {
if (!ruleSets[i].getName().startsWith("%%")) {
defaultRuleSet = ruleSets[i];
break;
}
}
}
// finally, we can go back through the temporary descriptions
// list and finish seting up the substructure (and we throw
// away the temporary descriptions as we go)
for (int i = 0; i < ruleSets.length; i++) {
ruleSets[i].parseRules(ruleSetDescriptions[i], this);
ruleSetDescriptions[i] = null;
}
// Now that the rules are initialized, the 'real' default rule
// set can be adjusted by the localization data.
// count the number of public rule sets
// (public rule sets have names that begin with % instead of %%)
int publicRuleSetCount = 0;
for (int i = 0; i < ruleSets.length; i++) {
if (!ruleSets[i].getName().startsWith("%%")) {
++publicRuleSetCount;
}
}
// prepare an array of the proper size and copy the names into it
String[] publicRuleSetTemp = new String[publicRuleSetCount];
publicRuleSetCount = 0;
for (int i = ruleSets.length - 1; i >= 0; i--) {
if (!ruleSets[i].getName().startsWith("%%")) {
publicRuleSetTemp[publicRuleSetCount++] = ruleSets[i].getName();
}
}
if (publicRuleSetNames != null) {
// confirm the names, if any aren't in the rules, that's an error
// it is ok if the rules contain public rule sets that are not in this list
loop: for (int i = 0; i < publicRuleSetNames.length; ++i) {
String name = publicRuleSetNames[i];
for (int j = 0; j < publicRuleSetTemp.length; ++j) {
if (name.equals(publicRuleSetTemp[j])) {
continue loop;
}
}
throw new IllegalArgumentException("did not find public rule set: " + name);
}
defaultRuleSet = findRuleSet(publicRuleSetNames[0]); // might be different
} else {
publicRuleSetNames = publicRuleSetTemp;
}
}
/**
* Take the localizations array and create a Map from the locale strings to
* the localization arrays.
*/
private void initLocalizations(String[][] localizations) {
if (localizations != null) {
publicRuleSetNames = localizations[0].clone();
Map