package goabnf

import (
	
	
	
	
	
)

// Regex builds a regular expression that recognises the given rulename.
//
// The rule must not contain a cycle in its dependency graph: a regular
// expression (RE2, no subroutines) cannot express recursion.
//
// Because RE2 has no subroutine/backreference, a rule referenced N times is
// inlined N times, so the output can grow exponentially with reference-nesting
// depth for diamond-shaped grammars. Pass WithMaxRegexLen to fail fast with
// *ErrRegexTooLarge instead of exhausting memory. The output is simplified
// (character classes merged, redundant groups and {1} quantifiers dropped) but
// is not guaranteed minimal.
func ( *Grammar) ( string,  ...RegexOption) (string, error) {
	 := &regexOptions{}
	for ,  := range  {
		.applyRegex()
	}

	,  := .RuleContainsCycle()
	if  != nil {
		return "", 
	}
	if  {
		return "", &ErrCyclicRule{Rulename: }
	}
	 := GetRule(, .Rulemap)
	if  == nil {
		return "", &ErrRuleNotFound{Rulename: }
	}

	 := &reBuilder{g: , memo: map[string]reNode{}}
	 := .alt(.Alternation)
	if .err != nil {
		return "", .err
	}
	 = simplify(, map[reNode]reNode{})

	 := &reRenderer{max: .maxLen}
	var  strings.Builder
	.render(&, , precAlt)
	if .err != nil {
		return "", .err
	}
	return .String(), nil
}

// ---- options & error ----

type regexOptions struct{ maxLen int }

// RegexOption configures Regex.
type RegexOption interface{ applyRegex(*regexOptions) }

type regexOptionFunc func(*regexOptions)

func ( regexOptionFunc) ( *regexOptions) { () }

// WithMaxRegexLen bounds the produced regex length in bytes. When the budget is
// exceeded, Regex returns *ErrRegexTooLarge. Zero (the default) is unbounded.
func ( int) RegexOption {
	return regexOptionFunc(func( *regexOptions) { .maxLen =  })
}

// ErrRegexTooLarge is returned by Regex when the output would exceed the budget
// set with WithMaxRegexLen.
type ErrRegexTooLarge struct{ Max int }

var _ error = (*ErrRegexTooLarge)(nil)

func ( *ErrRegexTooLarge) () string {
	return fmt.Sprintf("regex exceeds the configured %d-byte budget", .Max)
}

// ---- intermediate representation ----

const (
	precAlt    = 1 // alternation binds loosest
	precConcat = 2
	precRepeat = 3
	precAtom   = 4 // a class or single char binds tightest
)

type reNode interface{ prec() int }

type reRange struct{ lo, hi rune }

type reClass struct{ ranges []reRange } // a single [c,c] renders as a bare char
type reConcat struct{ parts []reNode }
type reAlt struct{ opts []reNode }
type reRepeat struct {
	sub      reNode
	min, max int
}
type reEmpty struct{}

// reNever matches nothing. It represents a num-val a RE2/Unicode pattern cannot
// express (a value entirely above U+10FFFF), keeping Regex consistent with the
// recognizer, which also matches nothing in that case.
type reNever struct{}

func (*reClass) () int  { return precAtom }
func (*reConcat) () int { return precConcat }
func (*reAlt) () int    { return precAlt }
func (*reRepeat) () int { return precRepeat }
func (*reEmpty) () int  { return precAtom }
func (*reNever) () int  { return precAtom }

var reEmptyV reNode = &reEmpty{}
var reNeverV reNode = &reNever{}

func isNever( reNode) bool { ,  := .(*reNever); return  }

// ---- build (memoised per rule => linear over the grammar DAG) ----

type reBuilder struct {
	g    *Grammar
	memo map[string]reNode
	err  error
}

func ( *reBuilder) ( string) reNode {
	 := strings.ToLower()
	if ,  := .memo[];  {
		return 
	}
	 := GetRule(, .g.Rulemap)
	if  == nil {
		return reEmptyV
	}
	 := .alt(.Alternation)
	.memo[] = 
	return 
}

func ( *reBuilder) ( Alternation) reNode {
	 := make([]reNode, 0, len(.Concatenations))
	for ,  := range .Concatenations {
		 = append(, .concat())
	}
	return &reAlt{opts: }
}

