package goabnf

import (
	
	
	
)

// fuzz.go turns a (fully expanded) transition graph into a total
// function from arbitrary bytes to a string the grammar admits. It is the core
// primitive for structure-aware fuzzing with testing.F: because every input
// maps to a valid production, the fuzzing engine's mutations explore the
// grammar's structure instead of bouncing off the target's first syntax check.
//
// The walk is deliberately different from a TransitionGraphReader: the reader
// enumerates entrypoint->endpoint trails (each directed edge at most once) for
// finite coverage, whereas the generator takes a free walk that MAY repeat
// edges -- so it can unroll a "*" repetition into "a", "aa", "aaa", ... -- and
// is kept finite by explicit budgets (max length, per-edge repetitions, total
// steps) rather than by the no-repeat rule. When a budget is hit the walk does
// not stop dead (that could leave it on a non-accepting node); it steers along
// shortest paths to the nearest endpoint, so the output is always a complete,
// valid production.

// source supplies the decisions that drive a walk. Two implementations exist: a
// byte tape (for testing.F, where mutations of the tape are the fuzzing signal)
// and a *rand.Rand (for property tests and corpus generation). intn(n) returns
// a value in [0, n); when a tape is exhausted it returns 0, which makes
// generation total and biases an empty/short tape toward the shortest
// production.
type source interface {
	intn(n int) int
}

type tapeSource struct {
	tape []byte
	pos  int
}

func ( *tapeSource) ( int) int {
	if  <= 1 {
		return 0
	}
	// Read just enough bytes to address n, big-endian. One byte per decision
	// when n <= 256 keeps locality high: a single-byte mutation flips at most
	// one decision (until the number of decisions changes).
	 := 1
	for  := ;  > 256;  = ( + 255) / 256 {
		++
	}
	 := 0
	for  := 0;  < ; ++ {
		 := 0
		if .pos < len(.tape) {
			 = int(.tape[.pos])
			.pos++
		}
		 = <<8 | 
		if  < 0 { // overflow guard on absurd widths
			 &= 0x7fffffff
		}
	}
	return  % 
}

type randSource struct{ r *rand.Rand }

func ( randSource) ( int) int {
	if  <= 1 {
		return 0
	}
	return .r.Intn()
}

// indexedSource addresses the tape by decision number rather than a moving
// cursor: the i-th decision always reads the fixed-width slot [i*stride, ...],
// regardless of how many bytes earlier decisions "needed". This keeps a tape
// edit local -- it can only perturb the one decision whose slot it lands in --
// so an upstream structural change no longer reframes the bytes every later
// decision reads (the residual non-locality is purely semantic: a forked walk
// reaches different nodes, where the same slot byte means a different choice).
// stride 4 addresses any choice count up to 2^32, well above the widest
// (full-Unicode) num-val range.
type indexedSource struct {
	tape []byte
	i    int
}

const indexedStride = 4

func ( *indexedSource) ( int) int {
	if  <= 1 {
		return 0
	}
	 := .i * indexedStride
	.i++
	 := 0
	for  := range indexedStride {
		 := 0
		if + < len(.tape) {
			 = int(.tape[+])
		}
		 = <<8 | 
		if  < 0 {
			 &= 0x7fffffff
		}
	}
	return  % 
}

// Generator produces strings admitted by a transition graph.
type Generator struct {
	tg *TransitionGraph

	maxLength int
	maxReps   int
	maxSteps  int

	stableAddr bool

	endSet    map[string]bool // node ID -> is an endpoint ("" == emptyNode)
	canReach  map[string]bool // node ID -> can still reach some endpoint
	distToEnd map[string]int  // node ID -> fewest steps to an endpoint
	entries   []*Node         // entrypoints that can reach an endpoint

	emitCache map[string][]emission // node ID -> octet emissions (lazy, for ExpectedNext)
	emitOK    map[string]bool       // node ID -> emissions analyzable
}

// GenOption configures a Generator.
type GenOption interface {
	apply(*Generator)
}

type genOptionFunc func(*Generator)

func ( genOptionFunc) ( *Generator) {
	()
}

// WithMaxLength bounds the number of bytes a generated production may contain.
// Once reached the walk steers to the nearest endpoint. Defaults to 4096.
func ( int) GenOption {
	return genOptionFunc(func( *Generator) {
		.maxLength = 
	})
}

