1 /*
   2  * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  *******************************************************************************
  28  * (C) Copyright IBM Corp. 1996-2005 - All Rights Reserved                     *
  29  *                                                                             *
  30  * The original version of this source code and documentation is copyrighted   *
  31  * and owned by IBM, These materials are provided under terms of a License     *
  32  * Agreement between IBM and Sun. This technology is protected by multiple     *
  33  * US and International patents. This notice and attribution to IBM may not    *
  34  * to removed.                                                                 *
  35  *******************************************************************************
  36  */
  37 
  38 /*
  39  **********************************************************************
  40  * Author: Alan Liu
  41  * Created: September 23 2003
  42  * Since: ICU 2.8
  43  **********************************************************************
  44  */
  45 
  46 package sun.text.normalizer;
  47 
  48 import java.text.ParsePosition;
  49 
  50 /**
  51  * An iterator that returns 32-bit code points.  This class is deliberately
  52  * <em>not</em> related to any of the JDK or ICU4J character iterator classes
  53  * in order to minimize complexity.
  54  * @author Alan Liu
  55  * @since ICU 2.8
  56  */
  57 @SuppressWarnings("deprecation")
  58 public class RuleCharacterIterator {
  59 
  60     // TODO: Ideas for later.  (Do not implement if not needed, lest the
  61     // code coverage numbers go down due to unused methods.)
  62     // 1. Add a copy constructor, equals() method, clone() method.
  63     // 2. Rather than return DONE, throw an exception if the end
  64     // is reached -- this is an alternate usage model, probably not useful.
  65     // 3. Return isEscaped from next().  If this happens,
  66     // don't keep an isEscaped member variable.
  67 
  68     /**
  69      * Text being iterated.
  70      */
  71     private String text;
  72 
  73     /**
  74      * Position of iterator.
  75      */
  76     private ParsePosition pos;
  77 
  78     /**
  79      * Symbol table used to parse and dereference variables.  May be null.
  80      */
  81     private SymbolTable sym;
  82 
  83     /**
  84      * Current variable expansion, or null if none.
  85      */
  86     private char[] buf;
  87 
  88     /**
  89      * Position within buf[].  Meaningless if buf == null.
  90      */
  91     private int bufPos;
  92 
  93     /**
  94      * Flag indicating whether the last character was parsed from an escape.
  95      */
  96     private boolean isEscaped;
  97 
  98     /**
  99      * Value returned when there are no more characters to iterate.
 100      */
 101     public static final int DONE = -1;
 102 
 103     /**
 104      * Bitmask option to enable parsing of variable names.
 105      * If {@code (options & PARSE_VARIABLES) != 0},
 106      * then an embedded variable will be expanded to
 107      * its value.  Variables are parsed using the SymbolTable API.
 108      */
 109     public static final int PARSE_VARIABLES = 1;
 110 
 111     /**
 112      * Bitmask option to enable parsing of escape sequences.
 113      * If {@code (options & PARSE_ESCAPES) != 0},
 114      * then an embedded escape sequence will be expanded
 115      * to its value.  Escapes are parsed using Utility.unescapeAt().
 116      */
 117     public static final int PARSE_ESCAPES   = 2;
 118 
 119     /**
 120      * Bitmask option to enable skipping of whitespace.
 121      * If {@code (options & SKIP_WHITESPACE) != 0},
 122      * then whitespace characters will be silently
 123      * skipped, as if they were not present in the input.  Whitespace
 124      * characters are defined by UCharacterProperty.isRuleWhiteSpace().
 125      */
 126     public static final int SKIP_WHITESPACE = 4;
 127 
 128     /**
 129      * Constructs an iterator over the given text, starting at the given
 130      * position.
 131      * @param text the text to be iterated
 132      * @param sym the symbol table, or null if there is none.  If sym is null,
 133      * then variables will not be deferenced, even if the PARSE_VARIABLES
 134      * option is set.
 135      * @param pos upon input, the index of the next character to return.  If a
 136      * variable has been dereferenced, then pos will <em>not</em> increment as
 137      * characters of the variable value are iterated.
 138      */
 139     public RuleCharacterIterator(String text, SymbolTable sym,
 140                                  ParsePosition pos) {
 141         if (text == null || pos.getIndex() > text.length()) {
 142             throw new IllegalArgumentException();
 143         }
 144         this.text = text;
 145         this.sym = sym;
 146         this.pos = pos;
 147         buf = null;
 148     }
 149 
 150     /**
 151      * Returns true if this iterator has no more characters to return.
 152      */
 153     public boolean atEnd() {
 154         return buf == null && pos.getIndex() == text.length();
 155     }
 156 
 157     /**
 158      * Returns the next character using the given options, or DONE if there
 159      * are no more characters, and advance the position to the next
 160      * character.
 161      * @param options one or more of the following options, bitwise-OR-ed
 162      * together: PARSE_VARIABLES, PARSE_ESCAPES, SKIP_WHITESPACE.
 163      * @return the current 32-bit code point, or DONE
 164      */
 165     public int next(int options) {
 166         int c = DONE;
 167         isEscaped = false;
 168 
 169         for (;;) {
 170             c = _current();
 171             _advance(UTF16.getCharCount(c));
 172 
 173             if (c == SymbolTable.SYMBOL_REF && buf == null &&
 174                 (options & PARSE_VARIABLES) != 0 && sym != null) {
 175                 String name = sym.parseReference(text, pos, text.length());
 176                 // If name == null there was an isolated SYMBOL_REF;
 177                 // return it.  Caller must be prepared for this.
 178                 if (name == null) {
 179                     break;
 180                 }
 181                 bufPos = 0;
 182                 buf = sym.lookup(name);
 183                 if (buf == null) {
 184                     throw new IllegalArgumentException(
 185                                 "Undefined variable: " + name);
 186                 }
 187                 // Handle empty variable value
 188                 if (buf.length == 0) {
 189                     buf = null;
 190                 }
 191                 continue;
 192             }
 193 
 194             if ((options & SKIP_WHITESPACE) != 0 &&
 195                 UCharacterProperty.isRuleWhiteSpace(c)) {
 196                 continue;
 197             }
 198 
 199             if (c == '\\' && (options & PARSE_ESCAPES) != 0) {
 200                 int offset[] = new int[] { 0 };
 201                 c = Utility.unescapeAt(lookahead(), offset);
 202                 jumpahead(offset[0]);
 203                 isEscaped = true;
 204                 if (c < 0) {
 205                     throw new IllegalArgumentException("Invalid escape");
 206                 }
 207             }
 208 
 209             break;
 210         }
 211 
 212         return c;
 213     }
 214 
 215     /**
 216      * Returns true if the last character returned by next() was
 217      * escaped.  This will only be the case if the option passed in to
 218      * next() included PARSE_ESCAPED and the next character was an
 219      * escape sequence.
 220      */
 221     public boolean isEscaped() {
 222         return isEscaped;
 223     }
 224 
 225     /**
 226      * Returns true if this iterator is currently within a variable expansion.
 227      */
 228     public boolean inVariable() {
 229         return buf != null;
 230     }
 231 
 232     /**
 233      * Returns an object which, when later passed to setPos(), will
 234      * restore this iterator's position.  Usage idiom:
 235      *
 236      * RuleCharacterIterator iterator = ...;
 237      * Object pos = iterator.getPos(null); // allocate position object
 238      * for (;;) {
 239      *   pos = iterator.getPos(pos); // reuse position object
 240      *   int c = iterator.next(...);
 241      *   ...
 242      * }
 243      * iterator.setPos(pos);
 244      *
 245      * @param p a position object previously returned by getPos(),
 246      * or null.  If not null, it will be updated and returned.  If
 247      * null, a new position object will be allocated and returned.
 248      * @return a position object which may be passed to setPos(),
 249      * either `p,' or if `p' == null, a newly-allocated object
 250      */
 251     public Object getPos(Object p) {
 252         if (p == null) {
 253             return new Object[] {buf, new int[] {pos.getIndex(), bufPos}};
 254         }
 255         Object[] a = (Object[]) p;
 256         a[0] = buf;
 257         int[] v = (int[]) a[1];
 258         v[0] = pos.getIndex();
 259         v[1] = bufPos;
 260         return p;
 261     }
 262 
 263     /**
 264      * Restores this iterator to the position it had when getPos()
 265      * returned the given object.
 266      * @param p a position object previously returned by getPos()
 267      */
 268     public void setPos(Object p) {
 269         Object[] a = (Object[]) p;
 270         buf = (char[]) a[0];
 271         int[] v = (int[]) a[1];
 272         pos.setIndex(v[0]);
 273         bufPos = v[1];
 274     }
 275 
 276     /**
 277      * Skips ahead past any ignored characters, as indicated by the given
 278      * options.  This is useful in conjunction with the lookahead() method.
 279      *
 280      * Currently, this only has an effect for SKIP_WHITESPACE.
 281      * @param options one or more of the following options, bitwise-OR-ed
 282      * together: PARSE_VARIABLES, PARSE_ESCAPES, SKIP_WHITESPACE.
 283      */
 284     public void skipIgnored(int options) {
 285         if ((options & SKIP_WHITESPACE) != 0) {
 286             for (;;) {
 287                 int a = _current();
 288                 if (!UCharacterProperty.isRuleWhiteSpace(a)) break;
 289                 _advance(UTF16.getCharCount(a));
 290             }
 291         }
 292     }
 293 
 294     /**
 295      * Returns a string containing the remainder of the characters to be
 296      * returned by this iterator, without any option processing.  If the
 297      * iterator is currently within a variable expansion, this will only
 298      * extend to the end of the variable expansion.  This method is provided
 299      * so that iterators may interoperate with string-based APIs.  The typical
 300      * sequence of calls is to call skipIgnored(), then call lookahead(), then
 301      * parse the string returned by lookahead(), then call jumpahead() to
 302      * resynchronize the iterator.
 303      * @return a string containing the characters to be returned by future
 304      * calls to next()
 305      */
 306     public String lookahead() {
 307         if (buf != null) {
 308             return new String(buf, bufPos, buf.length - bufPos);
 309         } else {
 310             return text.substring(pos.getIndex());
 311         }
 312     }
 313 
 314     /**
 315      * Advances the position by the given number of 16-bit code units.
 316      * This is useful in conjunction with the lookahead() method.
 317      * @param count the number of 16-bit code units to jump over
 318      */
 319     public void jumpahead(int count) {
 320         if (count < 0) {
 321             throw new IllegalArgumentException();
 322         }
 323         if (buf != null) {
 324             bufPos += count;
 325             if (bufPos > buf.length) {
 326                 throw new IllegalArgumentException();
 327             }
 328             if (bufPos == buf.length) {
 329                 buf = null;
 330             }
 331         } else {
 332             int i = pos.getIndex() + count;
 333             pos.setIndex(i);
 334             if (i > text.length()) {
 335                 throw new IllegalArgumentException();
 336             }
 337         }
 338     }
 339 
 340     /**
 341      * Returns the current 32-bit code point without parsing escapes, parsing
 342      * variables, or skipping whitespace.
 343      * @return the current 32-bit code point
 344      */
 345     private int _current() {
 346         if (buf != null) {
 347             return UTF16.charAt(buf, 0, buf.length, bufPos);
 348         } else {
 349             int i = pos.getIndex();
 350             return (i < text.length()) ? UTF16.charAt(text, i) : DONE;
 351         }
 352     }
 353 
 354     /**
 355      * Advances the position by the given amount.
 356      * @param count the number of 16-bit code units to advance past
 357      */
 358     private void _advance(int count) {
 359         if (buf != null) {
 360             bufPos += count;
 361             if (bufPos == buf.length) {
 362                 buf = null;
 363             }
 364         } else {
 365             pos.setIndex(pos.getIndex() + count);
 366             if (pos.getIndex() > text.length()) {
 367                 pos.setIndex(text.length());
 368             }
 369         }
 370     }
 371 }