query design
This page explains the search query language of
src/query: its grammar and precedence,
the tree it produces, why the serializer and the parser agree, how the flat
parameters of the web interface map to the same tree, and what the
operations cost. The query API lists the functions.
Design goal
One query must mean the same thing wherever it runs: typed as an expression,
built in the graphical query builder, carried in a URL, answered by SQLite
or by the static site’s worker. So the language needs a single owner that
parses, validates and normalises it, and that owner must give the same
result on every backend. Before this package the language lived in
TypeScript (lib/query.ts); it is now MoonBit, and the TypeScript module is
a thin wrapper.
Mathematical background
Grammar
The expression language, after removing white space between tokens, is
query = [ or ] ;
or = and , { "OR" , and } ;
and = unary , { "AND" , unary } ;
unary = "NOT" , unary | primary ;
primary = "(" , or , ")" | term ;
term = word , op , value | word | quoted ;
op = ":" | "=" | ">=" | "<=" ;
value = word | quoted ;
quoted = '"' , { char - ( '"' | "\" ) | "\" , char } , '"' ;
word = char - delim , { char - delim } ; (* not AND, OR, NOT *)
delim = space | "(" | ")" | ":" | "=" | ">=" | "<=" ;
AND, OR and NOT are recognised in any letter case; field names are
case-sensitive. space is the ECMAScript white space set
(is_white_space), so a full-width space separates words like an ASCII one.
A word stops only at a delimiter, so a>b is one word and
repository:https://x is the term repository:https followed by the stray
tokens : //x, which the parser rejects.
The tokenizer works on UTF-16 code units, like the TypeScript code it replaces. All delimiters are ASCII, so a surrogate pair is never split.
Precedence and the shape of the tree
The grammar is the usual precedence-climbing one: binds tighter than , which binds tighter than . So
Each or and and rule collects its operands into one group; a rule with
a single operand returns the operand itself (coalesce). Hence
a AND b AND cis oneAndgroup with three children, not a binary tree, because the loop collects all operands;(a)is the terma, not a group of one;(a AND b) AND ckeeps the inner group: parentheses are respected even when they change nothing.
NOT flips the negated flag of its operand instead of adding a node, so
NOT NOT a is the term a with negated = false. The root is always a
group: a lone term is wrapped in an And group, so every consumer can start
from Group.
Serialization and round trips
serialize writes a tree back. Let be parse_expression and be
serialize. The property that matters is semantic: for every tree the
parser can produce, has the same truth value as on every
package. It follows from three rules.
- Values. A value is written bare only when it is made of
[A-Za-z0-9_./-]and is not a keyword; otherwise it is quoted with\and"escaped. A bare value therefore re-tokenizes to exactly one word, and a quoted one to exactly its text. Values are trimmed, which matches the evaluators: every text test trims its needle first. - Precedence. A group with two or more children is parenthesised when its connective differs from its parent’s. A same-connective child needs no parentheses because and are associative: .
- Negation.
NOTbinds tighter than both connectives, so a negated group with two or more children is always parenthesised: must not become .
is not injective, so does not hold in general: (a AND b) AND c comes back flattened. It holds after one round, , which the tests check for a set of expressions.
The language has no spelling for an empty group. The query builder can
create one, and writes it as (), which does not parse. A tree with an
empty group is still valid JSON and evaluates normally (empty And = true,
empty Or = false).
Flat parameters
The web interface also keeps one parameter per field. legacy_params_to_ast
maps them to
where is the term of parameter (for example minScore ↦
score>=). rank and momentum accept lists: with labels
after canonicalisation,
which is a single term for and nothing for . derive_ast
chooses, in order, a non-blank ast parameter, a non-blank expr, and
.
Numbers and white space
Numeric terms keep their value as text; consumers read it with
number_value, which implements ECMAScript StringToNumber: trimmed blank
text is , 0x/0o/0b literals are integers in that base, Infinity
is infinite and everything else must be a decimal literal or gives NaN. The
decimal case is parsed by @string.parse_double, which rounds correctly,
after the syntax has been checked in MoonBit (the core parser also accepts
1_000 and inf, which ECMAScript does not).
Design decisions
MoonBit owns the language
Problem. The parser, the serializer and the validator were TypeScript, and the static evaluator and the SQL compiler were separate TypeScript files that had to agree with them.
Choice. All of them are MoonBit packages now (query, query_sql,
static_search), and the TypeScript side calls the generated JavaScript
through JSON strings. The JSON shape of the tree did not change, so URLs
and stored queries keep working.
Strings at the JavaScript boundary
Problem. The web code needs the functions with TypeScript types.
Choice. Each exported function takes and returns strings, and failures
come back as {"error": …} envelopes instead of exceptions. Strings are
the one type both sides represent the same way, the JSON form already
existed, and an envelope keeps the error message intact across the
boundary. lib/query.ts turns the envelopes back into objects and thrown
Errors, so its callers did not change.
One list per label set
The rank and momentum labels are each defined once (rank_labels,
momentum_labels). Error messages, list parsing, the SQL compiler and the
static evaluator all derive from them, so adding a momentum label is a
one-line change.
Fixed tables instead of host functions
trim, number_value and the case-insensitive keyword test are written in
MoonBit rather than delegated to the host, because Luna-Flow packages must
give identical results on every backend. They reproduce the ECMAScript
behaviour that the previous TypeScript code had, so no query changes meaning.
Correctness / invariants
- Every tree the parser returns has a group at the root and validates:
decode(encode(t)) == t. S(P(S(t))) = S(t)for parser output, and evaluates like .has_intentis false exactly when every term value is blank; the search then lists everything instead of filtering.negatedis written to JSON only when true, so the encoding of a tree is unique.
Complexity
For an expression of code units, tokenizing is (escapes are copied in slices), parsing is with recursion depth equal to the parenthesis depth, and serialization is in the size of the output. Validation of a JSON tree with nodes is .
Alternatives rejected
- Keep the TypeScript parser and port only the evaluator. Two languages would again own one grammar.
- Pass MoonBit objects to JavaScript instead of JSON. The generated objects are not plain JSON, so every consumer would need adapters.
- A parser generator. The grammar has five rules; a hand-written recursive-descent parser keeps the error messages the interface already shows.
Boundaries
- The language has no empty group, no wildcard syntax and no ranges in one
term (
score>=1 AND score<=2is the way to write a range). querydoes not know the database or the index; it does not decide what a field matches. That isquery_sqlandstatic_search.- Values are not validated per field here:
score>=abcparses, and the SQL compiler rejects it while the static evaluator matches nothing.