// WithMaxReps bounds how many times a single edge may be traversed, which caps
// how far repetitions ("*" / "1*" / "n*m") are unrolled. Defaults to 32.
func ( int) GenOption {
	return genOptionFunc(func( *Generator) {
		.maxReps = 
	})
}

// WithMaxSteps is a hard backstop on the total number of walk steps, defending
// against pathological graphs. Defaults to 100000.
func ( int) GenOption {
	return genOptionFunc(func( *Generator) {
		.maxSteps = 
	})
}

// WithStableAddressing makes Generate address the tape by decision number
// (fixed-width slots) instead of a moving cursor. This improves locality for a
// coverage-guided engine -- a one-byte tape edit perturbs a single decision
// rather than reframing every decision downstream of it -- at the cost of
// consuming the tape less densely. Recommended for use under testing.F.
func () GenOption {
	return genOptionFunc(func( *Generator) {
		.stableAddr = true
	})
}

// NewGenerator prepares a Generator from a transition graph. The graph must be
// fully expanded -- build it with WithDeflateRules(true) when the target rule
// references other rules -- because an unexpanded rule node carries no bytes and
// could not be turned into a valid production. It returns an error naming the
// first such node otherwise. (Recursive rules cannot be expanded at all; in that
// case TransitionGraph itself returns ErrCyclicRule before reaching here.)
func ( *TransitionGraph,  ...GenOption) (*Generator, error) {
	 := &Generator{
		tg:        ,
		maxLength: 4096,
		maxReps:   32,
		maxSteps:  100_000,
	}
	for ,  := range  {
		.apply()
	}

	// Collect every reachable node and the reverse adjacency, and verify the
	// graph is fully expanded (only producing leaves and the empty node).
	 := map[string][]*Node{}
	 := map[string]*Node{}
	var  []*Node
	for ,  := range .Entrypoints {
		if  != emptyNode {
			 = append(, )
		}
	}
	for len() > 0 {
		 := [len()-1]
		 = [:len()-1]
		 := tgNodeID()
		if ,  := [];  {
			continue
		}
		[] = 
		if !producing() {
			return nil, fmt.Errorf("transition graph contains an unexpanded rule node %q; build it with WithDeflateRules(true)", .Elem.String())
		}
		for ,  := range .Nexts {
			if  == emptyNode {
				continue
			}
			[tgNodeID()] = append([tgNodeID()], )
			 = append(, )
		}
	}

	// endSet, then backward BFS from endpoints for canReach + distToEnd.
	.endSet = map[string]bool{}
	.canReach = map[string]bool{}
	.distToEnd = map[string]int{}
	var  []string
	for ,  := range .Endpoints {
		 := tgNodeID()
		.endSet[] = true
		if !.canReach[] {
			.canReach[] = true
			.distToEnd[] = 0
			 = append(, )
		}
	}
	for len() > 0 {
		 := [0]
		 = [1:]
		for ,  := range [] {
			 := tgNodeID()
			if .canReach[] {
				continue
			}
			.canReach[] = true
			.distToEnd[] = .distToEnd[] + 1
			 = append(, )
		}
	}

	for ,  := range .Entrypoints {
		if .canReach[tgNodeID()] {
			.entries = append(.entries, )
		}
	}
	return , nil
}

// Generate maps the tape to a production the grammar admits. It is total: any
// tape (including nil) yields a valid production; an exhausted tape biases
// toward the shortest completion.
func ( *Generator) ( []byte) []byte {
	if .stableAddr {
		return .walk(&indexedSource{tape: }, nil)
	}
	return .walk(&tapeSource{tape: }, nil)
}

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

// traceSeg records that out[off:off+length] was emitted by a node carrying elem.
type traceSeg struct {
	off, length int
	elem        ElemItf
}

