// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package syntax

// Note to implementers:
// In this package, re is always a *Regexp and r is always a rune.

import (
	
	
	
)

// A Regexp is a node in a regular expression syntax tree.
type Regexp struct {
	Op       Op // operator
	Flags    Flags
	Sub      []*Regexp  // subexpressions, if any
	Sub0     [1]*Regexp // storage for short Sub
	Rune     []rune     // matched runes, for OpLiteral, OpCharClass
	Rune0    [2]rune    // storage for short Rune
	Min, Max int        // min, max for OpRepeat
	Cap      int        // capturing index, for OpCapture
	Name     string     // capturing name, for OpCapture
}

//go:generate stringer -type Op -trimprefix Op

// An Op is a single regular expression operator.
type Op uint8

// Operators are listed in precedence order, tightest binding to weakest.
// Character class operators are listed simplest to most complex
// (OpLiteral, OpCharClass, OpAnyCharNotNL, OpAnyChar).

const (
	OpNoMatch        Op = 1 + iota // matches no strings
	OpEmptyMatch                   // matches empty string
	OpLiteral                      // matches Runes sequence
	OpCharClass                    // matches Runes interpreted as range pair list
	OpAnyCharNotNL                 // matches any character except newline
	OpAnyChar                      // matches any character
	OpBeginLine                    // matches empty string at beginning of line
	OpEndLine                      // matches empty string at end of line
	OpBeginText                    // matches empty string at beginning of text
	OpEndText                      // matches empty string at end of text
	OpWordBoundary                 // matches word boundary `\b`
	OpNoWordBoundary               // matches word non-boundary `\B`
	OpCapture                      // capturing subexpression with index Cap, optional name Name
	OpStar                         // matches Sub[0] zero or more times
	OpPlus                         // matches Sub[0] one or more times
	OpQuest                        // matches Sub[0] zero or one times
	OpRepeat                       // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit)
	OpConcat                       // matches concatenation of Subs
	OpAlternate                    // matches alternation of Subs
)

const opPseudo Op = 128 // where pseudo-ops start

// Equal reports whether x and y have identical structure.
func ( *Regexp) ( *Regexp) bool {
	if  == nil ||  == nil {
		return  == 
	}
	if .Op != .Op {
		return false
	}
	switch .Op {
	case OpEndText:
		// The parse flags remember whether this is \z or \Z.
		if .Flags&WasDollar != .Flags&WasDollar {
			return false
		}

	case OpLiteral, OpCharClass:
		if len(.Rune) != len(.Rune) {
			return false
		}
		for ,  := range .Rune {
			if  != .Rune[] {
				return false
			}
		}

	case OpAlternate, OpConcat:
		if len(.Sub) != len(.Sub) {
			return false
		}
		for ,  := range .Sub {
			if !.(.Sub[]) {
				return false
			}
		}

	case OpStar, OpPlus, OpQuest:
		if .Flags&NonGreedy != .Flags&NonGreedy || !.Sub[0].(.Sub[0]) {
			return false
		}

	case OpRepeat:
		if .Flags&NonGreedy != .Flags&NonGreedy || .Min != .Min || .Max != .Max || !.Sub[0].(.Sub[0]) {
			return false
		}

	case OpCapture:
		if .Cap != .Cap || .Name != .Name || !.Sub[0].(.Sub[0]) {
			return false
		}
	}
	return true
}

// printFlags is a bit set indicating which flags (including non-capturing parens) to print around a regexp.
type printFlags uint8

const (
	flagI    printFlags = 1 << iota // (?i:
	flagM                           // (?m:
	flagS                           // (?s:
	flagOff                         // )
	flagPrec                        // (?: )
	negShift = 5                    // flagI<<negShift is (?-i:
)

// addSpan enables the flags f around start..last,
// by setting flags[start] = f and flags[last] = flagOff.
func addSpan(,  *Regexp,  printFlags,  *map[*Regexp]printFlags) {
	if * == nil {
		* = make(map[*Regexp]printFlags)
	}
	(*)[] = 
	(*)[] |= flagOff // maybe start==last
}

