package goabnf
import (
"errors"
"maps"
"math/rand"
"strings"
"unicode/utf8"
)
func (g *Grammar ) Generate (seed int64 , rulename string , opts ...GenerateOption ) ([]byte , error ) {
if err := checkCanGenerateSafely (g , rulename ); err != nil {
return nil , err
}
rand := rand .NewSource (seed )
options := &genOpts {
repMax : 16 ,
threshold : 256 ,
}
for _ , opt := range opts {
opt .apply (options )
}
rule := GetRule (rulename , g .Rulemap )
out := []byte {}
generateAlt (rand , g , &out , rule .Alternation , options )
return out , nil
}
func generateAlt(rand rand .Source , g *Grammar , out *[]byte , alt Alternation , options *genOpts ) {
cnt := alt .Concatenations [int (rand .Int63 ())%len (alt .Concatenations )]
for _ , rep := range cnt .Repetitions {
repmax := rep .Max
if repmax == inf {
repmax = options .repMax
}
torep := rep .Min + int (rand .Int63 ())%(repmax -rep .Min +1 )
for i := 0 ; generateKeepGoing (i , torep , rep .Min , len (*out ), options .threshold ); i ++ {
switch elem := rep .Element .(type ) {
case ElemRulename :
rule := GetRule (elem .Name , g .Rulemap )
generateAlt (rand , g , out , rule .Alternation , options )
case ElemOption :
if (rand .Int63 () % 2 ) == 0 {
generateAlt (rand , g , out , elem .Alternation , options )
}
case ElemGroup :
generateAlt (rand , g , out , elem .Alternation , options )
case ElemNumVal :
switch elem .Status {
case StatRange :
min , max := numvalToRune (elem .Elems [0 ], elem .Base ), numvalToRune (elem .Elems [1 ], elem .Base )
if max > utf8 .MaxRune {
max = utf8 .MaxRune
}
if min <= utf8 .MaxRune && min <= max {
r := min + (rune (rand .Int63 ()&0x0F ) % (max - min + 1 ))
appendPtr (out , r )
}
case StatSeries :
for _ , v := range elem .Elems {
r := numvalToRune (v , elem .Base )
if utf8 .ValidRune (r ) {
appendPtr (out , r )
}
}
}
case ElemCharVal :
for _ , val := range elem .Values {
if !elem .Sensitive && (int (rand .Int63 ())%2 ) == 0 {
val = runeMax (val )
}
appendPtr (out , val )
}
}
}
}
}
func appendPtr(slc *[]byte , v ...rune ) {
b := *slc
b = append (b , []byte (string (v ))...)
*slc = b
}
func generateKeepGoing(i , torep , minrep , lenout , threshold int ) bool {
if i == 0 && minrep == 0 && lenout >= threshold {
return false
}
return i < torep
}
type GenerateOption interface {
apply(*genOpts )
}
type genOpts struct {
repMax int
threshold int
}
type repMaxOption int
func WithRepMax (repMax int ) repMaxOption {
return repMaxOption (repMax )
}
func (opt repMaxOption ) apply (opts *genOpts ) {
opts .repMax = int (opt )
}
type thresholdOption int
func WithThreshold (threshold int ) thresholdOption {
return thresholdOption (threshold )
}
func (opt thresholdOption ) apply (opts *genOpts ) {
opts .threshold = int (opt )
}
func checkCanGenerateSafely(g *Grammar , rulename string ) error {
rule := GetRule (rulename , g .Rulemap )
if rule == nil {
return &ErrRuleNotFound {
Rulename : rulename ,
}
}
knownRules := map [string ]struct {}{
rulename : {},
}
if err := checkCanGenerateSafelyAlt (g , knownRules , rule .Alternation ); err != nil {
if err , ok := err .(*ErrCyclicRule ); ok {
return err
}
return &ErrCyclicRule {
Rulename : rulename ,
}
}
return nil
}
func checkCanGenerateSafelyAlt(g *Grammar , knownRules map [string ]struct {}, alt Alternation ) error {
errs := make ([]error , len (alt .Concatenations ))
for alti , concat := range alt .Concatenations {
errs [alti ] = checkCanGenerateSafelyConcat (g , knownRules , concat )
}
allErrors := true
for i := 0 ; i < len (errs ) && allErrors ; i ++ {
if errs [i ] == nil {
allErrors = false
}
}
if allErrors {
return errors .Join (errs ...)
}
return nil
}
func checkCanGenerateSafelyConcat(g *Grammar , knownRules map [string ]struct {}, concat Concatenation ) error {
for _ , rep := range concat .Repetitions {
if rep .Min == 0 {
continue
}
switch elem := rep .Element .(type ) {
case ElemRulename :
scopeRules := duplicateMap (knownRules )
for known := range scopeRules {
if strings .EqualFold (elem .Name , known ) {
return &ErrCyclicRule {
Rulename : elem .Name ,
}
}
}
rule := GetRule (elem .Name , g .Rulemap )
scopeRules [elem .Name ] = struct {}{}
if err := checkCanGenerateSafelyAlt (g , scopeRules , rule .Alternation ); err != nil {
if err , ok := err .(*ErrCyclicRule ); ok {
return err
}
return &ErrCyclicRule {
Rulename : elem .Name ,
}
}
case ElemGroup :
if err := checkCanGenerateSafelyAlt (g , knownRules , elem .Alternation ); err != nil {
return err
}
case ElemProseVal :
return ErrHandlingProseVal
}
}
return nil
}
func duplicateMap[T comparable , V any ](m map [T ]V ) map [T ]V {
n := make (map [T ]V , len (m ))
maps .Copy (n , m )
return n
}
The pages are generated with Golds v0.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 .