diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e55f9494f..5eeaf97abe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 string-matches error output is affected, including the interactive REPL's printed error messages and all 7 language-binding repos (Python, Node, WASM, Java, Android, Swift, C). +- **`src/query/datalog/parser.rs` now carries real `PRS-0xx` codes instead of + falling back to `INT-000`** (#358, #277 2/6). All 79 documented `PRS-0xx` + codes are wired up via `bail_coded!`/`err_coded!` at every parser call site + that maps onto one; a parse error's `.code()` is now e.g. `"PRS-005"` + ("Unclosed list") instead of the generic `"INT-000"`, and its + `Display`/`to_string()` prefix changes to match. `parser.rs`'s internal + signatures changed from `Result<_, String>` to `anyhow::Result<_>` + (crate-internal only — the public `db.execute()`/`db.prepare()` surface is + unchanged, still `Result`). Two documented codes, + PRS-028 ("window expression cannot be empty") and PRS-049 ("unexpected end + of fact vector"), are wired up but unreachable through the public API — the + `has_over`/`len() >= 4` conditions that guard their call sites already + guarantee the "bad" case can't occur, so no input reaches them. This is a + pre-existing property of the parser logic, not something this PR changed. + Two static message strings changed wording to match their + `docs/ERROR_REFERENCE.md` "Error text" verbatim (previously drifted): + `"Retract argument must be a vector"` → `"...must be a vector of facts"` + (PRS-044). Anything that string-matches parser error output — including + the interactive REPL and all 7 language-binding repos — is affected by + both the code prefix and this wording change. - **Storage/file-format errors now surface their real `STG-0xx` code** (#359, part of #277's rollout): all 27 documented `STG-0xx` codes are wired up across `src/storage/{mod,persistent_facts,btree,btree_v6,packed_pages}.rs` diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index d17b08930c..8251872237 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -180,7 +180,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-002 Unexpected character -**Error text**: `Unexpected character: @` +**Error text**: `Unexpected character: {}` **Cause**: Tokeniser encountered a character not valid in Datalog/EDN. Common culprits: `@`, `#` outside a tagged literal, `\`, smart quotes. @@ -197,7 +197,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-003 Unexpected token -**Error text**: `Unexpected token: Keyword(":find")` +**Error text**: `Unexpected token: {}` **Cause**: Parser encountered a token in a position where it cannot appear. Often caused by missing/misplaced delimiter, or keyword where symbol/value expected. @@ -260,7 +260,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-007 String exceeds maximum length -**Error text**: `String exceeds maximum length of 4096 bytes` +**Error text**: `String exceeds maximum length of {} bytes` **Cause**: A string value in the input exceeds 4096 bytes. Minigraf limits string lengths to keep the parser bounded. @@ -276,7 +276,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-008 Keyword exceeds maximum length -**Error text**: `Keyword exceeds maximum length of 4096 bytes` +**Error text**: `Keyword exceeds maximum length of {} bytes` **Cause**: An attribute keyword in the input exceeds 4096 bytes. @@ -292,7 +292,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-009 Tagged literal exceeds maximum length -**Error text**: `Tagged literal exceeds maximum length of 4096 bytes` +**Error text**: `Tagged literal exceeds maximum length of {} bytes` **Cause**: The string inside a `#uuid "..."` or other tagged literal exceeds 4096 bytes. UUIDs are 36 characters; anything longer indicates a malformed input. @@ -323,7 +323,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-011 Unknown command -**Error text**: `Unknown command: upsert` +**Error text**: `Unknown command: {}` **Cause**: The opening symbol is not a recognised command. Check spelling. @@ -385,7 +385,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-015 :as-of counter must be non-negative -**Error text**: `:as-of counter must be non-negative, got -1` +**Error text**: `:as-of counter must be non-negative, got {}` **Cause**: Transaction counters start at 1. A negative integer was passed to `:as-of`. @@ -402,7 +402,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-016 :as-of must be integer or ISO 8601 string -**Error text**: `:as-of must be an integer (counter) or ISO 8601 string, got :now` +**Error text**: `:as-of must be an integer (counter) or ISO 8601 string, got {}` **Cause**: `:as-of` value is neither an integer transaction count nor an ISO 8601 timestamp string. @@ -434,7 +434,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-018 :valid-at must be ISO 8601 or :any-valid-time -**Error text**: `:valid-at must be an ISO 8601 string or :any-valid-time, got 42` +**Error text**: `:valid-at must be an ISO 8601 string or :any-valid-time, got {}` **Cause**: `:valid-at` value is not an ISO 8601 string or the special keyword `:any-valid-time`. @@ -450,7 +450,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-019 :valid-from must be ISO 8601 -**Error text**: `:valid-from must be an ISO 8601 string, got 42` +**Error text**: `:valid-from must be an ISO 8601 string, got {}` **Cause**: The `:valid-from` key in a fact's option map must be an ISO 8601 string, not an integer or keyword. @@ -466,7 +466,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-020 :valid-to must be ISO 8601 -**Error text**: `:valid-to must be an ISO 8601 string, got :forever` +**Error text**: `:valid-to must be an ISO 8601 string, got {}` **Cause**: The `:valid-to` key in a fact's option map must be an ISO 8601 string. @@ -501,7 +501,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-022 :with variable not bound in :where -**Error text**: `':with' variable ?x not bound in :where` +**Error text**: `':with' variable {} not bound in :where` **Cause**: A variable listed in `:with` does not appear in any `:where` pattern. @@ -519,7 +519,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-023 Aggregate variable not bound in :where -**Error text**: `Aggregate variable ?amount not bound in :where` +**Error text**: `Aggregate variable {} not bound in :where` **Cause**: An aggregate's input variable (e.g. `(sum ?amount)`) is not bound by any `:where` pattern. @@ -536,7 +536,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-024 Aggregate expression must have exactly 2 elements -**Error text**: `Aggregate expression must have exactly 2 elements (func ?var), got 3` +**Error text**: `Aggregate expression must have exactly 2 elements (func ?var), got {}` **Cause**: An aggregate expression in `:find` must be `(function ?variable)` — exactly two elements. @@ -553,7 +553,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-025 Aggregate function name must be a symbol -**Error text**: `Aggregate function name must be a symbol, got Keyword(":sum")` +**Error text**: `Aggregate function name must be a symbol, got {}` **Cause**: The aggregate function name must be an unqualified symbol, not a keyword. @@ -587,7 +587,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-027 Window function requires :over clause -**Error text**: `'rank' is a window function and requires an ':over (...)' clause` +**Error text**: `'{}' is a window function and requires an ':over (...)' clause` **Cause**: Window functions (`rank`, `row-number`, `dense-rank`, `ntile`, `percent-rank`, `cume-dist`) must be accompanied by an `:over` clause specifying ordering and/or partitioning. @@ -638,7 +638,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-030 lag/lead not supported in this version -**Error text**: `'lag' is not supported in this version; lag/lead are planned for a future release` +**Error text**: `'{}' is not supported in this version; lag/lead are planned for a future release` **Cause**: The `lag` and `lead` window functions are not yet implemented in this version. @@ -655,7 +655,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-031 Function is not window-compatible -**Error text**: `'sum' is not window-compatible and cannot be used with ':over'` +**Error text**: `'{}' is not window-compatible and cannot be used with ':over'` **Cause**: The named function is a plain aggregate, not a window function. Only `rank`, `row-number`, `dense-rank`, `ntile`, `percent-rank`, and `cume-dist` support `:over`. @@ -672,7 +672,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-032 Function requires variable argument before :over -**Error text**: `'ntile' requires a variable argument (starting with ?) before ':over'` +**Error text**: `'{}' requires a variable argument (starting with ?) before ':over'` **Cause**: `ntile` requires a variable and then an `:over` clause: `(ntile ?bucket :over (:order-by ?score))`. @@ -689,7 +689,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-033 Function requires :over after variable argument -**Error text**: `'ntile' requires ':over' after the variable argument` +**Error text**: `'{}' requires ':over' after the variable argument` **Cause**: `ntile` was given a variable but no `:over` clause followed. @@ -706,7 +706,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-034 Function requires :over immediately after function name -**Error text**: `'rank' requires ':over' immediately after the function name (no variable argument)` +**Error text**: `'{}' requires ':over' immediately after the function name (no variable argument)` **Cause**: `rank`, `row-number`, `dense-rank`, `percent-rank`, and `cume-dist` take no variable — they take `:over` directly. A variable was placed between the function name and `:over`. @@ -791,7 +791,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-039 Unknown option in :over clause -**Error text**: `unknown option in ':over' clause: ':ascending'` +**Error text**: `unknown option in ':over' clause: '{}'` **Cause**: An unrecognised keyword appeared inside the `:over` list. Valid options are `:order-by` and `:partition-by`. @@ -808,7 +808,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-040 Unexpected element in :over clause -**Error text**: `unexpected element in ':over' clause: Integer(5)` +**Error text**: `unexpected element in ':over' clause: {}` **Cause**: A non-keyword, non-variable element appeared inside the `:over` list. @@ -900,7 +900,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-046 Fact must have at least 3 elements (E A V) -**Error text**: `Fact must have at least 3 elements (E A V), got 2` +**Error text**: `Fact must have at least 3 elements (E A V), got {}` **Cause**: Each fact must supply at minimum an entity, an attribute, and a value. @@ -916,7 +916,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-047 Optional 4th fact element must be a map -**Error text**: `Optional 4th element of a fact must be a map {:valid-from ... :valid-to ...}, got "2024-01-01"` +**Error text**: `Optional 4th element of a fact must be a map {:valid-from ... :valid-to ...}, got {}` **Cause**: The 4th element of a fact vector is not a map. @@ -1065,7 +1065,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-056 (or-join) join variables must be logic variables -**Error text**: `(or-join) join variables must be logic variables, got Keyword(":e")` +**Error text**: `(or-join) join variables must be logic variables, got {}` **Cause**: Join variables in `(or-join [?e ...])` must start with `?`. @@ -1135,7 +1135,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-060 Expected pattern vector or rule invocation in :where clause -**Error text**: `Expected pattern vector or rule invocation in :where clause, got Keyword(":name")` +**Error text**: `Expected pattern vector or rule invocation in :where clause, got {}` **Cause**: Something other than a pattern vector `[...]` or a list-form clause appeared directly in `:where`. @@ -1152,7 +1152,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-061 Unexpected element in query -**Error text**: `Unexpected element in query: Keyword(":limit")` +**Error text**: `Unexpected element in query: {}` **Cause**: An unrecognised key appeared at the top level of the query map. @@ -1186,7 +1186,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-063 Expression head must be a symbol -**Error text**: `expression head must be a symbol, got Keyword(":+")` +**Error text**: `expression head must be a symbol, got {}` **Cause**: The first element of an expression must be a symbol naming a function, not a keyword. @@ -1203,7 +1203,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-064 Function takes exactly 1 argument -**Error text**: `abs takes exactly 1 argument` +**Error text**: `{} takes exactly 1 argument` **Cause**: A built-in operator that takes 1 argument was given a different number. @@ -1221,7 +1221,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-065 Function takes exactly 2 arguments -**Error text**: `+ takes exactly 2 arguments` +**Error text**: `{} takes exactly 2 arguments` **Cause**: A built-in operator that takes 2 arguments was given a different number. @@ -1256,7 +1256,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-067 Unknown expression operator -**Error text**: `unknown expression operator: floor-div` +**Error text**: `unknown expression operator: {}` **Cause**: An expression clause used a function name that Minigraf does not recognise. Built-in operators include: `+`, `-`, `*`, `/`, `mod`, `quot`, `abs`, `min`, `max`, `str`, `not`, `=`, `!=`, `<`, `<=`, `>`, `>=`, `matches?`, `starts-with?`, `ends-with?`, `contains?`. @@ -1274,7 +1274,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-068 Expression clause must be [(expr)] or [(expr) ?out] -**Error text**: `expression clause must be [(expr)] or [(expr) ?out], got 3 elements` +**Error text**: `expression clause must be [(expr)] or [(expr) ?out], got {} elements` **Cause**: An expression clause in `:where` must be a 1- or 2-element outer vector: `[(predicate)]` or `[(expr) ?out]`. A 3+ element outer vector is invalid. @@ -1291,7 +1291,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-069 Expression output must be a ?variable -**Error text**: `expression output must be a ?variable, got Keyword(":result")` +**Error text**: `expression output must be a ?variable, got {}` **Cause**: The output binding in `[(expr) ?out]` is not a logic variable starting with `?`. @@ -1308,7 +1308,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-070 Unsupported expression argument -**Error text**: `unsupported expression argument: Map({...})` +**Error text**: `unsupported expression argument: {}` **Cause**: An argument inside an expression is of a type that the expression engine cannot accept (e.g. a nested map or list). @@ -1358,7 +1358,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-073 Unknown tagged literal -**Error text**: `Unknown tagged literal: #base64` +**Error text**: `Unknown tagged literal: #{}` **Cause**: A `#tag "..."` form used an unrecognised tag. Only `#uuid` is supported. @@ -1374,7 +1374,7 @@ See the [Datalog Reference](../../.wiki/Datalog-Reference.md) for syntax guidanc ### PRS-074 Bind slot name exceeds maximum length -**Error text**: `Bind slot name exceeds maximum length of 4096 bytes` +**Error text**: `Bind slot name exceeds maximum length of {} bytes` **Cause**: A prepared-query bind slot name `$name` in a `prepare()` call exceeds 4096 bytes. @@ -1390,7 +1390,7 @@ $<4097-char-slot-name> ### PRS-075 Transact rejects unexpected trailing argument(s) -**Error text**: `transact takes (transact [facts]) or (transact {opts} [facts]); found N unexpected trailing argument(s) — the valid-time options map must come BEFORE the facts vector, not after` +**Error text**: `transact takes (transact [facts]) or (transact {opts} [facts]); found {} unexpected trailing argument(s) — the valid-time options map must come BEFORE the facts vector, not after` **Cause**: `(transact ...)` was called with more top-level arguments than it accepts — either extra tokens after the facts vector, or the valid-time options map placed after the facts vector instead of before it. Earlier parser versions silently dropped these extra arguments (and any `:valid-from`/`:valid-to` in a misplaced map); this is now a hard error. @@ -1407,7 +1407,7 @@ $<4097-char-slot-name> ### PRS-076 Retract rejects unexpected trailing argument(s) -**Error text**: `retract takes (retract [facts]); found N unexpected trailing argument(s)` +**Error text**: `retract takes (retract [facts]); found {} unexpected trailing argument(s)` **Cause**: `(retract ...)` was called with more than one top-level argument. `retract` only accepts a single facts vector — unlike `transact`, it does not accept a leading options map. @@ -1423,7 +1423,7 @@ $<4097-char-slot-name> ### PRS-077 Unexpected trailing input after a complete form -**Error text**: `unexpected trailing input after a complete form: {token}` +**Error text**: `unexpected trailing input after a complete form: {}` **Cause**: The top-level input contains a syntactically complete EDN form (e.g. a fully closed list or vector) followed by additional tokens. Earlier parser versions silently stopped after the first complete form instead of rejecting the extra input. @@ -1439,7 +1439,7 @@ $<4097-char-slot-name> ### PRS-078 Query rejects unexpected trailing argument(s) -**Error text**: `query takes (query [...]); found N unexpected trailing argument(s)` +**Error text**: `query takes (query [...]); found {} unexpected trailing argument(s)` **Cause**: `(query ...)` was called with more than one top-level argument. All query options (`:find`, `:where`, `:as-of`, `:max-results`, etc.) must appear as keywords *inside* the query vector, not as sibling arguments after it. Earlier parser versions silently dropped these trailing arguments. @@ -1455,7 +1455,7 @@ $<4097-char-slot-name> ### PRS-079 Rule rejects unexpected trailing argument(s) -**Error text**: `rule takes (rule [...]); found N unexpected trailing argument(s)` +**Error text**: `rule takes (rule [...]); found {} unexpected trailing argument(s)` **Cause**: `(rule ...)` was called with more than one top-level argument. A rule definition is a single vector containing the rule head and body patterns; nothing may follow it. diff --git a/src/db.rs b/src/db.rs index ac1e86ab28..ba8301f5d5 100644 --- a/src/db.rs +++ b/src/db.rs @@ -537,7 +537,7 @@ impl Minigraf { ); } - let cmd = parse_datalog_command(input).map_err(|e| anyhow::anyhow!("{}", e))?; + let cmd = parse_datalog_command(input)?; // Determine if this is a read-only command (query only). // Rule registration is treated as a write because it mutates the shared RuleRegistry. @@ -775,7 +775,7 @@ impl Minigraf { ) -> Result { use crate::query::datalog::prepared::prepare_query; - let cmd = parse_datalog_command(query_str).map_err(|e| anyhow::anyhow!("{}", e))?; + let cmd = parse_datalog_command(query_str)?; let query = match cmd { DatalogCommand::Query(q) => q, @@ -1068,7 +1068,7 @@ impl<'a> WriteTransaction<'a> { } fn execute_inner(&mut self, input: &str) -> Result { - let cmd = parse_datalog_command(input).map_err(|e| anyhow::anyhow!("{}", e))?; + let cmd = parse_datalog_command(input)?; match cmd { DatalogCommand::Transact(tx) => { diff --git a/src/error.rs b/src/error.rs index c38c017d0e..125abc5245 100644 --- a/src/error.rs +++ b/src/error.rs @@ -44,6 +44,85 @@ pub enum ErrorCategory { /// size goal (see PHILOSOPHY.md) affordable as the registry grows. #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum ErrorCode { + Prs001, + Prs002, + Prs003, + Prs004, + Prs005, + Prs006, + Prs007, + Prs008, + Prs009, + Prs010, + Prs011, + Prs012, + Prs013, + Prs014, + Prs015, + Prs016, + Prs017, + Prs018, + Prs019, + Prs020, + Prs021, + Prs022, + Prs023, + Prs024, + Prs025, + Prs026, + Prs027, + Prs028, + Prs029, + Prs030, + Prs031, + Prs032, + Prs033, + Prs034, + Prs035, + Prs036, + Prs037, + Prs038, + Prs039, + Prs040, + Prs041, + Prs042, + Prs043, + Prs044, + Prs045, + Prs046, + Prs047, + Prs048, + Prs049, + Prs050, + Prs051, + Prs052, + Prs053, + Prs054, + Prs055, + Prs056, + Prs057, + Prs058, + Prs059, + Prs060, + Prs061, + Prs062, + Prs063, + Prs064, + Prs065, + Prs066, + Prs067, + Prs068, + Prs069, + Prs070, + Prs071, + Prs072, + Prs073, + Prs074, + Prs075, + Prs076, + Prs077, + Prs078, + Prs079, Qry001, Qry002, Qry003, @@ -92,9 +171,482 @@ pub(crate) enum ErrorCode { /// Single source of truth: (code, code string, message template, category). /// /// The message template is verified against `docs/ERROR_REFERENCE.md`'s -/// "Error text" lines by the sync test in this module (added once real -/// codes exist in a follow-up category PR — see the design spec). +/// "Error text" lines by the sync test in this module. pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ + ( + ErrorCode::Prs001, + "PRS-001", + "Unexpected end of input", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs002, + "PRS-002", + "Unexpected character: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs003, + "PRS-003", + "Unexpected token: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs004, + "PRS-004", + "Unclosed vector", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs005, + "PRS-005", + "Unclosed list", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs006, + "PRS-006", + "Unterminated map: missing '}'", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs007, + "PRS-007", + "String exceeds maximum length of {} bytes", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs008, + "PRS-008", + "Keyword exceeds maximum length of {} bytes", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs009, + "PRS-009", + "Tagged literal exceeds maximum length of {} bytes", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs010, + "PRS-010", + "Expected command symbol", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs011, + "PRS-011", + "Unknown command: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs012, + "PRS-012", + "Expected a list starting with a command symbol", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs013, + "PRS-013", + "Query requires a map argument", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs014, + "PRS-014", + ":as-of requires a value", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs015, + "PRS-015", + ":as-of counter must be non-negative, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs016, + "PRS-016", + ":as-of must be an integer (counter) or ISO 8601 string, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs017, + "PRS-017", + ":valid-at requires a value", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs018, + "PRS-018", + ":valid-at must be an ISO 8601 string or :any-valid-time, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs019, + "PRS-019", + ":valid-from must be an ISO 8601 string, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs020, + "PRS-020", + ":valid-to must be an ISO 8601 string, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs021, + "PRS-021", + "':with' clause requires at least one aggregate in :find", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs022, + "PRS-022", + "':with' variable {} not bound in :where", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs023, + "PRS-023", + "Aggregate variable {} not bound in :where", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs024, + "PRS-024", + "Aggregate expression must have exactly 2 elements (func ?var), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs025, + "PRS-025", + "Aggregate function name must be a symbol, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs026, + "PRS-026", + "Aggregate argument must be a variable (starting with ?)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs027, + "PRS-027", + "'{}' is a window function and requires an ':over (...)' clause", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs028, + "PRS-028", + "window expression cannot be empty", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs029, + "PRS-029", + "window function name must be a symbol", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs030, + "PRS-030", + "'{}' is not supported in this version; lag/lead are planned for a future release", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs031, + "PRS-031", + "'{}' is not window-compatible and cannot be used with ':over'", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs032, + "PRS-032", + "'{}' requires a variable argument (starting with ?) before ':over'", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs033, + "PRS-033", + "'{}' requires ':over' after the variable argument", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs034, + "PRS-034", + "'{}' requires ':over' immediately after the function name (no variable argument)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs035, + "PRS-035", + "':over' must be followed by a list, e.g., (:order-by ?var)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs036, + "PRS-036", + "unexpected tokens after ':over' clause in window expression", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs037, + "PRS-037", + "':partition-by' requires a variable (starting with ?)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs038, + "PRS-038", + "':order-by' requires a variable (starting with ?)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs039, + "PRS-039", + "unknown option in ':over' clause: '{}'", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs040, + "PRS-040", + "unexpected element in ':over' clause: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs041, + "PRS-041", + "Transact requires a vector of facts", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs042, + "PRS-042", + "Transact argument must be a vector of facts", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs043, + "PRS-043", + "Retract requires a vector of facts", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs044, + "PRS-044", + "Retract argument must be a vector of facts", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs045, + "PRS-045", + "Each fact must be a vector [e a v] or [e a v {opts}]", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs046, + "PRS-046", + "Fact must have at least 3 elements (E A V), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs047, + "PRS-047", + "Optional 4th element of a fact must be a map {:valid-from ... :valid-to ...}, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs048, + "PRS-048", + "Transact with options requires a facts vector after the map", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs049, + "PRS-049", + "unexpected end of fact vector", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs050, + "PRS-050", + "Empty list in :where clause", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs051, + "PRS-051", + "(not ...) cannot appear inside another (not ...)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs052, + "PRS-052", + "(not) requires at least one clause", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs053, + "PRS-053", + "(or) requires at least one branch", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs054, + "PRS-054", + "(or-join) requires a join-vars vector and at least one branch", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs055, + "PRS-055", + "(or-join) first argument must be a vector of join variables", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs056, + "PRS-056", + "(or-join) join variables must be logic variables, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs057, + "PRS-057", + "all branches of (or ...) must introduce the same set of new variables", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs058, + "PRS-058", + "(and) inside or/or-join requires at least one clause", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs059, + "PRS-059", + "(not-join) requires a join-vars vector and at least one clause", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs060, + "PRS-060", + "Expected pattern vector or rule invocation in :where clause, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs061, + "PRS-061", + "Unexpected element in query: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs062, + "PRS-062", + "expression list cannot be empty", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs063, + "PRS-063", + "expression head must be a symbol, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs064, + "PRS-064", + "{} takes exactly 1 argument", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs065, + "PRS-065", + "{} takes exactly 2 arguments", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs066, + "PRS-066", + "matches? second argument must be a string literal", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs067, + "PRS-067", + "unknown expression operator: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs068, + "PRS-068", + "expression clause must be [(expr)] or [(expr) ?out], got {} elements", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs069, + "PRS-069", + "expression output must be a ?variable, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs070, + "PRS-070", + "unsupported expression argument: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs071, + "PRS-071", + "Expected UUID string after #uuid tag", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs072, + "PRS-072", + "Invalid UUID", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs073, + "PRS-073", + "Unknown tagged literal: #{}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs074, + "PRS-074", + "Bind slot name exceeds maximum length of {} bytes", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs075, + "PRS-075", + "transact takes (transact [facts]) or (transact {opts} [facts]); found {} unexpected trailing argument(s) — the valid-time options map must come BEFORE the facts vector, not after", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs076, + "PRS-076", + "retract takes (retract [facts]); found {} unexpected trailing argument(s)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs077, + "PRS-077", + "unexpected trailing input after a complete form: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs078, + "PRS-078", + "query takes (query [...]); found {} unexpected trailing argument(s)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs079, + "PRS-079", + "rule takes (rule [...]); found {} unexpected trailing argument(s)", + ErrorCategory::Parser, + ), ( ErrorCode::Qry001, "QRY-001", @@ -598,10 +1150,11 @@ mod tests { } /// Exhaustively verifies every `ErrorCode` variant resolves to a real - /// `REGISTRY` entry, not `registry_entry`'s INT-000 fallback. The `match` - /// below must list every `ErrorCode` variant explicitly (no `_` arm) so - /// that adding a new variant without also handling it here is a compile - /// error — the real exhaustiveness guarantee `registry_entry`'s + /// `REGISTRY` entry, not `registry_entry`'s INT-000 fallback: `ALL` is + /// checked at runtime, and `_assert_all_variants_covered`'s `match` must + /// list every `ErrorCode` variant explicitly (no `_` arm) so that adding + /// a new variant without also adding it to both `ALL` and that match is + /// a compile error — the real exhaustiveness guarantee `registry_entry`'s /// `debug_assert!` cannot provide on its own (it's compiled out in /// release builds, and `registry_is_a_subset_of_error_reference_doc` /// only walks `REGISTRY`, not `ErrorCode`). @@ -625,6 +1178,85 @@ mod tests { fn exhaustive(code: ErrorCode) { match code { ErrorCode::Int000 + | ErrorCode::Prs001 + | ErrorCode::Prs002 + | ErrorCode::Prs003 + | ErrorCode::Prs004 + | ErrorCode::Prs005 + | ErrorCode::Prs006 + | ErrorCode::Prs007 + | ErrorCode::Prs008 + | ErrorCode::Prs009 + | ErrorCode::Prs010 + | ErrorCode::Prs011 + | ErrorCode::Prs012 + | ErrorCode::Prs013 + | ErrorCode::Prs014 + | ErrorCode::Prs015 + | ErrorCode::Prs016 + | ErrorCode::Prs017 + | ErrorCode::Prs018 + | ErrorCode::Prs019 + | ErrorCode::Prs020 + | ErrorCode::Prs021 + | ErrorCode::Prs022 + | ErrorCode::Prs023 + | ErrorCode::Prs024 + | ErrorCode::Prs025 + | ErrorCode::Prs026 + | ErrorCode::Prs027 + | ErrorCode::Prs028 + | ErrorCode::Prs029 + | ErrorCode::Prs030 + | ErrorCode::Prs031 + | ErrorCode::Prs032 + | ErrorCode::Prs033 + | ErrorCode::Prs034 + | ErrorCode::Prs035 + | ErrorCode::Prs036 + | ErrorCode::Prs037 + | ErrorCode::Prs038 + | ErrorCode::Prs039 + | ErrorCode::Prs040 + | ErrorCode::Prs041 + | ErrorCode::Prs042 + | ErrorCode::Prs043 + | ErrorCode::Prs044 + | ErrorCode::Prs045 + | ErrorCode::Prs046 + | ErrorCode::Prs047 + | ErrorCode::Prs048 + | ErrorCode::Prs049 + | ErrorCode::Prs050 + | ErrorCode::Prs051 + | ErrorCode::Prs052 + | ErrorCode::Prs053 + | ErrorCode::Prs054 + | ErrorCode::Prs055 + | ErrorCode::Prs056 + | ErrorCode::Prs057 + | ErrorCode::Prs058 + | ErrorCode::Prs059 + | ErrorCode::Prs060 + | ErrorCode::Prs061 + | ErrorCode::Prs062 + | ErrorCode::Prs063 + | ErrorCode::Prs064 + | ErrorCode::Prs065 + | ErrorCode::Prs066 + | ErrorCode::Prs067 + | ErrorCode::Prs068 + | ErrorCode::Prs069 + | ErrorCode::Prs070 + | ErrorCode::Prs071 + | ErrorCode::Prs072 + | ErrorCode::Prs073 + | ErrorCode::Prs074 + | ErrorCode::Prs075 + | ErrorCode::Prs076 + | ErrorCode::Prs077 + | ErrorCode::Prs078 + | ErrorCode::Prs079 | ErrorCode::Qry001 | ErrorCode::Qry002 | ErrorCode::Qry003 @@ -672,6 +1304,85 @@ mod tests { for code in [ ErrorCode::Int000, + ErrorCode::Prs001, + ErrorCode::Prs002, + ErrorCode::Prs003, + ErrorCode::Prs004, + ErrorCode::Prs005, + ErrorCode::Prs006, + ErrorCode::Prs007, + ErrorCode::Prs008, + ErrorCode::Prs009, + ErrorCode::Prs010, + ErrorCode::Prs011, + ErrorCode::Prs012, + ErrorCode::Prs013, + ErrorCode::Prs014, + ErrorCode::Prs015, + ErrorCode::Prs016, + ErrorCode::Prs017, + ErrorCode::Prs018, + ErrorCode::Prs019, + ErrorCode::Prs020, + ErrorCode::Prs021, + ErrorCode::Prs022, + ErrorCode::Prs023, + ErrorCode::Prs024, + ErrorCode::Prs025, + ErrorCode::Prs026, + ErrorCode::Prs027, + ErrorCode::Prs028, + ErrorCode::Prs029, + ErrorCode::Prs030, + ErrorCode::Prs031, + ErrorCode::Prs032, + ErrorCode::Prs033, + ErrorCode::Prs034, + ErrorCode::Prs035, + ErrorCode::Prs036, + ErrorCode::Prs037, + ErrorCode::Prs038, + ErrorCode::Prs039, + ErrorCode::Prs040, + ErrorCode::Prs041, + ErrorCode::Prs042, + ErrorCode::Prs043, + ErrorCode::Prs044, + ErrorCode::Prs045, + ErrorCode::Prs046, + ErrorCode::Prs047, + ErrorCode::Prs048, + ErrorCode::Prs049, + ErrorCode::Prs050, + ErrorCode::Prs051, + ErrorCode::Prs052, + ErrorCode::Prs053, + ErrorCode::Prs054, + ErrorCode::Prs055, + ErrorCode::Prs056, + ErrorCode::Prs057, + ErrorCode::Prs058, + ErrorCode::Prs059, + ErrorCode::Prs060, + ErrorCode::Prs061, + ErrorCode::Prs062, + ErrorCode::Prs063, + ErrorCode::Prs064, + ErrorCode::Prs065, + ErrorCode::Prs066, + ErrorCode::Prs067, + ErrorCode::Prs068, + ErrorCode::Prs069, + ErrorCode::Prs070, + ErrorCode::Prs071, + ErrorCode::Prs072, + ErrorCode::Prs073, + ErrorCode::Prs074, + ErrorCode::Prs075, + ErrorCode::Prs076, + ErrorCode::Prs077, + ErrorCode::Prs078, + ErrorCode::Prs079, ErrorCode::Qry001, ErrorCode::Qry002, ErrorCode::Qry003, diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index d577549772..1a8dbad916 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -1,6 +1,8 @@ use super::types::*; +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::types::Value; use crate::temporal::parse_timestamp; +use anyhow::{Result, bail}; use uuid::Uuid; const MAX_STRING_LENGTH: usize = 1024 * 1024; // 1MB @@ -29,7 +31,7 @@ enum Token { } /// Tokenize EDN input -fn tokenize(input: &str) -> Result, String> { +fn tokenize(input: &str) -> Result> { let mut tokens = Vec::new(); let mut chars = input.chars().peekable(); @@ -88,10 +90,7 @@ fn tokenize(input: &str) -> Result, String> { } } else { if string.len() >= MAX_STRING_LENGTH { - return Err(format!( - "String exceeds maximum length of {} bytes", - MAX_STRING_LENGTH - )); + bail_coded!(ErrorCode::Prs007, MAX_STRING_LENGTH); } string.push(ch); chars.next(); @@ -109,10 +108,7 @@ fn tokenize(input: &str) -> Result, String> { // A keyword can never be a query variable, so there is no ambiguity. if ch.is_alphanumeric() || ch == '/' || ch == '-' || ch == '_' || ch == '?' { if keyword.len() >= MAX_KEYWORD_LENGTH { - return Err(format!( - "Keyword exceeds maximum length of {} bytes", - MAX_KEYWORD_LENGTH - )); + bail_coded!(ErrorCode::Prs008, MAX_KEYWORD_LENGTH); } keyword.push(ch); chars.next(); @@ -129,10 +125,7 @@ fn tokenize(input: &str) -> Result, String> { while let Some(&ch) = chars.peek() { if ch.is_alphanumeric() || ch == '-' { if tag.len() >= MAX_SYMBOL_LENGTH { - return Err(format!( - "Tagged literal exceeds maximum length of {} bytes", - MAX_SYMBOL_LENGTH - )); + bail_coded!(ErrorCode::Prs009, MAX_SYMBOL_LENGTH); } tag.push(ch); chars.next(); @@ -152,14 +145,14 @@ fn tokenize(input: &str) -> Result, String> { let mut num_str = String::from("-"); let (is_float, num) = parse_number(&mut chars, &mut num_str)?; if is_float { - let f: f64 = num - .parse() - .map_err(|_| format!("Float literal out of range: {}", num))?; + let f: f64 = num.parse().map_err(|_| { + anyhow::anyhow!("Float literal out of range: {}", num) + })?; tokens.push(Token::Float(f)); } else { - let i: i64 = num - .parse() - .map_err(|_| format!("Integer literal out of range: {}", num))?; + let i: i64 = num.parse().map_err(|_| { + anyhow::anyhow!("Integer literal out of range: {}", num) + })?; tokens.push(Token::Integer(i)); } } else { @@ -181,12 +174,12 @@ fn tokenize(input: &str) -> Result, String> { if is_float { let f: f64 = num .parse() - .map_err(|_| format!("Float literal out of range: {}", num))?; + .map_err(|_| anyhow::anyhow!("Float literal out of range: {}", num))?; tokens.push(Token::Float(f)); } else { let i: i64 = num .parse() - .map_err(|_| format!("Integer literal out of range: {}", num))?; + .map_err(|_| anyhow::anyhow!("Integer literal out of range: {}", num))?; tokens.push(Token::Integer(i)); } } @@ -196,10 +189,10 @@ fn tokenize(input: &str) -> Result, String> { while let Some(&ch) = chars.peek() { if ch.is_alphanumeric() || ch == '?' || ch == '_' || ch == '-' || ch == '/' { if symbol.len() >= MAX_SYMBOL_LENGTH { - return Err(format!( + bail!( "Symbol exceeds maximum length of {} bytes", MAX_SYMBOL_LENGTH - )); + ); } symbol.push(ch); chars.next(); @@ -233,7 +226,7 @@ fn tokenize(input: &str) -> Result, String> { chars.next(); tokens.push(Token::Symbol("!=".to_string())); } else { - return Err("Unexpected character: !".to_string()); + bail_coded!(ErrorCode::Prs002, '!'); } } // EDN line comment: skip from ';' to the next newline (or end of input) @@ -252,10 +245,7 @@ fn tokenize(input: &str) -> Result, String> { while let Some(&ch) = chars.peek() { if ch.is_alphanumeric() || ch == '_' || ch == '-' { if name.len() >= MAX_SYMBOL_LENGTH { - return Err(format!( - "Bind slot name exceeds maximum length of {} bytes", - MAX_SYMBOL_LENGTH - )); + bail_coded!(ErrorCode::Prs074, MAX_SYMBOL_LENGTH); } name.push(ch); chars.next(); @@ -264,15 +254,12 @@ fn tokenize(input: &str) -> Result, String> { } } if name.is_empty() { - return Err( - "Bind slot '$' must be followed by an identifier (e.g. $entity)" - .to_string(), - ); + bail!("Bind slot '$' must be followed by an identifier (e.g. $entity)"); } tokens.push(Token::BindSlot(name)); } _ => { - return Err(format!("Unexpected character: {}", ch)); + bail_coded!(ErrorCode::Prs002, ch); } } } @@ -283,7 +270,7 @@ fn tokenize(input: &str) -> Result, String> { fn parse_number( chars: &mut std::iter::Peekable, num_str: &mut String, -) -> Result<(bool, String), String> { +) -> Result<(bool, String)> { let mut is_float = false; while let Some(&ch) = chars.peek() { @@ -302,18 +289,15 @@ fn parse_number( Ok((is_float, num_str.clone())) } -fn parse_symbol( - chars: &mut std::iter::Peekable, - first: char, -) -> Result { +fn parse_symbol(chars: &mut std::iter::Peekable, first: char) -> Result { let mut symbol = String::from(first); while let Some(&ch) = chars.peek() { if ch.is_alphanumeric() || ch == '?' || ch == '_' || ch == '-' || ch == '/' { if symbol.len() >= MAX_SYMBOL_LENGTH { - return Err(format!( + bail!( "Symbol exceeds maximum length of {} bytes", MAX_SYMBOL_LENGTH - )); + ); } symbol.push(ch); chars.next(); @@ -350,7 +334,7 @@ impl Parser { Some(token) } - fn parse_map(&mut self) -> Result { + fn parse_map(&mut self) -> Result { self.advance(); // consume '{' let mut pairs = Vec::new(); @@ -364,24 +348,24 @@ impl Parser { pairs.push((key, val)); } - Err("Unterminated map: missing '}'".to_string()) + bail_coded!(ErrorCode::Prs006); } - fn parse_value(&mut self) -> Result { + fn parse_value(&mut self) -> Result { self.depth += 1; if self.depth > MAX_RECURSION_DEPTH { self.depth -= 1; - return Err(format!( + bail!( "Exceeded maximum recursion depth of {}", MAX_RECURSION_DEPTH - )); + ); } let result = self.parse_value_inner(); self.depth -= 1; result } - fn parse_value_inner(&mut self) -> Result { + fn parse_value_inner(&mut self) -> Result { match self.peek() { Some(Token::LeftParen) => self.parse_list(), Some(Token::LeftBracket) => self.parse_vector(), @@ -391,42 +375,42 @@ impl Parser { Ok(EdnValue::Keyword(k)) } else { // peek confirmed Keyword variant; advance should match - Err("internal parser error: expected keyword token".to_string()) + bail!("internal parser error: expected keyword token"); } } Some(Token::Symbol(_)) => { if let Some(Token::Symbol(s)) = self.advance() { Ok(EdnValue::Symbol(s)) } else { - Err("internal parser error: expected symbol token".to_string()) + bail!("internal parser error: expected symbol token"); } } Some(Token::String(_)) => { if let Some(Token::String(s)) = self.advance() { Ok(EdnValue::String(s)) } else { - Err("internal parser error: expected string token".to_string()) + bail!("internal parser error: expected string token"); } } Some(Token::Integer(_)) => { if let Some(Token::Integer(i)) = self.advance() { Ok(EdnValue::Integer(i)) } else { - Err("internal parser error: expected integer token".to_string()) + bail!("internal parser error: expected integer token"); } } Some(Token::Float(_)) => { if let Some(Token::Float(f)) = self.advance() { Ok(EdnValue::Float(f)) } else { - Err("internal parser error: expected float token".to_string()) + bail!("internal parser error: expected float token"); } } Some(Token::Boolean(_)) => { if let Some(Token::Boolean(b)) = self.advance() { Ok(EdnValue::Boolean(b)) } else { - Err("internal parser error: expected boolean token".to_string()) + bail!("internal parser error: expected boolean token"); } } Some(Token::TaggedLiteral(_)) => { @@ -436,16 +420,16 @@ impl Parser { if let Some(Token::String(uuid_str)) = self.advance() { match Uuid::parse_str(&uuid_str) { Ok(uuid) => Ok(EdnValue::Uuid(uuid)), - Err(_) => Err("Invalid UUID".to_string()), + Err(_) => bail_coded!(ErrorCode::Prs072), } } else { - Err("Expected UUID string after #uuid tag".to_string()) + bail_coded!(ErrorCode::Prs071); } } else { - Err(format!("Unknown tagged literal: #{}", tag)) + bail_coded!(ErrorCode::Prs073, tag); } } else { - Err("internal parser error: expected tagged literal token".to_string()) + bail!("internal parser error: expected tagged literal token"); } } Some(Token::Nil) => { @@ -456,15 +440,18 @@ impl Parser { if let Some(Token::BindSlot(name)) = self.advance() { Ok(EdnValue::BindSlot(name)) } else { - Err("internal parser error: expected bind slot token".to_string()) + bail!("internal parser error: expected bind slot token"); } } - Some(token) => Err(format!("Unexpected token: {:?}", token)), - None => Err("Unexpected end of input".to_string()), + Some(token) => { + let repr = format!("{:?}", token); + bail_coded!(ErrorCode::Prs003, repr); + } + None => bail_coded!(ErrorCode::Prs001), } } - fn parse_vector(&mut self) -> Result { + fn parse_vector(&mut self) -> Result { self.advance(); // consume [ let mut elements = Vec::new(); @@ -476,10 +463,10 @@ impl Parser { elements.push(self.parse_value()?); } - Err("Unclosed vector".to_string()) + bail_coded!(ErrorCode::Prs004); } - fn parse_list(&mut self) -> Result { + fn parse_list(&mut self) -> Result { self.advance(); // consume ( let mut elements = Vec::new(); @@ -491,26 +478,24 @@ impl Parser { elements.push(self.parse_value()?); } - Err("Unclosed list".to_string()) + bail_coded!(ErrorCode::Prs005); } } /// Parse EDN input into EdnValue -pub fn parse_edn(input: &str) -> Result { +pub fn parse_edn(input: &str) -> Result { let tokens = tokenize(input)?; let mut parser = Parser::new(tokens); let value = parser.parse_value()?; if let Some(token) = parser.peek() { - return Err(format!( - "unexpected trailing input after a complete form: {:?}", - token - )); + let repr = format!("{:?}", token); + bail_coded!(ErrorCode::Prs077, repr); } Ok(value) } /// Parse a Datalog command from EDN -pub fn parse_datalog_command(input: &str) -> Result { +pub fn parse_datalog_command(input: &str) -> Result { let edn = parse_edn(input)?; match edn { @@ -521,7 +506,7 @@ pub fn parse_datalog_command(input: &str) -> Result { let command = match &elements[0] { EdnValue::Symbol(s) => s.as_str(), EdnValue::Keyword(k) => k.as_str(), - _ => return Err("Expected command symbol".to_string()), + _ => bail_coded!(ErrorCode::Prs010), }; // SAFETY: elements has at least 1 element, so [1..] is valid (may be empty) @@ -532,16 +517,16 @@ pub fn parse_datalog_command(input: &str) -> Result { "transact" => parse_transact(rest), "retract" => parse_retract(rest), "rule" => parse_rule(rest), - _ => Err(format!("Unknown command: {}", command)), + _ => bail_coded!(ErrorCode::Prs011, command), } } - _ => Err("Expected a list starting with a command symbol".to_string()), + _ => bail_coded!(ErrorCode::Prs012), } } /// Parse an aggregate expression list: (func-name ?var) /// e.g., [Symbol("count"), Symbol("?e")] → FindSpec::Aggregate { "count", "?e" } -fn parse_aggregate(elems: &[EdnValue]) -> Result { +fn parse_aggregate(elems: &[EdnValue]) -> Result { // Detect window function: contains ":over" keyword anywhere in elems let has_over = elems .iter() @@ -551,10 +536,7 @@ fn parse_aggregate(elems: &[EdnValue]) -> Result { } if elems.len() != 2 { - return Err(format!( - "Aggregate expression must have exactly 2 elements (func ?var), got {}", - elems.len() - )); + bail_coded!(ErrorCode::Prs024, elems.len()); } // SAFETY: len == 2 check above guarantees indices 0 and 1 exist @@ -562,20 +544,15 @@ fn parse_aggregate(elems: &[EdnValue]) -> Result { let func_name = match &elems[0] { EdnValue::Symbol(s) => s.clone(), other => { - return Err(format!( - "Aggregate function name must be a symbol, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs025, repr); } }; const WINDOW_ONLY: &[&str] = &["avg", "rank", "row-number"]; if WINDOW_ONLY.contains(&func_name.as_str()) { - return Err(format!( - "'{}' is a window function and requires an ':over (...)' clause", - func_name - )); + bail_coded!(ErrorCode::Prs027, func_name); } // Unknown aggregate names are allowed — they are resolved at runtime as UDFs. // If no UDF with this name is registered, the executor returns an error. @@ -584,7 +561,7 @@ fn parse_aggregate(elems: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let var = match &elems[1] { EdnValue::Symbol(s) if s.starts_with('?') => s.clone(), - _ => return Err("Aggregate argument must be a variable (starting with ?)".to_string()), + _ => bail_coded!(ErrorCode::Prs026), }; Ok(FindSpec::Aggregate { @@ -596,23 +573,20 @@ fn parse_aggregate(elems: &[EdnValue]) -> Result { /// Parse a window function expression. /// Syntax: `(func ?var :over (:partition-by ?p :order-by ?o :desc))` /// For rank/row-number (no var): `(rank :over (:order-by ?o))` -fn parse_window_expr(elems: &[EdnValue]) -> Result { +fn parse_window_expr(elems: &[EdnValue]) -> Result { if elems.is_empty() { - return Err("window expression cannot be empty".into()); + bail_coded!(ErrorCode::Prs028); } // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] let func_name = match &elems[0] { EdnValue::Symbol(s) => s.as_str(), - _ => return Err("window function name must be a symbol".into()), + _ => bail_coded!(ErrorCode::Prs029), }; if matches!(func_name, "lag" | "lead") { - return Err(format!( - "'{}' is not supported in this version; lag/lead are planned for a future release", - func_name - )); + bail_coded!(ErrorCode::Prs030, func_name); } let func = match func_name { @@ -624,10 +598,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { "rank" => WindowFunc::Rank, "row-number" => WindowFunc::RowNumber, "count-distinct" | "sum-distinct" => { - return Err(format!( - "'{}' is not window-compatible and cannot be used with ':over'", - func_name - )); + bail_coded!(ErrorCode::Prs031, func_name); } other => WindowFunc::Udf(other.to_string()), }; @@ -637,10 +608,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { let (var, over_keyword_idx) = match func { WindowFunc::Rank | WindowFunc::RowNumber => { if !matches!(elems.get(1), Some(EdnValue::Keyword(k)) if k == ":over") { - return Err(format!( - "'{}' requires ':over' immediately after the function name (no variable argument)", - func_name - )); + bail_coded!(ErrorCode::Prs034, func_name); } (None, 1usize) } @@ -648,31 +616,25 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { let var = match elems.get(1) { Some(EdnValue::Symbol(s)) if s.starts_with('?') => s.clone(), _ => { - return Err(format!( - "'{}' requires a variable argument (starting with ?) before ':over'", - func_name - )); + bail_coded!(ErrorCode::Prs032, func_name); } }; if !matches!(elems.get(2), Some(EdnValue::Keyword(k)) if k == ":over") { - return Err(format!( - "'{}' requires ':over' after the variable argument", - func_name - )); + bail_coded!(ErrorCode::Prs033, func_name); } (Some(var), 2usize) } }; if over_keyword_idx + 2 != elems.len() { - return Err("unexpected tokens after ':over' clause in window expression".into()); + bail_coded!(ErrorCode::Prs036); } // Parse the :over clause list let over_list = match elems.get(over_keyword_idx + 1) { Some(EdnValue::List(l)) => l.as_slice(), _ => { - return Err("':over' must be followed by a list, e.g., (:order-by ?var)".to_string()); + bail_coded!(ErrorCode::Prs035); } }; @@ -684,7 +646,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { while j < over_list.len() { let item = over_list .get(j) - .ok_or_else(|| "unexpected end of :over clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of :over clause"))?; match item { EdnValue::Keyword(k) => match k.as_str() { ":partition-by" => { @@ -692,9 +654,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { partition_by = match over_list.get(j) { Some(EdnValue::Symbol(s)) if s.starts_with('?') => Some(s.clone()), _ => { - return Err( - "':partition-by' requires a variable (starting with ?)".into() - ); + bail_coded!(ErrorCode::Prs037); } }; } @@ -703,7 +663,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { order_by = match over_list.get(j) { Some(EdnValue::Symbol(s)) if s.starts_with('?') => Some(s.clone()), _ => { - return Err("':order-by' requires a variable (starting with ?)".into()); + bail_coded!(ErrorCode::Prs038); } }; } @@ -714,18 +674,19 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { order = Order::Asc; } other => { - return Err(format!("unknown option in ':over' clause: '{}'", other)); + bail_coded!(ErrorCode::Prs039, other); } }, other => { - return Err(format!("unexpected element in ':over' clause: {:?}", other)); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs040, repr); } } j += 1; } let order_by = - order_by.ok_or_else(|| "':order-by' is required in the ':over' clause".to_string())?; + order_by.ok_or_else(|| anyhow::anyhow!("':order-by' is required in the ':over' clause"))?; Ok(FindSpec::Window(WindowSpec { func, @@ -736,24 +697,21 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { })) } -fn parse_query(elements: &[EdnValue]) -> Result { +fn parse_query(elements: &[EdnValue]) -> Result { // Parse (query [:find ?x ?y :as-of N :valid-at "ts" :where [patterns...]]) if elements.is_empty() { - return Err("Query requires a map argument".to_string()); + bail_coded!(ErrorCode::Prs013); } if elements.len() > 1 { - return Err(format!( - "query takes (query [...]); found {} unexpected trailing argument(s)", - elements.len() - 1 - )); + bail_coded!(ErrorCode::Prs078, elements.len() - 1); } // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] let query_vector = elements[0] .as_vector() - .ok_or("Query argument must be a vector")?; + .ok_or_else(|| anyhow::anyhow!("Query argument must be a vector"))?; let mut find_specs: Vec = Vec::new(); let mut with_vars: Vec = Vec::new(); @@ -768,7 +726,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { while i < query_vector.len() { let current_item = query_vector .get(i) - .ok_or_else(|| "unexpected end of query vector".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of query vector"))?; if let Some(keyword) = current_item.as_keyword() { match keyword { ":as-of" => { @@ -776,26 +734,25 @@ fn parse_query(elements: &[EdnValue]) -> Result { i += 1; let as_of_val = query_vector .get(i) - .ok_or_else(|| ":as-of requires a value".to_string())?; + .ok_or_else(|| err_coded!(ErrorCode::Prs014))?; let as_of = match as_of_val { EdnValue::Integer(n) if *n >= 0 => { - let val = u64::try_from(*n) - .map_err(|_| ":as-of counter must be non-negative".to_string())?; + let val = u64::try_from(*n).map_err(|_| { + anyhow::anyhow!(":as-of counter must be non-negative") + })?; AsOf::Counter(val) } EdnValue::Integer(n) => { - return Err(format!(":as-of counter must be non-negative, got {}", n)); + bail_coded!(ErrorCode::Prs015, n); } EdnValue::String(s) => { - let ts = parse_timestamp(s).map_err(|e| e.to_string())?; + let ts = parse_timestamp(s)?; AsOf::Timestamp(ts) } EdnValue::BindSlot(name) => AsOf::Slot(name.clone()), other => { - return Err(format!( - ":as-of must be an integer (counter) or ISO 8601 string, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs016, repr); } }; query_as_of = Some(as_of); @@ -806,19 +763,17 @@ fn parse_query(elements: &[EdnValue]) -> Result { i += 1; let valid_at_val = query_vector .get(i) - .ok_or_else(|| ":valid-at requires a value".to_string())?; + .ok_or_else(|| err_coded!(ErrorCode::Prs017))?; let valid_at = match valid_at_val { EdnValue::String(s) => { - let ts = parse_timestamp(s).map_err(|e| e.to_string())?; + let ts = parse_timestamp(s)?; ValidAt::Timestamp(ts) } EdnValue::Keyword(k) if k == ":any-valid-time" => ValidAt::AnyValidTime, EdnValue::BindSlot(name) => ValidAt::Slot(name.clone()), other => { - return Err(format!( - ":valid-at must be an ISO 8601 string or :any-valid-time, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs018, repr); } }; query_valid_at = Some(valid_at); @@ -834,12 +789,12 @@ fn parse_query(elements: &[EdnValue]) -> Result { } ":max-derived-facts" => { if query_max_derived_facts.is_some() { - return Err("duplicate :max-derived-facts".to_string()); + bail!("duplicate :max-derived-facts"); } i += 1; let val = query_vector .get(i) - .ok_or_else(|| ":max-derived-facts requires a value".to_string())?; + .ok_or_else(|| anyhow::anyhow!(":max-derived-facts requires a value"))?; match val { EdnValue::Integer(n) if *n >= 1 => { #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] @@ -848,10 +803,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { } } EdnValue::Integer(_) => { - return Err(":max-derived-facts must be >= 1".to_string()); + bail!(":max-derived-facts must be >= 1"); } _other => { - return Err(":max-derived-facts must be a positive integer".to_string()); + bail!(":max-derived-facts must be a positive integer"); } } i += 1; @@ -859,12 +814,12 @@ fn parse_query(elements: &[EdnValue]) -> Result { } ":max-results" => { if query_max_results.is_some() { - return Err("duplicate :max-results".to_string()); + bail!("duplicate :max-results"); } i += 1; let val = query_vector .get(i) - .ok_or_else(|| ":max-results requires a value".to_string())?; + .ok_or_else(|| anyhow::anyhow!(":max-results requires a value"))?; match val { EdnValue::Integer(n) if *n >= 1 => { #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] @@ -873,10 +828,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { } } EdnValue::Integer(_) => { - return Err(":max-results must be >= 1".to_string()); + bail!(":max-results must be >= 1"); } _other => { - return Err(":max-results must be a positive integer".to_string()); + bail!(":max-results must be a positive integer"); } } i += 1; @@ -886,9 +841,9 @@ fn parse_query(elements: &[EdnValue]) -> Result { // Collect ?-prefixed symbols until the next keyword or end of vector i += 1; while i < query_vector.len() { - let with_item = query_vector - .get(i) - .ok_or_else(|| "unexpected end of query vector in :with".to_string())?; + let with_item = query_vector.get(i).ok_or_else(|| { + anyhow::anyhow!("unexpected end of query vector in :with") + })?; match with_item { EdnValue::Symbol(s) if s.starts_with('?') => { with_vars.push(s.clone()); @@ -896,10 +851,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { } EdnValue::Keyword(_) => break, other => { - return Err(format!( - "':with' clause accepts only variables, got {:?}", - other - )); + bail!("':with' clause accepts only variables, got {:?}", other); } } } @@ -922,10 +874,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { find_specs.push(parse_aggregate(elems)?); } other => { - return Err(format!( + bail!( "Expected variable or aggregate expression in :find clause, got {:?}", other - )); + ); } }, Some(":where") => { @@ -943,14 +895,13 @@ fn parse_query(elements: &[EdnValue]) -> Result { let clause = parse_list_as_where_clause(rule_list, true)?; where_clauses.push(clause); } else { - return Err(format!( - "Expected pattern vector or rule invocation in :where clause, got {:?}", - current_item - )); + let repr = format!("{:?}", current_item); + bail_coded!(ErrorCode::Prs060, repr); } } _ => { - return Err(format!("Unexpected element in query: {:?}", current_item)); + let repr = format!("{:?}", current_item); + bail_coded!(ErrorCode::Prs061, repr); } } @@ -971,12 +922,12 @@ fn parse_query(elements: &[EdnValue]) -> Result { if let FindSpec::Aggregate { var, .. } = spec && !outer_bound.contains(var) { - return Err(format!("Aggregate variable {} not bound in :where", var)); + bail_coded!(ErrorCode::Prs023, var); } } for var in &with_vars { if !outer_bound.contains(var) { - return Err(format!("':with' variable {} not bound in :where", var)); + bail_coded!(ErrorCode::Prs022, var); } } // :with without any aggregate is an error @@ -985,7 +936,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { .iter() .any(|s| matches!(s, FindSpec::Aggregate { .. })) { - return Err("':with' clause requires at least one aggregate in :find".to_string()); + bail_coded!(ErrorCode::Prs021); } let mut query = DatalogQuery::new(find_specs, where_clauses); @@ -997,10 +948,10 @@ fn parse_query(elements: &[EdnValue]) -> Result { Ok(DatalogCommand::Query(query)) } -fn parse_transact(elements: &[EdnValue]) -> Result { +fn parse_transact(elements: &[EdnValue]) -> Result { // Parse (transact [facts]) or (transact {opts} [facts]) if elements.is_empty() { - return Err("Transact requires a vector of facts".to_string()); + bail_coded!(ErrorCode::Prs041); } // SAFETY: is_empty() check above guarantees index 0 exists @@ -1010,42 +961,34 @@ fn parse_transact(elements: &[EdnValue]) -> Result { // Check if the first element is a map (transaction-level options) let (tx_valid_from, tx_valid_to, facts_element, consumed) = if first_element.is_map() { let map = first_element.as_map().ok_or_else(|| { - "internal error: is_map() true but as_map() returned None".to_string() + anyhow::anyhow!("internal error: is_map() true but as_map() returned None") })?; let (from, to) = parse_valid_time_map(map)?; - let facts_elem = elements.get(1).ok_or_else(|| { - "Transact with options requires a facts vector after the map".to_string() - })?; + let facts_elem = elements + .get(1) + .ok_or_else(|| err_coded!(ErrorCode::Prs048))?; (from, to, facts_elem, 2) } else { (None, None, first_element, 1) }; if elements.len() > consumed { - return Err(format!( - "transact takes (transact [facts]) or (transact {{opts}} [facts]); found {} \ - unexpected trailing argument(s) — the valid-time options map must come BEFORE \ - the facts vector, not after", - elements.len() - consumed - )); + bail_coded!(ErrorCode::Prs075, elements.len() - consumed); } let facts_vector = facts_element .as_vector() - .ok_or("Transact argument must be a vector of facts")?; + .ok_or_else(|| err_coded!(ErrorCode::Prs042))?; let mut patterns = Vec::new(); for fact in facts_vector { let fact_vec = fact .as_vector() - .ok_or("Each fact must be a vector [e a v] or [e a v {opts}]")?; + .ok_or_else(|| err_coded!(ErrorCode::Prs045))?; // A fact is [e a v] or [e a v {opts}] if fact_vec.len() < 3 { - return Err(format!( - "Fact must have at least 3 elements (E A V), got {}", - fact_vec.len() - )); + bail_coded!(ErrorCode::Prs046, fact_vec.len()); } // SAFETY: len >= 3 check above guarantees indices 0, 1, 2 exist @@ -1061,13 +1004,11 @@ fn parse_transact(elements: &[EdnValue]) -> Result { match fact_vec.get(3) { Some(EdnValue::Map(pairs)) => parse_valid_time_map(pairs)?, Some(other) => { - return Err(format!( - "Optional 4th element of a fact must be a map {{:valid-from ... :valid-to ...}}, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs047, repr); } None => { - return Err("unexpected end of fact vector".to_string()); + bail_coded!(ErrorCode::Prs049); } } } else { @@ -1095,9 +1036,7 @@ fn parse_transact(elements: &[EdnValue]) -> Result { /// Parse a valid-time map `{:valid-from "ts" :valid-to "ts"}` into millisecond timestamps. /// Both keys are optional. -fn parse_valid_time_map( - pairs: &[(EdnValue, EdnValue)], -) -> Result<(Option, Option), String> { +fn parse_valid_time_map(pairs: &[(EdnValue, EdnValue)]) -> Result<(Option, Option)> { let mut valid_from = None; let mut valid_to = None; @@ -1107,31 +1046,27 @@ fn parse_valid_time_map( let s = match val { EdnValue::String(s) => s, other => { - return Err(format!( - ":valid-from must be an ISO 8601 string, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs019, repr); } }; - valid_from = Some(parse_timestamp(s).map_err(|e| e.to_string())?); + valid_from = Some(parse_timestamp(s)?); } Some(":valid-to") => { let s = match val { EdnValue::String(s) => s, other => { - return Err(format!( - ":valid-to must be an ISO 8601 string, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs020, repr); } }; - valid_to = Some(parse_timestamp(s).map_err(|e| e.to_string())?); + valid_to = Some(parse_timestamp(s)?); } _ => { - return Err(format!( + bail!( "Unknown key in valid-time map: {:?}; expected :valid-from or :valid-to", key - )); + ); } } } @@ -1139,38 +1074,35 @@ fn parse_valid_time_map( Ok((valid_from, valid_to)) } -fn parse_retract(elements: &[EdnValue]) -> Result { +fn parse_retract(elements: &[EdnValue]) -> Result { // Same structure as transact if elements.is_empty() { - return Err("Retract requires a vector of facts".to_string()); + bail_coded!(ErrorCode::Prs043); } if elements.len() > 1 { - return Err(format!( - "retract takes (retract [facts]); found {} unexpected trailing argument(s)", - elements.len() - 1 - )); + bail_coded!(ErrorCode::Prs076, elements.len() - 1); } // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] let facts_vector = elements[0] .as_vector() - .ok_or("Retract argument must be a vector")?; + .ok_or_else(|| err_coded!(ErrorCode::Prs044))?; let mut patterns = Vec::new(); for fact in facts_vector { let fact_vec = fact .as_vector() - .ok_or("Each fact must be a vector [e a v]")?; - patterns.push(Pattern::from_edn(fact_vec)?); + .ok_or_else(|| anyhow::anyhow!("Each fact must be a vector [e a v]"))?; + patterns.push(Pattern::from_edn(fact_vec).map_err(anyhow::Error::msg)?); } Ok(DatalogCommand::Retract(Transaction::new(patterns))) } /// Convert a single EDN token to an Expr leaf, or recurse for a nested list. -fn parse_expr_arg(edn: &EdnValue) -> Result { +fn parse_expr_arg(edn: &EdnValue) -> Result { match edn { EdnValue::Symbol(s) if s.starts_with('?') => Ok(Expr::Var(s.clone())), EdnValue::Integer(n) => Ok(Expr::Lit(Value::Integer(*n))), @@ -1181,7 +1113,10 @@ fn parse_expr_arg(edn: &EdnValue) -> Result { EdnValue::Keyword(k) => Ok(Expr::Lit(Value::Keyword(k.clone()))), EdnValue::List(inner) => parse_expr(inner), EdnValue::BindSlot(name) => Ok(Expr::Slot(name.clone())), - other => Err(format!("unsupported expression argument: {:?}", other)), + other => { + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs070, repr); + } } } @@ -1189,22 +1124,25 @@ fn parse_expr_arg(edn: &EdnValue) -> Result { /// /// For `matches?`, the second argument must be a string literal and is /// validated as a valid regex pattern at parse time. -fn parse_expr(list: &[EdnValue]) -> Result { +fn parse_expr(list: &[EdnValue]) -> Result { if list.is_empty() { - return Err("expression list cannot be empty".to_string()); + bail_coded!(ErrorCode::Prs062); } // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] let head = match &list[0] { EdnValue::Symbol(s) => s.as_str(), - other => return Err(format!("expression head must be a symbol, got {:?}", other)), + other => { + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs063, repr); + } }; match head { // Unary type predicates "string?" | "integer?" | "float?" | "boolean?" | "nil?" => { if list.len() != 2 { - return Err(format!("{} takes exactly 1 argument", head)); + bail_coded!(ErrorCode::Prs064, head); } let op = match head { "string?" => UnaryOp::StringQ, @@ -1224,7 +1162,7 @@ fn parse_expr(list: &[EdnValue]) -> Result { "<" | ">" | "<=" | ">=" | "=" | "!=" | "+" | "-" | "*" | "/" | "starts-with?" | "ends-with?" | "contains?" | "matches?" => { if list.len() != 3 { - return Err(format!("{} takes exactly 2 arguments", head)); + bail_coded!(ErrorCode::Prs065, head); } // matches? second arg must be a string literal; compile regex early. if head == "matches?" { @@ -1235,8 +1173,9 @@ fn parse_expr(list: &[EdnValue]) -> Result { let rhs = parse_expr_arg(&list[2])?; match &rhs { Expr::Lit(Value::String(pattern)) => { - let compiled = regex_lite::Regex::new(pattern) - .map_err(|e| format!("invalid regex pattern {:?}: {}", pattern, e))?; + let compiled = regex_lite::Regex::new(pattern).map_err(|e| { + anyhow::anyhow!("invalid regex pattern {:?}: {}", pattern, e) + })?; let rhs_lit = Expr::Lit(Value::String(pattern.clone())); return Ok(Expr::BinOp( BinOp::Matches { @@ -1248,7 +1187,7 @@ fn parse_expr(list: &[EdnValue]) -> Result { )); } _ => { - return Err("matches? second argument must be a string literal".to_string()); + bail_coded!(ErrorCode::Prs066); } } } @@ -1288,7 +1227,7 @@ fn parse_expr(list: &[EdnValue]) -> Result { Box::new(arg), )) } else { - Err(format!("unknown expression operator: {}", other)) + bail_coded!(ErrorCode::Prs067, other); } } } @@ -1297,13 +1236,13 @@ fn parse_expr(list: &[EdnValue]) -> Result { /// Parse a vector clause whose first element is a list: `[(expr)]` or `[(expr) ?out]`. /// /// Called from `:where` dispatch when `vec[0]` is an `EdnValue::List`. -fn parse_expr_clause(vec: &[EdnValue]) -> Result { +fn parse_expr_clause(vec: &[EdnValue]) -> Result { let first = vec .first() - .ok_or_else(|| "parse_expr_clause called with empty vector".to_string())?; + .ok_or_else(|| anyhow::anyhow!("parse_expr_clause called with empty vector"))?; let inner_list = match first { EdnValue::List(l) => l.as_slice(), - _ => return Err("parse_expr_clause called with non-list element 0".to_string()), + _ => bail!("parse_expr_clause called with non-list element 0"), }; let expr = parse_expr(inner_list)?; let binding = match vec.len() { @@ -1311,22 +1250,17 @@ fn parse_expr_clause(vec: &[EdnValue]) -> Result { 2 => { let second = vec .get(1) - .ok_or_else(|| "unexpected end of expression clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of expression clause"))?; match second { EdnValue::Symbol(s) if s.starts_with('?') => Some(s.clone()), other => { - return Err(format!( - "expression output must be a ?variable, got {:?}", - other - )); + let repr = format!("{:?}", other); + bail_coded!(ErrorCode::Prs069, repr); } } } n => { - return Err(format!( - "expression clause must be [(expr)] or [(expr) ?out], got {} elements", - n - )); + bail_coded!(ErrorCode::Prs068, n); } }; Ok(WhereClause::Expr { expr, binding }) @@ -1334,9 +1268,9 @@ fn parse_expr_clause(vec: &[EdnValue]) -> Result { /// Parse a list item (EDN List) appearing in a :where clause or rule body. /// Returns Err if the list is empty, has an unknown form, or contains nested `not`. -fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { +fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { if list.is_empty() { - return Err("Empty list in :where clause".to_string()); + bail_coded!(ErrorCode::Prs050); } // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] @@ -1344,15 +1278,15 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { if !allow_not { - return Err("(not ...) cannot appear inside another (not ...)".to_string()); + bail_coded!(ErrorCode::Prs051); } if list.len() < 2 { - return Err("(not) requires at least one clause".to_string()); + bail_coded!(ErrorCode::Prs052); } let mut inner = Vec::new(); let rest = list .get(1..) - .ok_or_else(|| "unexpected end of not clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of not clause"))?; for item in rest { if let Some(vec) = item.as_vector() { if matches!(vec.first(), Some(EdnValue::List(_))) { @@ -1366,57 +1300,48 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { if !allow_not { - return Err( - "(not-join ...) cannot appear inside another (not ...) or (not-join ...)" - .to_string(), - ); + bail!("(not-join ...) cannot appear inside another (not ...) or (not-join ...)"); } // Syntax: (not-join [?v1 ?v2 ...] clause1 clause2 ...) if list.len() < 3 { - return Err( - "(not-join) requires a join-vars vector and at least one clause".to_string(), - ); + bail_coded!(ErrorCode::Prs059); } let join_var_vec = match list.get(1) { Some(EdnValue::Vector(v)) => v, _ => { - return Err( - "(not-join) first argument must be a vector of join variables".to_string(), - ); + bail!("(not-join) first argument must be a vector of join variables"); } }; let join_vars: Vec = join_var_vec .iter() .map(|v| match v { EdnValue::Symbol(s) if s.starts_with('?') => Ok(s.clone()), - _ => Err(format!( + _ => Err(anyhow::anyhow!( "(not-join) join variables must be logic variables, got {:?}", v )), }) - .collect::>()?; + .collect::>()?; let mut inner = Vec::new(); let rest = list .get(2..) - .ok_or_else(|| "unexpected end of not-join clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of not-join clause"))?; for item in rest { if let Some(vec) = item.as_vector() { if matches!(vec.first(), Some(EdnValue::List(_))) { @@ -1430,18 +1355,16 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result { if list.len() < 2 { - return Err("(or) requires at least one branch".to_string()); + bail_coded!(ErrorCode::Prs053); } let mut branches: Vec> = Vec::new(); let rest = list .get(1..) - .ok_or_else(|| "unexpected end of or clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of or clause"))?; for item in rest { let branch = parse_or_branch(item)?; branches.push(branch); @@ -1465,32 +1388,28 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { if list.len() < 3 { - return Err( - "(or-join) requires a join-vars vector and at least one branch".to_string(), - ); + bail_coded!(ErrorCode::Prs054); } let join_var_vec = match list.get(1) { Some(EdnValue::Vector(v)) => v, _ => { - return Err( - "(or-join) first argument must be a vector of join variables".to_string(), - ); + bail_coded!(ErrorCode::Prs055); } }; let join_vars: Vec = join_var_vec .iter() .map(|v| match v { EdnValue::Symbol(s) if s.starts_with('?') => Ok(s.clone()), - _ => Err(format!( - "(or-join) join variables must be logic variables, got {:?}", - v - )), + _ => { + let repr = format!("{:?}", v); + Err(err_coded!(ErrorCode::Prs056, repr)) + } }) - .collect::>()?; + .collect::>()?; let mut branches: Vec> = Vec::new(); let rest = list .get(2..) - .ok_or_else(|| "unexpected end of or-join clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of or-join clause"))?; for item in rest { let branch = parse_or_branch(item)?; branches.push(branch); @@ -1503,17 +1422,17 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { let args = list .get(1..) - .ok_or_else(|| "unexpected end of rule invocation".to_string())? + .ok_or_else(|| anyhow::anyhow!("unexpected end of rule invocation"))? .to_vec(); Ok(WhereClause::RuleInvocation { predicate: predicate.clone(), args, }) } - _ => Err(format!( + _ => bail!( "Rule invocation must start with predicate name (symbol), got {:?}", head - )), + ), } } @@ -1522,12 +1441,12 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result { +fn parse_query_pattern(vec: &[EdnValue]) -> Result { if vec.len() != 3 { - return Err(format!( + bail!( "Pattern must have exactly 3 elements (E A V), got {}", vec.len() - )); + ); } // SAFETY: len == 3 check above guarantees indices 0, 1, 2 exist @@ -1536,10 +1455,7 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { if let EdnValue::Keyword(k) = &vec[0] && PseudoAttr::from_keyword(k).is_some() { - return Err(format!( - "pseudo-attribute {} is not valid in entity position", - k - )); + bail!("pseudo-attribute {} is not valid in entity position", k); } // Reject :db/* in value position @@ -1547,10 +1463,7 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { if let EdnValue::Keyword(k) = &vec[2] && PseudoAttr::from_keyword(k).is_some() { - return Err(format!( - "pseudo-attribute {} is not valid in value position", - k - )); + bail!("pseudo-attribute {} is not valid in value position", k); } // Detect pseudo-attribute in attribute position @@ -1562,7 +1475,7 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { return Ok(Pattern::pseudo(vec[0].clone(), pseudo, vec[2].clone())); } - Pattern::from_edn(vec) + Pattern::from_edn(vec).map_err(anyhow::Error::msg) } /// Parse a single branch of an (or ...) or (or-join ...) clause. @@ -1570,18 +1483,18 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { /// A branch is either: /// - A single clause: `[pattern]` or `(rule-invocation)` or `[(expr)]` /// - A grouped list of clauses: `(and clause1 clause2 ...)` -fn parse_or_branch(item: &EdnValue) -> Result, String> { +fn parse_or_branch(item: &EdnValue) -> Result> { match item { EdnValue::List(inner) if matches!(inner.first(), Some(EdnValue::Symbol(s)) if s == "and") => { // (and clause1 clause2 ...) — multi-clause branch if inner.len() < 2 { - return Err("(and) inside or/or-join requires at least one clause".to_string()); + bail_coded!(ErrorCode::Prs058); } let mut clauses = Vec::new(); let rest = inner .get(1..) - .ok_or_else(|| "unexpected end of and clause".to_string())?; + .ok_or_else(|| anyhow::anyhow!("unexpected end of and clause"))?; for clause_item in rest { clauses.push(parse_or_branch_item(clause_item)?); } @@ -1595,7 +1508,7 @@ fn parse_or_branch(item: &EdnValue) -> Result, String> { } /// Parse a single clause item within an or branch. -fn parse_or_branch_item(item: &EdnValue) -> Result { +fn parse_or_branch_item(item: &EdnValue) -> Result { match item { EdnValue::Vector(vec) => { if matches!(vec.first(), Some(EdnValue::List(_))) { @@ -1608,7 +1521,7 @@ fn parse_or_branch_item(item: &EdnValue) -> Result { // allow_not=true: or branches can contain not/not-join/or/or-join parse_list_as_where_clause(inner_list, true) } - _ => Err(format!("expected clause inside or branch, got {:?}", item)), + _ => bail!("expected clause inside or branch, got {:?}", item), } } @@ -1697,15 +1610,15 @@ fn vars_in_not(clause: &WhereClause) -> Vec { fn check_not_safety( clauses: &[WhereClause], outer_bound: &std::collections::HashSet, -) -> Result<(), String> { +) -> Result<()> { for clause in clauses { if let WhereClause::Not(_) = clause { for var in vars_in_not(clause) { if !outer_bound.contains(&var) { - return Err(format!( + bail!( "variable {} in (not ...) is not bound by any outer clause", var - )); + ); } } } @@ -1719,15 +1632,15 @@ fn check_not_safety( fn check_not_join_safety( clauses: &[WhereClause], outer_bound: &std::collections::HashSet, -) -> Result<(), String> { +) -> Result<()> { for clause in clauses { if let WhereClause::NotJoin { join_vars, .. } = clause { for var in join_vars { if !var.starts_with("?_") && !outer_bound.contains(var) { - return Err(format!( + bail!( "join variable {} in (not-join ...) is not bound by any outer clause", var - )); + ); } } } @@ -1754,23 +1667,23 @@ fn expr_vars(expr: &Expr) -> Vec { /// an earlier clause. Binding-form Expr clauses add their output var to scope. /// /// Called for both query `:where` clauses and rule body clauses. -fn check_expr_safety(clauses: &[WhereClause]) -> Result<(), String> { +fn check_expr_safety(clauses: &[WhereClause]) -> Result<()> { check_expr_safety_with_bound(clauses, &mut std::collections::HashSet::new()) } fn check_expr_safety_with_bound( clauses: &[WhereClause], bound: &mut std::collections::HashSet, -) -> Result<(), String> { +) -> Result<()> { for clause in clauses { match clause { WhereClause::Expr { expr, binding } => { for var in expr_vars(expr) { if !bound.contains(&var) { - return Err(format!( + bail!( "variable {} in expression clause is not bound by any earlier clause", var - )); + ); } } if let Some(out) = binding { @@ -1802,10 +1715,7 @@ fn check_expr_safety_with_bound( // SAFETY: windows(2) yields slices of exactly 2 elements #[allow(clippy::indexing_slicing)] if branch_new_var_sets.windows(2).any(|w| w[0] != w[1]) { - return Err( - "all branches of (or ...) must introduce the same set of new variables" - .to_string(), - ); + bail_coded!(ErrorCode::Prs057); } if let Some(new_vars) = branch_new_var_sets.first() { for var in new_vars { @@ -1820,10 +1730,10 @@ fn check_expr_safety_with_bound( } => { for var in join_vars { if !var.starts_with("?_") && !bound.contains(var) { - return Err(format!( + bail!( "join variable {} in (or-join ...) is not bound by any earlier clause", var - )); + ); } } for branch in branches { @@ -1842,19 +1752,16 @@ fn check_expr_safety_with_bound( Ok(()) } -fn parse_rule(elements: &[EdnValue]) -> Result { +fn parse_rule(elements: &[EdnValue]) -> Result { // Rule syntax: (rule [(predicate ?args) [pattern1] [pattern2] ...]) // elements[0] = Vector with head (list) + body (patterns/rule calls) if elements.is_empty() { - return Err("Rule must have a body".to_string()); + bail!("Rule must have a body"); } if elements.len() > 1 { - return Err(format!( - "rule takes (rule [...]); found {} unexpected trailing argument(s)", - elements.len() - 1 - )); + bail_coded!(ErrorCode::Prs079, elements.len() - 1); } // Parse the rule body (single vector containing head + body patterns) @@ -1862,10 +1769,10 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let body_vec = elements[0] .as_vector() - .ok_or("Rule body must be a vector")?; + .ok_or_else(|| anyhow::anyhow!("Rule body must be a vector"))?; if body_vec.is_empty() { - return Err("Rule body cannot be empty".to_string()); + bail!("Rule body cannot be empty"); } // First element is the head (must be a list) @@ -1873,10 +1780,10 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let head_list = body_vec[0] .as_list() - .ok_or("Rule head must be a list: (predicate ?args)")?; + .ok_or_else(|| anyhow::anyhow!("Rule head must be a list: (predicate ?args)"))?; if head_list.is_empty() { - return Err("Rule head cannot be empty".to_string()); + bail!("Rule head cannot be empty"); } // Verify head starts with a symbol (predicate name) @@ -1884,7 +1791,7 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] match &head_list[0] { EdnValue::Symbol(_) => {} - _ => return Err("Rule head must start with a symbol (predicate name)".to_string()), + _ => bail!("Rule head must start with a symbol (predicate name)"), } // Rest of body_vec are patterns, rule invocations, or (not ...) clauses @@ -1905,15 +1812,15 @@ fn parse_rule(elements: &[EdnValue]) -> Result { let clause = parse_list_as_where_clause(list, true)?; body_clauses.push(clause); } else { - return Err(format!( + bail!( "Rule body clause must be a vector (pattern) or list (rule invocation / not), got {:?}", item - )); + ); } } if body_clauses.is_empty() { - return Err("Rule must have at least one pattern or rule invocation in body".to_string()); + bail!("Rule must have at least one pattern or rule invocation in body"); } // Safety check: variables in (not ...) must be bound by the rule head or outer body clauses @@ -1981,7 +1888,12 @@ mod tests { let long_string = "\"".to_string() + &"x".repeat(MAX_STRING_LENGTH + 1); let result = tokenize(&long_string); assert!(result.is_err()); - assert!(result.unwrap_err().contains("exceeds maximum length")); + assert!( + result + .unwrap_err() + .to_string() + .contains("exceeds maximum length") + ); } #[test] @@ -1989,7 +1901,12 @@ mod tests { let long_keyword = ":".to_string() + &"x".repeat(MAX_KEYWORD_LENGTH + 1); let result = tokenize(&long_keyword); assert!(result.is_err()); - assert!(result.unwrap_err().contains("exceeds maximum length")); + assert!( + result + .unwrap_err() + .to_string() + .contains("exceeds maximum length") + ); } #[test] @@ -1997,7 +1914,7 @@ mod tests { let deeply_nested = "(".repeat(10_000); let result = parse_edn(&deeply_nested); assert!(result.is_err()); - assert!(result.unwrap_err().contains("recursion depth")); + assert!(result.unwrap_err().to_string().contains("recursion depth")); } #[test] @@ -2034,7 +1951,12 @@ mod tests { let long_symbol = "x".repeat(MAX_SYMBOL_LENGTH + 1); let result = tokenize(&long_symbol); assert!(result.is_err()); - assert!(result.unwrap_err().contains("exceeds maximum length")); + assert!( + result + .unwrap_err() + .to_string() + .contains("exceeds maximum length") + ); } #[test] @@ -2042,7 +1964,12 @@ mod tests { let long_tag = "#".to_string() + &"x".repeat(MAX_SYMBOL_LENGTH + 1); let result = tokenize(&long_tag); assert!(result.is_err()); - assert!(result.unwrap_err().contains("exceeds maximum length")); + assert!( + result + .unwrap_err() + .to_string() + .contains("exceeds maximum length") + ); } #[test] @@ -2365,7 +2292,7 @@ mod tests { let result = parse_datalog_command("(query [:find ?n :as-of -1 :where [?e :person/name ?n]])"); assert!(result.is_err()); - assert!(result.unwrap_err().contains("non-negative")); + assert!(result.unwrap_err().to_string().contains("non-negative")); } #[test] @@ -2433,7 +2360,7 @@ mod tests { r#"(query [:find ?n :as-of "2024-01-15T10:00:00+05:30" :where [?e :person/name ?n]])"#, ); assert!(result.is_err()); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("timezone offsets are not supported"), "error was: {}", @@ -2466,7 +2393,7 @@ mod tests { r#"(transact [[:alice :employment/status :active]] {:valid-from "2023-01-01"})"#, ); assert!(result.is_err(), "expected a parse error"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("unexpected") || msg.contains("trailing"), "error should mention the unexpected trailing argument, was: {}", @@ -2553,7 +2480,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a :b] :max-derived-facts 0])"#; let result = parse_datalog_command(input); assert!(result.is_err(), "0 should be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains(":max-derived-facts must be >= 1"), "wrong error: {}", @@ -2566,7 +2493,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a :b] :max-results 0])"#; let result = parse_datalog_command(input); assert!(result.is_err(), "0 should be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains(":max-results must be >= 1"), "wrong error: {}", @@ -2580,7 +2507,7 @@ mod tests { r#"(query [:find ?x :where [?x :a :b] :max-derived-facts 100 :max-derived-facts 200])"#; let result = parse_datalog_command(input); assert!(result.is_err(), "duplicate key should be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("duplicate :max-derived-facts"), "wrong error: {}", @@ -2593,7 +2520,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a :b] :max-results 100 :max-results 200])"#; let result = parse_datalog_command(input); assert!(result.is_err(), "duplicate key should be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("duplicate :max-results"), "wrong error: {}", @@ -2606,7 +2533,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a :b] :max-derived-facts "a lot"])"#; let result = parse_datalog_command(input); assert!(result.is_err(), "non-integer should be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains(":max-derived-facts must be a positive integer"), "wrong error: {}", @@ -2619,7 +2546,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a :b] :max-results "a lot"])"#; let result = parse_datalog_command(input); assert!(result.is_err(), "non-integer should be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains(":max-results must be a positive integer"), "wrong error: {}", @@ -2636,7 +2563,7 @@ mod tests { result.is_err(), "trailing tokens after a complete form must be rejected" ); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("unexpected trailing input"), "wrong error: {}", @@ -2653,7 +2580,7 @@ mod tests { result.is_err(), "trailing tokens after a complete command must be rejected" ); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("unexpected trailing input"), "wrong error: {}", @@ -2671,7 +2598,7 @@ mod tests { result.is_err(), "extra trailing argument to query must be rejected, not silently ignored" ); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("unexpected trailing argument"), "wrong error: {}", @@ -2687,7 +2614,7 @@ mod tests { result.is_err(), "extra trailing argument to rule must be rejected, not silently ignored" ); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("unexpected trailing argument"), "wrong error: {}", @@ -2762,7 +2689,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a ?v] (not)])"#; let result = parse_datalog_command(input); assert!(result.is_err()); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!(msg.contains("requires at least one clause")); } @@ -2771,7 +2698,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a ?v] (not (not [?x :banned true]))])"#; let result = parse_datalog_command(input); assert!(result.is_err()); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!(msg.contains("cannot appear inside another")); } @@ -2781,7 +2708,7 @@ mod tests { let input = r#"(query [:find ?x :where [?x :a ?v] (not [?y :banned true])])"#; let result = parse_datalog_command(input); assert!(result.is_err()); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!(msg.contains("not bound")); } @@ -2791,7 +2718,7 @@ mod tests { let input = r#"(rule [(eligible ?x) [?x :applied true] (not [?y :banned true])])"#; let result = parse_datalog_command(input); assert!(result.is_err()); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!(msg.contains("not bound")); } @@ -2870,7 +2797,7 @@ mod tests { (not-join [?role] [?e :has-role ?role])])", ); assert!(result.is_err(), "unbound join var must be rejected"); - let msg = result.unwrap_err(); + let msg = result.unwrap_err().to_string(); assert!( msg.contains("?role") && msg.contains("not bound"), "error must name the offending variable" @@ -3061,6 +2988,7 @@ mod tests { assert!( result .unwrap_err() + .to_string() .contains("requires at least one aggregate"), "wrong error message" ); @@ -3071,13 +2999,16 @@ mod tests { let result = parse_datalog_command(r#"(query [:find (count ?unbound) :where [?e :a ?v]])"#); assert!(result.is_err(), "unbound aggregate var should fail"); assert!( - result.unwrap_err().contains("not bound in :where"), + result + .unwrap_err() + .to_string() + .contains("not bound in :where"), "wrong error message" ); } // Helper used by parse_expr tests (Task 2 / Phase 7.2b) - fn parse(s: &str) -> Result { + fn parse(s: &str) -> Result { parse_datalog_command(s) } @@ -3327,7 +3258,7 @@ mod tests { fn test_integer_overflow_returns_error() { let result = tokenize("99999999999999999999999999999"); assert!(result.is_err(), "i64 overflow must return error, not panic"); - let err = result.unwrap_err(); + let err = result.unwrap_err().to_string(); assert!( err.contains("out of range"), "error should mention out of range" @@ -3425,7 +3356,7 @@ mod or_parse_tests { cmd.is_err(), "should fail: branches introduce different vars" ); - let err = cmd.unwrap_err(); + let err = cmd.unwrap_err().to_string(); assert!(err.contains("same set of new variables")); } @@ -3438,7 +3369,7 @@ mod or_parse_tests { [?unbound :tag :red])])"#, ); assert!(cmd.is_err(), "should fail: unbound join var"); - let err = cmd.unwrap_err(); + let err = cmd.unwrap_err().to_string(); assert!(err.contains("not bound")); } @@ -3450,7 +3381,7 @@ mod or_parse_tests { (not (or [?e :a true] [?e :b true]))])"#, ); assert!(cmd.is_err(), "or inside not should be a parse error"); - let err = cmd.unwrap_err(); + let err = cmd.unwrap_err().to_string(); assert!(err.contains("or") || err.contains("not")); } } @@ -3522,7 +3453,7 @@ mod window_parse_tests { r#"(query [:find (lag ?v :over (:order-by ?v)) :where [?e :x ?v]])"#, ); assert!(result.is_err()); - assert!(result.unwrap_err().contains("not supported")); + assert!(result.unwrap_err().to_string().contains("not supported")); } #[test] @@ -3531,7 +3462,7 @@ mod window_parse_tests { r#"(query [:find (sum ?v :over (:partition-by ?p)) :where [?e :x ?v] [?e :y ?p]])"#, ); assert!(result.is_err()); - assert!(result.unwrap_err().contains("order-by")); + assert!(result.unwrap_err().to_string().contains("order-by")); } #[test] @@ -3540,7 +3471,13 @@ mod window_parse_tests { r#"(query [:find (count-distinct ?v :over (:order-by ?v)) :where [?e :x ?v]])"#, ); assert!(result.is_err()); - assert!(result.unwrap_err().to_lowercase().contains("window")); + assert!( + result + .unwrap_err() + .to_string() + .to_lowercase() + .contains("window") + ); } #[test] @@ -3594,7 +3531,7 @@ mod window_parse_tests { r#"(query [:find (lead ?v :over (:order-by ?v)) :where [?e :x ?v]])"#, ); assert!(result.is_err()); - assert!(result.unwrap_err().contains("not supported")); + assert!(result.unwrap_err().to_string().contains("not supported")); } #[test] diff --git a/tests/error_codes_foundation_test.rs b/tests/error_codes_foundation_test.rs index 3bf0cda027..60aa786737 100644 --- a/tests/error_codes_foundation_test.rs +++ b/tests/error_codes_foundation_test.rs @@ -23,11 +23,14 @@ fn open_nonexistent_directory_returns_coded_error() { #[test] fn execute_parse_error_returns_coded_error() { + // Migrated by the PRS category PR (#358): parser.rs errors now carry + // their real PRS-0xx code instead of falling back to INT-000. This + // input never finds a closing `)`, so it's PRS-005 (Unclosed list). let db = Minigraf::in_memory().unwrap(); let result = db.execute("(this is not valid datalog"); let err = result.expect_err("malformed input should fail to parse"); - assert_eq!(err.category(), ErrorCategory::Internal); - assert_eq!(err.code(), "INT-000"); + assert_eq!(err.category(), ErrorCategory::Parser); + assert_eq!(err.code(), "PRS-005"); } #[test] diff --git a/tests/error_codes_prs_test.rs b/tests/error_codes_prs_test.rs new file mode 100644 index 0000000000..0cd7d4e276 --- /dev/null +++ b/tests/error_codes_prs_test.rs @@ -0,0 +1,423 @@ +//! Regression tests for issue #358 (#277 2/6): PRS-0xx parser error codes. +//! +//! `src/query/datalog/parser.rs` now carries a real, documented `PRS-0xx` +//! code (see `docs/ERROR_REFERENCE.md`) on every reachable parse-error site, +//! via `bail_coded!`/`err_coded!`, instead of the generic `INT-000` fallback +//! from the #277 foundation PR (#357). +//! +//! Coverage: every PRS code that is actually reachable through the public +//! API is exercised here. Two documented codes — PRS-028 ("window +//! expression cannot be empty") and PRS-049 ("unexpected end of fact +//! vector") — are guarded by conditions that can never be false given how +//! their call sites are reached (the surrounding `has_over`/`len() >= 4` +//! checks already guarantee the "bad" case can't occur), so no input +//! reaches them; they are intentionally not tested here. That's a +//! pre-existing property of the parser logic, not something this PR +//! changed. + +use minigraf::{ErrorCategory, Minigraf}; + +fn db() -> Minigraf { + Minigraf::in_memory().unwrap() +} + +/// Execute `input` and assert the resulting `MinigrafError` carries +/// `expected_code` in the `Parser` category. +fn assert_execute_code(input: &str, expected_code: &str) { + let db = db(); + let result = db.execute(input); + let err = match result { + Err(e) => e, + Ok(_) => panic!( + "expected {} for input, but execute() succeeded: {}", + expected_code, input + ), + }; + assert_eq!( + err.category(), + ErrorCategory::Parser, + "expected Parser category for {}", + expected_code + ); + assert_eq!(err.code(), expected_code, "wrong code for input: {}", input); +} + +#[test] +fn prs_codes_cover_tokenizer_and_edn_errors() { + let cases: &[(&str, &str)] = &[ + ("", "PRS-001"), + ("@", "PRS-002"), + (")", "PRS-003"), + ("[1", "PRS-004"), + ("(this is not valid datalog", "PRS-005"), + ("{:a 1", "PRS-006"), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_007_string_exceeds_maximum_length() { + let long_string = "\"".to_string() + &"x".repeat(1_048_577) + "\""; + assert_execute_code(&long_string, "PRS-007"); +} + +#[test] +fn prs_008_keyword_exceeds_maximum_length() { + let long_keyword = ":".to_string() + &"x".repeat(1025); + assert_execute_code(&long_keyword, "PRS-008"); +} + +#[test] +fn prs_009_tagged_literal_exceeds_maximum_length() { + let long_tag = "#".to_string() + &"x".repeat(1025); + assert_execute_code(&long_tag, "PRS-009"); +} + +#[test] +fn prs_074_bind_slot_name_exceeds_maximum_length() { + let long_slot = "$".to_string() + &"x".repeat(1025); + assert_execute_code(&long_slot, "PRS-074"); +} + +#[test] +fn prs_codes_cover_command_dispatch() { + let cases: &[(&str, &str)] = &[ + ("(1 2 3)", "PRS-010"), + ("(bogus [1])", "PRS-011"), + ("42", "PRS-012"), + ("(query)", "PRS-013"), + ("(transact)", "PRS-041"), + ("(retract)", "PRS-043"), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_as_of_and_valid_at() { + let cases: &[(&str, &str)] = &[ + ("(query [:find ?e :where [?e :name ?n] :as-of])", "PRS-014"), + ( + "(query [:find ?e :where [?e :name ?n] :as-of -1])", + "PRS-015", + ), + ( + "(query [:find ?e :where [?e :name ?n] :as-of :now])", + "PRS-016", + ), + ( + "(query [:find ?e :where [?e :name ?n] :valid-at])", + "PRS-017", + ), + ( + "(query [:find ?e :where [?e :name ?n] :valid-at 42])", + "PRS-018", + ), + ( + r#"(transact {:valid-from 42} [[:alice :name "Alice"]])"#, + "PRS-019", + ), + ( + r#"(transact {:valid-to 42} [[:alice :name "Alice"]])"#, + "PRS-020", + ), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_with_and_aggregates() { + let cases: &[(&str, &str)] = &[ + ( + r#"(query [:find ?e ?name :with ?order :where [?e :name ?name] [?e :order ?order]])"#, + "PRS-021", + ), + ( + r#"(query [:find (count ?e) :with ?unbound :where [?e :name ?n]])"#, + "PRS-022", + ), + ( + r#"(query [:find (sum ?amount) :where [?e :name ?n]])"#, + "PRS-023", + ), + ( + r#"(query [:find (sum ?amount :distinct) :where [?e :a ?amount]])"#, + "PRS-024", + ), + ( + r#"(query [:find (:sum ?amount) :where [?e :a ?amount]])"#, + "PRS-025", + ), + (r#"(query [:find (sum 42) :where [?e :a ?v]])"#, "PRS-026"), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_window_functions() { + let cases: &[(&str, &str)] = &[ + ( + r#"(query [:find (rank ?score) :where [?e :score ?score]])"#, + "PRS-027", + ), + ( + r#"(query [:find (:rank :over (:order-by ?score)) :where [?e :score ?score]])"#, + "PRS-029", + ), + ( + r#"(query [:find (lag ?v :over (:order-by ?v)) :where [?e :x ?v]])"#, + "PRS-030", + ), + ( + r#"(query [:find (count-distinct ?v :over (:order-by ?v)) :where [?e :x ?v]])"#, + "PRS-031", + ), + ( + r#"(query [:find (ntile :over (:order-by ?score)) :where [?e :score ?score]])"#, + "PRS-032", + ), + ( + r#"(query [:find (ntile ?bucket ?extra :over (:order-by ?score)) :where [?e :score ?score]])"#, + "PRS-033", + ), + ( + r#"(query [:find (rank ?score :over (:order-by ?score)) :where [?e :score ?score]])"#, + "PRS-034", + ), + ( + r#"(query [:find (rank :over :order-by) :where [?e :score ?score]])"#, + "PRS-035", + ), + ( + r#"(query [:find (rank :over (:order-by ?score) :extra) :where [?e :score ?score]])"#, + "PRS-036", + ), + ( + r#"(query [:find (rank :over (:partition-by :dept :order-by ?score)) :where [?e :dept ?d] [?e :score ?score]])"#, + "PRS-037", + ), + ( + r#"(query [:find (rank :over (:order-by "score")) :where [?e :score ?score]])"#, + "PRS-038", + ), + ( + r#"(query [:find (rank :over (:order-by ?score :ascending)) :where [?e :score ?score]])"#, + "PRS-039", + ), + ( + r#"(query [:find (rank :over (:order-by ?score 5)) :where [?e :score ?score]])"#, + "PRS-040", + ), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_transact_and_retract_shape() { + let cases: &[(&str, &str)] = &[ + ("(transact :bogus)", "PRS-042"), + ("(retract :bogus)", "PRS-044"), + ("(transact [:not-a-vector])", "PRS-045"), + (r#"(transact [[:alice :name]])"#, "PRS-046"), + (r#"(transact [[:alice :name "Alice" "bogus"]])"#, "PRS-047"), + ( + r#"(transact {:valid-from "2023-01-01T00:00:00Z"})"#, + "PRS-048", + ), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_where_clause_structure() { + let cases: &[(&str, &str)] = &[ + (r#"(query [:find ?x :where [?x :a ?v] ()])"#, "PRS-050"), + ( + r#"(query [:find ?x :where [?x :a ?v] (not (not [?x :b true]))])"#, + "PRS-051", + ), + (r#"(query [:find ?x :where [?x :a ?v] (not)])"#, "PRS-052"), + (r#"(query [:find ?x :where [?x :a ?v] (or)])"#, "PRS-053"), + ( + r#"(query [:find ?x :where [?x :a ?v] (or-join)])"#, + "PRS-054", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] (or-join ?x [?x :b true])])"#, + "PRS-055", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] (or-join [:x] [?x :b true])])"#, + "PRS-056", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] (or [?x :b ?y] [?x :c ?z])])"#, + "PRS-057", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] (or (and) [?x :b true])])"#, + "PRS-058", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] (not-join)])"#, + "PRS-059", + ), + (r#"(query [:find ?x :where [?x :a ?v] 42])"#, "PRS-060"), + (r#"(query [42 :find ?x :where [?x :a ?v]])"#, "PRS-061"), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_expressions() { + let cases: &[(&str, &str)] = &[ + (r#"(query [:find ?x :where [?x :a ?v] [()]])"#, "PRS-062"), + ( + r#"(query [:find ?x :where [?x :a ?v] [(:+ ?v 1)]])"#, + "PRS-063", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [(string? ?v ?v)]])"#, + "PRS-064", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [?x :b ?w] [(+ ?v ?w 1)]])"#, + "PRS-065", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [?x :b ?w] [(matches? ?v ?w)]])"#, + "PRS-066", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [?x :b ?w] [(floor-div ?v ?w)]])"#, + "PRS-067", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [(< ?v 100) ?y :extra]])"#, + "PRS-068", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [(+ ?v 1) :result]])"#, + "PRS-069", + ), + ( + r#"(query [:find ?x :where [?x :a ?v] [(+ ?v {:x 1}) ?y]])"#, + "PRS-070", + ), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_tagged_literals() { + let cases: &[(&str, &str)] = &[ + (r#"(transact [[#uuid :bogus :name "Alice"]])"#, "PRS-071"), + ( + r#"(transact [[#uuid "not-a-valid-uuid" :name "Alice"]])"#, + "PRS-072", + ), + (r#"(transact [[:alice :data #base64 "hello"]])"#, "PRS-073"), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +#[test] +fn prs_codes_cover_trailing_argument_rejection() { + let cases: &[(&str, &str)] = &[ + ( + r#"(transact [[:alice :employment/status :active]] {:valid-from "2023-01-01T00:00:00Z"})"#, + "PRS-075", + ), + ( + r#"(retract [[:alice :employment/status :active]] {:valid-from "2023-01-01T00:00:00Z"})"#, + "PRS-076", + ), + ( + r#"(query [:find ?e :where [?e :a :b]]) garbage-trailing-tokens"#, + "PRS-077", + ), + ( + r#"(query [:find ?e :where [?e :a :b]] :max-results 5)"#, + "PRS-078", + ), + ( + r#"(rule [(reachable ?a ?b) [?a :edge ?b]] :unexpected-extra)"#, + "PRS-079", + ), + ]; + for (input, code) in cases { + assert_execute_code(input, code); + } +} + +// ── db.prepare() surfaces the same PRS codes as db.execute() ──────────────── + +fn assert_prepare_code(input: &str, expected_code: &str) { + let db = db(); + let result = db.prepare(input); + let err = match result { + Err(e) => e, + Ok(_) => panic!( + "expected {} for input, but prepare() succeeded: {}", + expected_code, input + ), + }; + assert_eq!( + err.category(), + ErrorCategory::Parser, + "expected Parser category for {}", + expected_code + ); + assert_eq!(err.code(), expected_code, "wrong code for input: {}", input); +} + +#[test] +fn prs_codes_reach_through_prepare() { + let cases: &[(&str, &str)] = &[ + ("", "PRS-001"), + ("(query)", "PRS-013"), + ("(query [:find ?e :where [?e :name ?n] :as-of])", "PRS-014"), + (r#"(query [:find ?x :where [?x :a ?v] 42])"#, "PRS-060"), + ( + r#"(query [:find ?x :where [?x :a ?v] [(:+ ?v 1)]])"#, + "PRS-063", + ), + ( + r#"(query [:find ?e :where [?e :a :b]] :max-results 5)"#, + "PRS-078", + ), + ]; + for (input, code) in cases { + assert_prepare_code(input, code); + } +} + +// ── Non-query commands still can't be prepared (API-0xx, not PRS) ────────── + +#[test] +fn prepare_rejects_transact_command_not_prs() { + let db = db(); + let result = db.prepare(r#"(transact [[:alice :name "Alice"]])"#); + let err = result.expect_err("transact should not be preparable"); + // This is an Api-category rejection (only query commands can be + // prepared), not a parser error — the input parses fine as a valid + // Transact command, it's just the wrong command kind for prepare(). + assert_ne!(err.category(), ErrorCategory::Parser); +}