package goabnf

import (
	
	
	
)

// One-symbol lookahead for the GLL engines.
//
// GLL as published guards parsing steps with a selection test test(x, A, γ):
// a sequence γ in a production of A is only explored at input position i when
// the next input symbol x is in FIRST(γ), or γ is nullable and x is in
// FOLLOW(A) (Scott & Johnstone, "GLL parse-tree generation", Science of
// Computer Programming 78(10), 2013, §3.3). It guards the descriptor started
// for each alternate α of A (§4.3), and the call of each nonterminal instance
// A ::= α·Xβ with γ = Xβ (§4.1), so no GSS node is created for a call that
// cannot consume the next symbol.
//
// The guard prunes sub-parses whose continuation cannot consume the next input
// symbol, such as a repetition 1*ALPHA stopping inside a run of letters. This
// keeps the forest proportional to the derivations that can still complete,
// e.g. linear in the run length for 1*ALPHA followed by a delimiter.
//
// A sequence rejected by the guard would have failed on a terminal at the same
// position, so its FIRST (and, when nullable, FOLLOW) terminals feed the
// furthest-failure diagnostics in its place.
//
// Symbols are runes (ABNF terminals are matched on decoded UTF-8), so sets are
// rune intervals plus an end-of-input marker. FIRST/FOLLOW are computed on the
// context-free reading of the slot grammar, ignoring repetition bounds: the
// bounded language is a subset of it, so the sets over-approximate and the test
// never rejects a viable sequence.

type runeRange struct{ lo, hi rune }

// laSet is a lookahead set: rune intervals, the end-of-input marker, and the
// terminals contributing to it (for furthest-failure diagnostics).
type laSet struct {
	ranges []runeRange // sorted, non-overlapping, non-adjacent
	ascii  [2]uint64   // bitmap of ranges below utf8.RuneSelf
	eof    bool
	terms  []ssym
	descs  map[string]bool
}

func ( *laSet) (,  rune) bool {
	if  >  {
		return false
	}
	if .coversRange(, ) {
		return false
	}
	.ranges = append(.ranges, runeRange{, })
	sort.Slice(.ranges, func(,  int) bool { return .ranges[].lo < .ranges[].lo })
	 := .ranges[:1]
	for ,  := range .ranges[1:] {
		 := &[len()-1]
		if .lo <= .hi+1 {
			if .hi > .hi {
				.hi = .hi
			}
			continue
		}
		 = append(, )
	}
	.ranges = 
	return true
}

func ( *laSet) (,  rune) bool {
	for ,  := range .ranges {
		if .lo <=  &&  <= .hi {
			return true
		}
	}
	return false
}

func ( *laSet) ( ssym) bool {
	 := "?"
	if ,  := .term.(fmt.Stringer);  {
		 = .String()
	}
	if .descs == nil {
		.descs = map[string]bool{}
	}
	if .descs[] {
		return false
	}
	.descs[] = true
	.terms = append(.terms, )
	return true
}

// union adds o to s (optionally including o's end-of-input marker) and
// reports whether s changed.
func ( *laSet) ( *laSet,  bool) bool {
	 := false
	for ,  := range .ranges {
		if .addRange(.lo, .hi) {
			 = true
		}
	}
	if  && .eof && !.eof {
		.eof = true
		 = true
	}
	for ,  := range .terms {
		if .addTerm() {
			 = true
		}
	}
	return 
}

func ( *laSet) () {
	for ,  := range .ranges {
		for  := .lo;  <= .hi &&  < utf8.RuneSelf; ++ {
			if  >= 0 {
				.ascii[/64] |= 1 << ( % 64)
			}
		}
	}
}

func ( *laSet) ( rune) bool {
	if  >= 0 &&  < utf8.RuneSelf {
		return .ascii[/64]&(1<<(%64)) != 0
	}
	 := sort.Search(len(.ranges), func( int) bool { return .ranges[].hi >=  })
	return  < len(.ranges) && .ranges[].lo <= 
}

