package goabnf

import (
	
	
)

// Binary Subtree Representation (BSR).
//
// This is an alternative derivation representation to the SPPF in sppf.go,
// following Scott, Johnstone & van Binsbergen, "Derivation representation using
// binary subtree sets" (Science of Computer Programming 175, 2019). Instead of
// interning symbol/intermediate/packed nodes, the parser records a flat set of
// elements (slot, l, k, r): a grammar slot whose consumed prefix derives the
// input span [l,r], with the most recently consumed symbol spanning [k,r] and
// the earlier prefix spanning [l,k]. The same GLL control (descriptors, GSS,
// native counted repetition) drives it; only what gets recorded differs.
//
// The GSS node's pos field already holds a production's left extent (the call
// position), so a BSR element needs no extra threading: on a dot advance the
// element is (newSlot, l=frameLeftExtent, k=pivot, r=end).
//
// The BSR engine is validated to produce identical Valid/NumTrees/Ambiguous
// results to the SPPF engine across the differential corpus; it is the intended
// foundation for grammar-directed parser generation.

// bsrElem is one binary subtree element. The slot's dot is "just past" the most
// recently consumed symbol; that symbol spans [k,r] and the earlier prefix spans
// [l,k]. A complete production (dot == len) records the nonterminal's extent.
type bsrElem struct {
	slot    slot
	l, k, r int
}

// bsrGNode is a GSS node for the BSR engine. Unlike the SPPF GSS, its edges are
// unlabelled (no SPPF node is carried): the BSR pivots are recovered from node
// positions instead.
type bsrGNode struct {
	ret     slot // return slot in the caller's production
	pos     int  // call position == the caller production's left extent for callees
	rc      int  // repetition count (native counted repetition; 0 otherwise)
	edges   []*bsrGNode
	edgeSet map[*bsrGNode]bool
}

type bsrDesc struct {
	L  slot
	u  *bsrGNode
	i  int
	rc int
}

type bsrParser struct {
	sg    *slotGrammar
	input []byte

	set    map[bsrElem]bool
	gss    map[gssKey]*bsrGNode
	u0     *bsrGNode
	seen   map[bsrDesc]bool
	work   []bsrDesc
	popped map[*bsrGNode]map[int]bool

	maxElems int
	aborted  bool
}

// addAlt adds the descriptor starting alternate L.alt of L.nt at i when the
// lookahead test admits it.
func ( *bsrParser) ( slot,  *bsrGNode, ,  int) {
	if .sg.la.alt(.nt, .alt).admits(.input, ) {
		.add(, , , )
	}
}

func ( *bsrParser) ( slot,  *bsrGNode, ,  int) {
	 := bsrDesc{, , , }
	if .seen[] {
		return
	}
	.seen[] = true
	.work = append(.work, )
}

func ( *bsrParser) ( slot, ,  int) *bsrGNode {
	 := gssKey{, , }
	if ,  := .gss[];  {
		return 
	}
	 := &bsrGNode{ret: , pos: , rc: , edgeSet: map[*bsrGNode]bool{}}
	.gss[] = 
	return 
}

// record adds the BSR element for advancing into slot L over [l,r] with the last
// symbol pivoting at k. Per the binary-subtree scheme an element is kept only
// when the consumed prefix has length >= 2 (an intermediate extent) or the
// production is complete (dot == len). A length-1 prefix is degenerate (l == k)
// and is reconstructed directly from the single symbol, so it is not stored.
func ( *bsrParser) ( slot, , ,  int) {
	 := .sg.nts[.nt].alts[.alt]
	if .dot >= 2 || .dot == len() {
		if .maxElems > 0 && len(.set) >= .maxElems {
			.aborted = true
			return
		}
		.set[bsrElem{, , , }] = true
	}
}

func ( *bsrParser) ( slot,  *bsrGNode, ,  int) *bsrGNode {
	 := .gssNodeFor(, , )
	if !.edgeSet[] {
		.edgeSet[] = true
		.edges = append(.edges, )
		for  := range .popped[] {
			.record(, .pos, , )
			.add(, , , )
		}
	}
	return 
}

func ( *bsrParser) ( *bsrGNode,  int) {
	if  == .u0 {
		return
	}
	if .popped[] == nil {
		.popped[] = map[int]bool{}
	}
	.popped[][] = true
	for ,  := range .edges {
		.record(.ret, .pos, .pos, )
		.add(.ret, , , .rc)
	}
}

