package goabnf

import (
	
	
	
)

// Generates strings by recursive descent over the grammar AST, so unlike the*
// transition-graph Generator (a finite automaton, which can only express
// *regular* rules) it handles genuinely recursive rules -- nested objects,
// balanced delimiters, expression grammars -- where a rule is reached many times
// at many depths.
//
// The hard part of recursive generation is termination: a recursive rule can
// expand forever. This generator guarantees a finite, valid production by
// precomputing each rule's minimum expansion cost and, whenever a depth or
// length budget is exceeded, steering every choice toward the cheapest-to-finish
// expansion. It never truncates mid-derivation, so the output is always a
// complete word of the grammar. (It shares the tape/rand entropy `source` with
// the transition-graph generator, so it slots into testing.F the same way.)

const astUnbounded = 1 << 30 // "infinite" min-length sentinel (non-productive)

// ASTGenerator generates strings admitted by a (possibly recursive) grammar
// rule, directly from the AST.
type ASTGenerator struct {
	g     *Grammar
	start *Rule

	maxDepth  int // rule-expansion depth before steering to terminate
	maxLen    int // output bytes before steering to terminate
	maxRepeat int // cap for unbounded ("*") repetitions

	minCost map[string]int // rule name -> minimum expansion cost (productivity)
}

// ASTGenOption configures an ASTGenerator.
type ASTGenOption interface {
	apply(*ASTGenerator)
}

type astGenOptionFunc func(*ASTGenerator)

func ( astGenOptionFunc) ( *ASTGenerator) {
	()
}

// WithMaxDepth bounds rule-expansion (recursion) depth; past it the generator
// steers toward terminating expansions. Defaults to 32.
func ( int) ASTGenOption {
	return astGenOptionFunc(func( *ASTGenerator) {
		.maxDepth = 
	})
}

// WithMaxLen bounds the output length; past it the generator steers toward
// terminating expansions. Defaults to 4096. (Mandatory repetitions are always
// emitted, so the bound is soft -- a single huge fixed repetition can exceed it.)
func ( int) ASTGenOption {
	return astGenOptionFunc(func( *ASTGenerator) {
		.maxLen = 
	})
}

// WithMaxRepeat caps how far an unbounded ("*" / "1*") repetition is unrolled.
// Defaults to 16.
func ( int) ASTGenOption {
	return astGenOptionFunc(func( *ASTGenerator) {
		.maxRepeat = 
	})
}

// NewASTGenerator prepares a generator for rule. It errors if the rule is
// undefined, or if any rule reachable from it is undefined or non-productive
// (cannot derive any finite string), since neither can be generated. Unlike the
// transition-graph generator, recursive rules are fully supported.
func ( *Grammar,  string,  ...ASTGenOption) (*ASTGenerator, error) {
	 := GetRule(, .Rulemap)
	if  == nil {
		return nil, &ErrRuleNotFound{Rulename: }
	}
	 := &ASTGenerator{
		g:         ,
		start:     ,
		maxDepth:  32,
		maxLen:    4096,
		maxRepeat: 16,
	}
	for ,  := range  {
		.apply()
	}

	// Least-fixpoint of minimum expansion cost over every rule reachable in
	// principle -- user rules and the built-in core rules (ALPHA, DIGIT, ...),
	// which GetRule resolves as a fallback but which are absent from Rulemap.
	// Keyed by canonical rule name (GetRule is case-insensitive and honors user
	// overrides of core rules). A rule stuck at the sentinel is non-productive.
	 := map[string]*Rule{}
	for  := range .Rulemap {
		if  := GetRule(, .Rulemap);  != nil {
			[.Name] = 
		}
	}
	for  := range coreRules {
		if  := GetRule(, .Rulemap);  != nil {
			[.Name] = 
		}
	}
	.minCost = make(map[string]int, len())
	for  := range  {
		.minCost[] = astUnbounded
	}
	for  := true; ; {
		 = false
		for ,  := range  {
			if  := .costAlt(.Alternation);  < .minCost[] {
				.minCost[] = 
				 = true
			}
		}
	}

	// Every rule reachable from start must be defined and productive.
	 := map[string]bool{.Name: true}
	var  func(Alternation) error
	 := func( ElemItf) error {
		switch x := .(type) {
		case ElemRulename:
			 := GetRule(.Name, .Rulemap)
			if  == nil {
				return fmt.Errorf("rule %q (reachable from %q) is undefined and cannot be generated", .Name, )
			}
			if [.Name] {
				return nil
			}
			[.Name] = true
			if .minCost[.Name] >= astUnbounded {
				return fmt.Errorf("rule %q (reachable from %q) is non-productive (cannot derive any finite string)", .Name, )
			}
			return (.Alternation)
		case ElemGroup:
			return (.Alternation)
		case ElemOption:
			return (.Alternation)
		}
		return nil
	}
	 = func( Alternation) error {
		for ,  := range .Concatenations {
			for ,  := range .Repetitions {
				if  := (.Element);  != nil {
					return 
				}
			}
		}
		return nil
	}
	if .minCost[.Name] >= astUnbounded {
		return nil, fmt.Errorf("rule %q is non-productive (cannot derive any finite string)", )
	}
	if  := (.Alternation);  != nil {
		return nil, 
	}
	return , nil
}

