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