001: package antlr;
002:
003: /* ANTLR Translator Generator
004: * Project led by Terence Parr at http://www.cs.usfca.edu
005: * Software rights: http://www.antlr.org/license.html
006: */
007:
008: // class implements a String-like object whose sole purpose is to be
009: // entered into a lexer HashTable. It uses a lexer object to get
010: // information about case sensitivity.
011: public class ANTLRHashString {
012: // only one of s or buf is non-null
013: private String s;
014: private char[] buf;
015: private int len;
016: private CharScanner lexer;
017: private static final int prime = 151;
018:
019: public ANTLRHashString(char[] buf, int length, CharScanner lexer) {
020: this .lexer = lexer;
021: setBuffer(buf, length);
022: }
023:
024: // Hash strings constructed this way are unusable until setBuffer or setString are called.
025: public ANTLRHashString(CharScanner lexer) {
026: this .lexer = lexer;
027: }
028:
029: public ANTLRHashString(String s, CharScanner lexer) {
030: this .lexer = lexer;
031: setString(s);
032: }
033:
034: private final char charAt(int index) {
035: return (s != null) ? s.charAt(index) : buf[index];
036: }
037:
038: // Return true if o is an ANTLRHashString equal to this.
039: public boolean equals(Object o) {
040: if (!(o instanceof ANTLRHashString) && !(o instanceof String)) {
041: return false;
042: }
043:
044: ANTLRHashString s;
045: if (o instanceof String) {
046: s = new ANTLRHashString((String) o, lexer);
047: } else {
048: s = (ANTLRHashString) o;
049: }
050: int l = length();
051: if (s.length() != l) {
052: return false;
053: }
054: if (lexer.getCaseSensitiveLiterals()) {
055: for (int i = 0; i < l; i++) {
056: if (charAt(i) != s.charAt(i)) {
057: return false;
058: }
059: }
060: } else {
061: for (int i = 0; i < l; i++) {
062: if (lexer.toLower(charAt(i)) != lexer.toLower(s
063: .charAt(i))) {
064: return false;
065: }
066: }
067: }
068: return true;
069: }
070:
071: public int hashCode() {
072: int hashval = 0;
073: int l = length();
074:
075: if (lexer.getCaseSensitiveLiterals()) {
076: for (int i = 0; i < l; i++) {
077: hashval = hashval * prime + charAt(i);
078: }
079: } else {
080: for (int i = 0; i < l; i++) {
081: hashval = hashval * prime + lexer.toLower(charAt(i));
082: }
083: }
084: return hashval;
085: }
086:
087: private final int length() {
088: return (s != null) ? s.length() : len;
089: }
090:
091: public void setBuffer(char[] buf, int length) {
092: this .buf = buf;
093: this .len = length;
094: s = null;
095: }
096:
097: public void setString(String s) {
098: this.s = s;
099: buf = null;
100: }
101: }
|