package goabnf

import (
	
	
	
	
	
	
	
)

// TransitionGraph represent a grammar transition graph.
// It contains the list of entrypoints and endpoints.
// You could travel through the graph starting from the entrypoints.
type TransitionGraph struct {
	grammar  *Grammar
	rulename string
	options  *tgoptions

	Entrypoints []*Node
	Endpoints   []*Node
}

// Node of a TransitionGraph.
// Unically identifiate the node of the transition graph along
// with its underlying element and its next nodes.
type Node struct {
	ID   string
	Elem ElemItf

	Nexts []*Node
}

// TransitionGraph builds a transition graph out of a grammar
// and the given rulename.
// TODO it is possible to build transition graph out of cylic rules iff	it is not concatenated to another repetition (can't pipe O->I as there is no O). For instance, `a = "a" a` can exist.
func ( *Grammar) ( string,  ...TGOption) (*TransitionGraph, error) {
	// Build transition graph machine
	 := &tgoptions{
		deflateRules:        false,
		deflateNumVals:      false,
		deflateCharVals:     false,
		repetitionThreshold: 256,
		maxNodes:            0, // 0 == unbounded (backward compatible)
	}
	for ,  := range  {
		.apply()
	}
	 := &tgmachine{
		options: ,
		grammar: ,
		buf:     map[string][2][]*Node{},
	}

	// Find the rule
	 := GetRule(, .Rulemap)
	if  == nil {
		return nil, &ErrRuleNotFound{
			Rulename: ,
		}
	}

	// Ensure the rule is semantically valid and does not contain cycle.
	// Semantic validity is required to ensure rule dependencies actually
	// exist, while no cycle is required because the algorithm is recursive
	// and may not stop else.
	if .deflateRules {
		if  := SemvalABNF();  != nil {
			return nil, 
		}
	}
	,  := .RuleContainsCycle()
	if  != nil {
		return nil, 
	}
	if  {
		return nil, &ErrCyclicRule{
			Rulename: ,
		}
	}

	// Build transition graph
	, ,  := .altGraph(.Alternation)
	if  != nil {
		return nil, 
	}
	return &TransitionGraph{
		grammar:     ,
		rulename:    ,
		options:     ,
		Entrypoints: ,
		Endpoints:   ,
	}, nil
}

var (
	// The empty node enable to bridge the no-entrypoint case of a repetition.
	// This occurs when the minimum is 0.
	// It disappear as soon as the repetition is piped as an input from lower
	// inputs to upper outputs.
	emptyNode = (*Node)(nil)
)

type tgoptions struct {
	deflateRules        bool
	deflateNumVals      bool
	deflateCharVals     bool
	repetitionThreshold int
	maxNodes            int
}

type TGOption interface {
	apply(opts *tgoptions)
}

type deflateRulesOption bool

func ( deflateRulesOption) ( *tgoptions) {
	.deflateRules = bool()
}

// WithDeflateRules when passed to true, will recursively build the transition
// graphs of the rules it uses (reuse them if possible) and concatenate the
// sub transition graphs.
// It generates a more complex but exhaustive transition graph.
func ( bool) TGOption {
	return deflateRulesOption()
}

var _ TGOption = deflateRulesOption(false)

type deflateNumValsOption bool

func ( deflateNumValsOption) ( *tgoptions) {
	.deflateNumVals = bool()
}

// WithDeflateNumVals when passed to true, will replace a single node representing
// the ranges or series of multiple numeric values to individual nodes.
// It generates a more complex but exhaustive transition graph.
func ( bool) TGOption {
	return deflateNumValsOption()
}

var _ TGOption = deflateNumValsOption(false)

type deflateCharVals bool

func ( deflateCharVals) ( *tgoptions) {
	.deflateCharVals = bool()
}

// WithDeflateCharVals when passed to true, will replace a single node representing
// the char value to an exhaustive concatenation of all characters (lower and upper
// case) and the transitions between them.
func ( bool) TGOption {
	return deflateCharVals()
}

var _ TGOption = deflateCharVals(false)

type repetitionThreshold int

func ( repetitionThreshold) ( *tgoptions) {
	.repetitionThreshold = int()
}

// WithRepetitionThreshold defines the threshold to block a large repetition
// to occur, elseway it may consum all memory to build the transition graph.
// For instance, a rule defined as follows may self-DoS go-abnf.
//
// a = 9555("a")
//
// WARNING it does not avoid such memory consumption on chained repetitions.
// For instance, the two following cases could produce large transition graphs
// without control with this functional option.
//
// a = 10( 10( 10("a") ) )
//
// a = 10 ( 10*"a" ( 10"a" 9"a" 8"a" ) / ( *10"a" *10"a" *10"a" ) ) 10"a"
//
// Defaults to 256.
func ( int) TGOption {
	return repetitionThreshold()
}

type maxNodesOption int

func ( maxNodesOption) ( *tgoptions) {
	.maxNodes = int()
}