// calcFlags calculates the flags to print around each subexpression in re,
// storing that information in (*flags)[sub] for each affected subexpression.
// The first time an entry needs to be written to *flags, calcFlags allocates the map.
// calcFlags also calculates the flags that must be active or can't be active
// around re and returns those flags.
func calcFlags( *Regexp,  *map[*Regexp]printFlags) (,  printFlags) {
	switch .Op {
	default:
		return 0, 0

	case OpLiteral:
		// If literal is fold-sensitive, return (flagI, 0) or (0, flagI)
		// according to whether (?i) is active.
		// If literal is not fold-sensitive, return 0, 0.
		for ,  := range .Rune {
			if minFold <=  &&  <= maxFold && unicode.SimpleFold() !=  {
				if .Flags&FoldCase != 0 {
					return flagI, 0
				} else {
					return 0, flagI
				}
			}
		}
		return 0, 0

	case OpCharClass:
		// If literal is fold-sensitive, return 0, flagI - (?i) has been compiled out.
		// If literal is not fold-sensitive, return 0, 0.
		for  := 0;  < len(.Rune);  += 2 {
			 := max(minFold, .Rune[])
			 := min(maxFold, .Rune[+1])
			for  := ;  <= ; ++ {
				for  := unicode.SimpleFold();  != ;  = unicode.SimpleFold() {
					if !( <=  &&  <= ) && !inCharClass(, .Rune) {
						return 0, flagI
					}
				}
			}
		}
		return 0, 0

	case OpAnyCharNotNL: // (?-s).
		return 0, flagS

	case OpAnyChar: // (?s).
		return flagS, 0

	case OpBeginLine, OpEndLine: // (?m)^ (?m)$
		return flagM, 0

	case OpEndText:
		if .Flags&WasDollar != 0 { // (?-m)$
			return 0, flagM
		}
		return 0, 0

	case OpCapture, OpStar, OpPlus, OpQuest, OpRepeat:
		return (.Sub[0], )

	case OpConcat, OpAlternate:
		// Gather the must and cant for each subexpression.
		// When we find a conflicting subexpression, insert the necessary
		// flags around the previously identified span and start over.
		var , ,  printFlags
		 := 0
		 := 0
		 := false
		for ,  := range .Sub {
			,  := (, )
			if & != 0 || & != 0 {
				if  != 0 {
					addSpan(.Sub[], .Sub[], , )
				}
				 = 0
				 = 0
				 = 
				 = true
			}
			 |= 
			 |= 
			 |= 
			if  != 0 {
				 = 
			}
			if  == 0 &&  ==  {
				++
			}
		}
		if ! {
			// No conflicts: pass the accumulated must and cant upward.
			return , 
		}
		if  != 0 {
			// Conflicts found; need to finish final span.
			addSpan(.Sub[], .Sub[], , )
		}
		return 0, 
	}
}