func ( *reBuilder) ( Concatenation) reNode {
	 := make([]reNode, 0, len(.Repetitions))
	for ,  := range .Repetitions {
		 = append(, &reRepeat{sub: .elem(.Element), min: .Min, max: .Max})
	}
	return &reConcat{parts: }
}

func ( *reBuilder) ( ElemItf) reNode {
	switch v := .(type) {
	case ElemRulename:
		return .rule(.Name)
	case ElemGroup:
		return .alt(.Alternation)
	case ElemOption:
		return &reRepeat{sub: .alt(.Alternation), min: 0, max: 1}
	case ElemNumVal:
		switch .Status {
		case StatRange:
			 := numvalToRune(.Elems[0], .Base)
			 := min(
				// RE2 patterns are Unicode (max U+10FFFF). A range straddling that
				// ceiling is clamped to its representable subset; one wholly above it
				// matches nothing -- mirroring the recognizer.
				numvalToRune(.Elems[1], .Base), utf8.MaxRune)
			if  > utf8.MaxRune ||  >  {
				return reNeverV
			}
			return &reClass{ranges: []reRange{{, }}}
		default: // StatSeries is a CONCATENATION of values (a fixed sequence).
			 := make([]reNode, 0, len(.Elems))
			for ,  := range .Elems {
				 := numvalToRune(, .Base)
				// A series element must be a real character; if it is not, the
				// whole sequence can never match any (Unicode) input.
				if !utf8.ValidRune() {
					return reNeverV
				}
				 = append(, &reClass{ranges: []reRange{{, }}})
			}
			return &reConcat{parts: }
		}
	case ElemCharVal:
		// A char-val is case-insensitive unless Sensitive (RFC 7405); the
		// recognizer folds ASCII A-Z only (see runeMin/sensequal), so we match
		// that exactly here.
		 := make([]reNode, 0, len(.Values))
		for ,  := range .Values {
			 = append(, charClass(, .Sensitive))
		}
		return &reConcat{parts: }
	case ElemProseVal:
		if .err == nil {
			.err = ErrHandlingProseVal
		}
		return reEmptyV
	}
	return reEmptyV
}

func charClass( rune,  bool) reNode {
	if ! {
		switch {
		case  >= 'A' &&  <= 'Z':
			 :=  - 'A' + 'a'
			return &reClass{ranges: []reRange{{, }, {, }}}
		case  >= 'a' &&  <= 'z':
			 :=  - 'a' + 'A'
			return &reClass{ranges: []reRange{{, }, {, }}}
		}
	}
	return &reClass{ranges: []reRange{{, }}}
}

// ---- simplification (pointer-memoised => linear over the DAG) ----

func simplify( reNode,  map[reNode]reNode) reNode {
	if  == nil {
		return reEmptyV
	}
	if ,  := [];  {
		return 
	}
	var  reNode
	switch v := .(type) {
	case *reClass:
		 = &reClass{ranges: normalizeRanges(.ranges)}
	case *reEmpty:
		 = reEmptyV
	case *reNever:
		 = reNeverV
	case *reConcat:
		 := make([]reNode, 0, len(.parts))
		 := false
		for ,  := range .parts {
			 := (, )
			switch x := .(type) {
			case *reEmpty: // drop: empty in a concatenation contributes nothing
			case *reNever: // one un-matchable part makes the whole sequence un-matchable
				 = true
			case *reConcat:
				 = append(, .parts...) // flatten
			default:
				 = append(, )
			}
		}
		switch {
		case :
			 = reNeverV
		case len() == 0:
			 = reEmptyV
		case len() == 1:
			 = [0]
		default:
			 = &reConcat{parts: }
		}
	case *reAlt:
		 := make([]reNode, 0, len(.opts))
		for ,  := range .opts {
			 := (, )
			if isNever() { // a never-matching branch is dead; drop it
				continue
			}
			if ,  := .(*reAlt);  {
				 = append(, .opts...) // flatten
			} else {
				 = append(, )
			}
		}
		// Fold every class option into a single merged class: turns an
		// alternation of single characters / ranges into one [...].
		var  []reRange
		 := 0
		 := make([]reNode, 0, len())
		for ,  := range  {
			if ,  := .(*reClass);  {
				 = append(, .ranges...)
				++
			} else {
				 = append(, )
			}
		}
		 := make([]reNode, 0, len()+1)
		if  > 0 {
			 = append(, &reClass{ranges: normalizeRanges()})
		}
		 = append(, ...)
		switch len() {
		case 0:
			// Every branch was un-matchable: the alternation matches nothing.
			 = reNeverV
		case 1:
			 = [0]
		default:
			 = &reAlt{opts: }
		}
	case *reRepeat:
		 := (.sub, )
		switch {
		case isNever():
			// Zero occurrences are allowed iff min == 0 (then it matches empty);
			// otherwise the repetition is itself un-matchable.
			if .min == 0 {
				 = reEmptyV
			} else {
				 = reNeverV
			}
		case isEmpty():
			 = reEmptyV
		case .min == 1 && .max == 1:
			 = 
		default:
			 = &reRepeat{sub: , min: .min, max: .max}
		}
	default:
		 = 
	}
	[] = 
	return 
}