// WithMaxNodes bounds the total number of nodes the transition graph may
// allocate during construction. Unlike WithRepetitionThreshold, which only caps
// a single repetition, this bounds the *whole* graph and so also defends against
// the combinatorial blow-up of nested repetitions (e.g. 10( 10( 10("a") ) )) and
// of wide num-val ranges deflated with WithDeflateNumVals. When the bound would
// be exceeded, construction stops with *ErrMaxNodesExceeded before the nodes are
// allocated.
//
// A value <= 0 (the default) means unbounded, preserving the previous behaviour.
// Set a positive bound when building transition graphs from untrusted grammars
// to keep the work within a controlled domain.
func ( int) TGOption {
	return maxNodesOption()
}

// reserve accounts for n nodes about to be created, failing fast (before any
// allocation) when the WithMaxNodes budget would be exceeded. It is a no-op when
// the budget is unbounded.
func ( *tgmachine) ( int) error {
	if .options.maxNodes <= 0 {
		return nil // unbounded
	}
	if  < 0 || .nodeCount+ < 0 || .nodeCount+ > .options.maxNodes {
		return &ErrMaxNodesExceeded{Max: .options.maxNodes}
	}
	.nodeCount += 
	return nil
}

// reserveClones accounts for cloning the subgraph reachable from entries reps
// times. When the budget is unbounded it does no work at all (in particular it
// skips the reachability count), so the default path keeps its previous cost.
func ( *tgmachine) ( int,  []*Node) error {
	if .options.maxNodes <= 0 {
		return nil
	}
	return .reserve( * countReachable())
}

// countReachable counts the distinct non-empty nodes reachable from entries,
// i.e. how many nodes cloneTransitionGraph would clone.
func countReachable( []*Node) int {
	 := map[string]bool{}
	 := make([]*Node, 0, len())
	for ,  := range  {
		if  != emptyNode {
			 = append(, )
		}
	}
	for len() > 0 {
		 := [len()-1]
		 = [:len()-1]
		if  == emptyNode || [.ID] {
			continue
		}
		[.ID] = true
		for ,  := range .Nexts {
			if  != emptyNode && ![.ID] {
				 = append(, )
			}
		}
	}
	return len()
}

// CoverageMode selects what set of strings a TransitionGraphReader produces.
type CoverageMode int

const (
	// CoverageAllTrails (mode A, the default) emits every entrypoint->endpoint
	// trail (a walk using each directed edge at most once) and, for each trail,
	// every combination of its nodes' terminal variations. It is finite and
	// terminating for any graph, but on dense graphs or wide range/charval nodes
	// the number of trail x variation combinations can be very large.
	CoverageAllTrails CoverageMode = iota

	// CoverageCompact (mode B) emits a small set of strings that still covers
	// every reachable vertex, every edge, and every terminal value (each charval
	// casing, each numval range value) at least once, then stops. Its size is
	// bounded by roughly (#edges + #vertices + sum of per-node variations), so it
	// stays small even for grammars where CoverageAllTrails explodes.
	CoverageCompact
)

// ReaderOption configures a TransitionGraphReader.
type ReaderOption interface {
	apply(*readerOptions)
}

type readerOptions struct {
	mode CoverageMode
}

type coverageModeOption CoverageMode

func ( coverageModeOption) ( *readerOptions) {
	.mode = CoverageMode()
}

// WithCoverageMode selects the coverage strategy of the reader (CoverageAllTrails
// by default, or CoverageCompact for a bounded covering set).
func ( CoverageMode) ReaderOption {
	return coverageModeOption()
}

func ( *TransitionGraph) ( ...ReaderOption) *TransitionGraphReader {
	 := readerOptions{mode: CoverageAllTrails}
	for ,  := range  {
		.apply(&)
	}
	return &TransitionGraphReader{tg: , mode: .mode}
}

// TransitionGraphReader produces a finite set of strings that COVERS the
// transition graph: every reachable vertex and edge that lies on some
// entrypoint->endpoint walk appears in at least one produced string. It does so
// by enumerating every entrypoint->endpoint *trail* (a walk that uses each
// directed edge at most once) in order of increasing length, and for each trail
// every combination of its nodes' terminal variations (char-val casing,
// num-val ranges). Trails are bounded by the number of edges, so the set is
// finite and enumeration always terminates -- for any graph, cyclic or not.
type TransitionGraphReader struct {
	tg *TransitionGraph

	mode CoverageMode
	all  map[string]*Node // every node reachable from the entrypoints

	// CoverageCompact precomputed output.
	prods        [][]byte
	prodIdx      int
	builtCompact bool

	prepared bool
	entries  []*Node         // entrypoints that can reach an endpoint via producing nodes
	endSet   map[string]bool // endpoint node IDs
	canReach map[string]bool // node can reach an endpoint via producing nodes

	// Trail enumeration state.
	length          int            // current trail length (number of nodes)
	stack           []pathFrame    // current trail being walked
	usedEdges       map[string]int // edges currently on the trail (>0 == used)
	levelHadAnyPath bool           // any length-`length` trail seen this level
	exhausted       bool           // no more trails (coverage complete)

	// Variation odometer for the current trail.
	havePath bool
	varIdx   []int32
	varTot   []int32

	// Staged production.
	staged    []byte
	hasStaged bool
}