func ( *bsrParser) ( int,  *bsrGNode, ,  int) {
	 := .sg.nts[]
	if  >= .repMin {
		.addAlt(slot{, 0, 0}, , , )
	}
	if .repMax == inf ||  < .repMax {
		.addAlt(slot{, 1, 0}, , , )
	}
}

func ( *bsrParser) ( ssym,  int) int {
	if .kind == symEps {
		return 
	}
	switch v := .term.(type) {
	case ElemCharVal:
		 := 
		for  := 0;  < len(.Values); ++ {
			if  >= len(.input) {
				return -1
			}
			,  := utf8.DecodeRune(.input[:])
			if  == utf8.RuneError &&  == 1 {
				return -1
			}
			if !sensequal(.Values[], , .Sensitive) {
				return -1
			}
			 += 
		}
		return 
	case ElemNumVal:
		switch .Status {
		case StatRange:
			if  >= len(.input) {
				return -1
			}
			 := numvalToRune(.Elems[0], .Base)
			 := numvalToRune(.Elems[1], .Base)
			,  := utf8.DecodeRune(.input[:])
			if  == utf8.RuneError &&  == 1 {
				return -1
			}
			if  <=  &&  <=  {
				return  + 
			}
			return -1
		case StatSeries:
			 := 
			for  := 0;  < len(.Elems); ++ {
				 := numvalToRune(.Elems[], .Base)
				if !utf8.ValidRune() {
					return -1
				}
				 := string()
				 := len()
				if + > len(.input) ||  != string(.input[:+]) {
					return -1
				}
				 += 
			}
			return 
		}
	}
	return -1
}

func ( *bsrParser) () {
	 := .sg.start
	.u0 = &bsrGNode{ret: slot{-1, -1, -1}, pos: 0, edgeSet: map[*bsrGNode]bool{}}
	for  := range .sg.nts[].alts {
		.addAlt(slot{, , 0}, .u0, 0, 0)
	}
	for len(.work) > 0 {
		if .aborted {
			return
		}
		 := .work[len(.work)-1]
		.work = .work[:len(.work)-1]
		.process()
	}
}

func ( *bsrParser) ( bsrDesc) {
	, , ,  := .L, .u, .i, .rc
	for {
		 := .sg.nts[.nt].alts[.alt]
		if .dot == len() {
			.pop(, )
			return
		}
		 := [.dot]
		if .kind == symNonterm {
			if !.sg.la.callAt().admits(.input, ) {
				return
			}
			 := slot{.nt, .alt, .dot + 1}
			 := .create(, , , )
			if .sg.nts[.nt].isRep {
				 := 0
				if .nt == .nt {
					 = capRC(, .sg.nts[.nt])
				}
				.addRepAlts(.nt, , , )
			} else {
				for  := range .sg.nts[.nt].alts {
					.addAlt(slot{.nt, , 0}, , , 0)
				}
			}
			return
		}
		 := .matchTerm(, )
		if  < 0 {
			return
		}
		 := slot{.nt, .alt, .dot + 1}
		.record(, .pos, , )
		 = 
		 = 
	}
}

// ---------------------------------------------------------------------------
// Queries over the BSR set
// ---------------------------------------------------------------------------

// BSRForest is the BSR analogue of Forest: a set of binary subtree elements plus
// an index for reconstruction. Valid/NumTrees/Ambiguous/Tree mirror Forest.
type BSRForest struct {
	sg       *slotGrammar
	input    []byte
	rulename string
	set      map[bsrElem]bool
	index    map[bsrKey][]int // (slot,l,r) -> pivots k
	start    int
	n        int
}

type bsrKey struct {
	slot slot
	l, r int
}

func ( *BSRForest) () {
	.index = make(map[bsrKey][]int, len(.set))
	for  := range .set {
		 := bsrKey{.slot, .l, .r}
		.index[] = append(.index[], .k)
	}
}

// startElems returns, for each production of the start rule, the pivots of the
// complete-production elements spanning the whole input.
func ( *BSRForest) () (slot, []int, bool) {
	for ,  := range .sg.nts[.start].alts {
		 := slot{.start, , len()}
		if  := .index[bsrKey{, 0, .n}]; len() > 0 {
			return , , true
		}
	}
	return slot{}, nil, false
}