// Generate maps the tape to a production the grammar admits. Total and
// deterministic: any tape (including nil) yields a valid production; an
// exhausted tape biases toward the shortest one.
func ( *ASTGenerator) ( []byte) []byte {
	return .walk(&tapeSource{tape: })
}

// GenerateRand draws a production using r as the entropy source.
func ( *ASTGenerator) ( *rand.Rand) []byte {
	return .walk(randSource{r: })
}

func ( *ASTGenerator) ( source) []byte {
	 := []byte{}
	.genAlt(, &, .start.Alternation, 0)
	return 
}

// over reports whether we should stop taking expansions for their own sake and
// steer toward the nearest terminal string.
func ( *ASTGenerator) ( *[]byte,  int) bool {
	return  >= .maxDepth || len(*) >= .maxLen
}

func ( *ASTGenerator) ( source,  *[]byte,  Alternation,  int) {
	 := .Concatenations
	if len() == 0 {
		return
	}
	 := 0
	if .over(, ) {
		 = .cheapestConcat() // steer: pick the cheapest-to-finish branch
	} else if len() > 1 {
		 = .intn(len())
	}
	.genConcat(, , [], )
}

func ( *ASTGenerator) ( source,  *[]byte,  Concatenation,  int) {
	for ,  := range .Repetitions {
		.genRep(, , , )
	}
}

func ( *ASTGenerator) ( source,  *[]byte,  Repetition,  int) {
	 := .Min
	 := .Max
	if  == inf ||  <  { // unbounded: cap the optional unrolling
		 =  + .maxRepeat
	}
	 := 
	if !.over(, ) &&  >  {
		 =  + .intn(-+1)
	}
	for  := 0;  < ; ++ {
		.genElem(, , .Element, )
		// Stop optional extras once over length, but always emit the mandatory lo.
		if +1 >=  && len(*) >= .maxLen {
			break
		}
	}
}