type pathFrame struct {
	node    *Node
	cursor  int
	allowed []*Node // children selectable at this depth given the trail prefix
}

func tgNodeID( *Node) string {
	if  == nil {
		return ""
	}
	return .ID
}

// producing reports whether a node can emit terminal bytes. Rulename nodes
// (present only when rules are not deflated) cannot, so no trail may pass
// through them.
func producing( *Node) bool {
	if  == emptyNode {
		return true
	}
	switch .Elem.(type) {
	case ElemCharVal, ElemNumVal:
		return true
	default:
		return false
	}
}

func ( *TransitionGraphReader) () {
	if .prepared {
		return
	}
	.prepared = true
	.endSet = map[string]bool{}
	for ,  := range .tg.Endpoints {
		.endSet[tgNodeID()] = true
	}
	.usedEdges = map[string]int{}

	// Collect every node reachable from the entrypoints.
	 := map[string]*Node{}
	var  func( *Node)
	 = func( *Node) {
		 := tgNodeID()
		if ,  := [];  {
			return
		}
		[] = 
		if  == emptyNode {
			return // the empty sentinel ((*Node)(nil)) has no successors
		}
		for ,  := range .Nexts {
			()
		}
	}
	for ,  := range .tg.Entrypoints {
		()
	}
	.all = 

	// canReach[n] = n can produce AND (n is an endpoint OR some producing
	// successor of n can reach an endpoint). Monotonic fixpoint.
	.canReach = map[string]bool{}
	for  := true; ; {
		 = false
		for ,  := range  {
			if .canReach[] || !producing() {
				continue
			}
			 := .endSet[]
			if ! &&  != emptyNode {
				for ,  := range .Nexts {
					if producing() && .canReach[tgNodeID()] {
						 = true
						break
					}
				}
			}
			if  {
				.canReach[] = true
				 = true
			}
		}
	}

	for ,  := range .tg.Entrypoints {
		if producing() && .canReach[tgNodeID()] {
			.entries = append(.entries, )
		}
	}
}

func edgeStr(,  *Node) string {
	return tgNodeID() + ">" + tgNodeID()
}

// allowedAt returns the children selectable at depth d given the current trail
// prefix: successors that can still reach an endpoint and whose edge is not yet
// used on this trail. At depth 0 the "children" are the entrypoints.
func ( *TransitionGraphReader) ( int) []*Node {
	if  == 0 {
		return .entries
	}
	 := .stack[-1].node
	if  == emptyNode {
		return nil // empty sentinel has no successors
	}
	var  []*Node
	for ,  := range .Nexts {
		if !.canReach[tgNodeID()] {
			continue
		}
		if .usedEdges[edgeStr(, )] > 0 {
			continue
		}
		 = append(, )
	}
	return 
}

func ( *TransitionGraphReader) ( int) bool {
	 := .allowedAt()
	if len() == 0 {
		return false
	}
	 := [0]
	if  >= 1 {
		.usedEdges[edgeStr(.stack[-1].node, )]++
	}
	.stack = append(.stack, pathFrame{node: , cursor: 0, allowed: })
	return true
}

func ( *TransitionGraphReader) () bool {
	for len(.stack) > 0 {
		 := len(.stack) - 1
		 := &.stack[]
		if  >= 1 {
			.usedEdges[edgeStr(.stack[-1].node, .node)]--
		}
		if .cursor+1 < len(.allowed) {
			.cursor++
			.node = .allowed[.cursor]
			if  >= 1 {
				.usedEdges[edgeStr(.stack[-1].node, .node)]++
			}
			return true
		}
		.stack = .stack[:]
	}
	return false
}

// nextLeaf advances the trail to the next walk of exactly tgr.length nodes.
func ( *TransitionGraphReader) () bool {
	 := .length
	for {
		switch {
		case len(.stack) == :
			if !.bump() {
				return false
			}
		case len(.stack) < :
			if !.pushFirst(len(.stack)) {
				if !.bump() {
					return false
				}
			}
		}
		if len(.stack) ==  {
			.levelHadAnyPath = true
			return true
		}
	}
}

func ( *TransitionGraphReader) () {
	.stack = .stack[:0]
	for  := range .usedEdges {
		delete(.usedEdges, )
	}
	.levelHadAnyPath = false
}

// advancePath sets tgr.stack to the next entrypoint->endpoint trail, returning
// false once every trail has been produced (coverage complete).
func ( *TransitionGraphReader) () bool {
	for {
		if .length == 0 {
			.length = 1
			.resetLevel()
		}
		for .nextLeaf() {
			if .endSet[tgNodeID(.stack[len(.stack)-1].node)] {
				return true
			}
		}
		if !.levelHadAnyPath {
			return false // no trail this long exists => done
		}
		.length++
		.resetLevel()
	}
}

