Debian Codegraph @

debian/rust-vendor/icu_properties/src/unicodeset_parse/parse.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use alloc::borrow::Cow;
6 use alloc::collections::{BTreeMap, BTreeSet};
7 use alloc::format;
8 use alloc::string::{String, ToString};
9 use alloc::vec::Vec;
10 use core::fmt::Display;
11 use core::{iter::Peekable, str::CharIndices};
12
13 use crate::props::IndicConjunctBreak;
14 use crate::script::ScriptWithExtensions;
15 use crate::{
16 CodePointMapData,
17 props::{
18 CanonicalCombiningClass, EastAsianWidth, EnumeratedProperty, GeneralCategory,
19 GeneralCategoryGroup, GraphemeClusterBreak, LineBreak, Script, SentenceBreak, WordBreak,
20 },
21 };
22 use crate::{
23 CodePointSetData,
24 props::{PatternWhiteSpace, XidContinue, XidStart},
25 };
26 use crate::{PropertyParser, provider::*};
27 use icu_collections::{
28 codepointinvlist::{CodePointInversionList, CodePointInversionListBuilder},
29 codepointinvliststringlist::CodePointInversionListAndStringList,
30 };
31 use icu_provider::prelude::*;
32
33 /// The kind of error that occurred.
34 #[derive(Debug, Clone, Copy, PartialEq, Eq, displaydoc::Display)]
35 #[non_exhaustive]
36 pub enum ParseErrorKind {
37 /// An unexpected character was encountered.
38 ///
39 /// This variant implies the other variants
40 /// (notably `UnknownProperty` and `Unimplemented`) do not apply.
41 #[displaydoc("An unexpected character was encountered")]
42 UnexpectedChar(char),
43 /// The property name or value is unknown.
44 ///
45 /// For property names, make sure you use the spelling
46 /// defined in [ECMA-262](https://tc39.es/ecma262/#table-nonbinary-unicode-properties).
47 #[displaydoc("The property name or value is unknown")]
48 UnknownProperty,
49 /// A reference to an unknown variable.
50 UnknownVariable,
51 /// A variable of a certain type occurring in an unexpected context.
52 UnexpectedVariable,
53 /// The source is an incomplete unicode set.
54 Eof,
55 /// Something unexpected went wrong with our code. Please file a bug report on GitHub.
56 Internal,
57 /// The provided syntax is not supported by us.
58 ///
59 /// Note that unknown properties will return the
60 /// `UnknownProperty` variant, not this one.
61 #[displaydoc("The provided syntax is not supported by us.")]
62 Unimplemented,
63 /// The provided escape sequence is not a valid Unicode code point or represents too many code points.
64 InvalidEscape,
65 }
66 use ParseErrorKind as PEK;
67 use zerovec::VarZeroVec;
68
69 impl ParseErrorKind {
70 fn with_offset(self, offset: usize) -> ParseError {
71 ParseError {
72 offset: Some(offset),
73 kind: self,
74 }
75 }
76 }
77
78 impl From<ParseErrorKind> for ParseError {
79 fn from(kind: ParseErrorKind) -> Self {
80 ParseError { offset: None, kind }
81 }
82 }
83
84 /// The error type returned by the `parse` functions in this crate.
85 ///
86 /// See [`ParseError::fmt_with_source`] for pretty-printing and [`ParseErrorKind`] of the
87 /// different types of errors represented by this struct.
88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
89 pub struct ParseError {
90 // offset is the index to an arbitrary byte in the last character in the source that makes sense
91 // to display as location for the error, e.g., the unexpected character itself or
92 // for an unknown property name the last character of the name.
93 offset: Option<usize>,
94 kind: ParseErrorKind,
95 }
96
97 type Result<T, E = ParseError> = core::result::Result<T, E>;
98
99 impl ParseError {
100 /// Pretty-prints this error and if applicable, shows where the error occurred in the source.
101 ///
102 /// Must be called with the same source that was used to parse the set.
103 ///
104 /// # Examples
105 ///
106 /// ```
107 /// use icu::properties::unicodeset_parse::*;
108 ///
109 /// let source = "[[abc]-x]";
110 /// let set = parse(source);
111 /// assert!(set.is_err());
112 /// let err = set.unwrap_err();
113 /// assert_eq!(
114 /// err.fmt_with_source(source).to_string(),
115 /// "[[abc]-x← error: unexpected character 'x'"
116 /// );
117 /// ```
118 ///
119 /// ```
120 /// use icu::properties::unicodeset_parse::*;
121 ///
122 /// let source = r"[\N{LATIN CAPITAL LETTER A}]";
123 /// let set = parse(source);
124 /// assert!(set.is_err());
125 /// let err = set.unwrap_err();
126 /// assert_eq!(
127 /// err.fmt_with_source(source).to_string(),
128 /// r"[\N← error: unimplemented"
129 /// );
130 /// ```
131 pub fn fmt_with_source(&self, source: &str) -> impl Display + use<> {
132 let ParseError { offset, kind } = *self;
133
134 if kind == ParseErrorKind::Eof {
135 return format!("{source}← error: unexpected end of input");
136 }
137 let mut s = String::new();
138 if let Some(offset) = offset
139 && offset < source.len()
140 {
141 // offset points to any byte of the last character we want to display.
142 // in the case of ASCII, this is easy - we just display bytes [..=offset].
143 // however, if the last character is more than one byte in UTF-8
144 // we cannot use ..=offset, because that would potentially include only partial
145 // bytes of last character in our string. hence we must find the start of the
146 // following character and use that as the (exclusive) end of our string.
147
148 // offset points into the last character we want to include, hence the start of the
149 // first character we want to exclude is at least offset + 1.
150 let mut exclusive_end = offset + 1;
151 // TODO: replace this loop with str::ceil_char_boundary once stable
152 for _ in 0..3 {
153 // is_char_boundary returns true at the latest once exclusive_end == source.len()
154 if source.is_char_boundary(exclusive_end) {
155 break;
156 }
157 exclusive_end += 1;
158 }
159
160 // exclusive_end is at most source.len() due to str::is_char_boundary and at least 0 by type
161 s.push_str(&source[..exclusive_end]);
162 s.push_str("← ");
163 }
164 s.push_str("error: ");
165 match kind {
166 ParseErrorKind::UnexpectedChar(c) => {
167 s.push_str(&format!("unexpected character '{}'", c.escape_debug()));
168 }
169 ParseErrorKind::UnknownProperty => {
170 s.push_str("unknown property");
171 }
172 ParseErrorKind::UnknownVariable => {
173 s.push_str("unknown variable");
174 }
175 ParseErrorKind::UnexpectedVariable => {
176 s.push_str("unexpected variable");
177 }
178 ParseErrorKind::Eof => {
179 s.push_str("unexpected end of input");
180 }
181 ParseErrorKind::Internal => {
182 s.push_str("internal error");
183 }
184 ParseErrorKind::Unimplemented => {
185 s.push_str("unimplemented");
186 }
187 ParseErrorKind::InvalidEscape => {
188 s.push_str("invalid escape sequence");
189 }
190 }
191
192 s
193 }
194
195 /// Returns the [`ParseErrorKind`] of this error.
196 pub fn kind(&self) -> ParseErrorKind {
197 self.kind
198 }
199
200 /// Returns the offset of this error in the source string, if it was specified.
201 pub fn offset(&self) -> Option<usize> {
202 self.offset
203 }
204
205 fn or_with_offset(self, offset: usize) -> Self {
206 match self.offset {
207 Some(_) => self,
208 None => ParseError {
209 offset: Some(offset),
210 ..self
211 },
212 }
213 }
214 }
215
216 /// The value of a variable in a `UnicodeSet`. Used as value type in [`VariableMap`].
217 #[derive(Debug, Clone)]
218 #[non_exhaustive]
219 pub enum VariableValue<'a> {
220 /// A `UnicodeSet`, represented as a [`CodePointInversionListAndStringList`](CodePointInversionListAndStringList).
221 UnicodeSet(CodePointInversionListAndStringList<'a>),
222 // in theory, a one-code-point string is always the same as a char, but we might want to keep
223 // this variant for efficiency?
224 /// A single code point.
225 Char(char),
226 /// A string. It is guaranteed that when returned from a `VariableMap`, this variant contains never exactly one code point.
227 String(Cow<'a, str>),
228 }
229
230 /// The map used for parsing `UnicodeSets` with variable support. See [`parse_with_variables`].
231 #[derive(Debug, Clone, Default)]
232 pub struct VariableMap<'a>(BTreeMap<String, VariableValue<'a>>);
233
234 impl<'a> VariableMap<'a> {
235 /// Creates a new empty map.
236 pub fn new() -> Self {
237 Self::default()
238 }
239
240 /// Removes a key from the map, returning the value at the key if the key
241 /// was previously in the map.
242 pub fn remove(&mut self, key: &str) -> Option<VariableValue<'a>> {
243 self.0.remove(key)
244 }
245
246 /// Get a reference to the value associated with this key, if it exists.
247 pub fn get(&self, key: &str) -> Option<&VariableValue<'a>> {
248 self.0.get(key)
249 }
250
251 /// Insert a `VariableValue` into the `VariableMap`.
252 ///
253 /// Returns `Err` with the old value, if it exists, and does not update the map.
254 pub fn insert(
255 &mut self,
256 key: String,
257 value: VariableValue<'a>,
258 ) -> Result<(), &VariableValue<'_>> {
259 // borrow-checker shenanigans, otherwise we could use if let
260 if self.0.contains_key(&key) {
261 // we just checked that this key exists
262 #[expect(clippy::indexing_slicing)]
263 return Err(&self.0[&key]);
264 }
265
266 if let VariableValue::String(s) = &value {
267 let mut chars = s.chars();
268 if let (Some(c), None) = (chars.next(), chars.next()) {
269 self.0.insert(key, VariableValue::Char(c));
270 return Ok(());
271 };
272 }
273
274 self.0.insert(key, value);
275 Ok(())
276 }
277
278 /// Insert a `char` into the `VariableMap`.
279 ///
280 /// Returns `Err` with the old value, if it exists, and does not update the map.
281 pub fn insert_char(&mut self, key: String, c: char) -> Result<(), &VariableValue<'_>> {
282 // borrow-checker shenanigans, otherwise we could use if let
283 if self.0.contains_key(&key) {
284 // we just checked that this key exists
285 #[expect(clippy::indexing_slicing)]
286 return Err(&self.0[&key]);
287 }
288
289 self.0.insert(key, VariableValue::Char(c));
290 Ok(())
291 }
292
293 /// Insert a `String` of any length into the `VariableMap`.
294 ///
295 /// Returns `Err` with the old value, if it exists, and does not update the map.
296 pub fn insert_string(&mut self, key: String, s: String) -> Result<(), &VariableValue<'_>> {
297 // borrow-checker shenanigans, otherwise we could use if let
298 if self.0.contains_key(&key) {
299 // we just checked that this key exists
300 #[expect(clippy::indexing_slicing)]
301 return Err(&self.0[&key]);
302 }
303
304 let mut chars = s.chars();
305 let val = match (chars.next(), chars.next()) {
306 (Some(c), None) => VariableValue::Char(c),
307 _ => VariableValue::String(Cow::Owned(s)),
308 };
309
310 self.0.insert(key, val);
311 Ok(())
312 }
313
314 /// Insert a `&str` of any length into the `VariableMap`.
315 ///
316 /// Returns `Err` with the old value, if it exists, and does not update the map.
317 pub fn insert_str(&mut self, key: String, s: &'a str) -> Result<(), &VariableValue<'_>> {
318 // borrow-checker shenanigans, otherwise we could use if let
319 if self.0.contains_key(&key) {
320 // we just checked that this key exists
321 #[expect(clippy::indexing_slicing)]
322 return Err(&self.0[&key]);
323 }
324
325 let mut chars = s.chars();
326 let val = match (chars.next(), chars.next()) {
327 (Some(c), None) => VariableValue::Char(c),
328 _ => VariableValue::String(Cow::Borrowed(s)),
329 };
330
331 self.0.insert(key, val);
332 Ok(())
333 }
334
335 /// Insert a [`CodePointInversionListAndStringList`](CodePointInversionListAndStringList) into the `VariableMap`.
336 ///
337 /// Returns `Err` with the old value, if it exists, and does not update the map.
338 pub fn insert_set(
339 &mut self,
340 key: String,
341 set: CodePointInversionListAndStringList<'a>,
342 ) -> Result<(), &VariableValue<'_>> {
343 // borrow-checker shenanigans, otherwise we could use if let
344 if self.0.contains_key(&key) {
345 // we just checked that this key exists
346 #[expect(clippy::indexing_slicing)]
347 return Err(&self.0[&key]);
348 }
349 self.0.insert(key, VariableValue::UnicodeSet(set));
350 Ok(())
351 }
352 }
353
354 // this ignores the ambiguity between \-escapes and \p{} perl properties. it assumes it is in a context where \p is just 'p'
355 // returns whether the provided char signifies the start of a literal char (raw or escaped - so \ is a legal char start)
356 // important: assumes c is not pattern_white_space
357 fn legal_char_start(c: char) -> bool {
358 !(c == '&' || c == '-' || c == '$' || c == '^' || c == '[' || c == ']' || c == '{')
359 }
360
361 // same as `legal_char_start` but adapted to the charInString nonterminal. \ is allowed due to escapes.
362 // important: assumes c is not pattern_white_space
363 fn legal_char_in_string_start(c: char) -> bool {
364 c != '}'
365 }
366
367 #[derive(Debug)]
368 enum SingleOrMultiChar {
369 Single(char),
370 // Multi is a marker that indicates parsing was paused and needs to be resumed using parse_multi_escape* when
371 // this token is consumed. The contained char is the first char of the multi sequence.
372 Multi(char),
373 }
374
375 // A char or a string. The Vec<char> represents multi-escapes in the 2+ case.
376 // invariant: a String is either zero or 2+ chars long, a one-char-string is equivalent to a single char.
377 // invariant: a char is 1+ chars long
378 #[derive(Debug)]
379 enum Literal {
380 String(String),
381 CharKind(SingleOrMultiChar),
382 }
383
384 #[derive(Debug)]
385 enum MainToken<'data> {
386 // to be interpreted as value
387 Literal(Literal),
388 // inner set
389 UnicodeSet(CodePointInversionListAndStringList<'data>),
390 // anchor, only at the end of a set ([... $])
391 DollarSign,
392 // intersection operator, only inbetween two sets ([[...] & [...]])
393 Ampersand,
394 // difference operator, only inbetween two sets ([[...] - [...]])
395 // or
396 // range operator, only inbetween two chars ([a-z], [a-{z}])
397 Minus,
398 // ] to indicate the end of a set
399 ClosingBracket,
400 }
401
402 impl<'data> MainToken<'data> {
403 fn from_variable_value(val: VariableValue<'data>) -> Self {
404 match val {
405 VariableValue::Char(c) => {
406 MainToken::Literal(Literal::CharKind(SingleOrMultiChar::Single(c)))
407 }
408 VariableValue::String(s) => {
409 // we know that the VariableMap only contains non-length-1 Strings.
410 MainToken::Literal(Literal::String(s.into_owned()))
411 }
412 VariableValue::UnicodeSet(set) => MainToken::UnicodeSet(set),
413 }
414 }
415 }
416
417 #[derive(Debug, Clone, Copy)]
418 enum Operation {
419 Union,
420 Difference,
421 Intersection,
422 }
423
424 // this builds the set on-the-fly while parsing it
425 struct UnicodeSetBuilder<'a, 'b, P: ?Sized> {
426 single_set: CodePointInversionListBuilder,
427 string_set: BTreeSet<String>,
428 iter: &'a mut Peekable<CharIndices<'b>>,
429 source: &'b str,
430 inverted: bool,
431 variable_map: &'a VariableMap<'a>,
432 xid_start: &'a CodePointInversionList<'a>,
433 xid_continue: &'a CodePointInversionList<'a>,
434 pat_ws: &'a CodePointInversionList<'a>,
435 property_provider: &'a P,
436 }
437
438 impl<'a, 'b, P> UnicodeSetBuilder<'a, 'b, P>
439 where
440 P: ?Sized
441 + DataProvider<PropertyBinaryAlphabeticV1>
442 + DataProvider<PropertyBinaryAsciiHexDigitV1>
443 + DataProvider<PropertyBinaryBidiControlV1>
444 + DataProvider<PropertyBinaryBidiMirroredV1>
445 + DataProvider<PropertyBinaryCasedV1>
446 + DataProvider<PropertyBinaryCaseIgnorableV1>
447 + DataProvider<PropertyBinaryChangesWhenCasefoldedV1>
448 + DataProvider<PropertyBinaryChangesWhenCasemappedV1>
449 + DataProvider<PropertyBinaryChangesWhenLowercasedV1>
450 + DataProvider<PropertyBinaryChangesWhenNfkcCasefoldedV1>
451 + DataProvider<PropertyBinaryChangesWhenTitlecasedV1>
452 + DataProvider<PropertyBinaryChangesWhenUppercasedV1>
453 + DataProvider<PropertyBinaryDashV1>
454 + DataProvider<PropertyBinaryDefaultIgnorableCodePointV1>
455 + DataProvider<PropertyBinaryDeprecatedV1>
456 + DataProvider<PropertyBinaryDiacriticV1>
457 + DataProvider<PropertyBinaryEmojiComponentV1>
458 + DataProvider<PropertyBinaryEmojiModifierBaseV1>
459 + DataProvider<PropertyBinaryEmojiModifierV1>
460 + DataProvider<PropertyBinaryEmojiPresentationV1>
461 + DataProvider<PropertyBinaryEmojiV1>
462 + DataProvider<PropertyBinaryExtendedPictographicV1>
463 + DataProvider<PropertyBinaryExtenderV1>
464 + DataProvider<PropertyBinaryGraphemeBaseV1>
465 + DataProvider<PropertyBinaryGraphemeExtendV1>
466 + DataProvider<PropertyBinaryHexDigitV1>
467 + DataProvider<PropertyBinaryIdContinueV1>
468 + DataProvider<PropertyBinaryIdeographicV1>
469 + DataProvider<PropertyBinaryIdsBinaryOperatorV1>
470 + DataProvider<PropertyBinaryIdStartV1>
471 + DataProvider<PropertyBinaryIdsTrinaryOperatorV1>
472 + DataProvider<PropertyBinaryJoinControlV1>
473 + DataProvider<PropertyBinaryLogicalOrderExceptionV1>
474 + DataProvider<PropertyBinaryLowercaseV1>
475 + DataProvider<PropertyBinaryMathV1>
476 + DataProvider<PropertyBinaryNoncharacterCodePointV1>
477 + DataProvider<PropertyBinaryPatternSyntaxV1>
478 + DataProvider<PropertyBinaryPatternWhiteSpaceV1>
479 + DataProvider<PropertyBinaryQuotationMarkV1>
480 + DataProvider<PropertyBinaryRadicalV1>
481 + DataProvider<PropertyBinaryRegionalIndicatorV1>
482 + DataProvider<PropertyBinarySentenceTerminalV1>
483 + DataProvider<PropertyBinarySoftDottedV1>
484 + DataProvider<PropertyBinaryTerminalPunctuationV1>
485 + DataProvider<PropertyBinaryUnifiedIdeographV1>
486 + DataProvider<PropertyBinaryUppercaseV1>
487 + DataProvider<PropertyBinaryVariationSelectorV1>
488 + DataProvider<PropertyBinaryWhiteSpaceV1>
489 + DataProvider<PropertyBinaryXidContinueV1>
490 + DataProvider<PropertyBinaryXidStartV1>
491 + DataProvider<PropertyEnumCanonicalCombiningClassV1>
492 + DataProvider<PropertyEnumEastAsianWidthV1>
493 + DataProvider<PropertyEnumGeneralCategoryV1>
494 + DataProvider<PropertyEnumGraphemeClusterBreakV1>
495 + DataProvider<PropertyEnumIndicConjunctBreakV1>
496 + DataProvider<PropertyEnumLineBreakV1>
497 + DataProvider<PropertyEnumScriptV1>
498 + DataProvider<PropertyEnumSentenceBreakV1>
499 + DataProvider<PropertyEnumWordBreakV1>
500 + DataProvider<PropertyNameParseCanonicalCombiningClassV1>
501 + DataProvider<PropertyNameParseEastAsianWidthV1>
502 + DataProvider<PropertyNameParseGeneralCategoryMaskV1>
503 + DataProvider<PropertyNameParseGraphemeClusterBreakV1>
504 + DataProvider<PropertyNameParseIndicConjunctBreakV1>
505 + DataProvider<PropertyNameParseLineBreakV1>
506 + DataProvider<PropertyNameParseScriptV1>
507 + DataProvider<PropertyNameParseSentenceBreakV1>
508 + DataProvider<PropertyNameParseWordBreakV1>
509 + DataProvider<PropertyScriptWithExtensionsV1>,
510 {
511 fn new_internal(
512 iter: &'a mut Peekable<CharIndices<'b>>,
513 source: &'b str,
514 variable_map: &'a VariableMap<'a>,
515 xid_start: &'a CodePointInversionList<'a>,
516 xid_continue: &'a CodePointInversionList<'a>,
517 pat_ws: &'a CodePointInversionList<'a>,
518 provider: &'a P,
519 ) -> Self {
520 UnicodeSetBuilder {
521 single_set: CodePointInversionListBuilder::new(),
522 string_set: Default::default(),
523 iter,
524 source,
525 inverted: false,
526 variable_map,
527 xid_start,
528 xid_continue,
529 pat_ws,
530 property_provider: provider,
531 }
532 }
533
534 // the entry point, parses a full UnicodeSet. ignores remaining input
535 fn parse_unicode_set(&mut self) -> Result<()> {
536 match self.must_peek_char()? {
537 '\\' => self.parse_property_perl(),
538 '[' => {
539 self.iter.next();
540 if let Some(':') = self.peek_char() {
541 self.parse_property_posix()
542 } else {
543 self.parse_unicode_set_inner()
544 }
545 }
546 '$' => {
547 // must be variable ref to a UnicodeSet
548 let (offset, v) = self.parse_variable()?;
549 match v {
550 Some(VariableValue::UnicodeSet(s)) => {
551 self.single_set.add_set(s.code_points());
552 self.string_set
553 .extend(s.strings().iter().map(ToString::to_string));
554 Ok(())
555 }
556 Some(_) => Err(PEK::UnexpectedVariable.with_offset(offset)),
557 None => Err(PEK::UnexpectedChar('$').with_offset(offset)),
558 }
559 }
560 c => self.error_here(PEK::UnexpectedChar(c)),
561 }
562 }
563
564 // beginning [ is already consumed
565 fn parse_unicode_set_inner(&mut self) -> Result<()> {
566 // special cases for the first chars after [
567 if self.must_peek_char()? == '^' {
568 self.iter.next();
569 self.inverted = true;
570 }
571 // whitespace allowed between ^ and - in `[^ - ....]`
572 self.skip_whitespace();
573 if self.must_peek_char()? == '-' {
574 self.iter.next();
575 self.single_set.add_char('-');
576 }
577
578 // repeatedly parse the following:
579 // char
580 // char-char
581 // {string}
582 // unicodeset
583 // & and - operators, but only between unicodesets
584 // $variables in place of strings, chars, or unicodesets
585
586 #[derive(Debug, Clone, Copy)]
587 enum State {
588 // a state equivalent to the beginning
589 Begin,
590 // a state after a char. implies `prev_char` is Some(_), because we need to buffer it
591 // in case it is part of a range, e.g., a-z
592 Char,
593 // in the middle of parsing a range. implies `prev_char` is Some(_), and the next
594 // element must be a char as well
595 CharMinus,
596 // state directly after parsing a recursive unicode set. operators are only allowed
597 // in this state
598 AfterUnicodeSet,
599 // state directly after parsing an operator. forces the next element to be a recursive
600 // unicode set
601 AfterOp,
602 // state after parsing a $ (that was not a variable reference)
603 // the only valid next option is a closing bracket
604 AfterDollar,
605 // state after parsing a - in an otherwise invalid position
606 // the only valid next option is a closing bracket
607 AfterMinus,
608 }
609 use State::*;
610
611 const DEFAULT_OP: Operation = Operation::Union;
612
613 let mut state = Begin;
614 let mut prev_char = None;
615 let mut operation = Operation::Union;
616
617 loop {
618 self.skip_whitespace();
619
620 // for error messages
621 let (immediate_offset, immediate_char) = self.must_peek()?;
622
623 let (tok_offset, from_var, tok) = self.parse_main_token()?;
624 // warning: self.iter should not be advanced any more after this point on any path to
625 // MT::Literal(Literal::CharKind(SingleOrMultiChar::Multi)), because that variant
626 // expects a certain self.iter state
627
628 use MainToken as MT;
629 use SingleOrMultiChar as SMC;
630 match (state, tok) {
631 // the end of this unicode set
632 (
633 Begin | Char | CharMinus | AfterUnicodeSet | AfterDollar | AfterMinus,
634 MT::ClosingBracket,
635 ) => {
636 if let Some(prev) = prev_char.take() {
637 self.single_set.add_char(prev);
638 }
639 if matches!(state, CharMinus) {
640 self.single_set.add_char('-');
641 }
642
643 return Ok(());
644 }
645 // special case ends for -
646 // [[a-z]-]
647 (AfterOp, MT::ClosingBracket) if matches!(operation, Operation::Difference) => {
648 self.single_set.add_char('-');
649 return Ok(());
650 }
651 (Begin, MT::Minus) => {
652 self.single_set.add_char('-');
653 state = AfterMinus;
654 }
655 // inner unicode set
656 (Begin | Char | AfterUnicodeSet | AfterOp, MT::UnicodeSet(set)) => {
657 if let Some(prev) = prev_char.take() {
658 self.single_set.add_char(prev);
659 }
660
661 self.process_chars(operation, set.code_points().clone());
662 self.process_strings(
663 operation,
664 set.strings().iter().map(ToString::to_string).collect(),
665 );
666
667 operation = DEFAULT_OP;
668 state = AfterUnicodeSet;
669 }
670 // a literal char (either individually or as the start of a range if char)
671 (
672 Begin | Char | AfterUnicodeSet,
673 MT::Literal(Literal::CharKind(SMC::Single(c))),
674 ) => {
675 if let Some(prev) = prev_char.take() {
676 self.single_set.add_char(prev);
677 }
678 prev_char = Some(c);
679 state = Char;
680 }
681 // a bunch of literal chars as part of a multi-escape sequence
682 (
683 Begin | Char | AfterUnicodeSet,
684 MT::Literal(Literal::CharKind(SMC::Multi(first_c))),
685 ) => {
686 if let Some(prev) = prev_char.take() {
687 self.single_set.add_char(prev);
688 }
689 self.single_set.add_char(first_c);
690 self.parse_multi_escape_into_set()?;
691
692 // Note we cannot go to the Char state, because a multi-escape sequence of
693 // length > 1 cannot initiate a range
694 state = Begin;
695 }
696 // a literal string (length != 1, by CharOrString invariant)
697 (Begin | Char | AfterUnicodeSet, MT::Literal(Literal::String(s))) => {
698 if let Some(prev) = prev_char.take() {
699 self.single_set.add_char(prev);
700 }
701
702 self.string_set.insert(s);
703 state = Begin;
704 }
705 // parse a literal char as the end of a range
706 (CharMinus, MT::Literal(Literal::CharKind(SMC::Single(c)))) => {
707 let start = prev_char.ok_or(ParseError {
708 offset: Some(tok_offset),
709 kind: PEK::Internal,
710 })?;
711 let end = c;
712 if start > end {
713 // TODO(#3558): Better error message (e.g., "start greater than end in range")?
714 return Err(PEK::UnexpectedChar(end).with_offset(tok_offset));
715 }
716
717 self.single_set.add_range(start..=end);
718 prev_char = None;
719 state = Begin;
720 }
721 // start parsing a char range
722 (Char, MT::Minus) => {
723 state = CharMinus;
724 }
725 // start parsing a unicode set difference
726 (AfterUnicodeSet, MT::Minus) => {
727 operation = Operation::Difference;
728 state = AfterOp;
729 }
730 // start parsing a unicode set difference
731 (AfterUnicodeSet, MT::Ampersand) => {
732 operation = Operation::Intersection;
733 state = AfterOp;
734 }
735 (Begin | Char | AfterUnicodeSet, MT::DollarSign) => {
736 if let Some(prev) = prev_char.take() {
737 self.single_set.add_char(prev);
738 }
739 self.single_set.add_char('\u{FFFF}');
740 state = AfterDollar;
741 }
742 _ => {
743 // TODO(#3558): We have precise knowledge about the following MainToken here,
744 // should we make use of that?
745
746 if from_var {
747 // otherwise we get error messages such as
748 // [$a-$← error: unexpected character '$'
749 // for input [$a-$b], $a = 'a', $b = "string" ;
750 return Err(PEK::UnexpectedVariable.with_offset(tok_offset));
751 }
752 return Err(PEK::UnexpectedChar(immediate_char).with_offset(immediate_offset));
753 }
754 }
755 }
756 }
757
758 fn parse_main_token(&mut self) -> Result<(usize, bool, MainToken<'a>)> {
759 let (initial_offset, first) = self.must_peek()?;
760 if first == ']' {
761 self.iter.next();
762 return Ok((initial_offset, false, MainToken::ClosingBracket));
763 }
764 let (_, second) = self.must_peek_double()?;
765 match (first, second) {
766 // variable or anchor
767 ('$', _) => {
768 let (offset, var_or_anchor) = self.parse_variable()?;
769 match var_or_anchor {
770 None => Ok((offset, false, MainToken::DollarSign)),
771 Some(v) => Ok((offset, true, MainToken::from_variable_value(v.clone()))),
772 }
773 }
774 // string
775 ('{', _) => self
776 .parse_string()
777 .map(|(offset, l)| (offset, false, MainToken::Literal(l))),
778 // inner set
779 ('\\', 'p' | 'P') | ('[', _) => {
780 let mut inner_builder = UnicodeSetBuilder::new_internal(
781 self.iter,
782 self.source,
783 self.variable_map,
784 self.xid_start,
785 self.xid_continue,
786 self.pat_ws,
787 self.property_provider,
788 );
789 inner_builder.parse_unicode_set()?;
790 let (single, string_set) = inner_builder.finalize();
791 // note: offset - 1, because we already consumed full set
792 let offset = self.must_peek_index()? - 1;
793 let mut strings = string_set.into_iter().collect::<Vec<_>>();
794 strings.sort();
795 let cpilasl = CodePointInversionListAndStringList::try_from(
796 single.build(),
797 VarZeroVec::from(&strings),
798 )
799 .map_err(|_| PEK::Internal.with_offset(offset))?;
800 Ok((offset, false, MainToken::UnicodeSet(cpilasl)))
801 }
802 // note: c cannot be a whitespace, because we called skip_whitespace just before
803 // (in the main parse loop), so it's safe to call this guard function
804 (c, _) if legal_char_start(c) => self
805 .parse_char()
806 .map(|(offset, c)| (offset, false, MainToken::Literal(Literal::CharKind(c)))),
807 ('-', _) => {
808 self.iter.next();
809 Ok((initial_offset, false, MainToken::Minus))
810 }
811 ('&', _) => {
812 self.iter.next();
813 Ok((initial_offset, false, MainToken::Ampersand))
814 }
815 (c, _) => Err(PEK::UnexpectedChar(c).with_offset(initial_offset)),
816 }
817 }
818
819 // parses a variable or an anchor. expects '$' as next token.
820 // if this is a single $ (eg `[... $ ]` or the invalid `$ a`), then this function returns Ok(None),
821 // otherwise Ok(Some(variable_value)).
822 fn parse_variable(&mut self) -> Result<(usize, Option<&'a VariableValue<'a>>)> {
823 self.consume('$')?;
824
825 let mut res = String::new();
826 let (mut var_offset, first_c) = self.must_peek()?;
827
828 if !self.xid_start.contains(first_c) {
829 // -1 because we already consumed the '$'
830 return Ok((var_offset - 1, None));
831 }
832
833 res.push(first_c);
834 self.iter.next();
835 // important: if we are parsing a root unicodeset as a variable, we might reach EOF as
836 // a valid end of the variable name, so we cannot use must_peek here.
837 while let Some(&(offset, c)) = self.iter.peek() {
838 if !self.xid_continue.contains(c) {
839 break;
840 }
841 // only update the offset if we're adding a new char to our variable
842 var_offset = offset;
843 self.iter.next();
844 res.push(c);
845 }
846
847 if let Some(v) = self.variable_map.0.get(&res) {
848 return Ok((var_offset, Some(v)));
849 }
850
851 Err(PEK::UnknownVariable.with_offset(var_offset))
852 }
853
854 // parses and consumes: '{' (s charInString)* s '}'
855 fn parse_string(&mut self) -> Result<(usize, Literal)> {
856 self.consume('{')?;
857
858 let mut buffer = String::new();
859 let mut last_offset;
860
861 loop {
862 self.skip_whitespace();
863 last_offset = self.must_peek_index()?;
864 match self.must_peek_char()? {
865 '}' => {
866 self.iter.next();
867 break;
868 }
869 // note: c cannot be a whitespace, because we called skip_whitespace just before,
870 // so it's safe to call this guard function
871 c if legal_char_in_string_start(c) => {
872 // don't need the offset, because '}' will always be the last char
873 let (_, c) = self.parse_char()?;
874 match c {
875 SingleOrMultiChar::Single(c) => buffer.push(c),
876 SingleOrMultiChar::Multi(first) => {
877 buffer.push(first);
878 self.parse_multi_escape_into_string(&mut buffer)?;
879 }
880 }
881 }
882 c => return self.error_here(PEK::UnexpectedChar(c)),
883 }
884 }
885
886 let mut chars = buffer.chars();
887 let literal = match (chars.next(), chars.next()) {
888 (Some(c), None) => Literal::CharKind(SingleOrMultiChar::Single(c)),
889 _ => Literal::String(buffer),
890 };
891 Ok((last_offset, literal))
892 }
893
894 // finishes a partial multi escape parse. in case of a parse error, self.single_set
895 // may be left in an inconsistent state
896 fn parse_multi_escape_into_set(&mut self) -> Result<()> {
897 // note: would be good to somehow merge the two multi_escape methods. splitting up the UnicodeSetBuilder into a more
898 // conventional parser + lexer combo might allow this.
899 // issue is that we cannot pass this method an argument that somehow mutates `self` in the current architecture.
900 // self.lexer.parse_multi_into_charappendable(&mut self.single_set) should work because the lifetimes are separate
901
902 // whitespace before first char of this loop (ie, second char in this multi_escape) must be
903 // enforced when creating the SingleOrMultiChar::Multi.
904 let mut first = true;
905 loop {
906 let skipped = self.skip_whitespace();
907 match self.must_peek_char()? {
908 '}' => {
909 self.iter.next();
910 return Ok(());
911 }
912 initial_c => {
913 if skipped == 0 && !first {
914 // bracketed hex code points must be separated by whitespace
915 return self.error_here(PEK::UnexpectedChar(initial_c));
916 }
917 first = false;
918
919 let (_, c) = self.parse_hex_digits_into_char(1, 6)?;
920 self.single_set.add_char(c);
921 }
922 }
923 }
924 }
925
926 // finishes a partial multi escape parse. in case of a parse error, the caller must clean up the
927 // string if necessary.
928 fn parse_multi_escape_into_string(&mut self, s: &mut String) -> Result<()> {
929 // whitespace before first char of this loop (ie, second char in this multi_escape) must be
930 // enforced when creating the SingleOrMultiChar::Multi.
931 let mut first = true;
932 loop {
933 let skipped = self.skip_whitespace();
934 match self.must_peek_char()? {
935 '}' => {
936 self.iter.next();
937 return Ok(());
938 }
939 initial_c => {
940 if skipped == 0 && !first {
941 // bracketed hex code points must be separated by whitespace
942 return self.error_here(PEK::UnexpectedChar(initial_c));
943 }
944 first = false;
945
946 let (_, c) = self.parse_hex_digits_into_char(1, 6)?;
947 s.push(c);
948 }
949 }
950 }
951 }
952
953 // starts with \ and consumes the whole escape sequence if a single
954 // char is escaped, otherwise pauses the parse after the first char
955 fn parse_escaped_char(&mut self) -> Result<(usize, SingleOrMultiChar)> {
956 self.consume('\\')?;
957
958 let (offset, next_char) = self.must_next()?;
959
960 match next_char {
961 'u' | 'x' if self.peek_char() == Some('{') => {
962 // bracketedHex
963 self.iter.next();
964
965 self.skip_whitespace();
966 let (_, first_c) = self.parse_hex_digits_into_char(1, 6)?;
967 let skipped = self.skip_whitespace();
968
969 match self.must_peek()? {
970 (offset, '}') => {
971 self.iter.next();
972 Ok((offset, SingleOrMultiChar::Single(first_c)))
973 }
974 // note: enforcing whitespace after the first char here, because the parse_multi_escape functions
975 // won't have access to this information anymore
976 (offset, c) if c.is_ascii_hexdigit() && skipped > 0 => {
977 Ok((offset, SingleOrMultiChar::Multi(first_c)))
978 }
979 (_, c) => self.error_here(PEK::UnexpectedChar(c)),
980 }
981 }
982 'u' => {
983 // 'u' hex{4}
984 self.parse_hex_digits_into_char(4, 4)
985 .map(|(offset, c)| (offset, SingleOrMultiChar::Single(c)))
986 }
987 'x' => {
988 // 'x' hex{2}
989 self.parse_hex_digits_into_char(2, 2)
990 .map(|(offset, c)| (offset, SingleOrMultiChar::Single(c)))
991 }
992 'U' => {
993 // 'U00' ('0' hex{5} | '10' hex{4})
994 self.consume('0')?;
995 self.consume('0')?;
996 self.parse_hex_digits_into_char(6, 6)
997 .map(|(offset, c)| (offset, SingleOrMultiChar::Single(c)))
998 }
999 'N' => {
1000 // parse code point with name in {}
1001 // tracking issue: https://github.com/unicode-org/icu4x/issues/1397
1002 Err(PEK::Unimplemented.with_offset(offset))
1003 }
1004 'a' => Ok((offset, SingleOrMultiChar::Single('\u{0007}'))),
1005 'b' => Ok((offset, SingleOrMultiChar::Single('\u{0008}'))),
1006 't' => Ok((offset, SingleOrMultiChar::Single('\u{0009}'))),
1007 'n' => Ok((offset, SingleOrMultiChar::Single('\u{000A}'))),
1008 'v' => Ok((offset, SingleOrMultiChar::Single('\u{000B}'))),
1009 'f' => Ok((offset, SingleOrMultiChar::Single('\u{000C}'))),
1010 'r' => Ok((offset, SingleOrMultiChar::Single('\u{000D}'))),
1011 _ => Ok((offset, SingleOrMultiChar::Single(next_char))),
1012 }
1013 }
1014
1015 // starts with :, consumes the trailing :]
1016 fn parse_property_posix(&mut self) -> Result<()> {
1017 self.consume(':')?;
1018 if self.must_peek_char()? == '^' {
1019 self.inverted = true;
1020 self.iter.next();
1021 }
1022
1023 self.parse_property_inner(':')?;
1024
1025 self.consume(']')?;
1026
1027 Ok(())
1028 }
1029
1030 // starts with \p{ or \P{, consumes the trailing }
1031 fn parse_property_perl(&mut self) -> Result<()> {
1032 self.consume('\\')?;
1033 match self.must_next()? {
1034 (_, 'p') => {}
1035 (_, 'P') => self.inverted = true,
1036 (offset, c) => return Err(PEK::UnexpectedChar(c).with_offset(offset)),
1037 }
1038 self.consume('{')?;
1039
1040 self.parse_property_inner('}')?;
1041
1042 Ok(())
1043 }
1044
1045 fn parse_property_inner(&mut self, end: char) -> Result<()> {
1046 // UnicodeSet spec ignores whitespace, '-', and '_',
1047 // but ECMA-262 requires '_', so we'll allow that.
1048 // TODO(#3559): support loose matching on property names (e.g., "AS -_- CII_Hex_ D-igit")
1049 // TODO(#3559): support more properties than ECMA-262
1050
1051 let property_offset;
1052
1053 let mut key_buffer = String::new();
1054 let mut value_buffer = String::new();
1055
1056 enum State {
1057 // initial state, nothing parsed yet
1058 Begin,
1059 // non-empty property name
1060 PropertyName,
1061 // property name parsed, '=' or '≠' parsed, no value parsed yet
1062 PropertyValueBegin,
1063 // non-empty property name, non-empty property value
1064 PropertyValue,
1065 }
1066 use State::*;
1067
1068 let mut state = Begin;
1069 // whether '=' (true) or '≠' (false) was parsed
1070 let mut equality = true;
1071
1072 loop {
1073 self.skip_whitespace();
1074 match (state, self.must_peek_char()?) {
1075 // parse the end of the property expression
1076 (PropertyName | PropertyValue, c) if c == end => {
1077 // byte index of (full) property name/value is one back
1078 property_offset = self.must_peek_index()? - 1;
1079 self.iter.next();
1080 break;
1081 }
1082 // parse the property name
1083 // NOTE: this might be too strict, because in the case of e.g. [:value:], we might want to
1084 // allow [:lower-case-letter:] ([:gc=lower-case-letter:] works)
1085 (Begin | PropertyName, c) if c.is_ascii_alphanumeric() || c == '_' => {
1086 key_buffer.push(c);
1087 self.iter.next();
1088 state = PropertyName;
1089 }
1090 // parse the name-value separator
1091 (PropertyName, c @ ('=' | '≠')) => {
1092 equality = c == '=';
1093 self.iter.next();
1094 state = PropertyValueBegin;
1095 }
1096 // parse the property value
1097 (PropertyValue | PropertyValueBegin, c) if c != end => {
1098 value_buffer.push(c);
1099 self.iter.next();
1100 state = PropertyValue;
1101 }
1102 (_, c) => return self.error_here(PEK::UnexpectedChar(c)),
1103 }
1104 }
1105
1106 if !equality {
1107 self.inverted = !self.inverted;
1108 }
1109
1110 let inverted = self
1111 .load_property_codepoints(&key_buffer, &value_buffer)
1112 // any error that does not already have an offset should use the appropriate property offset
1113 .map_err(|e| e.or_with_offset(property_offset))?;
1114 if inverted {
1115 self.inverted = !self.inverted;
1116 }
1117
1118 Ok(())
1119 }
1120
1121 // returns whether the set needs to be inverted or not
1122 fn load_property_codepoints(&mut self, key: &str, value: &str) -> Result<bool> {
1123 // we support:
1124 // [:gc = value:]
1125 // [:sc = value:]
1126 // [:scx = value:]
1127 // [:Grapheme_Cluster_Break = value:]
1128 // [:Sentence_Break = value:]
1129 // [:Word_Break = value:]
1130 // [:value:] - looks up value in gc, sc
1131 // [:prop:] - binary property, returns codepoints that have the property
1132 // [:prop = truthy/falsy:] - same as above
1133
1134 let mut inverted = false;
1135
1136 // contains a value for the General_Category property that needs to be tried
1137 let mut try_gc = Err(PEK::UnknownProperty.into());
1138 // contains a value for the Script property that needs to be tried
1139 let mut try_sc = Err(PEK::UnknownProperty.into());
1140 // contains a value for the Script_Extensions property that needs to be tried
1141 let mut try_scx = Err(PEK::UnknownProperty.into());
1142 // contains a value for the Grapheme_Cluster_Break property that needs to be tried
1143 let mut try_gcb = Err(PEK::UnknownProperty.into());
1144 // contains a value for the Indic_Conjuct_Break property that needs to be tried
1145 let mut try_incb = Err(PEK::UnknownProperty.into());
1146 // contains a value for the Line_Break property that needs to be tried
1147 let mut try_lb = Err(PEK::UnknownProperty.into());
1148 // contains a value for the Sentence_Break property that needs to be tried
1149 let mut try_sb = Err(PEK::UnknownProperty.into());
1150 // contains a value for the Word_Break property that needs to be tried
1151 let mut try_wb = Err(PEK::UnknownProperty.into());
1152 // contains a value for the East_Asian_Width property that needs to be tried
1153 let mut try_eaw = Err(PEK::UnknownProperty.into());
1154 // contains a supposed binary property name that needs to be tried
1155 let mut try_binary = Err(PEK::UnknownProperty.into());
1156 // contains a supposed canonical combining class property name that needs to be tried
1157 let mut try_ccc: Result<&str, ParseError> = Err(PEK::UnknownProperty.into());
1158 // contains a supposed block property name that needs to be tried
1159 let mut try_block: Result<&str, ParseError> = Err(PEK::UnknownProperty.into());
1160
1161 if !value.is_empty() {
1162 // key is gc, sc, scx, grapheme cluster break, sentence break, word break
1163 // value is a property value
1164 // OR
1165 // key is a binary property and value is a truthy/falsy value
1166
1167 fn loose(s: &[u8]) -> impl Iterator<Item = u8> + '_ {
1168 s.iter()
1169 .map(|&c| c.to_ascii_lowercase())
1170 .filter(|&c| c != b'_')
1171 }
1172
1173 if loose(key.as_bytes()).eq(loose(GeneralCategory::NAME))
1174 || loose(key.as_bytes()).eq(loose(GeneralCategory::SHORT_NAME))
1175 {
1176 try_gc = Ok(value)
1177 } else if loose(key.as_bytes()).eq(loose(GraphemeClusterBreak::NAME))
1178 || loose(key.as_bytes()).eq(loose(GraphemeClusterBreak::SHORT_NAME))
1179 {
1180 try_gcb = Ok(value)
1181 } else if loose(key.as_bytes()).eq(loose(IndicConjunctBreak::NAME))
1182 || loose(key.as_bytes()).eq(loose(IndicConjunctBreak::SHORT_NAME))
1183 {
1184 try_incb = Ok(value)
1185 } else if loose(key.as_bytes()).eq(loose(LineBreak::NAME))
1186 || loose(key.as_bytes()).eq(loose(LineBreak::SHORT_NAME))
1187 {
1188 try_lb = Ok(value)
1189 } else if loose(key.as_bytes()).eq(loose(Script::NAME))
1190 || loose(key.as_bytes()).eq(loose(Script::SHORT_NAME))
1191 {
1192 try_sc = Ok(value)
1193 } else if loose(key.as_bytes()).eq(loose(SentenceBreak::NAME))
1194 || loose(key.as_bytes()).eq(loose(SentenceBreak::SHORT_NAME))
1195 {
1196 try_sb = Ok(value)
1197 } else if loose(key.as_bytes()).eq(loose(WordBreak::NAME))
1198 || loose(key.as_bytes()).eq(loose(WordBreak::SHORT_NAME))
1199 {
1200 try_wb = Ok(value)
1201 } else if loose(key.as_bytes()).eq(loose(EastAsianWidth::NAME))
1202 || loose(key.as_bytes()).eq(loose(EastAsianWidth::SHORT_NAME))
1203 {
1204 try_eaw = Ok(value)
1205 } else if loose(key.as_bytes()).eq(loose(CanonicalCombiningClass::NAME))
1206 || loose(key.as_bytes()).eq(loose(CanonicalCombiningClass::SHORT_NAME))
1207 {
1208 try_ccc = Ok(value)
1209 } else if loose(key.as_bytes()).eq(loose(b"Script_Extensions"))
1210 || loose(key.as_bytes()).eq(loose(b"scx"))
1211 {
1212 try_scx = Ok(value)
1213 } else if loose(key.as_bytes()).eq(loose(b"Block"))
1214 || loose(key.as_bytes()).eq(loose(b"blk"))
1215 {
1216 try_block = Ok(value)
1217 } else {
1218 let normalized_value = value.to_ascii_lowercase();
1219 let truthy = matches!(normalized_value.as_str(), "true" | "t" | "yes" | "y");
1220 let falsy = matches!(normalized_value.as_str(), "false" | "f" | "no" | "n");
1221 // value must either match truthy or falsy
1222 if truthy == falsy {
1223 return Err(PEK::UnknownProperty.into());
1224 }
1225 // correctness: if we reach this point, only `try_binary` can be Ok, hence
1226 // it does not matter that further down we unconditionally return `inverted`,
1227 // because only `try_binary` can enter that code path.
1228 inverted = falsy;
1229 try_binary = Ok(key);
1230 }
1231 } else {
1232 // key is binary property
1233 // OR a value of gc, sc (only gc or sc are supported as implicit keys by UTS35!)
1234 try_gc = Ok(key);
1235 try_sc = Ok(key);
1236 try_binary = Ok(key);
1237 }
1238
1239 try_gc
1240 .and_then(|value| self.try_load_general_category_set(value))
1241 .or_else(|_| try_sc.and_then(|value| self.try_load_script_set(value)))
1242 .or_else(|_| try_scx.and_then(|value| self.try_load_script_extensions_set(value)))
1243 .or_else(|_| try_binary.and_then(|value| self.try_load_ecma262_binary_set(value)))
1244 .or_else(|_| try_gcb.and_then(|value| self.try_load_grapheme_cluster_break_set(value)))
1245 .or_else(|_| try_incb.and_then(|value| self.try_load_indic_conjunct_break_set(value)))
1246 .or_else(|_| try_lb.and_then(|value| self.try_load_line_break_set(value)))
1247 .or_else(|_| try_sb.and_then(|value| self.try_load_sentence_break_set(value)))
1248 .or_else(|_| try_wb.and_then(|value| self.try_load_word_break_set(value)))
1249 .or_else(|_| try_eaw.and_then(|value| self.try_load_east_asian_width_set(value)))
1250 .or_else(|_| try_ccc.and_then(|value| self.try_load_ccc_set(value)))
1251 .or_else(|_| try_block.and_then(|value| self.try_load_block_set(value)))?;
1252 Ok(inverted)
1253 }
1254
1255 fn finalize(mut self) -> (CodePointInversionListBuilder, BTreeSet<String>) {
1256 if self.inverted {
1257 // code point inversion; removes all strings
1258 #[cfg(feature = "log")]
1259 {
1260 let single_set = self.single_set.clone().build();
1261 if !self
1262 .string_set
1263 .iter()
1264 // if the string starts with a cp in the cp-set, then it'll be rejected through that
1265 .all(|s| s.chars().next().is_some_and(|c| single_set.contains(c)))
1266 {
1267 log::info!(
1268 "Inverting a unicode set with strings. This removes all strings entirely."
1269 );
1270 }
1271 }
1272 self.string_set.clear();
1273 self.single_set.complement();
1274 }
1275
1276 (self.single_set, self.string_set)
1277 }
1278
1279 // parses either a raw char or an escaped char. all chars are allowed, the caller must make sure to handle
1280 // cases where some characters are not allowed
1281 fn parse_char(&mut self) -> Result<(usize, SingleOrMultiChar)> {
1282 let (offset, c) = self.must_peek()?;
1283 match c {
1284 '\\' => self.parse_escaped_char(),
1285 _ => {
1286 self.iter.next();
1287 Ok((offset, SingleOrMultiChar::Single(c)))
1288 }
1289 }
1290 }
1291
1292 // note: could turn this from the current two-pass approach into a one-pass approach
1293 // by manually parsing the digits instead of using u32::from_str_radix.
1294 fn parse_hex_digits_into_char(&mut self, min: usize, max: usize) -> Result<(usize, char)> {
1295 let first_offset = self.must_peek_index()?;
1296 let end_offset = self.validate_hex_digits(min, max)?;
1297
1298 // validate_hex_digits ensures that chars (including the last one) are ascii hex digits,
1299 // which are all exactly one UTF-8 byte long, so slicing on these offsets always respects char boundaries
1300 let hex_source = &self.source[first_offset..=end_offset];
1301 let num = u32::from_str_radix(hex_source, 16).map_err(|_| PEK::Internal)?;
1302 char::try_from(num)
1303 .map(|c| (end_offset, c))
1304 .map_err(|_| PEK::InvalidEscape.with_offset(end_offset))
1305 }
1306
1307 // validates [0-9a-fA-F]{min,max}, returns the offset of the last digit, consuming everything in the process
1308 fn validate_hex_digits(&mut self, min: usize, max: usize) -> Result<usize> {
1309 let mut last_offset = 0;
1310 for count in 0..max {
1311 let (offset, c) = self.must_peek()?;
1312 if !c.is_ascii_hexdigit() {
1313 if count < min {
1314 return Err(PEK::UnexpectedChar(c).with_offset(offset));
1315 } else {
1316 break;
1317 }
1318 }
1319 self.iter.next();
1320 last_offset = offset;
1321 }
1322 Ok(last_offset)
1323 }
1324
1325 // returns the number of skipped whitespace chars
1326 fn skip_whitespace(&mut self) -> usize {
1327 let mut num = 0;
1328 while let Some(c) = self.peek_char() {
1329 if !self.pat_ws.contains(c) {
1330 break;
1331 }
1332 self.iter.next();
1333 num += 1;
1334 }
1335 num
1336 }
1337
1338 fn consume(&mut self, expected: char) -> Result<()> {
1339 match self.must_next()? {
1340 (offset, c) if c != expected => Err(PEK::UnexpectedChar(c).with_offset(offset)),
1341 _ => Ok(()),
1342 }
1343 }
1344
1345 // use this whenever an empty iterator would imply an Eof error
1346 fn must_next(&mut self) -> Result<(usize, char)> {
1347 self.iter.next().ok_or(ParseError {
1348 offset: None,
1349 kind: PEK::Eof,
1350 })
1351 }
1352
1353 // use this whenever an empty iterator would imply an Eof error
1354 fn must_peek(&mut self) -> Result<(usize, char)> {
1355 self.iter.peek().copied().ok_or(ParseError {
1356 offset: None,
1357 kind: PEK::Eof,
1358 })
1359 }
1360
1361 // must_peek, but looks two chars ahead. use sparingly
1362 fn must_peek_double(&mut self) -> Result<(usize, char)> {
1363 let mut copy = self.iter.clone();
1364 copy.next();
1365 copy.next().ok_or(ParseError {
1366 offset: None,
1367 kind: PEK::Eof,
1368 })
1369 }
1370
1371 // see must_peek
1372 fn must_peek_char(&mut self) -> Result<char> {
1373 self.must_peek().map(|(_, c)| c)
1374 }
1375
1376 // see must_peek
1377 fn must_peek_index(&mut self) -> Result<usize> {
1378 self.must_peek().map(|(idx, _)| idx)
1379 }
1380
1381 fn peek_char(&mut self) -> Option<char> {
1382 self.iter.peek().map(|&(_, c)| c)
1383 }
1384
1385 // TODO: return Result<!> once ! is stable
1386 #[inline]
1387 fn error_here<T>(&mut self, kind: ParseErrorKind) -> Result<T> {
1388 match self.iter.peek() {
1389 None => Err(kind.into()),
1390 Some(&(offset, _)) => Err(kind.with_offset(offset)),
1391 }
1392 }
1393
1394 fn process_strings(&mut self, op: Operation, other_strings: BTreeSet<String>) {
1395 match op {
1396 Operation::Union => self.string_set.extend(other_strings),
1397 Operation::Difference => {
1398 self.string_set = self
1399 .string_set
1400 .difference(&other_strings)
1401 .cloned()
1402 .collect()
1403 }
1404 Operation::Intersection => {
1405 self.string_set = self
1406 .string_set
1407 .intersection(&other_strings)
1408 .cloned()
1409 .collect()
1410 }
1411 }
1412 }
1413
1414 fn process_chars(&mut self, op: Operation, other_chars: CodePointInversionList) {
1415 match op {
1416 Operation::Union => self.single_set.add_set(&other_chars),
1417 Operation::Difference => self.single_set.remove_set(&other_chars),
1418 Operation::Intersection => self.single_set.retain_set(&other_chars),
1419 }
1420 }
1421
1422 fn try_load_general_category_set(&mut self, name: &str) -> Result<()> {
1423 // TODO(#3550): This could be cached; does not depend on name.
1424 let name_map =
1425 PropertyParser::<GeneralCategoryGroup>::try_new_unstable(self.property_provider)
1426 .map_err(|_| PEK::Internal)?;
1427 let gc_value = name_map
1428 .as_borrowed()
1429 .get_loose(name)
1430 .ok_or(PEK::UnknownProperty)?;
1431 // TODO(#3550): This could be cached; does not depend on name.
1432 let set = CodePointMapData::<GeneralCategory>::try_new_unstable(self.property_provider)
1433 .map_err(|_| PEK::Internal)?
1434 .as_borrowed()
1435 .get_set_for_value_group(gc_value);
1436 self.single_set.add_set(&set.to_code_point_inversion_list());
1437 Ok(())
1438 }
1439
1440 fn try_get_script(&self, name: &str) -> Result<Script> {
1441 // TODO(#3550): This could be cached; does not depend on name.
1442 let name_map = PropertyParser::<Script>::try_new_unstable(self.property_provider)
1443 .map_err(|_| PEK::Internal)?;
1444 name_map.as_borrowed().get_loose(name).ok_or(ParseError {
1445 offset: None,
1446 kind: PEK::UnknownProperty,
1447 })
1448 }
1449
1450 fn try_load_script_set(&mut self, name: &str) -> Result<()> {
1451 let sc_value = self.try_get_script(name)?;
1452 // TODO(#3550): This could be cached; does not depend on name.
1453 let property_map = CodePointMapData::<Script>::try_new_unstable(self.property_provider)
1454 .map_err(|_| PEK::Internal)?;
1455 let set = property_map.as_borrowed().get_set_for_value(sc_value);
1456 self.single_set.add_set(&set.to_code_point_inversion_list());
1457 Ok(())
1458 }
1459
1460 fn try_load_script_extensions_set(&mut self, name: &str) -> Result<()> {
1461 // TODO(#3550): This could be cached; does not depend on name.
1462 let scx = ScriptWithExtensions::try_new_unstable(self.property_provider)
1463 .map_err(|_| PEK::Internal)?;
1464 let sc_value = self.try_get_script(name)?;
1465 let set = scx.as_borrowed().get_script_extensions_set(sc_value);
1466 self.single_set.add_set(&set);
1467 Ok(())
1468 }
1469
1470 fn try_load_ecma262_binary_set(&mut self, name: &str) -> Result<()> {
1471 let set =
1472 CodePointSetData::try_new_for_ecma262_unstable(self.property_provider, name.as_bytes())
1473 .ok_or(PEK::UnknownProperty)?
1474 .map_err(|_data_error| PEK::Internal)?;
1475 self.single_set.add_set(&set.to_code_point_inversion_list());
1476 Ok(())
1477 }
1478
1479 fn try_load_grapheme_cluster_break_set(&mut self, name: &str) -> Result<()> {
1480 let parser =
1481 PropertyParser::<GraphemeClusterBreak>::try_new_unstable(self.property_provider)
1482 .map_err(|_| PEK::Internal)?;
1483 let gcb_value = parser
1484 .as_borrowed()
1485 .get_loose(name)
1486 .ok_or(PEK::UnknownProperty)?;
1487 // TODO(#3550): This could be cached; does not depend on name.
1488 let property_map =
1489 CodePointMapData::<GraphemeClusterBreak>::try_new_unstable(self.property_provider)
1490 .map_err(|_| PEK::Internal)?;
1491 let set = property_map.as_borrowed().get_set_for_value(gcb_value);
1492 self.single_set.add_set(&set.to_code_point_inversion_list());
1493 Ok(())
1494 }
1495
1496 fn try_load_indic_conjunct_break_set(&mut self, name: &str) -> Result<()> {
1497 let parser = PropertyParser::<IndicConjunctBreak>::try_new_unstable(self.property_provider)
1498 .map_err(|_| PEK::Internal)?;
1499 let gcb_value = parser
1500 .as_borrowed()
1501 .get_loose(name)
1502 .ok_or(PEK::UnknownProperty)?;
1503 // TODO(#3550): This could be cached; does not depend on name.
1504 let property_map =
1505 CodePointMapData::<IndicConjunctBreak>::try_new_unstable(self.property_provider)
1506 .map_err(|_| PEK::Internal)?;
1507 let set = property_map.as_borrowed().get_set_for_value(gcb_value);
1508 self.single_set.add_set(&set.to_code_point_inversion_list());
1509 Ok(())
1510 }
1511
1512 fn try_load_line_break_set(&mut self, name: &str) -> Result<()> {
1513 let parser = PropertyParser::<LineBreak>::try_new_unstable(self.property_provider)
1514 .map_err(|_| PEK::Internal)?;
1515 let lb_value = parser
1516 .as_borrowed()
1517 .get_loose(name)
1518 .ok_or(PEK::UnknownProperty)?;
1519 // TODO(#3550): This could be cached; does not depend on name.
1520 let property_map = CodePointMapData::<LineBreak>::try_new_unstable(self.property_provider)
1521 .map_err(|_| PEK::Internal)?;
1522 let set = property_map.as_borrowed().get_set_for_value(lb_value);
1523 self.single_set.add_set(&set.to_code_point_inversion_list());
1524 Ok(())
1525 }
1526
1527 fn try_load_sentence_break_set(&mut self, name: &str) -> Result<()> {
1528 let parser = PropertyParser::<SentenceBreak>::try_new_unstable(self.property_provider)
1529 .map_err(|_| PEK::Internal)?;
1530 let sb_value = parser
1531 .as_borrowed()
1532 .get_loose(name)
1533 .ok_or(PEK::UnknownProperty)?;
1534 // TODO(#3550): This could be cached; does not depend on name.
1535 let property_map =
1536 CodePointMapData::<SentenceBreak>::try_new_unstable(self.property_provider)
1537 .map_err(|_| PEK::Internal)?;
1538 let set = property_map.as_borrowed().get_set_for_value(sb_value);
1539 self.single_set.add_set(&set.to_code_point_inversion_list());
1540 Ok(())
1541 }
1542
1543 fn try_load_word_break_set(&mut self, name: &str) -> Result<()> {
1544 let parser = PropertyParser::<WordBreak>::try_new_unstable(self.property_provider)
1545 .map_err(|_| PEK::Internal)?;
1546 let wb_value = parser
1547 .as_borrowed()
1548 .get_loose(name)
1549 .ok_or(PEK::UnknownProperty)?;
1550 // TODO(#3550): This could be cached; does not depend on name.
1551 let property_map = CodePointMapData::<WordBreak>::try_new_unstable(self.property_provider)
1552 .map_err(|_| PEK::Internal)?;
1553 let set = property_map.as_borrowed().get_set_for_value(wb_value);
1554 self.single_set.add_set(&set.to_code_point_inversion_list());
1555 Ok(())
1556 }
1557
1558 fn try_load_east_asian_width_set(&mut self, name: &str) -> Result<()> {
1559 let parser = PropertyParser::<EastAsianWidth>::try_new_unstable(self.property_provider)
1560 .map_err(|_| PEK::Internal)?;
1561 let eaw_value = parser
1562 .as_borrowed()
1563 .get_loose(name)
1564 .ok_or(PEK::UnknownProperty)?;
1565 // TODO(#3550): This could be cached; does not depend on name.
1566 let property_map =
1567 CodePointMapData::<EastAsianWidth>::try_new_unstable(self.property_provider)
1568 .map_err(|_| PEK::Internal)?;
1569 let set = property_map.as_borrowed().get_set_for_value(eaw_value);
1570 self.single_set.add_set(&set.to_code_point_inversion_list());
1571 Ok(())
1572 }
1573
1574 fn try_load_ccc_set(&mut self, name: &str) -> Result<()> {
1575 let parser =
1576 PropertyParser::<CanonicalCombiningClass>::try_new_unstable(self.property_provider)
1577 .map_err(|_| PEK::Internal)?;
1578 let value = parser
1579 .as_borrowed()
1580 .get_loose(name)
1581 // TODO: make the property parser do this
1582 .or_else(|| name.parse().ok().map(CanonicalCombiningClass))
1583 .ok_or(PEK::UnknownProperty)?;
1584 // TODO(#3550): This could be cached; does not depend on name.
1585 let property_map =
1586 CodePointMapData::<CanonicalCombiningClass>::try_new_unstable(self.property_provider)
1587 .map_err(|_| PEK::Internal)?;
1588 let set = property_map.as_borrowed().get_set_for_value(value);
1589 self.single_set.add_set(&set.to_code_point_inversion_list());
1590 Ok(())
1591 }
1592
1593 fn try_load_block_set(&mut self, name: &str) -> Result<()> {
1594 // TODO: source these from properties
1595 self.single_set
1596 .add_range(match name.to_ascii_lowercase().as_str() {
1597 "arabic" => '\u{0600}'..'\u{06FF}',
1598 "thaana" => '\u{0780}'..'\u{07BF}',
1599 _ => {
1600 #[cfg(feature = "log")]
1601 log::warn!("Skipping :block={name}:");
1602 return Err(PEK::Unimplemented.into());
1603 }
1604 });
1605 Ok(())
1606 }
1607 }
1608
1609 /// <div class="stab unstable">
1610 /// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
1611 /// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
1612 /// of the icu meta-crate. Use with caution.
1613 /// <a href="https://github.com/unicode-org/icu4x/issues/3959">#3959</a>
1614 /// </div>
1615 ///
1616 /// Parses a `UnicodeSet` pattern and returns a `UnicodeSet` in the form of a [`CodePointInversionListAndStringList`](CodePointInversionListAndStringList),
1617 /// as well as the number of bytes consumed from the source string.
1618 ///
1619 /// Supports `UnicodeSets` as described in [UTS #35 - Unicode Sets](https://unicode.org/reports/tr35/#Unicode_Sets).
1620 ///
1621 /// The error type of the returned Result can be pretty-printed with [`ParseError::fmt_with_source`].
1622 ///
1623 /// # Variables
1624 ///
1625 /// If you need support for variables inside `UnicodeSets` (e.g., `[$start-$end]`), use [`parse_with_variables`].
1626 ///
1627 /// # Limitations
1628 ///
1629 /// * Currently, we only support the [ECMA-262 properties](https://tc39.es/ecma262/#table-nonbinary-unicode-properties).
1630 /// The property names must match the exact spelling listed in ECMA-262. Note that we do support UTS35 syntax for elided `General_Category`
1631 /// and `Script` property names, i.e., `[:Latn:]` and `[:Ll:]` are both valid, with the former implying the `Script` property, and the latter the
1632 /// `General_Category` property.
1633 /// * We do not support `\N{Unicode code point name}` character escaping. Use any other escape method described in UTS35.
1634 ///
1635 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1636 ///
1637 /// [📚 Help choosing a constructor](icu_provider::constructors)
1638 ///
1639 /// # Examples
1640 ///
1641 /// Parse ranges
1642 /// ```
1643 /// use icu::properties::unicodeset_parse::parse;
1644 ///
1645 /// let source = "[a-zA-Z0-9]";
1646 /// let (set, consumed) = parse(source).unwrap();
1647 /// let code_points = set.code_points();
1648 ///
1649 /// assert!(code_points.contains_range('a'..='z'));
1650 /// assert!(code_points.contains_range('A'..='Z'));
1651 /// assert!(code_points.contains_range('0'..='9'));
1652 /// assert_eq!(consumed, source.len());
1653 /// ```
1654 ///
1655 /// Parse properties, set operations, inner sets
1656 /// ```
1657 /// use icu::properties::unicodeset_parse::parse;
1658 ///
1659 /// let (set, _) =
1660 /// parse("[[:^ll:]-[^][:gc = Lowercase Letter:]&[^[[^]-[a-z]]]]").unwrap();
1661 /// assert!(set.code_points().contains_range('a'..='z'));
1662 /// assert_eq!(('a'..='z').count(), set.size());
1663 /// ```
1664 ///
1665 /// Inversions remove strings
1666 /// ```
1667 /// use icu::properties::unicodeset_parse::parse;
1668 ///
1669 /// let (set, _) =
1670 /// parse(r"[[a-z{hello\ world}]&[^a-y{hello\ world}]]").unwrap();
1671 /// assert!(set.contains('z'));
1672 /// assert_eq!(set.size(), 1);
1673 /// assert!(!set.has_strings());
1674 /// ```
1675 ///
1676 /// Set operators (including the implicit union) have the same precedence and are left-associative
1677 /// ```
1678 /// use icu::properties::unicodeset_parse::parse;
1679 ///
1680 /// let (set, _) = parse("[[ace][bdf] - [abc][def]]").unwrap();
1681 /// assert!(set.code_points().contains_range('d'..='f'));
1682 /// assert_eq!(set.size(), ('d'..='f').count());
1683 /// ```
1684 ///
1685 /// Supports partial parses
1686 /// ```
1687 /// use icu::properties::unicodeset_parse::parse;
1688 ///
1689 /// let (set, consumed) = parse("[a-c][x-z]").unwrap();
1690 /// let code_points = set.code_points();
1691 /// assert!(code_points.contains_range('a'..='c'));
1692 /// assert!(!code_points.contains_range('x'..='z'));
1693 /// assert_eq!(set.size(), ('a'..='c').count());
1694 /// // only the first UnicodeSet is parsed
1695 /// assert_eq!(consumed, "[a-c]".len());
1696 /// ```
1697 #[cfg(feature = "compiled_data")]
1698 pub fn parse(source: &str) -> Result<(CodePointInversionListAndStringList<'static>, usize)> {
1699 parse_unstable(source, &Baked)
1700 }
1701
1702 /// <div class="stab unstable">
1703 /// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
1704 /// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
1705 /// of the icu meta-crate. Use with caution.
1706 /// <a href="https://github.com/unicode-org/icu4x/issues/3959">#3959</a>
1707 /// </div>
1708 ///
1709 /// Parses a `UnicodeSet` pattern with support for variables enabled.
1710 ///
1711 /// See [`parse`] for more information.
1712 ///
1713 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1714 ///
1715 /// # Examples
1716 ///
1717 /// ```
1718 /// use icu::properties::unicodeset_parse::*;
1719 ///
1720 /// let (my_set, _) = parse("[abc]").unwrap();
1721 ///
1722 /// let mut variable_map = VariableMap::new();
1723 /// variable_map.insert_char("start".into(), 'a').unwrap();
1724 /// variable_map.insert_char("end".into(), 'z').unwrap();
1725 /// variable_map.insert_string("str".into(), "Hello World".into()).unwrap();
1726 /// variable_map.insert_set("the_set".into(), my_set).unwrap();
1727 ///
1728 /// // If a variable already exists, `Err` is returned, and the map is not updated.
1729 /// variable_map.insert_char("end".into(), 'Ω').unwrap_err();
1730 ///
1731 /// let source = "[[$start-$end]-$the_set $str]";
1732 /// let (set, consumed) = parse_with_variables(source, &variable_map).unwrap();
1733 /// assert_eq!(consumed, source.len());
1734 /// assert!(set.code_points().contains_range('d'..='z'));
1735 /// assert!(set.contains_str("Hello World"));
1736 /// assert_eq!(set.size(), 1 + ('d'..='z').count());
1737 #[cfg(feature = "compiled_data")]
1738 pub fn parse_with_variables(
1739 source: &str,
1740 variable_map: &VariableMap<'_>,
1741 ) -> Result<(CodePointInversionListAndStringList<'static>, usize)> {
1742 parse_unstable_with_variables(source, variable_map, &Baked)
1743 }
1744
1745 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, parse_with_variables)]
1746 pub fn parse_unstable_with_variables<P>(
1747 source: &str,
1748 variable_map: &VariableMap<'_>,
1749 provider: &P,
1750 ) -> Result<(CodePointInversionListAndStringList<'static>, usize)>
1751 where
1752 P: ?Sized
1753 + DataProvider<PropertyBinaryAlphabeticV1>
1754 + DataProvider<PropertyBinaryAsciiHexDigitV1>
1755 + DataProvider<PropertyBinaryBidiControlV1>
1756 + DataProvider<PropertyBinaryBidiMirroredV1>
1757 + DataProvider<PropertyBinaryCasedV1>
1758 + DataProvider<PropertyBinaryCaseIgnorableV1>
1759 + DataProvider<PropertyBinaryChangesWhenCasefoldedV1>
1760 + DataProvider<PropertyBinaryChangesWhenCasemappedV1>
1761 + DataProvider<PropertyBinaryChangesWhenLowercasedV1>
1762 + DataProvider<PropertyBinaryChangesWhenNfkcCasefoldedV1>
1763 + DataProvider<PropertyBinaryChangesWhenTitlecasedV1>
1764 + DataProvider<PropertyBinaryChangesWhenUppercasedV1>
1765 + DataProvider<PropertyBinaryDashV1>
1766 + DataProvider<PropertyBinaryDefaultIgnorableCodePointV1>
1767 + DataProvider<PropertyBinaryDeprecatedV1>
1768 + DataProvider<PropertyBinaryDiacriticV1>
1769 + DataProvider<PropertyBinaryEmojiComponentV1>
1770 + DataProvider<PropertyBinaryEmojiModifierBaseV1>
1771 + DataProvider<PropertyBinaryEmojiModifierV1>
1772 + DataProvider<PropertyBinaryEmojiPresentationV1>
1773 + DataProvider<PropertyBinaryEmojiV1>
1774 + DataProvider<PropertyBinaryExtendedPictographicV1>
1775 + DataProvider<PropertyBinaryExtenderV1>
1776 + DataProvider<PropertyBinaryGraphemeBaseV1>
1777 + DataProvider<PropertyBinaryGraphemeExtendV1>
1778 + DataProvider<PropertyBinaryHexDigitV1>
1779 + DataProvider<PropertyBinaryIdContinueV1>
1780 + DataProvider<PropertyBinaryIdeographicV1>
1781 + DataProvider<PropertyBinaryIdsBinaryOperatorV1>
1782 + DataProvider<PropertyBinaryIdStartV1>
1783 + DataProvider<PropertyBinaryIdsTrinaryOperatorV1>
1784 + DataProvider<PropertyBinaryJoinControlV1>
1785 + DataProvider<PropertyBinaryLogicalOrderExceptionV1>
1786 + DataProvider<PropertyBinaryLowercaseV1>
1787 + DataProvider<PropertyBinaryMathV1>
1788 + DataProvider<PropertyBinaryNoncharacterCodePointV1>
1789 + DataProvider<PropertyBinaryPatternSyntaxV1>
1790 + DataProvider<PropertyBinaryPatternWhiteSpaceV1>
1791 + DataProvider<PropertyBinaryQuotationMarkV1>
1792 + DataProvider<PropertyBinaryRadicalV1>
1793 + DataProvider<PropertyBinaryRegionalIndicatorV1>
1794 + DataProvider<PropertyBinarySentenceTerminalV1>
1795 + DataProvider<PropertyBinarySoftDottedV1>
1796 + DataProvider<PropertyBinaryTerminalPunctuationV1>
1797 + DataProvider<PropertyBinaryUnifiedIdeographV1>
1798 + DataProvider<PropertyBinaryUppercaseV1>
1799 + DataProvider<PropertyBinaryVariationSelectorV1>
1800 + DataProvider<PropertyBinaryWhiteSpaceV1>
1801 + DataProvider<PropertyBinaryXidContinueV1>
1802 + DataProvider<PropertyBinaryXidStartV1>
1803 + DataProvider<PropertyEnumCanonicalCombiningClassV1>
1804 + DataProvider<PropertyEnumEastAsianWidthV1>
1805 + DataProvider<PropertyEnumGeneralCategoryV1>
1806 + DataProvider<PropertyEnumGraphemeClusterBreakV1>
1807 + DataProvider<PropertyEnumIndicConjunctBreakV1>
1808 + DataProvider<PropertyEnumLineBreakV1>
1809 + DataProvider<PropertyEnumScriptV1>
1810 + DataProvider<PropertyEnumSentenceBreakV1>
1811 + DataProvider<PropertyEnumWordBreakV1>
1812 + DataProvider<PropertyNameParseCanonicalCombiningClassV1>
1813 + DataProvider<PropertyNameParseEastAsianWidthV1>
1814 + DataProvider<PropertyNameParseGeneralCategoryMaskV1>
1815 + DataProvider<PropertyNameParseGraphemeClusterBreakV1>
1816 + DataProvider<PropertyNameParseIndicConjunctBreakV1>
1817 + DataProvider<PropertyNameParseLineBreakV1>
1818 + DataProvider<PropertyNameParseScriptV1>
1819 + DataProvider<PropertyNameParseSentenceBreakV1>
1820 + DataProvider<PropertyNameParseWordBreakV1>
1821 + DataProvider<PropertyScriptWithExtensionsV1>,
1822 {
1823 // TODO(#3550): Add function "parse_overescaped" that uses a custom iterator to de-overescape (i.e., maps \\ to \) on-the-fly?
1824 // ^ will likely need a different iterator type on UnicodeSetBuilder
1825
1826 let mut iter = source.char_indices().peekable();
1827
1828 let xid_start =
1829 CodePointSetData::try_new_unstable::<XidStart>(provider).map_err(|_| PEK::Internal)?;
1830 let xid_start_list = xid_start.to_code_point_inversion_list();
1831 let xid_continue =
1832 CodePointSetData::try_new_unstable::<XidContinue>(provider).map_err(|_| PEK::Internal)?;
1833 let xid_continue_list = xid_continue.to_code_point_inversion_list();
1834
1835 let pat_ws = CodePointSetData::try_new_unstable::<PatternWhiteSpace>(provider)
1836 .map_err(|_| PEK::Internal)?;
1837 let pat_ws_list = pat_ws.to_code_point_inversion_list();
1838
1839 let mut builder = UnicodeSetBuilder::new_internal(
1840 &mut iter,
1841 source,
1842 variable_map,
1843 &xid_start_list,
1844 &xid_continue_list,
1845 &pat_ws_list,
1846 provider,
1847 );
1848
1849 builder.parse_unicode_set()?;
1850 let (single, string_set) = builder.finalize();
1851 let built_single = single.build();
1852
1853 let mut strings = string_set.into_iter().collect::<Vec<_>>();
1854 strings.sort();
1855 let zerovec = (&strings).into();
1856
1857 let cpinvlistandstrlist = CodePointInversionListAndStringList::try_from(built_single, zerovec)
1858 .map_err(|_| PEK::Internal)?;
1859
1860 let parsed_bytes = match iter.peek().copied() {
1861 None => source.len(),
1862 Some((offset, _)) => offset,
1863 };
1864
1865 Ok((cpinvlistandstrlist, parsed_bytes))
1866 }
1867
1868 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, parse)]
1869 pub fn parse_unstable<P>(
1870 source: &str,
1871 provider: &P,
1872 ) -> Result<(CodePointInversionListAndStringList<'static>, usize)>
1873 where
1874 P: ?Sized
1875 + DataProvider<PropertyBinaryAlphabeticV1>
1876 + DataProvider<PropertyBinaryAsciiHexDigitV1>
1877 + DataProvider<PropertyBinaryBidiControlV1>
1878 + DataProvider<PropertyBinaryBidiMirroredV1>
1879 + DataProvider<PropertyBinaryCasedV1>
1880 + DataProvider<PropertyBinaryCaseIgnorableV1>
1881 + DataProvider<PropertyBinaryChangesWhenCasefoldedV1>
1882 + DataProvider<PropertyBinaryChangesWhenCasemappedV1>
1883 + DataProvider<PropertyBinaryChangesWhenLowercasedV1>
1884 + DataProvider<PropertyBinaryChangesWhenNfkcCasefoldedV1>
1885 + DataProvider<PropertyBinaryChangesWhenTitlecasedV1>
1886 + DataProvider<PropertyBinaryChangesWhenUppercasedV1>
1887 + DataProvider<PropertyBinaryDashV1>
1888 + DataProvider<PropertyBinaryDefaultIgnorableCodePointV1>
1889 + DataProvider<PropertyBinaryDeprecatedV1>
1890 + DataProvider<PropertyBinaryDiacriticV1>
1891 + DataProvider<PropertyBinaryEmojiComponentV1>
1892 + DataProvider<PropertyBinaryEmojiModifierBaseV1>
1893 + DataProvider<PropertyBinaryEmojiModifierV1>
1894 + DataProvider<PropertyBinaryEmojiPresentationV1>
1895 + DataProvider<PropertyBinaryEmojiV1>
1896 + DataProvider<PropertyBinaryExtendedPictographicV1>
1897 + DataProvider<PropertyBinaryExtenderV1>
1898 + DataProvider<PropertyBinaryGraphemeBaseV1>
1899 + DataProvider<PropertyBinaryGraphemeExtendV1>
1900 + DataProvider<PropertyBinaryHexDigitV1>
1901 + DataProvider<PropertyBinaryIdContinueV1>
1902 + DataProvider<PropertyBinaryIdeographicV1>
1903 + DataProvider<PropertyBinaryIdsBinaryOperatorV1>
1904 + DataProvider<PropertyBinaryIdStartV1>
1905 + DataProvider<PropertyBinaryIdsTrinaryOperatorV1>
1906 + DataProvider<PropertyBinaryJoinControlV1>
1907 + DataProvider<PropertyBinaryLogicalOrderExceptionV1>
1908 + DataProvider<PropertyBinaryLowercaseV1>
1909 + DataProvider<PropertyBinaryMathV1>
1910 + DataProvider<PropertyBinaryNoncharacterCodePointV1>
1911 + DataProvider<PropertyBinaryPatternSyntaxV1>
1912 + DataProvider<PropertyBinaryPatternWhiteSpaceV1>
1913 + DataProvider<PropertyBinaryQuotationMarkV1>
1914 + DataProvider<PropertyBinaryRadicalV1>
1915 + DataProvider<PropertyBinaryRegionalIndicatorV1>
1916 + DataProvider<PropertyBinarySentenceTerminalV1>
1917 + DataProvider<PropertyBinarySoftDottedV1>
1918 + DataProvider<PropertyBinaryTerminalPunctuationV1>
1919 + DataProvider<PropertyBinaryUnifiedIdeographV1>
1920 + DataProvider<PropertyBinaryUppercaseV1>
1921 + DataProvider<PropertyBinaryVariationSelectorV1>
1922 + DataProvider<PropertyBinaryWhiteSpaceV1>
1923 + DataProvider<PropertyBinaryXidContinueV1>
1924 + DataProvider<PropertyBinaryXidStartV1>
1925 + DataProvider<PropertyEnumCanonicalCombiningClassV1>
1926 + DataProvider<PropertyEnumEastAsianWidthV1>
1927 + DataProvider<PropertyEnumGeneralCategoryV1>
1928 + DataProvider<PropertyEnumGraphemeClusterBreakV1>
1929 + DataProvider<PropertyEnumIndicConjunctBreakV1>
1930 + DataProvider<PropertyEnumLineBreakV1>
1931 + DataProvider<PropertyEnumScriptV1>
1932 + DataProvider<PropertyEnumSentenceBreakV1>
1933 + DataProvider<PropertyEnumWordBreakV1>
1934 + DataProvider<PropertyNameParseCanonicalCombiningClassV1>
1935 + DataProvider<PropertyNameParseEastAsianWidthV1>
1936 + DataProvider<PropertyNameParseGeneralCategoryMaskV1>
1937 + DataProvider<PropertyNameParseGraphemeClusterBreakV1>
1938 + DataProvider<PropertyNameParseIndicConjunctBreakV1>
1939 + DataProvider<PropertyNameParseLineBreakV1>
1940 + DataProvider<PropertyNameParseScriptV1>
1941 + DataProvider<PropertyNameParseSentenceBreakV1>
1942 + DataProvider<PropertyNameParseWordBreakV1>
1943 + DataProvider<PropertyScriptWithExtensionsV1>,
1944 {
1945 let dummy = Default::default();
1946 parse_unstable_with_variables(source, &dummy, provider)
1947 }
1948
1949 #[cfg(test)]
1950 mod tests {
1951 use core::ops::RangeInclusive;
1952 use std::collections::HashSet;
1953
1954 use super::*;
1955
1956 // "aabxzz" => [a..=a, b..=x, z..=z]
1957 fn range_iter_from_str(s: &str) -> impl Iterator<Item = RangeInclusive<u32>> {
1958 debug_assert_eq!(
1959 s.chars().count() % 2,
1960 0,
1961 "string \"{}\" does not contain an even number of code points",
1962 s.escape_debug()
1963 );
1964 let mut res = vec![];
1965 let mut skip = false;
1966 for (a, b) in s.chars().zip(s.chars().skip(1)) {
1967 if skip {
1968 skip = false;
1969 continue;
1970 }
1971 let a = a as u32;
1972 let b = b as u32;
1973 res.push(a..=b);
1974 skip = true;
1975 }
1976
1977 res.into_iter()
1978 }
1979
1980 fn assert_set_equality<'a>(
1981 source: &str,
1982 cpinvlistandstrlist: &CodePointInversionListAndStringList,
1983 single: impl Iterator<Item = RangeInclusive<u32>>,
1984 strings: impl Iterator<Item = &'a str>,
1985 ) {
1986 let expected_ranges: HashSet<_> = single.collect();
1987 let actual_ranges: HashSet<_> = cpinvlistandstrlist.code_points().iter_ranges().collect();
1988 assert_eq!(
1989 actual_ranges,
1990 expected_ranges,
1991 "got unexpected ranges {:?}, expected {:?} for parsed set \"{}\"",
1992 actual_ranges,
1993 expected_ranges,
1994 source.escape_debug()
1995 );
1996 let mut expected_size = cpinvlistandstrlist.code_points().size();
1997 for s in strings {
1998 expected_size += 1;
1999 assert!(
2000 cpinvlistandstrlist.contains_str(s),
2001 "missing string \"{}\" from parsed set \"{}\"",
2002 s.escape_debug(),
2003 source.escape_debug()
2004 );
2005 }
2006 let actual_size = cpinvlistandstrlist.size();
2007 assert_eq!(
2008 actual_size,
2009 expected_size,
2010 "got unexpected size {}, expected {} for parsed set \"{}\"",
2011 actual_size,
2012 expected_size,
2013 source.escape_debug()
2014 );
2015 }
2016
2017 fn assert_is_error_and_message_eq(source: &str, expected_err: &str, vm: &VariableMap<'_>) {
2018 let result = parse_with_variables(source, vm);
2019 assert!(result.is_err(), "{source} does not cause an error!");
2020 let err = result.unwrap_err();
2021 assert_eq!(err.fmt_with_source(source).to_string(), expected_err);
2022 }
2023
2024 #[test]
2025 fn test_semantics_with_variables() {
2026 let mut map_char_char = VariableMap::default();
2027 map_char_char.insert_char("a".to_string(), 'a').unwrap();
2028 map_char_char.insert_char("var2".to_string(), 'z').unwrap();
2029
2030 let mut map_headache = VariableMap::default();
2031 map_headache.insert_char("hehe".to_string(), '-').unwrap();
2032
2033 let mut map_char_string = VariableMap::default();
2034 map_char_string.insert_char("a".to_string(), 'a').unwrap();
2035 map_char_string
2036 .insert_string("var2".to_string(), "abc".to_string())
2037 .unwrap();
2038
2039 let (set, _) = parse(r"[a-z {Hello,\ World!}]").unwrap();
2040 let mut map_char_set = VariableMap::default();
2041 map_char_set.insert_char("a".to_string(), 'a').unwrap();
2042 map_char_set.insert_set("set".to_string(), set).unwrap();
2043
2044 let cases: Vec<(_, _, _, Vec<&str>)> = vec![
2045 // simple
2046 (&map_char_char, "[$a]", "aa", vec![]),
2047 (&map_char_char, "[ $a ]", "aa", vec![]),
2048 (&map_char_char, "[$a$]", "aa\u{ffff}\u{ffff}", vec![]),
2049 (&map_char_char, "[$a$ ]", "aa\u{ffff}\u{ffff}", vec![]),
2050 (&map_char_char, "[$a$var2]", "aazz", vec![]),
2051 (&map_char_char, "[$a - $var2]", "az", vec![]),
2052 (&map_char_char, "[$a-$var2]", "az", vec![]),
2053 (&map_headache, "[a $hehe z]", "aazz--", vec![]),
2054 (
2055 &map_char_char,
2056 "[[$]var2]",
2057 "\u{ffff}\u{ffff}vvaarr22",
2058 vec![],
2059 ),
2060 // variable prefix escaping
2061 (&map_char_char, r"[\$var2]", "$$vvaarr22", vec![]),
2062 (&map_char_char, r"[\\$var2]", r"\\zz", vec![]),
2063 // no variable dereferencing in strings
2064 (&map_char_char, "[{$a}]", "", vec!["$a"]),
2065 // set operations
2066 (&map_char_set, "[$set & [b-z]]", "bz", vec![]),
2067 (&map_char_set, "[[a-z]-[b-z]]", "aa", vec![]),
2068 (&map_char_set, "[$set-[b-z]]", "aa", vec!["Hello, World!"]),
2069 (&map_char_set, "[$set-$set]", "", vec![]),
2070 (&map_char_set, "[[a-zA]-$set]", "AA", vec![]),
2071 (&map_char_set, "[$set[b-z]]", "az", vec!["Hello, World!"]),
2072 (&map_char_set, "[[a-a]$set]", "az", vec!["Hello, World!"]),
2073 (&map_char_set, "$set", "az", vec!["Hello, World!"]),
2074 // strings
2075 (&map_char_string, "[$var2]", "", vec!["abc"]),
2076 ];
2077 for (variable_map, source, single, strings) in cases {
2078 let parsed = parse_with_variables(source, variable_map);
2079 if let Err(err) = parsed {
2080 panic!(
2081 "{source} results in an error: {}",
2082 err.fmt_with_source(source)
2083 );
2084 }
2085 let (set, consumed) = parsed.unwrap();
2086 assert_eq!(consumed, source.len(), "{source:?} is not fully consumed");
2087 assert_set_equality(
2088 source,
2089 &set,
2090 range_iter_from_str(single),
2091 strings.into_iter(),
2092 );
2093 }
2094 }
2095
2096 #[test]
2097 fn test_semantics() {
2098 const ALL_CHARS: &str = "\x00\u{10FFFF}";
2099 let cases: Vec<(_, _, Vec<&str>)> = vec![
2100 // simple
2101 ("[a]", "aa", vec![]),
2102 ("[]", "", vec![]),
2103 ("[qax]", "aaqqxx", vec![]),
2104 ("[a-z]", "az", vec![]),
2105 ("[--]", "--", vec![]),
2106 ("[a-b-]", "ab--", vec![]),
2107 ("[[a-b]-]", "ab--", vec![]),
2108 ("[{ab}-]", "--", vec!["ab"]),
2109 ("[-a-b]", "ab--", vec![]),
2110 ("[-a]", "--aa", vec![]),
2111 // whitespace escaping
2112 (r"[\n]", "\n\n", vec![]),
2113 ("[\\\n]", "\n\n", vec![]),
2114 // empty - whitespace is skipped
2115 ("[\n]", "", vec![]),
2116 ("[\u{9}]", "", vec![]),
2117 ("[\u{A}]", "", vec![]),
2118 ("[\u{B}]", "", vec![]),
2119 ("[\u{C}]", "", vec![]),
2120 ("[\u{D}]", "", vec![]),
2121 ("[\u{20}]", "", vec![]),
2122 ("[\u{85}]", "", vec![]),
2123 ("[\u{200E}]", "", vec![]),
2124 ("[\u{200F}]", "", vec![]),
2125 ("[\u{2028}]", "", vec![]),
2126 ("[\u{2029}]", "", vec![]),
2127 // whitespace significance:
2128 ("[^[^$]]", "\u{ffff}\u{ffff}", vec![]),
2129 ("[^[^ $]]", "\u{ffff}\u{ffff}", vec![]),
2130 ("[^[^ $ ]]", "\u{ffff}\u{ffff}", vec![]),
2131 ("[^[^a$]]", "aa\u{ffff}\u{ffff}", vec![]),
2132 ("[^[^a$ ]]", "aa\u{ffff}\u{ffff}", vec![]),
2133 ("[-]", "--", vec![]),
2134 ("[ - ]", "--", vec![]),
2135 ("[ - - ]", "--", vec![]),
2136 ("[ a-b - ]", "ab--", vec![]),
2137 ("[ -a]", "--aa", vec![]),
2138 ("[a-]", "--aa", vec![]),
2139 ("[a- ]", "--aa", vec![]),
2140 ("[ :]", "::", vec![]),
2141 ("[ :L:]", "::LL", vec![]),
2142 // but not all "whitespace", only Pattern_White_Space:
2143 ("[\u{A0}]", "\u{A0}\u{A0}", vec![]), // non-breaking space
2144 // anchor
2145 ("[$]", "\u{ffff}\u{ffff}", vec![]),
2146 (r"[\$]", "$$", vec![]),
2147 ("[{$}]", "$$", vec![]),
2148 // set operations
2149 ("[[a-z]&[b-z]]", "bz", vec![]),
2150 ("[[a-z]-[b-z]]", "aa", vec![]),
2151 ("[[a-z][b-z]]", "az", vec![]),
2152 ("[[a-a][b-z]]", "az", vec![]),
2153 ("[[a-z{abc}]&[b-z{abc}{abx}]]", "bz", vec!["abc"]),
2154 ("[[{abx}a-z{abc}]&[b-z{abc}]]", "bz", vec!["abc"]),
2155 ("[[a-z{abx}]-[{abx}b-z{abc}]]", "aa", vec![]),
2156 ("[[a-z{abx}{abc}]-[{abx}b-z]]", "aa", vec!["abc"]),
2157 ("[[a-z{abc}][b-z{abx}]]", "az", vec!["abc", "abx"]),
2158 // strings
2159 ("[{this is a minus -}]", "", vec!["thisisaminus-"]),
2160 // associativity
2161 ("[[a-a][b-z] - [a-d][e-z]]", "ez", vec![]),
2162 ("[[a-a][b-z] - [a-d]&[e-z]]", "ez", vec![]),
2163 ("[[a-a][b-z] - [a-z][]]", "", vec![]),
2164 ("[[a-a][b-z] - [a-z]&[]]", "", vec![]),
2165 ("[[a-a][b-z] & [a-z]-[]]", "az", vec![]),
2166 ("[[a-a][b-z] & []-[a-z]]", "", vec![]),
2167 ("[[a-a][b-z] & [a-b][x-z]]", "abxz", vec![]),
2168 ("[[a-z]-[a-b]-[y-z]]", "cx", vec![]),
2169 // escape tests
2170 (r"[\x61-\x63]", "ac", vec![]),
2171 (r"[a-\x63]", "ac", vec![]),
2172 (r"[\x61-c]", "ac", vec![]),
2173 (r"[\u0061-\x63]", "ac", vec![]),
2174 (r"[\U00000061-\x63]", "ac", vec![]),
2175 (r"[\x{61}-\x63]", "ac", vec![]),
2176 (r"[\u{61}-\x63]", "ac", vec![]),
2177 (r"[\u{61}{hello\ world}]", "aa", vec!["hello world"]),
2178 (r"[{hello\ world}\u{61}]", "aa", vec!["hello world"]),
2179 (r"[{h\u{65}llo\ world}]", "", vec!["hello world"]),
2180 // complement tests
2181 (r"[^]", ALL_CHARS, vec![]),
2182 (r"[[^]-[^a-z]]", "az", vec![]),
2183 (r"[^{h\u{65}llo\ world}]", ALL_CHARS, vec![]),
2184 (
2185 r"[^[{h\u{65}llo\ world}]-[{hello\ world}]]",
2186 ALL_CHARS,
2187 vec![],
2188 ),
2189 (
2190 r"[^[\x00-\U0010FFFF]-[\u0100-\U0010FFFF]]",
2191 "\u{100}\u{10FFFF}",
2192 vec![],
2193 ),
2194 (r"[^[^a-z]]", "az", vec![]),
2195 (r"[^[^\^]]", "^^", vec![]),
2196 (r"[{\x{61 0062 063}}]", "", vec!["abc"]),
2197 (r"[\x{61 0062 063}]", "ac", vec![]),
2198 // binary properties
2199 (r"[:AHex:]", "09afAF", vec![]),
2200 (r"[:AHex=True:]", "09afAF", vec![]),
2201 (r"[:AHex=T:]", "09afAF", vec![]),
2202 (r"[:AHex=Yes:]", "09afAF", vec![]),
2203 (r"[:AHex=Y:]", "09afAF", vec![]),
2204 (r"[:^AHex≠True:]", "09afAF", vec![]),
2205 (r"[:AHex≠False:]", "09afAF", vec![]),
2206 (r"[[:^AHex≠False:]&[\x00-\x10]]", "\0\x10", vec![]),
2207 (r"\p{AHex}", "09afAF", vec![]),
2208 (r"\p{AHex=True}", "09afAF", vec![]),
2209 (r"\p{AHex=T}", "09afAF", vec![]),
2210 (r"\p{AHex=Yes}", "09afAF", vec![]),
2211 (r"\p{AHex=Y}", "09afAF", vec![]),
2212 (r"\P{AHex≠True}", "09afAF", vec![]),
2213 (r"\p{AHex≠False}", "09afAF", vec![]),
2214 // general category
2215 (r"[[:gc=lower-case-letter:]&[a-zA-Z]]", "az", vec![]),
2216 (r"[[:lower case letter:]&[a-zA-Z]]", "az", vec![]),
2217 // general category groups
2218 // equivalence between L and the union of all the L* categories
2219 (
2220 r"[[[:L:]-[\p{Ll}\p{Lt}\p{Lu}\p{Lo}\p{Lm}]][[\p{Ll}\p{Lt}\p{Lu}\p{Lo}\p{Lm}]-[:L:]]]",
2221 "",
2222 vec![],
2223 ),
2224 // script
2225 (r"[[:sc=latn:]&[a-zA-Z]]", "azAZ", vec![]),
2226 (r"[[:sc=Latin:]&[a-zA-Z]]", "azAZ", vec![]),
2227 (r"[[:Latin:]&[a-zA-Z]]", "azAZ", vec![]),
2228 (r"[[:latn:]&[a-zA-Z]]", "azAZ", vec![]),
2229 // script extensions
2230 (r"[[:scx=latn:]&[a-zA-Z]]", "azAZ", vec![]),
2231 (r"[[:scx=Latin:]&[a-zA-Z]]", "azAZ", vec![]),
2232 (r"[[:scx=Hira:]&[\u30FC]]", "\u{30FC}\u{30FC}", vec![]),
2233 (r"[[:sc=Hira:]&[\u30FC]]", "", vec![]),
2234 (r"[[:scx=Kana:]&[\u30FC]]", "\u{30FC}\u{30FC}", vec![]),
2235 (r"[[:sc=Kana:]&[\u30FC]]", "", vec![]),
2236 (r"[[:sc=Common:]&[\u30FC]]", "\u{30FC}\u{30FC}", vec![]),
2237 // grapheme cluster break
2238 (
2239 r"\p{Grapheme_Cluster_Break=ZWJ}",
2240 "\u{200D}\u{200D}",
2241 vec![],
2242 ),
2243 // sentence break
2244 (
2245 r"\p{Sentence_Break=ATerm}",
2246 "\u{002E}\u{002E}\u{2024}\u{2024}\u{FE52}\u{FE52}\u{FF0E}\u{FF0E}",
2247 vec![],
2248 ),
2249 // word break
2250 (r"\p{Word_Break=Single_Quote}", "\u{0027}\u{0027}", vec![]),
2251 // more syntax edge cases from UTS35 directly
2252 (r"[\^a]", "^^aa", vec![]),
2253 (r"[{{}]", "{{", vec![]),
2254 (r"[{}}]", "}}", vec![""]),
2255 (r"[}]", "}}", vec![]),
2256 (r"[{$var}]", "", vec!["$var"]),
2257 (r"[{[a-z}]", "", vec!["[a-z"]),
2258 (r"[ { [ a - z } ]", "", vec!["[a-z"]),
2259 // TODO(#3556): Add more tests (specifically conformance tests if they exist)
2260 ];
2261 for (source, single, strings) in cases {
2262 let parsed = parse(source);
2263 if let Err(err) = parsed {
2264 panic!(
2265 "{source} results in an error: {}",
2266 err.fmt_with_source(source)
2267 );
2268 }
2269 let (set, consumed) = parsed.unwrap();
2270 assert_eq!(consumed, source.len());
2271 assert_set_equality(
2272 source,
2273 &set,
2274 range_iter_from_str(single),
2275 strings.into_iter(),
2276 );
2277 }
2278 }
2279
2280 #[test]
2281 fn test_error_messages_with_variables() {
2282 let mut map_char_char = VariableMap::default();
2283 map_char_char.insert_char("a".to_string(), 'a').unwrap();
2284 map_char_char.insert_char("var2".to_string(), 'z').unwrap();
2285
2286 let mut map_char_string = VariableMap::default();
2287 map_char_string.insert_char("a".to_string(), 'a').unwrap();
2288 map_char_string
2289 .insert_string("var2".to_string(), "abc".to_string())
2290 .unwrap();
2291
2292 let (set, _) = parse(r"[a-z {Hello,\ World!}]").unwrap();
2293 let mut map_char_set = VariableMap::default();
2294 map_char_set.insert_char("a".to_string(), 'a').unwrap();
2295 map_char_set.insert_set("set".to_string(), set).unwrap();
2296
2297 let cases = [
2298 (&map_char_char, "[$$a]", r"[$$a← error: unexpected variable"),
2299 (
2300 &map_char_char,
2301 "[$ a]",
2302 r"[$ a← error: unexpected character 'a'",
2303 ),
2304 (&map_char_char, "$a", r"$a← error: unexpected variable"),
2305 (&map_char_char, "$", r"$← error: unexpected end of input"),
2306 (
2307 &map_char_string,
2308 "[$var2-$a]",
2309 r"[$var2-$a← error: unexpected variable",
2310 ),
2311 (
2312 &map_char_string,
2313 "[$a-$var2]",
2314 r"[$a-$var2← error: unexpected variable",
2315 ),
2316 (
2317 &map_char_set,
2318 "[$a-$set]",
2319 r"[$a-$set← error: unexpected variable",
2320 ),
2321 (
2322 &map_char_set,
2323 "[$set-$a]",
2324 r"[$set-$a← error: unexpected variable",
2325 ),
2326 (
2327 &map_char_set,
2328 "[$=]",
2329 "[$=← error: unexpected character '='",
2330 ),
2331 ];
2332 for (variable_map, source, expected_err) in cases {
2333 assert_is_error_and_message_eq(source, expected_err, variable_map);
2334 }
2335 }
2336
2337 #[test]
2338 fn test_error_messages() {
2339 let cases = [
2340 (r"[a-z[\]]", r"[a-z[\]]← error: unexpected end of input"),
2341 (r"", r"← error: unexpected end of input"),
2342 (r"[{]", r"[{]← error: unexpected end of input"),
2343 // we match ECMA-262 strictly, so case matters
2344 (
2345 r"[:general_category:]",
2346 r"[:general_category← error: unknown property",
2347 ),
2348 (r"[:ll=true:]", r"[:ll=true← error: unknown property"),
2349 (r"[:=", r"[:=← error: unexpected character '='"),
2350 // property names may not be empty
2351 (r"[::]", r"[::← error: unexpected character ':'"),
2352 (r"[:=hello:]", r"[:=← error: unexpected character '='"),
2353 // property values may not be empty
2354 (r"[:gc=:]", r"[:gc=:← error: unexpected character ':'"),
2355 (r"[\xag]", r"[\xag← error: unexpected character 'g'"),
2356 (r"[a-b-z]", r"[a-b-z← error: unexpected character 'z'"),
2357 // TODO(#3558): Might be better as "[a-\p← error: unexpected character 'p'"?
2358 (r"[a-\p{ll}]", r"[a-\← error: unexpected character '\\'"),
2359 (r"[a-&]", r"[a-&← error: unexpected character '&'"),
2360 (r"[a&b]", r"[a&← error: unexpected character '&'"),
2361 (r"[[set]&b]", r"[[set]&b← error: unexpected character 'b'"),
2362 (r"[[set]&]", r"[[set]&]← error: unexpected character ']'"),
2363 (r"[a-\x60]", r"[a-\x60← error: unexpected character '`'"),
2364 (r"[a-`]", r"[a-`← error: unexpected character '`'"),
2365 (r"[\x{6g}]", r"[\x{6g← error: unexpected character 'g'"),
2366 (r"[\x{g}]", r"[\x{g← error: unexpected character 'g'"),
2367 (r"[\x{}]", r"[\x{}← error: unexpected character '}'"),
2368 (
2369 r"[\x{dabeef}]",
2370 r"[\x{dabeef← error: invalid escape sequence",
2371 ),
2372 (
2373 r"[\x{10ffff0}]",
2374 r"[\x{10ffff0← error: unexpected character '0'",
2375 ),
2376 (
2377 r"[\x{11ffff}]",
2378 r"[\x{11ffff← error: invalid escape sequence",
2379 ),
2380 (
2381 r"[\x{10ffff 1 10ffff0}]",
2382 r"[\x{10ffff 1 10ffff0← error: unexpected character '0'",
2383 ),
2384 // > 1 byte in UTF-8 edge case
2385 (r"ä", r"ä← error: unexpected character 'ä'"),
2386 (r"\p{gc=ä}", r"\p{gc=ä← error: unknown property"),
2387 (r"\p{gc=ä}", r"\p{gc=ä← error: unknown property"),
2388 (
2389 r"[\xe5-\xe4]",
2390 r"[\xe5-\xe4← error: unexpected character 'ä'",
2391 ),
2392 (r"[\xe5-ä]", r"[\xe5-ä← error: unexpected character 'ä'"),
2393 // whitespace significance
2394 (r"[ ^]", r"[ ^← error: unexpected character '^'"),
2395 (r"[:]", r"[:]← error: unexpected character ']'"),
2396 (r"[:L]", r"[:L]← error: unexpected character ']'"),
2397 (r"\p {L}", r"\p ← error: unexpected character ' '"),
2398 // multi-escapes are not allowed in ranges
2399 (
2400 r"[\x{61 62}-d]",
2401 r"[\x{61 62}-d← error: unexpected character 'd'",
2402 ),
2403 (
2404 r"[\x{61 63}-\x{62 64}]",
2405 r"[\x{61 63}-\← error: unexpected character '\\'",
2406 ),
2407 // TODO(#3558): This is a bad error message.
2408 (r"[a-\x{62 64}]", r"[a-\← error: unexpected character '\\'"),
2409 ];
2410 let vm = Default::default();
2411 for (source, expected_err) in cases {
2412 assert_is_error_and_message_eq(source, expected_err, &vm);
2413 }
2414 }
2415
2416 #[test]
2417 fn test_consumed() {
2418 let cases = [
2419 (r"[a-z\]{[}]".len(), r"[a-z\]{[}][]"),
2420 (r"[a-z\]{[}]".len(), r"[a-z\]{[}] []"),
2421 (r"[a-z\]{[}]".len(), r"[a-z\]{]}] []"),
2422 (r"[a-z\]{{[}]".len(), r"[a-z\]{{]}] []"),
2423 (r"[a-z\]{[}]".len(), r"[a-z\]{]}]\p{L}"),
2424 (r"[a-z\]{[}]".len(), r"[a-z\]{]}]$var"),
2425 ];
2426
2427 let vm = Default::default();
2428 for (expected_consumed, source) in cases {
2429 let (_, consumed) = parse(source).unwrap();
2430 assert_eq!(expected_consumed, consumed);
2431 let (_, consumed) = parse_with_variables(source, &vm).unwrap();
2432 assert_eq!(expected_consumed, consumed);
2433 }
2434 }
2435 }