-
-
Notifications
You must be signed in to change notification settings - Fork 875
Expand file tree
/
Copy pathuniset_props.cpp
More file actions
1589 lines (1471 loc) · 67.6 KB
/
uniset_props.cpp
File metadata and controls
1589 lines (1471 loc) · 67.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 1999-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: uniset_props.cpp
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2004aug25
* created by: Markus W. Scherer
*
* Character property dependent functions moved here from uniset.cpp
*/
#include <array>
#include <optional>
#include "unicode/utypes.h"
#include "unicode/uniset.h"
#include "unicode/parsepos.h"
#include "unicode/uchar.h"
#include "unicode/uscript.h"
#include "unicode/symtable.h"
#include "unicode/uset.h"
#include "unicode/locid.h"
#include "unicode/brkiter.h"
#include "unicode/utfiterator.h"
#include "uset_imp.h"
#include "ruleiter.h"
#include "cmemory.h"
#include "ucln_cmn.h"
#include "util.h"
#include "uvector.h"
#include "uprops.h"
#include "patternprops.h"
#include "propname.h"
#include "normalizer2impl.h"
#include "uinvchar.h"
#include "uprops.h"
#include "charstr.h"
#include "cstring.h"
#include "mutex.h"
#include "umutex.h"
#include "uassert.h"
#include "hash.h"
U_NAMESPACE_USE
namespace {
// Special property set IDs
constexpr char ANY[] = "ANY"; // [\u0000-\U0010FFFF]
constexpr char ASCII[] = "ASCII"; // [\u0000-\u007F]
constexpr char ASSIGNED[] = "Assigned"; // [:^Cn:]
} // namespace
// Cached sets ------------------------------------------------------------- ***
U_CDECL_BEGIN
static UBool U_CALLCONV uset_cleanup();
static UnicodeSet *uni32Singleton;
static icu::UInitOnce uni32InitOnce {};
/**
* Cleanup function for UnicodeSet
*/
static UBool U_CALLCONV uset_cleanup() {
delete uni32Singleton;
uni32Singleton = nullptr;
uni32InitOnce.reset();
return true;
}
U_CDECL_END
U_NAMESPACE_BEGIN
using U_HEADER_ONLY_NAMESPACE::utfStringCodePoints;
namespace {
// Cache some sets for other services -------------------------------------- ***
void U_CALLCONV createUni32Set(UErrorCode &errorCode) {
U_ASSERT(uni32Singleton == nullptr);
uni32Singleton = new UnicodeSet(UnicodeString(u"[:age=3.2:]"), errorCode);
if(uni32Singleton==nullptr) {
errorCode=U_MEMORY_ALLOCATION_ERROR;
} else {
uni32Singleton->freeze();
}
ucln_common_registerCleanup(UCLN_COMMON_USET, uset_cleanup);
}
U_CFUNC UnicodeSet *
uniset_getUnicode32Instance(UErrorCode &errorCode) {
umtx_initOnce(uni32InitOnce, &createUni32Set, errorCode);
return uni32Singleton;
}
// helper functions for matching of pattern syntax pieces ------------------ ***
// these functions are parallel to the PERL_OPEN etc. strings above
// using these functions is not only faster than UnicodeString::compare() and
// caseCompare(), but they also make UnicodeSet work for simple patterns when
// no Unicode properties data is available - when caseCompare() fails
inline UBool
isPerlOpen(const UnicodeString &pattern, int32_t pos) {
char16_t c;
return pattern.charAt(pos)==u'\\' && ((c=pattern.charAt(pos+1))==u'p' || c==u'P');
}
/*static inline UBool
isPerlClose(const UnicodeString &pattern, int32_t pos) {
return pattern.charAt(pos)==u'}';
}*/
inline UBool
isNameOpen(const UnicodeString &pattern, int32_t pos) {
return pattern.charAt(pos)==u'\\' && pattern.charAt(pos+1)==u'N';
}
inline UBool
isPOSIXOpen(const UnicodeString &pattern, int32_t pos) {
return pattern.charAt(pos)==u'[' && pattern.charAt(pos+1)==u':';
}
/*static inline UBool
isPOSIXClose(const UnicodeString &pattern, int32_t pos) {
return pattern.charAt(pos)==u':' && pattern.charAt(pos+1)==u']';
}*/
// TODO memory debugging provided inside uniset.cpp
// could be made available here but probably obsolete with use of modern
// memory leak checker tools
#define _dbgct(me)
// Strips leading and trailing spaces and turns runs of spaces into single spaces.
// This should be replaced by UAX44-LM1 and UAX44-LM2 skeletonizations as part of ICU-3736.
template<typename CharT>
UBool mungeCharName(std::basic_string_view<CharT> src, char* dst, int32_t dstCapacity) {
int32_t j = 0;
--dstCapacity; /* make room for term. zero */
if constexpr (!std::is_same_v<CharT, char>) {
if (!uprv_isInvariantUString(src.data(), static_cast<int32_t>(src.size()))) {
return false;
}
}
for (CharT uch : src) {
char ch;
if constexpr (std::is_same_v<CharT, char>) {
ch = uch;
} else {
// This would want to be UCHAR_TO_CHAR but that is defined in uinvchar.cpp. This function
// should not last long anyway (famous last words)…
u_UCharsToChars(&uch, &ch, 1);
}
if (ch == ' ' && (j == 0 || (j > 0 && dst[j - 1] == ' '))) {
continue;
}
if (j >= dstCapacity) return false;
dst[j++] = ch;
}
if (j > 0 && dst[j-1] == ' ') --j;
dst[j] = 0;
return true;
}
// Returns the character with the given name or name alias, or U_SENTINEL if no such character
// exists.
template<typename CharT>
UChar32 getCharacterByName(const std::basic_string_view<CharT> name) {
// Must munge name, since u_charFromName() does not do 'loose' matching.
char buf[128]; // it suffices that this be > uprv_getMaxCharNameLength
if (!mungeCharName(name, buf, sizeof(buf))) {
return U_SENTINEL;
}
for (const UCharNameChoice nameChoice : std::array{U_EXTENDED_CHAR_NAME, U_CHAR_NAME_ALIAS}) {
UErrorCode ec = U_ZERO_ERROR;
UChar32 ch = u_charFromName(nameChoice, buf, &ec);
if (U_SUCCESS(ec)) {
return ch;
}
}
return U_SENTINEL;
}
} // namespace
//----------------------------------------------------------------
// Constructors &c
//----------------------------------------------------------------
/**
* Constructs a set from the given pattern, optionally ignoring
* white space. See the class description for the syntax of the
* pattern language.
* @param pattern a string specifying what characters are in the set
*/
UnicodeSet::UnicodeSet(const UnicodeString& pattern,
UErrorCode& status) {
applyPattern(pattern, status);
_dbgct(this);
}
//----------------------------------------------------------------
// Public API
//----------------------------------------------------------------
UnicodeSet& UnicodeSet::applyPattern(const UnicodeString& pattern,
UErrorCode& status) {
// Equivalent to
// return applyPattern(pattern, USET_IGNORE_SPACE, nullptr, status);
// but without dependency on closeOver().
ParsePosition pos(0);
applyPatternIgnoreSpace(pattern, pos, nullptr, status);
if (U_FAILURE(status)) return *this;
int32_t i = pos.getIndex();
// Skip over trailing whitespace
ICU_Utility::skipWhitespace(pattern, i, true);
if (i != pattern.length()) {
status = U_ILLEGAL_ARGUMENT_ERROR;
}
return *this;
}
void
UnicodeSet::applyPatternIgnoreSpace(const UnicodeString& pattern,
ParsePosition& pos,
const SymbolTable* symbols,
UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
if (isFrozen()) {
status = U_NO_WRITE_PERMISSION;
return;
}
// Need to build the pattern in a temporary string because
// _applyPattern calls add() etc., which set pat to empty.
UnicodeString rebuiltPat;
RuleCharacterIterator chars(pattern, symbols, pos);
applyPattern(pattern, pos, chars, symbols, rebuiltPat, USET_IGNORE_SPACE, nullptr, status);
if (U_FAILURE(status)) return;
if (chars.inVariable()) {
// syntaxError(chars, "Extra chars in variable value");
status = U_MALFORMED_SET;
return;
}
setPattern(rebuiltPat);
}
/**
* Return true if the given position, in the given pattern, appears
* to be the start of a UnicodeSet pattern.
*/
UBool UnicodeSet::resemblesPattern(const UnicodeString& pattern, int32_t pos) {
return ((pos+1) < pattern.length() &&
pattern.charAt(pos) == static_cast<char16_t>(91)/*[*/) ||
resemblesPropertyPattern(pattern, pos);
}
//----------------------------------------------------------------
// Implementation: Pattern parsing
//----------------------------------------------------------------
#define U_DEBUGGING_UNICODESET_PARSING 0
class UnicodeSet::Lexer {
public:
Lexer(const UnicodeString &pattern,
const ParsePosition &parsePosition,
RuleCharacterIterator &chars,
uint32_t unicodeSetOptions,
const SymbolTable *const symbols,
UnicodeSet &(UnicodeSet::*caseClosure)(int32_t attribute))
: pattern_(pattern), parsePosition_(parsePosition), chars_(chars),
unicodeSetOptions_(unicodeSetOptions),
charsOptions_(RuleCharacterIterator::PARSE_ESCAPES |
((unicodeSetOptions & USET_IGNORE_SPACE) != 0
? RuleCharacterIterator::SKIP_WHITESPACE
: 0)),
symbols_(symbols),
caseClosure_(caseClosure) {}
class LexicalElement {
public:
bool isSetOperator(const char16_t op) const {
return U_SUCCESS(errorCode_) && category_ == SET_OPERATOR && string_[0] == op;
}
bool isStringLiteral() const {
return U_SUCCESS(errorCode_) && category_ == STRING_LITERAL;
}
bool isNamedElement() const {
return U_SUCCESS(errorCode_) && category_ == NAMED_ELEMENT;
}
bool isBracketedElement() const {
return U_SUCCESS(errorCode_) && category_ == BRACKETED_ELEMENT;
}
std::optional<UnicodeString> element() const {
if (U_SUCCESS(errorCode_) &&
(category_ == LITERAL_ELEMENT || category_ == ESCAPED_ELEMENT ||
category_ == BRACKETED_ELEMENT || category_ == STRING_LITERAL)) {
return string_;
}
return std::nullopt;
}
std::optional<UChar32> codePoint() const {
if (U_SUCCESS(errorCode_) && (category_ == LITERAL_ELEMENT || category_ == ESCAPED_ELEMENT ||
category_ == BRACKETED_ELEMENT || category_ == NAMED_ELEMENT)) {
return string_.char32At(0);
}
return std::nullopt;
}
// If `*this` is a valid property-query or set-valued-variable, returns the set represented
// by this lexical element, which lives at least as long as `*this`. Null otherwise.
const UnicodeSet *set() const {
if (U_FAILURE(errorCode_)) {
return nullptr;
}
if (category_ == PROPERTY_QUERY || category_ == VARIABLE) {
if (precomputedSet_ != nullptr) {
return precomputedSet_;
} else {
return &set_;
}
}
return nullptr;
}
const UErrorCode& errorCode() const{
return errorCode_;
}
#if U_DEBUGGING_UNICODESET_PARSING
UnicodeString debugString() const {
UnicodeString result;
if (U_FAILURE(errorCode_)) {
result.append(u"Ill-formed token (")
.append(UnicodeString::fromUTF8(u_errorName(errorCode_)))
.append(u"), possibly ");
}
return result.append(category_names_[category_])
.append(u" '")
.append(sourceText_)
.append(u"'");
}
#endif
private:
// See https://unicode.org/reports/tr61#Lexical-Elements.
enum Category : std::uint8_t {
SET_OPERATOR,
LITERAL_ELEMENT,
ESCAPED_ELEMENT,
NAMED_ELEMENT,
BRACKETED_ELEMENT,
STRING_LITERAL,
PROPERTY_QUERY,
// Used for ill-formed variables and set-valued variables that are not directly a
// property-query, e.g., $basicLatinLetters=[A-Za-z]. Variables that expand to a single
// lexical element instead have the category of that lexical element, e.g., $Ll=\p{Ll} has
// the category PROPERTY_QUERY, $a=a has the category LITERAL_ELEMENT, and $s={Zeichenkette}
// has the category STRING_LITERAL.
VARIABLE,
END_OF_TEXT,
};
static constexpr std::array<std::u16string_view, END_OF_TEXT + 1> category_names_{{
u"set-operator",
u"literal-element",
u"escaped-element",
u"named-element",
u"bracketed-element",
u"string-literal",
u"property-query",
u"variable",
u"(end of text)",
}};
LexicalElement(Category category, UnicodeString string, RuleCharacterIterator::Pos after,
UErrorCode errorCode, const UnicodeSet *precomputedSet, UnicodeSet set,
std::u16string_view sourceText)
: category_(category), string_(std::move(string)), after_(after), errorCode_(errorCode),
precomputedSet_(precomputedSet), set_(set), sourceText_(sourceText) {}
Category category_;
UnicodeString string_;
RuleCharacterIterator::Pos after_;
UErrorCode errorCode_;
const UnicodeSet *precomputedSet_;
UnicodeSet set_;
std::u16string_view sourceText_;
friend class Lexer;
};
UnicodeString getPositionForDebugging() const {
return pattern_.tempSubString(0, parsePosition_.getIndex()) + u"☞" +
pattern_.tempSubString(parsePosition_.getIndex(), 60);
}
bool acceptSetOperator(char16_t op) {
if (lookahead().isSetOperator(op)) {
advance();
return true;
}
return false;
}
const LexicalElement &lookahead() {
if (!ahead_.has_value()) {
const RuleCharacterIterator::Pos before = getPos();
ahead_.emplace(nextToken());
chars_.setPos(before);
}
return *ahead_;
}
const LexicalElement &lookahead2() {
if (!ahead2_.has_value()) {
// Note that if someone has called `getCharacterIterator` and played with the result,
// `before` may not actually be before `ahead_`, but we do not actually depend on this here,
// since we start from ahead_.after_.
const RuleCharacterIterator::Pos before = getPos();
chars_.setPos(lookahead().after_);
ahead2_.emplace(nextToken());
chars_.setPos(before);
}
return *ahead2_;
}
// For use in older functions that take the `RuleCharacterIterator` directly.
// Any advancement of the resulting `RuleCharacterIterator` has no effect on the result of subsequent
// calls to `lookahead`, `lookahead2`, `advance`, or `acceptSetOperator`.
// Once `advance` or `acceptSetOperator` has been called, the result of a call to
// `getCharacterIterator` preceding the call to `advance` or `acceptSetOperator` must no longer be
// used.
RuleCharacterIterator &getCharacterIterator() {
// Make sure we compute a correct `ahead_.after_` so we do not depend on the current value of
// `getPos()` for lexing.
lookahead();
return chars_;
}
int32_t charsOptions() {
return charsOptions_;
}
bool atEnd() const {
return chars_.atEnd();
}
void advance() {
// If someone called `getCharacterIterator`, we are now changing the character iterator under
// their feet; further, we may not have an `ahead_`, so if they keep playing with it we would be
// working on incorrect values of `getPos`. This is why the result of `getCharacterIterator`
// must no longer be used.
chars_.setPos(lookahead().after_);
ahead_ = ahead2_;
ahead2_.reset();
}
private:
// A version of getPos that returns its position instead of taking it as at out parameter, so we
// can have const positions.
RuleCharacterIterator::Pos getPos() const {
RuleCharacterIterator::Pos result;
chars_.getPos(result);
return result;
}
LexicalElement nextToken() {
UErrorCode errorCode = U_ZERO_ERROR;
chars_.skipIgnored(charsOptions_);
if (chars_.atEnd()) {
return LexicalElement(LexicalElement::END_OF_TEXT, {}, getPos(), errorCode,
/*precomputedSet=*/nullptr,
/*set=*/{},
u"");
}
const int32_t start = parsePosition_.getIndex();
const RuleCharacterIterator::Pos before = getPos();
// First try to get the next character without parsing escapes.
UBool unusedEscaped;
const UChar32 first =
chars_.next(charsOptions_ & ~RuleCharacterIterator::PARSE_ESCAPES, unusedEscaped, errorCode);
if (first == u'[' || first == u'\\') {
const RuleCharacterIterator::Pos afterFirst = getPos();
// This could be a property-query or named-element.
const UChar32 second = chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if ((first == u'[' && second == u':') ||
(first == u'\\' && (second == u'p' || second == u'P' || second == u'N'))) {
if (second == u'N') {
UChar32 const queryResult = scanNamedElementBrackets(errorCode);
return LexicalElement(
LexicalElement::NAMED_ELEMENT, UnicodeString(queryResult), getPos(), errorCode,
/*precomputedSet=*/nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
} else {
UnicodeSet queryResult = scanPropertyQueryAfterStart(first, second, start, errorCode);
return LexicalElement(
LexicalElement::PROPERTY_QUERY, {}, getPos(), errorCode,
/*precomputedSet=*/nullptr, /*set=*/std::move(queryResult),
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
}
}
// Not a property-query.
chars_.setPos(afterFirst);
}
if (first == u'$' && symbols_ != nullptr) {
auto nameEnd = parsePosition_;
// The SymbolTable defines the lexing of variable names past the $.
if (UnicodeString name = symbols_->parseReference(pattern_, nameEnd, pattern_.length());
!name.isEmpty()) {
chars_.jumpahead(nameEnd.getIndex() - (start + 1));
const std::u16string_view source =
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start);
const UnicodeSet *precomputedSet = symbols_->lookupSet(name);
if (precomputedSet != nullptr) {
return LexicalElement(LexicalElement::VARIABLE, {}, getPos(), U_ZERO_ERROR,
precomputedSet, /*set=*/{}, source);
}
// The variable was not a precomputed set. Use the old-fashioned `lookup`, which
// should give us its source text; if that parses as a single set or element, use
// it. Note that variables are not allowed in that expansion.
// Implementers of higher-level syntaxes that pre-parse UnicodeSet-valued variables
// can use variables in their variable definitions, but those that simply use the
// source text substitution API cannot.
const UnicodeString *const expression = symbols_->lookup(name);
if (expression == nullptr) {
return LexicalElement(
LexicalElement::VARIABLE, {}, getPos(), U_UNDEFINED_VARIABLE,
/*precomputedSet=*/nullptr,
/*set=*/{},
source);
}
return evaluateVariable(*expression, source);
}
}
switch (first) {
case u'[':
return LexicalElement(
LexicalElement::SET_OPERATOR, UnicodeString(u'['), getPos(), errorCode,
/*precomputedSet=*/nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
case u'\\': {
// Now try to parse the escape.
chars_.setPos(before);
UChar32 codePoint = chars_.next(charsOptions_, unusedEscaped, errorCode);
return LexicalElement(
LexicalElement::ESCAPED_ELEMENT,
UnicodeString(codePoint), getPos(), errorCode,
nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
}
case u'&':
case u'-':
case u']':
case u'^':
case u'$':
// We make $ a set-operator to handle the ICU extensions involving $.
return LexicalElement(
LexicalElement::SET_OPERATOR, UnicodeString(first), getPos(), errorCode,
/*precomputedSet=*/nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
case u'{': {
UnicodeString string;
UBool escaped;
UChar32 next;
int32_t codePointCount = 0;
while (!chars_.atEnd() && U_SUCCESS(errorCode)) {
const RuleCharacterIterator::Pos beforeNext = getPos();
next = chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if (next == u'\\') {
const UChar32 afterBackslash =
chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if (afterBackslash == u'N') {
next = scanNamedElementBrackets(errorCode);
escaped = true;
} else if (afterBackslash == u'p' || afterBackslash == u'P') {
return LexicalElement(LexicalElement::STRING_LITERAL, {}, getPos(),
U_MALFORMED_SET,
/*precomputedSet=*/nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(
start, parsePosition_.getIndex() - start));
} else {
chars_.setPos(beforeNext);
// Parse the escape.
next = chars_.next(charsOptions_, escaped, errorCode);
}
} else {
#if U_ICU_VERSION_MAJOR_NUM < 81
if (U_SUCCESS(errorCode) && PatternProps::isWhiteSpace(next)) {
// Transitional prohibition of unescaped spaces in string literals (in
// ICU 78 and earlier, these were ignored; in ICU 81 they will mean
// themselves).
errorCode = UErrorCode::U_ILLEGAL_ARGUMENT_ERROR;
}
#else
#error Remove this transitional check, see ICU-23307 and ICU-TC minutes of 2026-01-16.
#endif
escaped = false;
}
if (!escaped && next == u'}') {
return LexicalElement(
codePointCount == 1 ? LexicalElement::BRACKETED_ELEMENT
: LexicalElement::STRING_LITERAL,
std::move(string), getPos(), errorCode,
/*precomputedSet=*/nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
}
string.append(next);
codePointCount += 1;
}
return LexicalElement(
LexicalElement::STRING_LITERAL, {}, getPos(), U_MALFORMED_SET,
/*precomputedSet=*/nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
}
default:
return LexicalElement(
LexicalElement::LITERAL_ELEMENT, UnicodeString(first), getPos(), errorCode, nullptr,
/*set=*/{},
std::u16string_view(pattern_).substr(start, parsePosition_.getIndex() - start));
}
}
UChar32 scanNamedElementBrackets(UErrorCode &errorCode) {
UBool unusedEscaped;
const UChar32 open = chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if (open == u'{') {
int32_t start = parsePosition_.getIndex();
std::optional<UChar32> hex;
std::optional<UChar32> literal;
while (!chars_.atEnd() && U_SUCCESS(errorCode)) {
UChar32 last = chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if (last == u':') {
if (!hex.has_value()) {
hex.emplace();
for (char16_t digit : std::u16string_view(pattern_).substr(
start, parsePosition_.getIndex() - 1 - start)) {
uint8_t nibble;
if (digit >= u'0' && digit <= u'9') {
nibble = digit - '0';
} else {
digit = digit & ~0x20;
if (digit >= u'A' && digit <= u'F') {
nibble = digit - u'A' + 0xA;
} else {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
}
*hex = (*hex << 4) + nibble;
if (hex > 0x10FFFF) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
}
} else if (!literal.has_value()) {
const auto literalCodePoints = utfStringCodePoints<UChar32, UTF_BEHAVIOR_FFFD>(
std::u16string_view(pattern_).substr(start,
parsePosition_.getIndex() - 1 - start));
auto it = literalCodePoints.begin();
if (it == literalCodePoints.end() || !it->wellFormed() ||
(literal = it->codePoint(), ++it) != literalCodePoints.end()) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
} else {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
start = parsePosition_.getIndex();
} else if (last == u'}') {
const UChar32 result = getCharacterByName(std::u16string_view(pattern_).substr(
start, parsePosition_.getIndex() - 1 - start));
if (result < 0 || (hex.has_value() && result != hex) ||
(literal.has_value() && result != literal)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
return result;
}
}
}
if (U_SUCCESS(errorCode)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
}
return {};
}
LexicalElement evaluateVariable(const UnicodeString &expression, const std::u16string_view source) {
UErrorCode errorCode = U_ZERO_ERROR;
ParsePosition expressionPosition;
RuleCharacterIterator expressionIterator(expression, symbols_, expressionPosition);
// Do not pass the symbols: we do not support recursive expansion of variables.
Lexer expressionLexer(expression, expressionPosition, expressionIterator, unicodeSetOptions_,
/*symbols=*/nullptr, caseClosure_);
auto variableToken = expressionLexer.lookahead();
if (variableToken.isSetOperator(u'[')) {
UnicodeString rebuiltPattern;
UnicodeSet expressionValue;
expressionValue.parseUnicodeSet(expressionLexer, rebuiltPattern, unicodeSetOptions_,
caseClosure_, /*depth=*/0, errorCode);
expressionValue.setPattern(rebuiltPattern);
if (!expressionLexer.atEnd()) {
return LexicalElement(
LexicalElement::VARIABLE, {}, getPos(), U_MALFORMED_VARIABLE_DEFINITION,
/*precomputedSet=*/nullptr,
/*set=*/{},
source);
}
return LexicalElement(
LexicalElement::VARIABLE, {}, getPos(), errorCode,
/*precomputedSet=*/nullptr,
/*set=*/std::move(expressionValue),
source);
} else {
expressionLexer.advance();
if (!expressionLexer.atEnd()) {
return LexicalElement(
LexicalElement::VARIABLE, {}, getPos(), U_MALFORMED_VARIABLE_DEFINITION,
/*precomputedSet=*/nullptr,
/*set=*/{},
source);
}
switch (variableToken.category_) {
case LexicalElement::LITERAL_ELEMENT:
case LexicalElement::ESCAPED_ELEMENT:
case LexicalElement::NAMED_ELEMENT:
case LexicalElement::BRACKETED_ELEMENT:
case LexicalElement::STRING_LITERAL:
case LexicalElement::PROPERTY_QUERY:
// Return the same lexical element that we found while parsing the variable contents,
// except the source position corresponds to the position of the variable rather than 0
// in its expansion, and the source is the name of the variable rather than its
// expansion.
return LexicalElement(
variableToken.category_, std::move(variableToken.string_), getPos(),
variableToken.errorCode_, variableToken.precomputedSet_, std::move(variableToken.set_), source);
default:
return LexicalElement(LexicalElement::VARIABLE, {}, getPos(),
U_MALFORMED_VARIABLE_DEFINITION,
/*precomputedSet=*/nullptr,
/*set=*/{}, source);
}
}
}
UnicodeSet scanPropertyQueryAfterStart(UChar32 first, UChar32 second, int32_t queryStart, UErrorCode &errorCode) {
std::optional<int32_t> queryOperatorPosition;
int32_t queryExpressionStart = parsePosition_.getIndex();
bool exteriorlyNegated = false;
bool interiorlyNegated = false;
UBool unusedEscaped;
// Do not skip whitespace so we can recognize unspaced :]. Lex escapes and
// named-element: while ICU does not support string-valued properties and thus has no
// use for escapes, we still want to lex through escapes to allow downstream
// implementations (mostly unicodetools) to implement string-valued properties.
const UChar32 third = chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if (first == u'\\') {
if (third != u'{') {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
exteriorlyNegated = second == u'P';
queryExpressionStart = parsePosition_.getIndex();
} else {
if (third == u'^') {
exteriorlyNegated = true;
queryExpressionStart = parsePosition_.getIndex();
}
}
RuleCharacterIterator::Pos beforePenultimate = getPos();
UChar32 penultimateUnescaped =
chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
while (!chars_.atEnd() && U_SUCCESS(errorCode)) {
const RuleCharacterIterator::Pos beforeLast = getPos();
UChar32 lastUnescaped =
chars_.next(charsOptions_ & ~(RuleCharacterIterator::PARSE_ESCAPES |
RuleCharacterIterator::SKIP_WHITESPACE),
unusedEscaped, errorCode);
if (penultimateUnescaped == u'\\') {
if (lastUnescaped == 'N') {
scanNamedElementBrackets(errorCode);
if (!U_SUCCESS(errorCode)) {
return {};
}
} else {
// There must be an escaped-element starting at beforePenultimate. Go
// back there and advance through it.
chars_.setPos(beforePenultimate);
chars_.next(charsOptions_ & ~RuleCharacterIterator::SKIP_WHITESPACE, unusedEscaped,
errorCode);
}
// Neither a named-element nor an escaped-element can be part of a closing :].
lastUnescaped = -1;
} else if (!queryOperatorPosition.has_value() && lastUnescaped == u'=') {
queryOperatorPosition = parsePosition_.getIndex() - 1;
} else if (!queryOperatorPosition.has_value() && lastUnescaped == u'≠') {
if (exteriorlyNegated) {
// Reject doubly negated property queries.
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
interiorlyNegated = true;
queryOperatorPosition = parsePosition_.getIndex() - 1;
} else if ((first == u'[' && penultimateUnescaped == u':' && lastUnescaped == u']') ||
(first == u'\\' && lastUnescaped == u'}')) {
// Note that no unescaping is performed here, as ICU does not support string-valued or
// or miscellaneous properties.
const int32_t queryExpressionLimit =
first == u'[' ? parsePosition_.getIndex() - 2 : parsePosition_.getIndex() - 1;
// Contrary to Java, applyPropertyAlias does not support a null property-predicate in
// C++; instead "" indicates the absence of a property-predicate. This is OK with the
// properties supported by ICU, but not with string-valued or miscellaneous properties;
// see https://github.com/unicode-org/icu/pull/3456.
UnicodeString propertyPredicate;
if (queryOperatorPosition.has_value()) {
propertyPredicate =
pattern_.tempSubStringBetween(*queryOperatorPosition + 1, queryExpressionLimit);
if (propertyPredicate.isEmpty()) {
// \p{X=} is valid if X is a string-valued or miscellaneous property, but
// ICU does not support those. Thus, it is invalid for ICU purposes, and
// passing an empty propertyPredicate to applyPropertyAlias can be valid
// (this is how we represent \p{X}), so we need to return the error here.
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
}
UnicodeSet result;
result.applyPropertyAlias(
pattern_.tempSubStringBetween(queryExpressionStart,
queryOperatorPosition.value_or(queryExpressionLimit)),
propertyPredicate, errorCode);
if (exteriorlyNegated != interiorlyNegated) {
result.complement().removeAllStrings();
}
result.setPattern(pattern_.tempSubStringBetween(queryStart, parsePosition_.getIndex()));
return result;
}
beforePenultimate = beforeLast;
penultimateUnescaped = lastUnescaped;
}
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return {};
}
const UnicodeString &pattern_;
const ParsePosition &parsePosition_;
RuleCharacterIterator &chars_;
const uint32_t unicodeSetOptions_;
const int32_t charsOptions_;
const SymbolTable *const symbols_;
UnicodeSet &(UnicodeSet::* const caseClosure_)(int32_t attribute);
std::optional<LexicalElement> ahead_;
std::optional<LexicalElement> ahead2_;
};
namespace {
constexpr int32_t MAX_DEPTH = 100;
#if U_DEBUGGING_UNICODESET_PARSING
#define U_UNICODESET_RETURN_IF_ERROR(ec) \
do { \
constexpr std::string_view functionName = __func__;\
static_assert (functionName.substr(0, 5) == "parse");\
if (U_FAILURE(ec)) { \
if (depth < 5) { \
printf("--- in %s l. %d\n", __func__+5, __LINE__); \
} else if (depth == 5 && std::string_view(__func__+5) == "UnicodeSet") { \
printf("--- [...]\n"); \
} \
return; \
} \
} while (false)
#define U_UNICODESET_RETURN_WITH_PARSE_ERROR(expected, actual, lexer, ec) \
do { \
constexpr std::string_view functionName = __func__; \
static_assert(functionName.substr(0, 5) == "parse"); \
std::string actualUTF8; \
std::string contextUTF8; \
printf("*** Expected %s, got %s %s\n", (expected), \
UnicodeString(actual).toUTF8String(actualUTF8).c_str(), \
lexer.getPositionForDebugging().toUTF8String(contextUTF8).c_str()); \
printf("--- in %s l. %d\n", __func__ + 5, __LINE__); \
if (U_FAILURE(lexer.lookahead().errorCode())) { \
(ec) = lexer.lookahead().errorCode(); \
} else { \
(ec) = U_MALFORMED_SET; \
} \
return; \
} while (false)
#else
#define U_UNICODESET_RETURN_IF_ERROR(ec) \
do { \
if (U_FAILURE(ec)) { \
return; \
} \
} while (false)
#define U_UNICODESET_RETURN_WITH_PARSE_ERROR(expected, actual, lexer, ec) \
do { \
if (U_FAILURE(lexer.lookahead().errorCode())) { \
(ec) = lexer.lookahead().errorCode(); \
} else { \
(ec) = U_MALFORMED_SET; \
} \
return; \
} while (false)
#endif
} // namespace
/**
* Parse the pattern from the given RuleCharacterIterator. The
* iterator is advanced over the parsed pattern.
* @param pattern The pattern, only used by debug traces.
* @param parsePosition The ParsePosition underlying chars, only used by debug traces.
* @param chars iterator over the pattern characters. Upon return
* it will be advanced to the first character after the parsed
* pattern, or the end of the iteration if all characters are
* parsed.
* @param symbols symbol table to use to parse and dereference
* variables, or null if none.
* @param rebuiltPat the pattern that was parsed, rebuilt or
* copied from the input pattern, as appropriate.
* @param options a bit mask of zero or more of the following:
* IGNORE_SPACE, CASE.
*/
void UnicodeSet::applyPattern(const UnicodeString &pattern,
const ParsePosition &parsePosition,
RuleCharacterIterator &chars,
const SymbolTable *symbols,
UnicodeString &rebuiltPat,
uint32_t options,
UnicodeSet &(UnicodeSet::*caseClosure)(int32_t attribute),
UErrorCode &ec) {
if (U_FAILURE(ec)) return;
Lexer lexer(pattern, parsePosition, chars, options, symbols, caseClosure);
parseUnicodeSet(lexer, rebuiltPat, options, caseClosure, /*depth=*/0, ec);
}
void UnicodeSet::parseUnicodeSet(Lexer &lexer,
UnicodeString& rebuiltPat,
uint32_t options,
UnicodeSet& (UnicodeSet::*caseClosure)(int32_t attribute),
int32_t depth,
UErrorCode &ec) {
clear();
if (depth > MAX_DEPTH) {
U_UNICODESET_RETURN_WITH_PARSE_ERROR(("depth <= " + std::to_string(MAX_DEPTH)).c_str(),
("depth = " + std::to_string(depth)).c_str(), lexer, ec);
}
bool isComplement = false;
// Whether to keep the syntax of the pattern at this level, only doing basic pretty-printing, e.g.,