func ( *TransitionGraphReader) () {
	if .hasStaged || .exhausted {
		return
	}
	if !.havePath {
		if !.advancePath() {
			.exhausted = true
			return
		}
		.havePath = true
		.varTot = .varTot[:0]
		.varIdx = .varIdx[:0]
		for  := range .stack {
			,  := nodeEmit(.stack[].node, 0)
			if  < 1 {
				 = 1
			}
			.varTot = append(.varTot, )
			.varIdx = append(.varIdx, 0)
		}
	}
	.staged = .staged[:0]
	for  := range .stack {
		,  := nodeEmit(.stack[].node, .varIdx[])
		.staged = append(.staged, ...)
	}
	.hasStaged = true
}

func ( *TransitionGraphReader) () {
	.hasStaged = false
	 := len(.varIdx) - 1
	for  >= 0 {
		.varIdx[]++
		if .varIdx[] < .varTot[] {
			break
		}
		.varIdx[] = 0
		--
	}
	if  < 0 {
		.havePath = false // variations exhausted -> move to next trail
	}
}

// Next reports whether another covering string is available.
func ( *TransitionGraphReader) () bool {
	.prepare()
	if .mode == CoverageCompact {
		.buildCompact()
		return .prodIdx < len(.prods)
	}
	.ensureStaged()
	return .hasStaged
}

// Scan returns the next covering string, or nil once coverage is complete.
func ( *TransitionGraphReader) () []byte {
	.prepare()
	if .mode == CoverageCompact {
		.buildCompact()
		if .prodIdx >= len(.prods) {
			return nil
		}
		 := .prods[.prodIdx]
		.prodIdx++
		return 
	}
	.ensureStaged()
	if !.hasStaged {
		return nil
	}
	 := make([]byte, len(.staged))
	copy(, .staged)
	.consumeStaged()
	return 
}

// buildCompact precomputes the CoverageCompact output: a bounded set of strings
// that together visit every reachable vertex, traverse every edge, and emit every
// terminal value (each charval casing, each numval range value) at least once.
// It is greedy, not minimal, but its size is bounded by roughly
// (#edges + #vertices + sum of per-node variation counts).
func ( *TransitionGraphReader) () {
	if .builtCompact {
		return
	}
	.builtCompact = true

	 := func( *Node) []*Node {
		if  == emptyNode {
			return nil
		}
		var  []*Node
		for ,  := range .Nexts {
			if producing() && .canReach[tgNodeID()] {
				 = append(, )
			}
		}
		return 
	}

	// Forward BFS from entrypoints: coverable vertices, edges, and entry->node
	// shortest-path predecessors.
	 := map[string]*Node{}
	 := map[string]*Node{}
	 := map[string]int{} // stable BFS discovery index per node
	var  []*Node              // nodes in discovery order
	type  struct{ ,  *Node }
	var  []
	 := map[string]bool{}
	var  []*Node
	 := func( *Node) {
		 := tgNodeID()
		if ,  := [];  {
			return
		}
		[] = 
		[] = 
		[] = len()
		 = append(, )
		 = append(, )
	}
	for ,  := range .entries {
		()
	}
	for len() > 0 {
		 := [0]
		 = [1:]
		for ,  := range () {
			 := tgNodeID()
			 := tgNodeID() + ">" + 
			if ![] {
				[] = true
				 = append(, {, })
			}
			if ,  := []; ! {
				[] = 
				[] = 
				[] = len()
				 = append(, )
				 = append(, )
			}
		}
	}

	// Backward BFS from endpoints: node->endpoint shortest-path successors.
	// Node IDs are random UUIDs, so we order everything by stable BFS discovery
	// index instead -- otherwise the chosen shortest paths (and thus the covering
	// set) would vary between builds.
	 := map[string][]*Node{}
	for ,  := range  {
		for ,  := range () {
			 := tgNodeID()
			[] = append([], )
		}
	}
	 := map[string]*Node{}
	var  []*Node
	for ,  := range  {
		if .endSet[tgNodeID()] {
			[tgNodeID()] = 
			 = append(, )
		}
	}
	for len() > 0 {
		 := [0]
		 = [1:]
		for ,  := range [tgNodeID()] {
			 := tgNodeID()
			if ,  := []; ! {
				[] = 
				 = append(, )
			}
		}
	}

	 := func( *Node) []*Node {
		var  []*Node
		 := 
		for {
			 = append(, )
			 := tgNodeID()
			 := []
			if tgNodeID() ==  {
				break
			}
			 = 
		}
		for ,  := 0, len()-1;  < ; ,  = +1, -1 {
			[], [] = [], []
		}
		return 
	}
	 := func( *Node) []*Node {
		var  []*Node
		 := 
		for {
			 = append(, )
			 := tgNodeID()
			 := []
			if tgNodeID() ==  {
				break
			}
			 = 
		}
		return 
	}

	 := map[string]bool{}
	 := map[string]bool{}
	// nextVal[id] is the smallest variation index of a node not yet emitted.
	// Values are always taken in increasing order, so a forward cursor per node
	// makes value coverage O(total values) instead of O(sum of width^2).
	 := map[string]int32{}

	 := func( []*Node) {
		for ,  := range  {
			[tgNodeID()] = true
			if +1 < len() {
				[tgNodeID()+">"+tgNodeID([+1])] = true
			}
		}
	}
	 := func( []*Node,  bool) bool {
		 := make([]int32, len())
		 := map[string]int32{} // fresh values taken for each node in THIS emit
		 := 0
		for ,  := range  {
			 := tgNodeID()
			,  := nodeEmit(, 0)
			if  < 1 {
				 = 1
			}
			 := [] + []
			if  <  {
				[] = 
				[]++
				++
			} else {
				[] = 0 // all of this node's values already covered; reuse 0
			}
		}
		if ! &&  == 0 {
			return false
		}
		for ,  := range  {
			[] += 
		}
		var  []byte
		for ,  := range  {
			,  := nodeEmit(, [])
			 = append(, ...)
		}
		.prods = append(.prods, )
		return true
	}

	var  [][]*Node

	sort.SliceStable(, func(,  int) bool {
		,  := [tgNodeID([].)], [tgNodeID([].)]
		if  !=  {
			return  < 
		}
		return [tgNodeID([].)] < [tgNodeID([].)]
	})
	for ,  := range  {
		 := tgNodeID(.) + ">" + tgNodeID(.)
		if [] {
			continue
		}
		if ,  := [tgNodeID(.)]; ! {
			continue
		}
		 := append((.), (.)...)
		 = append(, )
		(, true)
		()
	}

	for ,  := range  {
		 := tgNodeID()
		if [] {
			continue
		}
		if ,  := []; ! {
			continue
		}
		var  []*Node
		if .endSet[] {
			 = ()
		} else {
			 := ()
			 = append((), [1:]...)
		}
		 = append(, )
		(, true)
		()
	}

	for ,  := range  {
		for (, false) {
		}
	}
}

