1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 /*
28  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
29  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
30  *
31  *   The original version of this source code and documentation is copyrighted
32  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33  * materials are provided under terms of a License Agreement between Taligent
34  * and Sun. This technology is protected by multiple US and International
35  * patents. This notice and attribution to Taligent may not be removed.
36  *   Taligent is a registered trademark of Taligent, Inc.
37  *
38  */
39 
40 package java.text;
41 
42 import libcore.icu.CollationKeyICU;
43 
44 /**
45  * The <code>RuleBasedCollator</code> class is a concrete subclass of
46  * <code>Collator</code> that provides a simple, data-driven, table
47  * collator.  With this class you can create a customized table-based
48  * <code>Collator</code>.  <code>RuleBasedCollator</code> maps
49  * characters to sort keys.
50  *
51  * <p>
52  * <code>RuleBasedCollator</code> has the following restrictions
53  * for efficiency (other subclasses may be used for more complex languages) :
54  * <ol>
55  * <li>If a special collation rule controlled by a &lt;modifier&gt; is
56       specified it applies to the whole collator object.
57  * <li>All non-mentioned characters are at the end of the
58  *     collation order.
59  * </ol>
60  *
61  * <p>
62  * The collation table is composed of a list of collation rules, where each
63  * rule is of one of three forms:
64  * <pre>
65  *    &lt;modifier&gt;
66  *    &lt;relation&gt; &lt;text-argument&gt;
67  *    &lt;reset&gt; &lt;text-argument&gt;
68  * </pre>
69  * The definitions of the rule elements is as follows:
70  * <UL>
71  *    <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
72  *        characters, excluding special characters (that is, common
73  *        whitespace characters [0009-000D, 0020] and rule syntax characters
74  *        [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those
75  *        characters are desired, you can put them in single quotes
76  *        (e.g. ampersand =&gt; '&amp;'). Note that unquoted white space characters
77  *        are ignored; e.g. <code>b c</code> is treated as <code>bc</code>.
78  *    <LI><strong>Modifier</strong>: There are currently two modifiers that
79  *        turn on special collation rules.
80  *        <UL>
81  *            <LI>'@' : Turns on backwards sorting of accents (secondary
82  *                      differences), as in French.
83  *            <LI>'!' : Turns on Thai/Lao vowel-consonant swapping.  If this
84  *                      rule is in force when a Thai vowel of the range
85  *                      &#92;U0E40-&#92;U0E44 precedes a Thai consonant of the range
86  *                      &#92;U0E01-&#92;U0E2E OR a Lao vowel of the range &#92;U0EC0-&#92;U0EC4
87  *                      precedes a Lao consonant of the range &#92;U0E81-&#92;U0EAE then
88  *                      the vowel is placed after the consonant for collation
89  *                      purposes.
90  *        </UL>
91  *        <p>'@' : Indicates that accents are sorted backwards, as in French.
92  *    <LI><strong>Relation</strong>: The relations are the following:
93  *        <UL>
94  *            <LI>'&lt;' : Greater, as a letter difference (primary)
95  *            <LI>';' : Greater, as an accent difference (secondary)
96  *            <LI>',' : Greater, as a case difference (tertiary)
97  *            <LI>'=' : Equal
98  *        </UL>
99  *    <LI><strong>Reset</strong>: There is a single reset
100  *        which is used primarily for contractions and expansions, but which
101  *        can also be used to add a modification at the end of a set of rules.
102  *        <p>'&amp;' : Indicates that the next rule follows the position to where
103  *            the reset text-argument would be sorted.
104  * </UL>
105  *
106  * <p>
107  * This sounds more complicated than it is in practice. For example, the
108  * following are equivalent ways of expressing the same thing:
109  * <blockquote>
110  * <pre>
111  * a &lt; b &lt; c
112  * a &lt; b &amp; b &lt; c
113  * a &lt; c &amp; a &lt; b
114  * </pre>
115  * </blockquote>
116  * Notice that the order is important, as the subsequent item goes immediately
117  * after the text-argument. The following are not equivalent:
118  * <blockquote>
119  * <pre>
120  * a &lt; b &amp; a &lt; c
121  * a &lt; c &amp; a &lt; b
122  * </pre>
123  * </blockquote>
124  * Either the text-argument must already be present in the sequence, or some
125  * initial substring of the text-argument must be present. (e.g. "a &lt; b &amp; ae &lt;
126  * e" is valid since "a" is present in the sequence before "ae" is reset). In
127  * this latter case, "ae" is not entered and treated as a single character;
128  * instead, "e" is sorted as if it were expanded to two characters: "a"
129  * followed by an "e". This difference appears in natural languages: in
130  * traditional Spanish "ch" is treated as though it contracts to a single
131  * character (expressed as "c &lt; ch &lt; d"), while in traditional German
132  * a-umlaut is treated as though it expanded to two characters
133  * (expressed as "a,A &lt; b,B ... &amp;ae;&#92;u00e3&amp;AE;&#92;u00c3").
134  * [&#92;u00e3 and &#92;u00c3 are, of course, the escape sequences for a-umlaut.]
135  * <p>
136  * <strong>Ignorable Characters</strong>
137  * <p>
138  * For ignorable characters, the first rule must start with a relation (the
139  * examples we have used above are really fragments; "a &lt; b" really should be
140  * "&lt; a &lt; b"). If, however, the first relation is not "&lt;", then all the all
141  * text-arguments up to the first "&lt;" are ignorable. For example, ", - &lt; a &lt; b"
142  * makes "-" an ignorable character, as we saw earlier in the word
143  * "black-birds". In the samples for different languages, you see that most
144  * accents are ignorable.
145  *
146  * <p><strong>Normalization and Accents</strong>
147  * <p>
148  * <code>RuleBasedCollator</code> automatically processes its rule table to
149  * include both pre-composed and combining-character versions of
150  * accented characters.  Even if the provided rule string contains only
151  * base characters and separate combining accent characters, the pre-composed
152  * accented characters matching all canonical combinations of characters from
153  * the rule string will be entered in the table.
154  * <p>
155  * This allows you to use a RuleBasedCollator to compare accented strings
156  * even when the collator is set to NO_DECOMPOSITION.  There are two caveats,
157  * however.  First, if the strings to be collated contain combining
158  * sequences that may not be in canonical order, you should set the collator to
159  * CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of
160  * combining sequences.  Second, if the strings contain characters with
161  * compatibility decompositions (such as full-width and half-width forms),
162  * you must use FULL_DECOMPOSITION, since the rule tables only include
163  * canonical mappings.
164  *
165  * <p><strong>Errors</strong>
166  * <p>
167  * The following are errors:
168  * <UL>
169  *     <LI>A text-argument contains unquoted punctuation symbols
170  *        (e.g. "a &lt; b-c &lt; d").
171  *     <LI>A relation or reset character not followed by a text-argument
172  *        (e.g. "a &lt; ,b").
173  *     <LI>A reset where the text-argument (or an initial substring of the
174  *         text-argument) is not already in the sequence.
175  *         (e.g. "a &lt; b &amp; e &lt; f")
176  * </UL>
177  * If you produce one of these errors, a <code>RuleBasedCollator</code> throws
178  * a <code>ParseException</code>.
179  *
180  * <p><strong>Examples</strong>
181  * <p>Simple:     "&lt; a &lt; b &lt; c &lt; d"
182  * <p>Norwegian:  "&lt; a, A &lt; b, B &lt; c, C &lt; d, D &lt; e, E &lt; f, F
183  *                 &lt; g, G &lt; h, H &lt; i, I &lt; j, J &lt; k, K &lt; l, L
184  *                 &lt; m, M &lt; n, N &lt; o, O &lt; p, P &lt; q, Q &lt; r, R
185  *                 &lt; s, S &lt; t, T &lt; u, U &lt; v, V &lt; w, W &lt; x, X
186  *                 &lt; y, Y &lt; z, Z
187  *                 &lt; &#92;u00E6, &#92;u00C6
188  *                 &lt; &#92;u00F8, &#92;u00D8
189  *                 &lt; &#92;u00E5 = a&#92;u030A, &#92;u00C5 = A&#92;u030A;
190  *                      aa, AA"
191  *
192  * <p>
193  * To create a <code>RuleBasedCollator</code> object with specialized
194  * rules tailored to your needs, you construct the <code>RuleBasedCollator</code>
195  * with the rules contained in a <code>String</code> object. For example:
196  * <blockquote>
197  * <pre>
198  * String simple = "&lt; a&lt; b&lt; c&lt; d";
199  * RuleBasedCollator mySimple = new RuleBasedCollator(simple);
200  * </pre>
201  * </blockquote>
202  * Or:
203  * <blockquote>
204  * <pre>
205  * String Norwegian = "&lt; a, A &lt; b, B &lt; c, C &lt; d, D &lt; e, E &lt; f, F &lt; g, G &lt; h, H &lt; i, I" +
206  *                    "&lt; j, J &lt; k, K &lt; l, L &lt; m, M &lt; n, N &lt; o, O &lt; p, P &lt; q, Q &lt; r, R" +
207  *                    "&lt; s, S &lt; t, T &lt; u, U &lt; v, V &lt; w, W &lt; x, X &lt; y, Y &lt; z, Z" +
208  *                    "&lt; &#92;u00E6, &#92;u00C6" +     // Latin letter ae &amp; AE
209  *                    "&lt; &#92;u00F8, &#92;u00D8" +     // Latin letter o &amp; O with stroke
210  *                    "&lt; &#92;u00E5 = a&#92;u030A," +  // Latin letter a with ring above
211  *                    "  &#92;u00C5 = A&#92;u030A;" +  // Latin letter A with ring above
212  *                    "  aa, AA";
213  * RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
214  * </pre>
215  * </blockquote>
216  *
217  * <p>
218  * A new collation rules string can be created by concatenating rules
219  * strings. For example, the rules returned by {@link #getRules()} could
220  * be concatenated to combine multiple <code>RuleBasedCollator</code>s.
221  *
222  * <p>
223  * The following example demonstrates how to change the order of
224  * non-spacing accents,
225  * <blockquote>
226  * <pre>
227  * // old rule
228  * String oldRules = "=&#92;u0301;&#92;u0300;&#92;u0302;&#92;u0308"    // main accents
229  *                 + ";&#92;u0327;&#92;u0303;&#92;u0304;&#92;u0305"    // main accents
230  *                 + ";&#92;u0306;&#92;u0307;&#92;u0309;&#92;u030A"    // main accents
231  *                 + ";&#92;u030B;&#92;u030C;&#92;u030D;&#92;u030E"    // main accents
232  *                 + ";&#92;u030F;&#92;u0310;&#92;u0311;&#92;u0312"    // main accents
233  *                 + "&lt; a , A ; ae, AE ; &#92;u00e6 , &#92;u00c6"
234  *                 + "&lt; b , B &lt; c, C &lt; e, E &amp; C &lt; d, D";
235  * // change the order of accent characters
236  * String addOn = "&amp; &#92;u0300 ; &#92;u0308 ; &#92;u0302";
237  * RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
238  * </pre>
239  * </blockquote>
240  *
241  * @see        Collator
242  * @see        CollationElementIterator
243  * @author     Helena Shih, Laura Werner, Richard Gillam
244  */
245 public class RuleBasedCollator extends Collator {
RuleBasedCollator(android.icu.text.RuleBasedCollator wrapper)246     RuleBasedCollator(android.icu.text.RuleBasedCollator wrapper) {
247         super(wrapper);
248     }
249     // IMPLEMENTATION NOTES:  The implementation of the collation algorithm is
250     // divided across three classes: RuleBasedCollator, RBCollationTables, and
251     // CollationElementIterator.  RuleBasedCollator contains the collator's
252     // transient state and includes the code that uses the other classes to
253     // implement comparison and sort-key building.  RuleBasedCollator also
254     // contains the logic to handle French secondary accent sorting.
255     // A RuleBasedCollator has two CollationElementIterators.  State doesn't
256     // need to be preserved in these objects between calls to compare() or
257     // getCollationKey(), but the objects persist anyway to avoid wasting extra
258     // creation time.  compare() and getCollationKey() are synchronized to ensure
259     // thread safety with this scheme.  The CollationElementIterator is responsible
260     // for generating collation elements from strings and returning one element at
261     // a time (sometimes there's a one-to-many or many-to-one mapping between
262     // characters and collation elements-- this class handles that).
263     // CollationElementIterator depends on RBCollationTables, which contains the
264     // collator's static state.  RBCollationTables contains the actual data
265     // tables specifying the collation order of characters for a particular locale
266     // or use.  It also contains the base logic that CollationElementIterator
267     // uses to map from characters to collation elements.  A single RBCollationTables
268     // object is shared among all RuleBasedCollators for the same locale, and
269     // thus by all the CollationElementIterators they create.
270 
271     /**
272      * RuleBasedCollator constructor.  This takes the table rules and builds
273      * a collation table out of them.  Please see RuleBasedCollator class
274      * description for more details on the collation rule syntax.
275      * @see java.util.Locale
276      * @param rules the collation rules to build the collation table from.
277      * @exception ParseException A format exception
278      * will be thrown if the build process of the rules fails. For
279      * example, build rule "a &lt; ? &lt; d" will cause the constructor to
280      * throw the ParseException because the '?' is not quoted.
281      */
RuleBasedCollator(String rules)282     public RuleBasedCollator(String rules) throws ParseException {
283         if (rules == null) {
284             throw new NullPointerException("rules == null");
285         }
286         try {
287             icuColl = new android.icu.text.RuleBasedCollator(rules);
288         } catch (Exception e) {
289             if (e instanceof ParseException) {
290                 throw (ParseException) e;
291             }
292             /*
293              * -1 means it's not a ParseException. Maybe IOException thrown when
294              * an error occurred while reading internal data.
295              */
296             throw new ParseException(e.getMessage(), -1);
297         }
298     }
299 
300     /**
301      * Gets the table-based rules for the collation object.
302      *
303      * <p>On Android, the returned string will be empty unless this instance was
304      * constructed using {@link #RuleBasedCollator(String)}.
305      *
306      * @return returns the collation rules that the table collation object
307      * was created from.
308      */
getRules()309     public String getRules()
310     {
311         return collAsICU().getRules();
312     }
313 
314     /**
315      * Returns a CollationElementIterator for the given String.
316      *
317      * @param source the string to be collated
318      * @return a {@code CollationElementIterator} object
319      * @see java.text.CollationElementIterator
320      */
getCollationElementIterator(String source)321     public CollationElementIterator getCollationElementIterator(String source) {
322         if (source == null) {
323             throw new NullPointerException("source == null");
324         }
325         return new CollationElementIterator(collAsICU().getCollationElementIterator(source));
326     }
327 
328     /**
329      * Returns a CollationElementIterator for the given CharacterIterator.
330      *
331      * @param source the character iterator to be collated
332      * @return a {@code CollationElementIterator} object
333      * @see java.text.CollationElementIterator
334      * @since 1.2
335      */
getCollationElementIterator( CharacterIterator source)336     public CollationElementIterator getCollationElementIterator(
337                                                 CharacterIterator source) {
338        if (source == null) {
339             throw new NullPointerException("source == null");
340         }
341         return new CollationElementIterator(collAsICU().getCollationElementIterator(source));
342     }
343 
344     /**
345      * Compares the character data stored in two different strings based on the
346      * collation rules.  Returns information about whether a string is less
347      * than, greater than or equal to another string in a language.
348      * This can be overriden in a subclass.
349      *
350      * @exception NullPointerException if <code>source</code> or <code>target</code> is null.
351      */
compare(String source, String target)352     public synchronized int compare(String source, String target)
353     {
354         if (source == null || target == null) {
355             throw new NullPointerException();
356         }
357         return icuColl.compare(source, target);
358     }
359 
360     /**
361      * Transforms the string into a series of characters that can be compared
362      * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
363      * It can be overriden in a subclass.
364      */
getCollationKey(String source)365     public synchronized CollationKey getCollationKey(String source)
366     {
367         if (source == null) {
368             return null;
369         }
370         return new CollationKeyICU(source, icuColl.getCollationKey(source));
371     }
372 
373     /**
374      * Standard override; no change in semantics.
375      */
clone()376     public Object clone() {
377         return super.clone();
378     }
379 
380     /**
381      * Compares the equality of two collation objects.
382      * @param obj the table-based collation object to be compared with this.
383      * @return true if the current table-based collation object is the same
384      * as the table-based collation object obj; false otherwise.
385      */
equals(Object obj)386     public boolean equals(Object obj) {
387         if (obj == null) return false;
388         return super.equals(obj);
389     }
390 
391     /**
392      * Generates the hash code for the table-based collation object
393      */
hashCode()394     public int hashCode() {
395         return icuColl.hashCode();
396     }
397 
collAsICU()398     private android.icu.text.RuleBasedCollator collAsICU() {
399         return (android.icu.text.RuleBasedCollator) icuColl;
400     }
401 }
402