904 lines
23 KiB
Go
904 lines
23 KiB
Go
package goabnf
|
|
|
|
import (
|
|
"fmt"
|
|
"go/format"
|
|
"strconv"
|
|
"strings"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// GenerateGoParserFromABNF is a convenience wrapper that parses ABNF grammar
|
|
// source and generates a specialised parser for it in one step. root is the rule
|
|
// the generated parser starts from; pkg is the package name of the emitted file.
|
|
// It is the natural entry point for a code-generation command (e.g. driven by
|
|
// `go generate`).
|
|
func GenerateGoParserFromABNF(abnfSource []byte, root, pkg string, opts ...ABNFOption) ([]byte, error) {
|
|
g, err := ParseABNF(abnfSource, opts...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse ABNF source: %w", err)
|
|
}
|
|
return GenerateGoParser(g, root, pkg)
|
|
}
|
|
|
|
// GenerateGoParser emits a standalone Go source file containing a parser
|
|
// SPECIALISED to grammar g rooted at root. Unlike a table-driven interpreter,
|
|
// the grammar is compiled into control flow:
|
|
//
|
|
// - the parse loop is a jump-table switch over slot IDs; each case is the
|
|
// straight-line code for that one slot (its symbol, its successor, its
|
|
// completion), so there is no per-step table lookup and no symbol-kind
|
|
// dispatch at runtime;
|
|
// - terminals are inlined as byte comparisons / rune decodes against baked
|
|
// literals (no ElemItf, no closure table);
|
|
// - nonterminal calls, completions, and the {min,max} repetition gating are
|
|
// baked as constants at each site;
|
|
// - only the genuinely grammar-independent machinery (GSS, descriptor
|
|
// worklist, BSR set) remains as fixed runtime, plus a compact metadata table
|
|
// used solely by the reconstruction queries (NumTrees/Ambiguous/Tree), which
|
|
// inherently need grammar structure.
|
|
//
|
|
// The output depends only on the standard library, is panic-free (input decoded
|
|
// via utf8, no manual indexing) and bounded (MaxElements aborts pathological
|
|
// inputs with ErrTooLarge). It is validated against ParseBSR via the differential
|
|
// harness. pkg is the package name for the emitted file.
|
|
func GenerateGoParser(g *Grammar, root, pkg string) ([]byte, error) {
|
|
sg, err := compileSlots(g, root, defaultMaxSlots)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gen := &codegen{sg: sg, root: root, pkg: pkg}
|
|
gen.assignSlots()
|
|
src := gen.emit()
|
|
formatted, ferr := format.Source([]byte(src))
|
|
if ferr != nil {
|
|
return []byte(src), fmt.Errorf("generated source failed to format: %w", ferr)
|
|
}
|
|
return formatted, nil
|
|
}
|
|
|
|
type sInfo struct {
|
|
nt, alt, dot, plen int
|
|
}
|
|
|
|
type codegen struct {
|
|
sg *slotGrammar
|
|
root string
|
|
pkg string
|
|
|
|
slots []sInfo // slot id -> (nt,alt,dot,prodLen)
|
|
idOf [][]int // nt,alt -> base slot id (dot 0); dot d == base+d
|
|
series []string
|
|
seriesIdx map[string]int
|
|
usesUTF8 bool // whether any emitted matcher references unicode/utf8
|
|
}
|
|
|
|
func (c *codegen) startID(nt, alt int) int { return c.idOf[nt][alt] }
|
|
func (c *codegen) compID(nt, alt int) int { return c.idOf[nt][alt] + len(c.sg.nts[nt].alts[alt]) }
|
|
|
|
// assignSlots numbers every slot (nt,alt,dot) with dots within a production
|
|
// consecutive, so the slot at dot d-1 is (id-1).
|
|
func (c *codegen) assignSlots() {
|
|
c.seriesIdx = map[string]int{}
|
|
c.idOf = make([][]int, len(c.sg.nts))
|
|
for nt, info := range c.sg.nts {
|
|
c.idOf[nt] = make([]int, len(info.alts))
|
|
for alt, prod := range info.alts {
|
|
c.idOf[nt][alt] = len(c.slots)
|
|
for dot := 0; dot <= len(prod); dot++ {
|
|
c.slots = append(c.slots, sInfo{nt, alt, dot, len(prod)})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (c *codegen) emit() string {
|
|
c.scanUTF8()
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "// Code generated by go-abnf for root %q. DO NOT EDIT.\n\n", c.root)
|
|
fmt.Fprintf(&b, "package %s\n\n", c.pkg)
|
|
c.emitImports(&b)
|
|
b.WriteString(headerBoilerplate)
|
|
c.emitProcess(&b)
|
|
c.emitSeed(&b)
|
|
c.emitMetadata(&b)
|
|
b.WriteString(queryBoilerplate)
|
|
c.emitSeriesVars(&b)
|
|
return b.String()
|
|
}
|
|
|
|
// scanUTF8 sets usesUTF8 if any terminal compiles to code that decodes runes
|
|
// (a num-val range, or a char-val with a non-ASCII rune).
|
|
func (c *codegen) scanUTF8() {
|
|
for _, nt := range c.sg.nts {
|
|
for _, prod := range nt.alts {
|
|
for _, s := range prod {
|
|
if s.kind != symTerm {
|
|
continue
|
|
}
|
|
switch v := s.term.(type) {
|
|
case ElemNumVal:
|
|
if v.Status == StatRange {
|
|
c.usesUTF8 = true
|
|
}
|
|
case ElemCharVal:
|
|
for _, r := range v.Values {
|
|
if r > 0x7f {
|
|
c.usesUTF8 = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (c *codegen) emitImports(b *strings.Builder) {
|
|
b.WriteString("import (\n\t\"errors\"\n\t\"math/big\"\n")
|
|
if c.usesUTF8 {
|
|
b.WriteString("\t\"unicode/utf8\"\n")
|
|
}
|
|
b.WriteString(")\n")
|
|
}
|
|
|
|
// emitProcess generates the specialised parse loop: a jump-table switch over
|
|
// slot ids, one case per slot.
|
|
func (c *codegen) emitProcess(b *strings.Builder) {
|
|
b.WriteString("\nfunc (p *parser) process(d desc) {\n")
|
|
b.WriteString("\tL, u, i, rc := d.L, d.u, d.i, d.rc\n")
|
|
b.WriteString("\t_ = rc\n")
|
|
b.WriteString("\tfor {\n\t\tswitch L {\n")
|
|
for id, s := range c.slots {
|
|
info := c.sg.nts[s.nt]
|
|
fmt.Fprintf(b, "\t\tcase %d: // %s\n", id, c.slotComment(s))
|
|
if s.dot == s.plen {
|
|
b.WriteString("\t\t\tp.pop(u, i)\n\t\t\treturn\n")
|
|
continue
|
|
}
|
|
sym := info.alts[s.alt][s.dot]
|
|
nextID := id + 1
|
|
switch sym.kind {
|
|
case symNonterm:
|
|
c.emitCall(b, s, sym.nt, nextID)
|
|
default:
|
|
c.emitTerminal(b, sym, nextID)
|
|
}
|
|
}
|
|
b.WriteString("\t\tdefault:\n\t\t\treturn\n")
|
|
b.WriteString("\t\t}\n\t}\n}\n")
|
|
}
|
|
|
|
func (c *codegen) emitCall(b *strings.Builder, s sInfo, callee, retID int) {
|
|
fmt.Fprintf(b, "\t\t\tv := p.create(%d, u, i, rc)\n", retID)
|
|
ci := c.sg.nts[callee]
|
|
if ci.isRep {
|
|
if callee == s.nt {
|
|
// self-recursion inside the rep's own loop: continue the chain.
|
|
if ci.repMax == inf {
|
|
fmt.Fprintf(b, "\t\t\tcrc := rc + 1\n\t\t\tif crc > %d {\n\t\t\t\tcrc = %d\n\t\t\t}\n", ci.repMin, ci.repMin)
|
|
} else {
|
|
b.WriteString("\t\t\tcrc := rc + 1\n")
|
|
}
|
|
fmt.Fprintf(b, "\t\t\tif crc >= %d {\n\t\t\t\tp.add(%d, v, i, crc)\n\t\t\t}\n", ci.repMin, c.startID(callee, 0))
|
|
if ci.repMax == inf {
|
|
fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, crc)\n", c.startID(callee, 1))
|
|
} else {
|
|
fmt.Fprintf(b, "\t\t\tif crc < %d {\n\t\t\t\tp.add(%d, v, i, crc)\n\t\t\t}\n", ci.repMax, c.startID(callee, 1))
|
|
}
|
|
} else {
|
|
// external call: fresh chain at count 0; gating decided at gen time.
|
|
if ci.repMin == 0 {
|
|
fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, 0)\n", c.startID(callee, 0))
|
|
}
|
|
if ci.repMax == inf || 0 < ci.repMax {
|
|
fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, 0)\n", c.startID(callee, 1))
|
|
}
|
|
}
|
|
} else {
|
|
for alt := range ci.alts {
|
|
fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, 0)\n", c.startID(callee, alt))
|
|
}
|
|
}
|
|
b.WriteString("\t\t\treturn\n")
|
|
}
|
|
|
|
func (c *codegen) emitTerminal(b *strings.Builder, sym ssym, nextID int) {
|
|
if sym.kind == symEps {
|
|
fmt.Fprintf(b, "\t\t\tp.record(%d, u.pos, i, i)\n", nextID)
|
|
fmt.Fprintf(b, "\t\t\tL = %d\n\t\t\tcontinue\n", nextID)
|
|
return
|
|
}
|
|
if !c.emitMatch(b, sym) {
|
|
// The terminal can never match (a prose-val, or a series carrying a
|
|
// non-Unicode value): emitMatch has emitted `return` and defined no j,
|
|
// so the success tail below would be unreachable and reference an
|
|
// undefined j ; we should stop here.
|
|
return
|
|
}
|
|
fmt.Fprintf(b, "\t\t\tp.record(%d, u.pos, i, j)\n", nextID)
|
|
fmt.Fprintf(b, "\t\t\ti = j\n\t\t\tL = %d\n\t\t\tcontinue\n", nextID)
|
|
}
|
|
|
|
// emitMatch emits inline code setting j to the end index on success or return on
|
|
// failure. It reports whether the terminal can match at all: a false result
|
|
// means it emitted only `return` and defined no j (prose-val, or a series with a
|
|
// non-Unicode value), so the caller must not emit the j-dependent success tail.
|
|
func (c *codegen) emitMatch(b *strings.Builder, s ssym) bool {
|
|
switch v := s.term.(type) {
|
|
case ElemCharVal:
|
|
c.emitCharVal(b, v)
|
|
return true
|
|
case ElemNumVal:
|
|
switch v.Status {
|
|
case StatRange:
|
|
lo := numvalToRune(v.Elems[0], v.Base)
|
|
hi := numvalToRune(v.Elems[1], v.Base)
|
|
b.WriteString("\t\t\tif i >= len(p.input) {\n\t\t\t\treturn\n\t\t\t}\n")
|
|
b.WriteString("\t\t\trv, rs := utf8.DecodeRune(p.input[i:])\n")
|
|
b.WriteString("\t\t\tif rv == utf8.RuneError && rs == 1 {\n\t\t\t\treturn\n\t\t\t}\n")
|
|
fmt.Fprintf(b, "\t\t\tif rv < %d || rv > %d {\n\t\t\t\treturn\n\t\t\t}\n", lo, hi)
|
|
b.WriteString("\t\t\tj := i + rs\n")
|
|
return true
|
|
case StatSeries:
|
|
return c.emitSeries(b, v)
|
|
default:
|
|
b.WriteString("\t\t\treturn\n")
|
|
return false
|
|
}
|
|
default: // prose-val: never matches
|
|
b.WriteString("\t\t\treturn\n")
|
|
return false
|
|
}
|
|
}
|
|
|
|
func (c *codegen) emitCharVal(b *strings.Builder, v ElemCharVal) {
|
|
allASCII := true
|
|
for _, r := range v.Values {
|
|
if r > 0x7f {
|
|
allASCII = false
|
|
break
|
|
}
|
|
}
|
|
if allASCII {
|
|
fmt.Fprintf(b, "\t\t\tif i+%d > len(p.input) {\n\t\t\t\treturn\n\t\t\t}\n", len(v.Values))
|
|
for off, r := range v.Values {
|
|
bb := byte(r)
|
|
if v.Sensitive {
|
|
fmt.Fprintf(b, "\t\t\tif p.input[i+%d] != %d {\n\t\t\t\treturn\n\t\t\t}\n", off, bb)
|
|
} else {
|
|
fmt.Fprintf(b, "\t\t\tif foldB(p.input[i+%d]) != %d {\n\t\t\t\treturn\n\t\t\t}\n", off, foldByte(bb))
|
|
}
|
|
}
|
|
fmt.Fprintf(b, "\t\t\tj := i + %d\n", len(v.Values))
|
|
return
|
|
}
|
|
// rare non-ASCII char-val: decode rune-by-rune.
|
|
b.WriteString("\t\t\tj := i\n")
|
|
for _, r := range v.Values {
|
|
b.WriteString("\t\t\t{\n")
|
|
b.WriteString("\t\t\t\tif j >= len(p.input) {\n\t\t\t\t\treturn\n\t\t\t\t}\n")
|
|
b.WriteString("\t\t\t\trv, rs := utf8.DecodeRune(p.input[j:])\n")
|
|
b.WriteString("\t\t\t\tif rv == utf8.RuneError && rs == 1 {\n\t\t\t\t\treturn\n\t\t\t\t}\n")
|
|
if v.Sensitive {
|
|
fmt.Fprintf(b, "\t\t\t\tif rv != %d {\n\t\t\t\t\treturn\n\t\t\t\t}\n", r)
|
|
} else {
|
|
fmt.Fprintf(b, "\t\t\t\tif foldR(rv) != %d {\n\t\t\t\t\treturn\n\t\t\t\t}\n", foldRune(r))
|
|
}
|
|
b.WriteString("\t\t\t\tj += rs\n\t\t\t}\n")
|
|
}
|
|
}
|
|
|
|
func (c *codegen) emitSeries(b *strings.Builder, v ElemNumVal) bool {
|
|
var sb strings.Builder
|
|
for _, e := range v.Elems {
|
|
r := numvalToRune(e, v.Base)
|
|
if !utf8.ValidRune(r) {
|
|
b.WriteString("\t\t\treturn // series contains a non-Unicode value\n")
|
|
return false
|
|
}
|
|
sb.WriteRune(r)
|
|
}
|
|
idx := c.seriesVar([]byte(sb.String()))
|
|
fmt.Fprintf(b, "\t\t\tif i+len(series%d) > len(p.input) || !bytesEqual(p.input[i:i+len(series%d)], series%d) {\n\t\t\t\treturn\n\t\t\t}\n", idx, idx, idx)
|
|
fmt.Fprintf(b, "\t\t\tj := i + len(series%d)\n", idx)
|
|
return true
|
|
}
|
|
|
|
func (c *codegen) seriesVar(bs []byte) int {
|
|
key := string(bs)
|
|
if i, ok := c.seriesIdx[key]; ok {
|
|
return i
|
|
}
|
|
i := len(c.series)
|
|
c.seriesIdx[key] = i
|
|
parts := make([]string, len(bs))
|
|
for k, x := range bs {
|
|
parts[k] = strconv.Itoa(int(x))
|
|
}
|
|
c.series = append(c.series, "[]byte{"+strings.Join(parts, ", ")+"}")
|
|
return i
|
|
}
|
|
|
|
func (c *codegen) emitSeed(b *strings.Builder) {
|
|
b.WriteString("\nfunc (p *parser) seed() {\n")
|
|
for alt := range c.sg.nts[c.sg.start].alts {
|
|
fmt.Fprintf(b, "\tp.add(%d, p.u0, 0, 0)\n", c.startID(c.sg.start, alt))
|
|
}
|
|
b.WriteString("}\n")
|
|
}
|
|
|
|
func (c *codegen) emitMetadata(b *strings.Builder) {
|
|
b.WriteString("\n// ---- baked metadata (reconstruction queries only) ----\n\n")
|
|
fmt.Fprintf(b, "const gRootName = %q\n", c.root)
|
|
fmt.Fprintf(b, "const gStart = %d\n\n", c.sg.start)
|
|
|
|
b.WriteString("var slotInfo = []sInfo{\n")
|
|
for _, s := range c.slots {
|
|
fmt.Fprintf(b, "\t{%d, %d, %d, %d},\n", s.nt, s.alt, s.dot, s.plen)
|
|
}
|
|
b.WriteString("}\n\n")
|
|
|
|
b.WriteString("var ntComplete = [][]int{\n")
|
|
for nt := range c.sg.nts {
|
|
b.WriteString("\t{")
|
|
for alt := range c.sg.nts[nt].alts {
|
|
if alt > 0 {
|
|
b.WriteString(", ")
|
|
}
|
|
fmt.Fprintf(b, "%d", c.compID(nt, alt))
|
|
}
|
|
b.WriteString("},\n")
|
|
}
|
|
b.WriteString("}\n\n")
|
|
|
|
b.WriteString("var qNTs = []qNT{\n")
|
|
for _, nt := range c.sg.nts {
|
|
fmt.Fprintf(b, "\t{isRule: %v, ruleName: %q, alts: ", nt.isRule, nt.ruleName)
|
|
if len(nt.alts) == 0 {
|
|
b.WriteString("nil},\n")
|
|
continue
|
|
}
|
|
b.WriteString("[][]qSym{")
|
|
for ai, prod := range nt.alts {
|
|
if ai > 0 {
|
|
b.WriteString(", ")
|
|
}
|
|
b.WriteString("{")
|
|
for si, sym := range prod {
|
|
if si > 0 {
|
|
b.WriteString(", ")
|
|
}
|
|
switch sym.kind {
|
|
case symNonterm:
|
|
fmt.Fprintf(b, "{kind: kNT, nt: %d}", sym.nt)
|
|
case symEps:
|
|
b.WriteString("{kind: kEps}")
|
|
default:
|
|
b.WriteString("{kind: kTerm}")
|
|
}
|
|
}
|
|
b.WriteString("}")
|
|
}
|
|
b.WriteString("}},\n")
|
|
}
|
|
b.WriteString("}\n")
|
|
}
|
|
|
|
func (c *codegen) emitSeriesVars(b *strings.Builder) {
|
|
if len(c.series) == 0 {
|
|
return
|
|
}
|
|
b.WriteString("\n// ---- baked series literals ----\n")
|
|
for i, s := range c.series {
|
|
fmt.Fprintf(b, "var series%d = %s\n", i, s)
|
|
}
|
|
}
|
|
|
|
func (c *codegen) slotComment(s sInfo) string {
|
|
nt := c.sg.nts[s.nt]
|
|
name := nt.ruleName
|
|
if name == "" {
|
|
name = nt.label
|
|
}
|
|
prod := nt.alts[s.alt]
|
|
parts := make([]string, 0, len(prod)+1)
|
|
for d, sym := range prod {
|
|
if d == s.dot {
|
|
parts = append(parts, ".")
|
|
}
|
|
parts = append(parts, symStr(c.sg, sym))
|
|
}
|
|
if s.dot == len(prod) {
|
|
parts = append(parts, ".")
|
|
}
|
|
return strings.TrimSpace(name+" ::= "+strings.Join(parts, " ")) +
|
|
fmt.Sprintf(" (%d,%d,%d)", s.nt, s.alt, s.dot)
|
|
}
|
|
|
|
func symStr(sg *slotGrammar, s ssym) string {
|
|
switch s.kind {
|
|
case symNonterm:
|
|
n := sg.nts[s.nt]
|
|
if n.ruleName != "" {
|
|
return n.ruleName
|
|
}
|
|
if n.label != "" {
|
|
return n.label
|
|
}
|
|
return "nt" + strconv.Itoa(s.nt)
|
|
case symEps:
|
|
return "eps"
|
|
default:
|
|
if s.term != nil {
|
|
return sanitizeComment(s.term.String())
|
|
}
|
|
return "?"
|
|
}
|
|
}
|
|
|
|
func sanitizeComment(s string) string {
|
|
s = strings.ReplaceAll(s, "*/", "* /")
|
|
s = strings.ReplaceAll(s, "\r", " ")
|
|
s = strings.ReplaceAll(s, "\n", " ")
|
|
return s
|
|
}
|
|
|
|
func foldByte(b byte) byte {
|
|
if b >= 'A' && b <= 'Z' {
|
|
return b - 'A' + 'a'
|
|
}
|
|
return b
|
|
}
|
|
|
|
func foldRune(r rune) rune {
|
|
if r >= 'A' && r <= 'Z' {
|
|
return r - 'A' + 'a'
|
|
}
|
|
return r
|
|
}
|
|
|
|
// headerBoilerplate: runtime types, GSS/BSR engine state. Grammar-independent.
|
|
// (Imports are emitted separately so unicode/utf8 is only pulled in when a
|
|
// terminal actually decodes runes.) The generated process()/seed() and metadata
|
|
// complete the file.
|
|
const headerBoilerplate = `
|
|
// MaxElements bounds the BSR set; parsing aborts with ErrTooLarge beyond it.
|
|
// Set to 0 to disable the bound.
|
|
var MaxElements = 1 << 22
|
|
|
|
// ErrTooLarge is returned when the BSR set exceeds MaxElements.
|
|
var ErrTooLarge = errors.New("parse: BSR set exceeded MaxElements")
|
|
|
|
const inf = -1
|
|
|
|
const (
|
|
kNT = 0
|
|
kTerm = 1
|
|
kEps = 2
|
|
)
|
|
|
|
// sInfo decodes a slot id into (nonterminal, alternate, dot, production length).
|
|
type sInfo struct{ nt, alt, dot, plen int }
|
|
|
|
// qSym is a query-only symbol descriptor (kind, and nt for nonterminals).
|
|
type qSym struct{ kind, nt int }
|
|
|
|
// qNT is query-only nonterminal metadata.
|
|
type qNT struct {
|
|
isRule bool
|
|
ruleName string
|
|
alts [][]qSym
|
|
}
|
|
|
|
type bsrElem struct {
|
|
sl int
|
|
l, k, r int
|
|
}
|
|
|
|
type gssKey struct {
|
|
ret int
|
|
pos int
|
|
rc int
|
|
}
|
|
|
|
type gnode struct {
|
|
ret int
|
|
pos int
|
|
rc int
|
|
edges []*gnode
|
|
edgeSet map[*gnode]bool
|
|
}
|
|
|
|
type desc struct {
|
|
L, i, rc int
|
|
u *gnode
|
|
}
|
|
|
|
type parser struct {
|
|
input []byte
|
|
set map[bsrElem]bool
|
|
gss map[gssKey]*gnode
|
|
u0 *gnode
|
|
seen map[desc]bool
|
|
work []desc
|
|
popped map[*gnode]map[int]bool
|
|
aborted bool
|
|
}
|
|
|
|
func foldB(b byte) byte {
|
|
if b >= 'A' && b <= 'Z' {
|
|
return b - 'A' + 'a'
|
|
}
|
|
return b
|
|
}
|
|
|
|
func foldR(r rune) rune {
|
|
if r >= 'A' && r <= 'Z' {
|
|
return r - 'A' + 'a'
|
|
}
|
|
return r
|
|
}
|
|
|
|
func bytesEqual(a, b []byte) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
for i := range a {
|
|
if a[i] != b[i] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (p *parser) add(L int, u *gnode, i, rc int) {
|
|
d := desc{L: L, i: i, rc: rc, u: u}
|
|
if p.seen[d] {
|
|
return
|
|
}
|
|
p.seen[d] = true
|
|
p.work = append(p.work, d)
|
|
}
|
|
|
|
func (p *parser) gssNodeFor(ret, pos, rc int) *gnode {
|
|
k := gssKey{ret, pos, rc}
|
|
if v, ok := p.gss[k]; ok {
|
|
return v
|
|
}
|
|
v := &gnode{ret: ret, pos: pos, rc: rc, edgeSet: map[*gnode]bool{}}
|
|
p.gss[k] = v
|
|
return v
|
|
}
|
|
|
|
// record inserts a BSR element, keeping only intermediate (prefix length >= 2)
|
|
// or complete (dot == len) extents.
|
|
func (p *parser) record(L, l, k, r int) {
|
|
si := slotInfo[L]
|
|
if si.dot >= 2 || si.dot == si.plen {
|
|
if MaxElements > 0 && len(p.set) >= MaxElements {
|
|
p.aborted = true
|
|
return
|
|
}
|
|
p.set[bsrElem{L, l, k, r}] = true
|
|
}
|
|
}
|
|
|
|
func (p *parser) create(ret int, u *gnode, i, rc int) *gnode {
|
|
v := p.gssNodeFor(ret, i, rc)
|
|
if !v.edgeSet[u] {
|
|
v.edgeSet[u] = true
|
|
v.edges = append(v.edges, u)
|
|
for j := range p.popped[v] {
|
|
p.record(ret, u.pos, i, j)
|
|
p.add(ret, u, j, rc)
|
|
}
|
|
}
|
|
return v
|
|
}
|
|
|
|
func (p *parser) pop(u *gnode, j int) {
|
|
if u == p.u0 {
|
|
return
|
|
}
|
|
if p.popped[u] == nil {
|
|
p.popped[u] = map[int]bool{}
|
|
}
|
|
p.popped[u][j] = true
|
|
for _, v := range u.edges {
|
|
p.record(u.ret, v.pos, u.pos, j)
|
|
p.add(u.ret, v, j, u.rc)
|
|
}
|
|
}
|
|
`
|
|
|
|
// queryBoilerplate: Result, reconstruction queries (over slotInfo/ntComplete/
|
|
// qNTs), and the public Parse. Grammar-independent.
|
|
const queryBoilerplate = `
|
|
// ---- result + reconstruction queries ----
|
|
|
|
type ParseTree struct {
|
|
Rule string
|
|
Start, End int
|
|
Children []*ParseTree
|
|
}
|
|
|
|
type bsrKey struct {
|
|
sl int
|
|
l, r int
|
|
}
|
|
|
|
type nodeID struct {
|
|
sl int // slot id for intermediate nodes; -1 for symbol nodes
|
|
nt int // nonterminal id for symbol nodes
|
|
l, r int
|
|
}
|
|
|
|
// Result holds the BSR set for a parse and answers queries over it.
|
|
type Result struct {
|
|
input []byte
|
|
set map[bsrElem]bool
|
|
index map[bsrKey][]int
|
|
n int
|
|
}
|
|
|
|
func (r *Result) buildIndex() {
|
|
if r.index != nil {
|
|
return
|
|
}
|
|
r.index = make(map[bsrKey][]int, len(r.set))
|
|
for e := range r.set {
|
|
bk := bsrKey{e.sl, e.l, e.r}
|
|
r.index[bk] = append(r.index[bk], e.k)
|
|
}
|
|
}
|
|
|
|
// Valid reports whether the whole input is derivable by the root rule.
|
|
func (r *Result) Valid() bool {
|
|
r.buildIndex()
|
|
for _, sl := range ntComplete[gStart] {
|
|
if len(r.index[bsrKey{sl, 0, r.n}]) > 0 {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Elements returns the number of BSR elements (representation size).
|
|
func (r *Result) Elements() int { return len(r.set) }
|
|
|
|
// NumTrees returns the number of distinct parse trees, or -1 for infinitely many.
|
|
func (r *Result) NumTrees() *big.Int {
|
|
if !r.Valid() {
|
|
return big.NewInt(0)
|
|
}
|
|
memo := map[nodeID]*big.Int{}
|
|
onStack := map[nodeID]bool{}
|
|
infinite := false
|
|
|
|
var symWays func(s qSym, a, b int) *big.Int
|
|
var countSym func(nt, l, rr int) *big.Int
|
|
var countInter func(sl, l, rr int) *big.Int
|
|
var countElem func(sl, l, k, rr int) *big.Int
|
|
|
|
symWays = func(s qSym, a, b int) *big.Int {
|
|
if s.kind == kNT {
|
|
return countSym(s.nt, a, b)
|
|
}
|
|
return big.NewInt(1)
|
|
}
|
|
countElem = func(sl, l, k, rr int) *big.Int {
|
|
si := slotInfo[sl]
|
|
prod := qNTs[si.nt].alts[si.alt]
|
|
last := symWays(prod[si.dot-1], k, rr)
|
|
var pre *big.Int
|
|
switch {
|
|
case si.dot == 1:
|
|
pre = big.NewInt(1)
|
|
case si.dot == 2:
|
|
pre = symWays(prod[0], l, k)
|
|
default:
|
|
pre = countInter(sl-1, l, k)
|
|
}
|
|
return new(big.Int).Mul(pre, last)
|
|
}
|
|
countInter = func(sl, l, rr int) *big.Int {
|
|
id := nodeID{sl: sl, nt: -1, l: l, r: rr}
|
|
if v, ok := memo[id]; ok {
|
|
return v
|
|
}
|
|
if onStack[id] {
|
|
infinite = true
|
|
return big.NewInt(1)
|
|
}
|
|
onStack[id] = true
|
|
total := big.NewInt(0)
|
|
for _, k := range r.index[bsrKey{sl, l, rr}] {
|
|
total.Add(total, countElem(sl, l, k, rr))
|
|
}
|
|
onStack[id] = false
|
|
memo[id] = total
|
|
return total
|
|
}
|
|
countSym = func(nt, l, rr int) *big.Int {
|
|
id := nodeID{sl: -1, nt: nt, l: l, r: rr}
|
|
if v, ok := memo[id]; ok {
|
|
return v
|
|
}
|
|
if onStack[id] {
|
|
infinite = true
|
|
return big.NewInt(1)
|
|
}
|
|
onStack[id] = true
|
|
total := big.NewInt(0)
|
|
for _, sl := range ntComplete[nt] {
|
|
for _, k := range r.index[bsrKey{sl, l, rr}] {
|
|
total.Add(total, countElem(sl, l, k, rr))
|
|
}
|
|
}
|
|
onStack[id] = false
|
|
memo[id] = total
|
|
return total
|
|
}
|
|
res := countSym(gStart, 0, r.n)
|
|
if infinite {
|
|
return big.NewInt(-1)
|
|
}
|
|
return res
|
|
}
|
|
|
|
// Ambiguous reports whether the input has more than one distinct parse tree.
|
|
func (r *Result) Ambiguous() bool {
|
|
if !r.Valid() {
|
|
return false
|
|
}
|
|
visited := map[nodeID]bool{}
|
|
var symAmb func(nt, l, rr int) bool
|
|
var interAmb func(sl, l, rr int) bool
|
|
var elemAmb func(sl, l, k, rr int) bool
|
|
var symOf func(s qSym, a, b int) bool
|
|
symOf = func(s qSym, a, b int) bool {
|
|
if s.kind == kNT {
|
|
return symAmb(s.nt, a, b)
|
|
}
|
|
return false
|
|
}
|
|
elemAmb = func(sl, l, k, rr int) bool {
|
|
si := slotInfo[sl]
|
|
prod := qNTs[si.nt].alts[si.alt]
|
|
if symOf(prod[si.dot-1], k, rr) {
|
|
return true
|
|
}
|
|
switch {
|
|
case si.dot == 1:
|
|
return false
|
|
case si.dot == 2:
|
|
return symOf(prod[0], l, k)
|
|
default:
|
|
return interAmb(sl-1, l, k)
|
|
}
|
|
}
|
|
interAmb = func(sl, l, rr int) bool {
|
|
id := nodeID{sl: sl, nt: -1, l: l, r: rr}
|
|
if visited[id] {
|
|
return false
|
|
}
|
|
visited[id] = true
|
|
ks := r.index[bsrKey{sl, l, rr}]
|
|
if len(ks) > 1 {
|
|
return true
|
|
}
|
|
for _, k := range ks {
|
|
if elemAmb(sl, l, k, rr) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
symAmb = func(nt, l, rr int) bool {
|
|
id := nodeID{sl: -1, nt: nt, l: l, r: rr}
|
|
if visited[id] {
|
|
return false
|
|
}
|
|
visited[id] = true
|
|
packs := 0
|
|
for _, sl := range ntComplete[nt] {
|
|
packs += len(r.index[bsrKey{sl, l, rr}])
|
|
}
|
|
if packs > 1 {
|
|
return true
|
|
}
|
|
for _, sl := range ntComplete[nt] {
|
|
for _, k := range r.index[bsrKey{sl, l, rr}] {
|
|
if elemAmb(sl, l, k, rr) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
return symAmb(gStart, 0, r.n)
|
|
}
|
|
|
|
// Tree extracts a single parse tree (first element at each extent), or nil if
|
|
// the input is invalid. Synthetic nonterminals are collapsed to rule names.
|
|
func (r *Result) Tree() *ParseTree {
|
|
if !r.Valid() {
|
|
return nil
|
|
}
|
|
for _, sl := range ntComplete[gStart] {
|
|
if ks := r.index[bsrKey{sl, 0, r.n}]; len(ks) > 0 {
|
|
var kids []*ParseTree
|
|
r.collectElem(sl, 0, ks[0], r.n, &kids, map[nodeID]bool{})
|
|
return &ParseTree{Rule: qNTs[gStart].ruleName, Start: 0, End: r.n, Children: kids}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *Result) collectElem(sl, l, k, rr int, out *[]*ParseTree, visited map[nodeID]bool) {
|
|
si := slotInfo[sl]
|
|
prod := qNTs[si.nt].alts[si.alt]
|
|
switch {
|
|
case si.dot == 1:
|
|
case si.dot == 2:
|
|
r.collectChild(prod[0], l, k, out, visited)
|
|
default:
|
|
if ks := r.index[bsrKey{sl - 1, l, k}]; len(ks) > 0 {
|
|
r.collectElem(sl-1, l, ks[0], k, out, visited)
|
|
}
|
|
}
|
|
r.collectChild(prod[si.dot-1], k, rr, out, visited)
|
|
}
|
|
|
|
func (r *Result) collectChild(s qSym, a, b int, out *[]*ParseTree, visited map[nodeID]bool) {
|
|
if s.kind != kNT {
|
|
if s.kind == kEps {
|
|
return
|
|
}
|
|
*out = append(*out, &ParseTree{Start: a, End: b})
|
|
return
|
|
}
|
|
id := nodeID{sl: -1, nt: s.nt, l: a, r: b}
|
|
if visited[id] {
|
|
return
|
|
}
|
|
visited[id] = true
|
|
for _, sl := range ntComplete[s.nt] {
|
|
if ks := r.index[bsrKey{sl, a, b}]; len(ks) > 0 {
|
|
if qNTs[s.nt].isRule {
|
|
var kids []*ParseTree
|
|
r.collectElem(sl, a, ks[0], b, &kids, visited)
|
|
*out = append(*out, &ParseTree{Rule: qNTs[s.nt].ruleName, Start: a, End: b, Children: kids})
|
|
} else {
|
|
r.collectElem(sl, a, ks[0], b, out, visited)
|
|
}
|
|
visited[id] = false
|
|
return
|
|
}
|
|
}
|
|
visited[id] = false
|
|
}
|
|
|
|
// Parse parses input under the baked root rule using the specialised engine.
|
|
func Parse(input []byte) (*Result, error) {
|
|
p := &parser{
|
|
input: input,
|
|
set: map[bsrElem]bool{},
|
|
gss: map[gssKey]*gnode{},
|
|
seen: map[desc]bool{},
|
|
popped: map[*gnode]map[int]bool{},
|
|
}
|
|
p.u0 = &gnode{ret: -1, edgeSet: map[*gnode]bool{}}
|
|
p.seed()
|
|
for len(p.work) > 0 {
|
|
if p.aborted {
|
|
return nil, ErrTooLarge
|
|
}
|
|
d := p.work[len(p.work)-1]
|
|
p.work = p.work[:len(p.work)-1]
|
|
p.process(d)
|
|
}
|
|
return &Result{input: input, set: p.set, n: len(input)}, nil
|
|
}
|
|
`
|