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