func ( *Generator) ( source,  *[]traceSeg) []byte {
	 := []byte{}
	if len(.entries) == 0 {
		return 
	}
	 := .entries[.intn(len(.entries))]

	 := map[string]int{}
	 := 0
	for {
		if  != emptyNode && producing() {
			,  := nodeEmit(, 0)
			if  < 1 {
				 = 1
			}
			var  int32
			if  > 1 {
				 = int32(.intn(int()))
			}
			,  := nodeEmit(, )
			if  != nil && len() > 0 {
				* = append(*, traceSeg{off: len(), length: len(), elem: .Elem})
			}
			 = append(, ...)
		}

		// The empty node is a terminal entry/endpoint sentinel with no
		// successors; reaching it as an entrypoint means the whole production is
		// nullable, so stopping here yields the (valid) empty production.
		if  == emptyNode {
			break
		}

		 := tgNodeID()
		 := .endSet[]

		// liveAll: successors that can still reach an endpoint (used for
		// termination steering). liveCapped: those not yet at the per-edge cap
		// (used for ordinary random choice).
		var ,  []*Node
		for ,  := range .Nexts {
			if  == emptyNode || !.canReach[tgNodeID()] {
				continue
			}
			 = append(, )
			if [+">"+tgNodeID()] < .maxReps {
				 = append(, )
			}
		}
		if len() == 0 {
			break // terminal; canReach guarantees this node is an endpoint
		}

		 := len() >= .maxLength ||  >= .maxSteps
		 :=  || len() == 0

		var  *Node
		if  {
			if  {
				break
			}
			// One decision: 0 == stop here, otherwise continue to a successor.
			 := .intn(len() + 1)
			if  == 0 {
				break
			}
			 = [-1]
		} else if  {
			 = .nearestToEnd()
		} else {
			 = [.intn(len())]
		}

		[+">"+tgNodeID()]++
		++
		 = 
	}
	return 
}

// nearestToEnd returns the candidate with the fewest steps to an endpoint.
// Following it repeatedly walks a shortest path to an endpoint (distToEnd
// strictly decreases), so the termination phase never repeats an edge.
func ( *Generator) ( []*Node) *Node {
	 := [0]
	 := .distToEnd[tgNodeID()]
	for ,  := range [1:] {
		if  := .distToEnd[tgNodeID()];  <  {
			,  = , 
		}
	}
	return 
}

// From here, generate *negative* test inputs: strings that lie just outside the
// grammar, each paired with a label describing the violation. They are the
// complement of Generate's valid productions -- a correct target MUST reject them
// -- and they reach the error-handling paths (truncation, boundary overruns,
// trailing input) where many parser bugs live and which a valid-only generator
// can never exercise.
//
// A perturbation is NOT assumed invalid: grammars can be ambiguous or redundant
// (flipping "a" to "b" in `"a" / "b"` is still valid), so every candidate is
// checked against the grammar and only genuinely-rejected ones are returned.
// This makes the "target must reject" oracle sound.

// NearMiss returns a string just outside the grammar together with a label
// describing how it violates the grammar, or ok=false if no minimal
// perturbation within the attempt budget produced a string the grammar rejects.
// It is deterministic in tape and total.
func ( *Generator) ( []byte) ( []byte,  string,  bool) {
	 := &tapeSource{tape: }
	var  []traceSeg
	 := .walk(, &)

	for ,  := range .nearMissCandidates(, , ) {
		if .bytes == nil || string(.bytes) == string() {
			continue
		}
		,  := .tg.grammar.IsValid(.tg.rulename, .bytes)
		if  == nil && ! {
			return .bytes, .label, true
		}
	}
	return nil, "", false
}

// NearMissRand is the *rand.Rand-driven variant of NearMiss.
func ( *Generator) ( *rand.Rand) ( []byte,  string,  bool) {
	// Draw a tape and reuse the deterministic path so behaviour is identical.
	 := make([]byte, 64)
	.Read()
	return .NearMiss()
}

type candidate struct {
	bytes []byte
	label string
}

func cloneBytes( []byte) []byte {
	 := make([]byte, len())
	copy(, )
	return 
}