// nodeEmit returns the bytes a node emits for variation index tpos, and the
// node's total number of variations. For a non-sensitive char-val the variations
// are the 2^k casings of its k cased letters; for a num-val range, one byte per
// value in the range.
func nodeEmit( *Node,  int32) ( []byte,  int32) {
	if  == emptyNode {
		return nil, 1
	}
	switch v := .Elem.(type) {
	case ElemCharVal:
		if .Sensitive {
			for ,  := range .Values {
				 = append(, string()...)
			}
			return , 1
		}
		var  int
		for ,  := range .Values {
			if ( >= 'a' &&  <= 'z') || ( >= 'A' &&  <= 'Z') {
				++
			}
		}
		// 2^numVar casings; cap to avoid int32 overflow on pathologically long
		// case-insensitive literals (2^31 casings is unenumerable anyway). Letters
		// beyond the cap are emitted lower-case only.
		// XXX This is an arbitrary bound
		if  > 30 {
			 = 30
		}
		 = int32(1) << uint()
		 := uint(0)
		for ,  := range .Values {
			 :=  >= 'a' &&  <= 'z'
			 :=  >= 'A' &&  <= 'Z'
			if ! && ! {
				 = append(, string()...)
				continue
			}
			 := 
			if  {
				 =  - 'A' + 'a'
			}
			 := 
			if  {
				 =  - 'a' + 'A'
			}
			if (>>)&1 == 1 {
				 = append(, string()...)
			} else {
				 = append(, string()...)
			}
			++
		}
		return , 

	case ElemNumVal:
		switch .Status {
		case StatSeries:
			for ,  := range .Elems {
				 := numvalToRune(, .Base)
				 = append(, []byte(string())...)
			}
			return , 1
		case StatRange:
			,  := numvalToInt32(.Elems[0], .Base), numvalToInt32(.Elems[1], .Base)
			// The graph operates over runes; clamp to the Unicode range so an
			// out-of-range bound cannot overflow the int32 count below.
			if  > utf8.MaxRune {
				 = utf8.MaxRune
			}
			if  > utf8.MaxRune ||  >  {
				return nil, 1 // no representable character in this range
			}
			 := rune( + )
			return []byte(string()),  -  + 1
		}
	}
	return nil, 1
}

type tgmachine struct {
	options *tgoptions
	grammar *Grammar
	buf     map[string][2][]*Node

	nodeCount int // nodes reserved so far, checked against options.maxNodes
}

