package goabnf

import (
	
	
	
)

// recognize.go holds the engine behind (*Grammar).IsValid.
//
// Validity only needs the SET of input positions each element can reach, never
// the (possibly exponential) set of distinct parse trees that reach them. We
// compute, for each (element, start-index), the set of reachable end-indices,
// deduplicating positions at every step and memoizing per (element, index).
// Positions live in [0, len(input)], so the work is polynomial rather than the
// exponential path enumeration that Parse performs.
//
// IsValid enforces left-termination before calling in, so the in-progress
// guard below is defense-in-depth: it can never fire for a left-terminating
// grammar (a same-index re-entry implies the rule is not left terminating).

type recognizer struct {
	g          *Grammar
	input      []byte
	memo       map[string]map[int]bool // element.String()+"@"+index -> reachable end set
	inProgress map[string]bool

	// Left-recursion support. leftRec maps each left-recursive rule (lowercase
	// name) to its left-corner SCC, grown jointly. growing holds the live seed
	// of each rule currently being grown (key "rule@index"); a re-entrant call
	// returns the seed instead of recursing.
	leftRec map[string][]string
	growing map[string]map[int]bool
}

func cloneSet( map[int]bool) map[int]bool {
	 := make(map[int]bool, len())
	for  := range  {
		[] = true
	}
	return 
}

func ( *recognizer) ( Alternation,  int) map[int]bool {
	 := map[int]bool{}
	for ,  := range .Concatenations {
		for  := range .reachConcat(, ) {
			[] = true
		}
	}
	return 
}

func ( *recognizer) ( Concatenation,  int) map[int]bool {
	 := map[int]bool{: true}
	for ,  := range .Repetitions {
		 := map[int]bool{}
		for  := range  {
			for  := range .reachRep(, ) {
				[] = true
			}
		}
		 = 
		if len() == 0 {
			break
		}
	}
	return 
}

func ( *recognizer) ( Repetition,  int) map[int]bool {
	 := map[int]bool{}
	if .Min == 0 {
		[] = true
	}

	// level = positions reachable after exactly c occurrences.
	 := map[int]bool{: true}
	// seen = every position reached at any count so far. reachElem only moves
	// forward (an end position is >= its start), so once a step introduces no
	// position outside seen, the reachable set has closed and no later
	// repetition can add a new end position. Breaking there keeps an unbounded
	// repetition over an element with large reach-sets (e.g. *(1*ALPHA)) at
	// O(n^2); the previous len(next)==len(level) test never tripped because
	// level shrank by one each step ({1..n}, {2..n}, ...), giving O(n^3).
	 := map[int]bool{: true}

	// Levels are stationary after at most len(input)+1 counts: reachElem only
	// moves forward, so whether position x is in a level depends on positions
	// below x plus x reaching itself, and each position settles one count after
	// the ones below it. The stationary check below therefore fires within cap.
	 := len(.input) + 2
	for  := 1;  <= ; ++ {
		if .Max != inf &&  > .Max {
			break
		}
		 := map[int]bool{}
		for  := range  {
			for  := range .reachElem(.Element, ) {
				[] = true
			}
		}
		if len() == 0 {
			break
		}
		if  >= .Min {
			for  := range  {
				[] = true
			}
		}
		 := false
		for  := range  {
			if ![] {
				[] = true
				 = true
			}
		}
		// Stationary level: every further count reaches the same positions, so
		// a minimum not yet met is met by that same set. This happens with a
		// nullable element, e.g. 3"" on an empty input, where the count must
		// go past the input length to reach the minimum.
		if  < .Min && sameSet(, ) {
			if .Max == inf || .Min <= .Max {
				for  := range  {
					[] = true
				}
			}
			break
		}
		 = 
		// Reachable set closed and the minimum-count requirement met.
		if ! &&  >= .Min {
			break
		}
	}
	return 
}

func ( *recognizer) ( ElemItf,  int) map[int]bool {
	// Left-recursive rulenames are resolved by seed-growing rather than the
	// flat memoized recursion below (which would cut the recursion to empty and
	// under-accept).
	if ,  := .(ElemRulename);  {
		if ,  := .leftRec[strings.ToLower(.Name)];  {
			return .reachLeftRec(strings.ToLower(.Name), , )
		}
	}

	 := .String() + "@" + strconv.Itoa()
	if ,  := .memo[];  {
		return 
	}
	if .inProgress[] {
		// Re-entry at the same position == non-progressing recursion in a rule
		// not flagged left-recursive. Return empty (defense-in-depth) instead of
		// looping forever.
		return map[int]bool{}
	}
	.inProgress[] = true
	 := .computeElem(, )
	delete(.inProgress, )
	// Safe to cache: a rule reached here either is independent of any actively
	// growing seed, or is itself a growing SCC member (handled by reachLeftRec
	// via r.growing, not this path). A lower left-corner SCC cannot reference
	// the SCC growing above it -- they would be one SCC -- so its result is
	// stable. Caching nested SCCs is what keeps left recursion polynomial.
	.memo[] = cloneSet()
	return 
}