// nearMissCandidates proposes minimal perturbations of base, ordered with a
// little entropy from src so different tapes explore different operators first.
// Correctness does not depend on the order: NearMiss verifies each against the
// grammar.
func ( *Generator) ( source,  []byte,  []traceSeg) []candidate {
	var  []candidate

	// (1) Boundary violations: take a num-val range segment one step past its
	// edge. These are the high-value off-by-one cases.
	for ,  := range  {
		,  := numvalRange(.elem)
		if ! {
			continue
		}
		for ,  := range []struct {
			    rune
			 string
		}{
			{rune(.min - 1), "below"},
			{rune(.max + 1), "above"},
		} {
			if . < 0 || . > 0x10FFFF {
				continue
			}
			 := cloneBytes()
			 := []byte(string(.))
			 := append(append(cloneBytes([:.off]), ...), [.off+.length:]...)
			 = append(, candidate{, fmt.Sprintf("byte at offset %d is one %s num-val range %s", .off, ., .label)})
		}
	}

	// (2) Off-alphabet substitution at a chosen position: replace one byte with
	// a "wild" value. Verified, so even an unlucky pick is safe.
	if len() > 0 {
		 := .intn(len())
		for ,  := range []byte{0x00, 0xFF, [] ^ 0x20, [] + 1, '!'} {
			if  == [] {
				continue
			}
			 := cloneBytes()
			[] = 
			 = append(, candidate{, fmt.Sprintf("byte at offset %d substituted with 0x%02x", , )})
		}
	}

	// (3) Truncation: drop a suffix (incomplete input -- exercises overread /
	// "premature end" handling).
	for ,  := range []int{1, 2, len() / 2, len() - 1} {
		if  <= 0 ||  > len() {
			continue
		}
		 = append(, candidate{cloneBytes([:len()-]), fmt.Sprintf("truncated by %d byte(s) (len %d)", , len()-)})
	}

	// (4) Trailing input: append a byte (exercises "ignores trailing garbage").
	for ,  := range []byte{0x00, '!', 0xFF, 'A'} {
		 := append(cloneBytes(), )
		 = append(, candidate{, fmt.Sprintf("trailing byte 0x%02x appended", )})
	}

	// (5) Deletion of a single interior byte.
	if len() >= 2 {
		 := .intn(len())
		 := append(cloneBytes([:]), [+1:]...)
		 = append(, candidate{, fmt.Sprintf("byte at offset %d deleted", )})
	}

	// Light entropy-driven rotation so the first verified hit varies by tape.
	if len() > 1 {
		 := .intn(len())
		 = append([:], [:]...)
	}
	return 
}

type numvalInfo struct {
	min, max int32
	label    string
}

// numvalRange reports whether elem is a num-val range and, if so, its bounds.
func numvalRange( ElemItf) (numvalInfo, bool) {
	,  := .(ElemNumVal)
	if ! || .Status != StatRange {
		return numvalInfo{}, false
	}
	,  := numvalToInt32(.Elems[0], .Base), numvalToInt32(.Elems[1], .Base)
	// Clamp the upper bound to the Unicode range so the "just above" boundary
	// probe (max+1) stays a meaningful rune rather than overflowing.
	if  > utf8.MaxRune {
		 = utf8.MaxRune
	}
	return numvalInfo{min: , max: , label: .String()}, true
}

// From here answers for a given prefix "which octets may legally come next, and
// is the prefix itself a complete word?" by simulating the transition-graph
// automaton over the prefix and reading the frontier. The graph is not a plain
// byte DFA -- each node emits a multi-octet string with per-position choices
// (letter casings, num-val ranges) -- so this is an NFA-style frontier simulation,
// not a single-state walk.
//
// Its headline use is sharpening NearMiss: appending an octet that is NOT in the
// expected-next set yields a string that is provably not a prefix of any word in
// the language, i.e. guaranteed invalid, with a precise label. It also enables
// error-position testing ("the target must fail at byte N").

// octetSet is a 256-bit set of octets.
type octetSet [4]uint64

func ( *octetSet) ( byte) {
	[>>6] |= 1 << ( & 63)
}

func ( octetSet) ( byte) bool {
	return [>>6]&(1<<(&63)) != 0
}

func ( octetSet) ( octetSet) octetSet {
	return octetSet{[0] | [0], [1] | [1], [2] | [2], [3] | [3]}
}

func ( octetSet) () []byte {
	var  []byte
	for  := range 256 {
		if .has(byte()) {
			 = append(, byte())
		}
	}
	return 
}

// emission is one fixed-length alternative of a node's output: pos[j] is the set
// of octets the node may emit at byte offset j. A node usually has exactly one
// emission; a num-val range that spans several UTF-8 lengths has one per length.
type emission struct {
	pos []octetSet
}

// expectedNextRangeCap bounds how many runes a multi-byte num-val range is
// expanded into for analysis; beyond it ExpectedNext reports ok=false rather
// than doing unbounded work. ASCII ranges are always handled (<=128 octets).
const expectedNextRangeCap = 1 << 16

func ( *Generator) ( *Node) ([]emission, bool) {
	 := tgNodeID()
	if .emitCache == nil {
		.emitCache = map[string][]emission{}
		.emitOK = map[string]bool{}
	}
	if ,  := .emitCache[];  {
		return , .emitOK[]
	}
	,  := nodeEmissions()
	.emitCache[] = 
	.emitOK[] = 
	return , 
}

