package goabnfimport ()// Generates strings by recursive descent over the grammar AST, so unlike the*// transition-graph Generator (a finite automaton, which can only express// *regular* rules) it handles genuinely recursive rules -- nested objects,// balanced delimiters, expression grammars -- where a rule is reached many times// at many depths.//// The hard part of recursive generation is termination: a recursive rule can// expand forever. This generator guarantees a finite, valid production by// precomputing each rule's minimum expansion cost and, whenever a depth or// length budget is exceeded, steering every choice toward the cheapest-to-finish// expansion. It never truncates mid-derivation, so the output is always a// complete word of the grammar. (It shares the tape/rand entropy `source` with// the transition-graph generator, so it slots into testing.F the same way.)const astUnbounded = 1 << 30// "infinite" min-length sentinel (non-productive)// ASTGenerator generates strings admitted by a (possibly recursive) grammar// rule, directly from the AST.typeASTGeneratorstruct { g *Grammar start *Rule maxDepth int// rule-expansion depth before steering to terminate maxLen int// output bytes before steering to terminate maxRepeat int// cap for unbounded ("*") repetitions minCost map[string]int// rule name -> minimum expansion cost (productivity)}// ASTGenOption configures an ASTGenerator.typeASTGenOptioninterface { apply(*ASTGenerator)}type astGenOptionFunc func(*ASTGenerator)func ( astGenOptionFunc) ( *ASTGenerator) { ()}// WithMaxDepth bounds rule-expansion (recursion) depth; past it the generator// steers toward terminating expansions. Defaults to 32.func ( int) ASTGenOption {returnastGenOptionFunc(func( *ASTGenerator) { .maxDepth = })}// WithMaxLen bounds the output length; past it the generator steers toward// terminating expansions. Defaults to 4096. (Mandatory repetitions are always// emitted, so the bound is soft -- a single huge fixed repetition can exceed it.)func ( int) ASTGenOption {returnastGenOptionFunc(func( *ASTGenerator) { .maxLen = })}// WithMaxRepeat caps how far an unbounded ("*" / "1*") repetition is unrolled.// Defaults to 16.func ( int) ASTGenOption {returnastGenOptionFunc(func( *ASTGenerator) { .maxRepeat = })}// NewASTGenerator prepares a generator for rule. It errors if the rule is// undefined, or if any rule reachable from it is undefined or non-productive// (cannot derive any finite string), since neither can be generated. Unlike the// transition-graph generator, recursive rules are fully supported.func ( *Grammar, string, ...ASTGenOption) (*ASTGenerator, error) { := GetRule(, .Rulemap)if == nil {returnnil, &ErrRuleNotFound{Rulename: } } := &ASTGenerator{g: ,start: ,maxDepth: 32,maxLen: 4096,maxRepeat: 16, }for , := range { .apply() }// Least-fixpoint of minimum expansion cost over every rule reachable in // principle -- user rules and the built-in core rules (ALPHA, DIGIT, ...), // which GetRule resolves as a fallback but which are absent from Rulemap. // Keyed by canonical rule name (GetRule is case-insensitive and honors user // overrides of core rules). A rule stuck at the sentinel is non-productive. := map[string]*Rule{}for := range .Rulemap {if := GetRule(, .Rulemap); != nil { [.Name] = } }for := rangecoreRules {if := GetRule(, .Rulemap); != nil { [.Name] = } } .minCost = make(map[string]int, len())for := range { .minCost[] = astUnbounded }for := true; ; { = falsefor , := range {if := .costAlt(.Alternation); < .minCost[] { .minCost[] = = true } } }// Every rule reachable from start must be defined and productive. := map[string]bool{.Name: true}varfunc(Alternation) error := func( ElemItf) error {switch x := .(type) {caseElemRulename: := GetRule(.Name, .Rulemap)if == nil {returnfmt.Errorf("rule %q (reachable from %q) is undefined and cannot be generated", .Name, ) }if [.Name] {returnnil } [.Name] = trueif .minCost[.Name] >= astUnbounded {returnfmt.Errorf("rule %q (reachable from %q) is non-productive (cannot derive any finite string)", .Name, ) }return (.Alternation)caseElemGroup:return (.Alternation)caseElemOption:return (.Alternation) }returnnil } = func( Alternation) error {for , := range .Concatenations {for , := range .Repetitions {if := (.Element); != nil {return } } }returnnil }if .minCost[.Name] >= astUnbounded {returnnil, fmt.Errorf("rule %q is non-productive (cannot derive any finite string)", ) }if := (.Alternation); != nil {returnnil, }return , nil}// Generate maps the tape to a production the grammar admits. Total and// deterministic: any tape (including nil) yields a valid production; an// exhausted tape biases toward the shortest one.func ( *ASTGenerator) ( []byte) []byte {return .walk(&tapeSource{tape: })}// GenerateRand draws a production using r as the entropy source.func ( *ASTGenerator) ( *rand.Rand) []byte {return .walk(randSource{r: })}func ( *ASTGenerator) ( source) []byte { := []byte{} .genAlt(, &, .start.Alternation, 0)return}// over reports whether we should stop taking expansions for their own sake and// steer toward the nearest terminal string.func ( *ASTGenerator) ( *[]byte, int) bool {return >= .maxDepth || len(*) >= .maxLen}func ( *ASTGenerator) ( source, *[]byte, Alternation, int) { := .Concatenationsiflen() == 0 {return } := 0if .over(, ) { = .cheapestConcat() // steer: pick the cheapest-to-finish branch } elseiflen() > 1 { = .intn(len()) } .genConcat(, , [], )}func ( *ASTGenerator) ( source, *[]byte, Concatenation, int) {for , := range .Repetitions { .genRep(, , , ) }}func ( *ASTGenerator) ( source, *[]byte, Repetition, int) { := .Min := .Maxif == inf || < { // unbounded: cap the optional unrolling = + .maxRepeat } := if !.over(, ) && > { = + .intn(-+1) }for := 0; < ; ++ { .genElem(, , .Element, )// Stop optional extras once over length, but always emit the mandatory lo.if +1 >= && len(*) >= .maxLen {break } }}func ( *ASTGenerator) ( source, *[]byte, ElemItf, int) {switch e := .(type) {caseElemRulename:// Guaranteed defined+productive by NewASTGenerator. := GetRule(.Name, .g.Rulemap) .genAlt(, , .Alternation, +1)caseElemGroup: .genAlt(, , .Alternation, )caseElemOption:if !.over(, ) && .intn(2) == 1 { .genAlt(, , .Alternation, ) }caseElemCharVal:for , := range .Values {if !.Sensitive && isASCIILetter() && .intn(2) == 1 { = flipASCIICase() } * = append(*, []byte(string())...) }caseElemNumVal:switch .Status {caseStatSeries:for , := range .Elems { := numvalToRune(, .Base)// Emit only real characters; an out-of-range value cannot appear // in UTF-8 input, so the series would never match anyway.ifutf8.ValidRune() { * = append(*, []byte(string())...) } }caseStatRange: , := numvalToRune(.Elems[0], .Base), numvalToRune(.Elems[1], .Base)// Emit within the representable (Unicode) subset of the range.if > utf8.MaxRune { = utf8.MaxRune }if > utf8.MaxRune || > {break// nothing representable to emit } := int(-) + 1if < 1 { = 1 } * = append(*, []byte(string(+rune(.intn())))...) }caseElemProseVal:// prose-val is informal text; nothing mechanical to emit. }}// cheapestConcat returns the index of the concatenation with the smallest// minimum expansion cost -- the fastest way to finish the current alternation.func ( *ASTGenerator) ( []Concatenation) int { , := 0, .costConcat([0])for := 1; < len(); ++ {if := .costConcat([]); < { , = , } }return}// ---- minimum-expansion-cost cost model (for productivity + steering) ----func ( *ASTGenerator) ( Alternation) int {iflen(.Concatenations) == 0 {return0 } := astUnboundedfor , := range .Concatenations {if := .costConcat(); < { = } }return}func ( *ASTGenerator) ( Concatenation) int { := 0for , := range .Repetitions { = addClamp(, mulClamp(.Min, .costElem(.Element))) }return}func ( *ASTGenerator) ( ElemItf) int {switch e := .(type) {caseElemRulename: := GetRule(.Name, .g.Rulemap)if == nil {returnastUnbounded// undefined rule }if , := .minCost[.Name]; {// +1 expansion penalty: referencing a rule always costs strictly // more than emitting a terminal, so a recursive branch can never // tie with (and be chosen over) a terminating one -- even when a // nullable prefix makes their emitted lengths equal.returnaddClamp(1, ) }returnastUnboundedcaseElemGroup:return .costAlt(.Alternation)caseElemOption:return0// can be skippedcaseElemCharVal:returnlen(string(.Values))caseElemNumVal:switch .Status {caseStatSeries: := 0for , := range .Elems { += len(string(numvalToRune(, .Base))) }returndefault: // StatRange: one rune, take the lower bound's encoded lengthreturnlen(string(numvalToRune(.Elems[0], .Base))) }caseElemProseVal:return0 }return0}func addClamp(, int) int {if >= astUnbounded || >= astUnbounded {returnastUnbounded }if := + ; < astUnbounded {return }returnastUnbounded}func mulClamp(, int) int {if == 0 {return0 }if >= astUnbounded {returnastUnbounded }if := * ; >= 0 && < astUnbounded {return }returnastUnbounded}func isASCIILetter( rune) bool {return ( >= 'a' && <= 'z') || ( >= 'A' && <= 'Z')}func flipASCIICase( rune) rune {switch {case >= 'a' && <= 'z':return - 'a' + 'A'case >= 'A' && <= 'Z':return - 'A' + 'a' }return}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.