// termFirst returns the FIRST set of a terminal and whether it matches the
// empty string, mirroring matchTerm.
func termFirst( ssym) (laSet, bool) {
	var  laSet
	if .kind == symEps {
		return , true
	}
	switch v := .term.(type) {
	case ElemCharVal:
		if len(.Values) == 0 {
			return , true
		}
		 := .Values[0]
		if .Sensitive {
			.addRange(, )
		} else {
			 := runeMin()
			.addRange(, )
			 := runeMax()
			.addRange(, )
		}

	case ElemNumVal:
		switch .Status {
		case StatRange:
			.addRange(numvalToRune(.Elems[0], .Base), numvalToRune(.Elems[1], .Base))

		case StatSeries:
			if len(.Elems) == 0 {
				return , true
			}
			if  := numvalToRune(.Elems[0], .Base); utf8.ValidRune() {
				.addRange(, )
			}
		}
	}
	// A terminal that never matches (prose-val, out-of-range series) has an
	// empty rune set but is still an attempted terminal for diagnostics.
	.addTerm()
	return , false
}

// lookahead holds the selection sets FIRST(γ) ∪ (FOLLOW(A) if γ is nullable)
// of the slot grammar: sel for every alternate γ = α of A, call for every
// nonterminal instance A ::= α·Xβ with γ = Xβ.
type lookahead struct {
	sel  [][]laSet   // [nt][alt]
	call [][][]laSet // [nt][alt][dot], set only where the symbol at dot is a nonterminal
}

func computeLookahead( *slotGrammar) *lookahead {
	 := len(.nts)
	 := make([]bool, )
	 := make([]laSet, )
	 := make([]laSet, )

	 := func( ssym) bool {
		switch .kind {
		case symNonterm:
			return [.nt]

		default:
			,  := termFirst()
			return 
		}
	}
	// firstSeq returns FIRST(seq) and whether seq is nullable.
	 := func( []ssym) (laSet, bool) {
		var  laSet
		for ,  := range  {
			if .kind == symNonterm {
				.union(&[.nt], false)
			} else {
				,  := termFirst()
				.union(&, false)
			}
			if !() {
				return , false
			}
		}
		return , true
	}

	for  := true; ; {
		 = false
		for ,  := range .nts {
			for ,  := range .alts {
				,  := ()
				if [].union(&, false) {
					 = true
				}
				if  && ![] {
					[] = true
					 = true
				}
			}
		}
	}

	[.start].eof = true
	for  := true; ; {
		 = false
		for ,  := range .nts {
			for ,  := range .alts {
				for ,  := range  {
					if .kind != symNonterm {
						continue
					}
					,  := ([+1:])
					if [.nt].union(&, false) {
						 = true
					}
					if  && [.nt].union(&[], true) {
						 = true
					}
				}
			}
		}
	}

	 := func( int,  []ssym) laSet {
		,  := ()
		if  {
			.union(&[], true)
		}
		.seal()
		return 
	}
	 := &lookahead{sel: make([][]laSet, ), call: make([][][]laSet, )}
	for ,  := range .nts {
		.sel[] = make([]laSet, len(.alts))
		.call[] = make([][]laSet, len(.alts))
		for ,  := range .alts {
			.sel[][] = (, )
			.call[][] = make([]laSet, len())
			for ,  := range  {
				if .kind == symNonterm {
					.call[][][] = (, [:])
				}
			}
		}
	}
	return 
}

// alt returns the selection set guarding alternate alt of nonterminal nt.
func ( *lookahead) (,  int) *laSet { return &.sel[][] }

// callAt returns the selection set guarding the nonterminal call at slot L.
func ( *lookahead) ( slot) *laSet { return &.call[.nt][.alt][.dot] }

// admits reports whether the next input symbol at i is in s, i.e. whether the
// guarded sequence may derive a prefix of input[i:] in some context.
func ( *laSet) ( []byte,  int) bool {
	if  >= len() {
		return .eof
	}
	,  := utf8.DecodeRune([:])
	if  == utf8.RuneError &&  == 1 {
		// No terminal matches an invalid UTF-8 sequence (see matchTerm).
		return false
	}
	return .contains()
}