func ( *tgmachine) ( Alternation) ( []*Node,  []*Node,  error) {
	for ,  := range .Concatenations {
		, ,  := .concatGraph()
		if  != nil {
			return nil, nil, 
		}

		// Group concatenation inputs, but avoid duplicating the emptyNode
		 := slices.Contains(, emptyNode)
		for ,  := range  {
			if  == emptyNode &&  {
				continue
			}
			 = append(, )
		}

		// Group concatenation outputs, but avoid duplicating the emptyNode
		 := slices.Contains(, emptyNode)
		for ,  := range  {
			if  == emptyNode &&  {
				continue
			}
			 = append(, )
		}
	}
	return
}

func ( *tgmachine) ( Concatenation) ( []*Node,  []*Node,  error) {
	, ,  := .repGraph(.Repetitions[0])
	if  != nil {
		return nil, nil, 
	}
	for  := 1;  < len(.Repetitions); ++ {
		, ,  := .repGraph(.Repetitions[])
		if  != nil {
			return nil, nil, 
		}
		,  = concatTransitionGraphs(, , , )
	}
	return , , nil
}

func concatTransitionGraphs(, , ,  []*Node) ( []*Node,  []*Node) {
	// If prevI contains the emptyNode it means currI (possibly with
	// the emptyNode) is also part of the entrypoints (without prevI's
	// emptyNode).
	if slices.Contains(, emptyNode) {
		for ,  := range  {
			if  == emptyNode {
				continue
			}
			 = append(, )
		}
		 = append(, ...)
	} else {
		 = 
	}

	// plug previous outputs (prevO) to current inputs (currI).
	for ,  := range  {
		if  == emptyNode {
			continue
		}
		for ,  := range  {
			if  == emptyNode {
				continue
			}
			.Nexts = append(.Nexts, )
		}
	}

	// new concatenation output is the previous ones if current
	// inputs contains the emptyNode (repetition is skippable),
	// and the current outputs ones.
	if slices.Contains(, emptyNode) {
		 = append(, ...)
	}
	for ,  := range  {
		if  == emptyNode {
			continue
		}
		 = append(, )
	}

	return
}

func ( *tgmachine) ( Repetition) ( []*Node,  []*Node,  error) {
	// element entry-/end-points (resp. I/O)
	, ,  := .elemGraph(.Element)
	if  != nil {
		return nil, nil, 
	}

	if .Min == 0 {
		 = appendNodes(, emptyNode)
		 = appendNodes(, emptyNode)

		switch .Max {
		case 1:
			// min = 0 & max = 1: optional v
			 = appendNodes(, ...)
			 = appendNodes(, ...)
		case inf:
			// min = 0 & max = inf: optional infinity
			 := []*Node{}
			for ,  := range  {
				if  == emptyNode {
					continue
				}
				 = appendNodes(, )
			}
			for ,  := range  {
				if  == emptyNode {
					continue
				}
				.Nexts = appendNodes(.Nexts, ...)
			}
			 = appendNodes(, ...)
			 = appendNodes(, ...)

		default:
			// min = 0 & 1 < max < inf: optional to n
			if .Max > .options.repetitionThreshold {
				return nil, nil, ErrRepetitionThreshold
			}
			if  := .reserveClones(.Max, );  != nil {
				return nil, nil, 
			}
			, ,  := chainTransitionGraph(, , .Max)
			 = appendNodes(, ...)
			for ,  := range  {
				 = appendNodes(, .Endpoints...)
			}
		}
	} else {
		switch .Max {
		case 1:
			// min == 1 & max == 1: mandatory
			if .Min != 1 {
				return nil, nil, ErrRepetitionMinNotOne
			}
			 = appendNodes(, ...)
			 = appendNodes(, ...)

		case inf:
			// min >= 1 && max = inf: n to infinity
			if .Min > .options.repetitionThreshold {
				return nil, nil, ErrRepetitionThreshold
			}
			if  := .reserveClones(.Min, );  != nil {
				return nil, nil, 
			}
			, ,  := chainTransitionGraph(, , .Min)
			 = appendNodes(, ...)
			 = appendNodes(, ...)

			 := [len()-1]
			for ,  := range .Endpoints {
				if  == emptyNode {
					continue
				}
				for ,  := range .Entrypoints {
					// Make sure to not append the empty node as a next node, this is not possible
					if  == emptyNode {
						continue
					}
					.Nexts = appendNodes(.Nexts, )
				}
			}

		default:
			// min >= 1 && max < inf: n to m
			if .Min > .Max {
				return nil, nil, ErrRepetitionMinGtMax
			}
			if .Max > .options.repetitionThreshold {
				return nil, nil, ErrRepetitionThreshold
			}

			// Build the flat chain (not endpoints, except last)
			,  := , 
			if .Min > 1 {
				if  := .reserveClones(.Min, );  != nil {
					return nil, nil, 
				}
				_, ,  = chainTransitionGraph(, , .Min)
			}
			 = appendNodes(, ...)
			 = appendNodes(, ...)

			// Build remaining endpoints
			 := .Max - .Min
			if  > 0 {
				if  := .reserveClones(.Max-.Min, );  != nil {
					return nil, nil, 
				}
				, ,  := chainTransitionGraph(, , .Max-.Min)
				for ,  := range  {
					 = appendNodes(, .Endpoints...)
				}
				for ,  := range  {
					if  == emptyNode {
						continue
					}
					for ,  := range  {
						if  == emptyNode {
							continue
						}
						.Nexts = appendNodes(.Nexts, )
					}
				}
			}
		}
	}

	return
}

