1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 *******************************************************************************
6 * Copyright (C) 1999-2014, International Business Machines
7 * Corporation and others. All Rights Reserved.
9 *******************************************************************************
10 * file name: uniset_props.cpp
12 * tab size: 8 (not used)
15 * created on: 2004aug25
16 * created by: Markus W. Scherer
18 * Character property dependent functions moved here from uniset.cpp
21 #include "unicode/utypes.h"
22 #include "unicode/uniset.h"
23 #include "unicode/parsepos.h"
24 #include "unicode/uchar.h"
25 #include "unicode/uscript.h"
26 #include "unicode/symtable.h"
27 #include "unicode/uset.h"
28 #include "unicode/locid.h"
29 #include "unicode/brkiter.h"
38 #include "normalizer2impl.h"
50 // Define UChar constants using hex for EBCDIC compatibility
51 // Used #define to reduce private static exports and memory access time.
52 #define SET_OPEN ((UChar)0x005B) /*[*/
53 #define SET_CLOSE ((UChar)0x005D) /*]*/
54 #define HYPHEN ((UChar)0x002D) /*-*/
55 #define COMPLEMENT ((UChar)0x005E) /*^*/
56 #define COLON ((UChar)0x003A) /*:*/
57 #define BACKSLASH ((UChar)0x005C) /*\*/
58 #define INTERSECTION ((UChar)0x0026) /*&*/
59 #define UPPER_U ((UChar)0x0055) /*U*/
60 #define LOWER_U ((UChar)0x0075) /*u*/
61 #define OPEN_BRACE ((UChar)123) /*{*/
62 #define CLOSE_BRACE ((UChar)125) /*}*/
63 #define UPPER_P ((UChar)0x0050) /*P*/
64 #define LOWER_P ((UChar)0x0070) /*p*/
65 #define UPPER_N ((UChar)78) /*N*/
66 #define EQUALS ((UChar)0x003D) /*=*/
68 //static const UChar POSIX_OPEN[] = { SET_OPEN,COLON,0 }; // "[:"
69 static const UChar POSIX_CLOSE
[] = { COLON
,SET_CLOSE
,0 }; // ":]"
70 //static const UChar PERL_OPEN[] = { BACKSLASH,LOWER_P,0 }; // "\\p"
71 //static const UChar PERL_CLOSE[] = { CLOSE_BRACE,0 }; // "}"
72 //static const UChar NAME_OPEN[] = { BACKSLASH,UPPER_N,0 }; // "\\N"
73 static const UChar HYPHEN_RIGHT_BRACE
[] = {HYPHEN
,SET_CLOSE
,0}; /*-]*/
75 // Special property set IDs
76 static const char ANY
[] = "ANY"; // [\u0000-\U0010FFFF]
77 static const char ASCII
[] = "ASCII"; // [\u0000-\u007F]
78 static const char ASSIGNED
[] = "Assigned"; // [:^Cn:]
80 // Unicode name property alias
81 #define NAME_PROP "na"
82 #define NAME_PROP_LENGTH 2
85 * Delimiter string used in patterns to close a category reference:
86 * ":]". Example: "[:Lu:]".
88 //static const UChar CATEGORY_CLOSE[] = {COLON, SET_CLOSE, 0x0000}; /* ":]" */
90 // Cached sets ------------------------------------------------------------- ***
93 static UBool U_CALLCONV
uset_cleanup();
95 static UnicodeSet
*uni32Singleton
;
96 static icu::UInitOnce uni32InitOnce
= U_INITONCE_INITIALIZER
;
99 * Cleanup function for UnicodeSet
101 static UBool U_CALLCONV
uset_cleanup(void) {
102 delete uni32Singleton
;
103 uni32Singleton
= NULL
;
104 uni32InitOnce
.reset();
114 // Cache some sets for other services -------------------------------------- ***
115 void U_CALLCONV
createUni32Set(UErrorCode
&errorCode
) {
116 U_ASSERT(uni32Singleton
== NULL
);
117 uni32Singleton
= new UnicodeSet(UNICODE_STRING_SIMPLE("[:age=3.2:]"), errorCode
);
118 if(uni32Singleton
==NULL
) {
119 errorCode
=U_MEMORY_ALLOCATION_ERROR
;
121 uni32Singleton
->freeze();
123 ucln_common_registerCleanup(UCLN_COMMON_USET
, uset_cleanup
);
128 uniset_getUnicode32Instance(UErrorCode
&errorCode
) {
129 umtx_initOnce(uni32InitOnce
, &createUni32Set
, errorCode
);
130 return uni32Singleton
;
133 // helper functions for matching of pattern syntax pieces ------------------ ***
134 // these functions are parallel to the PERL_OPEN etc. strings above
136 // using these functions is not only faster than UnicodeString::compare() and
137 // caseCompare(), but they also make UnicodeSet work for simple patterns when
138 // no Unicode properties data is available - when caseCompare() fails
141 isPerlOpen(const UnicodeString
&pattern
, int32_t pos
) {
143 return pattern
.charAt(pos
)==BACKSLASH
&& ((c
=pattern
.charAt(pos
+1))==LOWER_P
|| c
==UPPER_P
);
146 /*static inline UBool
147 isPerlClose(const UnicodeString &pattern, int32_t pos) {
148 return pattern.charAt(pos)==CLOSE_BRACE;
152 isNameOpen(const UnicodeString
&pattern
, int32_t pos
) {
153 return pattern
.charAt(pos
)==BACKSLASH
&& pattern
.charAt(pos
+1)==UPPER_N
;
157 isPOSIXOpen(const UnicodeString
&pattern
, int32_t pos
) {
158 return pattern
.charAt(pos
)==SET_OPEN
&& pattern
.charAt(pos
+1)==COLON
;
161 /*static inline UBool
162 isPOSIXClose(const UnicodeString &pattern, int32_t pos) {
163 return pattern.charAt(pos)==COLON && pattern.charAt(pos+1)==SET_CLOSE;
166 // TODO memory debugging provided inside uniset.cpp
167 // could be made available here but probably obsolete with use of modern
168 // memory leak checker tools
173 //----------------------------------------------------------------
175 //----------------------------------------------------------------
178 * Constructs a set from the given pattern, optionally ignoring
179 * white space. See the class description for the syntax of the
181 * @param pattern a string specifying what characters are in the set
183 UnicodeSet::UnicodeSet(const UnicodeString
& pattern
,
184 UErrorCode
& status
) {
185 applyPattern(pattern
, status
);
189 //----------------------------------------------------------------
191 //----------------------------------------------------------------
193 UnicodeSet
& UnicodeSet::applyPattern(const UnicodeString
& pattern
,
194 UErrorCode
& status
) {
196 // return applyPattern(pattern, USET_IGNORE_SPACE, NULL, status);
197 // but without dependency on closeOver().
198 ParsePosition
pos(0);
199 applyPatternIgnoreSpace(pattern
, pos
, NULL
, status
);
200 if (U_FAILURE(status
)) return *this;
202 int32_t i
= pos
.getIndex();
203 // Skip over trailing whitespace
204 ICU_Utility::skipWhitespace(pattern
, i
, TRUE
);
205 if (i
!= pattern
.length()) {
206 status
= U_ILLEGAL_ARGUMENT_ERROR
;
212 UnicodeSet::applyPatternIgnoreSpace(const UnicodeString
& pattern
,
214 const SymbolTable
* symbols
,
215 UErrorCode
& status
) {
216 if (U_FAILURE(status
)) {
220 status
= U_NO_WRITE_PERMISSION
;
223 // Need to build the pattern in a temporary string because
224 // _applyPattern calls add() etc., which set pat to empty.
225 UnicodeString rebuiltPat
;
226 RuleCharacterIterator
chars(pattern
, symbols
, pos
);
227 applyPattern(chars
, symbols
, rebuiltPat
, USET_IGNORE_SPACE
, NULL
, 0, status
);
228 if (U_FAILURE(status
)) return;
229 if (chars
.inVariable()) {
230 // syntaxError(chars, "Extra chars in variable value");
231 status
= U_MALFORMED_SET
;
234 setPattern(rebuiltPat
);
238 * Return true if the given position, in the given pattern, appears
239 * to be the start of a UnicodeSet pattern.
241 UBool
UnicodeSet::resemblesPattern(const UnicodeString
& pattern
, int32_t pos
) {
242 return ((pos
+1) < pattern
.length() &&
243 pattern
.charAt(pos
) == (UChar
)91/*[*/) ||
244 resemblesPropertyPattern(pattern
, pos
);
247 //----------------------------------------------------------------
248 // Implementation: Pattern parsing
249 //----------------------------------------------------------------
254 * A small all-inline class to manage a UnicodeSet pointer. Add
255 * operator->() etc. as needed.
257 class UnicodeSetPointer
{
260 inline UnicodeSetPointer() : p(0) {}
261 inline ~UnicodeSetPointer() { delete p
; }
262 inline UnicodeSet
* pointer() { return p
; }
263 inline UBool
allocate() {
265 p
= new UnicodeSet();
271 constexpr int32_t MAX_DEPTH
= 100;
276 * Parse the pattern from the given RuleCharacterIterator. The
277 * iterator is advanced over the parsed pattern.
278 * @param chars iterator over the pattern characters. Upon return
279 * it will be advanced to the first character after the parsed
280 * pattern, or the end of the iteration if all characters are
282 * @param symbols symbol table to use to parse and dereference
283 * variables, or null if none.
284 * @param rebuiltPat the pattern that was parsed, rebuilt or
285 * copied from the input pattern, as appropriate.
286 * @param options a bit mask of zero or more of the following:
287 * IGNORE_SPACE, CASE.
289 void UnicodeSet::applyPattern(RuleCharacterIterator
& chars
,
290 const SymbolTable
* symbols
,
291 UnicodeString
& rebuiltPat
,
293 UnicodeSet
& (UnicodeSet::*caseClosure
)(int32_t attribute
),
296 if (U_FAILURE(ec
)) return;
297 if (depth
> MAX_DEPTH
) {
298 ec
= U_ILLEGAL_ARGUMENT_ERROR
;
302 // Syntax characters: [ ] ^ - & { }
304 // Recognized special forms for chars, sets: c-c s-s s&s
306 int32_t opts
= RuleCharacterIterator::PARSE_VARIABLES
|
307 RuleCharacterIterator::PARSE_ESCAPES
;
308 if ((options
& USET_IGNORE_SPACE
) != 0) {
309 opts
|= RuleCharacterIterator::SKIP_WHITESPACE
;
312 UnicodeString patLocal
, buf
;
313 UBool usePat
= FALSE
;
314 UnicodeSetPointer scratch
;
315 RuleCharacterIterator::Pos backup
;
317 // mode: 0=before [, 1=between [...], 2=after ]
318 // lastItem: 0=none, 1=char, 2=set
319 int8_t lastItem
= 0, mode
= 0;
320 UChar32 lastChar
= 0;
323 UBool invert
= FALSE
;
327 while (mode
!= 2 && !chars
.atEnd()) {
328 U_ASSERT((lastItem
== 0 && op
== 0) ||
329 (lastItem
== 1 && (op
== 0 || op
== HYPHEN
/*'-'*/)) ||
330 (lastItem
== 2 && (op
== 0 || op
== HYPHEN
/*'-'*/ ||
331 op
== INTERSECTION
/*'&'*/)));
334 UBool literal
= FALSE
;
335 UnicodeSet
* nested
= 0; // alias - do not delete
337 // -------- Check for property pattern
339 // setMode: 0=none, 1=unicodeset, 2=propertypat, 3=preparsed
341 if (resemblesPropertyPattern(chars
, opts
)) {
345 // -------- Parse '[' of opening delimiter OR nested set.
346 // If there is a nested set, use `setMode' to define how
347 // the set should be parsed. If the '[' is part of the
348 // opening delimiter for this pattern, parse special
349 // strings "[", "[^", "[-", and "[^-". Check for stand-in
350 // characters representing a nested set in the symbol
354 // Prepare to backup if necessary
355 chars
.getPos(backup
);
356 c
= chars
.next(opts
, literal
, ec
);
357 if (U_FAILURE(ec
)) return;
359 if (c
== 0x5B /*'['*/ && !literal
) {
361 chars
.setPos(backup
); // backup
364 // Handle opening '[' delimiter
366 patLocal
.append((UChar
) 0x5B /*'['*/);
367 chars
.getPos(backup
); // prepare to backup
368 c
= chars
.next(opts
, literal
, ec
);
369 if (U_FAILURE(ec
)) return;
370 if (c
== 0x5E /*'^'*/ && !literal
) {
372 patLocal
.append((UChar
) 0x5E /*'^'*/);
373 chars
.getPos(backup
); // prepare to backup
374 c
= chars
.next(opts
, literal
, ec
);
375 if (U_FAILURE(ec
)) return;
377 // Fall through to handle special leading '-';
378 // otherwise restart loop for nested [], \p{}, etc.
379 if (c
== HYPHEN
/*'-'*/) {
381 // Fall through to handle literal '-' below
383 chars
.setPos(backup
); // backup
387 } else if (symbols
!= 0) {
388 const UnicodeFunctor
*m
= symbols
->lookupMatcher(c
);
390 const UnicodeSet
*ms
= dynamic_cast<const UnicodeSet
*>(m
);
392 ec
= U_MALFORMED_SET
;
395 // casting away const, but `nested' won't be modified
396 // (important not to modify stored set)
397 nested
= const_cast<UnicodeSet
*>(ms
);
403 // -------- Handle a nested set. This either is inline in
404 // the pattern or represented by a stand-in that has
405 // previously been parsed and was looked up in the symbol
411 // syntaxError(chars, "Char expected after operator");
412 ec
= U_MALFORMED_SET
;
415 add(lastChar
, lastChar
);
416 _appendToPat(patLocal
, lastChar
, FALSE
);
421 if (op
== HYPHEN
/*'-'*/ || op
== INTERSECTION
/*'&'*/) {
427 if (!scratch
.allocate()) {
428 ec
= U_MEMORY_ALLOCATION_ERROR
;
431 nested
= scratch
.pointer();
435 nested
->applyPattern(chars
, symbols
, patLocal
, options
, caseClosure
, depth
+ 1, ec
);
438 chars
.skipIgnored(opts
);
439 nested
->applyPropertyPattern(chars
, patLocal
, ec
);
440 if (U_FAILURE(ec
)) return;
442 case 3: // `nested' already parsed
443 nested
->_toPattern(patLocal
, FALSE
);
450 // Entire pattern is a category; leave parse loop
460 case INTERSECTION
: /*'&'*/
475 // syntaxError(chars, "Missing '['");
476 ec
= U_MALFORMED_SET
;
480 // -------- Parse special (syntax) characters. If the
481 // current character is not special, or if it is escaped,
482 // then fall through and handle it below.
488 add(lastChar
, lastChar
);
489 _appendToPat(patLocal
, lastChar
, FALSE
);
491 // Treat final trailing '-' as a literal
492 if (op
== HYPHEN
/*'-'*/) {
495 } else if (op
== INTERSECTION
/*'&'*/) {
496 // syntaxError(chars, "Trailing '&'");
497 ec
= U_MALFORMED_SET
;
500 patLocal
.append((UChar
) 0x5D /*']'*/);
509 // Treat final trailing '-' as a literal
511 c
= chars
.next(opts
, literal
, ec
);
512 if (U_FAILURE(ec
)) return;
513 if (c
== 0x5D /*']'*/ && !literal
) {
514 patLocal
.append(HYPHEN_RIGHT_BRACE
, 2);
520 // syntaxError(chars, "'-' not after char or set");
521 ec
= U_MALFORMED_SET
;
523 case INTERSECTION
/*'&'*/:
524 if (lastItem
== 2 && op
== 0) {
528 // syntaxError(chars, "'&' not after set");
529 ec
= U_MALFORMED_SET
;
532 // syntaxError(chars, "'^' not after '['");
533 ec
= U_MALFORMED_SET
;
537 // syntaxError(chars, "Missing operand after operator");
538 ec
= U_MALFORMED_SET
;
542 add(lastChar
, lastChar
);
543 _appendToPat(patLocal
, lastChar
, FALSE
);
549 while (!chars
.atEnd()) {
550 c
= chars
.next(opts
, literal
, ec
);
551 if (U_FAILURE(ec
)) return;
552 if (c
== 0x7D /*'}'*/ && !literal
) {
558 if (buf
.length() < 1 || !ok
) {
559 // syntaxError(chars, "Invalid multicharacter string");
560 ec
= U_MALFORMED_SET
;
564 // We have new string. Add it to set and continue;
565 // we don't need to drop through to the further
568 patLocal
.append((UChar
) 0x7B /*'{'*/);
569 _appendToPat(patLocal
, buf
, FALSE
);
570 patLocal
.append((UChar
) 0x7D /*'}'*/);
572 case SymbolTable::SYMBOL_REF
:
574 // [a-$] error error (ambiguous)
575 // [a$] anchor anchor
576 // [a-$x] var "x"* literal '$'
577 // [a-$.] error literal '$'
578 // *We won't get here in the case of var "x"
580 chars
.getPos(backup
);
581 c
= chars
.next(opts
, literal
, ec
);
582 if (U_FAILURE(ec
)) return;
583 UBool anchor
= (c
== 0x5D /*']'*/ && !literal
);
584 if (symbols
== 0 && !anchor
) {
585 c
= SymbolTable::SYMBOL_REF
;
586 chars
.setPos(backup
);
587 break; // literal '$'
589 if (anchor
&& op
== 0) {
591 add(lastChar
, lastChar
);
592 _appendToPat(patLocal
, lastChar
, FALSE
);
596 patLocal
.append((UChar
) SymbolTable::SYMBOL_REF
);
597 patLocal
.append((UChar
) 0x5D /*']'*/);
601 // syntaxError(chars, "Unquoted '$'");
602 ec
= U_MALFORMED_SET
;
610 // -------- Parse literal characters. This includes both
611 // escaped chars ("\u4E01") and non-syntax characters
620 if (op
== HYPHEN
/*'-'*/) {
622 // Don't allow redundant (a-a) or empty (b-a) ranges;
623 // these are most likely typos.
624 // syntaxError(chars, "Invalid range");
625 ec
= U_MALFORMED_SET
;
629 _appendToPat(patLocal
, lastChar
, FALSE
);
631 _appendToPat(patLocal
, c
, FALSE
);
635 add(lastChar
, lastChar
);
636 _appendToPat(patLocal
, lastChar
, FALSE
);
642 // syntaxError(chars, "Set expected after operator");
643 ec
= U_MALFORMED_SET
;
653 // syntaxError(chars, "Missing ']'");
654 ec
= U_MALFORMED_SET
;
658 chars
.skipIgnored(opts
);
661 * Handle global flags (invert, case insensitivity). If this
662 * pattern should be compiled case-insensitive, then we need
663 * to close over case BEFORE COMPLEMENTING. This makes
664 * patterns like /[^abc]/i work.
666 if ((options
& USET_CASE_INSENSITIVE
) != 0) {
667 (this->*caseClosure
)(USET_CASE_INSENSITIVE
);
669 else if ((options
& USET_ADD_CASE_MAPPINGS
) != 0) {
670 (this->*caseClosure
)(USET_ADD_CASE_MAPPINGS
);
676 // Use the rebuilt pattern (patLocal) only if necessary. Prefer the
677 // generated pattern.
679 rebuiltPat
.append(patLocal
);
681 _generatePattern(rebuiltPat
, FALSE
);
683 if (isBogus() && U_SUCCESS(ec
)) {
684 // We likely ran out of memory. AHHH!
685 ec
= U_MEMORY_ALLOCATION_ERROR
;
689 //----------------------------------------------------------------
690 // Property set implementation
691 //----------------------------------------------------------------
695 static UBool
numericValueFilter(UChar32 ch
, void* context
) {
696 return u_getNumericValue(ch
) == *(double*)context
;
699 static UBool
generalCategoryMaskFilter(UChar32 ch
, void* context
) {
700 int32_t value
= *(int32_t*)context
;
701 return (U_GET_GC_MASK((UChar32
) ch
) & value
) != 0;
704 static UBool
versionFilter(UChar32 ch
, void* context
) {
705 static const UVersionInfo none
= { 0, 0, 0, 0 };
708 UVersionInfo
* version
= (UVersionInfo
*)context
;
709 return uprv_memcmp(&v
, &none
, sizeof(v
)) > 0 && uprv_memcmp(&v
, version
, sizeof(v
)) <= 0;
715 } IntPropertyContext
;
717 static UBool
intPropertyFilter(UChar32 ch
, void* context
) {
718 IntPropertyContext
* c
= (IntPropertyContext
*)context
;
719 return u_getIntPropertyValue((UChar32
) ch
, c
->prop
) == c
->value
;
722 static UBool
scriptExtensionsFilter(UChar32 ch
, void* context
) {
723 return uscript_hasScript(ch
, *(UScriptCode
*)context
);
729 * Generic filter-based scanning code for UCD property UnicodeSets.
731 void UnicodeSet::applyFilter(UnicodeSet::Filter filter
,
733 const UnicodeSet
* inclusions
,
734 UErrorCode
&status
) {
735 if (U_FAILURE(status
)) return;
737 // Logically, walk through all Unicode characters, noting the start
738 // and end of each range for which filter.contain(c) is
739 // true. Add each range to a set.
741 // To improve performance, use an inclusions set which
742 // encodes information about character ranges that are known
743 // to have identical properties.
744 // inclusions contains the first characters of
745 // same-value ranges for the given property.
749 UChar32 startHasProperty
= -1;
750 int32_t limitRange
= inclusions
->getRangeCount();
752 for (int j
=0; j
<limitRange
; ++j
) {
754 UChar32 start
= inclusions
->getRangeStart(j
);
755 UChar32 end
= inclusions
->getRangeEnd(j
);
757 // for all the code points in the range, process
758 for (UChar32 ch
= start
; ch
<= end
; ++ch
) {
759 // only add to this UnicodeSet on inflection points --
760 // where the hasProperty value changes to false
761 if ((*filter
)(ch
, context
)) {
762 if (startHasProperty
< 0) {
763 startHasProperty
= ch
;
765 } else if (startHasProperty
>= 0) {
766 add(startHasProperty
, ch
-1);
767 startHasProperty
= -1;
771 if (startHasProperty
>= 0) {
772 add((UChar32
)startHasProperty
, (UChar32
)0x10FFFF);
774 if (isBogus() && U_SUCCESS(status
)) {
775 // We likely ran out of memory. AHHH!
776 status
= U_MEMORY_ALLOCATION_ERROR
;
782 static UBool
mungeCharName(char* dst
, const char* src
, int32_t dstCapacity
) {
783 /* Note: we use ' ' in compiler code page */
786 --dstCapacity
; /* make room for term. zero */
787 while ((ch
= *src
++) != 0) {
788 if (ch
== ' ' && (j
==0 || (j
>0 && dst
[j
-1]==' '))) {
791 if (j
>= dstCapacity
) return FALSE
;
794 if (j
> 0 && dst
[j
-1] == ' ') --j
;
801 //----------------------------------------------------------------
803 //----------------------------------------------------------------
805 #define FAIL(ec) {ec=U_ILLEGAL_ARGUMENT_ERROR; return *this;}
808 UnicodeSet::applyIntPropertyValue(UProperty prop
, int32_t value
, UErrorCode
& ec
) {
809 if (U_FAILURE(ec
) || isFrozen()) { return *this; }
810 if (prop
== UCHAR_GENERAL_CATEGORY_MASK
) {
811 const UnicodeSet
* inclusions
= CharacterProperties::getInclusionsForProperty(prop
, ec
);
812 applyFilter(generalCategoryMaskFilter
, &value
, inclusions
, ec
);
813 } else if (prop
== UCHAR_SCRIPT_EXTENSIONS
) {
814 const UnicodeSet
* inclusions
= CharacterProperties::getInclusionsForProperty(prop
, ec
);
815 UScriptCode script
= (UScriptCode
)value
;
816 applyFilter(scriptExtensionsFilter
, &script
, inclusions
, ec
);
817 } else if (0 <= prop
&& prop
< UCHAR_BINARY_LIMIT
) {
818 if (value
== 0 || value
== 1) {
819 const USet
*set
= u_getBinaryPropertySet(prop
, &ec
);
820 if (U_FAILURE(ec
)) { return *this; }
821 copyFrom(*UnicodeSet::fromUSet(set
), TRUE
);
828 } else if (UCHAR_INT_START
<= prop
&& prop
< UCHAR_INT_LIMIT
) {
829 const UnicodeSet
* inclusions
= CharacterProperties::getInclusionsForProperty(prop
, ec
);
830 IntPropertyContext c
= {prop
, value
};
831 applyFilter(intPropertyFilter
, &c
, inclusions
, ec
);
833 ec
= U_ILLEGAL_ARGUMENT_ERROR
;
839 UnicodeSet::applyPropertyAlias(const UnicodeString
& prop
,
840 const UnicodeString
& value
,
842 if (U_FAILURE(ec
) || isFrozen()) return *this;
844 // prop and value used to be converted to char * using the default
845 // converter instead of the invariant conversion.
846 // This should not be necessary because all Unicode property and value
847 // names use only invariant characters.
848 // If there are any variant characters, then we won't find them anyway.
849 // Checking first avoids assertion failures in the conversion.
850 if( !uprv_isInvariantUString(prop
.getBuffer(), prop
.length()) ||
851 !uprv_isInvariantUString(value
.getBuffer(), value
.length())
855 CharString pname
, vname
;
856 pname
.appendInvariantChars(prop
, ec
);
857 vname
.appendInvariantChars(value
, ec
);
858 if (U_FAILURE(ec
)) return *this;
862 UBool invert
= FALSE
;
864 if (value
.length() > 0) {
865 p
= u_getPropertyEnum(pname
.data());
866 if (p
== UCHAR_INVALID_CODE
) FAIL(ec
);
869 if (p
== UCHAR_GENERAL_CATEGORY
) {
870 p
= UCHAR_GENERAL_CATEGORY_MASK
;
873 if ((p
>= UCHAR_BINARY_START
&& p
< UCHAR_BINARY_LIMIT
) ||
874 (p
>= UCHAR_INT_START
&& p
< UCHAR_INT_LIMIT
) ||
875 (p
>= UCHAR_MASK_START
&& p
< UCHAR_MASK_LIMIT
)) {
876 v
= u_getPropertyValueEnum(p
, vname
.data());
877 if (v
== UCHAR_INVALID_CODE
) {
878 // Handle numeric CCC
879 if (p
== UCHAR_CANONICAL_COMBINING_CLASS
||
880 p
== UCHAR_TRAIL_CANONICAL_COMBINING_CLASS
||
881 p
== UCHAR_LEAD_CANONICAL_COMBINING_CLASS
) {
883 double val
= uprv_strtod(vname
.data(), &end
);
884 // Anything between 0 and 255 is valid even if unused.
885 // Cast double->int only after range check.
886 // We catch NaN here because comparing it with both 0 and 255 will be false
887 // (as are all comparisons with NaN).
888 if (*end
!= 0 || !(0 <= val
&& val
<= 255) ||
889 (v
= (int32_t)val
) != val
) {
890 // non-integral value or outside 0..255, or trailing junk
902 case UCHAR_NUMERIC_VALUE
:
905 double val
= uprv_strtod(vname
.data(), &end
);
909 applyFilter(numericValueFilter
, &val
,
910 CharacterProperties::getInclusionsForProperty(p
, ec
), ec
);
915 // Must munge name, since u_charFromName() does not do
917 char buf
[128]; // it suffices that this be > uprv_getMaxCharNameLength
918 if (!mungeCharName(buf
, vname
.data(), sizeof(buf
))) FAIL(ec
);
919 UChar32 ch
= u_charFromName(U_EXTENDED_CHAR_NAME
, buf
, &ec
);
928 case UCHAR_UNICODE_1_NAME
:
929 // ICU 49 deprecates the Unicode_1_Name property APIs.
933 // Must munge name, since u_versionFromString() does not do
936 if (!mungeCharName(buf
, vname
.data(), sizeof(buf
))) FAIL(ec
);
937 UVersionInfo version
;
938 u_versionFromString(version
, buf
);
939 applyFilter(versionFilter
, &version
,
940 CharacterProperties::getInclusionsForProperty(p
, ec
), ec
);
943 case UCHAR_SCRIPT_EXTENSIONS
:
944 v
= u_getPropertyValueEnum(UCHAR_SCRIPT
, vname
.data());
945 if (v
== UCHAR_INVALID_CODE
) {
948 // fall through to calling applyIntPropertyValue()
951 // p is a non-binary, non-enumerated property that we
952 // don't support (yet).
959 // value is empty. Interpret as General Category, Script, or
961 p
= UCHAR_GENERAL_CATEGORY_MASK
;
962 v
= u_getPropertyValueEnum(p
, pname
.data());
963 if (v
== UCHAR_INVALID_CODE
) {
965 v
= u_getPropertyValueEnum(p
, pname
.data());
966 if (v
== UCHAR_INVALID_CODE
) {
967 p
= u_getPropertyEnum(pname
.data());
968 if (p
>= UCHAR_BINARY_START
&& p
< UCHAR_BINARY_LIMIT
) {
970 } else if (0 == uprv_comparePropertyNames(ANY
, pname
.data())) {
971 set(MIN_VALUE
, MAX_VALUE
);
973 } else if (0 == uprv_comparePropertyNames(ASCII
, pname
.data())) {
976 } else if (0 == uprv_comparePropertyNames(ASSIGNED
, pname
.data())) {
977 // [:Assigned:]=[:^Cn:]
978 p
= UCHAR_GENERAL_CATEGORY_MASK
;
988 applyIntPropertyValue(p
, v
, ec
);
993 if (isBogus() && U_SUCCESS(ec
)) {
994 // We likely ran out of memory. AHHH!
995 ec
= U_MEMORY_ALLOCATION_ERROR
;
1000 //----------------------------------------------------------------
1001 // Property set patterns
1002 //----------------------------------------------------------------
1005 * Return true if the given position, in the given pattern, appears
1006 * to be the start of a property set pattern.
1008 UBool
UnicodeSet::resemblesPropertyPattern(const UnicodeString
& pattern
,
1010 // Patterns are at least 5 characters long
1011 if ((pos
+5) > pattern
.length()) {
1015 // Look for an opening [:, [:^, \p, or \P
1016 return isPOSIXOpen(pattern
, pos
) || isPerlOpen(pattern
, pos
) || isNameOpen(pattern
, pos
);
1020 * Return true if the given iterator appears to point at a
1021 * property pattern. Regardless of the result, return with the
1022 * iterator unchanged.
1023 * @param chars iterator over the pattern characters. Upon return
1024 * it will be unchanged.
1025 * @param iterOpts RuleCharacterIterator options
1027 UBool
UnicodeSet::resemblesPropertyPattern(RuleCharacterIterator
& chars
,
1029 // NOTE: literal will always be FALSE, because we don't parse escapes.
1030 UBool result
= FALSE
, literal
;
1031 UErrorCode ec
= U_ZERO_ERROR
;
1032 iterOpts
&= ~RuleCharacterIterator::PARSE_ESCAPES
;
1033 RuleCharacterIterator::Pos pos
;
1035 UChar32 c
= chars
.next(iterOpts
, literal
, ec
);
1036 if (c
== 0x5B /*'['*/ || c
== 0x5C /*'\\'*/) {
1037 UChar32 d
= chars
.next(iterOpts
& ~RuleCharacterIterator::SKIP_WHITESPACE
,
1039 result
= (c
== 0x5B /*'['*/) ? (d
== 0x3A /*':'*/) :
1040 (d
== 0x4E /*'N'*/ || d
== 0x70 /*'p'*/ || d
== 0x50 /*'P'*/);
1043 return result
&& U_SUCCESS(ec
);
1047 * Parse the given property pattern at the given parse position.
1049 UnicodeSet
& UnicodeSet::applyPropertyPattern(const UnicodeString
& pattern
,
1050 ParsePosition
& ppos
,
1052 int32_t pos
= ppos
.getIndex();
1054 UBool posix
= FALSE
; // true for [:pat:], false for \p{pat} \P{pat} \N{pat}
1055 UBool isName
= FALSE
; // true for \N{pat}, o/w false
1056 UBool invert
= FALSE
;
1058 if (U_FAILURE(ec
)) return *this;
1060 // Minimum length is 5 characters, e.g. \p{L}
1061 if ((pos
+5) > pattern
.length()) {
1065 // On entry, ppos should point to one of the following locations:
1066 // Look for an opening [:, [:^, \p, or \P
1067 if (isPOSIXOpen(pattern
, pos
)) {
1070 pos
= ICU_Utility::skipWhitespace(pattern
, pos
);
1071 if (pos
< pattern
.length() && pattern
.charAt(pos
) == COMPLEMENT
) {
1075 } else if (isPerlOpen(pattern
, pos
) || isNameOpen(pattern
, pos
)) {
1076 UChar c
= pattern
.charAt(pos
+1);
1077 invert
= (c
== UPPER_P
);
1078 isName
= (c
== UPPER_N
);
1080 pos
= ICU_Utility::skipWhitespace(pattern
, pos
);
1081 if (pos
== pattern
.length() || pattern
.charAt(pos
++) != OPEN_BRACE
) {
1082 // Syntax error; "\p" or "\P" not followed by "{"
1086 // Open delimiter not seen
1090 // Look for the matching close delimiter, either :] or }
1093 close
= pattern
.indexOf(POSIX_CLOSE
, 2, pos
);
1095 close
= pattern
.indexOf(CLOSE_BRACE
, pos
);
1098 // Syntax error; close delimiter missing
1102 // Look for an '=' sign. If this is present, we will parse a
1103 // medium \p{gc=Cf} or long \p{GeneralCategory=Format}
1105 int32_t equals
= pattern
.indexOf(EQUALS
, pos
);
1106 UnicodeString propName
, valueName
;
1107 if (equals
>= 0 && equals
< close
&& !isName
) {
1108 // Equals seen; parse medium/long pattern
1109 pattern
.extractBetween(pos
, equals
, propName
);
1110 pattern
.extractBetween(equals
+1, close
, valueName
);
1114 // Handle case where no '=' is seen, and \N{}
1115 pattern
.extractBetween(pos
, close
, propName
);
1119 // This is a little inefficient since it means we have to
1120 // parse NAME_PROP back to UCHAR_NAME even though we already
1121 // know it's UCHAR_NAME. If we refactor the API to
1122 // support args of (UProperty, char*) then we can remove
1123 // NAME_PROP and make this a little more efficient.
1124 valueName
= propName
;
1125 propName
= UnicodeString(NAME_PROP
, NAME_PROP_LENGTH
, US_INV
);
1129 applyPropertyAlias(propName
, valueName
, ec
);
1131 if (U_SUCCESS(ec
)) {
1136 // Move to the limit position after the close delimiter if the
1138 ppos
.setIndex(close
+ (posix
? 2 : 1));
1145 * Parse a property pattern.
1146 * @param chars iterator over the pattern characters. Upon return
1147 * it will be advanced to the first character after the parsed
1148 * pattern, or the end of the iteration if all characters are
1150 * @param rebuiltPat the pattern that was parsed, rebuilt or
1151 * copied from the input pattern, as appropriate.
1153 void UnicodeSet::applyPropertyPattern(RuleCharacterIterator
& chars
,
1154 UnicodeString
& rebuiltPat
,
1156 if (U_FAILURE(ec
)) return;
1157 UnicodeString pattern
;
1158 chars
.lookahead(pattern
);
1159 ParsePosition
pos(0);
1160 applyPropertyPattern(pattern
, pos
, ec
);
1161 if (U_FAILURE(ec
)) return;
1162 if (pos
.getIndex() == 0) {
1163 // syntaxError(chars, "Invalid property pattern");
1164 ec
= U_MALFORMED_SET
;
1167 chars
.jumpahead(pos
.getIndex());
1168 rebuiltPat
.append(pattern
, 0, pos
.getIndex());