1 /*
2 **********************************************************************
3 * Copyright (c) 2001-2007, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
6 * Date Name Description
7 * 11/19/2001 aliu Creation.
8 **********************************************************************
9 */
10
11 #include "util.h"
12 #include "unicode/unimatch.h"
13 #include "unicode/uniset.h"
14
15 // Define UChar constants using hex for EBCDIC compatibility
16
17 static const UChar BACKSLASH = 0x005C; /*\*/
18 static const UChar UPPER_U = 0x0055; /*U*/
19 static const UChar LOWER_U = 0x0075; /*u*/
20 static const UChar APOSTROPHE = 0x0027; // '\''
21 static const UChar SPACE = 0x0020; // ' '
22
23 // "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24 static const UChar DIGITS[] = {
25 48,49,50,51,52,53,54,55,56,57,
26 65,66,67,68,69,70,71,72,73,74,
27 75,76,77,78,79,80,81,82,83,84,
28 85,86,87,88,89,90
29 };
30
31 U_NAMESPACE_BEGIN
32
appendNumber(UnicodeString & result,int32_t n,int32_t radix,int32_t minDigits)33 UnicodeString& ICU_Utility::appendNumber(UnicodeString& result, int32_t n,
34 int32_t radix, int32_t minDigits) {
35 if (radix < 2 || radix > 36) {
36 // Bogus radix
37 return result.append((UChar)63/*?*/);
38 }
39 // Handle negatives
40 if (n < 0) {
41 n = -n;
42 result.append((UChar)45/*-*/);
43 }
44 // First determine the number of digits
45 int32_t nn = n;
46 int32_t r = 1;
47 while (nn >= radix) {
48 nn /= radix;
49 r *= radix;
50 --minDigits;
51 }
52 // Now generate the digits
53 while (--minDigits > 0) {
54 result.append(DIGITS[0]);
55 }
56 while (r > 0) {
57 int32_t digit = n / r;
58 result.append(DIGITS[digit]);
59 n -= digit * r;
60 r /= radix;
61 }
62 return result;
63 }
64
65 static const UChar HEX[16] = {48,49,50,51,52,53,54,55, // 0-7
66 56,57,65,66,67,68,69,70}; // 8-9 A-F
67
68 /**
69 * Return true if the character is NOT printable ASCII.
70 */
isUnprintable(UChar32 c)71 UBool ICU_Utility::isUnprintable(UChar32 c) {
72 return !(c >= 0x20 && c <= 0x7E);
73 }
74
75 /**
76 * Escape unprintable characters using \uxxxx notation for U+0000 to
77 * U+FFFF and \Uxxxxxxxx for U+10000 and above. If the character is
78 * printable ASCII, then do nothing and return FALSE. Otherwise,
79 * append the escaped notation and return TRUE.
80 */
escapeUnprintable(UnicodeString & result,UChar32 c)81 UBool ICU_Utility::escapeUnprintable(UnicodeString& result, UChar32 c) {
82 if (isUnprintable(c)) {
83 result.append(BACKSLASH);
84 if (c & ~0xFFFF) {
85 result.append(UPPER_U);
86 result.append(HEX[0xF&(c>>28)]);
87 result.append(HEX[0xF&(c>>24)]);
88 result.append(HEX[0xF&(c>>20)]);
89 result.append(HEX[0xF&(c>>16)]);
90 } else {
91 result.append(LOWER_U);
92 }
93 result.append(HEX[0xF&(c>>12)]);
94 result.append(HEX[0xF&(c>>8)]);
95 result.append(HEX[0xF&(c>>4)]);
96 result.append(HEX[0xF&c]);
97 return TRUE;
98 }
99 return FALSE;
100 }
101
102 /**
103 * Returns the index of a character, ignoring quoted text.
104 * For example, in the string "abc'hide'h", the 'h' in "hide" will not be
105 * found by a search for 'h'.
106 */
107 // FOR FUTURE USE. DISABLE FOR NOW for coverage reasons.
108 /*
109 int32_t ICU_Utility::quotedIndexOf(const UnicodeString& text,
110 int32_t start, int32_t limit,
111 UChar charToFind) {
112 for (int32_t i=start; i<limit; ++i) {
113 UChar c = text.charAt(i);
114 if (c == BACKSLASH) {
115 ++i;
116 } else if (c == APOSTROPHE) {
117 while (++i < limit
118 && text.charAt(i) != APOSTROPHE) {}
119 } else if (c == charToFind) {
120 return i;
121 }
122 }
123 return -1;
124 }
125 */
126
127 /**
128 * Skip over a sequence of zero or more white space characters at pos.
129 * @param advance if true, advance pos to the first non-white-space
130 * character at or after pos, or str.length(), if there is none.
131 * Otherwise leave pos unchanged.
132 * @return the index of the first non-white-space character at or
133 * after pos, or str.length(), if there is none.
134 */
skipWhitespace(const UnicodeString & str,int32_t & pos,UBool advance)135 int32_t ICU_Utility::skipWhitespace(const UnicodeString& str, int32_t& pos,
136 UBool advance) {
137 int32_t p = pos;
138 while (p < str.length()) {
139 UChar32 c = str.char32At(p);
140 if (!uprv_isRuleWhiteSpace(c)) {
141 break;
142 }
143 p += UTF_CHAR_LENGTH(c);
144 }
145 if (advance) {
146 pos = p;
147 }
148 return p;
149 }
150
151 /**
152 * Skip over whitespace in a Replaceable. Whitespace is defined by
153 * uprv_isRuleWhiteSpace(). Skipping may be done in the forward or
154 * reverse direction. In either case, the leftmost index will be
155 * inclusive, and the rightmost index will be exclusive. That is,
156 * given a range defined as [start, limit), the call
157 * skipWhitespace(text, start, limit) will advance start past leading
158 * whitespace, whereas the call skipWhitespace(text, limit, start),
159 * will back up limit past trailing whitespace.
160 * @param text the text to be analyzed
161 * @param pos either the start or limit of a range of 'text', to skip
162 * leading or trailing whitespace, respectively
163 * @param stop either the limit or start of a range of 'text', to skip
164 * leading or trailing whitespace, respectively
165 * @return the new start or limit, depending on what was passed in to
166 * 'pos'
167 */
168 //?FOR FUTURE USE. DISABLE FOR NOW for coverage reasons.
169 //?int32_t ICU_Utility::skipWhitespace(const Replaceable& text,
170 //? int32_t pos, int32_t stop) {
171 //? UChar32 c;
172 //? UBool isForward = (stop >= pos);
173 //?
174 //? if (!isForward) {
175 //? --pos; // pos is a limit, so back up by one
176 //? }
177 //?
178 //? while (pos != stop &&
179 //? uprv_isRuleWhiteSpace(c = text.char32At(pos))) {
180 //? if (isForward) {
181 //? pos += UTF_CHAR_LENGTH(c);
182 //? } else {
183 //? pos -= UTF_CHAR_LENGTH(c);
184 //? }
185 //? }
186 //?
187 //? if (!isForward) {
188 //? ++pos; // make pos back into a limit
189 //? }
190 //?
191 //? return pos;
192 //?}
193
194 /**
195 * Parse a single non-whitespace character 'ch', optionally
196 * preceded by whitespace.
197 * @param id the string to be parsed
198 * @param pos INPUT-OUTPUT parameter. On input, pos[0] is the
199 * offset of the first character to be parsed. On output, pos[0]
200 * is the index after the last parsed character. If the parse
201 * fails, pos[0] will be unchanged.
202 * @param ch the non-whitespace character to be parsed.
203 * @return true if 'ch' is seen preceded by zero or more
204 * whitespace characters.
205 */
parseChar(const UnicodeString & id,int32_t & pos,UChar ch)206 UBool ICU_Utility::parseChar(const UnicodeString& id, int32_t& pos, UChar ch) {
207 int32_t start = pos;
208 skipWhitespace(id, pos, TRUE);
209 if (pos == id.length() ||
210 id.charAt(pos) != ch) {
211 pos = start;
212 return FALSE;
213 }
214 ++pos;
215 return TRUE;
216 }
217
218 /**
219 * Parse a pattern string within the given Replaceable and a parsing
220 * pattern. Characters are matched literally and case-sensitively
221 * except for the following special characters:
222 *
223 * ~ zero or more uprv_isRuleWhiteSpace chars
224 *
225 * If end of pattern is reached with all matches along the way,
226 * pos is advanced to the first unparsed index and returned.
227 * Otherwise -1 is returned.
228 * @param pat pattern that controls parsing
229 * @param text text to be parsed, starting at index
230 * @param index offset to first character to parse
231 * @param limit offset after last character to parse
232 * @return index after last parsed character, or -1 on parse failure.
233 */
parsePattern(const UnicodeString & pat,const Replaceable & text,int32_t index,int32_t limit)234 int32_t ICU_Utility::parsePattern(const UnicodeString& pat,
235 const Replaceable& text,
236 int32_t index,
237 int32_t limit) {
238 int32_t ipat = 0;
239
240 // empty pattern matches immediately
241 if (ipat == pat.length()) {
242 return index;
243 }
244
245 UChar32 cpat = pat.char32At(ipat);
246
247 while (index < limit) {
248 UChar32 c = text.char32At(index);
249
250 // parse \s*
251 if (cpat == 126 /*~*/) {
252 if (uprv_isRuleWhiteSpace(c)) {
253 index += UTF_CHAR_LENGTH(c);
254 continue;
255 } else {
256 if (++ipat == pat.length()) {
257 return index; // success; c unparsed
258 }
259 // fall thru; process c again with next cpat
260 }
261 }
262
263 // parse literal
264 else if (c == cpat) {
265 index += UTF_CHAR_LENGTH(c);
266 ipat += UTF_CHAR_LENGTH(cpat);
267 if (ipat == pat.length()) {
268 return index; // success; c parsed
269 }
270 // fall thru; get next cpat
271 }
272
273 // match failure of literal
274 else {
275 return -1;
276 }
277
278 cpat = pat.char32At(ipat);
279 }
280
281 return -1; // text ended before end of pat
282 }
283
284 /**
285 * Append a character to a rule that is being built up. To flush
286 * the quoteBuf to rule, make one final call with isLiteral == TRUE.
287 * If there is no final character, pass in (UChar32)-1 as c.
288 * @param rule the string to append the character to
289 * @param c the character to append, or (UChar32)-1 if none.
290 * @param isLiteral if true, then the given character should not be
291 * quoted or escaped. Usually this means it is a syntactic element
292 * such as > or $
293 * @param escapeUnprintable if true, then unprintable characters
294 * should be escaped using \uxxxx or \Uxxxxxxxx. These escapes will
295 * appear outside of quotes.
296 * @param quoteBuf a buffer which is used to build up quoted
297 * substrings. The caller should initially supply an empty buffer,
298 * and thereafter should not modify the buffer. The buffer should be
299 * cleared out by, at the end, calling this method with a literal
300 * character.
301 */
appendToRule(UnicodeString & rule,UChar32 c,UBool isLiteral,UBool escapeUnprintable,UnicodeString & quoteBuf)302 void ICU_Utility::appendToRule(UnicodeString& rule,
303 UChar32 c,
304 UBool isLiteral,
305 UBool escapeUnprintable,
306 UnicodeString& quoteBuf) {
307 // If we are escaping unprintables, then escape them outside
308 // quotes. \u and \U are not recognized within quotes. The same
309 // logic applies to literals, but literals are never escaped.
310 if (isLiteral ||
311 (escapeUnprintable && ICU_Utility::isUnprintable(c))) {
312 if (quoteBuf.length() > 0) {
313 // We prefer backslash APOSTROPHE to double APOSTROPHE
314 // (more readable, less similar to ") so if there are
315 // double APOSTROPHEs at the ends, we pull them outside
316 // of the quote.
317
318 // If the first thing in the quoteBuf is APOSTROPHE
319 // (doubled) then pull it out.
320 while (quoteBuf.length() >= 2 &&
321 quoteBuf.charAt(0) == APOSTROPHE &&
322 quoteBuf.charAt(1) == APOSTROPHE) {
323 rule.append(BACKSLASH).append(APOSTROPHE);
324 quoteBuf.remove(0, 2);
325 }
326 // If the last thing in the quoteBuf is APOSTROPHE
327 // (doubled) then remove and count it and add it after.
328 int32_t trailingCount = 0;
329 while (quoteBuf.length() >= 2 &&
330 quoteBuf.charAt(quoteBuf.length()-2) == APOSTROPHE &&
331 quoteBuf.charAt(quoteBuf.length()-1) == APOSTROPHE) {
332 quoteBuf.truncate(quoteBuf.length()-2);
333 ++trailingCount;
334 }
335 if (quoteBuf.length() > 0) {
336 rule.append(APOSTROPHE);
337 rule.append(quoteBuf);
338 rule.append(APOSTROPHE);
339 quoteBuf.truncate(0);
340 }
341 while (trailingCount-- > 0) {
342 rule.append(BACKSLASH).append(APOSTROPHE);
343 }
344 }
345 if (c != (UChar32)-1) {
346 /* Since spaces are ignored during parsing, they are
347 * emitted only for readability. We emit one here
348 * only if there isn't already one at the end of the
349 * rule.
350 */
351 if (c == SPACE) {
352 int32_t len = rule.length();
353 if (len > 0 && rule.charAt(len-1) != c) {
354 rule.append(c);
355 }
356 } else if (!escapeUnprintable || !ICU_Utility::escapeUnprintable(rule, c)) {
357 rule.append(c);
358 }
359 }
360 }
361
362 // Escape ' and '\' and don't begin a quote just for them
363 else if (quoteBuf.length() == 0 &&
364 (c == APOSTROPHE || c == BACKSLASH)) {
365 rule.append(BACKSLASH);
366 rule.append(c);
367 }
368
369 // Specials (printable ascii that isn't [0-9a-zA-Z]) and
370 // whitespace need quoting. Also append stuff to quotes if we are
371 // building up a quoted substring already.
372 else if (quoteBuf.length() > 0 ||
373 (c >= 0x0021 && c <= 0x007E &&
374 !((c >= 0x0030/*'0'*/ && c <= 0x0039/*'9'*/) ||
375 (c >= 0x0041/*'A'*/ && c <= 0x005A/*'Z'*/) ||
376 (c >= 0x0061/*'a'*/ && c <= 0x007A/*'z'*/))) ||
377 uprv_isRuleWhiteSpace(c)) {
378 quoteBuf.append(c);
379 // Double ' within a quote
380 if (c == APOSTROPHE) {
381 quoteBuf.append(c);
382 }
383 }
384
385 // Otherwise just append
386 else {
387 rule.append(c);
388 }
389 }
390
appendToRule(UnicodeString & rule,const UnicodeString & text,UBool isLiteral,UBool escapeUnprintable,UnicodeString & quoteBuf)391 void ICU_Utility::appendToRule(UnicodeString& rule,
392 const UnicodeString& text,
393 UBool isLiteral,
394 UBool escapeUnprintable,
395 UnicodeString& quoteBuf) {
396 for (int32_t i=0; i<text.length(); ++i) {
397 appendToRule(rule, text[i], isLiteral, escapeUnprintable, quoteBuf);
398 }
399 }
400
401 /**
402 * Given a matcher reference, which may be null, append its
403 * pattern as a literal to the given rule.
404 */
appendToRule(UnicodeString & rule,const UnicodeMatcher * matcher,UBool escapeUnprintable,UnicodeString & quoteBuf)405 void ICU_Utility::appendToRule(UnicodeString& rule,
406 const UnicodeMatcher* matcher,
407 UBool escapeUnprintable,
408 UnicodeString& quoteBuf) {
409 if (matcher != NULL) {
410 UnicodeString pat;
411 appendToRule(rule, matcher->toPattern(pat, escapeUnprintable),
412 TRUE, escapeUnprintable, quoteBuf);
413 }
414 }
415
416 U_NAMESPACE_END
417
418 U_CAPI UBool U_EXPORT2
uprv_isRuleWhiteSpace(UChar32 c)419 uprv_isRuleWhiteSpace(UChar32 c) {
420 /* "white space" in the sense of ICU rule parsers
421 This is a FIXED LIST that is NOT DEPENDENT ON UNICODE PROPERTIES.
422 See UAX #31 Identifier and Pattern Syntax: http://www.unicode.org/reports/tr31/
423 U+0009..U+000D, U+0020, U+0085, U+200E..U+200F, and U+2028..U+2029
424 Equivalent to test for Pattern_White_Space Unicode property.
425 */
426 return (c >= 0x0009 && c <= 0x2029 &&
427 (c <= 0x000D || c == 0x0020 || c == 0x0085 ||
428 c == 0x200E || c == 0x200F || c >= 0x2028));
429 }
430
431 U_CAPI U_NAMESPACE_QUALIFIER UnicodeSet* U_EXPORT2
uprv_openRuleWhiteSpaceSet(UErrorCode * ec)432 uprv_openRuleWhiteSpaceSet(UErrorCode* ec) {
433 if(U_FAILURE(*ec)) {
434 return NULL;
435 }
436 // create a set with the Pattern_White_Space characters,
437 // without a pattern for fewer code dependencies
438 U_NAMESPACE_QUALIFIER UnicodeSet *set=new U_NAMESPACE_QUALIFIER UnicodeSet(9, 0xd);
439 set->UnicodeSet::add(0x20).add(0x85).add(0x200e, 0x200f).add(0x2028, 0x2029);
440 return set;
441 }
442
443 //eof
444