func chainTransitionGraph(,  []*Node,  int) ( []TransitionGraph,  []*Node,  []*Node) {
	// Make sure to not chain... nothing ¯\_(ツ)_/¯
	if  == 0 {
		return
	}
	 = make([]TransitionGraph, )

	// Init chaining
	,  = cloneTransitionGraph(, )
	[0] = TransitionGraph{
		Entrypoints: ,
		Endpoints:   ,
	}

	// Gotta chain them all
	for  := 1;  < ; ++ {
		,  := cloneTransitionGraph(, )
		[] = TransitionGraph{
			Entrypoints: ,
			Endpoints:   ,
		}
		,  = concatTransitionGraphs(, , , )
	}
	return
}

func cloneTransitionGraph(,  []*Node) ( []*Node,  []*Node) {
	// Traverse graph to map all cloned originToNewNodes by their origin IDs
	 := map[string]cnode{}
	for ,  := range  {
		if  == emptyNode {
			continue
		}
		cloneTG(, )
	}

	// Rebuild links
	for ,  := range  {
		 := make([]*Node, 0, len(.origin.Nexts))
		for ,  := range .origin.Nexts {
			 = append(, [.ID].cloned)
		}
		.cloned.Nexts = 
	}

	// Get cloned I/O
	 = make([]*Node, 0, len())
	for ,  := range  {
		if  == emptyNode {
			 = append(, emptyNode)
			continue
		}
		 = append(, [.ID].cloned)
	}
	 = make([]*Node, 0, len())
	for ,  := range  {
		if  == emptyNode {
			 = append(, emptyNode)
			continue
		}
		 = append(, [.ID].cloned)
	}
	return
}

type cnode struct {
	origin, cloned *Node
}

func cloneTG( map[string]cnode,  *Node) {
	 := newID()

	[.ID] = cnode{
		origin: ,
		cloned: &Node{
			ID:    ,
			Elem:  .Elem,
			Nexts: nil, // will map it later, requires all origins to be cloned first
		},
	}

	// recurse iff not known yet
	for ,  := range .Nexts {
		if ,  := [.ID];  {
			continue
		}
		(, )
	}
}

func appendNodes( []*Node,  ...*Node) []*Node {
	for ,  := range  {
		if slices.Contains(, ) {
			continue
		}
		 = append(, )
	}
	return 
}