// Valid reports whether the whole input is derivable by the root rule.
func ( *BSRForest) () bool {
	for ,  := range .sg.nts[.start].alts {
		 := slot{.start, , len()}
		if len(.index[bsrKey{, 0, .n}]) > 0 {
			return true
		}
	}
	return false
}

// Nodes returns the number of BSR elements (the representation's size).
func ( *BSRForest) () int { return len(.set) }

// symNode/interNode identities for memoisation and cycle detection.
type bsrNodeID struct {
	inter bool
	slot  slot // for intermediate nodes
	nt    int  // for symbol nodes
	l, r  int
}

// NumTrees returns the number of distinct parse trees represented, or -1 for
// infinitely many (a cycle, i.e. an infinitely-ambiguous grammar). It mirrors
// Forest.NumTrees but counts over BSR extents instead of SPPF nodes.
func ( *BSRForest) () *big.Int {
	if !.Valid() {
		return big.NewInt(0)
	}
	 := map[bsrNodeID]*big.Int{}
	 := map[bsrNodeID]bool{}
	 := false

	var  func( ssym, ,  int) *big.Int
	var  func(, ,  int) *big.Int
	var  func( slot, ,  int) *big.Int
	var  func( slot, , ,  int) *big.Int

	 = func( ssym, ,  int) *big.Int {
		if .kind == symNonterm {
			return (.nt, , )
		}
		return big.NewInt(1) // terminal / eps leaf
	}

	 = func( slot, , ,  int) *big.Int {
		 := .sg.nts[.nt].alts[.alt]
		 := ([.dot-1], , )
		var  *big.Int
		switch .dot {
		case 1: // empty prefix (l == k)
			 = big.NewInt(1)
		case 2: // single-symbol prefix
			 = ([0], , )
		default: // intermediate prefix
			 = (slot{.nt, .alt, .dot - 1}, , )
		}
		return new(big.Int).Mul(, )
	}

	 = func( slot, ,  int) *big.Int {
		 := bsrNodeID{inter: true, slot: , l: , r: }
		if ,  := [];  {
			return 
		}
		if [] {
			 = true
			return big.NewInt(1)
		}
		[] = true
		 := big.NewInt(0)
		for ,  := range .index[bsrKey{, , }] {
			.Add(, (, , , ))
		}
		[] = false
		[] = 
		return 
	}

	 = func(, ,  int) *big.Int {
		 := bsrNodeID{nt: , l: , r: }
		if ,  := [];  {
			return 
		}
		if [] {
			 = true
			return big.NewInt(1)
		}
		[] = true
		 := big.NewInt(0)
		for ,  := range .sg.nts[].alts {
			 := slot{, , len()}
			for ,  := range .index[bsrKey{, , }] {
				.Add(, (, , , ))
			}
		}
		[] = false
		[] = 
		return 
	}

	 := (.start, 0, .n)
	if  {
		return big.NewInt(-1)
	}
	return 
}

// Ambiguous reports whether the input has more than one distinct parse tree.
func ( *BSRForest) () bool {
	if !.Valid() {
		return false
	}
	 := map[bsrNodeID]bool{}

	var  func(, ,  int) bool
	var  func( slot, ,  int) bool
	var  func( slot, , ,  int) bool

	 := func( ssym, ,  int) bool {
		if .kind == symNonterm {
			return (.nt, , )
		}
		return false
	}
	 = func( slot, , ,  int) bool {
		 := .sg.nts[.nt].alts[.alt]
		if ([.dot-1], , ) {
			return true
		}
		switch .dot {
		case 1:
			return false
		case 2:
			return ([0], , )
		default:
			return (slot{.nt, .alt, .dot - 1}, , )
		}
	}
	 = func( slot, ,  int) bool {
		 := bsrNodeID{inter: true, slot: , l: , r: }
		if [] {
			return false
		}
		[] = true
		 := .index[bsrKey{, , }]
		if len() > 1 {
			return true
		}
		for ,  := range  {
			if (, , , ) {
				return true
			}
		}
		return false
	}
	 = func(, ,  int) bool {
		 := bsrNodeID{nt: , l: , r: }
		if [] {
			return false
		}
		[] = true
		 := 0
		for ,  := range .sg.nts[].alts {
			 := slot{, , len()}
			 := .index[bsrKey{, , }]
			 += len()
		}
		if  > 1 {
			return true
		}
		for ,  := range .sg.nts[].alts {
			 := slot{, , len()}
			for ,  := range .index[bsrKey{, , }] {
				if (, , , ) {
					return true
				}
			}
		}
		return false
	}
	return (.start, 0, .n)
}

