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