package goabnf

import (
	
	
	
	
)

// Grammar represents an ABNF grammar as defined by RFC 5234.
// It is constituted of a set of rules with a unique name.
type Grammar struct {
	Rulemap map[string]*Rule
}

// IsValid checks there exist at least a path that completly consumes
// input, hence is valid given this grammar and especially one of its
// rule.
func ( *Grammar) ( string,  []byte) (bool, error) {
	 := GetRule(, .Rulemap)
	if  == nil {
		return false, &ErrRuleNotFound{Rulename: }
	}
	// Validity only needs to know whether some derivation consumes the whole
	// input, never the (possibly exponentially many) derivations themselves.
	// We therefore propagate the set of reachable end-positions per
	// (element, index) instead of enumerating paths, which keeps this
	// polynomial. Left-recursive rules are resolved by seed-growing rather than
	// refused; see recognize.go and leftrec.go.
	 := &recognizer{
		g:          ,
		input:      ,
		memo:       map[string]map[int]bool{},
		inProgress: map[string]bool{},
		leftRec:    .leftRecursiveSCCs(),
		growing:    map[string]map[int]bool{},
	}
	 := .reachElem(ElemRulename{Name: }, 0)
	return [len()], nil
}

// String returns the representation of the grammar that is valid
// according to the ABNF specifications/RFCs.
// This notably imply the use of CRLF instead of LF, and does not
// preserve the initial order nor pretty print it.
func ( *Grammar) () string {
	 := ""
	for ,  := range .Rulemap {
		 += .String() + "\r\n"
	}
	return 
}

// PrettyPrint returns a prettified string that represents the grammar.
func ( *Grammar) () string {
	// Determine maximum rulename length
	 := 0
	for  := range .Rulemap {
		if len() >  {
			 = len()
		}
	}

	// Construct output
	 := ""
	for ,  := range .Rulemap {
		 := ""
		for  := 0;  < -len(); ++ {
			 += " "
		}

		 += fmt.Sprintf("%s%s = %s\r\n", , , .Alternation)
	}
	return 
}

// ParseABNF is a helper facilitating the call to Parse using the
// pre-computed ABNF grammar and evaluated the resulting to produce
// a ready-to-use grammar.
func ( []byte,  ...ABNFOption) (*Grammar, error) {
	 := process(...)

	// Parse the ABNF source using the ABNF meta-grammar with the GLL engine.
	,  := Parse(, ABNF, "rulelist")
	if  != nil {
		return nil, 
	}
	if !.Valid() {
		return nil, .ParseError()
	}
	if .Ambiguous() {
		return nil, &ErrMultipleSolutionsFound{}
	}

	,  := evalForest(, , )
	if  != nil {
		return nil, 
	}

	if .validate {
		if  := SemvalABNF();  != nil {
			return nil, 
		}
	}
	return , nil
}

// Parse parses input against grammar starting at rootRulename using the GLL
// engine, returning the shared packed parse forest. Unlike the previous
// backtracking parser it accepts ANY grammar -- left, right and mutual
// recursion and ambiguity included -- in worst-case cubic time, so it never
// stack-overflows on left recursion nor blows up exponentially. Inspect the
// result with the Forest methods (Valid, Ambiguous, NumTrees, Tree).
func ( []byte,  *Grammar,  string) (*Forest, error) {
	return ParseForest(, , )
}

// EvaluateABNF evaluates a parse forest -- produced by parsing an ABNF source
// against the ABNF meta-grammar -- into a ready-to-use *Grammar.
func ( []byte,  *Forest,  ...ABNFOption) (*Grammar, error) {
	return evalForest(, , process(...))
}

func evalForest( []byte,  *Forest,  *abnfOptions) (*Grammar, error) {
	 := .Tree()
	if  == nil {
		return nil, ErrNoSolutionFound
	}
	 := &feval{input: , o: }
	return .rulelist()
}

// feval evaluates the rule-keyed ParseTree of an ABNF source into a *Grammar.
// It dispatches on rule names and reads byte spans, so it is decoupled from the
// exact (scaffolding-collapsed) shape of the tree.
type feval struct {
	input []byte
	o     *abnfOptions
}

