home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 6 / AACD06.ISO / AACD / Programming / ICU / src / icu / source / i18n / rbbi_bld.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-27  |  77.8 KB  |  1,628 lines

  1. /*
  2. **********************************************************************
  3. *   Copyright (C) 1999 Alan Liu and others. All rights reserved.
  4. **********************************************************************
  5. *   Date        Name        Description
  6. *   10/22/99    alan        Creation.
  7. **********************************************************************
  8. */
  9.  
  10. #include "rbbi.h"
  11. #include "rbbi_bld.h"
  12.  
  13. //=======================================================================
  14. // RuleBasedBreakIterator.Builder
  15. //=======================================================================
  16. /**
  17.  * The Builder class has the job of constructing a RuleBasedBreakIterator from a
  18.  * textual description.  A Builder is constructed by RuleBasedBreakIterator's
  19.  * constructor, which uses it to construct the iterator itself and then throws it
  20.  * away.
  21.  * <p>The construction logic is separated out into its own class for two primary
  22.  * reasons:
  23.  * <ul><li>The construction logic is quite complicated and large.  Separating it
  24.  * out into its own class means the code must only be loaded into memory while a
  25.  * RuleBasedBreakIterator is being constructed, and can be purged after that.
  26.  * <li>There is a fair amount of state that must be maintained throughout the
  27.  * construction process that is not needed by the iterator after construction.
  28.  * Separating this state out into another class prevents all of the functions that
  29.  * construct the iterator from having to have really long parameter lists,
  30.  * (hopefully) contributing to readability and maintainability.</ul>
  31.  * <p>It'd be really nice if this could be an independent class rather than an
  32.  * inner class, because that would shorten the source file considerably, but
  33.  * making Builder an inner class of RuleBasedBreakIterator allows it direct access
  34.  * to RuleBasedBreakIterator's private members, which saves us from having to
  35.  * provide some kind of "back door" to the Builder class that could then also be
  36.  * used by other classes.
  37.  */
  38.  
  39. /**
  40.  * No special construction is required for the Builder.
  41.  */
  42. RuleBasedBreakIteratorBuilder::RuleBasedBreakIteratorBuilder() {
  43. }
  44.  
  45. /**
  46.  * This is the main function for setting up the BreakIterator's tables.  It
  47.  * just vectors different parts of the job off to other functions.
  48.  */
  49. void RuleBasedBreakIteratorBuilder::buildBreakIterator() {
  50.     Vector tempRuleList = buildRuleList(description);
  51.     buildCharCategories(tempRuleList);
  52.     buildStateTable(tempRuleList);
  53.     buildBackwardsStateTable(tempRuleList);
  54. }
  55.  
  56. /**
  57.  * Thus function has three main purposes:
  58.  * <ul><li>Perform general syntax checking on the description, so the rest of the
  59.  * build code can assume that it's parsing a legal description.
  60.  * <li>Split the description into separate rules
  61.  * <li>Perform variable-name substitutions (so that no one else sees variable names)
  62.  * </ul>
  63.  */
  64. Vector RuleBasedBreakIteratorBuilder::buildRuleList(UnicodeString description) {
  65.     // invariants:
  66.     // - parentheses must be balanced: ()[]{}<>
  67.     // - nothing can be nested inside <>
  68.     // - nothing can be nested inside [] except more []s
  69.     // - pairs of ()[]{}<> must not be empty
  70.     // - ; can only occur at the outer level
  71.     // - | can only appear inside ()
  72.     // - only one = or / can occur in a single rule
  73.     // - = and / cannot both occur in the same rule
  74.     // - <> can only occur on the left side of a = expression
  75.     //   (because we'll perform substitutions to eliminate them from other places)
  76.     // - the left-hand side of a = expression can only be a single character
  77.     //   (possibly with \) or text inside <>
  78.     // - the right-hand side of a = expression must be enclosed in [] or ()
  79.     // - * may not occur at the beginning of a rule, nor may it follow
  80.     //   =, /, (, (, |, }, ;, or *
  81.     // - ? may only follow *
  82.     // - the rule list must contain at least one / rule
  83.     // - no rule may be empty
  84.     // - all printing characters in the ASCII range except letters and digits
  85.     //   are reserved and must be preceded by \
  86.     // - ! may only occur at the beginning of a rule
  87.  
  88.     // set up a vector to contain the broken-up description (each entry in the
  89.     // vector is a separate rule) and a stack for keeping track of opening
  90.     // punctuation
  91.     Vector tempRuleList = new Vector();
  92.     Stack parenStack = new Stack();
  93.  
  94.     int32_t p = 0;
  95.     int32_t ruleStart = 0;
  96.     UChar c = '\u0000';
  97.     UChar lastC = '\u0000';
  98.     UChar lastOpen = '\u0000';
  99.     bool_t haveEquals = FALSE;
  100.     bool_t havePipe = FALSE;
  101.     bool_t sawVarName = FALSE;
  102.     final UnicodeString UCharsThatCantPrecedeAsterisk = "=/{(|}*;\u0000";
  103.  
  104.     // if the description doesn't end with a semicolon, tack a semicolon onto the end
  105.     if (description.length() != 0 && description.UCharAt(description.length() - 1) != ';')
  106.         description = description + ";";
  107.  
  108.     // for each character, do...
  109.     while (p < description.length()) {
  110.         c = description.UCharAt(p);
  111.         switch (c) {
  112.             // if the character is opening punctuation, verify that no nesting
  113.             // rules are broken, and push the character onto the stack
  114.             case '{':
  115.             case '<':
  116.             case '[':
  117.             case '(':
  118.                 if (lastOpen == '<')
  119.                     error("Can't nest brackets inside <>", p, description);
  120.                 if (lastOpen == '[' && c != '[')
  121.                     error("Can't nest anything in [] but []", p, description);
  122.                 
  123.                 // if we see < anywhere except on the left-hand side of =,
  124.                 // we must be seeing a variable name that was never defined
  125.                 if (c == '<' && (haveEquals || havePipe))
  126.                     error("Unknown variable name", p, description);
  127.  
  128.                 lastOpen = c;
  129.                 parenStack.push(new Character(c));
  130.                 if (c == '<')
  131.                     sawVarName = TRUE;
  132.                 break;
  133.  
  134.             // if the character is closing punctuation, verify that it matches the
  135.             // last opening punctuation we saw, and that the brackets contain
  136.             // something, then pop the stack
  137.             case '}':
  138.             case '>':
  139.             case ']':
  140.             case ')':
  141.                 UChar expectedClose = '\u0000';
  142.                 switch (lastOpen) {
  143.                     case '{':
  144.                         expectedClose = '}';
  145.                         break;
  146.                     case '[':
  147.                         expectedClose = ']';
  148.                         break;
  149.                     case '(':
  150.                         expectedClose = ')';
  151.                         break;
  152.                     case '<':
  153.                         expectedClose = '>';
  154.                         break;
  155.                 }
  156.                 if (c != expectedClose)
  157.                     error("Unbalanced parentheses", p, description);
  158.                 if (lastC == lastOpen)
  159.                     error("Parens don't contain anything", p, description);
  160.                 parenStack.pop();
  161.                 if (!parenStack.empty())
  162.                     lastOpen = ((Character)(parenStack.peek())).UCharValue();
  163.                 else
  164.                     lastOpen = '\u0000';
  165.  
  166.                 break;
  167.  
  168.             // if the character is an asterisk, make sure it occurs in a place
  169.             // where an asterisk can legally go
  170.             case '*':
  171.                 if (UCharsThatCantPrecedeAsterisk.indexOf(lastC) != -1)
  172.                     error("Misplaced asterisk", p, description);
  173.                 break;
  174.  
  175.             // if the character is a question mark, make sure it follows an asterisk
  176.             case '?':
  177.                 if (lastC != '*')
  178.                     error("Misplaced ?", p, description);
  179.                 break;
  180.  
  181.             // if the character is an equals sign, make sure we haven't seen another
  182.             // equals sign or a slash yet
  183.             case '=':
  184.                 if (havePipe || haveEquals)
  185.                     error("More than one = or / in rule", p, description);
  186.                 haveEquals = TRUE;
  187.                 break;
  188.  
  189.             // if the character is a slash, make sure we haven't seen another slash
  190.             // or an equals sign yet
  191.             case '/':
  192.                 if (havePipe || haveEquals)
  193.                     error("More than one = or / in rule", p, description);
  194.                 if (sawVarName)
  195.                     error("Unknown variable name", p, description);
  196.                 havePipe = TRUE;
  197.                 break;
  198.  
  199.             // if the character is an exclamation point, make sure it occurs only
  200.             // at the beginning of a rule
  201.             case '!':
  202.                 if (lastC != ';' && lastC != '\u0000')
  203.                     error("! can only occur at the beginning of a rule", p, description);
  204.                 break;
  205.  
  206.             // if the character is a backslash, skip the character that follows it
  207.             // (it'll get treated as a literal character)
  208.             case '\\':
  209.                 ++p;
  210.                 break;
  211.  
  212.             // we don't have to do anything special on a period
  213.             case '.':
  214.                 break;
  215.  
  216.             // if the character is a syntax character that can only occur
  217.             // inside [], make sure that it does in fact only occur inside [].
  218.             case '^':
  219.             case '-':
  220.             case ':':
  221.                 if (lastOpen != '[' && lastOpen != '<')
  222.                     error("Illegal character", p, description);
  223.                 break;
  224.  
  225.             // if the character is a semicolon, do the following...
  226.             case ';':
  227.                 // make sure the rule contains something and that there are no
  228.                 // unbalanced parentheses or brackets
  229.                 if (lastC == ';' || lastC == '\u0000')
  230.                     error("Empty rule", p, description);
  231.                 if (!parenStack.empty())
  232.                     error("Unbalanced parenheses", p, description);
  233.  
  234.                 if (parenStack.empty()) {
  235.                     // if the rule contained an = sign, call processSubstitution()
  236.                     // to replace the substitution name with the substitution text
  237.                     // wherever it appears in the description
  238.                     if (haveEquals)
  239.                         description = processSubstitution(description.substring(ruleStart,
  240.                                         p), description, p + 1);
  241.                     else {
  242.                         // otherwise, check to make sure the rule doesn't reference
  243.                         // any undefined substitutions
  244.                         if (sawVarName)
  245.                             error("Unknown variable name", p, description);
  246.  
  247.                         // then add it to tempRuleList
  248.                         tempRuleList.addElement(description.substring(ruleStart, p));
  249.                     }
  250.                     
  251.                     // and reset everything to process the next rule
  252.                     ruleStart = p + 1;
  253.                     haveEquals = havePipe = sawVarName = FALSE;
  254.                 }
  255.                 break;
  256.  
  257.             // if the character is a vertical bar, check to make sure that it
  258.             // occurs inside a () expression and that the character that precedes
  259.             // it isn't also a vertical bar
  260.             case '|':
  261.                 if (lastC == '|')
  262.                     error("Empty alternative", p, description);
  263.                 if (parenStack.empty() || lastOpen != '(')
  264.                     error("Misplaced |", p, description);
  265.                 break;
  266.  
  267.             // if the character is anything else (escaped characters are
  268.             // skipped and don't make it here), it's an error
  269.             default:
  270.                 if (c >= ' ' && c < '\u007f' && !Character.isLetter(c) &&
  271.                                 !Character.isDigit(c))
  272.                     error("Illegal character", p, description);
  273.                 break;
  274.         }
  275.         lastC = c;
  276.         ++p;
  277.     }
  278.     if (tempRuleList.size() == 0)
  279.         error("No valid rules in description", p, description);
  280.     return tempRuleList;
  281. }
  282.  
  283. /**
  284.  * This function performs variable-name substitutions.  First it does syntax
  285.  * checking on the variable-name definition.  If it's syntactically valid, it
  286.  * then goes through the remainder of the description and does a simple
  287.  * find-and-replace of the variable name with its text.  (The variable text
  288.  * must be enclosed in either [] or () for this to work.)
  289.  */
  290. UnicodeString RuleBasedBreakIteratorBuilder::processSubstitution(UnicodeString substitutionRule, UnicodeString description,
  291.                         int32_t startPos) {
  292.     // isolate out the text on either side of the equals sign
  293.     UnicodeString replace;
  294.     UnicodeString replaceWith;
  295.     int32_t equalPos = substitutionRule.indexOf('=');
  296.     replace = substitutionRule.substring(0, equalPos);
  297.     replaceWith = substitutionRule.substring(equalPos + 1);
  298.  
  299.     // check to see whether the substitution name is something we've declared
  300.     // to be "special".  For RuleBasedBreakIterator itself, this is "<ignore>".
  301.     // This function takes care of any extra processing that has to be done
  302.     // with "special" substitution names.
  303.     handleSpecialSubstitution(replace, replaceWith, startPos, description);
  304.  
  305.     // perform various other syntax checks on the rule
  306.     if (replaceWith.length() == 0)
  307.         error("Nothing on right-hand side of =", startPos, description);
  308.     if (replace.length() == 0)
  309.         error("Nothing on left-hand side of =", startPos, description);
  310.     if (replace.length() == 2 && replace.UCharAt(0) != '\\')
  311.         error("Illegal left-hand side for =", startPos, description);
  312.     if (replace.length() >= 3 && replace.UCharAt(0) != '<' && replace.UCharAt(equalPos - 1)
  313.                     != '>')
  314.         error("Illegal left-hand side for =", startPos, description);
  315.     if (!(replaceWith.UCharAt(0) == '[' && replaceWith.UCharAt(replaceWith.length() - 1)
  316.                     == ']') && !(replaceWith.UCharAt(0) == '(' && replaceWith.UCharAt(
  317.                     replaceWith.length() - 1) == ')'))
  318.         error("Illegal right-hand side for =", startPos, description);
  319.  
  320.     // now go through the rest of the description (which hasn't been broken up
  321.     // into separate rules yet) and replace every occurrence of the
  322.     // substitution name with the substitution body
  323.     UnicodeString result = new UnicodeString();
  324.     result.append(description.substring(0, startPos));
  325.     int32_t lastPos = startPos;
  326.     int32_t pos = description.indexOf(replace, startPos);
  327.     while (pos != -1) {
  328.         result.append(description.substring(lastPos, pos));
  329.         result.append(replaceWith);
  330.         lastPos = pos + replace.length();
  331.         pos = description.indexOf(replace, lastPos);
  332.     }
  333.     result.append(description.substring(lastPos));
  334.     return result.toString();
  335. }
  336.  
  337. /**
  338.  * This function defines a protocol for handling substitution names that
  339.  * are "special," i.e., that have some property beyond just being
  340.  * substitutions.  At the RuleBasedBreakIterator level, we have one
  341.  * special substitution name, "<ignore>".  Subclasses can override this
  342.  * function to add more.  Any special processing that has to go on beyond
  343.  * that which is done by the normal substitution-processing code is done
  344.  * here.
  345.  */
  346. void RuleBasedBreakIteratorBuilder::handleSpecialSubstitution(UnicodeString replace, UnicodeString replaceWith,
  347.                     int32_t startPos, UnicodeString description) {
  348.     // if we get a definition for a substitution called "ignore", it defines
  349.     // the ignore characters for the iterator.  Check to make sure the expression
  350.     // is a [] expression, and if it is, parse it and store the characters off
  351.     // to the side.
  352.     if (replace.equals("<ignore>")) {
  353.         if (replaceWith.UCharAt(0) == '(')
  354.             error("Ignore group can't be enclosed in (", startPos, description);
  355.         ignoreChars = CharSet.parseString(replaceWith);
  356.     }
  357. }
  358.  
  359. /**
  360.  * This function builds the character category table.  On entry,
  361.  * tempRuleList is a vector of break rules that has had variable names substituted.
  362.  * On exit, the charCategoryTable data member has been initialized to hold the
  363.  * character category table, and tempRuleList's rules have been munged to contain
  364.  * character category numbers everywhere a literal character or a [] expression
  365.  * originally occurred.
  366.  */
  367. void RuleBasedBreakIteratorBuilder::buildCharCategories(Vector tempRuleList) {
  368.     int32_t bracketLevel = 0;
  369.     int32_t p = 0;
  370.     int32_t lineNum = 0;
  371.  
  372.     // build hash table of every literal character or [] expression in the rule list
  373.     // and use CharSet.parseString() to derive a CharSet object representing the
  374.     // characters each refers to
  375.     expressions = new Hashtable();
  376.     while (lineNum < tempRuleList.size()) {
  377.         UnicodeString line = (UnicodeString)(tempRuleList.elementAt(lineNum));
  378.         p = 0;
  379.         while (p < line.length()) {
  380.             UChar c = line.UCharAt(p);
  381.             switch (c) {
  382.                 // skip over all syntax characters except [
  383.                 case '{': case '}': case '(': case ')': case '*': case '.':
  384.                 case '/': case '|': case ';': case '?': case '!':
  385.                     break;
  386.  
  387.                 // for [, find the matching ] (taking nested [] pairs into account)
  388.                 // and add the whole expression to the expression list
  389.                 case '[':
  390.                     int32_t q = p + 1;
  391.                     ++bracketLevel;
  392.                     while (q < line.length() && bracketLevel != 0) {
  393.                         c = line.UCharAt(q);
  394.                         if (c == '[')
  395.                             ++bracketLevel;
  396.                         else if (c == ']')
  397.                             --bracketLevel;
  398.                         ++q;
  399.                     }
  400.                     if (expressions.get(line.substring(p, q)) == 0) {
  401.                         expressions.put(line.substring(p, q), CharSet.parseString(line.
  402.                                         substring(p, q)));
  403.                     }
  404.                     p = q - 1;
  405.                     break;
  406.  
  407.                 // for \ sequences, just move to the next character and treat
  408.                 // it as a single character
  409.                 case '\\':
  410.                     ++p;
  411.                     c = line.UCharAt(p);
  412.                     // DON'T break; fall through into "default" clause
  413.  
  414.                 // for an isolated single character, add it to the expression list
  415.                 default:
  416.                     expressions.put(line.substring(p, p + 1), CharSet.parseString(line.
  417.                                     substring(p, p + 1)));
  418.                     break;
  419.             }
  420.             ++p;
  421.         }
  422.         ++lineNum;
  423.     }
  424.     // dump CharSet's internal expression cache
  425.     CharSet.releaseExpressionCache();
  426.  
  427.     // create the temporary category table (which is a vector of CharSet objects)
  428.     categories = new Vector();
  429.     if (ignoreChars != 0)
  430.         categories.addElement(ignoreChars);
  431.     else
  432.         categories.addElement(new CharSet());
  433.     ignoreChars = 0;
  434.  
  435.     // Derive the character categories.  Go through the existing character categories
  436.     // looking for overlap.  Any time there's overlap, we create a new character
  437.     // category for the characters that overlapped and remove them from their original
  438.     // category.  At the end, any characters that are left in the expression haven't
  439.     // been mentioned in any category, so another new category is created for them.
  440.     // For example, if the first expression is [abc], then a, b, and c will be placed
  441.     // into a single character category.  If the next expression is [bcd], we will first
  442.     // remove b and c from their existing category (leaving a behind), create a new
  443.     // category for b and c, and then create another new category for d (which hadn't
  444.     // been mentioned in the previous expression).
  445.     // At no time should a character ever occur in more than one character category.
  446.     
  447.     // for each expression in the expressions list, do...
  448.     Enumeration iter = expressions.elements();
  449.     while (iter.hasMoreElements()) {
  450.         // initialize the working char set to the chars in the current expression
  451.         CharSet e = (CharSet)iter.nextElement();
  452.         
  453.         // for each category in the category list, do...
  454.         for (int32_t j = categories.size() - 1; !e.empty() && j > 0; j--) {
  455.             
  456.             // if there's overlap between the current working set of chars
  457.             // and the current category...
  458.             CharSet that = (CharSet)(categories.elementAt(j));
  459.             if (!that.intersection(e).empty()) {
  460.                 
  461.                 // add a new category for the characters that were in the
  462.                 // current category but not in the working char set
  463.                 CharSet temp = that.difference(e);
  464.                 if (!temp.empty())
  465.                     categories.addElement(temp);
  466.                     
  467.                 // remove those characters from the working char set and replace
  468.                 // the current category with the characters that it did
  469.                 // have in common with the current working char set
  470.                 temp = e.intersection(that);
  471.                 e = e.difference(that);
  472.                 if (!temp.equals(that))
  473.                     categories.setElementAt(temp, j);
  474.             }
  475.         }
  476.         
  477.         // if there are still characters left in the working char set,
  478.         // add a new category containing them
  479.         if (!e.empty())
  480.             categories.addElement(e);
  481.     }
  482.  
  483.     // we have the ignore characters stored in position 0.  Make an extra pass through
  484.     // the character category list and remove anything from the ignore list that shows
  485.     // up in some other category
  486.     CharSet allChars = new CharSet();
  487.     for (int32_t i = 1; i < categories.size(); i++)
  488.         allChars = allChars.union((CharSet)(categories.elementAt(i)));
  489.     CharSet ignoreChars = (CharSet)(categories.elementAt(0));
  490.     ignoreChars = ignoreChars.difference(allChars);
  491.     categories.setElementAt(ignoreChars, 0);
  492.  
  493.     // now that we've derived the character categories, go back through the expression
  494.     // list and replace each CharSet object with a String that represents the
  495.     // character categories that expression refers to.  The String is encoded: each
  496.     // character is a character category number (plus 0x100 to avoid confusing them
  497.     // with syntax characters in the rule grammar)
  498.     iter = expressions.keys();
  499.     while (iter.hasMoreElements()) {
  500.         UnicodeString key = (UnicodeString)iter.nextElement();
  501.         CharSet cs = (CharSet)expressions.get(key);
  502.         UnicodeString cats = new UnicodeString();
  503.         
  504.         // for each category...
  505.         for (int32_t j = 0; j < categories.size(); j++) {
  506.             
  507.             // if the current expression contains characters in that category...
  508.             CharSet temp = cs.intersection((CharSet)(categories.elementAt(j)));
  509.             if (!temp.empty()) {
  510.                 
  511.                 // then add the encoded category number to the String for this
  512.                 // expression
  513.                 cats.append((UChar)(0x100 + j));
  514.                 if (temp.equals(cs))
  515.                     break;
  516.             }
  517.         }
  518.         
  519.         // once we've finished building the encoded String for this expression,
  520.         // replace the CharSet object with it
  521.         expressions.put(key, cats.toString());
  522.     }
  523.  
  524.     // and finally, we turn the temporary category table into a permanent category
  525.     // table, which is a CompactByteArray. (we skip category 0, which by definition
  526.     // refers to all characters not mentioned specifically in the rules)
  527.     UCharCategoryTable = new CompactByteArray((int8_t)0);
  528.     
  529.     // for each category...
  530.     for (int32_t i = 0; i < categories.size(); i++) {
  531.         CharSet UChars = (CharSet)(categories.elementAt(i));
  532.         
  533.         // go through the character ranges in the category one by one...
  534.         Enumeration enum = UChars.getChars();
  535.         while (enum.hasMoreElements()) {
  536.             UChar* range = (UChar*)(enum.nextElement());
  537.             
  538.             // and set the corresponding elements in the CompactArray accordingly
  539.             if (i != 0)
  540.                 UCharCategoryTable.setElementAt(range[0], range[1], (int8_t)i);
  541.                 
  542.             // (category 0 is special-- it's the hiding place for the ignore
  543.             // characters, whose real category number in the CompactArray is
  544.             // -1 [this is because category 0 contains all characters not
  545.             // specifically mentioned anywhere in the rules] )
  546.             else
  547.                 UCharCategoryTable.setElementAt(range[0], range[1], IGNORE);
  548.         }
  549.     }
  550.     
  551.     // once we've populated the CompactArray, compact it
  552.     UCharCategoryTable.compact();
  553.     // initialize numCategories
  554.     numCategories = categories.size();
  555. }
  556.  
  557. /**
  558.  * This is the function that builds the forward state table.  Most of the real
  559.  * work is done in parseRule(), which is called once for each rule in the
  560.  * description.
  561.  */
  562. void RuleBasedBreakIteratorBuilder::buildStateTable(Vector tempRuleList) {
  563.         // initialize our temporary state table, and fill it with two states:
  564.         // state 0 is a dummy state that allows state 1 to be the starting state
  565.         // and 0 to represent "stop".  State 1 is added here to seed things
  566.         // before we start parsing
  567.         tempStateTable = new Vector();
  568.         tempStateTable.addElement(new int16_t[numCategories + 1]);
  569.         tempStateTable.addElement(new int16_t[numCategories + 1]);
  570.         
  571.         // call parseRule() for every rule in the rule list (except those which
  572.         // start with !, which are actually backwards-iteration rules)
  573.         for (int32_t i = 0; i < tempRuleList.size(); i++) {
  574.             UnicodeString rule = (UnicodeString)tempRuleList.elementAt(i);
  575.             if (rule.UCharAt(0) != '!')
  576.                 parseRule(rule, TRUE);
  577.         }
  578.         
  579.         // finally, use finishBuildingStateTable() to minimize the number of
  580.         // states in the table and perform some other cleanup work
  581.         finishBuildingStateTable(TRUE);
  582. }
  583.  
  584. /**
  585.  * This is where most of the work really happens.  This routine parses a single
  586.  * rule in the rule description, adding and modifying states in the state
  587.  * table according to the new expression.  The state table is kept deterministic
  588.  * throughout the whole operation, although some ugly postprocessing is needed
  589.  * to handle the *? token.
  590.  */
  591. void RuleBasedBreakIteratorBuilder::parseRule(UnicodeString rule, bool_t forward) {
  592.     // algorithm notes:
  593.     //   - The basic idea here is to read successive character-category groups
  594.     //   from the input string.  For each group, you create a state and point
  595.     //   the appropriate entries in the previous state to it.  This produces a
  596.     //   straight line from the start state to the end state.  The {}, *, and (|)
  597.     //   idioms produce branches in this straight line.  These branches (states
  598.     //   that can transition to more than one other state) are called "decision
  599.     //   points."  A list of decision points is kept.  This contains a list of
  600.     //   all states that can transition to the next state to be created.  For a
  601.     //   straight line progression, the only thing in the decision-point list is
  602.     //   the current state.  But if there's a branch, the decision-point list
  603.     //   will contain all of the beginning points of the branch when the next
  604.     //   state to be created represents the end point of the branch.  A stack is
  605.     //   used to save decision point lists in the presence of nested parentheses
  606.     //   and the like.  For example, when a { is encountered, the current decision
  607.     //   point list is saved on the stack and restored when the corresponding }
  608.     //   is encountered.  This way, after the } is read, the decision point list
  609.     //   will contain both the state right before the } _and_ the state before
  610.     //   the whole {} expression.  Both of these states can transition to the next
  611.     //   state after the {} expression.
  612.     //   - one complication arises when we have to stamp a transition value into
  613.     //   an array cell that already contains one.  The updateStateTable() and
  614.     //   mergeStates() functions handle this case.  Their basic approach is to
  615.     //   create a new state that combines the two states that conflict and point
  616.     //   at it when necessary.  This happens recursively, so if the merged states
  617.     //   also conflict, they're resolved in the same way, and so on.  There are
  618.     //   a number of tests aimed at preventing infinite recursion.
  619.     //   - another complication arises with repeating characters.  It's somewhat
  620.     //   ambiguous whether the user wants a greedy or non-greedy match in these cases.
  621.     //   (e.g., whether "[a-z]*abc" means the SHORTEST sequence of letters ending in
  622.     //   "abc" or the LONGEST sequence of letters ending in "abc".  We've adopted
  623.     //   the *? to mean "shortest" and * by itself to mean "longest".  (You get the
  624.     //   same result with both if there's no overlap between the repeating character
  625.     //   group and the group immediately following it.)  Handling the *? token is
  626.     //   rather complicated and involves keeping track of whether a state needs to
  627.     //   be merged (as described above) or merely overwritten when you update one of
  628.     //   its cells, and copying the contents of a state that loops with a *? token
  629.     //   into some of the states that follow it after the rest of the table-building
  630.     //   process is complete ("backfilling").
  631.     // implementation notes:
  632.     //   - This function assumes syntax checking has been performed on the input string
  633.     //   prior to its being passed in here.  It assumes that parentheses are
  634.     //   balanced, all literal characters are enclosed in [] and turned into category
  635.     //   numbers, that there are no illegal characters or character sequences, and so
  636.     //   on.  Violation of these invariants will lead to undefined behavior.
  637.     //   - It'd probably be better to use linked lists rather than Vector and Stack
  638.     //   to maintain the decision point list and stack.  I went for simplicity in
  639.     //   this initial implementation.  If performance is critical enough, we can go
  640.     //   back and fix this later.
  641.     //   -There are a number of important limitations on the *? token.  It does not work
  642.     //   right when followed by a repeating character sequence (e.g., ".*?(abc)*")
  643.     //   (although it does work right when followed by a single repeating character).
  644.     //   It will not always work right when nested in parentheses or braces (although
  645.     //   sometimes it will).  It also will not work right if the group of repeating
  646.     //   characters and the group of characters that follows overlap partially
  647.     //   (e.g., "[a-g]*?[e-j]").  None of these capabilites was deemed necessary for
  648.     //   describing breaking rules we know about, so we left them out for
  649.     //   expeditiousness.
  650.     //   - The / token is not fully general: There are cases where it will put the
  651.     //   break in the wrong place.  In particular, rule sets such as "?; cat/alog;"
  652.     //   will put a break after "cat" instead of after "c" ANY time it sees "cat",
  653.     //   regardless of whether the text matches "catalog" or not.  Also, rules such
  654.     //   as "[a-z]*?abc;" will be treated the same as "[a-z]*?aa*bc;"-- that is,
  655.     //   if the string ends in "aaaabc", the break will go before the first "a"
  656.     //   rather than the last one.  Both of these are limitations in the design
  657.     //   of RuleBasedBreakIterator and not limitations of the rule parser.
  658.  
  659.     int32_t p = 0;
  660.     int32_t currentState = 1;   // don't use state number 0; 0 means "stop"
  661.     int32_t lastState = currentState;
  662.     UnicodeString pendingChars = "";
  663.  
  664.     decisionPointStack = new Stack();
  665.     decisionPointList = new Vector();
  666.     loopingStates = new Vector();
  667.     statesToBackfill = new Vector();
  668.  
  669.     int16_t* state;
  670.     bool_t sawEarlyBreak = FALSE;
  671.  
  672.     // if we're adding rules to the backward state table, mark the initial state
  673.     // as a looping state
  674.     if (!forward)
  675.         loopingStates.addElement(new Integer(1));
  676.  
  677.     // put the current state on the decision point list before we start
  678.     decisionPointList.addElement(new Integer(currentState)); // we want currentState to
  679.                                                              // be 1 here...
  680.     currentState = tempStateTable.size() - 1;   // but after that, we want it to be
  681.                                                 // 1 less than the state number of the next state
  682.     while (p < rule.length()) {
  683.         UChar c = rule.UCharAt(p);
  684.         clearLoopingStates = FALSE;
  685.  
  686.         // this section handles literal characters, escaped character (which are
  687.         // effectively literal characters too), the . token, and [] expressions
  688.         if (c == '[' || c == '\\' || Character.isLetter(c) || Character.isDigit(c)
  689.                         || c < ' ' || c == '.' || c >= '\u007f') {
  690.             
  691.             // if we're not on a period, isolate the expression and look up
  692.             // the corresponding category list
  693.             if (c != '.') {
  694.                 int32_t q = p;
  695.                 
  696.                 // if we're on a backslash, the expression is the character
  697.                 // after the backslash
  698.                 if (c == '\\') {
  699.                     q = p + 2;
  700.                     ++p;
  701.                 }
  702.                 
  703.                 // if we're on an opening bracket, scan to the closing bracket
  704.                 // to isolate the expression
  705.                 else if (c == '[') {
  706.                     int32_t bracketLevel = 1;
  707.                     while (bracketLevel > 0) {
  708.                         ++q;
  709.                         c = rule.UCharAt(q);
  710.                         if (c == '[')
  711.                             ++bracketLevel;
  712.                         else if (c == ']')
  713.                             --bracketLevel;
  714.                         else if (c == '\\')
  715.                             ++q;
  716.                     }
  717.                     ++q;
  718.                 }
  719.                 
  720.                 // otherwise, the expression is just the character itself
  721.                 else
  722.                     q = p + 1;
  723.                     
  724.                 // look up the category list for the expression and store it
  725.                 // in pendingChars
  726.                 pendingChars = (UnicodeString)expressions.get(rule.substring(p, q));
  727.                 
  728.                 // advance the current position past the expression
  729.                 p = q - 1;
  730.             }
  731.             
  732.             // if the character we're on is a period, we end up down here
  733.             else {
  734.                 int32_t rowNum = ((Integer)decisionPointList.lastElement()).intValue();
  735.                 state = (int16_t*)tempStateTable.elementAt(rowNum);
  736.                 
  737.                 // if the period is followed by an asterisk, then just set the current
  738.                 // state to loop back on itself
  739.                 if (p + 1 < rule.length() && rule.UCharAt(p + 1) == '*' && state[0] != 0) {
  740.                     decisionPointList.addElement(new Integer(state[0]));
  741.                     pendingChars = "";
  742.                     ++p;
  743.                 }
  744.                 
  745.                 // otherwise, fabricate a category list ("pendingChars") with
  746.                 // every category in it
  747.                 else {
  748.                     UnicodeString temp = new UnicodeString();
  749.                     for (int32_t i = 0; i < numCategories; i++)
  750.                         temp.append((UChar)(i + 0x100));
  751.                     pendingChars = temp.toString();
  752.                 }
  753.             }
  754.  
  755.             // we'll end up in here for all expressions except for .*, which is
  756.             // special-cased above
  757.             if (pendingChars.length() != 0) {
  758.                 
  759.                 // if the expression is followed by an asterisk, then push a copy
  760.                 // of the current desicion point list onto the stack (this is
  761.                 // the same thing we do on an opening brace)
  762.                 if (p + 1 < rule.length() && rule.UCharAt(p + 1) == '*')
  763.                     decisionPointStack.push(decisionPointList.clone());
  764.                     
  765.                 // create a new state, add it to the list of states to backfill
  766.                 // if we have looping states to worry about, set its "don't make
  767.                 // me an accepting state" flag if we've seen a slash, and add
  768.                 // it to the end of the state table
  769.                 int32_t newState = tempStateTable.size();
  770.                 if (loopingStates.size() != 0)
  771.                     statesToBackfill.addElement(new Integer(newState));
  772.                 state = new int16_t[numCategories + 1];
  773.                 if (sawEarlyBreak)
  774.                     state[numCategories] = 0x4000;
  775.                 tempStateTable.addElement(state);
  776.                 
  777.                 // update everybody in the decision point list to point to
  778.                 // the new state (this also performs all the reconciliation
  779.                 // needed to make the table deterministic), then clear the
  780.                 // decision point list
  781.                 updateStateTable(decisionPointList, pendingChars, (int16_t)newState);
  782.                 decisionPointList.removeAllElements();
  783.                 
  784.                 // add all states created since the last literal character we've
  785.                 // seen to the decision point list
  786.                 lastState = currentState;
  787.                 do {
  788.                     ++currentState;
  789.                     decisionPointList.addElement(new Integer(currentState));
  790.                 } while (currentState + 1 < tempStateTable.size());
  791.             }
  792.         }
  793.  
  794.         // a { marks the beginning of an optional run of characters.  Push a
  795.         // copy of the current decision point list onto the stack.  This saves
  796.         // it, preventing it from being affected by whatever's inside the parentheses.
  797.         // This decision point list is restored when a } is encountered.
  798.         else if (c == '{') {
  799.             decisionPointStack.push(decisionPointList.clone());
  800.         }
  801.  
  802.         // a } marks the end of an optional run of characters.  Pop the last decision
  803.         // point list off the stack and merge it with the current decision point list.
  804.         // a * denotes a repeating character or group (* after () is handled separately
  805.         // below).  In addition to restoring the decision point list, modify the
  806.         // current state to point to itself on the appropriate character categories.
  807.         else if (c == '}' || c == '*') {
  808.             // when there's a *, update the current state to loop back on itself
  809.             // on the character categories that caused us to enter this state
  810.             if (c == '*') {
  811.                 for (int32_t i = lastState + 1; i < tempStateTable.size(); i++) {
  812.                     Vector temp = new Vector();
  813.                     temp.addElement(new Integer(i));
  814.                     updateStateTable(temp, pendingChars, (int16_t)(lastState + 1));
  815.                 }
  816.             }
  817.             
  818.             // pop the top element off the decision point stack and merge
  819.             // it with the current decision point list (this causes the divergent
  820.             // paths through the state table to come together again on the next
  821.             // new state)
  822.             Vector temp = (Vector)decisionPointStack.pop();
  823.             for (int32_t i = 0; i < decisionPointList.size(); i++)
  824.                 temp.addElement(decisionPointList.elementAt(i));
  825.             decisionPointList = temp;
  826.         }
  827.  
  828.         // a ? after a * modifies the behavior of * in cases where there is overlap
  829.         // between the set of characters that repeat and the characters which follow.
  830.         // Without the ?, all states following the repeating state, up to a state which
  831.         // is reached by a character that doesn't overlap, will loop back into the
  832.         // repeating state.  With the ?, the mark states following the *? DON'T loop
  833.         // back into the repeating state.  Thus, "[a-z]*xyz" will match the longest
  834.         // sequence of letters that ends in "xyz," while "[a-z]*? will match the
  835.         // _shortest_ sequence of letters that ends in "xyz".
  836.         // We use extra bookkeeping to achieve this effect, since everything else works
  837.         // according to the "longest possible match" principle.  The basic principle
  838.         // is that transitions out of a looping state are written in over the looping
  839.         // value instead of being reconciled, and that we copy the contents of the
  840.         // looping state into empty cells of all non-terminal states that follow the
  841.         // looping state.
  842.         else if (c == '?') {
  843.             setLoopingStates(decisionPointList, decisionPointList);
  844.         }
  845.  
  846.         // a ( marks the beginning of a sequence of characters.  Parentheses can either
  847.         // contain several alternative character sequences (i.e., "(ab|cd|ef)"), or
  848.         // they can contain a sequence of characters that can repeat (i.e., "(abc)*").  Thus,
  849.         // A () group can have multiple entry and exit points.  To keep track of this,
  850.         // we reserve TWO spots on the decision-point stack.  The top of the stack is 
  851.         // the list of exit points, which becomes the current decision point list when
  852.         // the ) is reached.  The next entry down is the decision point list at the
  853.         // beginning of the (), which becomes the current decision point list at every
  854.         // entry point.
  855.         // In addition to keeping track of the exit points and the active decision
  856.         // points before the ( (i.e., the places from which the () can be entered),
  857.         // we need to keep track of the entry points in case the expression loops
  858.         // (i.e., is followed by *).  We do that by creating a dummy state in the
  859.         // state table and adding it to the decision point list (BEFORE it's duplicated
  860.         // on the stack).  Nobody points to this state, so it'll get optimized out
  861.         // at the end.  It exists only to hold the entry points in case the ()
  862.         // expression loops.
  863.         else if (c == '(') {
  864.             
  865.             // add a new state to the state table to hold the entry points into
  866.             // the () expression
  867.             tempStateTable.addElement(new int16_t[numCategories + 1]);
  868.             
  869.             // we have to adjust lastState and currentState to account for the
  870.             // new dummy state
  871.             lastState = currentState;
  872.             ++currentState;
  873.             
  874.             // add the current state to the decision point list (add it at the
  875.             // BEGINNING so we can find it later)
  876.             decisionPointList.insertElementAt(new Integer(currentState), 0);
  877.             
  878.             // finally, push a copy of the current decision point list onto the
  879.             // stack (this keeps track of the active decision point list before
  880.             // the () expression), followed by an empty decision point list
  881.             // (this will hold the exit points)
  882.             decisionPointStack.push(decisionPointList.clone());
  883.             decisionPointStack.push(new Vector());
  884.         }
  885.  
  886.         // a | separates alternative character sequences in a () expression.  When
  887.         // a | is encountered, we add the current decision point list to the exit-point
  888.         // list, and restore the decision point list to its state prior to the (.
  889.         else if (c == '|') {
  890.             
  891.             // pick out the top two decision point lists on the stack
  892.             Vector oneDown = (Vector)decisionPointStack.pop();
  893.             Vector twoDown = (Vector)decisionPointStack.peek();
  894.             decisionPointStack.push(oneDown);
  895.             
  896.             // append the current decision point list to the list below it
  897.             // on the stack (the list of exit points), and restore the
  898.             // current decision point list to its state before the () expression
  899.             for (int32_t i = 0; i < decisionPointList.size(); i++)
  900.                 oneDown.addElement(decisionPointList.elementAt(i));
  901.             decisionPointList = (Vector)twoDown.clone();
  902.         }
  903.  
  904.         // a ) marks the end of a sequence of characters.  We do one of two things
  905.         // depending on whether the sequence repeats (i.e., whether the ) is followed
  906.         // by *):  If the sequence doesn't repeat, then the exit-point list is merged
  907.         // with the current decision point list and the decision point list from before
  908.         // the () is thrown away.  If the sequence does repeat, then we fish out the
  909.         // state we were in before the ( and copy all of its forward transitions
  910.         // (i.e., every transition added by the () expression) into every state in the
  911.         // exit-point list and the current decision point list.  The current decision
  912.         // point list is then merged with both the exit-point list AND the saved version
  913.         // of the decision point list from before the ().  Then we throw out the *.
  914.         else if (c == ')') {
  915.             
  916.             // pull the exit point list off the stack, merge it with the current
  917.             // decision point list, and make the merged version the current
  918.             // decision point list
  919.             Vector exitPoints = (Vector)decisionPointStack.pop();
  920.             for (int32_t i = 0; i < decisionPointList.size(); i++)
  921.                 exitPoints.addElement(decisionPointList.elementAt(i));
  922.             decisionPointList = exitPoints;
  923.  
  924.             // if the ) isn't followed by a *, then all we have to do is throw
  925.             // away the other list on the decision point stack, and we're done
  926.             if (p + 1 >= rule.length() || rule.UCharAt(p + 1) != '*')
  927.                 decisionPointStack.pop();
  928.                 
  929.             // but if the sequence repeats, we have a lot more work to do...
  930.             else {
  931.                 
  932.                 // now exitPoints and decisionPointList have to point to equivalent
  933.                 // vectors, but not the SAME vector
  934.                 exitPoints = (Vector)decisionPointList.clone();
  935.                 
  936.                 // pop the original decision point list off the stack
  937.                 Vector temp = (Vector)decisionPointStack.pop();
  938.  
  939.                 // we squirreled away the row number of our entry point list
  940.                 // at the beginning of the original decision point list.  Fish
  941.                 // that state number out and retrieve the entry point list
  942.                 int32_t tempStateNum = ((Integer)temp.firstElement()).intValue();
  943.                 int16_t* tempState = (int16_t*)tempStateTable.elementAt(tempStateNum);
  944.  
  945.                 // merge the original decision point list with the current
  946.                 // decision point list
  947.                 for (int32_t i = 0; i < decisionPointList.size(); i++)
  948.                     temp.addElement(decisionPointList.elementAt(i));
  949.                 decisionPointList = temp;
  950.  
  951.                 // finally, copy every forward reference from the entry point
  952.                 // list into every state in the new decision point list
  953.                 for (int32_t i = 0; i < tempState.length; i++) {
  954.                     if (tempState[i] > tempStateNum)
  955.                         updateStateTable(exitPoints,
  956.                                          new Character((UChar)(i + 0x100)).toString(),
  957.                                          tempState[i]);
  958.                 }
  959.                 
  960.                 // update lastState and currentState, and throw away the *
  961.                 lastState = currentState;
  962.                 currentState = tempStateTable.size() - 1;
  963.                 ++p;
  964.             }
  965.         }
  966.  
  967.         // a / marks the position where the break is to go if the character sequence
  968.         // matches this rule.  We update the flag word of every state on the decision
  969.         // point list to mark them as ending states, and take note of the fact that 
  970.         // we've seen the slash
  971.         else if (c == '/') {
  972.             sawEarlyBreak = TRUE;
  973.             for (int32_t i = 0; i < decisionPointList.size(); i++) {
  974.                 state = (int16_t*)tempStateTable.elementAt(((Integer)decisionPointList.
  975.                                 elementAt(i)).intValue());
  976.                 state[numCategories] |= 0x8000;
  977.             }
  978.         }
  979.  
  980.         // if we get here without executing any of the above clauses, we have a
  981.         // syntax error.  However, for now we just ignore the offending character
  982.         // and move on
  983.  
  984.         // clearLoopingStates is a signal back from updateStateTable() that we've
  985.         // transitioned to a state that won't loop back to the current looping
  986.         // state.  (In other words, we've gotten to a point where we can no longer
  987.         // go back into a *? we saw earlier.)  Clear out the list of looping states
  988.         // and backfill any states that need to be backfilled.
  989.         if (clearLoopingStates)
  990.             setLoopingStates(0, decisionPointList);
  991.  
  992.         // advance to the next character, now that we've processed the current
  993.         // character
  994.         ++p;
  995.     }
  996.  
  997.     // this takes care of backfilling any states that still need to be backfilled
  998.     setLoopingStates(0, decisionPointList);
  999.  
  1000.     // when we reach the end of the string, we do a postprocessing step to mark the
  1001.     // end states.  If we didn't see the / token, then the decision point list
  1002.     // contains every state that can transition to the end state-- that is, every
  1003.     // state that is the last state in a sequence that matches the rule.  All of
  1004.     // these states are considered "mark states"-- that is, states that cause the
  1005.     // position returned from next() to be updated.  A mark state represents a possible
  1006.     // break position.  This allows us to look ahead and remember how far the rule
  1007.     // matched before following the new branch (see next() for more information).
  1008.     // The temporary state table has an extra "flag column" at the end where this
  1009.     // information is stored.  We mark the end states by setting a flag in their
  1010.     // flag column.
  1011.     // (If we did see the /, we've already marked the end states.)
  1012.     if (!sawEarlyBreak) {
  1013.         for (int32_t i = 0; i < decisionPointList.size(); i++) {
  1014.             int32_t rowNum = ((Integer)decisionPointList.elementAt(i)).intValue();
  1015.             state = (int16_t*)tempStateTable.elementAt(rowNum);
  1016.             state[numCategories] |= 0x8000;
  1017.         }
  1018.     }
  1019. }
  1020.  
  1021. /**
  1022.  * Update entries in the state table, and merge states when necessary to keep
  1023.  * the table deterministic.
  1024.  * @param rows The list of rows that need updating (the decision point list)
  1025.  * @param pendingChars A character category list, encoded in a String.  This is the
  1026.  * list of the columns that need updating.
  1027.  * @param newValue Update the cells specfied above to contain this value
  1028.  */
  1029. void RuleBasedBreakIteratorBuilder::updateStateTable(Vector rows,
  1030.                                       UnicodeString pendingChars,
  1031.                                       int16_t newValue) {
  1032.     // create a dummy state that has the specified row number (newValue) in
  1033.     // the cells that need to be updated (those specified by pendingChars)
  1034.     // and 0 in the other cells
  1035.     int16_t* newValues = new int16_t[numCategories + 1];
  1036.     for (int32_t i = 0; i < pendingChars.length(); i++)
  1037.         newValues[(int32_t)(pendingChars.UCharAt(i)) - 0x100] = newValue;
  1038.  
  1039.     // go through the list of rows to update, and update them by calling
  1040.     // mergeStates() to merge them the the dummy state we created
  1041.     for (int32_t i = 0; i < rows.size(); i++) {
  1042.         mergeStates(((Integer)rows.elementAt(i)).intValue(), newValues, rows);
  1043.     }
  1044. }
  1045.  
  1046. /**
  1047.  * The real work of making the state table deterministic happens here.  This function
  1048.  * merges a state in the state table (specified by rowNum) with a state that is
  1049.  * passed in (newValues).  The basic process is to copy the nonzero cells in newStates
  1050.  * into the state in the state table (we'll call that oldValues).  If there's a
  1051.  * collision (i.e., if the same cell has a nonzero value in both states, and it's
  1052.  * not the SAME value), then we have to reconcile the collision.  We do this by
  1053.  * creating a new state, adding it to the end of the state table, and using this
  1054.  * function recursively to merge the original two states into a single, combined
  1055.  * state.  This process may happen recursively (i.e., each successive level may
  1056.  * involve collisions).  To prevent infinite recursion, we keep a log of merge
  1057.  * operations.  Any time we're merging two states we've merged before, we can just
  1058.  * supply the row number for the result of that merge operation rather than creating
  1059.  * a new state just like it.
  1060.  * @param rowNum The row number in the state table of the state to be updated
  1061.  * @param newValues The state to merge it with.
  1062.  * @param rowsBeingUpdated A copy of the list of rows passed to updateStateTable()
  1063.  * (itself a copy of the decision point list from parseRule()).  Newly-created
  1064.  * states get added to the decision point list if their "parents" were on it.
  1065.  */
  1066. void RuleBasedBreakIteratorBuilder::mergeStates(int32_t rowNum,
  1067.                                  int16_t* newValues,
  1068.                                  Vector rowsBeingUpdated) {
  1069.     int16_t* oldValues = (int16_t*)(tempStateTable.elementAt(rowNum));
  1070.     bool_t isLoopingState = loopingStates.contains(new Integer(rowNum));
  1071.  
  1072.     // for each of the cells in the rows we're reconciling, do...
  1073.     for (int32_t i = 0; i < oldValues.length; i++) {
  1074.         
  1075.         // if they contain the same value, we don't have to do anything
  1076.         if (oldValues[i] == newValues[i])
  1077.             continue;
  1078.             
  1079.         // if oldValues is a looping state and the state the current cell points to
  1080.         // is too, then we can just stomp over the current value of that cell (and
  1081.         // set the clear-looping-states flag if necessaru)
  1082.         else if (isLoopingState && loopingStates.contains(new Integer(oldValues[i]))) {
  1083.             if (newValues[i] != 0) {
  1084.                 if (oldValues[i] == 0)
  1085.                     clearLoopingStates = TRUE;
  1086.                 oldValues[i] = newValues[i];
  1087.             }
  1088.         }
  1089.         
  1090.         // if the current cell in oldValues is 0, copy in the corresponding value
  1091.         // from newValues
  1092.         else if (oldValues[i] == 0)
  1093.             oldValues[i] = newValues[i];
  1094.             
  1095.         // the last column of each row is the flag column.  Take care to merge the
  1096.         // flag words correctly
  1097.         else if (i == numCategories) {
  1098.             oldValues[i] = (int16_t)((newValues[i] & 0xc000) | oldValues[i]);
  1099.         }
  1100.         
  1101.         // if both newValues and oldValues have a nonzero value in the current
  1102.         // cell, and it isn't the same value both places...
  1103.         else if (oldValues[i] != 0 && newValues[i] != 0) {
  1104.             
  1105.             // look up this pair of cell values in the merge list.  If it's
  1106.             // found, update the cell in oldValues to point to the merged state
  1107.             int32_t combinedRowNum = searchMergeList(oldValues[i], newValues[i]);
  1108.             if (combinedRowNum != 0)
  1109.                 oldValues[i] = (int16_t)combinedRowNum;
  1110.                 
  1111.             // otherwise, we have to reconcile them...
  1112.             else {
  1113.                 // copy our row numbers into variables to make things easier
  1114.                 int32_t oldRowNum = oldValues[i];
  1115.                 int32_t newRowNum = newValues[i];
  1116.                 combinedRowNum = tempStateTable.size();
  1117.                 
  1118.                 // add this pair of row numbers to the merge list (create it first
  1119.                 // if we haven't created the merge list yet)
  1120.                 if (mergeList == 0)
  1121.                     mergeList = new Vector();
  1122.                 mergeList.addElement(new int32_t* { oldRowNum, newRowNum, combinedRowNum });
  1123.  
  1124.                 // create a new row to represent the merged state, and copy the
  1125.                 // contents of oldRow into it, then add it to the end of the
  1126.                 // state table and update the original row (oldValues) to point
  1127.                 // to the new, merged, state
  1128.                 int16_t* newRow = new int16_t[numCategories + 1];
  1129.                 int16_t* oldRow = (int16_t*)(tempStateTable.elementAt(oldRowNum));
  1130.                 System.arraycopy(oldRow, 0, newRow, 0, numCategories + 1);
  1131.                 tempStateTable.addElement(newRow);
  1132.                 oldValues[i] = (int16_t)combinedRowNum;
  1133.  
  1134.                 // if the decision point list contains either of the parent rows,
  1135.                 // update it to include the new row as well
  1136.                 if ((decisionPointList.contains(new Integer(oldRowNum)) ||
  1137.                                 decisionPointList.contains(new Integer(newRowNum))) &&
  1138.                                 !decisionPointList.contains(new Integer(combinedRowNum)))
  1139.                     decisionPointList.addElement(new Integer(combinedRowNum));
  1140.                     
  1141.                 // do the same thing with the list of rows being updated
  1142.                 if ((rowsBeingUpdated.contains(new Integer(oldRowNum)) ||
  1143.                                 rowsBeingUpdated.contains(new Integer(newRowNum))) &&
  1144.                                 !rowsBeingUpdated.contains(new Integer(combinedRowNum)))
  1145.                     decisionPointList.addElement(new Integer(combinedRowNum));
  1146.                 // now (groan) do the same thing for all the entries on the
  1147.                 // decision point stack
  1148.                 for (int32_t k = 0; k < decisionPointStack.size(); k++) {
  1149.                     Vector dpl = (Vector)decisionPointStack.elementAt(k);
  1150.                     if ((dpl.contains(new Integer(oldRowNum)) ||
  1151.                                     dpl.contains(new Integer(newRowNum))) && !dpl.contains(
  1152.                                     new Integer(combinedRowNum)))
  1153.                         dpl.addElement(new Integer(combinedRowNum));
  1154.                 }
  1155.  
  1156.                 // FINALLY (puff puff puff), call mergeStates() recursively to copy
  1157.                 // the row referred to by newValues into the new row and resolve any
  1158.                 // conflicts that come up at that level
  1159.                 mergeStates(combinedRowNum, (int16_t*)(tempStateTable.elementAt(
  1160.                                 newValues[i])), rowsBeingUpdated);
  1161.             }
  1162.         }
  1163.     }
  1164.     return;
  1165. }
  1166.  
  1167. /**
  1168.  * The merge list is a list of pairs of rows that have been merged somewhere in
  1169.  * the process of building this state table, along with the row number of the
  1170.  * row containing the merged state.  This function looks up a pair of row numbers
  1171.  * and returns the row number of the row they combine into.  (It returns 0 if
  1172.  * this pair of rows isn't in the merge list.)
  1173.  */
  1174. int32_t RuleBasedBreakIteratorBuilder::searchMergeList(int32_t a, int32_t b) {
  1175.     // if there is no merge list, there obviously isn't anything in it
  1176.     if (mergeList == 0)
  1177.         return 0;
  1178.         
  1179.     // otherwise, for each element in the merge list...
  1180.     else {
  1181.         int32_t* entry;
  1182.         for (int32_t i = 0; i < mergeList.size(); i++) {
  1183.             entry = (int32_t*)(mergeList.elementAt(i));
  1184.             
  1185.             // we have a hit if the two row numbers match the two row numbers
  1186.             // in the beginning of the entry (the two that combine), in either
  1187.             // order
  1188.             if ((entry[0] == a && entry[1] == b) || (entry[0] == b && entry[1] == a))
  1189.                 return entry[2];
  1190.                 
  1191.             // we also have a hit if one of the two row numbers matches the marged
  1192.             // row number and the other one matches one of the original row numbers
  1193.             if ((entry[2] == a && (entry[0] == b || entry[1] == b)))
  1194.                 return entry[2];
  1195.             if ((entry[2] == b && (entry[0] == a || entry[1] == a)))
  1196.                 return entry[2];
  1197.         }
  1198.         return 0;
  1199.     }
  1200. }
  1201.  
  1202. /**
  1203.  * This function is used to update the list of current loooping states (i.e.,
  1204.  * states that are controlled by a *? construct).  It backfills values from
  1205.  * the looping states into unpopulated cells of the states that are currently
  1206.  * marked for backfilling, and then updates the list of looping states to be
  1207.  * the new list
  1208.  * @param newLoopingStates The list of new looping states
  1209.  * @param endStates The list of states to treat as end states (states that
  1210.  * can exit the loop).
  1211.  */
  1212. void RuleBasedBreakIteratorBuilder::setLoopingStates(Vector newLoopingStates, Vector endStates) {
  1213.     
  1214.     // if the current list of looping states isn't empty, we have to backfill
  1215.     // values from the looping states into the states that are waiting to be
  1216.     // backfilled
  1217.     if (!loopingStates.isEmpty()) {
  1218.         int32_t loopingState = ((Integer)loopingStates.lastElement()).intValue();
  1219.         int32_t rowNum;
  1220.  
  1221.         // don't backfill into an end state OR any state reachable from an end state
  1222.         // (since the search for reachable states is recursive, it's split out into
  1223.         // a separate function, eliminateBackfillStates(), below)
  1224.         for (int32_t i = 0; i < endStates.size(); i++) {
  1225.             eliminateBackfillStates(((Integer)endStates.elementAt(i)).intValue());
  1226.         }
  1227.  
  1228.         // we DON'T actually backfill the states that need to be backfilled here.
  1229.         // Instead, we MARK them for backfilling.  The reason for this is that if
  1230.         // there are multiple rules in the state-table description, the looping
  1231.         // states may have some of their values changed by a succeeding rule, and
  1232.         // this wouldn't be reflected in the backfilled states.  We mark a state
  1233.         // for backfilling by putting the row number of the state to copy from
  1234.         // into the flag cell at the end of the row
  1235.         for (int32_t i = 0; i < statesToBackfill.size(); i++) {
  1236.             rowNum = ((Integer)statesToBackfill.elementAt(i)).intValue();
  1237.             int16_t* state = (int16_t*)tempStateTable.elementAt(rowNum);
  1238.             state[numCategories] = (int16_t)((state[numCategories] & 0xc000) |
  1239.                             loopingState);
  1240.         }
  1241.         statesToBackfill.removeAllElements();
  1242.         loopingStates.removeAllElements();
  1243.     }
  1244.  
  1245.     if (newLoopingStates != 0)
  1246.         loopingStates = (Vector)newLoopingStates.clone();
  1247. }
  1248.  
  1249. /**
  1250.  * This removes "ending states" and states reachable from them from the
  1251.  * list of states to backfill.
  1252.  * @param The row number of the state to remove from the backfill list
  1253.  */
  1254. void RuleBasedBreakIteratorBuilder::eliminateBackfillStates(int32_t baseState) {
  1255.     
  1256.     // don't do anything unless this state is actually in the backfill list...
  1257.     if (statesToBackfill.contains(new Integer(baseState))) {
  1258.         
  1259.         // if it is, take it out
  1260.         statesToBackfill.removeElement(new Integer(baseState));
  1261.         
  1262.         // then go through and recursively call this function for every
  1263.         // state that the base state points to
  1264.         int16_t* state = (int16_t*)tempStateTable.elementAt(baseState);
  1265.         for (int32_t i = 0; i < numCategories; i++) {
  1266.             if (state[i] != 0)
  1267.                 eliminateBackfillStates(state[i]);
  1268.         }
  1269.     }
  1270. }
  1271.  
  1272. /**
  1273.  * This function completes the backfilling process by actually doing the
  1274.  * backfilling on the states that are marked for it
  1275.  */
  1276. void RuleBasedBreakIteratorBuilder::backfillLoopingStates() {
  1277.     int16_t* state;
  1278.     int16_t* loopingState = 0;
  1279.     int32_t loopingStateRowNum = 0;
  1280.     int32_t fromState;
  1281.  
  1282.     // for each state in the state table...
  1283.     for (int32_t i = 0; i < tempStateTable.size(); i++) {
  1284.         state = (int16_t*)tempStateTable.elementAt(i);
  1285.         
  1286.         // check the state's flag word to see if it's marked for backfilling
  1287.         // (it's marked for backfilling if any bits other than the two high-order
  1288.         // bits are set-- if they are, then the flag word, minus the two high bits,
  1289.         // is the row number to copy from)
  1290.         fromState = state[numCategories] & 0x3fff;
  1291.         if (fromState > 0) {
  1292.             
  1293.             // load up the state to copy from (if we haven't already)
  1294.             if (fromState != loopingStateRowNum) {
  1295.                 loopingStateRowNum = fromState;
  1296.                 loopingState = (int16_t*)tempStateTable.elementAt(loopingStateRowNum);
  1297.             }
  1298.             
  1299.             // clear out the backfill part of the flag word
  1300.             state[numCategories] &= 0xc000;
  1301.             
  1302.             // then fill all zero cells in the current state with values
  1303.             // from the corresponding cells of the fromState
  1304.             for (int32_t j = 0; j < state.length; j++) {
  1305.                 if (state[j] == 0)
  1306.                     state[j] = loopingState[j];
  1307.                 else if (state[j] == 0x4000)
  1308.                     state[j] = 0;
  1309.             }
  1310.         }
  1311.     }
  1312. }
  1313.  
  1314. /**
  1315.  * This function completes the state-table-building process by doing several
  1316.  * postprocessing steps and copying everything into its final resting place
  1317.  * in the iterator itself
  1318.  * @param forward True if we're working on the forward state table
  1319.  */
  1320. void RuleBasedBreakIteratorBuilder::finishBuildingStateTable(bool_t forward) {
  1321.     // start by backfilling the looping states
  1322.     backfillLoopingStates();
  1323.  
  1324.     int32_t* rowNumMap = new int32_t[tempStateTable.size()];
  1325.     Stack rowsToFollow = new Stack();
  1326.     rowsToFollow.push(new Integer(1));
  1327.     rowNumMap[1] = 1;
  1328.  
  1329.     // determine which states are no longer reachable from the start state
  1330.     // (the reachable states will have their row numbers in the row number
  1331.     // map, and the nonreachable states will have zero in the row number map)
  1332.     while (rowsToFollow.size() != 0) {
  1333.         int32_t rowNum = ((Integer)rowsToFollow.pop()).intValue();
  1334.         int16_t* row = (int16_t*)(tempStateTable.elementAt(rowNum));
  1335.  
  1336.         for (int32_t i = 0; i < numCategories; i++) {
  1337.             if (row[i] != 0) {
  1338.                 if (rowNumMap[row[i]] == 0) {
  1339.                     rowNumMap[row[i]] = row[i];
  1340.                     rowsToFollow.push(new Integer(row[i]));
  1341.                 }
  1342.             }
  1343.         }
  1344.     }
  1345.  
  1346.     bool_t madeChange;
  1347.     int32_t newRowNum;
  1348.  
  1349.     // algorithm for minimizing the number of states in the table adapted from
  1350.     // Aho & Ullman, "Principles of Compiler Design"
  1351.     // The basic idea here is to organize the states into classes.  When we're done,
  1352.     // all states in the same class can be considered identical and all but one eliminated.
  1353.  
  1354.     // initially assign states to classes based on the number of populated cells they
  1355.     // contain (the class number is the number of populated cells)
  1356.     int32_t* stateClasses = new int32_t[tempStateTable.size()];
  1357.     int32_t nextClass = numCategories + 1;
  1358.     int16_t* state1, state2;
  1359.     for (int32_t i = 1; i < stateClasses.length; i++) {
  1360.         if (rowNumMap[i] == 0)
  1361.             continue;
  1362.         state1 = (int16_t*)tempStateTable.elementAt(i);
  1363.         for (int32_t j = 0; j < numCategories; j++)
  1364.             if (state1[j] != 0)
  1365.                 ++stateClasses[i];
  1366.         if (stateClasses[i] == 0)
  1367.             stateClasses[i] = nextClass;
  1368.     }
  1369.     ++nextClass;
  1370.  
  1371.     // then, for each class, elect the first member of that class as that class's
  1372.     // "representative".  For each member of the class, compare it to the "representative."
  1373.     // If there's a column position where the state being tested transitions to a
  1374.     // state in a DIFFERENT class from the class where the "representative" transitions,
  1375.     // then move the state into a new class.  Repeat this process until no new classes
  1376.     // are created.
  1377.     int32_t currentClass;
  1378.     int32_t lastClass;
  1379.     bool_t split;
  1380.  
  1381.     do {
  1382.         currentClass = 1;
  1383.         lastClass = nextClass;
  1384.         while (currentClass < nextClass) {
  1385.             split = FALSE;
  1386.             state1 = state2 = 0;
  1387.             for (int32_t i = 0; i < stateClasses.length; i++) {
  1388.                 if (stateClasses[i] == currentClass) {
  1389.                     if (state1 == 0) {
  1390.                         state1 = (int16_t*)tempStateTable.elementAt(i);
  1391.                     }
  1392.                     else {
  1393.                         state2 = (int16_t*)tempStateTable.elementAt(i);
  1394.                         for (int32_t j = 0; j < state2.length; j++)
  1395.                             if ((j == numCategories && state1[j] != state2[j] && forward)
  1396.                                     || (j != numCategories && stateClasses[state1[j]]
  1397.                                     != stateClasses[state2[j]])) {
  1398.                                 stateClasses[i] = nextClass;
  1399.                                 split = TRUE;
  1400.                                 break;
  1401.                             }
  1402.                     }
  1403.                 }
  1404.             }
  1405.             if (split)
  1406.                 ++nextClass;
  1407.             ++currentClass;
  1408.         }
  1409.     } while (lastClass != nextClass);
  1410.  
  1411.     // at this point, all of the states in a class except the first one (the
  1412.     //"representative") can be eliminated, so update the row-number map accordingly
  1413.     int32_t* representatives = new int32_t[nextClass];
  1414.     for (int32_t i = 1; i < stateClasses.length; i++)
  1415.         if (representatives[stateClasses[i]] == 0)
  1416.             representatives[stateClasses[i]] = i;
  1417.         else
  1418.             rowNumMap[i] = representatives[stateClasses[i]];
  1419.  
  1420.     // renumber all remaining rows...
  1421.     // first drop all that are either unreferenced or not a class representative
  1422.     for (int32_t i = 1; i < rowNumMap.length; i++)
  1423.         if (rowNumMap[i] != i)
  1424.             tempStateTable.setElementAt(0, i);
  1425.     
  1426.     // then calculate everybody's new row number and update the row
  1427.     // number map appropriately (the first pass updates the row numbers
  1428.     // of all the class representatives [the rows we're keeping], and the
  1429.     // second pass updates the cross references for all the rows that
  1430.     // are being deleted)
  1431.     newRowNum = 1;
  1432.     for (int32_t i = 1; i < rowNumMap.length; i++)
  1433.         if (tempStateTable.elementAt(i) != 0)
  1434.             rowNumMap[i] = newRowNum++;
  1435.     for (int32_t i = 1; i < rowNumMap.length; i++)
  1436.         if (tempStateTable.elementAt(i) == 0)
  1437.             rowNumMap[i] = rowNumMap[rowNumMap[i]];
  1438.  
  1439.     // allocate the permanent state table, and copy the remaining rows into it
  1440.     // (adjusting all the cell values, of course)
  1441.     
  1442.     // this section does that for the forward state table
  1443.     if (forward) {
  1444.         endStates = new bool_t[newRowNum];
  1445.         stateTable = new int16_t[newRowNum * numCategories];
  1446.         int32_t p = 0;
  1447.         int32_t p2 = 0;
  1448.         for (int32_t i = 0; i < tempStateTable.size(); i++) {
  1449.             int16_t* row = (int16_t*)(tempStateTable.elementAt(i));
  1450.             if (row == 0)
  1451.                 continue;
  1452.             for (int32_t j = 0; j < numCategories; j++) {
  1453.                 stateTable[p] = (int16_t)(rowNumMap[row[j]]);
  1454.                 ++p;
  1455.             }
  1456.             endStates[p2++] = ((row[numCategories] & 0x8000) != 0);
  1457.         }
  1458.     }
  1459.     
  1460.     // and this section does it for the backward state table
  1461.     else {
  1462.         backwardsStateTable = new int16_t[newRowNum * numCategories];
  1463.         int32_t p = 0;
  1464.         for (int32_t i = 0; i < tempStateTable.size(); i++) {
  1465.             int16_t* row = (int16_t*)(tempStateTable.elementAt(i));
  1466.             if (row == 0)
  1467.                 continue;
  1468.             for (int32_t j = 0; j < numCategories; j++) {
  1469.                 backwardsStateTable[p] = (int16_t)(rowNumMap[row[j]]);
  1470.                 ++p;
  1471.             }
  1472.         }
  1473.     }
  1474. }
  1475.  
  1476. /**
  1477.  * This function builds the backward state table from the forward state
  1478.  * table and any additional rules (identified by the ! on the front)
  1479.  * supplied in the description
  1480.  */
  1481. void RuleBasedBreakIteratorBuilder::buildBackwardsStateTable(Vector tempRuleList) {
  1482.     
  1483.     // create the temporary state table and seed it with two rows (row 0
  1484.     // isn't used for anything, and we have to create row 1 (the initial
  1485.     // state) before we can do anything else
  1486.     tempStateTable = new Vector();
  1487.     tempStateTable.addElement(new int16_t[numCategories + 1]);
  1488.     tempStateTable.addElement(new int16_t[numCategories + 1]);
  1489.  
  1490.     // although the backwards state table is built automatically from the forward
  1491.     // state table, there are some situations (the default sentence-break rules,
  1492.     // for example) where this doesn't yield enough stop states, causing a dramatic
  1493.     // drop in performance.  To help with these cases, the user may supply
  1494.     // supplemental rules that are added to the backward state table.  These have
  1495.     // the same syntax as the normal break rules, but begin with '!' to distinguish
  1496.     // them from normal break rules
  1497.     for (int32_t i = 0; i < tempRuleList.size(); i++) {
  1498.         UnicodeString rule = (UnicodeString)tempRuleList.elementAt(i);
  1499.         if (rule.UCharAt(0) == '!') {
  1500.             parseRule(rule.substring(1), FALSE);
  1501.         }
  1502.     }
  1503.     backfillLoopingStates();
  1504.  
  1505.     // Backwards iteration is qualitatively different from forwards iteration.
  1506.     // This is because backwards iteration has to be made to operate from no context
  1507.     // at all-- the user should be able to ask BreakIterator for the break position
  1508.     // immediately on either side of some arbitrary offset in the text.  The
  1509.     // forward iteration table doesn't let us do that-- it assumes complete
  1510.     // information on the context, which means starting from the beginning of the
  1511.     // document.
  1512.     // The way we do backward and random-access iteration is to back up from the
  1513.     // current (or user-specified) position until we see something we're sure is
  1514.     // a break position (it may not be the last break position immediately
  1515.     // preceding our starting point, however).  Then we roll forward from there to
  1516.     // locate the actual break position we're after.
  1517.     // This means that the backwards state table doesn't have to identify every
  1518.     // break position, allowing the building algorithm to be much simpler.  Here,
  1519.     // we use a "pairs" approach, scanning the forward-iteration state table for
  1520.     // pairs of character categories we ALWAYS break between, and building a state
  1521.     // table from that information.  No context is required-- all this state table
  1522.     // looks at is a pair of adjacent characters.
  1523.     
  1524.     // It's possible that the user has supplied supplementary rules (see above).
  1525.     // This has to be done first to keep parseRule() and friends from becoming
  1526.     // EVEN MORE complicated.  The automatically-generated states are appended
  1527.     // onto the end of the state table, and then the two sets of rules are
  1528.     // stitched together at the end.  Take note of the row number of the
  1529.     // first row of the auromatically-generated part.
  1530.     int32_t backTableOffset = tempStateTable.size();
  1531.     if (backTableOffset > 2)
  1532.         ++backTableOffset;
  1533.  
  1534.     // the automatically-generated part of the table models a two-dimensional
  1535.     // array where the two dimensions represent the two characters we're currently
  1536.     // looking at.  To model this as a state table, we actually need one additional
  1537.     // row to represent the initial state.  It gets populated with the row numbers
  1538.     // of the other rows (in order).
  1539.     for (int32_t i = 0; i < numCategories + 1; i++)
  1540.         tempStateTable.addElement(new int16_t[numCategories + 1]);
  1541.     int16_t* state = (int16_t*)tempStateTable.elementAt(backTableOffset - 1);
  1542.     for (int32_t i = 0; i < numCategories; i++)
  1543.         state[i] = (int16_t)(i + backTableOffset);
  1544.  
  1545.     // scavenge the forward state table for pairs of character categories
  1546.     // that always have a break between them.  The algorithm is as follows:
  1547.     // Look down each column in the state table.  For each nonzero cell in
  1548.     // that column, look up the row it points to.  For each nonzero cell in
  1549.     // that row, populate a cell in the backwards state table: the row number
  1550.     // of that cell is the number of the column we were scanning (plus the
  1551.     // offset that locates this sub-table), and the column number of that cell
  1552.     // is the column number of the nonzero cell we just found.  This cell is
  1553.     // populated with its own column number (adjusted according to the actual
  1554.     // location of the sub-table).  This process will produce a state table
  1555.     // whose behavior is the same as looking up successive pairs of characters
  1556.     // in an array of Booleans to determine whether there is a break.
  1557.     int32_t numRows = stateTable.length / numCategories;
  1558.     for (int32_t column = 0; column < numCategories; column++) {
  1559.         for (int32_t row = 0; row < numRows; row++) {
  1560.             int32_t nextRow = lookupState(row, column);
  1561.             if (nextRow != 0) {
  1562.                 for (int32_t nextColumn = 0; nextColumn < numCategories; nextColumn++) {
  1563.                     int32_t cellValue = lookupState(nextRow, nextColumn);
  1564.                     if (cellValue != 0) {
  1565.                         state = (int16_t*)tempStateTable.elementAt(nextColumn +
  1566.                                         backTableOffset);
  1567.                         state[column] = (int16_t)(column + backTableOffset);
  1568.                     }
  1569.                 }
  1570.             }
  1571.         }
  1572.     }
  1573.  
  1574.     // if the user specified some backward-iteration rules with the ! token,
  1575.     // we have to merge the resulting state table with the auto-generated one
  1576.     // above.  First copy the populated cells from row 1 over the populated
  1577.     // cells in the auto-generated table.  Then copy values from row 1 of the
  1578.     // auto-generated table into all of the the unpopulated cells of the 
  1579.     // rule-based table.
  1580.     if (backTableOffset > 1) {
  1581.         
  1582.         // for every row in the auto-generated sub-table, if a cell is
  1583.         // populated that is also populated in row 1 of the rule-based
  1584.         // sub-table, copy the value from row 1 over the value in the
  1585.         // auto-generated sub-table
  1586.         state = (int16_t*)tempStateTable.elementAt(1);
  1587.         for (int32_t i = backTableOffset - 1; i < tempStateTable.size(); i++) {
  1588.             int16_t* state2 = (int16_t*)tempStateTable.elementAt(i);
  1589.             for (int32_t j = 0; j < numCategories; j++) {
  1590.                 if (state[j] != 0 && state2[j] != 0)
  1591.                     state2[j] = state[j];
  1592.             }
  1593.         }
  1594.         
  1595.         // now, for every row in the rule-based sub-table that is not
  1596.         // an end state, fill in all unpopulated cells with the values
  1597.         // of the corresponding cells in the first row of the auto-
  1598.         // generated sub-table.
  1599.         state = (int16_t*)tempStateTable.elementAt(backTableOffset - 1);
  1600.         for (int32_t i = 1; i < backTableOffset - 1; i++) {
  1601.             int16_t* state2 = (int16_t*)tempStateTable.elementAt(i);
  1602.             if ((state2[numCategories] & 0x8000) == 0) {
  1603.                 for (int32_t j = 0; j < numCategories; j++) {
  1604.                     if (state2[j] == 0)
  1605.                         state2[j] = state[j];
  1606.                 }
  1607.             }
  1608.         }
  1609.     }
  1610.  
  1611.     // finally, clean everything up and copy it into the actual BreakIterator
  1612.     // by calling finishBuildingStateTable()
  1613.     finishBuildingStateTable(FALSE);
  1614. }
  1615.  
  1616. /**
  1617.  * Throws an IllegalArgumentException representing a syntax error in the rule
  1618.  * description.  The exception's message contains some debugging information.
  1619.  * @param message A message describing the problem
  1620.  * @param position The position in the description where the problem was
  1621.  * discovered
  1622.  * @param context The string containing the error
  1623.  */
  1624. void RuleBasedBreakIteratorBuilder::error(UnicodeString message, int32_t position, UnicodeString context) {
  1625.     throw new IllegalArgumentException("Parse error: " + message + " at " + position
  1626.                     + " in " + context);
  1627. }
  1628.