github.com/AESNooper/go/src@v0.0.0-20220218095104-b56a4ab1bbbb/regexp/syntax/parse.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package syntax 6 7 import ( 8 "sort" 9 "strings" 10 "unicode" 11 "unicode/utf8" 12 ) 13 14 // An Error describes a failure to parse a regular expression 15 // and gives the offending expression. 16 type Error struct { 17 Code ErrorCode 18 Expr string 19 } 20 21 func (e *Error) Error() string { 22 return "error parsing regexp: " + e.Code.String() + ": `" + e.Expr + "`" 23 } 24 25 // An ErrorCode describes a failure to parse a regular expression. 26 type ErrorCode string 27 28 const ( 29 // Unexpected error 30 ErrInternalError ErrorCode = "regexp/syntax: internal error" 31 32 // Parse errors 33 ErrInvalidCharClass ErrorCode = "invalid character class" 34 ErrInvalidCharRange ErrorCode = "invalid character class range" 35 ErrInvalidEscape ErrorCode = "invalid escape sequence" 36 ErrInvalidNamedCapture ErrorCode = "invalid named capture" 37 ErrInvalidPerlOp ErrorCode = "invalid or unsupported Perl syntax" 38 ErrInvalidRepeatOp ErrorCode = "invalid nested repetition operator" 39 ErrInvalidRepeatSize ErrorCode = "invalid repeat count" 40 ErrInvalidUTF8 ErrorCode = "invalid UTF-8" 41 ErrMissingBracket ErrorCode = "missing closing ]" 42 ErrMissingParen ErrorCode = "missing closing )" 43 ErrMissingRepeatArgument ErrorCode = "missing argument to repetition operator" 44 ErrTrailingBackslash ErrorCode = "trailing backslash at end of expression" 45 ErrUnexpectedParen ErrorCode = "unexpected )" 46 ) 47 48 func (e ErrorCode) String() string { 49 return string(e) 50 } 51 52 // Flags control the behavior of the parser and record information about regexp context. 53 type Flags uint16 54 55 const ( 56 FoldCase Flags = 1 << iota // case-insensitive match 57 Literal // treat pattern as literal string 58 ClassNL // allow character classes like [^a-z] and [[:space:]] to match newline 59 DotNL // allow . to match newline 60 OneLine // treat ^ and $ as only matching at beginning and end of text 61 NonGreedy // make repetition operators default to non-greedy 62 PerlX // allow Perl extensions 63 UnicodeGroups // allow \p{Han}, \P{Han} for Unicode group and negation 64 WasDollar // regexp OpEndText was $, not \z 65 Simple // regexp contains no counted repetition 66 67 MatchNL = ClassNL | DotNL 68 69 Perl = ClassNL | OneLine | PerlX | UnicodeGroups // as close to Perl as possible 70 POSIX Flags = 0 // POSIX syntax 71 ) 72 73 // Pseudo-ops for parsing stack. 74 const ( 75 opLeftParen = opPseudo + iota 76 opVerticalBar 77 ) 78 79 type parser struct { 80 flags Flags // parse mode flags 81 stack []*Regexp // stack of parsed expressions 82 free *Regexp 83 numCap int // number of capturing groups seen 84 wholeRegexp string 85 tmpClass []rune // temporary char class work space 86 } 87 88 func (p *parser) newRegexp(op Op) *Regexp { 89 re := p.free 90 if re != nil { 91 p.free = re.Sub0[0] 92 *re = Regexp{} 93 } else { 94 re = new(Regexp) 95 } 96 re.Op = op 97 return re 98 } 99 100 func (p *parser) reuse(re *Regexp) { 101 re.Sub0[0] = p.free 102 p.free = re 103 } 104 105 // Parse stack manipulation. 106 107 // push pushes the regexp re onto the parse stack and returns the regexp. 108 func (p *parser) push(re *Regexp) *Regexp { 109 if re.Op == OpCharClass && len(re.Rune) == 2 && re.Rune[0] == re.Rune[1] { 110 // Single rune. 111 if p.maybeConcat(re.Rune[0], p.flags&^FoldCase) { 112 return nil 113 } 114 re.Op = OpLiteral 115 re.Rune = re.Rune[:1] 116 re.Flags = p.flags &^ FoldCase 117 } else if re.Op == OpCharClass && len(re.Rune) == 4 && 118 re.Rune[0] == re.Rune[1] && re.Rune[2] == re.Rune[3] && 119 unicode.SimpleFold(re.Rune[0]) == re.Rune[2] && 120 unicode.SimpleFold(re.Rune[2]) == re.Rune[0] || 121 re.Op == OpCharClass && len(re.Rune) == 2 && 122 re.Rune[0]+1 == re.Rune[1] && 123 unicode.SimpleFold(re.Rune[0]) == re.Rune[1] && 124 unicode.SimpleFold(re.Rune[1]) == re.Rune[0] { 125 // Case-insensitive rune like [Aa] or [Δδ]. 126 if p.maybeConcat(re.Rune[0], p.flags|FoldCase) { 127 return nil 128 } 129 130 // Rewrite as (case-insensitive) literal. 131 re.Op = OpLiteral 132 re.Rune = re.Rune[:1] 133 re.Flags = p.flags | FoldCase 134 } else { 135 // Incremental concatenation. 136 p.maybeConcat(-1, 0) 137 } 138 139 p.stack = append(p.stack, re) 140 return re 141 } 142 143 // maybeConcat implements incremental concatenation 144 // of literal runes into string nodes. The parser calls this 145 // before each push, so only the top fragment of the stack 146 // might need processing. Since this is called before a push, 147 // the topmost literal is no longer subject to operators like * 148 // (Otherwise ab* would turn into (ab)*.) 149 // If r >= 0 and there's a node left over, maybeConcat uses it 150 // to push r with the given flags. 151 // maybeConcat reports whether r was pushed. 152 func (p *parser) maybeConcat(r rune, flags Flags) bool { 153 n := len(p.stack) 154 if n < 2 { 155 return false 156 } 157 158 re1 := p.stack[n-1] 159 re2 := p.stack[n-2] 160 if re1.Op != OpLiteral || re2.Op != OpLiteral || re1.Flags&FoldCase != re2.Flags&FoldCase { 161 return false 162 } 163 164 // Push re1 into re2. 165 re2.Rune = append(re2.Rune, re1.Rune...) 166 167 // Reuse re1 if possible. 168 if r >= 0 { 169 re1.Rune = re1.Rune0[:1] 170 re1.Rune[0] = r 171 re1.Flags = flags 172 return true 173 } 174 175 p.stack = p.stack[:n-1] 176 p.reuse(re1) 177 return false // did not push r 178 } 179 180 // literal pushes a literal regexp for the rune r on the stack. 181 func (p *parser) literal(r rune) { 182 re := p.newRegexp(OpLiteral) 183 re.Flags = p.flags 184 if p.flags&FoldCase != 0 { 185 r = minFoldRune(r) 186 } 187 re.Rune0[0] = r 188 re.Rune = re.Rune0[:1] 189 p.push(re) 190 } 191 192 // minFoldRune returns the minimum rune fold-equivalent to r. 193 func minFoldRune(r rune) rune { 194 if r < minFold || r > maxFold { 195 return r 196 } 197 min := r 198 r0 := r 199 for r = unicode.SimpleFold(r); r != r0; r = unicode.SimpleFold(r) { 200 if min > r { 201 min = r 202 } 203 } 204 return min 205 } 206 207 // op pushes a regexp with the given op onto the stack 208 // and returns that regexp. 209 func (p *parser) op(op Op) *Regexp { 210 re := p.newRegexp(op) 211 re.Flags = p.flags 212 return p.push(re) 213 } 214 215 // repeat replaces the top stack element with itself repeated according to op, min, max. 216 // before is the regexp suffix starting at the repetition operator. 217 // after is the regexp suffix following after the repetition operator. 218 // repeat returns an updated 'after' and an error, if any. 219 func (p *parser) repeat(op Op, min, max int, before, after, lastRepeat string) (string, error) { 220 flags := p.flags 221 if p.flags&PerlX != 0 { 222 if len(after) > 0 && after[0] == '?' { 223 after = after[1:] 224 flags ^= NonGreedy 225 } 226 if lastRepeat != "" { 227 // In Perl it is not allowed to stack repetition operators: 228 // a** is a syntax error, not a doubled star, and a++ means 229 // something else entirely, which we don't support! 230 return "", &Error{ErrInvalidRepeatOp, lastRepeat[:len(lastRepeat)-len(after)]} 231 } 232 } 233 n := len(p.stack) 234 if n == 0 { 235 return "", &Error{ErrMissingRepeatArgument, before[:len(before)-len(after)]} 236 } 237 sub := p.stack[n-1] 238 if sub.Op >= opPseudo { 239 return "", &Error{ErrMissingRepeatArgument, before[:len(before)-len(after)]} 240 } 241 242 re := p.newRegexp(op) 243 re.Min = min 244 re.Max = max 245 re.Flags = flags 246 re.Sub = re.Sub0[:1] 247 re.Sub[0] = sub 248 p.stack[n-1] = re 249 250 if op == OpRepeat && (min >= 2 || max >= 2) && !repeatIsValid(re, 1000) { 251 return "", &Error{ErrInvalidRepeatSize, before[:len(before)-len(after)]} 252 } 253 254 return after, nil 255 } 256 257 // repeatIsValid reports whether the repetition re is valid. 258 // Valid means that the combination of the top-level repetition 259 // and any inner repetitions does not exceed n copies of the 260 // innermost thing. 261 // This function rewalks the regexp tree and is called for every repetition, 262 // so we have to worry about inducing quadratic behavior in the parser. 263 // We avoid this by only calling repeatIsValid when min or max >= 2. 264 // In that case the depth of any >= 2 nesting can only get to 9 without 265 // triggering a parse error, so each subtree can only be rewalked 9 times. 266 func repeatIsValid(re *Regexp, n int) bool { 267 if re.Op == OpRepeat { 268 m := re.Max 269 if m == 0 { 270 return true 271 } 272 if m < 0 { 273 m = re.Min 274 } 275 if m > n { 276 return false 277 } 278 if m > 0 { 279 n /= m 280 } 281 } 282 for _, sub := range re.Sub { 283 if !repeatIsValid(sub, n) { 284 return false 285 } 286 } 287 return true 288 } 289 290 // concat replaces the top of the stack (above the topmost '|' or '(') with its concatenation. 291 func (p *parser) concat() *Regexp { 292 p.maybeConcat(-1, 0) 293 294 // Scan down to find pseudo-operator | or (. 295 i := len(p.stack) 296 for i > 0 && p.stack[i-1].Op < opPseudo { 297 i-- 298 } 299 subs := p.stack[i:] 300 p.stack = p.stack[:i] 301 302 // Empty concatenation is special case. 303 if len(subs) == 0 { 304 return p.push(p.newRegexp(OpEmptyMatch)) 305 } 306 307 return p.push(p.collapse(subs, OpConcat)) 308 } 309 310 // alternate replaces the top of the stack (above the topmost '(') with its alternation. 311 func (p *parser) alternate() *Regexp { 312 // Scan down to find pseudo-operator (. 313 // There are no | above (. 314 i := len(p.stack) 315 for i > 0 && p.stack[i-1].Op < opPseudo { 316 i-- 317 } 318 subs := p.stack[i:] 319 p.stack = p.stack[:i] 320 321 // Make sure top class is clean. 322 // All the others already are (see swapVerticalBar). 323 if len(subs) > 0 { 324 cleanAlt(subs[len(subs)-1]) 325 } 326 327 // Empty alternate is special case 328 // (shouldn't happen but easy to handle). 329 if len(subs) == 0 { 330 return p.push(p.newRegexp(OpNoMatch)) 331 } 332 333 return p.push(p.collapse(subs, OpAlternate)) 334 } 335 336 // cleanAlt cleans re for eventual inclusion in an alternation. 337 func cleanAlt(re *Regexp) { 338 switch re.Op { 339 case OpCharClass: 340 re.Rune = cleanClass(&re.Rune) 341 if len(re.Rune) == 2 && re.Rune[0] == 0 && re.Rune[1] == unicode.MaxRune { 342 re.Rune = nil 343 re.Op = OpAnyChar 344 return 345 } 346 if len(re.Rune) == 4 && re.Rune[0] == 0 && re.Rune[1] == '\n'-1 && re.Rune[2] == '\n'+1 && re.Rune[3] == unicode.MaxRune { 347 re.Rune = nil 348 re.Op = OpAnyCharNotNL 349 return 350 } 351 if cap(re.Rune)-len(re.Rune) > 100 { 352 // re.Rune will not grow any more. 353 // Make a copy or inline to reclaim storage. 354 re.Rune = append(re.Rune0[:0], re.Rune...) 355 } 356 } 357 } 358 359 // collapse returns the result of applying op to sub. 360 // If sub contains op nodes, they all get hoisted up 361 // so that there is never a concat of a concat or an 362 // alternate of an alternate. 363 func (p *parser) collapse(subs []*Regexp, op Op) *Regexp { 364 if len(subs) == 1 { 365 return subs[0] 366 } 367 re := p.newRegexp(op) 368 re.Sub = re.Sub0[:0] 369 for _, sub := range subs { 370 if sub.Op == op { 371 re.Sub = append(re.Sub, sub.Sub...) 372 p.reuse(sub) 373 } else { 374 re.Sub = append(re.Sub, sub) 375 } 376 } 377 if op == OpAlternate { 378 re.Sub = p.factor(re.Sub) 379 if len(re.Sub) == 1 { 380 old := re 381 re = re.Sub[0] 382 p.reuse(old) 383 } 384 } 385 return re 386 } 387 388 // factor factors common prefixes from the alternation list sub. 389 // It returns a replacement list that reuses the same storage and 390 // frees (passes to p.reuse) any removed *Regexps. 391 // 392 // For example, 393 // ABC|ABD|AEF|BCX|BCY 394 // simplifies by literal prefix extraction to 395 // A(B(C|D)|EF)|BC(X|Y) 396 // which simplifies by character class introduction to 397 // A(B[CD]|EF)|BC[XY] 398 // 399 func (p *parser) factor(sub []*Regexp) []*Regexp { 400 if len(sub) < 2 { 401 return sub 402 } 403 404 // Round 1: Factor out common literal prefixes. 405 var str []rune 406 var strflags Flags 407 start := 0 408 out := sub[:0] 409 for i := 0; i <= len(sub); i++ { 410 // Invariant: the Regexps that were in sub[0:start] have been 411 // used or marked for reuse, and the slice space has been reused 412 // for out (len(out) <= start). 413 // 414 // Invariant: sub[start:i] consists of regexps that all begin 415 // with str as modified by strflags. 416 var istr []rune 417 var iflags Flags 418 if i < len(sub) { 419 istr, iflags = p.leadingString(sub[i]) 420 if iflags == strflags { 421 same := 0 422 for same < len(str) && same < len(istr) && str[same] == istr[same] { 423 same++ 424 } 425 if same > 0 { 426 // Matches at least one rune in current range. 427 // Keep going around. 428 str = str[:same] 429 continue 430 } 431 } 432 } 433 434 // Found end of a run with common leading literal string: 435 // sub[start:i] all begin with str[0:len(str)], but sub[i] 436 // does not even begin with str[0]. 437 // 438 // Factor out common string and append factored expression to out. 439 if i == start { 440 // Nothing to do - run of length 0. 441 } else if i == start+1 { 442 // Just one: don't bother factoring. 443 out = append(out, sub[start]) 444 } else { 445 // Construct factored form: prefix(suffix1|suffix2|...) 446 prefix := p.newRegexp(OpLiteral) 447 prefix.Flags = strflags 448 prefix.Rune = append(prefix.Rune[:0], str...) 449 450 for j := start; j < i; j++ { 451 sub[j] = p.removeLeadingString(sub[j], len(str)) 452 } 453 suffix := p.collapse(sub[start:i], OpAlternate) // recurse 454 455 re := p.newRegexp(OpConcat) 456 re.Sub = append(re.Sub[:0], prefix, suffix) 457 out = append(out, re) 458 } 459 460 // Prepare for next iteration. 461 start = i 462 str = istr 463 strflags = iflags 464 } 465 sub = out 466 467 // Round 2: Factor out common simple prefixes, 468 // just the first piece of each concatenation. 469 // This will be good enough a lot of the time. 470 // 471 // Complex subexpressions (e.g. involving quantifiers) 472 // are not safe to factor because that collapses their 473 // distinct paths through the automaton, which affects 474 // correctness in some cases. 475 start = 0 476 out = sub[:0] 477 var first *Regexp 478 for i := 0; i <= len(sub); i++ { 479 // Invariant: the Regexps that were in sub[0:start] have been 480 // used or marked for reuse, and the slice space has been reused 481 // for out (len(out) <= start). 482 // 483 // Invariant: sub[start:i] consists of regexps that all begin with ifirst. 484 var ifirst *Regexp 485 if i < len(sub) { 486 ifirst = p.leadingRegexp(sub[i]) 487 if first != nil && first.Equal(ifirst) && 488 // first must be a character class OR a fixed repeat of a character class. 489 (isCharClass(first) || (first.Op == OpRepeat && first.Min == first.Max && isCharClass(first.Sub[0]))) { 490 continue 491 } 492 } 493 494 // Found end of a run with common leading regexp: 495 // sub[start:i] all begin with first but sub[i] does not. 496 // 497 // Factor out common regexp and append factored expression to out. 498 if i == start { 499 // Nothing to do - run of length 0. 500 } else if i == start+1 { 501 // Just one: don't bother factoring. 502 out = append(out, sub[start]) 503 } else { 504 // Construct factored form: prefix(suffix1|suffix2|...) 505 prefix := first 506 for j := start; j < i; j++ { 507 reuse := j != start // prefix came from sub[start] 508 sub[j] = p.removeLeadingRegexp(sub[j], reuse) 509 } 510 suffix := p.collapse(sub[start:i], OpAlternate) // recurse 511 512 re := p.newRegexp(OpConcat) 513 re.Sub = append(re.Sub[:0], prefix, suffix) 514 out = append(out, re) 515 } 516 517 // Prepare for next iteration. 518 start = i 519 first = ifirst 520 } 521 sub = out 522 523 // Round 3: Collapse runs of single literals into character classes. 524 start = 0 525 out = sub[:0] 526 for i := 0; i <= len(sub); i++ { 527 // Invariant: the Regexps that were in sub[0:start] have been 528 // used or marked for reuse, and the slice space has been reused 529 // for out (len(out) <= start). 530 // 531 // Invariant: sub[start:i] consists of regexps that are either 532 // literal runes or character classes. 533 if i < len(sub) && isCharClass(sub[i]) { 534 continue 535 } 536 537 // sub[i] is not a char or char class; 538 // emit char class for sub[start:i]... 539 if i == start { 540 // Nothing to do - run of length 0. 541 } else if i == start+1 { 542 out = append(out, sub[start]) 543 } else { 544 // Make new char class. 545 // Start with most complex regexp in sub[start]. 546 max := start 547 for j := start + 1; j < i; j++ { 548 if sub[max].Op < sub[j].Op || sub[max].Op == sub[j].Op && len(sub[max].Rune) < len(sub[j].Rune) { 549 max = j 550 } 551 } 552 sub[start], sub[max] = sub[max], sub[start] 553 554 for j := start + 1; j < i; j++ { 555 mergeCharClass(sub[start], sub[j]) 556 p.reuse(sub[j]) 557 } 558 cleanAlt(sub[start]) 559 out = append(out, sub[start]) 560 } 561 562 // ... and then emit sub[i]. 563 if i < len(sub) { 564 out = append(out, sub[i]) 565 } 566 start = i + 1 567 } 568 sub = out 569 570 // Round 4: Collapse runs of empty matches into a single empty match. 571 start = 0 572 out = sub[:0] 573 for i := range sub { 574 if i+1 < len(sub) && sub[i].Op == OpEmptyMatch && sub[i+1].Op == OpEmptyMatch { 575 continue 576 } 577 out = append(out, sub[i]) 578 } 579 sub = out 580 581 return sub 582 } 583 584 // leadingString returns the leading literal string that re begins with. 585 // The string refers to storage in re or its children. 586 func (p *parser) leadingString(re *Regexp) ([]rune, Flags) { 587 if re.Op == OpConcat && len(re.Sub) > 0 { 588 re = re.Sub[0] 589 } 590 if re.Op != OpLiteral { 591 return nil, 0 592 } 593 return re.Rune, re.Flags & FoldCase 594 } 595 596 // removeLeadingString removes the first n leading runes 597 // from the beginning of re. It returns the replacement for re. 598 func (p *parser) removeLeadingString(re *Regexp, n int) *Regexp { 599 if re.Op == OpConcat && len(re.Sub) > 0 { 600 // Removing a leading string in a concatenation 601 // might simplify the concatenation. 602 sub := re.Sub[0] 603 sub = p.removeLeadingString(sub, n) 604 re.Sub[0] = sub 605 if sub.Op == OpEmptyMatch { 606 p.reuse(sub) 607 switch len(re.Sub) { 608 case 0, 1: 609 // Impossible but handle. 610 re.Op = OpEmptyMatch 611 re.Sub = nil 612 case 2: 613 old := re 614 re = re.Sub[1] 615 p.reuse(old) 616 default: 617 copy(re.Sub, re.Sub[1:]) 618 re.Sub = re.Sub[:len(re.Sub)-1] 619 } 620 } 621 return re 622 } 623 624 if re.Op == OpLiteral { 625 re.Rune = re.Rune[:copy(re.Rune, re.Rune[n:])] 626 if len(re.Rune) == 0 { 627 re.Op = OpEmptyMatch 628 } 629 } 630 return re 631 } 632 633 // leadingRegexp returns the leading regexp that re begins with. 634 // The regexp refers to storage in re or its children. 635 func (p *parser) leadingRegexp(re *Regexp) *Regexp { 636 if re.Op == OpEmptyMatch { 637 return nil 638 } 639 if re.Op == OpConcat && len(re.Sub) > 0 { 640 sub := re.Sub[0] 641 if sub.Op == OpEmptyMatch { 642 return nil 643 } 644 return sub 645 } 646 return re 647 } 648 649 // removeLeadingRegexp removes the leading regexp in re. 650 // It returns the replacement for re. 651 // If reuse is true, it passes the removed regexp (if no longer needed) to p.reuse. 652 func (p *parser) removeLeadingRegexp(re *Regexp, reuse bool) *Regexp { 653 if re.Op == OpConcat && len(re.Sub) > 0 { 654 if reuse { 655 p.reuse(re.Sub[0]) 656 } 657 re.Sub = re.Sub[:copy(re.Sub, re.Sub[1:])] 658 switch len(re.Sub) { 659 case 0: 660 re.Op = OpEmptyMatch 661 re.Sub = nil 662 case 1: 663 old := re 664 re = re.Sub[0] 665 p.reuse(old) 666 } 667 return re 668 } 669 if reuse { 670 p.reuse(re) 671 } 672 return p.newRegexp(OpEmptyMatch) 673 } 674 675 func literalRegexp(s string, flags Flags) *Regexp { 676 re := &Regexp{Op: OpLiteral} 677 re.Flags = flags 678 re.Rune = re.Rune0[:0] // use local storage for small strings 679 for _, c := range s { 680 if len(re.Rune) >= cap(re.Rune) { 681 // string is too long to fit in Rune0. let Go handle it 682 re.Rune = []rune(s) 683 break 684 } 685 re.Rune = append(re.Rune, c) 686 } 687 return re 688 } 689 690 // Parsing. 691 692 // Parse parses a regular expression string s, controlled by the specified 693 // Flags, and returns a regular expression parse tree. The syntax is 694 // described in the top-level comment. 695 func Parse(s string, flags Flags) (*Regexp, error) { 696 if flags&Literal != 0 { 697 // Trivial parser for literal string. 698 if err := checkUTF8(s); err != nil { 699 return nil, err 700 } 701 return literalRegexp(s, flags), nil 702 } 703 704 // Otherwise, must do real work. 705 var ( 706 p parser 707 err error 708 c rune 709 op Op 710 lastRepeat string 711 ) 712 p.flags = flags 713 p.wholeRegexp = s 714 t := s 715 for t != "" { 716 repeat := "" 717 BigSwitch: 718 switch t[0] { 719 default: 720 if c, t, err = nextRune(t); err != nil { 721 return nil, err 722 } 723 p.literal(c) 724 725 case '(': 726 if p.flags&PerlX != 0 && len(t) >= 2 && t[1] == '?' { 727 // Flag changes and non-capturing groups. 728 if t, err = p.parsePerlFlags(t); err != nil { 729 return nil, err 730 } 731 break 732 } 733 p.numCap++ 734 p.op(opLeftParen).Cap = p.numCap 735 t = t[1:] 736 case '|': 737 if err = p.parseVerticalBar(); err != nil { 738 return nil, err 739 } 740 t = t[1:] 741 case ')': 742 if err = p.parseRightParen(); err != nil { 743 return nil, err 744 } 745 t = t[1:] 746 case '^': 747 if p.flags&OneLine != 0 { 748 p.op(OpBeginText) 749 } else { 750 p.op(OpBeginLine) 751 } 752 t = t[1:] 753 case '$': 754 if p.flags&OneLine != 0 { 755 p.op(OpEndText).Flags |= WasDollar 756 } else { 757 p.op(OpEndLine) 758 } 759 t = t[1:] 760 case '.': 761 if p.flags&DotNL != 0 { 762 p.op(OpAnyChar) 763 } else { 764 p.op(OpAnyCharNotNL) 765 } 766 t = t[1:] 767 case '[': 768 if t, err = p.parseClass(t); err != nil { 769 return nil, err 770 } 771 case '*', '+', '?': 772 before := t 773 switch t[0] { 774 case '*': 775 op = OpStar 776 case '+': 777 op = OpPlus 778 case '?': 779 op = OpQuest 780 } 781 after := t[1:] 782 if after, err = p.repeat(op, 0, 0, before, after, lastRepeat); err != nil { 783 return nil, err 784 } 785 repeat = before 786 t = after 787 case '{': 788 op = OpRepeat 789 before := t 790 min, max, after, ok := p.parseRepeat(t) 791 if !ok { 792 // If the repeat cannot be parsed, { is a literal. 793 p.literal('{') 794 t = t[1:] 795 break 796 } 797 if min < 0 || min > 1000 || max > 1000 || max >= 0 && min > max { 798 // Numbers were too big, or max is present and min > max. 799 return nil, &Error{ErrInvalidRepeatSize, before[:len(before)-len(after)]} 800 } 801 if after, err = p.repeat(op, min, max, before, after, lastRepeat); err != nil { 802 return nil, err 803 } 804 repeat = before 805 t = after 806 case '\\': 807 if p.flags&PerlX != 0 && len(t) >= 2 { 808 switch t[1] { 809 case 'A': 810 p.op(OpBeginText) 811 t = t[2:] 812 break BigSwitch 813 case 'b': 814 p.op(OpWordBoundary) 815 t = t[2:] 816 break BigSwitch 817 case 'B': 818 p.op(OpNoWordBoundary) 819 t = t[2:] 820 break BigSwitch 821 case 'C': 822 // any byte; not supported 823 return nil, &Error{ErrInvalidEscape, t[:2]} 824 case 'Q': 825 // \Q ... \E: the ... is always literals 826 var lit string 827 lit, t, _ = strings.Cut(t[2:], `\E`) 828 for lit != "" { 829 c, rest, err := nextRune(lit) 830 if err != nil { 831 return nil, err 832 } 833 p.literal(c) 834 lit = rest 835 } 836 break BigSwitch 837 case 'z': 838 p.op(OpEndText) 839 t = t[2:] 840 break BigSwitch 841 } 842 } 843 844 re := p.newRegexp(OpCharClass) 845 re.Flags = p.flags 846 847 // Look for Unicode character group like \p{Han} 848 if len(t) >= 2 && (t[1] == 'p' || t[1] == 'P') { 849 r, rest, err := p.parseUnicodeClass(t, re.Rune0[:0]) 850 if err != nil { 851 return nil, err 852 } 853 if r != nil { 854 re.Rune = r 855 t = rest 856 p.push(re) 857 break BigSwitch 858 } 859 } 860 861 // Perl character class escape. 862 if r, rest := p.parsePerlClassEscape(t, re.Rune0[:0]); r != nil { 863 re.Rune = r 864 t = rest 865 p.push(re) 866 break BigSwitch 867 } 868 p.reuse(re) 869 870 // Ordinary single-character escape. 871 if c, t, err = p.parseEscape(t); err != nil { 872 return nil, err 873 } 874 p.literal(c) 875 } 876 lastRepeat = repeat 877 } 878 879 p.concat() 880 if p.swapVerticalBar() { 881 // pop vertical bar 882 p.stack = p.stack[:len(p.stack)-1] 883 } 884 p.alternate() 885 886 n := len(p.stack) 887 if n != 1 { 888 return nil, &Error{ErrMissingParen, s} 889 } 890 return p.stack[0], nil 891 } 892 893 // parseRepeat parses {min} (max=min) or {min,} (max=-1) or {min,max}. 894 // If s is not of that form, it returns ok == false. 895 // If s has the right form but the values are too big, it returns min == -1, ok == true. 896 func (p *parser) parseRepeat(s string) (min, max int, rest string, ok bool) { 897 if s == "" || s[0] != '{' { 898 return 899 } 900 s = s[1:] 901 var ok1 bool 902 if min, s, ok1 = p.parseInt(s); !ok1 { 903 return 904 } 905 if s == "" { 906 return 907 } 908 if s[0] != ',' { 909 max = min 910 } else { 911 s = s[1:] 912 if s == "" { 913 return 914 } 915 if s[0] == '}' { 916 max = -1 917 } else if max, s, ok1 = p.parseInt(s); !ok1 { 918 return 919 } else if max < 0 { 920 // parseInt found too big a number 921 min = -1 922 } 923 } 924 if s == "" || s[0] != '}' { 925 return 926 } 927 rest = s[1:] 928 ok = true 929 return 930 } 931 932 // parsePerlFlags parses a Perl flag setting or non-capturing group or both, 933 // like (?i) or (?: or (?i:. It removes the prefix from s and updates the parse state. 934 // The caller must have ensured that s begins with "(?". 935 func (p *parser) parsePerlFlags(s string) (rest string, err error) { 936 t := s 937 938 // Check for named captures, first introduced in Python's regexp library. 939 // As usual, there are three slightly different syntaxes: 940 // 941 // (?P<name>expr) the original, introduced by Python 942 // (?<name>expr) the .NET alteration, adopted by Perl 5.10 943 // (?'name'expr) another .NET alteration, adopted by Perl 5.10 944 // 945 // Perl 5.10 gave in and implemented the Python version too, 946 // but they claim that the last two are the preferred forms. 947 // PCRE and languages based on it (specifically, PHP and Ruby) 948 // support all three as well. EcmaScript 4 uses only the Python form. 949 // 950 // In both the open source world (via Code Search) and the 951 // Google source tree, (?P<expr>name) is the dominant form, 952 // so that's the one we implement. One is enough. 953 if len(t) > 4 && t[2] == 'P' && t[3] == '<' { 954 // Pull out name. 955 end := strings.IndexRune(t, '>') 956 if end < 0 { 957 if err = checkUTF8(t); err != nil { 958 return "", err 959 } 960 return "", &Error{ErrInvalidNamedCapture, s} 961 } 962 963 capture := t[:end+1] // "(?P<name>" 964 name := t[4:end] // "name" 965 if err = checkUTF8(name); err != nil { 966 return "", err 967 } 968 if !isValidCaptureName(name) { 969 return "", &Error{ErrInvalidNamedCapture, capture} 970 } 971 972 // Like ordinary capture, but named. 973 p.numCap++ 974 re := p.op(opLeftParen) 975 re.Cap = p.numCap 976 re.Name = name 977 return t[end+1:], nil 978 } 979 980 // Non-capturing group. Might also twiddle Perl flags. 981 var c rune 982 t = t[2:] // skip (? 983 flags := p.flags 984 sign := +1 985 sawFlag := false 986 Loop: 987 for t != "" { 988 if c, t, err = nextRune(t); err != nil { 989 return "", err 990 } 991 switch c { 992 default: 993 break Loop 994 995 // Flags. 996 case 'i': 997 flags |= FoldCase 998 sawFlag = true 999 case 'm': 1000 flags &^= OneLine 1001 sawFlag = true 1002 case 's': 1003 flags |= DotNL 1004 sawFlag = true 1005 case 'U': 1006 flags |= NonGreedy 1007 sawFlag = true 1008 1009 // Switch to negation. 1010 case '-': 1011 if sign < 0 { 1012 break Loop 1013 } 1014 sign = -1 1015 // Invert flags so that | above turn into &^ and vice versa. 1016 // We'll invert flags again before using it below. 1017 flags = ^flags 1018 sawFlag = false 1019 1020 // End of flags, starting group or not. 1021 case ':', ')': 1022 if sign < 0 { 1023 if !sawFlag { 1024 break Loop 1025 } 1026 flags = ^flags 1027 } 1028 if c == ':' { 1029 // Open new group 1030 p.op(opLeftParen) 1031 } 1032 p.flags = flags 1033 return t, nil 1034 } 1035 } 1036 1037 return "", &Error{ErrInvalidPerlOp, s[:len(s)-len(t)]} 1038 } 1039 1040 // isValidCaptureName reports whether name 1041 // is a valid capture name: [A-Za-z0-9_]+. 1042 // PCRE limits names to 32 bytes. 1043 // Python rejects names starting with digits. 1044 // We don't enforce either of those. 1045 func isValidCaptureName(name string) bool { 1046 if name == "" { 1047 return false 1048 } 1049 for _, c := range name { 1050 if c != '_' && !isalnum(c) { 1051 return false 1052 } 1053 } 1054 return true 1055 } 1056 1057 // parseInt parses a decimal integer. 1058 func (p *parser) parseInt(s string) (n int, rest string, ok bool) { 1059 if s == "" || s[0] < '0' || '9' < s[0] { 1060 return 1061 } 1062 // Disallow leading zeros. 1063 if len(s) >= 2 && s[0] == '0' && '0' <= s[1] && s[1] <= '9' { 1064 return 1065 } 1066 t := s 1067 for s != "" && '0' <= s[0] && s[0] <= '9' { 1068 s = s[1:] 1069 } 1070 rest = s 1071 ok = true 1072 // Have digits, compute value. 1073 t = t[:len(t)-len(s)] 1074 for i := 0; i < len(t); i++ { 1075 // Avoid overflow. 1076 if n >= 1e8 { 1077 n = -1 1078 break 1079 } 1080 n = n*10 + int(t[i]) - '0' 1081 } 1082 return 1083 } 1084 1085 // can this be represented as a character class? 1086 // single-rune literal string, char class, ., and .|\n. 1087 func isCharClass(re *Regexp) bool { 1088 return re.Op == OpLiteral && len(re.Rune) == 1 || 1089 re.Op == OpCharClass || 1090 re.Op == OpAnyCharNotNL || 1091 re.Op == OpAnyChar 1092 } 1093 1094 // does re match r? 1095 func matchRune(re *Regexp, r rune) bool { 1096 switch re.Op { 1097 case OpLiteral: 1098 return len(re.Rune) == 1 && re.Rune[0] == r 1099 case OpCharClass: 1100 for i := 0; i < len(re.Rune); i += 2 { 1101 if re.Rune[i] <= r && r <= re.Rune[i+1] { 1102 return true 1103 } 1104 } 1105 return false 1106 case OpAnyCharNotNL: 1107 return r != '\n' 1108 case OpAnyChar: 1109 return true 1110 } 1111 return false 1112 } 1113 1114 // parseVerticalBar handles a | in the input. 1115 func (p *parser) parseVerticalBar() error { 1116 p.concat() 1117 1118 // The concatenation we just parsed is on top of the stack. 1119 // If it sits above an opVerticalBar, swap it below 1120 // (things below an opVerticalBar become an alternation). 1121 // Otherwise, push a new vertical bar. 1122 if !p.swapVerticalBar() { 1123 p.op(opVerticalBar) 1124 } 1125 1126 return nil 1127 } 1128 1129 // mergeCharClass makes dst = dst|src. 1130 // The caller must ensure that dst.Op >= src.Op, 1131 // to reduce the amount of copying. 1132 func mergeCharClass(dst, src *Regexp) { 1133 switch dst.Op { 1134 case OpAnyChar: 1135 // src doesn't add anything. 1136 case OpAnyCharNotNL: 1137 // src might add \n 1138 if matchRune(src, '\n') { 1139 dst.Op = OpAnyChar 1140 } 1141 case OpCharClass: 1142 // src is simpler, so either literal or char class 1143 if src.Op == OpLiteral { 1144 dst.Rune = appendLiteral(dst.Rune, src.Rune[0], src.Flags) 1145 } else { 1146 dst.Rune = appendClass(dst.Rune, src.Rune) 1147 } 1148 case OpLiteral: 1149 // both literal 1150 if src.Rune[0] == dst.Rune[0] && src.Flags == dst.Flags { 1151 break 1152 } 1153 dst.Op = OpCharClass 1154 dst.Rune = appendLiteral(dst.Rune[:0], dst.Rune[0], dst.Flags) 1155 dst.Rune = appendLiteral(dst.Rune, src.Rune[0], src.Flags) 1156 } 1157 } 1158 1159 // If the top of the stack is an element followed by an opVerticalBar 1160 // swapVerticalBar swaps the two and returns true. 1161 // Otherwise it returns false. 1162 func (p *parser) swapVerticalBar() bool { 1163 // If above and below vertical bar are literal or char class, 1164 // can merge into a single char class. 1165 n := len(p.stack) 1166 if n >= 3 && p.stack[n-2].Op == opVerticalBar && isCharClass(p.stack[n-1]) && isCharClass(p.stack[n-3]) { 1167 re1 := p.stack[n-1] 1168 re3 := p.stack[n-3] 1169 // Make re3 the more complex of the two. 1170 if re1.Op > re3.Op { 1171 re1, re3 = re3, re1 1172 p.stack[n-3] = re3 1173 } 1174 mergeCharClass(re3, re1) 1175 p.reuse(re1) 1176 p.stack = p.stack[:n-1] 1177 return true 1178 } 1179 1180 if n >= 2 { 1181 re1 := p.stack[n-1] 1182 re2 := p.stack[n-2] 1183 if re2.Op == opVerticalBar { 1184 if n >= 3 { 1185 // Now out of reach. 1186 // Clean opportunistically. 1187 cleanAlt(p.stack[n-3]) 1188 } 1189 p.stack[n-2] = re1 1190 p.stack[n-1] = re2 1191 return true 1192 } 1193 } 1194 return false 1195 } 1196 1197 // parseRightParen handles a ) in the input. 1198 func (p *parser) parseRightParen() error { 1199 p.concat() 1200 if p.swapVerticalBar() { 1201 // pop vertical bar 1202 p.stack = p.stack[:len(p.stack)-1] 1203 } 1204 p.alternate() 1205 1206 n := len(p.stack) 1207 if n < 2 { 1208 return &Error{ErrUnexpectedParen, p.wholeRegexp} 1209 } 1210 re1 := p.stack[n-1] 1211 re2 := p.stack[n-2] 1212 p.stack = p.stack[:n-2] 1213 if re2.Op != opLeftParen { 1214 return &Error{ErrUnexpectedParen, p.wholeRegexp} 1215 } 1216 // Restore flags at time of paren. 1217 p.flags = re2.Flags 1218 if re2.Cap == 0 { 1219 // Just for grouping. 1220 p.push(re1) 1221 } else { 1222 re2.Op = OpCapture 1223 re2.Sub = re2.Sub0[:1] 1224 re2.Sub[0] = re1 1225 p.push(re2) 1226 } 1227 return nil 1228 } 1229 1230 // parseEscape parses an escape sequence at the beginning of s 1231 // and returns the rune. 1232 func (p *parser) parseEscape(s string) (r rune, rest string, err error) { 1233 t := s[1:] 1234 if t == "" { 1235 return 0, "", &Error{ErrTrailingBackslash, ""} 1236 } 1237 c, t, err := nextRune(t) 1238 if err != nil { 1239 return 0, "", err 1240 } 1241 1242 Switch: 1243 switch c { 1244 default: 1245 if c < utf8.RuneSelf && !isalnum(c) { 1246 // Escaped non-word characters are always themselves. 1247 // PCRE is not quite so rigorous: it accepts things like 1248 // \q, but we don't. We once rejected \_, but too many 1249 // programs and people insist on using it, so allow \_. 1250 return c, t, nil 1251 } 1252 1253 // Octal escapes. 1254 case '1', '2', '3', '4', '5', '6', '7': 1255 // Single non-zero digit is a backreference; not supported 1256 if t == "" || t[0] < '0' || t[0] > '7' { 1257 break 1258 } 1259 fallthrough 1260 case '0': 1261 // Consume up to three octal digits; already have one. 1262 r = c - '0' 1263 for i := 1; i < 3; i++ { 1264 if t == "" || t[0] < '0' || t[0] > '7' { 1265 break 1266 } 1267 r = r*8 + rune(t[0]) - '0' 1268 t = t[1:] 1269 } 1270 return r, t, nil 1271 1272 // Hexadecimal escapes. 1273 case 'x': 1274 if t == "" { 1275 break 1276 } 1277 if c, t, err = nextRune(t); err != nil { 1278 return 0, "", err 1279 } 1280 if c == '{' { 1281 // Any number of digits in braces. 1282 // Perl accepts any text at all; it ignores all text 1283 // after the first non-hex digit. We require only hex digits, 1284 // and at least one. 1285 nhex := 0 1286 r = 0 1287 for { 1288 if t == "" { 1289 break Switch 1290 } 1291 if c, t, err = nextRune(t); err != nil { 1292 return 0, "", err 1293 } 1294 if c == '}' { 1295 break 1296 } 1297 v := unhex(c) 1298 if v < 0 { 1299 break Switch 1300 } 1301 r = r*16 + v 1302 if r > unicode.MaxRune { 1303 break Switch 1304 } 1305 nhex++ 1306 } 1307 if nhex == 0 { 1308 break Switch 1309 } 1310 return r, t, nil 1311 } 1312 1313 // Easy case: two hex digits. 1314 x := unhex(c) 1315 if c, t, err = nextRune(t); err != nil { 1316 return 0, "", err 1317 } 1318 y := unhex(c) 1319 if x < 0 || y < 0 { 1320 break 1321 } 1322 return x*16 + y, t, nil 1323 1324 // C escapes. There is no case 'b', to avoid misparsing 1325 // the Perl word-boundary \b as the C backspace \b 1326 // when in POSIX mode. In Perl, /\b/ means word-boundary 1327 // but /[\b]/ means backspace. We don't support that. 1328 // If you want a backspace, embed a literal backspace 1329 // character or use \x08. 1330 case 'a': 1331 return '\a', t, err 1332 case 'f': 1333 return '\f', t, err 1334 case 'n': 1335 return '\n', t, err 1336 case 'r': 1337 return '\r', t, err 1338 case 't': 1339 return '\t', t, err 1340 case 'v': 1341 return '\v', t, err 1342 } 1343 return 0, "", &Error{ErrInvalidEscape, s[:len(s)-len(t)]} 1344 } 1345 1346 // parseClassChar parses a character class character at the beginning of s 1347 // and returns it. 1348 func (p *parser) parseClassChar(s, wholeClass string) (r rune, rest string, err error) { 1349 if s == "" { 1350 return 0, "", &Error{Code: ErrMissingBracket, Expr: wholeClass} 1351 } 1352 1353 // Allow regular escape sequences even though 1354 // many need not be escaped in this context. 1355 if s[0] == '\\' { 1356 return p.parseEscape(s) 1357 } 1358 1359 return nextRune(s) 1360 } 1361 1362 type charGroup struct { 1363 sign int 1364 class []rune 1365 } 1366 1367 // parsePerlClassEscape parses a leading Perl character class escape like \d 1368 // from the beginning of s. If one is present, it appends the characters to r 1369 // and returns the new slice r and the remainder of the string. 1370 func (p *parser) parsePerlClassEscape(s string, r []rune) (out []rune, rest string) { 1371 if p.flags&PerlX == 0 || len(s) < 2 || s[0] != '\\' { 1372 return 1373 } 1374 g := perlGroup[s[0:2]] 1375 if g.sign == 0 { 1376 return 1377 } 1378 return p.appendGroup(r, g), s[2:] 1379 } 1380 1381 // parseNamedClass parses a leading POSIX named character class like [:alnum:] 1382 // from the beginning of s. If one is present, it appends the characters to r 1383 // and returns the new slice r and the remainder of the string. 1384 func (p *parser) parseNamedClass(s string, r []rune) (out []rune, rest string, err error) { 1385 if len(s) < 2 || s[0] != '[' || s[1] != ':' { 1386 return 1387 } 1388 1389 i := strings.Index(s[2:], ":]") 1390 if i < 0 { 1391 return 1392 } 1393 i += 2 1394 name, s := s[0:i+2], s[i+2:] 1395 g := posixGroup[name] 1396 if g.sign == 0 { 1397 return nil, "", &Error{ErrInvalidCharRange, name} 1398 } 1399 return p.appendGroup(r, g), s, nil 1400 } 1401 1402 func (p *parser) appendGroup(r []rune, g charGroup) []rune { 1403 if p.flags&FoldCase == 0 { 1404 if g.sign < 0 { 1405 r = appendNegatedClass(r, g.class) 1406 } else { 1407 r = appendClass(r, g.class) 1408 } 1409 } else { 1410 tmp := p.tmpClass[:0] 1411 tmp = appendFoldedClass(tmp, g.class) 1412 p.tmpClass = tmp 1413 tmp = cleanClass(&p.tmpClass) 1414 if g.sign < 0 { 1415 r = appendNegatedClass(r, tmp) 1416 } else { 1417 r = appendClass(r, tmp) 1418 } 1419 } 1420 return r 1421 } 1422 1423 var anyTable = &unicode.RangeTable{ 1424 R16: []unicode.Range16{{Lo: 0, Hi: 1<<16 - 1, Stride: 1}}, 1425 R32: []unicode.Range32{{Lo: 1 << 16, Hi: unicode.MaxRune, Stride: 1}}, 1426 } 1427 1428 // unicodeTable returns the unicode.RangeTable identified by name 1429 // and the table of additional fold-equivalent code points. 1430 func unicodeTable(name string) (*unicode.RangeTable, *unicode.RangeTable) { 1431 // Special case: "Any" means any. 1432 if name == "Any" { 1433 return anyTable, anyTable 1434 } 1435 if t := unicode.Categories[name]; t != nil { 1436 return t, unicode.FoldCategory[name] 1437 } 1438 if t := unicode.Scripts[name]; t != nil { 1439 return t, unicode.FoldScript[name] 1440 } 1441 return nil, nil 1442 } 1443 1444 // parseUnicodeClass parses a leading Unicode character class like \p{Han} 1445 // from the beginning of s. If one is present, it appends the characters to r 1446 // and returns the new slice r and the remainder of the string. 1447 func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, err error) { 1448 if p.flags&UnicodeGroups == 0 || len(s) < 2 || s[0] != '\\' || s[1] != 'p' && s[1] != 'P' { 1449 return 1450 } 1451 1452 // Committed to parse or return error. 1453 sign := +1 1454 if s[1] == 'P' { 1455 sign = -1 1456 } 1457 t := s[2:] 1458 c, t, err := nextRune(t) 1459 if err != nil { 1460 return 1461 } 1462 var seq, name string 1463 if c != '{' { 1464 // Single-letter name. 1465 seq = s[:len(s)-len(t)] 1466 name = seq[2:] 1467 } else { 1468 // Name is in braces. 1469 end := strings.IndexRune(s, '}') 1470 if end < 0 { 1471 if err = checkUTF8(s); err != nil { 1472 return 1473 } 1474 return nil, "", &Error{ErrInvalidCharRange, s} 1475 } 1476 seq, t = s[:end+1], s[end+1:] 1477 name = s[3:end] 1478 if err = checkUTF8(name); err != nil { 1479 return 1480 } 1481 } 1482 1483 // Group can have leading negation too. \p{^Han} == \P{Han}, \P{^Han} == \p{Han}. 1484 if name != "" && name[0] == '^' { 1485 sign = -sign 1486 name = name[1:] 1487 } 1488 1489 tab, fold := unicodeTable(name) 1490 if tab == nil { 1491 return nil, "", &Error{ErrInvalidCharRange, seq} 1492 } 1493 1494 if p.flags&FoldCase == 0 || fold == nil { 1495 if sign > 0 { 1496 r = appendTable(r, tab) 1497 } else { 1498 r = appendNegatedTable(r, tab) 1499 } 1500 } else { 1501 // Merge and clean tab and fold in a temporary buffer. 1502 // This is necessary for the negative case and just tidy 1503 // for the positive case. 1504 tmp := p.tmpClass[:0] 1505 tmp = appendTable(tmp, tab) 1506 tmp = appendTable(tmp, fold) 1507 p.tmpClass = tmp 1508 tmp = cleanClass(&p.tmpClass) 1509 if sign > 0 { 1510 r = appendClass(r, tmp) 1511 } else { 1512 r = appendNegatedClass(r, tmp) 1513 } 1514 } 1515 return r, t, nil 1516 } 1517 1518 // parseClass parses a character class at the beginning of s 1519 // and pushes it onto the parse stack. 1520 func (p *parser) parseClass(s string) (rest string, err error) { 1521 t := s[1:] // chop [ 1522 re := p.newRegexp(OpCharClass) 1523 re.Flags = p.flags 1524 re.Rune = re.Rune0[:0] 1525 1526 sign := +1 1527 if t != "" && t[0] == '^' { 1528 sign = -1 1529 t = t[1:] 1530 1531 // If character class does not match \n, add it here, 1532 // so that negation later will do the right thing. 1533 if p.flags&ClassNL == 0 { 1534 re.Rune = append(re.Rune, '\n', '\n') 1535 } 1536 } 1537 1538 class := re.Rune 1539 first := true // ] and - are okay as first char in class 1540 for t == "" || t[0] != ']' || first { 1541 // POSIX: - is only okay unescaped as first or last in class. 1542 // Perl: - is okay anywhere. 1543 if t != "" && t[0] == '-' && p.flags&PerlX == 0 && !first && (len(t) == 1 || t[1] != ']') { 1544 _, size := utf8.DecodeRuneInString(t[1:]) 1545 return "", &Error{Code: ErrInvalidCharRange, Expr: t[:1+size]} 1546 } 1547 first = false 1548 1549 // Look for POSIX [:alnum:] etc. 1550 if len(t) > 2 && t[0] == '[' && t[1] == ':' { 1551 nclass, nt, err := p.parseNamedClass(t, class) 1552 if err != nil { 1553 return "", err 1554 } 1555 if nclass != nil { 1556 class, t = nclass, nt 1557 continue 1558 } 1559 } 1560 1561 // Look for Unicode character group like \p{Han}. 1562 nclass, nt, err := p.parseUnicodeClass(t, class) 1563 if err != nil { 1564 return "", err 1565 } 1566 if nclass != nil { 1567 class, t = nclass, nt 1568 continue 1569 } 1570 1571 // Look for Perl character class symbols (extension). 1572 if nclass, nt := p.parsePerlClassEscape(t, class); nclass != nil { 1573 class, t = nclass, nt 1574 continue 1575 } 1576 1577 // Single character or simple range. 1578 rng := t 1579 var lo, hi rune 1580 if lo, t, err = p.parseClassChar(t, s); err != nil { 1581 return "", err 1582 } 1583 hi = lo 1584 // [a-] means (a|-) so check for final ]. 1585 if len(t) >= 2 && t[0] == '-' && t[1] != ']' { 1586 t = t[1:] 1587 if hi, t, err = p.parseClassChar(t, s); err != nil { 1588 return "", err 1589 } 1590 if hi < lo { 1591 rng = rng[:len(rng)-len(t)] 1592 return "", &Error{Code: ErrInvalidCharRange, Expr: rng} 1593 } 1594 } 1595 if p.flags&FoldCase == 0 { 1596 class = appendRange(class, lo, hi) 1597 } else { 1598 class = appendFoldedRange(class, lo, hi) 1599 } 1600 } 1601 t = t[1:] // chop ] 1602 1603 // Use &re.Rune instead of &class to avoid allocation. 1604 re.Rune = class 1605 class = cleanClass(&re.Rune) 1606 if sign < 0 { 1607 class = negateClass(class) 1608 } 1609 re.Rune = class 1610 p.push(re) 1611 return t, nil 1612 } 1613 1614 // cleanClass sorts the ranges (pairs of elements of r), 1615 // merges them, and eliminates duplicates. 1616 func cleanClass(rp *[]rune) []rune { 1617 1618 // Sort by lo increasing, hi decreasing to break ties. 1619 sort.Sort(ranges{rp}) 1620 1621 r := *rp 1622 if len(r) < 2 { 1623 return r 1624 } 1625 1626 // Merge abutting, overlapping. 1627 w := 2 // write index 1628 for i := 2; i < len(r); i += 2 { 1629 lo, hi := r[i], r[i+1] 1630 if lo <= r[w-1]+1 { 1631 // merge with previous range 1632 if hi > r[w-1] { 1633 r[w-1] = hi 1634 } 1635 continue 1636 } 1637 // new disjoint range 1638 r[w] = lo 1639 r[w+1] = hi 1640 w += 2 1641 } 1642 1643 return r[:w] 1644 } 1645 1646 // appendLiteral returns the result of appending the literal x to the class r. 1647 func appendLiteral(r []rune, x rune, flags Flags) []rune { 1648 if flags&FoldCase != 0 { 1649 return appendFoldedRange(r, x, x) 1650 } 1651 return appendRange(r, x, x) 1652 } 1653 1654 // appendRange returns the result of appending the range lo-hi to the class r. 1655 func appendRange(r []rune, lo, hi rune) []rune { 1656 // Expand last range or next to last range if it overlaps or abuts. 1657 // Checking two ranges helps when appending case-folded 1658 // alphabets, so that one range can be expanding A-Z and the 1659 // other expanding a-z. 1660 n := len(r) 1661 for i := 2; i <= 4; i += 2 { // twice, using i=2, i=4 1662 if n >= i { 1663 rlo, rhi := r[n-i], r[n-i+1] 1664 if lo <= rhi+1 && rlo <= hi+1 { 1665 if lo < rlo { 1666 r[n-i] = lo 1667 } 1668 if hi > rhi { 1669 r[n-i+1] = hi 1670 } 1671 return r 1672 } 1673 } 1674 } 1675 1676 return append(r, lo, hi) 1677 } 1678 1679 const ( 1680 // minimum and maximum runes involved in folding. 1681 // checked during test. 1682 minFold = 0x0041 1683 maxFold = 0x1e943 1684 ) 1685 1686 // appendFoldedRange returns the result of appending the range lo-hi 1687 // and its case folding-equivalent runes to the class r. 1688 func appendFoldedRange(r []rune, lo, hi rune) []rune { 1689 // Optimizations. 1690 if lo <= minFold && hi >= maxFold { 1691 // Range is full: folding can't add more. 1692 return appendRange(r, lo, hi) 1693 } 1694 if hi < minFold || lo > maxFold { 1695 // Range is outside folding possibilities. 1696 return appendRange(r, lo, hi) 1697 } 1698 if lo < minFold { 1699 // [lo, minFold-1] needs no folding. 1700 r = appendRange(r, lo, minFold-1) 1701 lo = minFold 1702 } 1703 if hi > maxFold { 1704 // [maxFold+1, hi] needs no folding. 1705 r = appendRange(r, maxFold+1, hi) 1706 hi = maxFold 1707 } 1708 1709 // Brute force. Depend on appendRange to coalesce ranges on the fly. 1710 for c := lo; c <= hi; c++ { 1711 r = appendRange(r, c, c) 1712 f := unicode.SimpleFold(c) 1713 for f != c { 1714 r = appendRange(r, f, f) 1715 f = unicode.SimpleFold(f) 1716 } 1717 } 1718 return r 1719 } 1720 1721 // appendClass returns the result of appending the class x to the class r. 1722 // It assume x is clean. 1723 func appendClass(r []rune, x []rune) []rune { 1724 for i := 0; i < len(x); i += 2 { 1725 r = appendRange(r, x[i], x[i+1]) 1726 } 1727 return r 1728 } 1729 1730 // appendFolded returns the result of appending the case folding of the class x to the class r. 1731 func appendFoldedClass(r []rune, x []rune) []rune { 1732 for i := 0; i < len(x); i += 2 { 1733 r = appendFoldedRange(r, x[i], x[i+1]) 1734 } 1735 return r 1736 } 1737 1738 // appendNegatedClass returns the result of appending the negation of the class x to the class r. 1739 // It assumes x is clean. 1740 func appendNegatedClass(r []rune, x []rune) []rune { 1741 nextLo := '\u0000' 1742 for i := 0; i < len(x); i += 2 { 1743 lo, hi := x[i], x[i+1] 1744 if nextLo <= lo-1 { 1745 r = appendRange(r, nextLo, lo-1) 1746 } 1747 nextLo = hi + 1 1748 } 1749 if nextLo <= unicode.MaxRune { 1750 r = appendRange(r, nextLo, unicode.MaxRune) 1751 } 1752 return r 1753 } 1754 1755 // appendTable returns the result of appending x to the class r. 1756 func appendTable(r []rune, x *unicode.RangeTable) []rune { 1757 for _, xr := range x.R16 { 1758 lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride) 1759 if stride == 1 { 1760 r = appendRange(r, lo, hi) 1761 continue 1762 } 1763 for c := lo; c <= hi; c += stride { 1764 r = appendRange(r, c, c) 1765 } 1766 } 1767 for _, xr := range x.R32 { 1768 lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride) 1769 if stride == 1 { 1770 r = appendRange(r, lo, hi) 1771 continue 1772 } 1773 for c := lo; c <= hi; c += stride { 1774 r = appendRange(r, c, c) 1775 } 1776 } 1777 return r 1778 } 1779 1780 // appendNegatedTable returns the result of appending the negation of x to the class r. 1781 func appendNegatedTable(r []rune, x *unicode.RangeTable) []rune { 1782 nextLo := '\u0000' // lo end of next class to add 1783 for _, xr := range x.R16 { 1784 lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride) 1785 if stride == 1 { 1786 if nextLo <= lo-1 { 1787 r = appendRange(r, nextLo, lo-1) 1788 } 1789 nextLo = hi + 1 1790 continue 1791 } 1792 for c := lo; c <= hi; c += stride { 1793 if nextLo <= c-1 { 1794 r = appendRange(r, nextLo, c-1) 1795 } 1796 nextLo = c + 1 1797 } 1798 } 1799 for _, xr := range x.R32 { 1800 lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride) 1801 if stride == 1 { 1802 if nextLo <= lo-1 { 1803 r = appendRange(r, nextLo, lo-1) 1804 } 1805 nextLo = hi + 1 1806 continue 1807 } 1808 for c := lo; c <= hi; c += stride { 1809 if nextLo <= c-1 { 1810 r = appendRange(r, nextLo, c-1) 1811 } 1812 nextLo = c + 1 1813 } 1814 } 1815 if nextLo <= unicode.MaxRune { 1816 r = appendRange(r, nextLo, unicode.MaxRune) 1817 } 1818 return r 1819 } 1820 1821 // negateClass overwrites r and returns r's negation. 1822 // It assumes the class r is already clean. 1823 func negateClass(r []rune) []rune { 1824 nextLo := '\u0000' // lo end of next class to add 1825 w := 0 // write index 1826 for i := 0; i < len(r); i += 2 { 1827 lo, hi := r[i], r[i+1] 1828 if nextLo <= lo-1 { 1829 r[w] = nextLo 1830 r[w+1] = lo - 1 1831 w += 2 1832 } 1833 nextLo = hi + 1 1834 } 1835 r = r[:w] 1836 if nextLo <= unicode.MaxRune { 1837 // It's possible for the negation to have one more 1838 // range - this one - than the original class, so use append. 1839 r = append(r, nextLo, unicode.MaxRune) 1840 } 1841 return r 1842 } 1843 1844 // ranges implements sort.Interface on a []rune. 1845 // The choice of receiver type definition is strange 1846 // but avoids an allocation since we already have 1847 // a *[]rune. 1848 type ranges struct { 1849 p *[]rune 1850 } 1851 1852 func (ra ranges) Less(i, j int) bool { 1853 p := *ra.p 1854 i *= 2 1855 j *= 2 1856 return p[i] < p[j] || p[i] == p[j] && p[i+1] > p[j+1] 1857 } 1858 1859 func (ra ranges) Len() int { 1860 return len(*ra.p) / 2 1861 } 1862 1863 func (ra ranges) Swap(i, j int) { 1864 p := *ra.p 1865 i *= 2 1866 j *= 2 1867 p[i], p[i+1], p[j], p[j+1] = p[j], p[j+1], p[i], p[i+1] 1868 } 1869 1870 func checkUTF8(s string) error { 1871 for s != "" { 1872 rune, size := utf8.DecodeRuneInString(s) 1873 if rune == utf8.RuneError && size == 1 { 1874 return &Error{Code: ErrInvalidUTF8, Expr: s} 1875 } 1876 s = s[size:] 1877 } 1878 return nil 1879 } 1880 1881 func nextRune(s string) (c rune, t string, err error) { 1882 c, size := utf8.DecodeRuneInString(s) 1883 if c == utf8.RuneError && size == 1 { 1884 return 0, "", &Error{Code: ErrInvalidUTF8, Expr: s} 1885 } 1886 return c, s[size:], nil 1887 } 1888 1889 func isalnum(c rune) bool { 1890 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' 1891 } 1892 1893 func unhex(c rune) rune { 1894 if '0' <= c && c <= '9' { 1895 return c - '0' 1896 } 1897 if 'a' <= c && c <= 'f' { 1898 return c - 'a' + 10 1899 } 1900 if 'A' <= c && c <= 'F' { 1901 return c - 'A' + 10 1902 } 1903 return -1 1904 }