1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1997, 2020, 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} class is a concrete subclass of 46 * {@code Collator} that provides a simple, data-driven, table 47 * collator. With this class you can create a customized table-based 48 * {@code Collator}. {@code RuleBasedCollator} maps 49 * characters to sort keys. 50 * 51 * <p> 52 * {@code RuleBasedCollator} 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 <modifier> 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 * <modifier> 66 * <relation> <text-argument> 67 * <reset> <text-argument> 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 => '&'). Note that unquoted white space characters 77 * are ignored; e.g. {@code b c} is treated as {@code bc}. 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 * \U0E40-\U0E44 precedes a Thai consonant of the range 86 * \U0E01-\U0E2E OR a Lao vowel of the range \U0EC0-\U0EC4 87 * precedes a Lao consonant of the range \U0E81-\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>'<' : 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>'&' : 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 < b < c 112 * a < b & b < c 113 * a < c & a < 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 < b & a < c 121 * a < c & a < 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 < b & ae < 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 < ch < d"), while in traditional German 132 * a-umlaut is treated as though it expanded to two characters 133 * (expressed as "a,A < b,B ... &ae;\u00e3&AE;\u00c3"). 134 * [\u00e3 and \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 < b" really should be 140 * "< a < b"). If, however, the first relation is not "<", then all the all 141 * text-arguments up to the first "<" are ignorable. For example, ", - < a < 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} 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 < b-c < d"). 171 * <LI>A relation or reset character not followed by a text-argument 172 * (e.g. "a < ,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 < b & e < f") 176 * </UL> 177 * If you produce one of these errors, a {@code RuleBasedCollator} throws 178 * a {@code ParseException}. 179 * 180 * <p><strong>Examples</strong> 181 * <p>Simple: "< a < b < c < d" 182 * <p>Norwegian: "< a, A < b, B < c, C < d, D < e, E < f, F 183 * < g, G < h, H < i, I < j, J < k, K < l, L 184 * < m, M < n, N < o, O < p, P < q, Q < r, R 185 * < s, S < t, T < u, U < v, V < w, W < x, X 186 * < y, Y < z, Z 187 * < \u00E6, \u00C6 188 * < \u00F8, \u00D8 189 * < \u00E5 = a\u030A, \u00C5 = A\u030A; 190 * aa, AA" 191 * 192 * <p> 193 * To create a {@code RuleBasedCollator} object with specialized 194 * rules tailored to your needs, you construct the {@code RuleBasedCollator} 195 * with the rules contained in a {@code String} object. For example: 196 * <blockquote> 197 * <pre> 198 * String simple = "< a< b< c< d"; 199 * RuleBasedCollator mySimple = new RuleBasedCollator(simple); 200 * </pre> 201 * </blockquote> 202 * Or: 203 * <blockquote> 204 * <pre> 205 * String Norwegian = "< a, A < b, B < c, C < d, D < e, E < f, F < g, G < h, H < i, I" + 206 * "< j, J < k, K < l, L < m, M < n, N < o, O < p, P < q, Q < r, R" + 207 * "< s, S < t, T < u, U < v, V < w, W < x, X < y, Y < z, Z" + 208 * "< \u00E6, \u00C6" + // Latin letter ae & AE 209 * "< \u00F8, \u00D8" + // Latin letter o & O with stroke 210 * "< \u00E5 = a\u030A," + // Latin letter a with ring above 211 * " \u00C5 = A\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}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 = "=\u0301;\u0300;\u0302;\u0308" // main accents 229 * + ";\u0327;\u0303;\u0304;\u0305" // main accents 230 * + ";\u0306;\u0307;\u0309;\u030A" // main accents 231 * + ";\u030B;\u030C;\u030D;\u030E" // main accents 232 * + ";\u030F;\u0310;\u0311;\u0312" // main accents 233 * + "< a , A ; ae, AE ; \u00e6 , \u00c6" 234 * + "< b , B < c, C < e, E & C < d, D"; 235 * // change the order of accent characters 236 * String addOn = "& \u0300 ; \u0308 ; \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 * @since 1.1 245 */ 246 public class RuleBasedCollator extends Collator{ 247 // Android-added: protected constructor taking an ICU RuleBasedCollator. RuleBasedCollator(android.icu.text.RuleBasedCollator wrapper)248 RuleBasedCollator(android.icu.text.RuleBasedCollator wrapper) { 249 super(wrapper); 250 } 251 252 // IMPLEMENTATION NOTES: The implementation of the collation algorithm is 253 // divided across three classes: RuleBasedCollator, RBCollationTables, and 254 // CollationElementIterator. RuleBasedCollator contains the collator's 255 // transient state and includes the code that uses the other classes to 256 // implement comparison and sort-key building. RuleBasedCollator also 257 // contains the logic to handle French secondary accent sorting. 258 // A RuleBasedCollator has two CollationElementIterators. State doesn't 259 // need to be preserved in these objects between calls to compare() or 260 // getCollationKey(), but the objects persist anyway to avoid wasting extra 261 // creation time. compare() and getCollationKey() are synchronized to ensure 262 // thread safety with this scheme. The CollationElementIterator is responsible 263 // for generating collation elements from strings and returning one element at 264 // a time (sometimes there's a one-to-many or many-to-one mapping between 265 // characters and collation elements-- this class handles that). 266 // CollationElementIterator depends on RBCollationTables, which contains the 267 // collator's static state. RBCollationTables contains the actual data 268 // tables specifying the collation order of characters for a particular locale 269 // or use. It also contains the base logic that CollationElementIterator 270 // uses to map from characters to collation elements. A single RBCollationTables 271 // object is shared among all RuleBasedCollators for the same locale, and 272 // thus by all the CollationElementIterators they create. 273 274 /** 275 * RuleBasedCollator constructor. This takes the table rules and builds 276 * a collation table out of them. Please see RuleBasedCollator class 277 * description for more details on the collation rule syntax. 278 * @see java.util.Locale 279 * @param rules the collation rules to build the collation table from. 280 * @throws ParseException A format exception 281 * will be thrown if the build process of the rules fails. For 282 * example, build rule "a < ? < d" will cause the constructor to 283 * throw the ParseException because the '?' is not quoted. 284 */ RuleBasedCollator(String rules)285 public RuleBasedCollator(String rules) throws ParseException { 286 // BEGIN Android-changed: Switched to ICU. 287 if (rules == null) { 288 throw new NullPointerException("rules == null"); 289 } 290 try { 291 icuColl = new android.icu.text.RuleBasedCollator(rules); 292 } catch (Exception e) { 293 if (e instanceof ParseException) { 294 throw (ParseException) e; 295 } 296 /* 297 * -1 means it's not a ParseException. Maybe IOException thrown when 298 * an error occurred while reading internal data. 299 */ 300 throw new ParseException(e.getMessage(), -1); 301 } 302 // END Android-changed: Switched to ICU. 303 } 304 305 // Android-removed: (String rules, int decomp) constructor and copy constructor. 306 /* 307 * RuleBasedCollator constructor. This takes the table rules and builds 308 * a collation table out of them. Please see RuleBasedCollator class 309 * description for more details on the collation rule syntax. 310 * @see java.util.Locale 311 * @param rules the collation rules to build the collation table from. 312 * @param decomp the decomposition strength used to build the 313 * collation table and to perform comparisons. 314 * @throws ParseException A format exception 315 * will be thrown if the build process of the rules fails. For 316 * example, build rule "a < ? < d" will cause the constructor to 317 * throw the ParseException because the '?' is not quoted. 318 * 319 RuleBasedCollator(String rules, int decomp) throws ParseException { 320 setStrength(Collator.TERTIARY); 321 setDecomposition(decomp); 322 tables = new RBCollationTables(rules, decomp); 323 } 324 325 // Android-removed: (String rules, int decomp) constructor and copy constructor. 326 /** 327 * "Copy constructor." Used in clone() for performance. 328 * 329 private RuleBasedCollator(RuleBasedCollator that) { 330 setStrength(that.getStrength()); 331 setDecomposition(that.getDecomposition()); 332 tables = that.tables; 333 } 334 */ 335 336 // Android-changed: document that getRules() won't return rules in common case. 337 /** 338 * Gets the table-based rules for the collation object. 339 * 340 * <p>On Android, the returned string will be empty unless this instance was 341 * constructed using {@link #RuleBasedCollator(String)}. 342 * 343 * @return returns the collation rules that the table collation object 344 * was created from. 345 */ getRules()346 public String getRules() 347 { 348 // Android-changed: Switched to ICU. 349 return collAsICU().getRules(); 350 } 351 352 /** 353 * Returns a CollationElementIterator for the given String. 354 * 355 * @param source the string to be collated 356 * @return a {@code CollationElementIterator} object 357 * @see java.text.CollationElementIterator 358 */ getCollationElementIterator(String source)359 public CollationElementIterator getCollationElementIterator(String source) { 360 // Android-changed: Switch to ICU and check for null value. 361 if (source == null) { 362 throw new NullPointerException("source == null"); 363 } 364 return new CollationElementIterator(collAsICU().getCollationElementIterator(source)); 365 } 366 367 /** 368 * Returns a CollationElementIterator for the given CharacterIterator. 369 * 370 * @param source the character iterator to be collated 371 * @return a {@code CollationElementIterator} object 372 * @see java.text.CollationElementIterator 373 * @since 1.2 374 */ getCollationElementIterator( CharacterIterator source)375 public CollationElementIterator getCollationElementIterator( 376 CharacterIterator source) { 377 // Android-changed: Switch to ICU and check for null value. 378 if (source == null) { 379 throw new NullPointerException("source == null"); 380 } 381 return new CollationElementIterator(collAsICU().getCollationElementIterator(source)); 382 } 383 384 /** 385 * Compares the character data stored in two different strings based on the 386 * collation rules. Returns information about whether a string is less 387 * than, greater than or equal to another string in a language. 388 * This can be overridden in a subclass. 389 * 390 * @throws NullPointerException if {@code source} or {@code target} is null. 391 */ compare(String source, String target)392 public synchronized int compare(String source, String target) 393 { 394 if (source == null || target == null) { 395 throw new NullPointerException(); 396 } 397 // Android-changed: Switched to ICU. 398 return icuColl.compare(source, target); 399 } 400 401 /** 402 * Transforms the string into a series of characters that can be compared 403 * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey. 404 * It can be overridden in a subclass. 405 */ getCollationKey(String source)406 public synchronized CollationKey getCollationKey(String source) 407 { 408 // Android-changed: Switched to ICU. 409 if (source == null) { 410 return null; 411 } 412 return new CollationKeyICU(source, icuColl.getCollationKey(source)); 413 } 414 415 /** 416 * Standard override; no change in semantics. 417 */ clone()418 public Object clone() { 419 // Android-changed: remove special case for cloning. 420 return super.clone(); 421 } 422 423 /** 424 * Compares the equality of two collation objects. 425 * @param obj the table-based collation object to be compared with this. 426 * @return true if the current table-based collation object is the same 427 * as the table-based collation object obj; false otherwise. 428 */ equals(Object obj)429 public boolean equals(Object obj) { 430 if (obj == null) return false; 431 // Android-changed: delegate to super class, as that already compares icuColl. 432 return super.equals(obj); 433 } 434 435 /** 436 * Generates the hash code for the table-based collation object 437 */ hashCode()438 public int hashCode() { 439 // Android-changed: Switched to ICU. 440 return icuColl.hashCode(); 441 } 442 443 // Android-added: collAsIcu helper method. collAsICU()444 private android.icu.text.RuleBasedCollator collAsICU() { 445 return (android.icu.text.RuleBasedCollator) icuColl; 446 } 447 448 // BEGIN Android-removed: private constants and fields. 449 /* 450 // ============================================================== 451 // private 452 // ============================================================== 453 454 static final int CHARINDEX = 0x70000000; // need look up in .commit() 455 static final int EXPANDCHARINDEX = 0x7E000000; // Expand index follows 456 static final int CONTRACTCHARINDEX = 0x7F000000; // contract indexes follow 457 static final int UNMAPPED = 0xFFFFFFFF; 458 459 private static final int COLLATIONKEYOFFSET = 1; 460 461 private RBCollationTables tables = null; 462 463 // Internal objects that are cached across calls so that they don't have to 464 // be created/destroyed on every call to compare() and getCollationKey() 465 private StringBuffer primResult = null; 466 private StringBuffer secResult = null; 467 private StringBuffer terResult = null; 468 private CollationElementIterator sourceCursor = null; 469 private CollationElementIterator targetCursor = null; 470 */ 471 // END Android-removed: private constants and fields. 472 } 473