Home | History | Annotate | Download | only in syntax
      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 					p.push(literalRegexp(lit, p.flags))
    834 					break BigSwitch
    835 				case 'z':
    836 					p.op(OpEndText)
    837 					t = t[2:]
    838 					break BigSwitch
    839 				}
    840 			}
    841 
    842 			re := p.newRegexp(OpCharClass)
    843 			re.Flags = p.flags
    844 
    845 			// Look for Unicode character group like \p{Han}
    846 			if len(t) >= 2 && (t[1] == 'p' || t[1] == 'P') {
    847 				r, rest, err := p.parseUnicodeClass(t, re.Rune0[:0])
    848 				if err != nil {
    849 					return nil, err
    850 				}
    851 				if r != nil {
    852 					re.Rune = r
    853 					t = rest
    854 					p.push(re)
    855 					break BigSwitch
    856 				}
    857 			}
    858 
    859 			// Perl character class escape.
    860 			if r, rest := p.parsePerlClassEscape(t, re.Rune0[:0]); r != nil {
    861 				re.Rune = r
    862 				t = rest
    863 				p.push(re)
    864 				break BigSwitch
    865 			}
    866 			p.reuse(re)
    867 
    868 			// Ordinary single-character escape.
    869 			if c, t, err = p.parseEscape(t); err != nil {
    870 				return nil, err
    871 			}
    872 			p.literal(c)
    873 		}
    874 		lastRepeat = repeat
    875 	}
    876 
    877 	p.concat()
    878 	if p.swapVerticalBar() {
    879 		// pop vertical bar
    880 		p.stack = p.stack[:len(p.stack)-1]
    881 	}
    882 	p.alternate()
    883 
    884 	n := len(p.stack)
    885 	if n != 1 {
    886 		return nil, &Error{ErrMissingParen, s}
    887 	}
    888 	return p.stack[0], nil
    889 }
    890 
    891 // parseRepeat parses {min} (max=min) or {min,} (max=-1) or {min,max}.
    892 // If s is not of that form, it returns ok == false.
    893 // If s has the right form but the values are too big, it returns min == -1, ok == true.
    894 func (p *parser) parseRepeat(s string) (min, max int, rest string, ok bool) {
    895 	if s == "" || s[0] != '{' {
    896 		return
    897 	}
    898 	s = s[1:]
    899 	var ok1 bool
    900 	if min, s, ok1 = p.parseInt(s); !ok1 {
    901 		return
    902 	}
    903 	if s == "" {
    904 		return
    905 	}
    906 	if s[0] != ',' {
    907 		max = min
    908 	} else {
    909 		s = s[1:]
    910 		if s == "" {
    911 			return
    912 		}
    913 		if s[0] == '}' {
    914 			max = -1
    915 		} else if max, s, ok1 = p.parseInt(s); !ok1 {
    916 			return
    917 		} else if max < 0 {
    918 			// parseInt found too big a number
    919 			min = -1
    920 		}
    921 	}
    922 	if s == "" || s[0] != '}' {
    923 		return
    924 	}
    925 	rest = s[1:]
    926 	ok = true
    927 	return
    928 }
    929 
    930 // parsePerlFlags parses a Perl flag setting or non-capturing group or both,
    931 // like (?i) or (?: or (?i:.  It removes the prefix from s and updates the parse state.
    932 // The caller must have ensured that s begins with "(?".
    933 func (p *parser) parsePerlFlags(s string) (rest string, err error) {
    934 	t := s
    935 
    936 	// Check for named captures, first introduced in Python's regexp library.
    937 	// As usual, there are three slightly different syntaxes:
    938 	//
    939 	//   (?P<name>expr)   the original, introduced by Python
    940 	//   (?<name>expr)    the .NET alteration, adopted by Perl 5.10
    941 	//   (?'name'expr)    another .NET alteration, adopted by Perl 5.10
    942 	//
    943 	// Perl 5.10 gave in and implemented the Python version too,
    944 	// but they claim that the last two are the preferred forms.
    945 	// PCRE and languages based on it (specifically, PHP and Ruby)
    946 	// support all three as well.  EcmaScript 4 uses only the Python form.
    947 	//
    948 	// In both the open source world (via Code Search) and the
    949 	// Google source tree, (?P<expr>name) is the dominant form,
    950 	// so that's the one we implement.  One is enough.
    951 	if len(t) > 4 && t[2] == 'P' && t[3] == '<' {
    952 		// Pull out name.
    953 		end := strings.IndexRune(t, '>')
    954 		if end < 0 {
    955 			if err = checkUTF8(t); err != nil {
    956 				return "", err
    957 			}
    958 			return "", &Error{ErrInvalidNamedCapture, s}
    959 		}
    960 
    961 		capture := t[:end+1] // "(?P<name>"
    962 		name := t[4:end]     // "name"
    963 		if err = checkUTF8(name); err != nil {
    964 			return "", err
    965 		}
    966 		if !isValidCaptureName(name) {
    967 			return "", &Error{ErrInvalidNamedCapture, capture}
    968 		}
    969 
    970 		// Like ordinary capture, but named.
    971 		p.numCap++
    972 		re := p.op(opLeftParen)
    973 		re.Cap = p.numCap
    974 		re.Name = name
    975 		return t[end+1:], nil
    976 	}
    977 
    978 	// Non-capturing group.  Might also twiddle Perl flags.
    979 	var c rune
    980 	t = t[2:] // skip (?
    981 	flags := p.flags
    982 	sign := +1
    983 	sawFlag := false
    984 Loop:
    985 	for t != "" {
    986 		if c, t, err = nextRune(t); err != nil {
    987 			return "", err
    988 		}
    989 		switch c {
    990 		default:
    991 			break Loop
    992 
    993 		// Flags.
    994 		case 'i':
    995 			flags |= FoldCase
    996 			sawFlag = true
    997 		case 'm':
    998 			flags &^= OneLine
    999 			sawFlag = true
   1000 		case 's':
   1001 			flags |= DotNL
   1002 			sawFlag = true
   1003 		case 'U':
   1004 			flags |= NonGreedy
   1005 			sawFlag = true
   1006 
   1007 		// Switch to negation.
   1008 		case '-':
   1009 			if sign < 0 {
   1010 				break Loop
   1011 			}
   1012 			sign = -1
   1013 			// Invert flags so that | above turn into &^ and vice versa.
   1014 			// We'll invert flags again before using it below.
   1015 			flags = ^flags
   1016 			sawFlag = false
   1017 
   1018 		// End of flags, starting group or not.
   1019 		case ':', ')':
   1020 			if sign < 0 {
   1021 				if !sawFlag {
   1022 					break Loop
   1023 				}
   1024 				flags = ^flags
   1025 			}
   1026 			if c == ':' {
   1027 				// Open new group
   1028 				p.op(opLeftParen)
   1029 			}
   1030 			p.flags = flags
   1031 			return t, nil
   1032 		}
   1033 	}
   1034 
   1035 	return "", &Error{ErrInvalidPerlOp, s[:len(s)-len(t)]}
   1036 }
   1037 
   1038 // isValidCaptureName reports whether name
   1039 // is a valid capture name: [A-Za-z0-9_]+.
   1040 // PCRE limits names to 32 bytes.
   1041 // Python rejects names starting with digits.
   1042 // We don't enforce either of those.
   1043 func isValidCaptureName(name string) bool {
   1044 	if name == "" {
   1045 		return false
   1046 	}
   1047 	for _, c := range name {
   1048 		if c != '_' && !isalnum(c) {
   1049 			return false
   1050 		}
   1051 	}
   1052 	return true
   1053 }
   1054 
   1055 // parseInt parses a decimal integer.
   1056 func (p *parser) parseInt(s string) (n int, rest string, ok bool) {
   1057 	if s == "" || s[0] < '0' || '9' < s[0] {
   1058 		return
   1059 	}
   1060 	// Disallow leading zeros.
   1061 	if len(s) >= 2 && s[0] == '0' && '0' <= s[1] && s[1] <= '9' {
   1062 		return
   1063 	}
   1064 	t := s
   1065 	for s != "" && '0' <= s[0] && s[0] <= '9' {
   1066 		s = s[1:]
   1067 	}
   1068 	rest = s
   1069 	ok = true
   1070 	// Have digits, compute value.
   1071 	t = t[:len(t)-len(s)]
   1072 	for i := 0; i < len(t); i++ {
   1073 		// Avoid overflow.
   1074 		if n >= 1e8 {
   1075 			n = -1
   1076 			break
   1077 		}
   1078 		n = n*10 + int(t[i]) - '0'
   1079 	}
   1080 	return
   1081 }
   1082 
   1083 // can this be represented as a character class?
   1084 // single-rune literal string, char class, ., and .|\n.
   1085 func isCharClass(re *Regexp) bool {
   1086 	return re.Op == OpLiteral && len(re.Rune) == 1 ||
   1087 		re.Op == OpCharClass ||
   1088 		re.Op == OpAnyCharNotNL ||
   1089 		re.Op == OpAnyChar
   1090 }
   1091 
   1092 // does re match r?
   1093 func matchRune(re *Regexp, r rune) bool {
   1094 	switch re.Op {
   1095 	case OpLiteral:
   1096 		return len(re.Rune) == 1 && re.Rune[0] == r
   1097 	case OpCharClass:
   1098 		for i := 0; i < len(re.Rune); i += 2 {
   1099 			if re.Rune[i] <= r && r <= re.Rune[i+1] {
   1100 				return true
   1101 			}
   1102 		}
   1103 		return false
   1104 	case OpAnyCharNotNL:
   1105 		return r != '\n'
   1106 	case OpAnyChar:
   1107 		return true
   1108 	}
   1109 	return false
   1110 }
   1111 
   1112 // parseVerticalBar handles a | in the input.
   1113 func (p *parser) parseVerticalBar() error {
   1114 	p.concat()
   1115 
   1116 	// The concatenation we just parsed is on top of the stack.
   1117 	// If it sits above an opVerticalBar, swap it below
   1118 	// (things below an opVerticalBar become an alternation).
   1119 	// Otherwise, push a new vertical bar.
   1120 	if !p.swapVerticalBar() {
   1121 		p.op(opVerticalBar)
   1122 	}
   1123 
   1124 	return nil
   1125 }
   1126 
   1127 // mergeCharClass makes dst = dst|src.
   1128 // The caller must ensure that dst.Op >= src.Op,
   1129 // to reduce the amount of copying.
   1130 func mergeCharClass(dst, src *Regexp) {
   1131 	switch dst.Op {
   1132 	case OpAnyChar:
   1133 		// src doesn't add anything.
   1134 	case OpAnyCharNotNL:
   1135 		// src might add \n
   1136 		if matchRune(src, '\n') {
   1137 			dst.Op = OpAnyChar
   1138 		}
   1139 	case OpCharClass:
   1140 		// src is simpler, so either literal or char class
   1141 		if src.Op == OpLiteral {
   1142 			dst.Rune = appendLiteral(dst.Rune, src.Rune[0], src.Flags)
   1143 		} else {
   1144 			dst.Rune = appendClass(dst.Rune, src.Rune)
   1145 		}
   1146 	case OpLiteral:
   1147 		// both literal
   1148 		if src.Rune[0] == dst.Rune[0] && src.Flags == dst.Flags {
   1149 			break
   1150 		}
   1151 		dst.Op = OpCharClass
   1152 		dst.Rune = appendLiteral(dst.Rune[:0], dst.Rune[0], dst.Flags)
   1153 		dst.Rune = appendLiteral(dst.Rune, src.Rune[0], src.Flags)
   1154 	}
   1155 }
   1156 
   1157 // If the top of the stack is an element followed by an opVerticalBar
   1158 // swapVerticalBar swaps the two and returns true.
   1159 // Otherwise it returns false.
   1160 func (p *parser) swapVerticalBar() bool {
   1161 	// If above and below vertical bar are literal or char class,
   1162 	// can merge into a single char class.
   1163 	n := len(p.stack)
   1164 	if n >= 3 && p.stack[n-2].Op == opVerticalBar && isCharClass(p.stack[n-1]) && isCharClass(p.stack[n-3]) {
   1165 		re1 := p.stack[n-1]
   1166 		re3 := p.stack[n-3]
   1167 		// Make re3 the more complex of the two.
   1168 		if re1.Op > re3.Op {
   1169 			re1, re3 = re3, re1
   1170 			p.stack[n-3] = re3
   1171 		}
   1172 		mergeCharClass(re3, re1)
   1173 		p.reuse(re1)
   1174 		p.stack = p.stack[:n-1]
   1175 		return true
   1176 	}
   1177 
   1178 	if n >= 2 {
   1179 		re1 := p.stack[n-1]
   1180 		re2 := p.stack[n-2]
   1181 		if re2.Op == opVerticalBar {
   1182 			if n >= 3 {
   1183 				// Now out of reach.
   1184 				// Clean opportunistically.
   1185 				cleanAlt(p.stack[n-3])
   1186 			}
   1187 			p.stack[n-2] = re1
   1188 			p.stack[n-1] = re2
   1189 			return true
   1190 		}
   1191 	}
   1192 	return false
   1193 }
   1194 
   1195 // parseRightParen handles a ) in the input.
   1196 func (p *parser) parseRightParen() error {
   1197 	p.concat()
   1198 	if p.swapVerticalBar() {
   1199 		// pop vertical bar
   1200 		p.stack = p.stack[:len(p.stack)-1]
   1201 	}
   1202 	p.alternate()
   1203 
   1204 	n := len(p.stack)
   1205 	if n < 2 {
   1206 		return &Error{ErrUnexpectedParen, p.wholeRegexp}
   1207 	}
   1208 	re1 := p.stack[n-1]
   1209 	re2 := p.stack[n-2]
   1210 	p.stack = p.stack[:n-2]
   1211 	if re2.Op != opLeftParen {
   1212 		return &Error{ErrUnexpectedParen, p.wholeRegexp}
   1213 	}
   1214 	// Restore flags at time of paren.
   1215 	p.flags = re2.Flags
   1216 	if re2.Cap == 0 {
   1217 		// Just for grouping.
   1218 		p.push(re1)
   1219 	} else {
   1220 		re2.Op = OpCapture
   1221 		re2.Sub = re2.Sub0[:1]
   1222 		re2.Sub[0] = re1
   1223 		p.push(re2)
   1224 	}
   1225 	return nil
   1226 }
   1227 
   1228 // parseEscape parses an escape sequence at the beginning of s
   1229 // and returns the rune.
   1230 func (p *parser) parseEscape(s string) (r rune, rest string, err error) {
   1231 	t := s[1:]
   1232 	if t == "" {
   1233 		return 0, "", &Error{ErrTrailingBackslash, ""}
   1234 	}
   1235 	c, t, err := nextRune(t)
   1236 	if err != nil {
   1237 		return 0, "", err
   1238 	}
   1239 
   1240 Switch:
   1241 	switch c {
   1242 	default:
   1243 		if c < utf8.RuneSelf && !isalnum(c) {
   1244 			// Escaped non-word characters are always themselves.
   1245 			// PCRE is not quite so rigorous: it accepts things like
   1246 			// \q, but we don't.  We once rejected \_, but too many
   1247 			// programs and people insist on using it, so allow \_.
   1248 			return c, t, nil
   1249 		}
   1250 
   1251 	// Octal escapes.
   1252 	case '1', '2', '3', '4', '5', '6', '7':
   1253 		// Single non-zero digit is a backreference; not supported
   1254 		if t == "" || t[0] < '0' || t[0] > '7' {
   1255 			break
   1256 		}
   1257 		fallthrough
   1258 	case '0':
   1259 		// Consume up to three octal digits; already have one.
   1260 		r = c - '0'
   1261 		for i := 1; i < 3; i++ {
   1262 			if t == "" || t[0] < '0' || t[0] > '7' {
   1263 				break
   1264 			}
   1265 			r = r*8 + rune(t[0]) - '0'
   1266 			t = t[1:]
   1267 		}
   1268 		return r, t, nil
   1269 
   1270 	// Hexadecimal escapes.
   1271 	case 'x':
   1272 		if t == "" {
   1273 			break
   1274 		}
   1275 		if c, t, err = nextRune(t); err != nil {
   1276 			return 0, "", err
   1277 		}
   1278 		if c == '{' {
   1279 			// Any number of digits in braces.
   1280 			// Perl accepts any text at all; it ignores all text
   1281 			// after the first non-hex digit.  We require only hex digits,
   1282 			// and at least one.
   1283 			nhex := 0
   1284 			r = 0
   1285 			for {
   1286 				if t == "" {
   1287 					break Switch
   1288 				}
   1289 				if c, t, err = nextRune(t); err != nil {
   1290 					return 0, "", err
   1291 				}
   1292 				if c == '}' {
   1293 					break
   1294 				}
   1295 				v := unhex(c)
   1296 				if v < 0 {
   1297 					break Switch
   1298 				}
   1299 				r = r*16 + v
   1300 				if r > unicode.MaxRune {
   1301 					break Switch
   1302 				}
   1303 				nhex++
   1304 			}
   1305 			if nhex == 0 {
   1306 				break Switch
   1307 			}
   1308 			return r, t, nil
   1309 		}
   1310 
   1311 		// Easy case: two hex digits.
   1312 		x := unhex(c)
   1313 		if c, t, err = nextRune(t); err != nil {
   1314 			return 0, "", err
   1315 		}
   1316 		y := unhex(c)
   1317 		if x < 0 || y < 0 {
   1318 			break
   1319 		}
   1320 		return x*16 + y, t, nil
   1321 
   1322 	// C escapes.  There is no case 'b', to avoid misparsing
   1323 	// the Perl word-boundary \b as the C backspace \b
   1324 	// when in POSIX mode.  In Perl, /\b/ means word-boundary
   1325 	// but /[\b]/ means backspace.  We don't support that.
   1326 	// If you want a backspace, embed a literal backspace
   1327 	// character or use \x08.
   1328 	case 'a':
   1329 		return '\a', t, err
   1330 	case 'f':
   1331 		return '\f', t, err
   1332 	case 'n':
   1333 		return '\n', t, err
   1334 	case 'r':
   1335 		return '\r', t, err
   1336 	case 't':
   1337 		return '\t', t, err
   1338 	case 'v':
   1339 		return '\v', t, err
   1340 	}
   1341 	return 0, "", &Error{ErrInvalidEscape, s[:len(s)-len(t)]}
   1342 }
   1343 
   1344 // parseClassChar parses a character class character at the beginning of s
   1345 // and returns it.
   1346 func (p *parser) parseClassChar(s, wholeClass string) (r rune, rest string, err error) {
   1347 	if s == "" {
   1348 		return 0, "", &Error{Code: ErrMissingBracket, Expr: wholeClass}
   1349 	}
   1350 
   1351 	// Allow regular escape sequences even though
   1352 	// many need not be escaped in this context.
   1353 	if s[0] == '\\' {
   1354 		return p.parseEscape(s)
   1355 	}
   1356 
   1357 	return nextRune(s)
   1358 }
   1359 
   1360 type charGroup struct {
   1361 	sign  int
   1362 	class []rune
   1363 }
   1364 
   1365 // parsePerlClassEscape parses a leading Perl character class escape like \d
   1366 // from the beginning of s.  If one is present, it appends the characters to r
   1367 // and returns the new slice r and the remainder of the string.
   1368 func (p *parser) parsePerlClassEscape(s string, r []rune) (out []rune, rest string) {
   1369 	if p.flags&PerlX == 0 || len(s) < 2 || s[0] != '\\' {
   1370 		return
   1371 	}
   1372 	g := perlGroup[s[0:2]]
   1373 	if g.sign == 0 {
   1374 		return
   1375 	}
   1376 	return p.appendGroup(r, g), s[2:]
   1377 }
   1378 
   1379 // parseNamedClass parses a leading POSIX named character class like [:alnum:]
   1380 // from the beginning of s.  If one is present, it appends the characters to r
   1381 // and returns the new slice r and the remainder of the string.
   1382 func (p *parser) parseNamedClass(s string, r []rune) (out []rune, rest string, err error) {
   1383 	if len(s) < 2 || s[0] != '[' || s[1] != ':' {
   1384 		return
   1385 	}
   1386 
   1387 	i := strings.Index(s[2:], ":]")
   1388 	if i < 0 {
   1389 		return
   1390 	}
   1391 	i += 2
   1392 	name, s := s[0:i+2], s[i+2:]
   1393 	g := posixGroup[name]
   1394 	if g.sign == 0 {
   1395 		return nil, "", &Error{ErrInvalidCharRange, name}
   1396 	}
   1397 	return p.appendGroup(r, g), s, nil
   1398 }
   1399 
   1400 func (p *parser) appendGroup(r []rune, g charGroup) []rune {
   1401 	if p.flags&FoldCase == 0 {
   1402 		if g.sign < 0 {
   1403 			r = appendNegatedClass(r, g.class)
   1404 		} else {
   1405 			r = appendClass(r, g.class)
   1406 		}
   1407 	} else {
   1408 		tmp := p.tmpClass[:0]
   1409 		tmp = appendFoldedClass(tmp, g.class)
   1410 		p.tmpClass = tmp
   1411 		tmp = cleanClass(&p.tmpClass)
   1412 		if g.sign < 0 {
   1413 			r = appendNegatedClass(r, tmp)
   1414 		} else {
   1415 			r = appendClass(r, tmp)
   1416 		}
   1417 	}
   1418 	return r
   1419 }
   1420 
   1421 var anyTable = &unicode.RangeTable{
   1422 	R16: []unicode.Range16{{Lo: 0, Hi: 1<<16 - 1, Stride: 1}},
   1423 	R32: []unicode.Range32{{Lo: 1 << 16, Hi: unicode.MaxRune, Stride: 1}},
   1424 }
   1425 
   1426 // unicodeTable returns the unicode.RangeTable identified by name
   1427 // and the table of additional fold-equivalent code points.
   1428 func unicodeTable(name string) (*unicode.RangeTable, *unicode.RangeTable) {
   1429 	// Special case: "Any" means any.
   1430 	if name == "Any" {
   1431 		return anyTable, anyTable
   1432 	}
   1433 	if t := unicode.Categories[name]; t != nil {
   1434 		return t, unicode.FoldCategory[name]
   1435 	}
   1436 	if t := unicode.Scripts[name]; t != nil {
   1437 		return t, unicode.FoldScript[name]
   1438 	}
   1439 	return nil, nil
   1440 }
   1441 
   1442 // parseUnicodeClass parses a leading Unicode character class like \p{Han}
   1443 // from the beginning of s.  If one is present, it appends the characters to r
   1444 // and returns the new slice r and the remainder of the string.
   1445 func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, err error) {
   1446 	if p.flags&UnicodeGroups == 0 || len(s) < 2 || s[0] != '\\' || s[1] != 'p' && s[1] != 'P' {
   1447 		return
   1448 	}
   1449 
   1450 	// Committed to parse or return error.
   1451 	sign := +1
   1452 	if s[1] == 'P' {
   1453 		sign = -1
   1454 	}
   1455 	t := s[2:]
   1456 	c, t, err := nextRune(t)
   1457 	if err != nil {
   1458 		return
   1459 	}
   1460 	var seq, name string
   1461 	if c != '{' {
   1462 		// Single-letter name.
   1463 		seq = s[:len(s)-len(t)]
   1464 		name = seq[2:]
   1465 	} else {
   1466 		// Name is in braces.
   1467 		end := strings.IndexRune(s, '}')
   1468 		if end < 0 {
   1469 			if err = checkUTF8(s); err != nil {
   1470 				return
   1471 			}
   1472 			return nil, "", &Error{ErrInvalidCharRange, s}
   1473 		}
   1474 		seq, t = s[:end+1], s[end+1:]
   1475 		name = s[3:end]
   1476 		if err = checkUTF8(name); err != nil {
   1477 			return
   1478 		}
   1479 	}
   1480 
   1481 	// Group can have leading negation too.  \p{^Han} == \P{Han}, \P{^Han} == \p{Han}.
   1482 	if name != "" && name[0] == '^' {
   1483 		sign = -sign
   1484 		name = name[1:]
   1485 	}
   1486 
   1487 	tab, fold := unicodeTable(name)
   1488 	if tab == nil {
   1489 		return nil, "", &Error{ErrInvalidCharRange, seq}
   1490 	}
   1491 
   1492 	if p.flags&FoldCase == 0 || fold == nil {
   1493 		if sign > 0 {
   1494 			r = appendTable(r, tab)
   1495 		} else {
   1496 			r = appendNegatedTable(r, tab)
   1497 		}
   1498 	} else {
   1499 		// Merge and clean tab and fold in a temporary buffer.
   1500 		// This is necessary for the negative case and just tidy
   1501 		// for the positive case.
   1502 		tmp := p.tmpClass[:0]
   1503 		tmp = appendTable(tmp, tab)
   1504 		tmp = appendTable(tmp, fold)
   1505 		p.tmpClass = tmp
   1506 		tmp = cleanClass(&p.tmpClass)
   1507 		if sign > 0 {
   1508 			r = appendClass(r, tmp)
   1509 		} else {
   1510 			r = appendNegatedClass(r, tmp)
   1511 		}
   1512 	}
   1513 	return r, t, nil
   1514 }
   1515 
   1516 // parseClass parses a character class at the beginning of s
   1517 // and pushes it onto the parse stack.
   1518 func (p *parser) parseClass(s string) (rest string, err error) {
   1519 	t := s[1:] // chop [
   1520 	re := p.newRegexp(OpCharClass)
   1521 	re.Flags = p.flags
   1522 	re.Rune = re.Rune0[:0]
   1523 
   1524 	sign := +1
   1525 	if t != "" && t[0] == '^' {
   1526 		sign = -1
   1527 		t = t[1:]
   1528 
   1529 		// If character class does not match \n, add it here,
   1530 		// so that negation later will do the right thing.
   1531 		if p.flags&ClassNL == 0 {
   1532 			re.Rune = append(re.Rune, '\n', '\n')
   1533 		}
   1534 	}
   1535 
   1536 	class := re.Rune
   1537 	first := true // ] and - are okay as first char in class
   1538 	for t == "" || t[0] != ']' || first {
   1539 		// POSIX: - is only okay unescaped as first or last in class.
   1540 		// Perl: - is okay anywhere.
   1541 		if t != "" && t[0] == '-' && p.flags&PerlX == 0 && !first && (len(t) == 1 || t[1] != ']') {
   1542 			_, size := utf8.DecodeRuneInString(t[1:])
   1543 			return "", &Error{Code: ErrInvalidCharRange, Expr: t[:1+size]}
   1544 		}
   1545 		first = false
   1546 
   1547 		// Look for POSIX [:alnum:] etc.
   1548 		if len(t) > 2 && t[0] == '[' && t[1] == ':' {
   1549 			nclass, nt, err := p.parseNamedClass(t, class)
   1550 			if err != nil {
   1551 				return "", err
   1552 			}
   1553 			if nclass != nil {
   1554 				class, t = nclass, nt
   1555 				continue
   1556 			}
   1557 		}
   1558 
   1559 		// Look for Unicode character group like \p{Han}.
   1560 		nclass, nt, err := p.parseUnicodeClass(t, class)
   1561 		if err != nil {
   1562 			return "", err
   1563 		}
   1564 		if nclass != nil {
   1565 			class, t = nclass, nt
   1566 			continue
   1567 		}
   1568 
   1569 		// Look for Perl character class symbols (extension).
   1570 		if nclass, nt := p.parsePerlClassEscape(t, class); nclass != nil {
   1571 			class, t = nclass, nt
   1572 			continue
   1573 		}
   1574 
   1575 		// Single character or simple range.
   1576 		rng := t
   1577 		var lo, hi rune
   1578 		if lo, t, err = p.parseClassChar(t, s); err != nil {
   1579 			return "", err
   1580 		}
   1581 		hi = lo
   1582 		// [a-] means (a|-) so check for final ].
   1583 		if len(t) >= 2 && t[0] == '-' && t[1] != ']' {
   1584 			t = t[1:]
   1585 			if hi, t, err = p.parseClassChar(t, s); err != nil {
   1586 				return "", err
   1587 			}
   1588 			if hi < lo {
   1589 				rng = rng[:len(rng)-len(t)]
   1590 				return "", &Error{Code: ErrInvalidCharRange, Expr: rng}
   1591 			}
   1592 		}
   1593 		if p.flags&FoldCase == 0 {
   1594 			class = appendRange(class, lo, hi)
   1595 		} else {
   1596 			class = appendFoldedRange(class, lo, hi)
   1597 		}
   1598 	}
   1599 	t = t[1:] // chop ]
   1600 
   1601 	// Use &re.Rune instead of &class to avoid allocation.
   1602 	re.Rune = class
   1603 	class = cleanClass(&re.Rune)
   1604 	if sign < 0 {
   1605 		class = negateClass(class)
   1606 	}
   1607 	re.Rune = class
   1608 	p.push(re)
   1609 	return t, nil
   1610 }
   1611 
   1612 // cleanClass sorts the ranges (pairs of elements of r),
   1613 // merges them, and eliminates duplicates.
   1614 func cleanClass(rp *[]rune) []rune {
   1615 
   1616 	// Sort by lo increasing, hi decreasing to break ties.
   1617 	sort.Sort(ranges{rp})
   1618 
   1619 	r := *rp
   1620 	if len(r) < 2 {
   1621 		return r
   1622 	}
   1623 
   1624 	// Merge abutting, overlapping.
   1625 	w := 2 // write index
   1626 	for i := 2; i < len(r); i += 2 {
   1627 		lo, hi := r[i], r[i+1]
   1628 		if lo <= r[w-1]+1 {
   1629 			// merge with previous range
   1630 			if hi > r[w-1] {
   1631 				r[w-1] = hi
   1632 			}
   1633 			continue
   1634 		}
   1635 		// new disjoint range
   1636 		r[w] = lo
   1637 		r[w+1] = hi
   1638 		w += 2
   1639 	}
   1640 
   1641 	return r[:w]
   1642 }
   1643 
   1644 // appendLiteral returns the result of appending the literal x to the class r.
   1645 func appendLiteral(r []rune, x rune, flags Flags) []rune {
   1646 	if flags&FoldCase != 0 {
   1647 		return appendFoldedRange(r, x, x)
   1648 	}
   1649 	return appendRange(r, x, x)
   1650 }
   1651 
   1652 // appendRange returns the result of appending the range lo-hi to the class r.
   1653 func appendRange(r []rune, lo, hi rune) []rune {
   1654 	// Expand last range or next to last range if it overlaps or abuts.
   1655 	// Checking two ranges helps when appending case-folded
   1656 	// alphabets, so that one range can be expanding A-Z and the
   1657 	// other expanding a-z.
   1658 	n := len(r)
   1659 	for i := 2; i <= 4; i += 2 { // twice, using i=2, i=4
   1660 		if n >= i {
   1661 			rlo, rhi := r[n-i], r[n-i+1]
   1662 			if lo <= rhi+1 && rlo <= hi+1 {
   1663 				if lo < rlo {
   1664 					r[n-i] = lo
   1665 				}
   1666 				if hi > rhi {
   1667 					r[n-i+1] = hi
   1668 				}
   1669 				return r
   1670 			}
   1671 		}
   1672 	}
   1673 
   1674 	return append(r, lo, hi)
   1675 }
   1676 
   1677 const (
   1678 	// minimum and maximum runes involved in folding.
   1679 	// checked during test.
   1680 	minFold = 0x0041
   1681 	maxFold = 0x118df
   1682 )
   1683 
   1684 // appendFoldedRange returns the result of appending the range lo-hi
   1685 // and its case folding-equivalent runes to the class r.
   1686 func appendFoldedRange(r []rune, lo, hi rune) []rune {
   1687 	// Optimizations.
   1688 	if lo <= minFold && hi >= maxFold {
   1689 		// Range is full: folding can't add more.
   1690 		return appendRange(r, lo, hi)
   1691 	}
   1692 	if hi < minFold || lo > maxFold {
   1693 		// Range is outside folding possibilities.
   1694 		return appendRange(r, lo, hi)
   1695 	}
   1696 	if lo < minFold {
   1697 		// [lo, minFold-1] needs no folding.
   1698 		r = appendRange(r, lo, minFold-1)
   1699 		lo = minFold
   1700 	}
   1701 	if hi > maxFold {
   1702 		// [maxFold+1, hi] needs no folding.
   1703 		r = appendRange(r, maxFold+1, hi)
   1704 		hi = maxFold
   1705 	}
   1706 
   1707 	// Brute force.  Depend on appendRange to coalesce ranges on the fly.
   1708 	for c := lo; c <= hi; c++ {
   1709 		r = appendRange(r, c, c)
   1710 		f := unicode.SimpleFold(c)
   1711 		for f != c {
   1712 			r = appendRange(r, f, f)
   1713 			f = unicode.SimpleFold(f)
   1714 		}
   1715 	}
   1716 	return r
   1717 }
   1718 
   1719 // appendClass returns the result of appending the class x to the class r.
   1720 // It assume x is clean.
   1721 func appendClass(r []rune, x []rune) []rune {
   1722 	for i := 0; i < len(x); i += 2 {
   1723 		r = appendRange(r, x[i], x[i+1])
   1724 	}
   1725 	return r
   1726 }
   1727 
   1728 // appendFolded returns the result of appending the case folding of the class x to the class r.
   1729 func appendFoldedClass(r []rune, x []rune) []rune {
   1730 	for i := 0; i < len(x); i += 2 {
   1731 		r = appendFoldedRange(r, x[i], x[i+1])
   1732 	}
   1733 	return r
   1734 }
   1735 
   1736 // appendNegatedClass returns the result of appending the negation of the class x to the class r.
   1737 // It assumes x is clean.
   1738 func appendNegatedClass(r []rune, x []rune) []rune {
   1739 	nextLo := '\u0000'
   1740 	for i := 0; i < len(x); i += 2 {
   1741 		lo, hi := x[i], x[i+1]
   1742 		if nextLo <= lo-1 {
   1743 			r = appendRange(r, nextLo, lo-1)
   1744 		}
   1745 		nextLo = hi + 1
   1746 	}
   1747 	if nextLo <= unicode.MaxRune {
   1748 		r = appendRange(r, nextLo, unicode.MaxRune)
   1749 	}
   1750 	return r
   1751 }
   1752 
   1753 // appendTable returns the result of appending x to the class r.
   1754 func appendTable(r []rune, x *unicode.RangeTable) []rune {
   1755 	for _, xr := range x.R16 {
   1756 		lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride)
   1757 		if stride == 1 {
   1758 			r = appendRange(r, lo, hi)
   1759 			continue
   1760 		}
   1761 		for c := lo; c <= hi; c += stride {
   1762 			r = appendRange(r, c, c)
   1763 		}
   1764 	}
   1765 	for _, xr := range x.R32 {
   1766 		lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride)
   1767 		if stride == 1 {
   1768 			r = appendRange(r, lo, hi)
   1769 			continue
   1770 		}
   1771 		for c := lo; c <= hi; c += stride {
   1772 			r = appendRange(r, c, c)
   1773 		}
   1774 	}
   1775 	return r
   1776 }
   1777 
   1778 // appendNegatedTable returns the result of appending the negation of x to the class r.
   1779 func appendNegatedTable(r []rune, x *unicode.RangeTable) []rune {
   1780 	nextLo := '\u0000' // lo end of next class to add
   1781 	for _, xr := range x.R16 {
   1782 		lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride)
   1783 		if stride == 1 {
   1784 			if nextLo <= lo-1 {
   1785 				r = appendRange(r, nextLo, lo-1)
   1786 			}
   1787 			nextLo = hi + 1
   1788 			continue
   1789 		}
   1790 		for c := lo; c <= hi; c += stride {
   1791 			if nextLo <= c-1 {
   1792 				r = appendRange(r, nextLo, c-1)
   1793 			}
   1794 			nextLo = c + 1
   1795 		}
   1796 	}
   1797 	for _, xr := range x.R32 {
   1798 		lo, hi, stride := rune(xr.Lo), rune(xr.Hi), rune(xr.Stride)
   1799 		if stride == 1 {
   1800 			if nextLo <= lo-1 {
   1801 				r = appendRange(r, nextLo, lo-1)
   1802 			}
   1803 			nextLo = hi + 1
   1804 			continue
   1805 		}
   1806 		for c := lo; c <= hi; c += stride {
   1807 			if nextLo <= c-1 {
   1808 				r = appendRange(r, nextLo, c-1)
   1809 			}
   1810 			nextLo = c + 1
   1811 		}
   1812 	}
   1813 	if nextLo <= unicode.MaxRune {
   1814 		r = appendRange(r, nextLo, unicode.MaxRune)
   1815 	}
   1816 	return r
   1817 }
   1818 
   1819 // negateClass overwrites r and returns r's negation.
   1820 // It assumes the class r is already clean.
   1821 func negateClass(r []rune) []rune {
   1822 	nextLo := '\u0000' // lo end of next class to add
   1823 	w := 0             // write index
   1824 	for i := 0; i < len(r); i += 2 {
   1825 		lo, hi := r[i], r[i+1]
   1826 		if nextLo <= lo-1 {
   1827 			r[w] = nextLo
   1828 			r[w+1] = lo - 1
   1829 			w += 2
   1830 		}
   1831 		nextLo = hi + 1
   1832 	}
   1833 	r = r[:w]
   1834 	if nextLo <= unicode.MaxRune {
   1835 		// It's possible for the negation to have one more
   1836 		// range - this one - than the original class, so use append.
   1837 		r = append(r, nextLo, unicode.MaxRune)
   1838 	}
   1839 	return r
   1840 }
   1841 
   1842 // ranges implements sort.Interface on a []rune.
   1843 // The choice of receiver type definition is strange
   1844 // but avoids an allocation since we already have
   1845 // a *[]rune.
   1846 type ranges struct {
   1847 	p *[]rune
   1848 }
   1849 
   1850 func (ra ranges) Less(i, j int) bool {
   1851 	p := *ra.p
   1852 	i *= 2
   1853 	j *= 2
   1854 	return p[i] < p[j] || p[i] == p[j] && p[i+1] > p[j+1]
   1855 }
   1856 
   1857 func (ra ranges) Len() int {
   1858 	return len(*ra.p) / 2
   1859 }
   1860 
   1861 func (ra ranges) Swap(i, j int) {
   1862 	p := *ra.p
   1863 	i *= 2
   1864 	j *= 2
   1865 	p[i], p[i+1], p[j], p[j+1] = p[j], p[j+1], p[i], p[i+1]
   1866 }
   1867 
   1868 func checkUTF8(s string) error {
   1869 	for s != "" {
   1870 		rune, size := utf8.DecodeRuneInString(s)
   1871 		if rune == utf8.RuneError && size == 1 {
   1872 			return &Error{Code: ErrInvalidUTF8, Expr: s}
   1873 		}
   1874 		s = s[size:]
   1875 	}
   1876 	return nil
   1877 }
   1878 
   1879 func nextRune(s string) (c rune, t string, err error) {
   1880 	c, size := utf8.DecodeRuneInString(s)
   1881 	if c == utf8.RuneError && size == 1 {
   1882 		return 0, "", &Error{Code: ErrInvalidUTF8, Expr: s}
   1883 	}
   1884 	return c, s[size:], nil
   1885 }
   1886 
   1887 func isalnum(c rune) bool {
   1888 	return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'
   1889 }
   1890 
   1891 func unhex(c rune) rune {
   1892 	if '0' <= c && c <= '9' {
   1893 		return c - '0'
   1894 	}
   1895 	if 'a' <= c && c <= 'f' {
   1896 		return c - 'a' + 10
   1897 	}
   1898 	if 'A' <= c && c <= 'F' {
   1899 		return c - 'A' + 10
   1900 	}
   1901 	return -1
   1902 }
   1903