util.cpp 14 KB

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