// reachLeftRec computes the reachable end-set of a left-recursive rule at index
// by growing the whole left-corner SCC from the empty seed to its least
// fixpoint. Each growth step adds end-positions (bounded by len(input)), so it
// terminates; a re-entrant call to any SCC member at the same index returns the
// current seed. Pure (base-less) left recursion correctly settles at the empty
// set, i.e. "no match".
func ( *recognizer) ( string,  []string,  int) map[int]bool {
	 := "@" + strconv.Itoa()
	 :=  + 
	if ,  := .memo[];  {
		return 
	}
	if ,  := .growing[];  {
		return  // re-entrant: return the current seed
	}

	 := make([]string, len())
	for ,  := range  {
		[] =  + 
		.growing[[]] = map[int]bool{}
	}
	for  := true; ; {
		 = false
		for ,  := range  {
			 := GetRule(, .g.Rulemap)
			if  == nil {
				continue
			}
			 := .reachAlt(.Alternation, )
			 := .growing[[]]
			for  := range  {
				if ![] {
					[] = true
					 = true
				}
			}
		}
	}

	// The fixpoint converged. These end-sets are final and independent of any
	// outer growing seed (the SCC only re-references its own members, held in
	// r.growing, and strictly lower SCCs, which cannot reference it back), so
	// they can be memoized unconditionally.
	var  map[int]bool
	for ,  := range  {
		 := .growing[[]]
		delete(.growing, [])
		.memo[[]] = cloneSet()
		if  ==  {
			 = cloneSet()
		}
	}
	return 
}

func ( *recognizer) ( ElemItf,  int) map[int]bool {
	 := map[int]bool{}
	switch v := .(type) {
	case ElemRulename:
		 := GetRule(.Name, .g.Rulemap)
		if  == nil {
			return 
		}
		return .reachAlt(.Alternation, )

	case ElemGroup:
		return .reachAlt(.Alternation, )

	case ElemOption:
		[] = true // 0 occurrences
		for  := range .reachAlt(.Alternation, ) {
			[] = true
		}
		return 

	case ElemProseVal:
		// prose-val can't be matched (same as the original parser)
		return 

	case ElemNumVal:
		switch .Status {
		case StatRange:
			if  >= len(.input) {
				return 
			}
			// Bounds are numeric: a range straddling the Unicode ceiling still
			// matches its representable (rune) subset, one wholly above it matches
			// nothing. numvalToRune never panics (saturates out-of-int32 bounds).
			 := numvalToRune(.Elems[0], .Base)
			 := numvalToRune(.Elems[1], .Base)
			,  := utf8.DecodeRune(.input[:])
			if  == utf8.RuneError &&  == 1 {
				return 
			}
			if  <=  &&  <=  {
				[+] = true
			}
		case StatSeries:
			 := 
			for  := 0;  < len(.Elems); ++ {
				 := numvalToRune(.Elems[], .Base)
				// A series element must denote a real character; an out-of-range
				// value can never appear in UTF-8 input, so the series matches
				// nothing (and we avoid a spurious U+FFFD coincidence).
				if !utf8.ValidRune() {
					return 
				}
				 := string()
				 := len([]byte())
				if + > len(.input) ||  != string(.input[:+]) {
					return 
				}
				 += 
			}
			[] = true
		}
		return 

	case ElemCharVal:
		 := 
		for  := 0;  < len(.Values); ++ {
			if  >= len(.input) {
				return 
			}
			,  := utf8.DecodeRune(.input[:])
			if  == utf8.RuneError &&  == 1 {
				return 
			}
			if !sensequal(.Values[], , .Sensitive) {
				return 
			}
			 += 
		}
		[] = true
		return 
	}
	return 
}

func sameSet(,  map[int]bool) bool {
	if len() != len() {
		return false
	}
	for  := range  {
		if ![] {
			return false
		}
	}
	return true
}