// Tree extracts a single parse tree (first element at each extent), or nil if
// the input is invalid. Synthetic nonterminals (groups, options, repetitions)
// are collapsed so only original rule names appear, matching Forest.Tree.
func ( *BSRForest) () *ParseTree {
	if !.Valid() {
		return nil
	}
	, ,  := .startElems()
	if ! {
		return nil
	}
	 := map[bsrNodeID]bool{}
	return .emitSym(.start, , [0], 0, .n, )
}

// emitSym builds a ParseTree node for nonterminal nt over [l,r], chosen via the
// complete-production slot sl with pivot k.
func ( *BSRForest) ( int,  slot, , ,  int,  map[bsrNodeID]bool) *ParseTree {
	var  []*ParseTree
	.collectElem(, , , , &, )
	 := .sg.nts[]
	if !.isRule {
		// synthetic (group/option/rep): splice children into the parent
		return &ParseTree{Start: , End: , Children: } // caller flattens
	}
	return &ParseTree{Rule: .ruleName, Start: , End: , Children: }
}

// collectElem appends the children of element (sl,l,k,r) into out, flattening
// intermediate extents and synthetic nonterminals.
func ( *BSRForest) ( slot, , ,  int,  *[]*ParseTree,  map[bsrNodeID]bool) {
	 := .sg.nts[.nt].alts[.alt]
	// prefix x_1..x_{dot-1} over [l,k]
	switch .dot {
	case 1:
		// empty
	case 2:
		.collectChild([0], , , , )
	default:
		 := slot{.nt, .alt, .dot - 1}
		if  := .index[bsrKey{, , }]; len() > 0 {
			.(, , [0], , , )
		}
	}
	// last symbol x_{dot} over [k,r]
	.collectChild([.dot-1], , , , )
}

func ( *BSRForest) ( ssym, ,  int,  *[]*ParseTree,  map[bsrNodeID]bool) {
	if .kind != symNonterm {
		if .kind == symEps {
			return // epsilon contributes no leaf
		}
		* = append(*, &ParseTree{Start: , End: })
		return
	}
	 := bsrNodeID{nt: .nt, l: , r: }
	if [] {
		return
	}
	[] = true
	// pick the first complete-production element for this nonterminal extent
	for ,  := range .sg.nts[.nt].alts {
		 := slot{.nt, , len()}
		if  := .index[bsrKey{, , }]; len() > 0 {
			 := .sg.nts[.nt]
			if .isRule {
				var  []*ParseTree
				.collectElem(, , [0], , &, )
				* = append(*, &ParseTree{Rule: .ruleName, Start: , End: , Children: })
			} else {
				// synthetic: splice its children directly into the parent
				.collectElem(, , [0], , , )
			}
			[] = false
			return
		}
	}
	[] = false
}

func newBSRParser( *slotGrammar,  []byte,  int) *bsrParser {
	return &bsrParser{
		sg:       ,
		input:    ,
		set:      map[bsrElem]bool{},
		gss:      map[gssKey]*bsrGNode{},
		seen:     map[bsrDesc]bool{},
		popped:   map[*bsrGNode]map[int]bool{},
		maxElems: ,
	}
}

// ParseBSR parses input under rootRulename using the BSR engine. It accepts the
// same options as ParseForest (WithMaxForestNodes bounds the BSR set size).
func ( []byte,  *Grammar,  string,  ...ForestOption) (*BSRForest, error) {
	 := forestConfig{maxSlots: defaultMaxSlots}
	for ,  := range  {
		(&)
	}
	,  := compileSlots(, , .maxSlots)
	if  != nil {
		return nil, 
	}
	 := newBSRParser(, , .maxNodes)
	.parse()
	if .aborted {
		return nil, &ErrForestTooLarge{Max: .maxNodes}
	}
	 := &BSRForest{
		sg:       ,
		input:    ,
		rulename: ,
		set:      .set,
		start:    .start,
		n:        len(),
	}
	.buildIndex()
	return , nil
}