func isEmpty( reNode) bool { ,  := .(*reEmpty); return  }

// normalizeRanges sorts and coalesces overlapping/adjacent ranges.
func normalizeRanges( []reRange) []reRange {
	if len() <= 1 {
		return 
	}
	 := append([]reRange(nil), ...)
	sort.Slice(, func(,  int) bool {
		return [].lo < [].lo || ([].lo == [].lo && [].hi < [].hi)
	})
	 := []reRange{[0]}
	for ,  := range [1:] {
		 := &[len()-1]
		if .lo <= .hi+1 { // overlapping or adjacent
			if .hi > .hi {
				.hi = .hi
			}
		} else {
			 = append(, )
		}
	}
	return 
}

// ---- render (minimal grouping, length-budgeted) ----

type reRenderer struct {
	max int
	n   int
	err error
}

func ( *reRenderer) ( *strings.Builder,  string) {
	if .err != nil {
		return
	}
	.n += len()
	if .max > 0 && .n > .max {
		.err = &ErrRegexTooLarge{Max: .max}
		return
	}
	.WriteString()
}

// render emits node; it self-groups with (?:...) when its precedence is looser
// than the surrounding context requires.
func ( *reRenderer) ( *strings.Builder,  reNode,  int) {
	if .err != nil {
		return
	}
	 := .prec() < 
	if  {
		.write(, "(?:")
	}
	switch v := .(type) {
	case *reEmpty:
		// (?: ) already opened if grouped; otherwise emit an explicit empty.
		if ! {
			.write(, "(?:)")
		}
	case *reNever:
		// Negated full-Unicode class: matches no character, hence nothing.
		.write(, "[^\\x00-\\x{10ffff}]")
	case *reClass:
		.write(, renderClass())
	case *reConcat:
		for ,  := range .parts {
			.(, , precConcat)
		}
	case *reAlt:
		for ,  := range .opts {
			if  > 0 {
				.write(, "|")
			}
			.(, , precAlt)
		}
	case *reRepeat:
		.(, .sub, precAtom) // operand of a quantifier must be an atom
		.write(, quantifier(.min, .max))
	}
	if  {
		.write(, ")")
	}
}

func renderClass( *reClass) string {
	if len(.ranges) == 1 && .ranges[0].lo == .ranges[0].hi {
		return regescape(.ranges[0].lo) // bare single character
	}
	var  strings.Builder
	.WriteByte('[')
	for ,  := range .ranges {
		if .lo == .hi {
			.WriteString(classEscape(.lo))
		} else {
			.WriteString(classEscape(.lo))
			.WriteByte('-')
			.WriteString(classEscape(.hi))
		}
	}
	.WriteByte(']')
	return .String()
}

func quantifier(,  int) string {
	switch {
	case  == 0 &&  == 1:
		return "?"
	case  == 0 &&  == inf:
		return "*"
	case  == 1 &&  == inf:
		return "+"
	case  == inf:
		return fmt.Sprintf("{%d,}", )
	case  == :
		return fmt.Sprintf("{%d}", )
	case  == 0:
		return fmt.Sprintf("{0,%d}", )
	default:
		return fmt.Sprintf("{%d,%d}", , )
	}
}

// regescape quotes a single rune for use outside a character class.
func regescape( rune) string { return regexp.QuoteMeta(string()) }

// classEscape renders a rune as a character-class member. Alphanumerics are
// never class metacharacters; everything else is emitted as \x{...} to avoid
// the class-specific escaping pitfalls of ], ^, - and \.
func classEscape( rune) string {
	if ( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z') || ( >= '0' &&  <= '9') {
		return string()
	}
	return fmt.Sprintf("\\x{%x}", )
}