func ptChildren( *ParseTree,  string) []*ParseTree {
	var  []*ParseTree
	for ,  := range .Children {
		if .Rule ==  {
			 = append(, )
		}
	}
	return 
}

func ptFirst( *ParseTree,  ...string) *ParseTree {
	for ,  := range .Children {
		if slices.Contains(, .Rule) {
			return 
		}
	}
	return nil
}

func ( *feval) ( *ParseTree) string { return string(.input[.Start:.End]) }

func ( *feval) ( *ParseTree) (*Grammar, error) {
	 := map[string]*Rule{}
	for ,  := range ptChildren(, "rule") {
		, ,  := .rule()
		if  != nil {
			return nil, 
		}
		switch  {
		case "=":
			 := GetRule(.Name, nil) != nil
			if  {
				if !.o.redefineCore {
					return nil, &ErrCoreRuleModify{CoreRulename: .Name}
				}
			} else if GetRule(.Name, ) != nil {
				return nil, &ErrDuplicatedRule{Rulename: .Name}
			}
			[.Name] = 
		case "=/":
			 := GetRule(.Name, nil) != nil
			if !.o.redefineCore &&  {
				return nil, &ErrCoreRuleModify{CoreRulename: .Name}
			}
			 := GetRule(.Name, )
			if  == nil {
				return nil, &ErrRuleNotFound{Rulename: .Name}
			}
			.Alternation.Concatenations = append(.Alternation.Concatenations, .Alternation.Concatenations...)
			[.Name] = 
		}
	}
	return &Grammar{Rulemap: }, nil
}

func ( *feval) ( *ParseTree) (*Rule, string, error) {
	 := ptFirst(, "rulename")
	 := ptFirst(, "defined-as")
	 := ptFirst(, "elements")
	if  == nil ||  == nil ||  == nil {
		return nil, "", ErrNoSolutionFound
	}
	 := "="
	if strings.Contains(.span(), "=/") {
		 = "=/"
	}
	 := ptFirst(, "alternation")
	if  == nil {
		return nil, "", ErrNoSolutionFound
	}
	,  := .alternation()
	if  != nil {
		return nil, "", 
	}
	return &Rule{Name: .span(), Alternation: }, , nil
}

func ( *feval) ( *ParseTree) (Alternation, error) {
	var  []Concatenation
	for ,  := range ptChildren(, "concatenation") {
		,  := .concatenation()
		if  != nil {
			return Alternation{}, 
		}
		 = append(, )
	}
	return Alternation{Concatenations: }, nil
}

func ( *feval) ( *ParseTree) (Concatenation, error) {
	var  []Repetition
	for ,  := range ptChildren(, "repetition") {
		,  := .repetition()
		if  != nil {
			return Concatenation{}, 
		}
		 = append(, )
	}
	return Concatenation{Repetitions: }, nil
}

func ( *feval) ( *ParseTree) (Repetition, error) {
	,  := 1, 1
	if  := ptFirst(, "repeat");  != nil {
		,  = .parseRepeat()
	}
	 := ptFirst(, "element")
	if  == nil {
		return Repetition{}, ErrNoSolutionFound
	}
	,  := .element()
	if  != nil {
		return Repetition{}, 
	}
	return Repetition{Min: , Max: , Element: }, nil
}

func ( *feval) ( *ParseTree) (int, int) {
	 := .span()
	, ,  := strings.Cut(, "*")
	if ! {
		,  := strconv.Atoi()
		return , 
	}
	,  := 0, inf
	if  := ;  != "" {
		, _ = strconv.Atoi()
	}
	if  := ;  != "" {
		, _ = strconv.Atoi()
	}
	return , 
}

