Path: blob/master/src/java.base/share/classes/sun/text/DictionaryBasedBreakIterator.java
41152 views
/*1* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26*27* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved28* (C) Copyright IBM Corp. 1996 - 2002 - All Rights Reserved29*30* The original version of this source code and documentation31* is copyrighted and owned by Taligent, Inc., a wholly-owned32* subsidiary of IBM. These materials are provided under terms33* of a License Agreement between Taligent and Sun. This technology34* is protected by multiple US and International patents.35*36* This notice and attribution to Taligent may not be removed.37* Taligent is a registered trademark of Taligent, Inc.38*/3940package sun.text;4142import java.text.CharacterIterator;43import java.util.ArrayList;44import java.util.List;45import java.util.Stack;4647/**48* A subclass of RuleBasedBreakIterator that adds the ability to use a dictionary49* to further subdivide ranges of text beyond what is possible using just the50* state-table-based algorithm. This is necessary, for example, to handle51* word and line breaking in Thai, which doesn't use spaces between words. The52* state-table-based algorithm used by RuleBasedBreakIterator is used to divide53* up text as far as possible, and then contiguous ranges of letters are54* repeatedly compared against a list of known words (i.e., the dictionary)55* to divide them up into words.56*57* DictionaryBasedBreakIterator uses the same rule language as RuleBasedBreakIterator,58* but adds one more special substitution name: <dictionary>. This substitution59* name is used to identify characters in words in the dictionary. The idea is that60* if the iterator passes over a chunk of text that includes two or more characters61* in a row that are included in <dictionary>, it goes back through that range and62* derives additional break positions (if possible) using the dictionary.63*64* DictionaryBasedBreakIterator is also constructed with the filename of a dictionary65* file. It follows a prescribed search path to locate the dictionary (right now,66* it looks for it in /com/ibm/text/resources in each directory in the classpath,67* and won't find it in JAR files, but this location is likely to change). The68* dictionary file is in a serialized binary format. We have a very primitive (and69* slow) BuildDictionaryFile utility for creating dictionary files, but aren't70* currently making it public. Contact us for help.71*/72public class DictionaryBasedBreakIterator extends RuleBasedBreakIterator {7374/**75* a list of known words that is used to divide up contiguous ranges of letters,76* stored in a compressed, indexed, format that offers fast access77*/78private BreakDictionary dictionary;7980/**81* a list of flags indicating which character categories are contained in82* the dictionary file (this is used to determine which ranges of characters83* to apply the dictionary to)84*/85private boolean[] categoryFlags;8687/**88* a temporary hiding place for the number of dictionary characters in the89* last range passed over by next()90*/91private int dictionaryCharCount;9293/**94* when a range of characters is divided up using the dictionary, the break95* positions that are discovered are stored here, preventing us from having96* to use either the dictionary or the state table again until the iterator97* leaves this range of text98*/99private int[] cachedBreakPositions;100101/**102* if cachedBreakPositions is not null, this indicates which item in the103* cache the current iteration position refers to104*/105private int positionInCache;106107/**108* Constructs a DictionaryBasedBreakIterator.109*110* @param ruleFile the name of the rule data file111* @param ruleData the rule data loaded from the rule data file112* @param dictionaryFile the name of the dictionary file113* @param dictionaryData the dictionary data loaded from the dictionary file114* @throws MissingResourceException if rule data or dictionary initialization failed115*/116public DictionaryBasedBreakIterator(String ruleFile, byte[] ruleData,117String dictionaryFile, byte[] dictionaryData) {118super(ruleFile, ruleData);119byte[] tmp = super.getAdditionalData();120if (tmp != null) {121prepareCategoryFlags(tmp);122super.setAdditionalData(null);123}124dictionary = new BreakDictionary(dictionaryFile, dictionaryData);125}126127private void prepareCategoryFlags(byte[] data) {128categoryFlags = new boolean[data.length];129for (int i = 0; i < data.length; i++) {130categoryFlags[i] = (data[i] == (byte)1) ? true : false;131}132}133134@Override135public void setText(CharacterIterator newText) {136super.setText(newText);137cachedBreakPositions = null;138dictionaryCharCount = 0;139positionInCache = 0;140}141142/**143* Sets the current iteration position to the beginning of the text.144* (i.e., the CharacterIterator's starting offset).145* @return The offset of the beginning of the text.146*/147@Override148public int first() {149cachedBreakPositions = null;150dictionaryCharCount = 0;151positionInCache = 0;152return super.first();153}154155/**156* Sets the current iteration position to the end of the text.157* (i.e., the CharacterIterator's ending offset).158* @return The text's past-the-end offset.159*/160@Override161public int last() {162cachedBreakPositions = null;163dictionaryCharCount = 0;164positionInCache = 0;165return super.last();166}167168/**169* Advances the iterator one step backwards.170* @return The position of the last boundary position before the171* current iteration position172*/173@Override174public int previous() {175CharacterIterator text = getText();176177// if we have cached break positions and we're still in the range178// covered by them, just move one step backward in the cache179if (cachedBreakPositions != null && positionInCache > 0) {180--positionInCache;181text.setIndex(cachedBreakPositions[positionInCache]);182return cachedBreakPositions[positionInCache];183}184185// otherwise, dump the cache and use the inherited previous() method to move186// backward. This may fill up the cache with new break positions, in which187// case we have to mark our position in the cache188else {189cachedBreakPositions = null;190int result = super.previous();191if (cachedBreakPositions != null) {192positionInCache = cachedBreakPositions.length - 2;193}194return result;195}196}197198/**199* Sets the current iteration position to the last boundary position200* before the specified position.201* @param offset The position to begin searching from202* @return The position of the last boundary before "offset"203*/204@Override205public int preceding(int offset) {206CharacterIterator text = getText();207checkOffset(offset, text);208209// if we have no cached break positions, or "offset" is outside the210// range covered by the cache, we can just call the inherited routine211// (which will eventually call other routines in this class that may212// refresh the cache)213if (cachedBreakPositions == null || offset <= cachedBreakPositions[0] ||214offset > cachedBreakPositions[cachedBreakPositions.length - 1]) {215cachedBreakPositions = null;216return super.preceding(offset);217}218219// on the other hand, if "offset" is within the range covered by the cache,220// then all we have to do is search the cache for the last break position221// before "offset"222else {223positionInCache = 0;224while (positionInCache < cachedBreakPositions.length225&& offset > cachedBreakPositions[positionInCache]) {226++positionInCache;227}228--positionInCache;229text.setIndex(cachedBreakPositions[positionInCache]);230return text.getIndex();231}232}233234/**235* Sets the current iteration position to the first boundary position after236* the specified position.237* @param offset The position to begin searching forward from238* @return The position of the first boundary after "offset"239*/240@Override241public int following(int offset) {242CharacterIterator text = getText();243checkOffset(offset, text);244245// if we have no cached break positions, or if "offset" is outside the246// range covered by the cache, then dump the cache and call our247// inherited following() method. This will call other methods in this248// class that may refresh the cache.249if (cachedBreakPositions == null || offset < cachedBreakPositions[0] ||250offset >= cachedBreakPositions[cachedBreakPositions.length - 1]) {251cachedBreakPositions = null;252return super.following(offset);253}254255// on the other hand, if "offset" is within the range covered by the256// cache, then just search the cache for the first break position257// after "offset"258else {259positionInCache = 0;260while (positionInCache < cachedBreakPositions.length261&& offset >= cachedBreakPositions[positionInCache]) {262++positionInCache;263}264text.setIndex(cachedBreakPositions[positionInCache]);265return text.getIndex();266}267}268269/**270* This is the implementation function for next().271*/272@Override273protected int handleNext() {274CharacterIterator text = getText();275276// if there are no cached break positions, or if we've just moved277// off the end of the range covered by the cache, we have to dump278// and possibly regenerate the cache279if (cachedBreakPositions == null ||280positionInCache == cachedBreakPositions.length - 1) {281282// start by using the inherited handleNext() to find a tentative return283// value. dictionaryCharCount tells us how many dictionary characters284// we passed over on our way to the tentative return value285int startPos = text.getIndex();286dictionaryCharCount = 0;287int result = super.handleNext();288289// if we passed over more than one dictionary character, then we use290// divideUpDictionaryRange() to regenerate the cached break positions291// for the new range292if (dictionaryCharCount > 1 && result - startPos > 1) {293divideUpDictionaryRange(startPos, result);294}295296// otherwise, the value we got back from the inherited fuction297// is our return value, and we can dump the cache298else {299cachedBreakPositions = null;300return result;301}302}303304// if the cache of break positions has been regenerated (or existed all305// along), then just advance to the next break position in the cache306// and return it307if (cachedBreakPositions != null) {308++positionInCache;309text.setIndex(cachedBreakPositions[positionInCache]);310return cachedBreakPositions[positionInCache];311}312return -9999; // SHOULD NEVER GET HERE!313}314315/**316* Looks up a character category for a character.317*/318@Override319protected int lookupCategory(int c) {320// this override of lookupCategory() exists only to keep track of whether we've321// passed over any dictionary characters. It calls the inherited lookupCategory()322// to do the real work, and then checks whether its return value is one of the323// categories represented in the dictionary. If it is, bump the dictionary-324// character count.325int result = super.lookupCategory(c);326if (result != RuleBasedBreakIterator.IGNORE && categoryFlags[result]) {327++dictionaryCharCount;328}329return result;330}331332/**333* This is the function that actually implements the dictionary-based334* algorithm. Given the endpoints of a range of text, it uses the335* dictionary to determine the positions of any boundaries in this336* range. It stores all the boundary positions it discovers in337* cachedBreakPositions so that we only have to do this work once338* for each time we enter the range.339*/340@SuppressWarnings("unchecked")341private void divideUpDictionaryRange(int startPos, int endPos) {342CharacterIterator text = getText();343344// the range we're dividing may begin or end with non-dictionary characters345// (i.e., for line breaking, we may have leading or trailing punctuation346// that needs to be kept with the word). Seek from the beginning of the347// range to the first dictionary character348text.setIndex(startPos);349int c = getCurrent();350int category = lookupCategory(c);351while (category == IGNORE || !categoryFlags[category]) {352c = getNext();353category = lookupCategory(c);354}355356// initialize. We maintain two stacks: currentBreakPositions contains357// the list of break positions that will be returned if we successfully358// finish traversing the whole range now. possibleBreakPositions lists359// all other possible word ends we've passed along the way. (Whenever360// we reach an error [a sequence of characters that can't begin any word361// in the dictionary], we back up, possibly delete some breaks from362// currentBreakPositions, move a break from possibleBreakPositions363// to currentBreakPositions, and start over from there. This process364// continues in this way until we either successfully make it all the way365// across the range, or exhaust all of our combinations of break366// positions.)367Stack<Integer> currentBreakPositions = new Stack<>();368Stack<Integer> possibleBreakPositions = new Stack<>();369List<Integer> wrongBreakPositions = new ArrayList<>();370371// the dictionary is implemented as a trie, which is treated as a state372// machine. -1 represents the end of a legal word. Every word in the373// dictionary is represented by a path from the root node to -1. A path374// that ends in state 0 is an illegal combination of characters.375int state = 0;376377// these two variables are used for error handling. We keep track of the378// farthest we've gotten through the range being divided, and the combination379// of breaks that got us that far. If we use up all possible break380// combinations, the text contains an error or a word that's not in the381// dictionary. In this case, we "bless" the break positions that got us the382// farthest as real break positions, and then start over from scratch with383// the character where the error occurred.384int farthestEndPoint = text.getIndex();385Stack<Integer> bestBreakPositions = null;386387// initialize (we always exit the loop with a break statement)388c = getCurrent();389while (true) {390391// if we can transition to state "-1" from our current state, we're392// on the last character of a legal word. Push that position onto393// the possible-break-positions stack394if (dictionary.getNextState(state, 0) == -1) {395possibleBreakPositions.push(text.getIndex());396}397398// look up the new state to transition to in the dictionary399state = dictionary.getNextStateFromCharacter(state, c);400401// if the character we're sitting on causes us to transition to402// the "end of word" state, then it was a non-dictionary character403// and we've successfully traversed the whole range. Drop out404// of the loop.405if (state == -1) {406currentBreakPositions.push(text.getIndex());407break;408}409410// if the character we're sitting on causes us to transition to411// the error state, or if we've gone off the end of the range412// without transitioning to the "end of word" state, we've hit413// an error...414else if (state == 0 || text.getIndex() >= endPos) {415416// if this is the farthest we've gotten, take note of it in417// case there's an error in the text418if (text.getIndex() > farthestEndPoint) {419farthestEndPoint = text.getIndex();420421@SuppressWarnings("unchecked")422Stack<Integer> currentBreakPositionsCopy = (Stack<Integer>) currentBreakPositions.clone();423424bestBreakPositions = currentBreakPositionsCopy;425}426427// wrongBreakPositions is a list of all break positions428// we've tried starting that didn't allow us to traverse429// all the way through the text. Every time we pop a430// break position off of currentBreakPositions, we put it431// into wrongBreakPositions to avoid trying it again later.432// If we make it to this spot, we're either going to back433// up to a break in possibleBreakPositions and try starting434// over from there, or we've exhausted all possible break435// positions and are going to do the fallback procedure.436// This loop prevents us from messing with anything in437// possibleBreakPositions that didn't work as a starting438// point the last time we tried it (this is to prevent a bunch of439// repetitive checks from slowing down some extreme cases)440while (!possibleBreakPositions.isEmpty()441&& wrongBreakPositions.contains(possibleBreakPositions.peek())) {442possibleBreakPositions.pop();443}444445// if we've used up all possible break-position combinations, there's446// an error or an unknown word in the text. In this case, we start447// over, treating the farthest character we've reached as the beginning448// of the range, and "blessing" the break positions that got us that449// far as real break positions450if (possibleBreakPositions.isEmpty()) {451if (bestBreakPositions != null) {452currentBreakPositions = bestBreakPositions;453if (farthestEndPoint < endPos) {454text.setIndex(farthestEndPoint + 1);455}456else {457break;458}459}460else {461if ((currentBreakPositions.size() == 0 ||462currentBreakPositions.peek().intValue() != text.getIndex())463&& text.getIndex() != startPos) {464currentBreakPositions.push(text.getIndex());465}466getNext();467currentBreakPositions.push(text.getIndex());468}469}470471// if we still have more break positions we can try, then promote the472// last break in possibleBreakPositions into currentBreakPositions,473// and get rid of all entries in currentBreakPositions that come after474// it. Then back up to that position and start over from there (i.e.,475// treat that position as the beginning of a new word)476else {477Integer temp = possibleBreakPositions.pop();478Integer temp2 = null;479while (!currentBreakPositions.isEmpty() && temp.intValue() <480currentBreakPositions.peek().intValue()) {481temp2 = currentBreakPositions.pop();482wrongBreakPositions.add(temp2);483}484currentBreakPositions.push(temp);485text.setIndex(currentBreakPositions.peek().intValue());486}487488// re-sync "c" for the next go-round, and drop out of the loop if489// we've made it off the end of the range490c = getCurrent();491if (text.getIndex() >= endPos) {492break;493}494}495496// if we didn't hit any exceptional conditions on this last iteration,497// just advance to the next character and loop498else {499c = getNext();500}501}502503// dump the last break position in the list, and replace it with the actual504// end of the range (which may be the same character, or may be further on505// because the range actually ended with non-dictionary characters we want to506// keep with the word)507if (!currentBreakPositions.isEmpty()) {508currentBreakPositions.pop();509}510currentBreakPositions.push(endPos);511512// create a regular array to hold the break positions and copy513// the break positions from the stack to the array (in addition,514// our starting position goes into this array as a break position).515// This array becomes the cache of break positions used by next()516// and previous(), so this is where we actually refresh the cache.517cachedBreakPositions = new int[currentBreakPositions.size() + 1];518cachedBreakPositions[0] = startPos;519520for (int i = 0; i < currentBreakPositions.size(); i++) {521cachedBreakPositions[i + 1] = currentBreakPositions.elementAt(i).intValue();522}523positionInCache = 0;524}525}526527528