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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
use std::cmp::Ordering;
use crate::{
common::*,
expr::{TypedVariable, ValueType},
};
#[derive(Debug, Copy, Clone)]
pub enum Capture {
/// Ignore the capture
Ignore(SourceSpan),
/// Capture the entire match, but without a name
All(Span<ValueType>),
/// Capture the entire match, and bind it with the given name and type
Implicit(TypedVariable),
/// Capture a specific named group, and bind it with a different name and type
Mapped { group: Symbol, with: TypedVariable },
/// Capture a specific group with the given name and type
Explicit(TypedVariable),
}
impl Default for Capture {
#[inline(always)]
fn default() -> Self {
Self::Ignore(SourceSpan::from(0..0))
}
}
impl Eq for Capture {}
impl PartialEq for Capture {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Ignore(_), Self::Ignore(_)) => true,
(Self::All(_), Self::All(_)) => true,
(Self::Implicit(l), Self::Implicit(r)) => l == r,
(Self::Mapped { group: gl, with: l }, Self::Mapped { group: gr, with: r }) => {
gl == gr && l == r
}
(Self::Explicit(l), Self::Explicit(r)) => l == r,
_ => false,
}
}
}
impl PartialOrd for Capture {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Capture {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
match (self, other) {
(Self::Ignore(_), Self::Ignore(_)) => Ordering::Equal,
(Self::Ignore(_), _) => Ordering::Less,
(_, Self::Ignore(_)) => Ordering::Greater,
(Self::All(_), Self::All(_)) => Ordering::Equal,
(Self::All(_), _) => Ordering::Less,
(_, Self::All(_)) => Ordering::Greater,
(Self::Implicit(l), Self::Implicit(r)) => l.cmp(r),
(Self::Implicit(_), _) => Ordering::Less,
(_, Self::Implicit(_)) => Ordering::Greater,
(Self::Mapped { with: l, group: gl }, Self::Mapped { with: r, group: gr }) => {
l.cmp(r).then(gl.cmp(gr))
}
(Self::Mapped { with: l, .. }, Self::Explicit(r)) => l.cmp(r).then(Ordering::Less),
(Self::Explicit(l), Self::Mapped { with: r, .. }) => l.cmp(r).then(Ordering::Greater),
(Self::Explicit(l), Self::Explicit(r)) => l.cmp(r),
}
}
}
impl Capture {
pub fn name(&self) -> Option<Symbol> {
match self {
Self::Implicit(tv) | Self::Mapped { with: tv, .. } | Self::Explicit(tv) => {
Some(tv.name.into_inner())
}
Self::Ignore(_) | Self::All(_) => None,
}
}
pub fn group_name(&self) -> Option<Symbol> {
match self {
Self::Mapped { group, .. } => Some(*group),
Self::Explicit(tv) => Some(tv.name.into_inner()),
Self::Ignore(_) | Self::All(_) | Self::Implicit(_) => None,
}
}
pub fn value_type(&self) -> ValueType {
match self {
Self::Implicit(tv) | Self::Mapped { with: tv, .. } | Self::Explicit(tv) => tv.ty,
Self::All(t) => t.into_inner(),
Self::Ignore(_) => ValueType::String,
}
}
}
impl Spanned for Capture {
fn span(&self) -> SourceSpan {
match self {
Self::Implicit(tv) | Self::Mapped { with: tv, .. } | Self::Explicit(tv) => {
tv.name.span()
}
Self::All(span) => span.span(),
Self::Ignore(span) => *span,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegexPattern<'a> {
pub pattern: Span<Cow<'a, str>>,
pub captures: SmallVec<[Capture; 1]>,
}
impl<'a> RegexPattern<'a> {
pub fn new(pattern: Span<Cow<'a, str>>) -> Self {
Self {
pattern,
captures: smallvec![],
}
}
pub fn is_empty(&self) -> bool {
self.pattern.is_empty()
}
pub fn len(&self) -> usize {
self.pattern.len()
}
}
impl<'a> AsRef<str> for RegexPattern<'a> {
fn as_ref(&self) -> &str {
self.pattern.as_ref()
}
}
impl<'a> Spanned for RegexPattern<'a> {
fn span(&self) -> SourceSpan {
self.pattern.span()
}
}
/// A pattern prefix represents the first distinct
/// subpattern of the overall pattern which can be
/// matched independently of the rest of the pattern.
///
/// Prefixes are used when constructing sets of patterns
/// to find overlapping prefixes that can be collapsed
/// into more efficient searchers for matching.
#[derive(Clone)]
pub enum Prefix<'a> {
/// The entire pattern is empty
Empty(SourceSpan),
/// The entire pattern is a literal string
Literal(Span<Cow<'a, str>>),
/// The pattern is a literal string, but only a subset is the prefix
Substring(Span<Cow<'a, str>>),
/// The prefix is a simple regular expression
Regex(RegexPattern<'a>),
/// The prefix contains a match block/substitution that cannot be
/// reduced to a regular expression or literal prefix.
Match(Cow<'a, Match<'a>>),
}
impl<'a> Spanned for Prefix<'a> {
fn span(&self) -> SourceSpan {
match self {
Self::Empty(span) => *span,
Self::Literal(spanned) | Self::Substring(spanned) => spanned.span(),
Self::Regex(spanned) => spanned.span(),
Self::Match(spanned) => spanned.span(),
}
}
}
impl<'a> Prefix<'a> {
pub fn as_str(&self) -> Option<&str> {
match self {
Self::Empty(_) => Some(""),
Self::Literal(s) | Self::Substring(s) => Some(s.as_ref()),
Self::Regex(regex) => Some(regex.pattern.as_ref()),
Self::Match(_) => None,
}
}
}
impl<'a> Eq for Prefix<'a> {}
impl<'a> PartialEq for Prefix<'a> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other).is_eq()
}
}
impl<'a> PartialOrd for Prefix<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Ord for Prefix<'a> {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Self::Match(a), Self::Match(b)) => a.cmp(b),
(Self::Match(_), _) => Ordering::Greater,
(_, Self::Match(_)) => Ordering::Less,
(
Self::Regex(RegexPattern {
pattern: ap,
captures: ac,
}),
Self::Regex(RegexPattern {
pattern: bp,
captures: bc,
}),
) if !ac.is_empty() && !bc.is_empty() => ap.cmp(bp).then_with(|| ac.cmp(bc)),
(
Self::Regex(RegexPattern {
pattern: ap,
captures: ac,
}),
b,
) if !ac.is_empty() => ap.as_ref().cmp(b.as_str().unwrap()).then(Ordering::Greater),
(
a,
Self::Regex(RegexPattern {
pattern: bp,
captures: bc,
}),
) if !bc.is_empty() => a.as_str().unwrap().cmp(bp.as_ref()).then(Ordering::Less),
(a, b) => a.as_str().unwrap().cmp(b.as_str().unwrap()),
}
}
}
/// A check pattern is the part of a check line which must match in the check file somewhere
#[derive(Debug)]
pub enum CheckPattern<'a> {
/// There is no content, we're at the end of line
Empty(SourceSpan),
/// The entire pattern is a single raw string
Literal(Span<Cow<'a, str>>),
/// The entire pattern is a single regex string
Regex(RegexPattern<'a>),
/// The pattern is some mix of literal parts and match rules
Match(Span<Vec<CheckPatternPart<'a>>>),
}
impl<'a> PartialEq for CheckPattern<'a> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Empty(_), Self::Empty(_)) => true,
(Self::Literal(l), Self::Literal(r)) => l == r,
(Self::Regex(l), Self::Regex(r)) => l == r,
(Self::Match(l), Self::Match(r)) => l == r,
_ => false,
}
}
}
impl<'a> CheckPattern<'a> {
pub fn is_empty(&self) -> bool {
match self {
Self::Empty(_) => true,
Self::Literal(ref spanned) => spanned.is_empty(),
Self::Regex(ref spanned) => spanned.is_empty(),
Self::Match(parts) => parts.is_empty(),
}
}
pub fn locate_variables(&self) -> impl Iterator<Item = SourceSpan> + '_ {
CheckPatternVarIter::Pattern(self)
}
pub fn prefix(&self) -> Prefix<'a> {
match self {
Self::Literal(literal) => Prefix::Literal(literal.clone()),
Self::Regex(pattern) => Prefix::Regex(pattern.clone()),
Self::Match(parts) => match &parts[0] {
CheckPatternPart::Literal(literal) => Prefix::Substring(literal.clone()),
CheckPatternPart::Regex(pattern) => Prefix::Regex(pattern.clone()),
CheckPatternPart::Match(Match::Numeric {
span,
format,
capture: None,
expr: None,
..
}) => Prefix::Regex(RegexPattern::new(Span::new(
*span,
format.pattern_nocapture(),
))),
CheckPatternPart::Match(Match::Numeric {
span,
format,
capture: Some(name),
expr: None,
..
}) => Prefix::Regex(RegexPattern {
pattern: Span::new(*span, format.pattern(None)),
captures: smallvec![Capture::Implicit(TypedVariable {
name: *name,
ty: ValueType::Number(*format),
})],
}),
CheckPatternPart::Match(Match::Substitution {
pattern: Some(pattern),
name,
..
}) => Prefix::Regex(RegexPattern {
pattern: pattern.clone(),
captures: smallvec![Capture::Implicit(TypedVariable {
name: *name,
ty: ValueType::String,
})],
}),
CheckPatternPart::Match(part) => Prefix::Match(Cow::Owned(part.clone())),
},
Self::Empty(span) => Prefix::Empty(*span),
}
}
pub fn pop_prefix(&mut self) -> Prefix<'a> {
use std::collections::VecDeque;
match self {
Self::Literal(ref mut literal) => {
let span = literal.span();
let result = Prefix::Literal(core::mem::replace(
literal,
Span::new(span, Cow::Borrowed("")),
));
*self = Self::Empty(span);
result
}
Self::Regex(ref mut pattern) => {
let span = pattern.span();
let result = Prefix::Regex(core::mem::replace(
pattern,
RegexPattern::new(Span::new(span, Cow::Borrowed(""))),
));
*self = Self::Empty(span);
result
}
Self::Match(ref mut parts) => {
let span = parts.span();
let mut ps = VecDeque::<CheckPatternPart<'a>>::from(core::mem::take(&mut **parts));
let prefix = match ps.pop_front().unwrap() {
CheckPatternPart::Literal(literal) => Prefix::Substring(literal),
CheckPatternPart::Regex(pattern) => Prefix::Regex(pattern),
CheckPatternPart::Match(Match::Numeric {
span,
format,
capture: None,
expr: None,
..
}) => Prefix::Regex(RegexPattern::new(Span::new(
span,
format.pattern_nocapture(),
))),
CheckPatternPart::Match(Match::Numeric {
span,
format,
capture: Some(name),
expr: None,
..
}) => Prefix::Regex(RegexPattern {
pattern: Span::new(span, format.pattern_nocapture()),
captures: smallvec![Capture::Implicit(TypedVariable {
name,
ty: ValueType::Number(format),
})],
}),
CheckPatternPart::Match(Match::Substitution {
pattern: Some(pattern),
name,
..
}) => Prefix::Regex(RegexPattern {
pattern,
captures: smallvec![Capture::Implicit(TypedVariable {
name,
ty: ValueType::String,
})],
}),
CheckPatternPart::Match(part) => Prefix::Match(Cow::Owned(part)),
};
if ps.is_empty() {
*self = Self::Empty(span);
} else {
**parts = ps.into();
}
prefix
}
Self::Empty(span) => Prefix::Empty(*span),
}
}
pub fn is_literal(&self) -> bool {
match self {
Self::Empty(_) | Self::Literal(_) => true,
Self::Regex(_) => false,
Self::Match(ref parts) => parts
.iter()
.all(|p| matches!(p, CheckPatternPart::Literal(_))),
}
}
pub fn is_regex_compatible(&self) -> bool {
match self {
Self::Empty(_) | Self::Literal(_) | Self::Regex(_) => true,
Self::Match(ref parts) => parts.iter().all(|p| p.is_regex_compatible()),
}
}
/// Compacts this pattern into fewer parts where possible
pub fn compact(&mut self, interner: &StringInterner) {
use std::collections::VecDeque;
fn convert_to_regex(buffer: &mut String, padding: usize) {
let min_capacity = padding
+ buffer
.chars()
.map(|c| {
if regex_syntax::is_meta_character(c) {
2
} else {
1
}
})
.sum::<usize>();
let prev = core::mem::replace(buffer, String::with_capacity(min_capacity));
regex_syntax::escape_into(&prev, buffer);
}
match self {
Self::Match(ref empty) if empty.is_empty() => {
let span = empty.span();
*self = Self::Empty(span);
}
Self::Match(ref mut compacted) => {
let span = compacted.span();
let mut pattern_span = span.range();
let mut parts = VecDeque::from(core::mem::take(&mut **compacted));
let mut pattern = String::new();
let mut captures = SmallVec::<[Capture; 1]>::new();
let mut is_literal_mode = true;
while let Some(mut part) = parts.pop_front() {
match part {
CheckPatternPart::Literal(part) if is_literal_mode => {
pattern_span.end = part.end();
pattern.push_str(part.as_ref());
}
CheckPatternPart::Literal(part) => {
pattern_span.end = part.end();
regex_syntax::escape_into(part.as_ref(), &mut pattern);
}
CheckPatternPart::Regex(RegexPattern {
pattern: part,
captures: ref mut part_captures,
}) => {
let (span, part) = part.into_parts();
pattern_span.end = span.end();
captures.append(part_captures);
if is_literal_mode {
is_literal_mode = false;
convert_to_regex(&mut pattern, part.len())
}
pattern.push_str(part.as_ref());
}
CheckPatternPart::Match(Match::Substitution {
pattern: Some(part),
name,
span,
}) => {
pattern_span.end = span.end();
let part = part.into_inner();
let group_name = interner.resolve(name.into_inner());
if is_literal_mode {
is_literal_mode = false;
convert_to_regex(&mut pattern, 6 + group_name.len() + part.len());
}
pattern.push_str("(?P<");
pattern.push_str(group_name);
pattern.push('>');
pattern.push_str(part.as_ref());
pattern.push(')');
captures.push(Capture::Explicit(TypedVariable {
name,
ty: ValueType::String,
}));
}
CheckPatternPart::Match(Match::Numeric {
expr: None,
capture: None,
span,
format,
..
}) => {
pattern_span.end = span.end();
let format_pattern = format.pattern_nocapture();
if is_literal_mode {
is_literal_mode = false;
convert_to_regex(&mut pattern, format_pattern.len());
}
pattern.push_str(&format_pattern);
}
CheckPatternPart::Match(Match::Numeric {
expr: None,
capture: Some(name),
span,
format,
..
}) => {
pattern_span.end = span.end();
let group_name = interner.resolve(name.into_inner());
let format_pattern = format.pattern(Some(group_name));
if is_literal_mode {
is_literal_mode = false;
convert_to_regex(&mut pattern, format_pattern.len());
}
pattern.push_str(&format_pattern);
captures.push(Capture::Explicit(TypedVariable {
name,
ty: ValueType::Number(format),
}));
}
part @ CheckPatternPart::Match(_) => {
let span = part.span();
if pattern.is_empty() {
compacted.push(part);
is_literal_mode = true;
pattern.clear();
captures.clear();
pattern_span.end = span.end();
pattern_span.start = pattern_span.end;
continue;
}
if is_literal_mode {
compacted.push(CheckPatternPart::Literal(Span::new(
pattern_span,
Cow::Owned(core::mem::take(&mut pattern)),
)));
} else {
let captures = core::mem::take(&mut captures);
compacted.push(CheckPatternPart::Regex(RegexPattern {
pattern: Span::new(
pattern_span,
Cow::Owned(core::mem::take(&mut pattern)),
),
captures,
}));
is_literal_mode = true;
}
compacted.push(part);
pattern_span.end = span.end();
pattern_span.start = pattern_span.end;
}
}
}
if compacted.is_empty() {
let compacted = if is_literal_mode {
CheckPattern::Literal(Span::new(
pattern_span,
Cow::Owned(core::mem::take(&mut pattern)),
))
} else {
CheckPattern::Regex(RegexPattern {
pattern: Span::new(
pattern_span,
Cow::Owned(core::mem::take(&mut pattern)),
),
captures,
})
};
*self = compacted;
return;
}
if !pattern.is_empty() {
if is_literal_mode {
compacted.push(CheckPatternPart::Literal(Span::new(
pattern_span,
Cow::Owned(core::mem::take(&mut pattern)),
)));
} else {
compacted.push(CheckPatternPart::Regex(RegexPattern {
pattern: Span::new(
pattern_span,
Cow::Owned(core::mem::take(&mut pattern)),
),
captures,
}));
}
}
}
Self::Empty(_) | Self::Literal(_) | Self::Regex(_) => (),
}
}
/// Converts this pattern into a string which can be used as a
/// regular expression, even if the pattern was not originally
/// expressed as a regular expression.
///
/// Returns Err with the original pattern (potentially compacted),
/// if the conversion is not possible. Otherwise, returns Ok
/// with the built regular expression pattern.
pub fn into_regex_pattern(
mut self,
interner: &StringInterner,
) -> Result<RegexPattern<'a>, Self> {
self.compact(interner);
match self {
Self::Literal(s) => Ok(RegexPattern::new(s)),
Self::Regex(regex) => Ok(regex),
other => Err(other),
}
}
}
impl<'a> Spanned for CheckPattern<'a> {
fn span(&self) -> SourceSpan {
match self {
Self::Empty(span) => *span,
Self::Literal(ref spanned) => spanned.span(),
Self::Regex(ref spanned) => spanned.span(),
Self::Match(ref spanned) => spanned.span(),
}
}
}
impl<'a> From<Vec<CheckPatternPart<'a>>> for CheckPattern<'a> {
fn from(mut parts: Vec<CheckPatternPart<'a>>) -> Self {
match parts.len() {
0 => CheckPattern::Empty(SourceSpan::from(0..0)),
1 => match parts.pop().unwrap() {
CheckPatternPart::Literal(lit) => Self::Literal(lit),
CheckPatternPart::Regex(re) => Self::Regex(re),
part @ CheckPatternPart::Match(_) => {
Self::Match(Span::new(part.span(), vec![part]))
}
},
_ => {
let start = parts.first().unwrap().span().offset();
let last_span = parts.last().unwrap().span();
let end = last_span.offset() + last_span.len();
Self::Match(Span::new(SourceSpan::from(start..end), parts))
}
}
}
}
/// A check line is broken up into segments when either `[[` `]]`,
/// or `{{` `}}` is encountered, for substitutions/captures and regex
/// matches respectively; with the before and after parts being literal
/// (and optional). As such we have three types of segments/parts that
/// we can observe on a line
#[derive(Debug, PartialEq, Eq)]
pub enum CheckPatternPart<'a> {
/// This part consists of a match rule to be evaluated while matching
Match(Match<'a>),
/// This part is a raw literal string
Literal(Span<Cow<'a, str>>),
/// This part is a regex pattern
Regex(RegexPattern<'a>),
}
impl<'a> CheckPatternPart<'a> {
pub fn unwrap_str(self) -> Span<Cow<'a, str>> {
match self {
Self::Literal(s) => s,
part => panic!("expected a literal pattern, got {part:#?}"),
}
}
pub fn uses_variable(&self) -> bool {
match self {
Self::Literal(_) | Self::Regex(_) => false,
Self::Match(Match::Numeric {
expr: None,
capture: None,
..
}) => false,
Self::Match(_) => true,
}
}
pub fn is_regex_compatible(&self) -> bool {
match self {
Self::Literal(_)
| Self::Regex(_)
| Self::Match(Match::Substitution {
pattern: Some(_), ..
})
| Self::Match(Match::Numeric { expr: None, .. }) => true,
Self::Match(_) => false,
}
}
}
impl<'a> Spanned for CheckPatternPart<'a> {
fn span(&self) -> SourceSpan {
match self {
Self::Match(m) => m.span(),
Self::Literal(spanned) => spanned.span(),
Self::Regex(spanned) => spanned.span(),
}
}
}
/// This type represents a match rule wrapped in `[[` `]]`
#[derive(Debug, Clone)]
pub enum Match<'a> {
/// Match the given regular expression pattern, optionally binding `name`
/// to the matched value.
///
/// Corresponds to expressions such as `[[REG]]` and `[[REG:r[0-9]+]]`.
///
/// The precise format of this match type is `[[<name>:<pattern>]]`, where:
///
/// * `<name>` is a local variable name of the form `[A-Za-z_][A-Za-z0-9_]*`,
/// or a global variable name (prefixed with `$`). However, you are not permitted
/// to (re)bind global variables.
///
/// * `:<pattern>`, is any valid, non-empty, regular expression pattern. When present,
/// it changes the semantics of this match type from string substitution to string
/// capture - i.e. `name` will be bound to the matched input string.
///
/// If `:<pattern>` is not present, then the entire `[[<name>]]` block will be
/// substituted with the value of `<name>` as a literal pattern. The value will
/// be formatted according to its type.
///
/// Variables bound using this syntax are available immediately on the same line, you
/// can do things like `CHECK: op [[REG:r[0-9]+]], [[REG]]` to bind `REG` to the register
/// name of the first operand of `op`, e.g., `r1`; and verify that the same register is
/// used as the second operand.
///
/// NOTE: You should prefer the standard regular expression pattern matching syntax,
/// i.e. `{{<pattern>}}` if you don't need to bind a variable.
Substitution {
span: SourceSpan,
name: VariableName,
pattern: Option<Span<Cow<'a, str>>>,
},
/// Match the given numeric pattern, and optionally defines a variable if the
/// match succeeds.
///
/// Corresponds to expressions such as `[[#]]` or `[[#%.8X]]` or `[[#REG + 1]]`,
/// as well as `[[#REG:]]` and `[[#%X,OFFSET:12]]`. The former are matches,
/// while the latter both match and define the given variable.
///
/// The unified format is `[[#%<fmtspec>,<NUMVAR>: <constraint> <expr]]` where:
///
/// * `%<fmtspec>` is the same format specifier as used for defining a variable, but
/// in this context it indicates how the numeric value should be matched. It is optional,
/// and if not present, both components of the format spec are inferred from the matching
/// format of the numeric variables used by the expression constraint (if any), and
/// defaults to `%u` (unsigned, no leading zeros) if no numeric variable is used. In
/// case of conflict between format specifiers of several numeric variables, the
/// conversion specifier becomes mandatory, but the precision specifier remains optional.
///
/// * `<NUMVAR>:`, when present, indicates that `NUMVAR` will be (re)bound to the matched
/// value, if the match succeeds. If not present, no variable is defined.
///
/// * `<constraint>` describes how the value to match must relate to the value of the
/// given expression. Currently, the only constraint type is `==` for equality. If present,
/// `<expr>` is mandatory; however the inverse is not true, `<expr>` can be provided
/// without `<constraint>`, implying a default equality constraint.
///
/// * `<expr>` is an expression. An expression is in turn recursively defined as:
///
/// - A numeric operand
/// - An expression followed by an operator and a numeric operand
///
/// A numeric operand is a previously defined numeric variable, an integer literal,
/// or one of a set of built-in functions. Whitespace are allowed around these elements.
/// Numeric operands are 64-bit values. Overflow and underflow are rejected. The original
/// `lit` does not support operator precedence, but `litcheck` supports the standard precedence
/// of the supported operators, and parentheses can be used to manually manage precedence.
///
/// The operators supported are:
///
/// - `+`, addition
/// - `-`, subtraction
///
/// The built-in functions supported are:
///
/// - `add`, addition
/// - `sub`, subtraction
/// - `mul`, multiplication
/// - `div`, integer division
/// - `min`, minimum
/// - `max`, maximum
///
/// All components can be omitted except the `#`, i.e. `[[#]]` is a valid numeric match,
/// which defaults to matching an unsigned integer, with no leading zeros, of up to 64
/// bit precision.
Numeric {
span: SourceSpan,
/// The format of the value to match.
///
/// If not specified, it is implied by the format
/// of any numeric operands in `expr`, otherwise it
/// defaults to an unsigned integer with no leading zeros.
format: NumberFormat,
/// If set, contains the name of the variable to bind to
/// the matched value if the match succeeds.
capture: Option<VariableName>,
/// If specified, this changes the meaning of `expr`
/// in relation to the matched value.
constraint: Constraint,
/// The numeric expression to evaluate
///
/// If `constraint` is not set, this expression
/// produces a value which must match the input.
expr: Option<Expr>,
},
}
impl<'a> PartialOrd for Match<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Ord for Match<'a> {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(
Self::Substitution {
name: an,
pattern: Some(ap),
..
},
Self::Substitution {
name: bn,
pattern: Some(bp),
..
},
) => ap.cmp(bp).then_with(|| an.cmp(bn)),
(
Self::Substitution {
pattern: Some(_), ..
},
Self::Substitution { pattern: None, .. },
) => Ordering::Less,
(
Self::Substitution { pattern: None, .. },
Self::Substitution {
pattern: Some(_), ..
},
) => Ordering::Greater,
(Self::Substitution { name: an, .. }, Self::Substitution { name: bn, .. }) => {
an.cmp(bn)
}
(
Self::Numeric {
format: af,
capture: None,
expr: aexpr,
..
},
Self::Numeric {
format: bf,
capture: None,
expr: bexpr,
..
},
) => af
.pattern(None)
.cmp(&bf.pattern(None))
.then_with(|| aexpr.cmp(bexpr)),
(
Self::Numeric { capture: None, .. },
Self::Numeric {
capture: Some(_), ..
},
) => Ordering::Less,
(
Self::Numeric {
capture: Some(_), ..
},
Self::Numeric { capture: None, .. },
) => Ordering::Greater,
(
Self::Numeric {
format: af,
capture: Some(acap),
expr: aexpr,
..
},
Self::Numeric {
format: bf,
capture: Some(bcap),
expr: bexpr,
..
},
) => af
.pattern(None)
.cmp(&bf.pattern(None))
.then_with(|| acap.cmp(bcap))
.then_with(|| aexpr.cmp(bexpr)),
(
Self::Substitution {
name,
pattern: Some(pattern),
..
},
Self::Numeric {
format,
capture,
expr: None,
..
},
) => AsRef::<str>::as_ref(pattern)
.cmp(format.pattern(None).as_ref())
.then_with(|| Some(*name).cmp(capture))
.then(Ordering::Less),
(
Self::Numeric {
format,
capture,
expr: None,
..
},
Self::Substitution {
name,
pattern: Some(pattern),
..
},
) => format
.pattern(None)
.as_ref()
.cmp(pattern.as_ref())
.then_with(|| capture.cmp(&Some(*name)))
.then(Ordering::Greater),
(Self::Substitution { .. }, _) => Ordering::Less,
(_, Self::Substitution { .. }) => Ordering::Greater,
}
}
}
impl<'a> Spanned for Match<'a> {
fn span(&self) -> SourceSpan {
match self {
Self::Numeric { span, .. } | Self::Substitution { span, .. } => *span,
}
}
}
impl<'a> Eq for Match<'a> {}
impl<'a> PartialEq for Match<'a> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
Self::Substitution {
name: an,
pattern: ap,
..
},
Self::Substitution {
name: bn,
pattern: bp,
..
},
) => an == bn && ap == bp,
(
Self::Numeric {
format: af,
capture: acap,
constraint: ac,
expr: aexpr,
..
},
Self::Numeric {
format: bf,
capture: bcap,
constraint: bc,
expr: bexpr,
..
},
) => af == bf && acap == bcap && ac == bc && aexpr == bexpr,
_ => false,
}
}
}
/// Describes available constraints that can be expressed on numeric values
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Constraint {
Eq,
}
#[derive(Default)]
enum CheckPatternVarIter<'a, 'iter> {
#[default]
Empty,
Pattern(&'iter CheckPattern<'a>),
Regex(&'iter [Capture]),
Parts(&'iter [CheckPatternPart<'a>]),
Expr {
expr: &'iter Expr,
parts: &'iter [CheckPatternPart<'a>],
},
Buffered {
buffer: std::collections::VecDeque<SourceSpan>,
next: &'iter [CheckPatternPart<'a>],
},
}
impl<'a, 'iter> Iterator for CheckPatternVarIter<'a, 'iter> {
type Item = SourceSpan;
fn next(&mut self) -> Option<Self::Item> {
'outer: loop {
match core::mem::take(self) {
Self::Empty => break None,
Self::Pattern(pattern) => match pattern {
CheckPattern::Empty(_) | CheckPattern::Literal(_) => break None,
CheckPattern::Regex(ref re) => {
let (item, rest) = re.captures.split_first()?;
*self = Self::Regex(rest);
break Some(item.span());
}
CheckPattern::Match(ref parts) => {
*self = Self::Parts(parts);
continue;
}
},
Self::Regex(captures) => {
let (item, rest) = captures.split_first()?;
*self = Self::Regex(rest);
break Some(item.span());
}
Self::Parts(parts) => {
while let Some((part, parts)) = parts.split_first() {
match part {
CheckPatternPart::Literal(_) => break,
CheckPatternPart::Regex(ref re) => match re.captures.split_first() {
Some((item, vars)) => {
*self = Self::Buffered {
buffer: vars.iter().map(|v| v.span()).collect(),
next: parts,
};
break 'outer Some(item.span());
}
None => break,
},
CheckPatternPart::Match(Match::Substitution { name, .. }) => {
*self = Self::Parts(parts);
break 'outer Some(name.span());
}
CheckPatternPart::Match(Match::Numeric {
capture: None,
expr: None,
..
}) => {
continue;
}
CheckPatternPart::Match(Match::Numeric {
capture,
expr: Some(ref expr),
..
}) => {
*self = Self::Expr { expr, parts };
if let Some(name) = capture.as_ref() {
break 'outer Some(name.span());
}
continue 'outer;
}
CheckPatternPart::Match(Match::Numeric {
capture: Some(name),
expr: None,
..
}) => {
*self = Self::Parts(parts);
break 'outer Some(name.span());
}
}
}
break None;
}
Self::Expr { expr, parts } => {
let mut worklist = std::collections::VecDeque::with_capacity(2);
let mut buffer = std::collections::VecDeque::new();
worklist.push_back(expr);
loop {
let expr = worklist.pop_front();
match expr {
None => match buffer.pop_front() {
None => {
*self = Self::Parts(parts);
continue 'outer;
}
Some(span) => {
*self = Self::Buffered {
buffer,
next: parts,
};
break 'outer Some(span);
}
},
Some(Expr::Num(_)) => {
continue;
}
Some(Expr::Var(name)) => {
buffer.push_back(name.span());
}
Some(Expr::Binary {
ref lhs, ref rhs, ..
}) => {
worklist.push_back(lhs);
worklist.push_back(rhs);
}
}
}
}
Self::Buffered { mut buffer, next } => match buffer.pop_front() {
None => {
*self = Self::Parts(next);
}
Some(span) => {
*self = Self::Buffered { buffer, next };
break Some(span);
}
},
}
}
}
}