func nodeEmissions( *Node) ([]emission, bool) {
	switch v := .Elem.(type) {
	case ElemCharVal:
		 := emission{}
		for ,  := range .Values {
			if !.Sensitive && (( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z')) {
				,  := , 
				if  >= 'A' &&  <= 'Z' {
					 =  - 'A' + 'a'
				}
				if  >= 'a' &&  <= 'z' {
					 =  - 'a' + 'A'
				}
				var  octetSet
				.add(byte())
				.add(byte())
				.pos = append(.pos, )
			} else {
				for ,  := range []byte(string()) {
					var  octetSet
					.add()
					.pos = append(.pos, )
				}
			}
		}
		return []emission{}, true

	case ElemNumVal:
		switch .Status {
		case StatSeries:
			 := emission{}
			for ,  := range .Elems {
				 := numvalToRune(, .Base)
				if !utf8.ValidRune() {
					// An out-of-range element can never appear in UTF-8 input.
					return nil, false
				}
				for ,  := range []byte(string()) {
					var  octetSet
					.add()
					.pos = append(.pos, )
				}
			}
			return []emission{}, true
		case StatRange:
			,  := numvalToInt32(.Elems[0], .Base), numvalToInt32(.Elems[1], .Base)
			// Clamp to the Unicode range first: otherwise an out-of-range bound
			// near MaxInt32 overflows the int32 count below, bypasses the cap
			// guard, and turns the enumeration loop into a DoS. A range wholly
			// above U+10FFFF emits nothing.
			if  > utf8.MaxRune {
				 = utf8.MaxRune
			}
			if  > utf8.MaxRune ||  >  {
				return nil, false
			}
			if  <= 0x7f { // ASCII: a single one-octet emission
				var  octetSet
				for  := ;  <=  &&  <= 0x7f; ++ { // explicit ASCII bound for the conversion
					.add(byte())
				}
				return []emission{{pos: []octetSet{}}}, true
			}
			if -+1 > expectedNextRangeCap {
				return nil, false
			}
			 := map[int]*emission{}
			for  := ;  <= ; ++ {
				 := []byte(string(rune()))
				 := [len()]
				if  == nil {
					 = &emission{pos: make([]octetSet, len())}
					[len()] = 
				}
				for ,  := range  {
					.pos[].add()
				}
			}
			 := make([]emission, 0, len())
			for ,  := range  {
				 = append(, *)
			}
			return , true
		}
	}
	return nil, false
}

// ExpectedNext simulates the automaton over prefix and reports the octets that
// may legally follow it, whether prefix is itself a complete word, and whether
// the analysis succeeded (ok is false only when the graph uses a feature this
// analyzer declines to expand, e.g. an enormous multi-byte num-val range). When
// prefix is not a viable prefix of any word, next is empty and accepts is false.
func ( *Generator) ( []byte) ( []byte,  bool,  bool) {
	type  struct {
		    *Node
		,  int
	}
	 := []{}
	 := map[]bool{}
	 := func( ) {
		if ![] {
			[] = true
			 = append(, )
		}
	}
	 := func( *Node) bool {
		,  := .emissions()
		if ! {
			return false
		}
		for ,  := range  {
			if len(.pos) > 0 {
				({, , 0})
			}
		}
		return true
	}
	for ,  := range .tg.Entrypoints {
		if  == emptyNode {
			continue
		}
		if !() {
			return nil, false, false
		}
	}

	 := false
	 := true
	for ,  := range  {
		 := []{}
		 := map[]bool{}
		 := func( ) {
			if ![] {
				[] = true
				 = append(, )
			}
		}
		 = false
		for ,  := range  {
			,  := .emissions(.)
			 := [.]
			if !.pos[.].has() {
				continue
			}
			if .+1 == len(.pos) { // node s.n completes on this octet
				if .endSet[tgNodeID(.)] {
					 = true
				}
				for ,  := range ..Nexts {
					if  == emptyNode {
						continue
					}
					,  := .emissions()
					if ! {
						return nil, false, false
					}
					for ,  := range  {
						if len(.pos) > 0 {
							({, , 0})
						}
					}
				}
			} else {
				({., ., . + 1})
			}
		}
		,  = , 
		if len() == 0 {
			if  != len()-1 {
				 = false // dead before the end: prefix not viable
			}
			break
		}
	}

	if ! {
		return nil, false, true
	}
	if len() == 0 {
		 = .endSet[""] // empty word accepted iff emptyNode is an endpoint
	} else {
		 = 
	}
	var  octetSet
	for ,  := range  {
		,  := .emissions(.)
		 = .union([.].pos[.])
	}
	return .bytes(), , true
}