1. /*
  2. * @(#)RBTableBuilder.java 1.12 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is copyrighted
  12. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  13. * materials are provided under terms of a License Agreement between Taligent
  14. * and Sun. This technology is protected by multiple US and International
  15. * patents. This notice and attribution to Taligent may not be removed.
  16. * Taligent is a registered trademark of Taligent, Inc.
  17. *
  18. */
  19. package java.text;
  20. import java.util.Vector;
  21. import sun.text.UCompactIntArray;
  22. import sun.text.IntHashtable;
  23. import sun.text.Normalizer;
  24. import sun.text.NormalizerImpl;
  25. import sun.text.ComposedCharIter;
  26. import sun.text.NormalizerUtilities;
  27. /**
  28. * This class contains all the code to parse a RuleBasedCollator pattern
  29. * and build a RBCollationTables object from it. A particular instance
  30. * of tis class exists only during the actual build process-- once an
  31. * RBCollationTables object has been built, the RBTableBuilder object
  32. * goes away. This object carries all of the state which is only needed
  33. * during the build process, plus a "shadow" copy of all of the state
  34. * that will go into the tables object itself. This object communicates
  35. * with RBCollationTables through a separate class, RBCollationTables.BuildAPI,
  36. * this is an inner class of RBCollationTables and provides a separate
  37. * private API for communication with RBTableBuilder.
  38. * This class isn't just an inner class of RBCollationTables itself because
  39. * of its large size. For source-code readability, it seemed better for the
  40. * builder to have its own source file.
  41. */
  42. final class RBTableBuilder {
  43. public RBTableBuilder(RBCollationTables.BuildAPI tables) {
  44. this.tables = tables;
  45. }
  46. /**
  47. * Create a table-based collation object with the given rules.
  48. * This is the main function that actually builds the tables and
  49. * stores them back in the RBCollationTables object. It is called
  50. * ONLY by the RBCollationTables constructor.
  51. * @see java.util.RuleBasedCollator#RuleBasedCollator
  52. * @exception ParseException If the rules format is incorrect.
  53. */
  54. public void build(String pattern, int decmp) throws ParseException
  55. {
  56. boolean isSource = true;
  57. int i = 0;
  58. String expChars;
  59. String groupChars;
  60. if (pattern.length() == 0)
  61. throw new ParseException("Build rules empty.", 0);
  62. // This array maps Unicode characters to their collation ordering
  63. mapping = new UCompactIntArray((int)RBCollationTables.UNMAPPED);
  64. // Normalize the build rules. Find occurances of all decomposed characters
  65. // and normalize the rules before feeding into the builder. By "normalize",
  66. // we mean that all precomposed Unicode characters must be converted into
  67. // a base character and one or more combining characters (such as accents).
  68. // When there are multiple combining characters attached to a base character,
  69. // the combining characters must be in their canonical order
  70. //
  71. // sherman/Note:
  72. //(1)decmp will be NO_DECOMPOSITION only in ko locale to prevent decompose
  73. //hangual syllables to jamos, so we can actually just call decompose with
  74. //normalizer's IGNORE_HANGUL option turned on
  75. //
  76. //(2)just call the "special version" in NormalizerImpl directly
  77. //pattern = Normalizer.decompose(pattern, false, Normalizer.IGNORE_HANGUL, true);
  78. //
  79. //Normalizer.Mode mode = NormalizerUtilities.toNormalizerMode(decmp);
  80. //pattern = Normalizer.normalize(pattern, mode, 0, true);
  81. pattern = NormalizerImpl.canonicalDecomposeWithSingleQuotation(pattern);
  82. // Build the merged collation entries
  83. // Since rules can be specified in any order in the string
  84. // (e.g. "c , C < d , D < e , E .... C < CH")
  85. // this splits all of the rules in the string out into separate
  86. // objects and then sorts them. In the above example, it merges the
  87. // "C < CH" rule in just before the "C < D" rule.
  88. //
  89. mPattern = new MergeCollation(pattern);
  90. int order = 0;
  91. // Now walk though each entry and add it to my own tables
  92. for (i = 0; i < mPattern.getCount(); ++i)
  93. {
  94. PatternEntry entry = mPattern.getItemAt(i);
  95. if (entry != null) {
  96. groupChars = entry.getChars();
  97. if (groupChars.length() > 1) {
  98. switch(groupChars.charAt(groupChars.length()-1)) {
  99. case '@':
  100. frenchSec = true;
  101. groupChars = groupChars.substring(0, groupChars.length()-1);
  102. break;
  103. case '!':
  104. seAsianSwapping = true;
  105. groupChars = groupChars.substring(0, groupChars.length()-1);
  106. break;
  107. }
  108. }
  109. order = increment(entry.getStrength(), order);
  110. expChars = entry.getExtension();
  111. if (expChars.length() != 0) {
  112. addExpandOrder(groupChars, expChars, order);
  113. } else if (groupChars.length() > 1) {
  114. char ch = groupChars.charAt(0);
  115. if (Character.isHighSurrogate(ch) && groupChars.length() == 2) {
  116. addOrder(Character.toCodePoint(ch, groupChars.charAt(1)), order);
  117. } else {
  118. addContractOrder(groupChars, order);
  119. }
  120. } else {
  121. char ch = groupChars.charAt(0);
  122. addOrder(ch, order);
  123. }
  124. }
  125. }
  126. addComposedChars();
  127. commit();
  128. mapping.compact();
  129. /*
  130. System.out.println("mappingSize=" + mapping.getKSize());
  131. for (int j = 0; j < 0xffff; j++) {
  132. int value = mapping.elementAt(j);
  133. if (value != RBCollationTables.UNMAPPED)
  134. System.out.println("index=" + Integer.toString(j, 16)
  135. + ", value=" + Integer.toString(value, 16));
  136. }
  137. */
  138. tables.fillInTables(frenchSec, seAsianSwapping, mapping, contractTable, expandTable,
  139. contractFlags, maxSecOrder, maxTerOrder);
  140. }
  141. /** Add expanding entries for pre-composed unicode characters so that this
  142. * collator can be used reasonably well with decomposition turned off.
  143. */
  144. private void addComposedChars() throws ParseException {
  145. // Iterate through all of the pre-composed characters in Unicode
  146. ComposedCharIter iter = new ComposedCharIter();
  147. int c;
  148. while ((c = iter.next()) != ComposedCharIter.DONE) {
  149. if (getCharOrder(c) == RBCollationTables.UNMAPPED) {
  150. //
  151. // We don't already have an ordering for this pre-composed character.
  152. //
  153. // First, see if the decomposed string is already in our
  154. // tables as a single contracting-string ordering.
  155. // If so, just map the precomposed character to that order.
  156. //
  157. // TODO: What we should really be doing here is trying to find the
  158. // longest initial substring of the decomposition that is present
  159. // in the tables as a contracting character sequence, and find its
  160. // ordering. Then do this recursively with the remaining chars
  161. // so that we build a list of orderings, and add that list to
  162. // the expansion table.
  163. // That would be more correct but also significantly slower, so
  164. // I'm not totally sure it's worth doing.
  165. //
  166. String s = iter.decomposition();
  167. //sherman/Note: if this is 1 character decomposed string, the
  168. //only thing need to do is to check if this decomposed character
  169. //has an entry in our order table, this order is not necessary
  170. //to be a contraction order, if it does have one, add an entry
  171. //for the precomposed character by using the same order, the
  172. //previous impl unnecessarily adds a single character expansion
  173. //entry.
  174. if (s.length() == 1) {
  175. int order = getCharOrder(s.charAt(0));
  176. if (order != RBCollationTables.UNMAPPED) {
  177. addOrder(c, order);
  178. }
  179. continue;
  180. } else if (s.length() == 2) {
  181. char ch0 = s.charAt(0);
  182. if (Character.isHighSurrogate(ch0)) {
  183. int order = getCharOrder(s.codePointAt(0));
  184. if (order != RBCollationTables.UNMAPPED) {
  185. addOrder(c, order);
  186. }
  187. continue;
  188. }
  189. }
  190. int contractOrder = getContractOrder(s);
  191. if (contractOrder != RBCollationTables.UNMAPPED) {
  192. addOrder(c, contractOrder);
  193. } else {
  194. //
  195. // We don't have a contracting ordering for the entire string
  196. // that results from the decomposition, but if we have orders
  197. // for each individual character, we can add an expanding
  198. // table entry for the pre-composed character
  199. //
  200. boolean allThere = true;
  201. for (int i = 0; i < s.length(); i++) {
  202. if (getCharOrder(s.charAt(i)) == RBCollationTables.UNMAPPED) {
  203. allThere = false;
  204. break;
  205. }
  206. }
  207. if (allThere) {
  208. addExpandOrder(c, s, RBCollationTables.UNMAPPED);
  209. }
  210. }
  211. }
  212. }
  213. }
  214. /**
  215. * Look up for unmapped values in the expanded character table.
  216. *
  217. * When the expanding character tables are built by addExpandOrder,
  218. * it doesn't know what the final ordering of each character
  219. * in the expansion will be. Instead, it just puts the raw character
  220. * code into the table, adding CHARINDEX as a flag. Now that we've
  221. * finished building the mapping table, we can go back and look up
  222. * that character to see what its real collation order is and
  223. * stick that into the expansion table. That lets us avoid doing
  224. * a two-stage lookup later.
  225. */
  226. private final void commit()
  227. {
  228. if (expandTable != null) {
  229. for (int i = 0; i < expandTable.size(); i++) {
  230. int[] valueList = (int [])expandTable.elementAt(i);
  231. for (int j = 0; j < valueList.length; j++) {
  232. int order = valueList[j];
  233. if (order < RBCollationTables.EXPANDCHARINDEX && order > CHARINDEX) {
  234. // found a expanding character that isn't filled in yet
  235. int ch = order - CHARINDEX;
  236. // Get the real values for the non-filled entry
  237. int realValue = getCharOrder(ch);
  238. if (realValue == RBCollationTables.UNMAPPED) {
  239. // The real value is still unmapped, maybe it's ignorable
  240. valueList[j] = IGNORABLEMASK & ch;
  241. } else {
  242. // just fill in the value
  243. valueList[j] = realValue;
  244. }
  245. }
  246. }
  247. }
  248. }
  249. }
  250. /**
  251. * Increment of the last order based on the comparison level.
  252. */
  253. private final int increment(int aStrength, int lastValue)
  254. {
  255. switch(aStrength)
  256. {
  257. case Collator.PRIMARY:
  258. // increment priamry order and mask off secondary and tertiary difference
  259. lastValue += PRIMARYORDERINCREMENT;
  260. lastValue &= RBCollationTables.PRIMARYORDERMASK;
  261. isOverIgnore = true;
  262. break;
  263. case Collator.SECONDARY:
  264. // increment secondary order and mask off tertiary difference
  265. lastValue += SECONDARYORDERINCREMENT;
  266. lastValue &= RBCollationTables.SECONDARYDIFFERENCEONLY;
  267. // record max # of ignorable chars with secondary difference
  268. if (!isOverIgnore)
  269. maxSecOrder++;
  270. break;
  271. case Collator.TERTIARY:
  272. // increment tertiary order
  273. lastValue += TERTIARYORDERINCREMENT;
  274. // record max # of ignorable chars with tertiary difference
  275. if (!isOverIgnore)
  276. maxTerOrder++;
  277. break;
  278. }
  279. return lastValue;
  280. }
  281. /**
  282. * Adds a character and its designated order into the collation table.
  283. */
  284. private final void addOrder(int ch, int anOrder)
  285. {
  286. // See if the char already has an order in the mapping table
  287. int order = mapping.elementAt(ch);
  288. if (order >= RBCollationTables.CONTRACTCHARINDEX) {
  289. // There's already an entry for this character that points to a contracting
  290. // character table. Instead of adding the character directly to the mapping
  291. // table, we must add it to the contract table instead.
  292. int length = 1;
  293. if (Character.isSupplementaryCodePoint(ch)) {
  294. length = Character.toChars(ch, keyBuf, 0);
  295. } else {
  296. keyBuf[0] = (char)ch;
  297. }
  298. addContractOrder(new String(keyBuf, 0, length), anOrder);
  299. } else {
  300. // add the entry to the mapping table,
  301. // the same later entry replaces the previous one
  302. mapping.setElementAt(ch, anOrder);
  303. }
  304. }
  305. private final void addContractOrder(String groupChars, int anOrder) {
  306. addContractOrder(groupChars, anOrder, true);
  307. }
  308. /**
  309. * Adds the contracting string into the collation table.
  310. */
  311. private final void addContractOrder(String groupChars, int anOrder,
  312. boolean fwd)
  313. {
  314. if (contractTable == null) {
  315. contractTable = new Vector(INITIALTABLESIZE);
  316. }
  317. //initial character
  318. int ch = groupChars.codePointAt(0);
  319. /*
  320. char ch0 = groupChars.charAt(0);
  321. int ch = Character.isHighSurrogate(ch0)?
  322. Character.toCodePoint(ch0, groupChars.charAt(1)):ch0;
  323. */
  324. // See if the initial character of the string already has a contract table.
  325. int entry = mapping.elementAt(ch);
  326. Vector entryTable = getContractValuesImpl(entry - RBCollationTables.CONTRACTCHARINDEX);
  327. if (entryTable == null) {
  328. // We need to create a new table of contract entries for this base char
  329. int tableIndex = RBCollationTables.CONTRACTCHARINDEX + contractTable.size();
  330. entryTable = new Vector(INITIALTABLESIZE);
  331. contractTable.addElement(entryTable);
  332. // Add the initial character's current ordering first. then
  333. // update its mapping to point to this contract table
  334. entryTable.addElement(new EntryPair(groupChars.substring(0,Character.charCount(ch)), entry));
  335. mapping.setElementAt(ch, tableIndex);
  336. }
  337. // Now add (or replace) this string in the table
  338. int index = RBCollationTables.getEntry(entryTable, groupChars, fwd);
  339. if (index != RBCollationTables.UNMAPPED) {
  340. EntryPair pair = (EntryPair) entryTable.elementAt(index);
  341. pair.value = anOrder;
  342. } else {
  343. EntryPair pair = (EntryPair)entryTable.lastElement();
  344. // NOTE: This little bit of logic is here to speed CollationElementIterator
  345. // .nextContractChar(). This code ensures that the longest sequence in
  346. // this list is always the _last_ one in the list. This keeps
  347. // nextContractChar() from having to search the entire list for the longest
  348. // sequence.
  349. if (groupChars.length() > pair.entryName.length()) {
  350. entryTable.addElement(new EntryPair(groupChars, anOrder, fwd));
  351. } else {
  352. entryTable.insertElementAt(new EntryPair(groupChars, anOrder,
  353. fwd), entryTable.size() - 1);
  354. }
  355. }
  356. // If this was a forward mapping for a contracting string, also add a
  357. // reverse mapping for it, so that CollationElementIterator.previous
  358. // can work right
  359. if (fwd && groupChars.length() > 1) {
  360. addContractFlags(groupChars);
  361. addContractOrder(new StringBuffer(groupChars).reverse().toString(),
  362. anOrder, false);
  363. }
  364. }
  365. /**
  366. * If the given string has been specified as a contracting string
  367. * in this collation table, return its ordering.
  368. * Otherwise return UNMAPPED.
  369. */
  370. private int getContractOrder(String groupChars)
  371. {
  372. int result = RBCollationTables.UNMAPPED;
  373. if (contractTable != null) {
  374. int ch = groupChars.codePointAt(0);
  375. /*
  376. char ch0 = groupChars.charAt(0);
  377. int ch = Character.isHighSurrogate(ch0)?
  378. Character.toCodePoint(ch0, groupChars.charAt(1)):ch0;
  379. */
  380. Vector entryTable = getContractValues(ch);
  381. if (entryTable != null) {
  382. int index = RBCollationTables.getEntry(entryTable, groupChars, true);
  383. if (index != RBCollationTables.UNMAPPED) {
  384. EntryPair pair = (EntryPair) entryTable.elementAt(index);
  385. result = pair.value;
  386. }
  387. }
  388. }
  389. return result;
  390. }
  391. private final int getCharOrder(int ch) {
  392. int order = mapping.elementAt(ch);
  393. if (order >= RBCollationTables.CONTRACTCHARINDEX) {
  394. Vector groupList = getContractValuesImpl(order - RBCollationTables.CONTRACTCHARINDEX);
  395. EntryPair pair = (EntryPair)groupList.firstElement();
  396. order = pair.value;
  397. }
  398. return order;
  399. }
  400. /**
  401. * Get the entry of hash table of the contracting string in the collation
  402. * table.
  403. * @param ch the starting character of the contracting string
  404. */
  405. private Vector getContractValues(int ch)
  406. {
  407. int index = mapping.elementAt(ch);
  408. return getContractValuesImpl(index - RBCollationTables.CONTRACTCHARINDEX);
  409. }
  410. private Vector getContractValuesImpl(int index)
  411. {
  412. if (index >= 0)
  413. {
  414. return (Vector)contractTable.elementAt(index);
  415. }
  416. else // not found
  417. {
  418. return null;
  419. }
  420. }
  421. /**
  422. * Adds the expanding string into the collation table.
  423. */
  424. private final void addExpandOrder(String contractChars,
  425. String expandChars,
  426. int anOrder) throws ParseException
  427. {
  428. // Create an expansion table entry
  429. int tableIndex = addExpansion(anOrder, expandChars);
  430. // And add its index into the main mapping table
  431. if (contractChars.length() > 1) {
  432. char ch = contractChars.charAt(0);
  433. if (Character.isHighSurrogate(ch) && contractChars.length() == 2) {
  434. char ch2 = contractChars.charAt(1);
  435. if (Character.isLowSurrogate(ch2)) {
  436. //only add into table when it is a legal surrogate
  437. addOrder(Character.toCodePoint(ch, ch2), tableIndex);
  438. }
  439. } else {
  440. addContractOrder(contractChars, tableIndex);
  441. }
  442. } else {
  443. addOrder(contractChars.charAt(0), tableIndex);
  444. }
  445. }
  446. private final void addExpandOrder(int ch, String expandChars, int anOrder)
  447. throws ParseException
  448. {
  449. int tableIndex = addExpansion(anOrder, expandChars);
  450. addOrder(ch, tableIndex);
  451. }
  452. /**
  453. * Create a new entry in the expansion table that contains the orderings
  454. * for the given characers. If anOrder is valid, it is added to the
  455. * beginning of the expanded list of orders.
  456. */
  457. private int addExpansion(int anOrder, String expandChars) {
  458. if (expandTable == null) {
  459. expandTable = new Vector(INITIALTABLESIZE);
  460. }
  461. // If anOrder is valid, we want to add it at the beginning of the list
  462. int offset = (anOrder == RBCollationTables.UNMAPPED) ? 0 : 1;
  463. int[] valueList = new int[expandChars.length() + offset];
  464. if (offset == 1) {
  465. valueList[0] = anOrder;
  466. }
  467. int j = offset;
  468. for (int i = 0; i < expandChars.length(); i++) {
  469. char ch0 = expandChars.charAt(i);
  470. char ch1;
  471. int ch;
  472. if (Character.isHighSurrogate(ch0)) {
  473. if (++i == expandChars.length() ||
  474. !Character.isLowSurrogate(ch1=expandChars.charAt(i))) {
  475. //ether we are missing the low surrogate or the next char
  476. //is not a legal low surrogate, so stop loop
  477. break;
  478. }
  479. ch = Character.toCodePoint(ch0, ch1);
  480. } else {
  481. ch = ch0;
  482. }
  483. int mapValue = getCharOrder(ch);
  484. if (mapValue != RBCollationTables.UNMAPPED) {
  485. valueList[j++] = mapValue;
  486. } else {
  487. // can't find it in the table, will be filled in by commit().
  488. valueList[j++] = CHARINDEX + ch;
  489. }
  490. }
  491. if (j < valueList.length) {
  492. //we had at least one supplementary character, the size of valueList
  493. //is bigger than it really needs...
  494. int[] tmpBuf = new int[j];
  495. while (--j >= 0) {
  496. tmpBuf[j] = valueList[j];
  497. }
  498. valueList = tmpBuf;
  499. }
  500. // Add the expanding char list into the expansion table.
  501. int tableIndex = RBCollationTables.EXPANDCHARINDEX + expandTable.size();
  502. expandTable.addElement(valueList);
  503. return tableIndex;
  504. }
  505. private void addContractFlags(String chars) {
  506. char c0;
  507. int c;
  508. int len = chars.length();
  509. for (int i = 0; i < len; i++) {
  510. c0 = chars.charAt(i);
  511. c = Character.isHighSurrogate(c0)
  512. ?Character.toCodePoint(c0, chars.charAt(++i))
  513. :c0;
  514. contractFlags.put(c, 1);
  515. }
  516. }
  517. // ==============================================================
  518. // constants
  519. // ==============================================================
  520. final static int CHARINDEX = 0x70000000; // need look up in .commit()
  521. private final static int IGNORABLEMASK = 0x0000ffff;
  522. private final static int PRIMARYORDERINCREMENT = 0x00010000;
  523. private final static int SECONDARYORDERINCREMENT = 0x00000100;
  524. private final static int TERTIARYORDERINCREMENT = 0x00000001;
  525. private final static int INITIALTABLESIZE = 20;
  526. private final static int MAXKEYSIZE = 5;
  527. // ==============================================================
  528. // instance variables
  529. // ==============================================================
  530. // variables used by the build process
  531. private RBCollationTables.BuildAPI tables = null;
  532. private MergeCollation mPattern = null;
  533. private boolean isOverIgnore = false;
  534. private char[] keyBuf = new char[MAXKEYSIZE];
  535. private IntHashtable contractFlags = new IntHashtable(100);
  536. // "shadow" copies of the instance variables in RBCollationTables
  537. // (the values in these variables are copied back into RBCollationTables
  538. // at the end of the build process)
  539. private boolean frenchSec = false;
  540. private boolean seAsianSwapping = false;
  541. private UCompactIntArray mapping = null;
  542. private Vector contractTable = null;
  543. private Vector expandTable = null;
  544. private short maxSecOrder = 0;
  545. private short maxTerOrder = 0;
  546. }