// writeRegexp writes the Perl syntax for the regular expression re to b.
func writeRegexp( *strings.Builder,  *Regexp,  printFlags,  map[*Regexp]printFlags) {
	 |= []
	if &flagPrec != 0 && &^(flagOff|flagPrec) != 0 && &flagOff != 0 {
		// flagPrec is redundant with other flags being added and terminated
		 &^= flagPrec
	}
	if &^(flagOff|flagPrec) != 0 {
		.WriteString(`(?`)
		if &flagI != 0 {
			.WriteString(`i`)
		}
		if &flagM != 0 {
			.WriteString(`m`)
		}
		if &flagS != 0 {
			.WriteString(`s`)
		}
		if &((flagM|flagS)<<negShift) != 0 {
			.WriteString(`-`)
			if &(flagM<<negShift) != 0 {
				.WriteString(`m`)
			}
			if &(flagS<<negShift) != 0 {
				.WriteString(`s`)
			}
		}
		.WriteString(`:`)
	}
	if &flagOff != 0 {
		defer .WriteString(`)`)
	}
	if &flagPrec != 0 {
		.WriteString(`(?:`)
		defer .WriteString(`)`)
	}

	switch .Op {
	default:
		.WriteString("<invalid op" + strconv.Itoa(int(.Op)) + ">")
	case OpNoMatch:
		.WriteString(`[^\x00-\x{10FFFF}]`)
	case OpEmptyMatch:
		.WriteString(`(?:)`)
	case OpLiteral:
		for ,  := range .Rune {
			escape(, , false)
		}
	case OpCharClass:
		if len(.Rune)%2 != 0 {
			.WriteString(`[invalid char class]`)
			break
		}
		.WriteRune('[')
		if len(.Rune) == 0 {
			.WriteString(`^\x00-\x{10FFFF}`)
		} else if .Rune[0] == 0 && .Rune[len(.Rune)-1] == unicode.MaxRune && len(.Rune) > 2 {
			// Contains 0 and MaxRune. Probably a negated class.
			// Print the gaps.
			.WriteRune('^')
			for  := 1;  < len(.Rune)-1;  += 2 {
				,  := .Rune[]+1, .Rune[+1]-1
				escape(, ,  == '-')
				if  !=  {
					if  != +1 {
						.WriteRune('-')
					}
					escape(, ,  == '-')
				}
			}
		} else {
			for  := 0;  < len(.Rune);  += 2 {
				,  := .Rune[], .Rune[+1]
				escape(, ,  == '-')
				if  !=  {
					if  != +1 {
						.WriteRune('-')
					}
					escape(, ,  == '-')
				}
			}
		}
		.WriteRune(']')
	case OpAnyCharNotNL, OpAnyChar:
		.WriteString(`.`)
	case OpBeginLine:
		.WriteString(`^`)
	case OpEndLine:
		.WriteString(`$`)
	case OpBeginText:
		.WriteString(`\A`)
	case OpEndText:
		if .Flags&WasDollar != 0 {
			.WriteString(`$`)
		} else {
			.WriteString(`\z`)
		}
	case OpWordBoundary:
		.WriteString(`\b`)
	case OpNoWordBoundary:
		.WriteString(`\B`)
	case OpCapture:
		if .Name != "" {
			.WriteString(`(?P<`)
			.WriteString(.Name)
			.WriteRune('>')
		} else {
			.WriteRune('(')
		}
		if .Sub[0].Op != OpEmptyMatch {
			(, .Sub[0], [.Sub[0]], )
		}
		.WriteRune(')')
	case OpStar, OpPlus, OpQuest, OpRepeat:
		 := printFlags(0)
		 := .Sub[0]
		if .Op > OpCapture || .Op == OpLiteral && len(.Rune) > 1 {
			 = flagPrec
		}
		(, , , )

		switch .Op {
		case OpStar:
			.WriteRune('*')
		case OpPlus:
			.WriteRune('+')
		case OpQuest:
			.WriteRune('?')
		case OpRepeat:
			.WriteRune('{')
			.WriteString(strconv.Itoa(.Min))
			if .Max != .Min {
				.WriteRune(',')
				if .Max >= 0 {
					.WriteString(strconv.Itoa(.Max))
				}
			}
			.WriteRune('}')
		}
		if .Flags&NonGreedy != 0 {
			.WriteRune('?')
		}
	case OpConcat:
		for ,  := range .Sub {
			 := printFlags(0)
			if .Op == OpAlternate {
				 = flagPrec
			}
			(, , , )
		}
	case OpAlternate:
		for ,  := range .Sub {
			if  > 0 {
				.WriteRune('|')
			}
			(, , 0, )
		}
	}
}

func ( *Regexp) () string {
	var  strings.Builder
	var  map[*Regexp]printFlags
	,  := calcFlags(, &)
	 |= ( &^ flagI) << negShift
	if  != 0 {
		 |= flagOff
	}
	writeRegexp(&, , , )
	return .String()
}

const meta = `\.+*?()|[]{}^$`

func escape( *strings.Builder,  rune,  bool) {
	if unicode.IsPrint() {
		if strings.ContainsRune(meta, ) ||  {
			.WriteRune('\\')
		}
		.WriteRune()
		return
	}

	switch  {
	case '\a':
		.WriteString(`\a`)
	case '\f':
		.WriteString(`\f`)
	case '\n':
		.WriteString(`\n`)
	case '\r':
		.WriteString(`\r`)
	case '\t':
		.WriteString(`\t`)
	case '\v':
		.WriteString(`\v`)
	default:
		if  < 0x100 {
			.WriteString(`\x`)
			 := strconv.FormatInt(int64(), 16)
			if len() == 1 {
				.WriteRune('0')
			}
			.WriteString()
			break
		}
		.WriteString(`\x{`)
		.WriteString(strconv.FormatInt(int64(), 16))
		.WriteString(`}`)
	}
}

// MaxCap walks the regexp to find the maximum capture index.
func ( *Regexp) () int {
	 := 0
	if .Op == OpCapture {
		 = .Cap
	}
	for ,  := range .Sub {
		if  := .();  <  {
			 = 
		}
	}
	return 
}

// CapNames walks the regexp to find the names of capturing groups.
func ( *Regexp) () []string {
	 := make([]string, .MaxCap()+1)
	.capNames()
	return 
}

func ( *Regexp) ( []string) {
	if .Op == OpCapture {
		[.Cap] = .Name
	}
	for ,  := range .Sub {
		.()
	}
}