func ( *feval) ( *ParseTree) (ElemItf, error) {
	 := ptFirst(, "rulename", "group", "option", "char-val", "num-val", "prose-val")
	if  == nil {
		return nil, ErrNoSolutionFound
	}
	switch .Rule {
	case "rulename":
		return ElemRulename{Name: .span()}, nil
	case "group":
		,  := .alternation(ptFirst(, "alternation"))
		if  != nil {
			return nil, 
		}
		return ElemGroup{Alternation: }, nil
	case "option":
		,  := .alternation(ptFirst(, "alternation"))
		if  != nil {
			return nil, 
		}
		return ElemOption{Alternation: }, nil
	case "char-val":
		return .charVal(), nil
	case "num-val":
		return .numVal(), nil
	case "prose-val":
		return .proseVal(), nil
	}
	return nil, ErrNoSolutionFound
}

func ( *feval) ( *ParseTree) ElemCharVal {
	 := .span()
	 := false
	if len() >= 2 && [0] == '%' {
		if [1] == 's' || [1] == 'S' {
			 = true
		}
		 = [2:]
	}
	 := strings.IndexByte(, '"')
	 := strings.LastIndexByte(, '"')
	 := []rune{}
	if  >= 0 &&  >  {
		 = []rune([+1 : ])
	}
	return ElemCharVal{Sensitive: , Values: }
}

func ( *feval) ( *ParseTree) ElemNumVal {
	 := .span()
	 := "d"
	 := ""
	if len() >= 2 && [0] == '%' {
		switch [1] {
		case 'b', 'B':
			 = "b"
		case 'd', 'D':
			 = "d"
		case 'x', 'X':
			 = "x"
		}
		 = [2:]
	}
	 := StatSeries
	var  []string
	if strings.ContainsRune(, '-') {
		 = StatRange
		 = strings.Split(, "-")
	} else {
		 = strings.Split(, ".")
	}
	// A num-val outside the Unicode range is still a well-formed numeric
	// encoding (legitimate for non-textual / on-wire grammars), so it is kept
	// as-is here. Strict semantic validation (SemvalABNF) rejects it for textual
	// use; consumers that match against decoded runes treat an unrepresentable
	// value as non-matching rather than panicking.
	return ElemNumVal{Base: , Status: , Elems: }
}

func ( *feval) ( *ParseTree) ElemProseVal {
	 := []string{}
	for  := .Start + 1;  < .End-1; ++ {
		 = append(, string(.input[]))
	}
	return ElemProseVal{values: }
}

func sensequal(,  rune,  bool) bool {
	if ! {
		,  = runeMin(), runeMin()
	}
	return  == 
}

func runeMin( rune) rune {
	if  >= 'A' &&  <= 'Z' {
		return  - 'A' + 'a'
	}
	return 
}

func runeMax( rune) rune {
	if  >= 'a' &&  <= 'z' {
		return  - 'a' + 'A'
	}
	return 
}

// SemvalABNF proceed to semantic validations of an ABNF grammar.
// It currently support the following checks:
// - for all rules, its dependencies (rules) exist
// - for repetition, min <= max
// - for num-val, that the value fits in 7-bits (US-ASCII encoded)
// To update this list, please open an issue.
func ( *Grammar) error {
	// Check all dependencies exist
	for ,  := range .Rulemap {
		 := getDependencies(.Alternation)
		for ,  := range  {
			 := GetRule(, .Rulemap)
			if  == nil {
				return &ErrDependencyNotFound{
					Rulename: ,
				}
			}
		}
	}

	for ,  := range .Rulemap {
		if  := semvalAlternation(.Alternation);  != nil {
			return 
		}
	}
	return nil
}

func semvalAlternation( Alternation) error {
	for ,  := range .Concatenations {
		for ,  := range .Repetitions {
			// min <= max
			if .Max != inf && .Min > .Max {
				return &ErrSemanticRepetition{
					Repetition: ,
				}
			}
			switch elem := .Element.(type) {
			// num-val base
			case ElemNumVal:
				for ,  := range .Elems {
					if  := checkBounds(, .Base);  != nil {
						return 
					}
				}

			// propagate recursion
			case ElemGroup:
				if  := (.Alternation);  != nil {
					return 
				}

			case ElemOption:
				if  := (.Alternation);  != nil {
					return 
				}
			}
		}
	}
	return nil
}