func ( *ASTGenerator) ( source,  *[]byte,  ElemItf,  int) {
	switch e := .(type) {
	case ElemRulename:
		// Guaranteed defined+productive by NewASTGenerator.
		 := GetRule(.Name, .g.Rulemap)
		.genAlt(, , .Alternation, +1)

	case ElemGroup:
		.genAlt(, , .Alternation, )

	case ElemOption:
		if !.over(, ) && .intn(2) == 1 {
			.genAlt(, , .Alternation, )
		}

	case ElemCharVal:
		for ,  := range .Values {
			if !.Sensitive && isASCIILetter() && .intn(2) == 1 {
				 = flipASCIICase()
			}
			* = append(*, []byte(string())...)
		}

	case ElemNumVal:
		switch .Status {
		case StatSeries:
			for ,  := range .Elems {
				 := numvalToRune(, .Base)
				// Emit only real characters; an out-of-range value cannot appear
				// in UTF-8 input, so the series would never match anyway.
				if utf8.ValidRune() {
					* = append(*, []byte(string())...)
				}
			}
		case StatRange:
			,  := numvalToRune(.Elems[0], .Base), numvalToRune(.Elems[1], .Base)
			// Emit within the representable (Unicode) subset of the range.
			if  > utf8.MaxRune {
				 = utf8.MaxRune
			}
			if  > utf8.MaxRune ||  >  {
				break // nothing representable to emit
			}
			 := int(-) + 1
			if  < 1 {
				 = 1
			}
			* = append(*, []byte(string(+rune(.intn())))...)
		}

	case ElemProseVal:
		// prose-val is informal text; nothing mechanical to emit.
	}
}

// cheapestConcat returns the index of the concatenation with the smallest
// minimum expansion cost -- the fastest way to finish the current alternation.
func ( *ASTGenerator) ( []Concatenation) int {
	,  := 0, .costConcat([0])
	for  := 1;  < len(); ++ {
		if  := .costConcat([]);  <  {
			,  = , 
		}
	}
	return 
}

// ---- minimum-expansion-cost cost model (for productivity + steering) ----

func ( *ASTGenerator) ( Alternation) int {
	if len(.Concatenations) == 0 {
		return 0
	}
	 := astUnbounded
	for ,  := range .Concatenations {
		if  := .costConcat();  <  {
			 = 
		}
	}
	return 
}

func ( *ASTGenerator) ( Concatenation) int {
	 := 0
	for ,  := range .Repetitions {
		 = addClamp(, mulClamp(.Min, .costElem(.Element)))
	}
	return 
}

func ( *ASTGenerator) ( ElemItf) int {
	switch e := .(type) {
	case ElemRulename:
		 := GetRule(.Name, .g.Rulemap)
		if  == nil {
			return astUnbounded // undefined rule
		}
		if ,  := .minCost[.Name];  {
			// +1 expansion penalty: referencing a rule always costs strictly
			// more than emitting a terminal, so a recursive branch can never
			// tie with (and be chosen over) a terminating one -- even when a
			// nullable prefix makes their emitted lengths equal.
			return addClamp(1, )
		}
		return astUnbounded
	case ElemGroup:
		return .costAlt(.Alternation)
	case ElemOption:
		return 0 // can be skipped
	case ElemCharVal:
		return len(string(.Values))
	case ElemNumVal:
		switch .Status {
		case StatSeries:
			 := 0
			for ,  := range .Elems {
				 += len(string(numvalToRune(, .Base)))
			}
			return 
		default: // StatRange: one rune, take the lower bound's encoded length
			return len(string(numvalToRune(.Elems[0], .Base)))
		}
	case ElemProseVal:
		return 0
	}
	return 0
}

func addClamp(,  int) int {
	if  >= astUnbounded ||  >= astUnbounded {
		return astUnbounded
	}
	if  :=  + ;  < astUnbounded {
		return 
	}
	return astUnbounded
}

func mulClamp(,  int) int {
	if  == 0 {
		return 0
	}
	if  >= astUnbounded {
		return astUnbounded
	}
	if  :=  * ;  >= 0 &&  < astUnbounded {
		return 
	}
	return astUnbounded
}

func isASCIILetter( rune) bool {
	return ( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z')
}

func flipASCIICase( rune) rune {
	switch {
	case  >= 'a' &&  <= 'z':
		return  - 'a' + 'A'
	case  >= 'A' &&  <= 'Z':
		return  - 'A' + 'a'
	}
	return 
}