Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+210
-283
@@ -1,79 +1,56 @@
|
||||
/* gbnf_mask.cpp -- the token mask, precomputed per grammar so that no mask walks the vocabulary.
|
||||
*
|
||||
* THE COST OF A MASK IS ON THE STEP. fill_mask runs on the scheduler thread with the rank threads
|
||||
* parked at the barrier, so whatever it takes is added to the decode step of a constrained
|
||||
* request -- up to four times a step under speculation. A mask that descends the whole vocabulary
|
||||
* trie for a state it has not seen costs milliseconds on a quarter-million-piece vocabulary, and a
|
||||
* tool call reaches dozens of such states in its first steps. So nothing here descends the whole
|
||||
* vocabulary at run time: the grammar's compile does that, once per place a mask can start, and a
|
||||
* mask is assembled from the answers.
|
||||
* A mask's cost adds to the decode step (gbnf.h, "Cost"). Descending the whole vocabulary trie for
|
||||
* a new state costs milliseconds on a quarter-million-piece vocabulary, so only the compile does
|
||||
* that, once per place a mask can start; a mask is assembled from the answers.
|
||||
*
|
||||
* WHAT A MASK IS MADE OF. The state is a set of stacks, and a token is admissible iff SOME stack
|
||||
* admits it, so the mask is the union of one mask per stack. A stack's mask depends on its whole
|
||||
* contents in principle and on very little of them in practice: a token of a dozen characters
|
||||
* either stays inside the few frames nearest the top -- a string's content and its closing
|
||||
* quote, a free-text parameter and its end tag -- or leaves them through a delimiter. So a stack
|
||||
* S is split into a KEY, the frames nearest its top, and the CONTEXT below them:
|
||||
* Mask structure. A token is admissible iff some stack admits it, so the mask is the union of
|
||||
* per-stack masks. A short token either stays within the few frames nearest the top (a string's
|
||||
* content and closing quote, a free-text parameter and its end tag) or leaves them through a
|
||||
* delimiter. So a stack S is split into a key (the frames nearest the top) and the context below:
|
||||
*
|
||||
* S = context ++ key
|
||||
* mask(S) = accepted(key) U { t : t leaves the key after a prefix u, and the rest of
|
||||
* t is admitted by the context }
|
||||
*
|
||||
* accepted(key) does not depend on the context at all -- every path through the key's own frames
|
||||
* is a path through S -- so it is computed at compile time, by descending the vocabulary trie
|
||||
* with the key alone and an explicit bottom marker under it. What leaves the key is the
|
||||
* REMAINDER: for every token, the text after each point where it pops the key's last frame. Those
|
||||
* are kept as a small trie of their own, and at run time only that trie is walked, against the
|
||||
* real context. This is XGrammar's adaptive token mask cache (Dong et al., 2024) -- tokens split
|
||||
* into accepted, rejected and context-dependent per grammar position, with only the last checked
|
||||
* at run time -- carried over to a machine whose positions are stack SUFFIXES.
|
||||
* accepted(key) is independent of the context, so it is computed at compile time by descending
|
||||
* the vocabulary trie with the key over a bottom marker. The remainder (for every token, the text
|
||||
* after each point where it pops the key's last frame) is kept as a small trie, and only that is
|
||||
* walked at run time against the real context. This is XGrammar's adaptive token mask cache
|
||||
* (Dong et al., 2024), with stack suffixes as positions.
|
||||
*
|
||||
* WHY SUFFIXES AND NOT SINGLE ELEMENTS. The parser rewrites `x*` into a rule of its own and a
|
||||
* group into another, so the element on top of a stack is usually the one character class of a
|
||||
* one-element rule: `[^"\\]` inside a JSON string is the whole of its rule, and every token longer
|
||||
* than one character leaves it. Keyed on the top element alone, nearly the whole vocabulary would
|
||||
* be context-dependent at the positions that matter most. Keyed on the top three frames -- the
|
||||
* class, the repetition that loops over it and the closing quote below that -- the only tokens that
|
||||
* leave are the ones that close the string and keep going, a few hundred of them. The depth is
|
||||
* ADAPTIVE: a key is extended one frame down, into every frame that can sit below it, for as long
|
||||
* as its remainder is too large to walk on the step, and not otherwise.
|
||||
* Suffixes, not single elements. The parser gives `x*` and groups rules of their own, so a stack
|
||||
* top is often a one-element rule such as `[^"\\]` in a JSON string, which every multi-character
|
||||
* token leaves. Keyed on the top three frames (the class, its repetition, the closing quote) only
|
||||
* the few hundred tokens that close the string leave. Depth is adaptive: a key is extended one
|
||||
* frame down, into every frame that can sit below it, while its remainder is too large to walk.
|
||||
*
|
||||
* WHAT A KEY IS. Stack entries are element pointers, and two entries at different places in the
|
||||
* rules behave identically when what remains of their alternatives is the same sequence of
|
||||
* elements -- `"</parameter>\n"` closes every parameter of every tool, and its entries differ only
|
||||
* by address. Entries are therefore replaced by their CLASS, the hash-consed remainder of their
|
||||
* alternative, and keys are sequences of classes. Rules are hash-consed the same way first, so a
|
||||
* clause a template writes once per tool is one clause; and a repetition longer than the longest
|
||||
* token is one class whatever its count, because no token can tell the difference. A grammar of
|
||||
* fifty free-text parameters has one free-text key, not fifty, and `x{0,1000}` costs what
|
||||
* `x{0,128}` does on a vocabulary whose longest token is 128 characters.
|
||||
* Keys. Two stack entries behave identically when the rest of their alternatives is the same
|
||||
* element sequence (`"</parameter>\n"` closes every tool parameter). Entries are replaced by their
|
||||
* class, the hash-consed remainder of their alternative, and keys are class sequences. Rules are
|
||||
* hash-consed first, and a repetition longer than the longest token is one class whatever its
|
||||
* count. So fifty free-text parameters share one key, and `x{0,1000}` costs what `x{0,128}` does
|
||||
* when the longest token is 128 characters.
|
||||
*
|
||||
* WHAT A MASK THEN COSTS. For each stack: a lookup of its key, a few class comparisons deep; the
|
||||
* key's accepted set OR'ed in, which is a word-wise OR for a permissive key and a handful of bits
|
||||
* for a restrictive one; and, where the key has a remainder and the stack has a context, a walk of
|
||||
* the remainder trie from the context's state, which visits only the remainders the context keeps
|
||||
* alive. Nothing is proportional to the vocabulary except the OR, and nothing depends on whether
|
||||
* this state was seen before.
|
||||
* Mask cost. Per stack: a key lookup a few classes deep; an OR of the key's accepted set (word-wise
|
||||
* for a permissive key, a few bits for a restrictive one); and, if the key has a remainder and the
|
||||
* stack a context, a remainder-trie walk visiting only what the context keeps alive. Only the OR
|
||||
* scales with the vocabulary, and the cost is the same for new and seen states.
|
||||
*
|
||||
* A STATE CARRYING A SPLIT CHARACTER is the one exception to the plan, because what a token means
|
||||
* depends on the bytes carried in: only tokens that begin with the bytes that finish the
|
||||
* character are admissible at all. Those are a few hundred pieces in a byte-level vocabulary, kept
|
||||
* in a trie of their own per number of missing bytes, and walked with the full stack set.
|
||||
* Split characters. A state carrying a partial UTF-8 character admits only tokens that begin with
|
||||
* the missing bytes. Those few hundred pieces are kept in a trie per missing-byte count and walked
|
||||
* with the full stack set.
|
||||
*
|
||||
* THE AUTOMATON. Every walk here steps a set of stacks over code points. The successor of a set
|
||||
* depends only on WHICH of its stacks match the code point, and a set's character classes cut the
|
||||
* code points into a few intervals on which that answer is constant; so each state carries its
|
||||
* interval boundaries and the successor per interval, built on first use. A trie node's children
|
||||
* are sorted by code point, so the walk takes a whole run of children per interval -- an interval
|
||||
* no stack matches is skipped with one binary search, which is what makes a restrictive state
|
||||
* cost nothing at the vocabulary's widest node.
|
||||
* The automaton. A set's successor depends only on which of its stacks match the code point, and
|
||||
* its character classes cut the code points into intervals where that is constant; each state
|
||||
* stores its intervals and per-interval successor, built on first use. Trie children are sorted by
|
||||
* code point, so a walk takes a run of children per interval and skips a non-matching interval
|
||||
* with one binary search, making a restrictive state cheap even at the widest node.
|
||||
*
|
||||
* WHAT IS REFUSED. A grammar whose keys cannot be made small within kMaxKeyDepth frames -- one
|
||||
* where how much a token may take depends on how deep the parse is, without bound -- or whose
|
||||
* plan outgrows kMaxCompileWork, kMaxPlanBytes or the bound on one stack set, is refused when it
|
||||
* is compiled, naming the rule where it can: the alternative would be masks that are slow for as
|
||||
* long as the grammar is in use. What is refused is ambiguity and unbounded context, which the
|
||||
* grammars chat templates and the JSON-schema converter write do not have.
|
||||
* Refusal. A grammar whose keys cannot be made small within kMaxKeyDepth frames (token reach
|
||||
* depends on unbounded parse depth), or whose plan exceeds kMaxCompileWork, kMaxPlanBytes or the
|
||||
* stack-set bound, is refused at compile time, naming the rule where possible, rather than served
|
||||
* with slow masks. Grammars from chat templates and the JSON Schema converter are not affected.
|
||||
*/
|
||||
#include "gbnf_internal.h"
|
||||
|
||||
@@ -92,22 +69,20 @@ namespace {
|
||||
constexpr uint32_t kNone = 0xFFFFFFFFu;
|
||||
constexpr int32_t kUnbuilt = -2;
|
||||
|
||||
/* HOW LARGE A KEY'S REMAINDER MAY BE, which is what the run-time half of a mask may cost for one
|
||||
* key: a remainder trie is walked from the context's state, and in the worst case -- a context
|
||||
* that admits every remainder -- visits every node of it. Past either bound the key is extended
|
||||
* one frame down instead, where more of what leaves it is decided at compile time. */
|
||||
/* Maximum size of a key's remainder, which bounds a mask's run-time cost per key: the remainder
|
||||
* trie walk visits every node in the worst case. Past either bound the key is extended one frame
|
||||
* down, so more is decided at compile time. */
|
||||
constexpr size_t kMaxRemEntries = 1u << 13;
|
||||
constexpr size_t kMaxRemNodes = 1u << 13;
|
||||
|
||||
/* A walk whose remainder is already far past the bound is stopped where it is: the key will be
|
||||
* extended whatever the rest of the walk finds, and a key that leaves after its first character
|
||||
* would otherwise walk the whole vocabulary to learn that. Counted as tokens under the nodes where
|
||||
* the key has been left, so it is an overestimate and never stops a walk that could have fitted. */
|
||||
/* A walk whose remainder is already far past the bound stops early, since the key will be extended
|
||||
* anyway (otherwise a key left after one character walks the whole vocabulary). Counted as tokens
|
||||
* under nodes where the key was left, an overestimate, so it never stops a walk that would fit. */
|
||||
constexpr uint64_t kAbortRemTokens = 1u << 15;
|
||||
|
||||
/* How many frames a key may span. Real grammars settle within three or four: a string inside its
|
||||
* repetition inside its quotes, a whitespace run inside its optional. A key still too permissive
|
||||
* this deep is a grammar whose masks depend on unbounded stack context, which is refused. */
|
||||
/* Maximum frames per key. Real grammars settle within three or four (a string in its repetition in
|
||||
* its quotes; whitespace in its optional). A key still too permissive this deep means masks depend
|
||||
* on unbounded stack context, and the grammar is refused. */
|
||||
constexpr uint16_t kMaxKeyDepth = 12;
|
||||
|
||||
inline void set_bit(uint32_t* bits, int32_t id) {
|
||||
@@ -127,26 +102,22 @@ double ms_since(std::chrono::steady_clock::time_point t0) {
|
||||
|
||||
/* ============================================================ token tries
|
||||
|
||||
* A trie over code-point sequences, one terminal per token. The vocabulary is one; each key's
|
||||
* remainder is another; the pieces that resume a split character are three more.
|
||||
* A trie over code-point sequences, one terminal per token: one for the vocabulary, one per key
|
||||
* remainder, and three for pieces that resume a split character.
|
||||
*
|
||||
* Nodes are in BREADTH-FIRST order, which buys two things: a node's children occupy a CONTIGUOUS
|
||||
* id range, so an edge scan is a sequential read and no child pointers are stored; and a whole
|
||||
* level is contiguous, so a walk -- which is also breadth-first -- reads the node array front to
|
||||
* back. ONE STRUCT PER NODE AND NOT FOUR ARRAYS, because a visit reads all four fields; and the
|
||||
* terminals are held in NODE ORDER, so a level's terminals are read in increasing order too. The
|
||||
* walk is bound on how it touches memory rather than on work per node, and a pointer-linked
|
||||
* layout is slower than the rescanning walk a trie exists to replace.
|
||||
* Nodes are in breadth-first order, so a node's children are a contiguous id range (no child
|
||||
* pointers) and a breadth-first walk reads the node array front to back. Fields are one struct
|
||||
* per node since a visit reads all four, and terminals are in node order. The walk is
|
||||
* memory-bound; a pointer-linked layout is slower than the rescanning walk the trie replaces.
|
||||
*
|
||||
* Beside the breadth-first layout, every node knows its subtree's range in LEXICOGRAPHIC order,
|
||||
* `lo..hi` into `lex`. A walk never reads it; the compile does, to list what is under a node where
|
||||
* a key has been left, and so does the one construct that admits a whole subtree at once -- a
|
||||
* token element (`<[id]>`, `!<[id]>`), which matches a token's id wherever it is reached. */
|
||||
* Each node also records its subtree's range `lo..hi` in lexicographic order (`lex`). The walk
|
||||
* never reads it; the compile uses it to list what lies under a node where a key was left, as
|
||||
* do token elements (`<[id]>`, `!<[id]>`), which match a token's id wherever reached. */
|
||||
struct TrieNode {
|
||||
uint32_t cp; /* the code point on the edge INTO this node */
|
||||
uint32_t cp; /* the code point on the edge into this node */
|
||||
uint32_t first; /* its first child's node id */
|
||||
uint32_t n_child; /* how many children follow it */
|
||||
uint32_t tbeg; /* its first terminal slot; it ends at the NEXT node's tbeg */
|
||||
uint32_t tbeg; /* its first terminal slot; it ends at the next node's tbeg */
|
||||
};
|
||||
|
||||
struct TokenTrie {
|
||||
@@ -172,10 +143,9 @@ struct TrieEntry {
|
||||
int32_t id;
|
||||
};
|
||||
|
||||
/* LEXICOGRAPHIC ORDER IS WHAT MAKES A NODE A RANGE: two sequences share a d-code-point prefix iff
|
||||
* they are adjacent in this order and agree to depth d, so every node of the trie is a contiguous
|
||||
* slice of the sorted entries and the build never needs a per-node map. The sequences are
|
||||
* 0-terminated in the arena, which stops the comparison. */
|
||||
/* Sorted lexicographically, every trie node is a contiguous slice of the entries (sequences
|
||||
* sharing a prefix are adjacent), so the build needs no per-node map. Sequences are 0-terminated
|
||||
* in the arena, which stops the comparison. */
|
||||
static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector<TrieEntry>& ents,
|
||||
int32_t unique_over) {
|
||||
const uint32_t n = (uint32_t)ents.size();
|
||||
@@ -198,10 +168,9 @@ static void trie_build(TokenTrie& t, const uint32_t* cps, std::vector<TrieEntry>
|
||||
t.hi.push_back(n);
|
||||
cur.push_back({ 0u, n });
|
||||
|
||||
/* Level d's nodes were appended in the order their ranges appear in `cur`, so node id
|
||||
* `level_lo + i` is the node whose range is cur[i]. Children are appended in the same sweep,
|
||||
* which keeps each node's children -- and the next whole level -- contiguous, and makes node
|
||||
* ids increase with the order nodes are PROCESSED, which the terminal slots depend on. */
|
||||
/* Node `level_lo + i` has range cur[i]. Children are appended in the same sweep, keeping each
|
||||
* node's children and the next level contiguous, and making node ids follow processing order,
|
||||
* which the terminal slots depend on. */
|
||||
uint32_t level_lo = 0;
|
||||
for (uint32_t d = 0; !cur.empty(); ++d) {
|
||||
nxt.clear();
|
||||
@@ -251,26 +220,24 @@ struct VocabIndex {
|
||||
std::vector<int32_t> eog; /* end-of-generation: admissible once a stack completes */
|
||||
|
||||
/* Every piece decoded from a clean start, 0-terminated, in one arena that opens with a pad
|
||||
* element. `off` is kNone for a token the walk never considers: end-of-generation, and a
|
||||
* control token with no text, which can satisfy no character. */
|
||||
* element. `off` is kNone for tokens the walk skips: end-of-generation, and control tokens
|
||||
* with no text. */
|
||||
std::vector<uint32_t> cps;
|
||||
std::vector<uint32_t> off;
|
||||
std::vector<PartialUtf8> tail;
|
||||
TokenTrie trie;
|
||||
|
||||
/* Pieces that decode to no characters and carry nothing out: an overlong sequence for U+0000
|
||||
* first, which ends a decoded sequence. Every live stack admits one -- a completed one too,
|
||||
* which admits nothing else -- so a state with a completed stack admits these whatever its
|
||||
* keys do. */
|
||||
/* Pieces that decode to no characters and carry nothing out (e.g. an overlong U+0000 first,
|
||||
* which ends a decoded sequence). Every live stack admits them, a completed one included, so
|
||||
* a state with a completed stack admits these regardless of its keys. */
|
||||
std::vector<int32_t> blank;
|
||||
|
||||
/* THE PIECES THAT RESUME A SPLIT CHARACTER, per number of bytes the carried character still
|
||||
* needs. With r bytes missing, a piece is admissible only if its first r bytes are
|
||||
* continuation bytes and the rest decodes on its own; its first code point is then the
|
||||
* carried bits followed by those r bytes' bits, and everything after it is fixed. So each
|
||||
* trie's root edges hold the r bytes' bits (plus one, since 0 ends a sequence) and the walk
|
||||
* ORs the carried bits in. A piece of fewer than r continuation bytes and nothing else leaves
|
||||
* the character still unfinished, and is admissible iff some stack could still take it. */
|
||||
/* Pieces that resume a split character, indexed by bytes still missing (r). A piece is
|
||||
* admissible only if its first r bytes are continuation bytes and the rest decodes alone; its
|
||||
* first code point is the carried bits followed by those r bytes' bits. So root edges hold
|
||||
* the r bytes' bits plus one (0 ends a sequence) and the walk ORs the carried bits in. A piece
|
||||
* of fewer than r continuation bytes only (`shorts`) leaves the character unfinished and is
|
||||
* admissible iff some stack could still take it. */
|
||||
struct Resume {
|
||||
std::vector<uint32_t> cps;
|
||||
TokenTrie trie;
|
||||
@@ -315,10 +282,8 @@ std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v) {
|
||||
x->cps.insert(x->cps.end(), dec.first.begin(), dec.first.end());
|
||||
ents.push_back({ x->off[(size_t)id], dec.second, id });
|
||||
|
||||
/* Leading continuation bytes, and what they contribute to a character carried in. The
|
||||
* decode reads the piece as a C string, as decode_utf8 does, so a NUL ends the piece: it
|
||||
* stops the run like any other non-continuation byte, and a piece of continuation bytes
|
||||
* and then a NUL is as short as the bytes before it. */
|
||||
/* Leading continuation bytes and their bits. Like decode_utf8, the piece is read as a C
|
||||
* string, so a NUL ends it: continuation bytes followed by a NUL count as a short piece. */
|
||||
const size_t len = ::strnlen(piece.c_str(), piece.size());
|
||||
size_t k = 0;
|
||||
uint32_t bits = 0;
|
||||
@@ -331,8 +296,8 @@ std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v) {
|
||||
for (int r = 1; r <= 3; ++r) {
|
||||
VocabIndex::Resume& R = x->resume[r - 1];
|
||||
if ((int)k == r && !more_cont) {
|
||||
/* Finishes the character with exactly its first r bytes; the rest decodes from a
|
||||
* clean start, and an invalid rest takes the whole piece with it. */
|
||||
/* Finishes the character with exactly r bytes; the rest decodes from a clean
|
||||
* start, and an invalid rest disqualifies the piece. */
|
||||
const auto rest = decode_utf8(piece.substr((size_t)r), PartialUtf8{});
|
||||
if (rest.second.n_remain < 0) continue;
|
||||
const uint32_t o = (uint32_t)R.cps.size();
|
||||
@@ -361,22 +326,20 @@ std::shared_ptr<const VocabIndex> vocab_index_build(const VocabView& v) {
|
||||
|
||||
/* ============================================================ the stack-set automaton
|
||||
|
||||
* A set of stacks is one state of the pushdown automaton's subset construction: walking the set
|
||||
* forward is the same answer as walking every stack and OR-ing, because admissibility is the
|
||||
* existence of a path, and the union of successors is exactly the set of stacks some path reaches.
|
||||
* States are interned by value, so a set reached twice is one state.
|
||||
* A stack set is one state of the subset construction: walking the set gives the same answer as
|
||||
* walking each stack and OR-ing, since admissibility is the existence of a path. States are
|
||||
* interned by value, so a set reached twice is one state.
|
||||
*
|
||||
* THE SUCCESSOR OF A STACK DOES NOT DEPEND ON THE CODE POINT. Stepping a char-range top pops the
|
||||
* range and pushes what follows it, which `match_char(top, 0).second` finds whatever the code
|
||||
* point; the code point decides only WHETHER the stack steps. So each stack's successor is a
|
||||
* closure computed once per state, and a state's transition depends only on which stacks fire.
|
||||
* The character classes of a state's tops cut the code points into intervals over which that
|
||||
* answer is constant, and the successor is kept per interval. A state holds:
|
||||
* A stack's successor does not depend on the code point: stepping a char-range top pops it and
|
||||
* pushes what follows (`match_char(top, 0).second`); the code point only decides whether the
|
||||
* stack steps. So each stack's successor closure is computed once per state, and a transition
|
||||
* depends only on which stacks fire, which is constant over the intervals the tops' character
|
||||
* classes cut. The successor is kept per interval. A state holds:
|
||||
*
|
||||
* ctop the char-range tops, which step over code points and test a carried partial;
|
||||
* ttop the token tops (`<[id]>`, `!<[id]>`), which match a token's id wherever reached;
|
||||
* has_empty whether the set holds the empty stack: a completed parse, or -- in a key's walk --
|
||||
* the bottom marker, meaning the key has been left.
|
||||
* has_empty whether the set holds the empty stack: a completed parse, or in a key's walk the
|
||||
* bottom marker, meaning the key has been left.
|
||||
*
|
||||
* States live in a deque, so a reference to one survives interning another. */
|
||||
class SetDfa {
|
||||
@@ -399,21 +362,19 @@ public:
|
||||
|
||||
explicit SetDfa(const GbnfRuleSet* rules) : rules_(rules) {}
|
||||
|
||||
/* The operation whose work every step is charged to, and the mark its growth is measured
|
||||
* from. */
|
||||
/* Set the operation every step is charged to, and the mark its growth is measured from. */
|
||||
void begin(OpWork* w) { work_ = w; walk_base_ = elems_; }
|
||||
|
||||
size_t elems() const { return elems_; }
|
||||
size_t n_states() const { return st_.size(); }
|
||||
const St& st(int32_t sid) const { return st_[(size_t)sid]; }
|
||||
|
||||
/* Canonicalise a stack set and return its state, or -1 for the empty set -- the dead state,
|
||||
* represented by absence so a caller can prune on the sign alone. */
|
||||
/* Canonicalise a stack set and return its state, or -1 for the empty (dead) set, so callers
|
||||
* can prune on the sign. */
|
||||
int32_t intern(GbnfStacks s) {
|
||||
if (s.empty()) return -1;
|
||||
/* WHAT A SORT COSTS, which is not its length: n log n comparisons of stacks, each as long
|
||||
* as the stacks' common prefix. Charged as every element once per level of the sort, so
|
||||
* a set too wide to sort within the bound is refused rather than sorted anyway. */
|
||||
/* A sort is n log n stack comparisons, each as long as the common prefix; charged as every
|
||||
* element once per sort level, so a set too wide to sort within the bound is refused. */
|
||||
size_t elems = 0;
|
||||
for (const GbnfStack& k : s) elems += k.size() + 1;
|
||||
work_->add(elems * (1 + (uint64_t)std::bit_width(s.size())));
|
||||
@@ -430,8 +391,8 @@ public:
|
||||
return intern_ptrs(ps, &s);
|
||||
}
|
||||
|
||||
/* The same, from pointers to the stacks. They are copied only if the set is a new state --
|
||||
* moved out of `owned` when the caller holds them in a vector of its own. */
|
||||
/* The same, from pointers to the stacks. They are copied only for a new state, or moved out
|
||||
* of `owned` when the caller passes its own vector. */
|
||||
int32_t intern_ptrs(const std::vector<const GbnfStack*>& ps, GbnfStacks* owned = nullptr) {
|
||||
if (ps.empty()) return -1;
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
@@ -486,9 +447,9 @@ public:
|
||||
return id;
|
||||
}
|
||||
|
||||
/* advance_stack(s) as a state. Memoised on the stack, because many stacks -- in one state or
|
||||
* in many -- close to the same place: every alternative of a wide rule that has just matched
|
||||
* returns to one continuation, and every token of a context is resolved from it. */
|
||||
/* advance_stack(s) as a state, memoised on the stack: many stacks, in one state or many,
|
||||
* close to the same place (every matched alternative of a wide rule returns to one
|
||||
* continuation). */
|
||||
int32_t closure(const GbnfStack& s) {
|
||||
auto it = closure_ids_.find(s);
|
||||
if (it != closure_ids_.end()) return it->second;
|
||||
@@ -501,14 +462,11 @@ public:
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The state whose stacks are the union of these states' stacks.
|
||||
*
|
||||
* The union is memoised on the states united -- a state's successors over two intervals, or
|
||||
* the closures of two contexts, are united again and again -- and built by MERGING POINTERS:
|
||||
* every state's stacks are already sorted, so a balanced tree of pairwise merges compares each
|
||||
* stack once per level where sorting the concatenation would compare them n log n times, and
|
||||
* no stack is copied until the union turns out to be a state not seen before. The bounds are
|
||||
* checked after every merge, so a union that will not fit is refused before it is built. */
|
||||
/* The state whose stacks are the union of these states' stacks. Memoised on the input
|
||||
* states, since the same unions recur. Each state's stacks are sorted, so the union is a
|
||||
* balanced tree of pairwise pointer merges (each stack compared once per level, not n log n)
|
||||
* and stacks are copied only for a new state. Bounds are checked after every merge, so an
|
||||
* oversized union is refused before it is built. */
|
||||
int32_t unite(std::vector<int32_t>& ids) {
|
||||
std::sort(ids.begin(), ids.end());
|
||||
ids.erase(std::unique(ids.begin(), ids.end()), ids.end());
|
||||
@@ -552,9 +510,8 @@ public:
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The state's intervals, built on first use: every boundary of every char-range top. Over
|
||||
* each interval every top either matches every code point or none, because each of its items
|
||||
* starts or ends at a boundary. */
|
||||
/* The state's intervals, built on first use from every boundary of every char-range top, so
|
||||
* each top matches either all or none of the code points in an interval. */
|
||||
const St& parted(int32_t sid) {
|
||||
St& S = st_[(size_t)sid];
|
||||
if (S.parted) return S;
|
||||
@@ -586,9 +543,9 @@ public:
|
||||
return S;
|
||||
}
|
||||
|
||||
/* The successor over interval i of a parted state, computed on first use. The firing pattern
|
||||
* is memoised as well as the interval: many intervals fire the same stacks -- everything
|
||||
* that is not a quote or a backslash, in a JSON string -- and their union is built once. */
|
||||
/* The successor over interval i of a parted state, computed on first use. Also memoised by
|
||||
* firing pattern, since many intervals fire the same stacks (in a JSON string, everything but
|
||||
* a quote or backslash). */
|
||||
int32_t next(int32_t sid, size_t i) {
|
||||
St& S = st_[(size_t)sid];
|
||||
if (S.next[i] != kUnbuilt) return S.next[i];
|
||||
@@ -663,9 +620,8 @@ private:
|
||||
|
||||
/* ============================================================ the walk
|
||||
|
||||
* Descend a trie breadth-first carrying one automaton state per live node, setting a bit for every
|
||||
* token the state admits there. A node's tokens are admitted as follows, which is the candidate
|
||||
* walk's rule stated the other way up:
|
||||
* Descend a trie breadth-first with one automaton state per live node, setting a bit for every
|
||||
* token the state admits there (the candidate walk's rule, inverted):
|
||||
*
|
||||
* ending here admitted iff nothing is carried out, or some char-range top could take
|
||||
* some completion of what is;
|
||||
@@ -691,8 +647,7 @@ struct Walk {
|
||||
uint64_t frontier_limit = UINT64_MAX;
|
||||
bool aborted = false;
|
||||
|
||||
/* The admitted ids in the order they were first set, while there are few enough to be worth
|
||||
* listing; past `list_cap` only the bits are kept. */
|
||||
/* Admitted ids in first-set order, up to `list_cap`; past it only the bits are kept. */
|
||||
std::vector<int32_t>* list = nullptr;
|
||||
size_t list_cap = 0;
|
||||
bool list_full = false;
|
||||
@@ -712,10 +667,9 @@ static inline void admit(Walk& w, int32_t id) {
|
||||
}
|
||||
}
|
||||
|
||||
/* What a visit needs of the state it is made in. Read once per RUN of children -- every child in
|
||||
* one interval of the parent's state shares its successor -- rather than once per child: a
|
||||
* permissive walk visits every node of the vocabulary trie, and at that count the lookup of a
|
||||
* state is a measurable part of a visit. */
|
||||
/* What a visit needs of its state. Read once per run of children sharing an interval (and so a
|
||||
* successor), not per child: a permissive walk visits every vocabulary trie node, where the state
|
||||
* lookup is a measurable part of a visit. */
|
||||
struct VisitState {
|
||||
const SetDfa::St* S = nullptr;
|
||||
bool expand = false; /* it has char-range tops, so children can be stepped */
|
||||
@@ -732,8 +686,8 @@ static inline VisitState visit_state(const SetDfa& dfa, const Walk& w, int32_t s
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The tokens ending at a node whose state is live: admitted outright unless they carry out a
|
||||
* partial character, which some char-range top must be able to finish. */
|
||||
/* Tokens ending at a live node: admitted unless they carry out a partial character that no
|
||||
* char-range top can finish. */
|
||||
static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_t t0,
|
||||
uint32_t t1) {
|
||||
const TokenTrie& T = *w.trie;
|
||||
@@ -750,7 +704,7 @@ static void visit_terminals(Walk& w, OpWork& work, const VisitState& vs, uint32_
|
||||
}
|
||||
}
|
||||
|
||||
/* What a token top admits from below node n, `t1 - t0` of whose tokens end at n itself. */
|
||||
/* What a token top admits from below node n; `n_end` of n's subtree tokens end at n itself. */
|
||||
static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work,
|
||||
const VisitState& vs, uint32_t n,
|
||||
uint32_t n_end) {
|
||||
@@ -778,8 +732,8 @@ static __attribute__((noinline)) void visit_token_tops(Walk& w, OpWork& work,
|
||||
}
|
||||
}
|
||||
|
||||
/* Visit node n: admit what ends here and what a token top takes from below, record an exit.
|
||||
* Returns whether the node's children are worth stepping. */
|
||||
/* Visit node n: admit what ends here and what a token top takes from below, and record an exit.
|
||||
* Returns whether the node's children should be stepped. */
|
||||
static inline __attribute__((always_inline)) bool walk_visit(Walk& w, OpWork& work,
|
||||
const TrieNode* nd, uint32_t n,
|
||||
const VisitState& vs,
|
||||
@@ -825,10 +779,10 @@ static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch&
|
||||
const uint32_t c1 = nd[n].first + nd[n].n_child;
|
||||
size_t i = 0;
|
||||
|
||||
/* One run of children per interval: the children are sorted, so the interval only
|
||||
* moves forward -- a step at a time among a few intervals, by binary search among
|
||||
* many -- a dead one is skipped by a binary search over the children, and a live one
|
||||
* hands every child in it the same state. */
|
||||
/* One run of children per interval. Children are sorted, so the interval only moves
|
||||
* forward (linear among few intervals, binary search among many). A dead interval is
|
||||
* skipped by binary search over the children; a live one gives all its children the
|
||||
* same state. */
|
||||
while (c < c1) {
|
||||
const uint64_t cp = cp_of(c);
|
||||
if (m <= 16) {
|
||||
@@ -863,11 +817,11 @@ static void walk(SetDfa& dfa, int32_t start, Walk& w, OpWork& work, WalkScratch&
|
||||
|
||||
/* ============================================================ the plan */
|
||||
|
||||
/* A KEY: a suffix of stack entries by class, bottom first. Held as a tree grown downward -- a
|
||||
* node is its bottom class plus the node for the entries above it -- which is also how a stack
|
||||
* is looked up: from its top, one entry down per level, until a node that is not extended.
|
||||
/* A key: a suffix of stack entries by class, bottom first. Held as a tree grown downward (a node
|
||||
* is its bottom class plus the node for the entries above it); a stack is looked up from its top,
|
||||
* one entry down per level, until a node that is not extended.
|
||||
*
|
||||
* `mask` is the accepted set: of a final node, used with any context; of an extended node that
|
||||
* `mask` is the accepted set: for a final node, used with any context; for an extended node that
|
||||
* can be a whole stack, used only when the stack ends there. `rem` is the remainder trie, walked
|
||||
* from the context's state when there is a context. */
|
||||
struct KeyNode {
|
||||
@@ -897,9 +851,9 @@ struct MaskPlan {
|
||||
std::vector<TokenTrie> rems;
|
||||
PlanStats stats;
|
||||
|
||||
/* THE RUN-TIME HALF IS A MEMO. The automaton here holds the states contexts close to and the
|
||||
* remainders step into; it grows as they are discovered and every state in it is a fact about
|
||||
* the grammar, so one lock covers it and every request and rank shares it. */
|
||||
/* Run-time memo: the automaton holding the states contexts close to and remainders step
|
||||
* into. It grows as states are discovered; each is a fact about the grammar, so one lock
|
||||
* covers it and every request and rank shares it. */
|
||||
mutable std::mutex mu;
|
||||
mutable std::unique_ptr<SetDfa> dfa;
|
||||
mutable WalkScratch ws;
|
||||
@@ -941,27 +895,23 @@ struct Grammar {
|
||||
}
|
||||
};
|
||||
|
||||
/* WHICH RULES ARE THE SAME RULE. A generated grammar repeats itself: every tool's
|
||||
* undeclared-parameter clause is `("<parameter=" ([^>] | ">" [^\n])* ">\n")`, and the parser gives
|
||||
* each copy -- the group, the repetition, the alternatives inside it -- rules of its own. Their
|
||||
* entries would be distinct classes, and each would get a key and a walk of the vocabulary of
|
||||
* its own, one per tool, for identical answers.
|
||||
/* Merge identical rules. Generated grammars repeat clauses (every tool's undeclared-parameter
|
||||
* clause `("<parameter=" ([^>] | ">" [^\n])* ">\n")`), and the parser gives each copy its own
|
||||
* rules, which would otherwise mean a key and a vocabulary walk per copy.
|
||||
*
|
||||
* So rules are hash-consed on their bodies with references replaced by the referenced rule's
|
||||
* canonical id, bottom-up over the reference graph's strongly connected components. A rule that
|
||||
* refers only to itself -- which is what a repetition is -- is hashed with its self-references
|
||||
* marked as such, so identical repetitions merge too. A larger cycle of rules is left distinct:
|
||||
* mutual recursion is rare in what generators emit and is correct unmerged. Returns the canonical
|
||||
* id of each rule; ids of merged rules are equal, and no id is a rule index. */
|
||||
* Rules are hash-consed on their bodies, with references replaced by the target's canonical id,
|
||||
* bottom-up over the reference graph's SCCs. A self-referencing rule (a repetition) is hashed
|
||||
* with its self-references marked, so identical repetitions merge. Larger cycles are left
|
||||
* distinct (rare in generated grammars, and correct unmerged). Returns each rule's canonical id;
|
||||
* merged rules share one, and no id is a rule index. */
|
||||
static std::vector<uint32_t> canonical_rules(const Grammar& G, const std::vector<char>& nullable,
|
||||
uint32_t max_cps, OpWork& work) {
|
||||
const GbnfRuleSet& R = G.R;
|
||||
const size_t NR = R.n_rules(), NE = R.elems.size();
|
||||
auto rule_end = [&](size_t r) { return r + 1 < NR ? R.start[r + 1] : (uint32_t)NE; };
|
||||
|
||||
/* Tarjan's strongly connected components over references, iteratively. Components come out
|
||||
* in reverse topological order: every rule a component refers to outside itself is already
|
||||
* canonical when it is reached. */
|
||||
/* Tarjan's SCCs over references, iteratively. Components come out in reverse topological
|
||||
* order, so every rule a component refers to outside itself is already canonical. */
|
||||
std::vector<int32_t> idx(NR, -1), low(NR, 0);
|
||||
std::vector<char> on(NR, 0);
|
||||
std::vector<uint32_t> stk;
|
||||
@@ -1019,14 +969,12 @@ static std::vector<uint32_t> canonical_rules(const Grammar& G, const std::vector
|
||||
out.append((const char*)&v, 4);
|
||||
};
|
||||
|
||||
/* A BOUNDED REPETITION IS A STAR, AS FAR AS ANY TOKEN CAN TELL. The parser writes x{0,n} as a
|
||||
* chain, `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, and every link is a rule of its own --
|
||||
* so `[^"]{0,1000}` would be a thousand keys, each walking the vocabulary. But a token holds
|
||||
* at most `max_cps` code points, and when x always consumes at least one, a token can take at
|
||||
* most that many repetitions: with more than that left, no token can tell the link from
|
||||
* `x*`. Such links are given the star's canonical id; the shorter ones stay what they are.
|
||||
* `depth` and `operand` hold, per link, how many repetitions it allows and the signature of
|
||||
* what it repeats; a star, which refers to itself, is not a link. */
|
||||
/* A bounded repetition looks like a star to any token. The parser writes x{0,n} as a chain
|
||||
* `S(k) ::= x S(k-1) |` down to `S(1) ::= x |`, one rule per link. A token holds at most
|
||||
* `max_cps` code points, so if x always consumes one, a link with more repetitions left than
|
||||
* that is indistinguishable from `x*` and gets the star's canonical id. `depth` and `operand`
|
||||
* hold, per link, its remaining repetitions and the signature of what it repeats; a star
|
||||
* (self-referencing) is not a link. */
|
||||
std::vector<uint32_t> depth(NR, 0);
|
||||
std::vector<std::string> operand(NR);
|
||||
auto consumes = [&](uint32_t a, uint32_t e) {
|
||||
@@ -1097,9 +1045,7 @@ static std::vector<uint32_t> canonical_rules(const Grammar& G, const std::vector
|
||||
return canon;
|
||||
}
|
||||
|
||||
/* Which rules can match the empty string: a fixed point, as in find_left_recursion. An
|
||||
* alternative with a terminal in it never can; one of rule references only can once all of them
|
||||
* can, so it waits on a count. */
|
||||
/* Which rules can match the empty string: a fixed point, as in find_left_recursion. */
|
||||
static std::vector<char> nullable_rules(const GbnfRuleSet& R, OpWork& work) {
|
||||
const size_t NR = R.n_rules(), NE = R.elems.size();
|
||||
std::vector<char> nullable(NR, 0);
|
||||
@@ -1142,16 +1088,13 @@ static std::vector<char> nullable_rules(const GbnfRuleSet& R, OpWork& work) {
|
||||
return nullable;
|
||||
}
|
||||
|
||||
/* THE CLASS OF AN ENTRY is what remains of its alternative from it on, element for element with
|
||||
* rule references by canonical rule, hash-consed from the end of each alternative backward. Two
|
||||
* entries of one class behave identically wherever they are: what a stack does next is fixed by
|
||||
* the elements its entries have left and the rules those reference. Class 0 is the end of an
|
||||
* alternative and is never an entry.
|
||||
/* An entry's class is the rest of its alternative from it on, with rule references by canonical
|
||||
* rule, hash-consed backward from the end of each alternative. Entries of one class behave
|
||||
* identically anywhere. Class 0 is the end of an alternative and is never an entry.
|
||||
*
|
||||
* A RUN OF ONE UNIT is capped the way a repetition chain is (canonical_rules): x{1000} is a
|
||||
* thousand x in a row, and an entry with more than `max_cps` of a unit that always consumes a
|
||||
* code point still ahead of it behaves, for every token, like one with one fewer. Such an entry
|
||||
* takes the class of the entry after it. */
|
||||
* A run of one unit is capped like a repetition chain (canonical_rules): x{1000} is a thousand x
|
||||
* in a row, and an entry with more than `max_cps` of a code-point-consuming unit ahead of it
|
||||
* behaves, for every token, like one with one fewer, so it takes the next entry's class. */
|
||||
static void compute_classes(Grammar& G, MaskPlan& P, const std::vector<char>& nullable,
|
||||
uint32_t max_cps, OpWork& work) {
|
||||
const GbnfRuleSet& R = G.R;
|
||||
@@ -1209,19 +1152,15 @@ static void compute_classes(Grammar& G, MaskPlan& P, const std::vector<char>& nu
|
||||
}
|
||||
}
|
||||
|
||||
/* A RULE THAT CAN NEVER MATCH ANYTHING, and cannot be left either: every way into it comes back
|
||||
* into it without reaching a character or its own end -- `r ::= r` is the shortest. A stack that
|
||||
* enters one closes to nothing at all, and upstream's candidate walk reads a stack set that is
|
||||
* empty as rejecting nothing, so the mask past such a point admits every token while accepting
|
||||
* any of them ends the parse. A mask built from stack suffixes cannot reproduce that reading --
|
||||
* it depends on whether the rest of one particular stack is empty -- and nothing a grammar means
|
||||
* depends on it, so a grammar that can reach such a rule is refused, by the rule's name.
|
||||
/* A blind rule can neither match anything nor be left (`r ::= r` is the shortest). A stack that
|
||||
* enters one closes to nothing, which upstream's candidate walk reads as admitting every token
|
||||
* while accepting any of them ends the parse. Suffix-based masks cannot reproduce that, and no
|
||||
* meaningful grammar depends on it, so a grammar that can reach such a rule is refused by name.
|
||||
*
|
||||
* A rule can POP past itself iff it is nullable, and its closure YIELDS a stack iff some element
|
||||
* it can reach before a first element that cannot pop is a terminal or a rule that yields. Both are
|
||||
* least fixed points computed with worklists, linear in the grammar -- a chain of a hundred
|
||||
* thousand rules is one pass, not one per link. A rule doing neither is blind. Returns a blind
|
||||
* rule reachable from the root, or kNone. */
|
||||
* A rule can pop past itself iff it is nullable; its closure yields a stack iff some element
|
||||
* reachable before the first non-nullable one is a terminal or a yielding rule. Both are least
|
||||
* fixed points computed with worklists in one linear pass. A rule doing neither is blind.
|
||||
* Returns a blind rule reachable from the root, or kNone. */
|
||||
static uint32_t blind_rule(const Grammar& G, const std::vector<char>& nullable, OpWork& work) {
|
||||
const GbnfRuleSet& R = G.R;
|
||||
const size_t NR = R.n_rules();
|
||||
@@ -1270,8 +1209,8 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
}
|
||||
work.add(NE);
|
||||
|
||||
/* Reachable rules. A reference inside an unreachable rule is not a place any stack can be,
|
||||
* and counting it would give frames predecessors they never have. */
|
||||
/* Reachable rules. References inside unreachable rules must not count, or frames would get
|
||||
* predecessors no stack has. */
|
||||
G.reach.assign(NR, 0);
|
||||
std::vector<uint32_t> todo{ G.root };
|
||||
G.reach[G.root] = 1;
|
||||
@@ -1288,7 +1227,7 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Tail references (a frame REPLACED rather than stacked on), and every reference by target. */
|
||||
/* Tail references (a frame replaced rather than stacked on), and every reference by target. */
|
||||
G.rev_tail.assign(NR, {});
|
||||
G.refs_to.assign(NR, {});
|
||||
std::vector<std::vector<uint32_t>> tail_to(NR);
|
||||
@@ -1311,8 +1250,8 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The frames a stack can have at its bottom: the root's, and whatever it hands over to by
|
||||
* tail reference. */
|
||||
/* Frames a stack can have at its bottom: the root's, and whatever it hands over to by tail
|
||||
* reference. */
|
||||
G.bottom_ok.assign(NR, 0);
|
||||
todo.assign(1, G.root);
|
||||
G.bottom_ok[G.root] = 1;
|
||||
@@ -1323,7 +1262,7 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
if (!G.bottom_ok[t]) { G.bottom_ok[t] = 1; todo.push_back(t); }
|
||||
}
|
||||
|
||||
/* The terminals, by class: every place a stack's top can be. */
|
||||
/* Terminals by class: every place a stack's top can be. */
|
||||
G.tops.assign(G.rep.size(), {});
|
||||
for (size_t r = 0; r < NR; ++r) {
|
||||
if (!G.reach[r]) continue;
|
||||
@@ -1345,16 +1284,14 @@ static void analyse(Grammar& G, MaskPlan& P, OpWork& work) {
|
||||
G.stamp.assign(NR, 0);
|
||||
}
|
||||
|
||||
/* THE ENTRIES THAT CAN SIT DIRECTLY BELOW A FRAME OF RULE r: the element after every reference to
|
||||
* r, or to a rule that hands over to r by tail reference. Every entry below a stack's top is such
|
||||
* an element -- where the frame below resumes.
|
||||
/* Entries that can sit directly below a frame of rule r: the element after every reference to r,
|
||||
* or to a rule that hands over to r by tail reference (where the frame below resumes).
|
||||
*
|
||||
* KEPT BY ELEMENT, NOT BY CLASS, and a key's bottom entry carries the elements it can be. Classes
|
||||
* merge elements of different rules, and so merge what can sit below them: the `space` that ends
|
||||
* `integer` and the `space` after `integer` in the rule that uses it are one class, and below the
|
||||
* first is the second, so by class that class can sit below itself without end -- a chain no real
|
||||
* stack holds, and one a key would be extended along until it was refused. By element, adjacency
|
||||
* is exact, and a key grows only as deep as real stacks do. */
|
||||
* Kept by element, not class; a key's bottom entry carries the elements it can be. Classes merge
|
||||
* elements of different rules: the `space` ending `integer` and the `space` after `integer` in its
|
||||
* user are one class, so by class it could sit below itself without end, and a key would be
|
||||
* extended along that phantom chain until refused. By element, keys grow only as deep as real
|
||||
* stacks. */
|
||||
static const std::vector<uint32_t>& below_of(Grammar& G, uint32_t r, OpWork& work) {
|
||||
if (G.below_done[r]) return G.below[r];
|
||||
std::vector<uint32_t>& out = G.below[r];
|
||||
@@ -1380,13 +1317,11 @@ static const std::vector<uint32_t>& below_of(Grammar& G, uint32_t r, OpWork& wor
|
||||
|
||||
/* The entries that can sit directly below any of `pos`, as (class, element), sorted.
|
||||
*
|
||||
* ONE WALK FROM ALL OF `pos`'s RULES, not one below_of per rule. The links of a repetition chain
|
||||
* hand over to each other by tail reference, so the walk up from one link climbs every link above
|
||||
* it; and every link past the longest token is one class, so one key's positions are all n links
|
||||
* of `x{0,n}`. Walked a rule at a time that is n^2/2 steps -- `maxLength: 32000` took two seconds
|
||||
* to compile, and 48000 was refused for the work. Walked from every rule at once, each rule is
|
||||
* visited once. A rule whose own set is already known contributes it and is not climbed past. A
|
||||
* key of one rule, the common case, keeps the memo. */
|
||||
* One walk from all of `pos`'s rules, not below_of per rule. Repetition-chain links hand over by
|
||||
* tail reference, so climbing from one link visits every link above it, and one key's positions
|
||||
* can be all n links of `x{0,n}`; per rule that is n^2/2 steps. Walking from all rules at once
|
||||
* visits each rule once. A rule whose set is already known contributes it and is not climbed
|
||||
* past. A single-rule key (the common case) uses the below_of memo. */
|
||||
static void preds_of(Grammar& G, const MaskPlan& P, const std::vector<uint32_t>& pos,
|
||||
std::vector<std::pair<uint32_t, uint32_t>>* out, OpWork& work) {
|
||||
out->clear();
|
||||
@@ -1440,9 +1375,9 @@ static std::string rule_name_of(const std::vector<std::string>* names, uint32_t
|
||||
|
||||
/* ============================================================ building the keys */
|
||||
|
||||
/* What one key's walk decided. A final key keeps its accepted set, which holds whatever the
|
||||
* context, and its remainder trie. A key that is not final is extended; it keeps an accepted set
|
||||
* only if it can also be a whole stack, where there is no context and that set is the mask. */
|
||||
/* What one key's walk decided. A final key keeps its accepted set (valid for any context) and its
|
||||
* remainder trie. A non-final key is extended, and keeps an accepted set only if it can also be a
|
||||
* whole stack, where that set is the mask. */
|
||||
struct Outcome {
|
||||
bool final_ = false;
|
||||
int32_t mask = -1;
|
||||
@@ -1467,8 +1402,8 @@ public:
|
||||
} else if (!w.aborted) {
|
||||
o.mask = store(w);
|
||||
} else {
|
||||
/* The walk was cut short once the key was known to be extended; as a whole stack it
|
||||
* needs the rest. */
|
||||
/* The walk stopped early because the key will be extended; as a whole stack it needs
|
||||
* a full walk. */
|
||||
clear(w);
|
||||
Walk whole = start_walk(false);
|
||||
walk(dfa_, s0, whole, work_, ws_);
|
||||
@@ -1492,8 +1427,8 @@ private:
|
||||
return w;
|
||||
}
|
||||
|
||||
/* Keep an accepted set: listed when the walk listed it, as a bitmask otherwise. Clears the
|
||||
* scratch bits either way. */
|
||||
/* Keep an accepted set: as a list if the walk listed it, else as a bitmask. Clears the scratch
|
||||
* bits either way. */
|
||||
int32_t store(Walk& w) {
|
||||
KeyMask m;
|
||||
if (!w.list_full) {
|
||||
@@ -1527,10 +1462,9 @@ private:
|
||||
return true;
|
||||
}
|
||||
if (!w.aborted) {
|
||||
/* What leaves the key and is not already admitted without it: the tokens under each
|
||||
* node where the key was left, from that depth on. A token that ends exactly there
|
||||
* leaves an empty remainder, which only a carried-out partial character can make
|
||||
* worth keeping. */
|
||||
/* The remainder: tokens under each node where the key was left, from that depth on,
|
||||
* that are not already admitted. A token ending exactly there leaves an empty
|
||||
* remainder, kept only if it carries out a partial character. */
|
||||
rents_.clear();
|
||||
bool too_many = false;
|
||||
for (const auto& f : frontier_) {
|
||||
@@ -1601,7 +1535,7 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr<const
|
||||
work.limit = kMaxCompileWork;
|
||||
|
||||
Grammar G(R, root);
|
||||
/* The longest token in code points, which is as far as any mask can see into the grammar. */
|
||||
/* The longest token in code points: how far any mask can see into the grammar. */
|
||||
const uint32_t max_cps = X.trie.depth > 0 ? X.trie.depth - 1 : 0;
|
||||
const std::vector<char> nullable = nullable_rules(R, work);
|
||||
compute_classes(G, P, nullable, max_cps, work);
|
||||
@@ -1639,14 +1573,13 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr<const
|
||||
GbnfStack local;
|
||||
for (size_t qi = 0; qi < todo.size(); ++qi) {
|
||||
const int32_t ki = todo[qi];
|
||||
/* The compile automaton is a memo like the run-time one; it is dropped between keys once
|
||||
* it is large, never during a walk. Each key is one operation as far as its growth bound
|
||||
* goes, as each mask is at run time. */
|
||||
/* The compile automaton is a memo, dropped between keys (never during a walk) once large.
|
||||
* Each key counts as one operation for the growth bound, as each mask does at run time. */
|
||||
if (dfa.elems() > kMaxDfaElems) dfa = SetDfa(&R);
|
||||
dfa.begin(&work);
|
||||
|
||||
/* A node's class is its BOTTOM entry and `up` is the suffix above it, so following `up`
|
||||
* lists the key bottom-first, which is a stack's order. */
|
||||
/* A node's class is its bottom entry and `up` the suffix above it, so following `up`
|
||||
* lists the key bottom-first, in stack order. */
|
||||
local.clear();
|
||||
for (int32_t k = ki; k >= 0; k = P.keys[(size_t)k].up)
|
||||
local.push_back(&R.elems[G.rep[P.keys[(size_t)k].cls]]);
|
||||
@@ -1715,9 +1648,9 @@ int plan_build(const GbnfRuleSet& R, uint32_t root, const std::shared_ptr<const
|
||||
|
||||
/* ============================================================ a mask */
|
||||
|
||||
/* The key a stack is served by, and how many of its entries it spans: from the top down, one
|
||||
* entry per level, until a node that is not extended or the stack runs out. -1 is a stack no key
|
||||
* covers, which the analysis rules out; it is reported rather than served. */
|
||||
/* The key serving a stack, and how many entries it spans: from the top down, one entry per level,
|
||||
* until a non-extended node or the stack's bottom. -1 means no key covers the stack, which the
|
||||
* analysis rules out; the caller reports it. */
|
||||
static int32_t key_of(const MaskPlan& P, const GbnfStack& S, size_t* depth, OpWork& work) {
|
||||
const GbnfRuleSet& R = *P.rules;
|
||||
const uint32_t c0 = P.cls[R.index(S.back())];
|
||||
@@ -1802,13 +1735,11 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
|
||||
const SetDfa::St& S = dfa.st(s0);
|
||||
const TrieNode* nd = RS.trie.node.data();
|
||||
|
||||
/* A CHARACTER FINISHED AS U+0000 ENDS THE PIECE. The carried bits are zero only after the
|
||||
* head of an overlong sequence, and with zero bits to finish it the character decodes to 0 --
|
||||
* which in a decoded sequence is its terminator, so the piece reads as having no characters at
|
||||
* all, whatever follows. Such a piece is admissible as one that ends before its first
|
||||
* character is: outright if it carries nothing out, and otherwise if some char-range top could
|
||||
* finish what it does. Those pieces are all under the root edge for zero bits, the first, and
|
||||
* are served here rather than stepped over as a character. */
|
||||
/* A character finished as U+0000 ends the piece. Carried bits are zero only after the head of
|
||||
* an overlong sequence; finishing it with zero bits decodes to 0, the sequence terminator, so
|
||||
* the piece has no characters whatever follows. Such a piece is admissible if it carries
|
||||
* nothing out, or if some char-range top could finish what it carries. These pieces are all
|
||||
* under the first root edge (zero bits) and are handled here, not stepped as a character. */
|
||||
const bool nul = partial.value == 0 && nd[0].n_child > 0 && nd[nd[0].first].cp == 1;
|
||||
if (nul) {
|
||||
std::vector<uint32_t> todo{ nd[0].first };
|
||||
@@ -1843,11 +1774,9 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
|
||||
}
|
||||
}
|
||||
|
||||
/* The plan's automaton, for one operation charged to `work`. The caller holds P.mu.
|
||||
*
|
||||
* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: every
|
||||
* state in it can be rediscovered, and a grammar whose stacks deepen with every token would
|
||||
* otherwise hold a new state per token for as long as it is cached. */
|
||||
/* The plan's automaton, for one operation charged to `work`. Caller holds P.mu. Past its bound
|
||||
* the memo is dropped and rebuilt rather than refused, since every state can be rediscovered and
|
||||
* a grammar whose stacks deepen every token would otherwise add a state per token. */
|
||||
static SetDfa& plan_dfa(const MaskPlan& P, OpWork& work) {
|
||||
if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
|
||||
if (P.dfa)
|
||||
@@ -1865,9 +1794,8 @@ bool plan_step(const MaskPlan& P, const std::vector<const GbnfStack*>& stacks, P
|
||||
std::lock_guard<std::mutex> lk(P.mu);
|
||||
SetDfa& dfa = plan_dfa(P, work);
|
||||
|
||||
/* The set as a state: the one the caller names, or canonicalised through pointers -- sorted,
|
||||
* without duplicates, and copied only if the automaton has not seen it. Charged as intern()
|
||||
* charges a sort. */
|
||||
/* The set as a state: the one the caller names, or canonicalised through pointers (sorted,
|
||||
* de-duplicated, copied only if new). The sort is charged as in intern(). */
|
||||
const bool named = at->id >= 0 && at->gen == P.dfa_gen;
|
||||
int32_t s0;
|
||||
if (named) {
|
||||
@@ -1891,8 +1819,7 @@ bool plan_step(const MaskPlan& P, const std::vector<const GbnfStack*>& stacks, P
|
||||
}
|
||||
int32_t s = s0;
|
||||
|
||||
/* One successor per code point: the interval the code point falls in, then that interval's
|
||||
* successor, each built on first use and served from the memo after. */
|
||||
/* Per code point: find its interval, then that interval's successor (both memoised). */
|
||||
for (size_t k = 0; k < n && s >= 0; ++k) {
|
||||
const SetDfa::St& S = dfa.parted(s);
|
||||
const size_t i = (size_t)(std::upper_bound(S.lo.begin(), S.lo.end(), cps[k]) -
|
||||
|
||||
Reference in new issue
Block a user