func ( *tgmachine) ( ElemItf) ( []*Node,  []*Node,  error) {
	switch v := .(type) {
	// Final elements => create the node, no need to pipe I/O
	case ElemCharVal:
		if len(.Values) == 0 {
			 = append(, emptyNode)
			 = append(, emptyNode)
			return
		}

		if !.options.deflateCharVals {
			if  := .reserve(1);  != nil {
				return nil, nil, 
			}
			 := newNode()
			 = append(, )
			 = append(, )
			return
		}

		if  := .reserve(2 * len(.Values));  != nil {
			return nil, nil, 
		}

		var  []*Node = nil
		var  []*Node = nil
		for ,  := range .Values {
			 :=  >= 'a' &&  <= 'z'
			 :=  >= 'A' &&  <= 'Z'
			 := ( || ) && !.Sensitive

			if ! {
				 := newNode(ElemCharVal{
					Sensitive: true,
					Values:    []rune{},
				})
				 = []*Node{}

				if  == nil {
					 = append(, )
				}
				for ,  := range  {
					.Nexts = append(.Nexts, ...)
				}
				 = []*Node{}
			} else {
				 := 
				if  {
					 = runeMin()
				}
				 := 
				if  {
					 = runeMax()
				}

				 := newNode(ElemCharVal{
					Sensitive: true,
					Values:    []rune{},
				})
				 := newNode(ElemCharVal{
					Sensitive: true,
					Values:    []rune{},
				})
				 = []*Node{, }

				if  == nil {
					 = append(, , )
				}
				for ,  := range  {
					.Nexts = append(.Nexts, ...)
				}
				 = []*Node{, }
			}
		}
		 = append(, ...)
		return

	case ElemNumVal:
		if !.options.deflateNumVals {
			if  := .reserve(1);  != nil {
				return nil, nil, 
			}
			 := newNode()
			 = append(, )
			 = append(, )
			return
		}
		switch .Status {
		case StatRange:
			,  := numvalToInt32(.Elems[0], .Base), numvalToInt32(.Elems[1], .Base)
			// One node is enumerated per rune; clamp to the Unicode range so an
			// out-of-range bound cannot overflow the count (int32) and bypass the
			// node budget, which would turn this loop into a DoS. A range wholly
			// above U+10FFFF contributes no node (it matches nothing).
			if  > utf8.MaxRune {
				 = utf8.MaxRune
			}
			if  > utf8.MaxRune ||  >  {
				return
			}
			if  := .reserve(int( -  + 1));  != nil {
				return nil, nil, 
			}
			for  := ;  <= ; ++ {
				 := newNode(ElemNumVal{
					Base:   .Base,
					Status: StatSeries,
					Elems:  []string{int32ToNumval(, .Base)},
				})
				 = append(, )
				 = append(, )
			}

		case StatSeries:
			if  := .reserve(len(.Elems));  != nil {
				return nil, nil, 
			}
			for ,  := range .Elems {
				 := newNode(ElemNumVal{
					Base:   .Base,
					Status: StatSeries,
					Elems:  []string{},
				})
				 = append(, )
				 = append(, )
			}
		}
		return

	// Recursive elements => pipe I/O
	case ElemRulename:
		if .options.deflateRules {
			 := strings.ToLower(.Name)
			if ,  := .buf[];  {
				if  := .reserveClones(1, [0]);  != nil {
					return nil, nil, 
				}
				,  := cloneTransitionGraph([0], [1])
				return , , nil
			}
			 := GetRule(.Name, .grammar.Rulemap)
			if  == nil {
				return nil, nil, &ErrRuleNotFound{
					Rulename: .Name,
				}
			}
			, ,  := .altGraph(.Alternation)
			if  != nil {
				return nil, nil, 
			}
			if  := .reserveClones(1, );  != nil {
				return nil, nil, 
			}
			,  := cloneTransitionGraph(, )
			.buf[] = [2][]*Node{, }
			return , , nil
		}
		if  := .reserve(1);  != nil {
			return nil, nil, 
		}
		 := newNode()
		 = append(, )
		 = append(, )
		return

	case ElemOption:
		, ,  := .altGraph(.Alternation)
		if  != nil {
			return nil, nil, 
		}
		 = appendNodes(, emptyNode)
		 = appendNodes(, emptyNode)
		return , , nil

	case ElemGroup:
		return .altGraph(.Alternation)
	case ElemProseVal:
		return nil, nil, ErrProseValInTransitionGraph
	}

	panic("unsupported element")
}

// newID returns a random identifier for a graph node, the way containerd and
// containers/storage build container IDs: random bytes from crypto/rand, hex
// encoded. Node IDs only have to be unique within one graph, so 16 bytes are
// plenty. crypto/rand.Read never returns an error since Go 1.24.
func newID() string {
	 := make([]byte, 16)
	rand.Read()
	return hex.EncodeToString()
}

func newNode( ElemItf) *Node {
	 := newID()
	return &Node{
		ID:   ,
		Elem: ,
		// Final node, no need to pipe I/O
	}
}

// ToMermaid produces a mermaid-encoded representation of the transition graph.
func ( *TransitionGraph) () string {
	// Map all nodes
	 := map[string]*Node{}
	for ,  := range .Entrypoints {
		if  == emptyNode {
			continue
		}
		mapNodes(, )
	}

	// Write them all
	 := "flowchart LR\n    classDef entrypoint fill:#479abf\n\n"
	for ,  := range  {
		// Write down the node
		 := "    " + .ID
		 := elemToString(.Elem)
		if slices.Contains(.Endpoints, ) {
			 += "(((\"" +  + "\")))"
		} else {
			 += "[\"" +  + "\"]"
		}
		 += 
		if slices.Contains(.Entrypoints, ) {
			 += ":::entrypoint"
		}
		 += "\n"

		// Write down its links
		for ,  := range .Nexts {
			 += fmt.Sprintf("    %s --> %s\n", .ID, .ID)
		}
		 += "\n"
	}

	// Don't forget the empty node
	if slices.Contains(.Entrypoints, emptyNode) {
		 += "    emptyNode(((\u2205))):::entrypoint\n"
	}

	return 
}

func mapNodes( map[string]*Node,  *Node) {
	if ,  := [.ID];  {
		return
	}
	[.ID] = 
	for ,  := range .Nexts {
		(, )
	}
}

func elemToString( ElemItf) string {
	switch v := .(type) {
	case ElemRulename:
		return .Name
	case ElemCharVal:
		 := ""
		for ,  := range .Values {
			if  == '`' {
				 += "backquote"
			} else if  == '"' {
				 += "dquote"
			} else if 33 <=  &&  <= 127 {
				 += string()
			}
		}
		return 
	case ElemNumVal:
		if .Status == StatRange {
			return fmt.Sprintf("0%s%s-%s", .Base, .Elems[0], .Elems[1])
		}
		return fmt.Sprintf("0%s%s", .Base, strings.Join(.Elems, "."))
	}
	panic("not implemented yet")
}