package goabnfimport ()// This file implements a GLL parser (Scott & Johnstone) producing a binarized// Shared Packed Parse Forest (SPPF) for ABNF grammars.//// GLL parses ANY context-free grammar -- including left, right, hidden and// mutual recursion, and arbitrary ambiguity -- in worst-case O(n^3) time and// space, using a graph-structured stack (GSS) and a descriptor worklist whose// "seen" set makes recursion terminate. The forest shares every sub-derivation// and packs ambiguity, so it stays polynomial even when it represents// exponentially or infinitely many trees.//// Pipeline: lower the ABNF AST into a flat slotted grammar (synthetic// nonterminals for groups, options and repetitions), then run GLL over the// slots. Recognition, ambiguity, tree counting and extraction are polynomial// queries over the resulting forest.// ---------------------------------------------------------------------------// Slotted grammar// ---------------------------------------------------------------------------type symKind uint8const ( symNonterm symKind = iota symTerm // a char-val / num-val / prose-val matcher symEps // matches the empty string)type ssym struct { kind symKind nt int// nonterminal id, for symNonterm term ElemItf// terminal element, for symTerm}type sgNT struct { label string// diagnostic label isRule bool// corresponds to an original ABNF rule (kept in the tree) ruleName string// original rule name when isRule alts [][]ssym// alternates; every alternate has >= 1 symbol// Native counted repetition. When isRep, the nonterminal stands for // `repElem{repMin,repMax}` and its two alternates are the self-recursive // encoding `R ::= eps | repElem R`. The [repMin,repMax] bound is enforced at // parse time by a count carried in the GLL state (see addRepAlts), so the // slot grammar stays O(1) in the repetition bound instead of unrolling it. isRep bool repMin int repMax int// inf (== -1) means unbounded}type slotGrammar struct { nts []*sgNT index map[string]int// dedup key -> nt id start int la *lookahead// selection sets guarding descriptor creation}func ( *slotGrammar) (, string) (int, bool) {if , := .index[]; {return , true } := len(.nts) .nts = append(.nts, &sgNT{label: }) .index[] = return , false}// compileSlots lowers grammar starting at rootRulename into a slotted grammar.const defaultMaxSlots = 1 << 16func compileSlots( *Grammar, string, int) (*slotGrammar, error) {ifGetRule(, .Rulemap) == nil {returnnil, &ErrRuleNotFound{Rulename: } } := &slotGrammar{index: map[string]int{}} := &lowerer{g: , sg: , max: } .start = .rule()if .err != nil {returnnil, .err }if .over {returnnil, &ErrGrammarTooLarge{Max: } } .la = computeLookahead()return , nil}type lowerer struct { g *Grammar sg *slotGrammar err error max int// max nonterminals; 0 == unbounded over bool// budget exceeded}func ( *lowerer) () bool {if .max > 0 && len(.sg.nts) >= .max { .over = true }return .over}func ( *lowerer) ( string) int { := "rule:" + canon() , := .sg.reserve(, )if {return }if .budgetExceeded() {return } := GetRule(, .g.Rulemap)if == nil {// Unknown rule: a nonterminal with no alternates derives nothing. .sg.nts[].label = return } .sg.nts[].isRule = true .sg.nts[].ruleName = .Name .sg.nts[].alts = .alts(.Alternation)return}func ( *lowerer) ( Alternation) [][]ssym { := make([][]ssym, 0, len(.Concatenations))for , := range .Concatenations { := make([]ssym, 0, len(.Repetitions))for , := range .Repetitions { = append(, .rep()) }iflen() == 0 { = []ssym{{kind: symEps}} } = append(, ) }return}func ( *lowerer) ( Repetition) ssym {if .Min == 1 && .Max == 1 {return .elem(.Element) } := "rep:" + .String() , := .sg.reserve(, .String())if {returnssym{kind: symNonterm, nt: } }if .budgetExceeded() {returnssym{kind: symNonterm, nt: } }// A malformed bound where max < min accepts nothing: leave the rep // nonterminal with no alternates so it derives the empty language (it is // unsatisfiable, NOT unbounded). This matches the recognizer.if .Max != inf && .Max < .Min {returnssym{kind: symNonterm, nt: } }// Lower to the self-recursive encoding R ::= eps | E R, a single nonterminal // regardless of the bound. The [Min,Max] count is enforced at parse time // (addRepAlts), so lowering is O(1) in the bound and there is no per-count // nonterminal explosion (the old optTail/reqOne unrolling, which scaled with // Max-Min and Min respectively). := .elem(.Element) := ssym{kind: symNonterm, nt: } .sg.nts[].alts = [][]ssym{ {{kind: symEps}}, // alt 0: stop {, }, // alt 1: consume one element, then loop } .sg.nts[].label = .String() .sg.nts[].isRep = true .sg.nts[].repMin = .Min .sg.nts[].repMax = .Maxreturn}func ( *lowerer) ( ElemItf) ssym {switch v := .(type) {caseElemRulename:returnssym{kind: symNonterm, nt: .rule(.Name)}caseElemGroup:returnssym{kind: symNonterm, nt: .group()}caseElemOption:returnssym{kind: symNonterm, nt: .option()}caseElemCharVal, ElemNumVal, ElemProseVal:returnssym{kind: symTerm, term: } }returnssym{kind: symTerm, term: }}func ( *lowerer) ( ElemGroup) int { := "grp:" + .String() , := .sg.reserve(, .String())if {return }if .budgetExceeded() {return } .sg.nts[].alts = .alts(.Alternation)return}func ( *lowerer) ( ElemOption) int { := "opt:" + .String() , := .sg.reserve(, .String())if {return }if .budgetExceeded() {return } := [][]ssym{{{kind: symEps}}} = append(, .alts(.Alternation)...) .sg.nts[].alts = return}func canon( string) string { := []byte()for := range {if [] >= 'A' && [] <= 'Z' { [] += 'a' - 'A' } }returnstring()}// ---------------------------------------------------------------------------// SPPF nodes// ---------------------------------------------------------------------------type gnodeKind uint8const ( gSymbol gnodeKind = iota// a nonterminal node (Start..End) gInter // a binarisation intermediate node gTerm // a terminal / epsilon node)type gnode struct { kind gnodeKind nt int// symbol nonterminal id, for gSymbol Start, End int packs []pack// >1 pack == ambiguity}// pack is a packed node. It is labelled by the grammar slot it completes and// its pivot (Scott & Johnstone, "GLL parse-tree generation", Science of// Computer Programming 78(10), 2013, §3.1); the pivot is the left extent of the// last child. Two alternates deriving the same span through the same children// are distinct derivations, hence distinct packed nodes.type pack struct { L slot kids []*gnode// 1 or 2 children}func ( *gnode) ( slot, []*gnode) {for , := range .packs {if .L != || len(.kids) != len() {continue } := truefor := range .kids {if .kids[] != [] { = falsebreak } }if {return } } .packs = append(.packs, pack{L: , kids: })}// ---------------------------------------------------------------------------// GLL machinery// ---------------------------------------------------------------------------type slot struct{ nt, alt, dot int }type gssNode struct { ret slot// return slot pos int rc int// repetition count carried for native counted repetition (0 otherwise) edges []gssEdge edgeSet map[gssEdge]bool}type gssEdge struct { w *gnode to *gssNode}type descriptor struct { L slot u *gssNode i int w *gnode rc int// repetition count (0 outside a counted repetition)}type gllParser struct { sg *slotGrammar input []byte nodes map[nodeKey]*gnode gss map[gssKey]*gssNode u0 *gssNode seen map[descriptor]bool work []descriptor popped map[*gssNode]map[*gnode]bool maxNodes int aborted bool// Furthest-failure diagnostics: maxPos is the deepest input offset at which // a terminal match was attempted and failed; expected collects the terminals // that could have been consumed there (deduplicated via expectedSeen). They // drive ParseError when the parse has no solution. maxPos int expected []string expectedSeen map[string]bool}// nodeKey interns SPPF nodes without allocating strings. Distinct kinds never// collide: symbol nodes key on (kind,nt,start,end); intermediate nodes on// (kind,L,start,end); terminal nodes on (kind,start,end).type nodeKey struct { kind gnodeKind nt int L slot start, end int}type gssKey struct { ret slot pos int rc int}// addAlt adds the descriptor starting alternate L.alt of L.nt at i when the// lookahead test admits it. A rejected alternate would fail on its first// terminal at i (or, when nullable, its continuation would), so its terminals// are reported to the furthest-failure diagnostics in its place.func ( *gllParser) ( slot, *gssNode, int, int) {if .admits(.sg.la.alt(.nt, .alt), ) { .add(, , , nil, ) }}// admits applies a lookahead test at i. A rejected sequence would have failed// on one of the set's terminals at i, so those feed the furthest-failure// diagnostics in its place.func ( *gllParser) ( *laSet, int) bool {if .admits(.input, ) {returntrue }if >= .maxPos {for , := range .terms { .noteFail(, ) } }returnfalse}func ( *gllParser) ( slot, *gssNode, int, *gnode, int) { := descriptor{, , , , }if .seen[] {return } .seen[] = true .work = append(.work, )}func ( *gllParser) ( slot, , int) *gssNode { := gssKey{, , }if , := .gss[]; {return } := &gssNode{ret: , pos: , rc: , edgeSet: map[gssEdge]bool{}} .gss[] = return}func ( *gllParser) ( slot, *gssNode, int, *gnode, int) *gssNode { := .gssNodeFor(, , ) := gssEdge{w: , to: }if !.edgeSet[] { .edgeSet[] = true .edges = append(.edges, )for := range .popped[] { := .getNodeP(, , ) .add(, , .End, , ) } }return}func ( *gllParser) ( *gssNode, int, *gnode) {if == .u0 {return }if .popped[] == nil { .popped[] = map[*gnode]bool{} } .popped[][] = truefor , := range .edges { := .getNodeP(.ret, .w, ) .add(.ret, .to, , , .rc) }}func ( *gllParser) ( nodeKey) *gnode {if , := .nodes[]; {return }if .maxNodes > 0 && len(.nodes) >= .maxNodes { .aborted = true } := &gnode{kind: .kind, nt: .nt, Start: .start, End: .end} .nodes[] = return}func ( *gllParser) (, int) *gnode {return .findNode(nodeKey{kind: gTerm, nt: -1, start: , end: })}// getNodeP combines left node w (may be nil == $) and right node z under slot L.func ( *gllParser) ( slot, , *gnode) *gnode { := .sg.nts[.nt].alts[.alt] := .dot == len()if .dot == 1 && ! {return// single symbol consumed, more to come: pass straight up } := .Startif != nil { = .Start }varnodeKeyif { = nodeKey{kind: gSymbol, nt: .nt, start: , end: .End} } else { = nodeKey{kind: gInter, nt: -1, L: , start: , end: .End} } := .findNode()if != nil { .addPack(, []*gnode{, }) } else { .addPack(, []*gnode{}) }return}// matchTerm returns the end index after matching the terminal at i, or -1.func ( *gllParser) ( ssym, int) int {if .kind == symEps {return }switch v := .term.(type) {caseElemCharVal: := for := 0; < len(.Values); ++ {if >= len(.input) {return -1 } , := utf8.DecodeRune(.input[:])if == utf8.RuneError && == 1 {return -1 }if !sensequal(.Values[], , .Sensitive) {return -1 } += }returncaseElemNumVal:switch .Status {caseStatRange:if >= len(.input) {return -1 }// Numeric comparison: a range straddling U+10FFFF matches its rune // subset; numvalToRune never panics (saturates out-of-int32 bounds). := numvalToRune(.Elems[0], .Base) := numvalToRune(.Elems[1], .Base) , := utf8.DecodeRune(.input[:])if == utf8.RuneError && == 1 {return -1 }if <= && <= {return + }return -1caseStatSeries: := for := 0; < len(.Elems); ++ { := numvalToRune(.Elems[], .Base)// Series elements must be real characters: an out-of-range value // matches no UTF-8 input (and avoids a spurious U+FFFD match).if !utf8.ValidRune() {return -1 } := string() := len()if + > len(.input) || != string(.input[:+]) {return -1 } += }return } }return -1// prose-val and anything else never matches}// parse runs the GLL loop and returns the symbol node (start, 0, n) or nil.func ( *gllParser) () *gnode { := .sg.start .u0 = &gssNode{ret: slot{-1, -1, -1}, pos: 0}for := range .sg.nts[].alts { .addAlt(slot{, , 0}, .u0, 0, 0) }forlen(.work) > 0 {if .aborted {returnnil } := .work[len(.work)-1] .work = .work[:len(.work)-1] .process() } := nodeKey{kind: gSymbol, nt: , start: 0, end: len(.input)}return .nodes[]}func ( *gllParser) ( descriptor) { , , , , := .L, .u, .i, .w, .rcfor { := .sg.nts[.nt].alts[.alt]if .dot == len() { := if == nil { = .getNodeT(, ) } .pop(, , )return } := [.dot]if .kind == symNonterm {if !.admits(.sg.la.callAt(), ) {return } := slot{.nt, .alt, .dot + 1}// Preserve the current repetition frame count across the sub-parse so // that when it returns we resume the loop with the right count. := .create(, , , , )if .sg.nts[.nt].isRep {// Native counted repetition: a self-reference inside the rep's own // loop alternate continues the chain (count+1); any other reference // starts a fresh chain at count 0. := 0if .nt == .nt { = capRC(, .sg.nts[.nt]) } .addRepAlts(.nt, , , ) } else {for := range .sg.nts[.nt].alts { .addAlt(slot{.nt, , 0}, , , 0) } }return } := .matchTerm(, )if < 0 { .noteFail(, )return } := .getNodeT(, ) := slot{.nt, .alt, .dot + 1} = .getNodeP(, , ) = = }}// noteFail records that a terminal match failed at input offset i. It maintains// the furthest such offset and, for that offset only, the set of terminals that// could have been consumed -- the classic "furthest-failure" position used to// report where parsing got stuck.func ( *gllParser) ( int, ssym) {if > .maxPos { .maxPos = .expected = .expected[:0] .expectedSeen = nil }if != .maxPos {return } := "?"if , := .term.(fmt.Stringer); { = .String() }if .expectedSeen == nil { .expectedSeen = map[string]bool{} }if !.expectedSeen[] { .expectedSeen[] = true .expected = append(.expected, ) }}// capRC returns the count after consuming one more element of a repetition R// currently at count rc. For an unbounded repetition it saturates at repMin// (once the minimum is met the exact count no longer matters), which keeps the// reachable counts -- and hence the GLL state -- finite even when the element is// nullable.func capRC( int, *sgNT) int { := + 1if .repMax == inf && > .repMin { = .repMin }return}// addRepAlts seeds the two alternates of a repetition nonterminal, gated by the// current count rc: it may stop (alt 0) only once the minimum is met, and may// consume another element (alt 1) only while under the maximum. This enforces// the {repMin,repMax} bound in parser state instead of unrolling it into the// grammar, mirroring the recognizer's c>=min / c<max gates. rc is carried in the// GSS key so two derivations that reach the same point with different committed// counts are kept distinct (no over-/under-counting via shared continuations).func ( *gllParser) ( int, *gssNode, , int) { := .sg.nts[]if >= .repMin { .addAlt(slot{, 0, 0}, , , ) // stop: alt 0 == [eps] }if .repMax == inf || < .repMax { .addAlt(slot{, 1, 0}, , , ) // loop: alt 1 == [element, self] }}// ---------------------------------------------------------------------------// Public API// ---------------------------------------------------------------------------// Forest is a shared packed parse forest produced by ParseForest.typeForeststruct { sg *slotGrammar input []byte rulename string root *gnode built int// maxPos / expected carry the furthest-failure diagnostics from the parse, // surfaced through ParseError when the forest is invalid. maxPos int expected []string}// ForestOption configures ParseForest.typeForestOptionfunc(*forestConfig)type forestConfig struct { maxNodes int maxSlots int}// WithMaxForestNodes bounds the number of SPPF nodes the forest may allocate.// Because a complete SPPF is worst-case cubic in the input length, this caps the// time and memory ParseForest can spend on adversarial input. 0 means unbounded.func ( int) ForestOption { returnfunc( *forestConfig) { .maxNodes = } }// WithMaxSlots bounds the number of nonterminals produced while lowering the// grammar. A finite repetition m*n lowers to ~n nonterminals, so this caps the// cost of an adversarial grammar such as a = 9999999999"x". 0 means unbounded;// the default is 65536.func ( int) ForestOption { returnfunc( *forestConfig) { .maxSlots = } }// ErrForestTooLarge is returned by ParseForest when the SPPF exceeds the// configured WithMaxForestNodes budget.typeErrForestTooLargestruct{ Max int }func ( *ErrForestTooLarge) () string {return"abnf: parse forest exceeded " + strconv.Itoa(.Max) + " nodes"}// ErrGrammarTooLarge is returned by ParseForest when lowering the grammar would// exceed the WithMaxSlots budget, typically because of an absurd repetition// bound (e.g. a = 9999999999"x").typeErrGrammarTooLargestruct{ Max int }func ( *ErrGrammarTooLarge) () string {return"abnf: grammar lowering exceeded " + strconv.Itoa(.Max) + " nonterminals"}func newGLLParser( *slotGrammar, []byte, int) *gllParser {return &gllParser{sg: ,input: ,nodes: map[nodeKey]*gnode{},gss: map[gssKey]*gssNode{},seen: map[descriptor]bool{},popped: map[*gssNode]map[*gnode]bool{},maxNodes: , }}// ParseForest parses input with grammar starting at rootRulename using GLL,// returning the shared packed parse forest. It runs in worst-case O(n^3) time// and space for ANY grammar -- left/right/mutual recursion and ambiguity// included -- so it is safe on untrusted or malformed grammars.func ( []byte, *Grammar, string, ...ForestOption) (*Forest, error) { := forestConfig{maxSlots: defaultMaxSlots}for , := range { (&) } , := compileSlots(, , .maxSlots)if != nil {returnnil, } := newGLLParser(, , .maxNodes) := .parse()if .aborted {returnnil, &ErrForestTooLarge{Max: .maxNodes} }return &Forest{sg: , input: , rulename: , root: , built: len(.nodes), maxPos: .maxPos, expected: .expected}, nil}// Valid reports whether the whole input is derivable by the root rule.func ( *Forest) () bool { return .root != nil }// ParseError returns the furthest-failure diagnostic for an invalid forest:// where parsing got stuck and which terminals were expected there. It returns// nil when the forest is valid. The returned error unwraps to// [ErrNoSolutionFound].func ( *Forest) () *ParseError {if .Valid() {returnnil }returnnewParseError(.input, .maxPos, .expected)}// Nodes returns the number of forest nodes reachable from the root.func ( *Forest) () int {if .root == nil {return0 } := map[*gnode]bool{}varfunc( *gnode) = func( *gnode) {if [] {return } [] = truefor , := range .packs {for , := range .kids { () } } } (.root)returnlen()}// Ambiguous reports whether the input has more than one distinct parse tree.func ( *Forest) () bool {if .root == nil {returnfalse } := map[*gnode]bool{}varfunc( *gnode) bool = func( *gnode) bool {if [] {returnfalse } [] = trueiflen(.packs) > 1 {returntrue }for , := range .packs {for , := range .kids {if () {returntrue } } }returnfalse }return (.root)}// NumTrees returns the number of distinct parse trees the forest represents.// A result of -1 means infinitely many (a cycle in the forest, i.e. an// infinitely-ambiguous grammar such as A = A / "x").func ( *Forest) () *big.Int {if .root == nil {returnbig.NewInt(0) } := map[*gnode]*big.Int{} := map[*gnode]bool{} := falsevarfunc( *gnode) *big.Int = func( *gnode) *big.Int {if , := []; {return }if [] { = truereturnbig.NewInt(1) } [] = true := big.NewInt(0)iflen(.packs) == 0 { = big.NewInt(1) }for , := range .packs { := big.NewInt(1)for , := range .kids { .Mul(, ()) } .Add(, ) } [] = false [] = return } := (.root)if {returnbig.NewInt(-1) }return}// ParseTree is a concrete syntax tree keyed by grammar rules: rule nodes carry// the rule name, terminals are leaves with empty Rule.typeParseTreestruct { Rule string Start, End int Children []*ParseTree}// Tree extracts a single parse tree (first packing at each node), or nil if the// input is invalid. A visited guard keeps extraction finite on cyclic forests.func ( *Forest) () *ParseTree {if .root == nil {returnnil }return .emitSymbol(.root, map[*gnode]bool{})}func ( *Forest) ( *gnode, map[*gnode]bool) *ParseTree { := &ParseTree{Start: .Start, End: .End}if .kind == gSymbol && .nt >= 0 && .sg.nts[.nt].isRule { .Rule = .sg.nts[.nt].ruleName } [] = true .collect(, &.Children, )delete(, )return}func ( *Forest) ( *gnode, *[]*ParseTree, map[*gnode]bool) {iflen(.packs) == 0 {if .kind == gTerm && .End > .Start { * = append(*, &ParseTree{Start: .Start, End: .End}) }return }for , := range .packs[0].kids { .collectChild(, , ) }}func ( *Forest) ( *gnode, *[]*ParseTree, map[*gnode]bool) {switch {case .kind == gTerm:if .End > .Start { * = append(*, &ParseTree{Start: .Start, End: .End}) }case .kind == gSymbol && .nt >= 0 && .sg.nts[.nt].isRule:if [] { * = append(*, &ParseTree{Rule: .sg.nts[.nt].ruleName, Start: .Start, End: .End})return } * = append(*, .emitSymbol(, ))default:if [] {return } [] = true .collect(, , )delete(, ) }}
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.