(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Register = Catalog.Register module Value = Catalog.Value open Register open Semantics type affinity = Value_ops.affinity (* The [int64] value of an integer register ([Int] or [Bigint]). *) let i64_of m = match m.kind with Int -> Int64.of_int m.i | _ -> m.big (* An arithmetic result into [m]: a NaN is NULL, not a REAL. vdbe.c's arithmetic opcodes test sqlite3IsNaN on the double and jump to arithmetic_result_is_null rather than storing it, so [Inf - Inf] is NULL while [Inf * Inf] is the REAL Inf. The register spelling of {!Value_ops.real}. *) let set_arith_real m x = if Float.is_nan x then set_null m else set_real m x (* Truthiness for a WHERE/ON test (lang_expr.html sec.14): the register cast to NUMERIC as a [CAST] would cast it, true unless that is zero. NULL is unknown in SQL and false to a filter, which has to decide. *) let truth m = match m.kind with | Null -> false | Int -> m.i <> 0 | Bigint -> m.big <> 0L | Real -> m.r <> 0. | Text | Blob -> ( (* casting text to NUMERIC takes the longest prefix that reads as a number, so '5x' is true where 'abc', '' and '0' are false *) match Value_ops.leading_number m.s with | Value.Int 0L | Value.Float 0. -> false | _ -> true) (* The storage classes in sqlite3's order: NULL < numbers < text < blob. *) let kind_rank = function | Null -> 0 | Int | Bigint | Real -> 1 | Text -> 2 | Blob -> 3 let num_of m = match m.kind with | Int -> float_of_int m.i | Bigint -> Int64.to_float m.big | _ -> m.r (* Comparison of two registers as sqlite3 orders them: two numbers numerically, two strings or blobs by bytes, otherwise by storage class. The result is the usual [-1/0/1]; callers handle NULL separately for SQL's three-valued logic. *) let compare a b = match (a.kind, b.kind) with | Int, Int -> Int.compare a.i b.i | (Int | Bigint), (Int | Bigint) -> Int64.compare (i64_of a) (i64_of b) | (Int | Bigint), Real -> Value.int_float_compare (i64_of a) b.r | Real, (Int | Bigint) -> -Value.int_float_compare (i64_of b) a.r | Real, Real -> Float.compare a.r b.r | Text, Text | Blob, Blob -> String.compare a.s b.s | _ -> Int.compare (kind_rank a.kind) (kind_rank b.kind) (* Compare under a comparison's affinity -- the ONE character {!Value_ops.compare_affinity} computes for the pair, applied to both registers as [OP_Eq]..[OP_Ge] apply P5 (vdbe.c) before sqlite3MemCompare: - a numeric affinity reads a text register as the number it spells, so [c = '2.0625'] matches a numeric column [c]. Text spelling no whole number stays text and keeps its place above every number. - [`Text] renders a numeric register as text, and only when the other register is already text: the C tests MEM_Str on either operand first, so two numbers under TEXT affinity still compare as numbers. - [`Blob] and no affinity convert nothing. This is the case a per-operand "is a column" flag could not reach: an undeclared column carries BLOB affinity, and a comparison against one converts neither end. A blob register is a string to neither rule: applyAffinity reaches applyNumericAffinity through a [MEM_Str] test and sqlite3VdbeMemStringify is guarded by the same, so a blob keeps its class whatever its bytes spell. The number a text register spells comes from {!Value_ops.whole_number}, the one reader of sqlite3's numeric grammar, so the VM and the value layer agree on what a number is -- and text spelling an integer becomes an INTEGER, which a real register then orders against by {!Value.int_float_compare} rather than by widening it. sqlite3 does the same: applyNumericAffinity makes such text a MEM_Int, and sqlite3MemCompare pairs it with a MEM_Real through sqlite3IntFloatCompare. *) let num_vs_text num txt = let int_reg = match num.kind with Int | Bigint -> true | _ -> false in match Value_ops.whole_number txt.s with | Some (Value.Int i) when int_reg -> Int64.compare (i64_of num) i | Some (Value.Float f) when int_reg -> Value.int_float_compare (i64_of num) f | Some (Value.Int i) -> -Value.int_float_compare i num.r | Some (Value.Float f) -> Float.compare num.r f | _ -> compare num txt (* Two text registers under a numeric affinity: each becomes the number it spells, and one that spells none stays text -- which orders above every number, so the coerced side is the smaller. *) let text_vs_text a b = match (Value_ops.whole_number a.s, Value_ops.whole_number b.s) with | Some x, Some y -> Value.compare x y | Some _, None -> -1 | None, Some _ -> 1 | None, None -> String.compare a.s b.s let text_of_num m = Value_ops.text_of_value (Register.to_value m) let compare_with aff a b = match aff with | Some (`Numeric | `Integer | `Real) -> ( match (a.kind, b.kind) with | (Int | Bigint | Real), Text -> num_vs_text a b | Text, (Int | Bigint | Real) -> -num_vs_text b a | Text, Text -> text_vs_text a b | _ -> compare a b) | Some `Text -> ( match (a.kind, b.kind) with | (Int | Bigint | Real), Text -> String.compare (text_of_num a) b.s | Text, (Int | Bigint | Real) -> String.compare a.s (text_of_num b) | _ -> compare a b) | Some `Blob | None -> compare a b (* A constant operand converted once: under a numeric affinity a text that spells a number becomes it, so a text it leaves spells none, and orders above every number and against another text by bytes (text_vs_text). *) let settles = function | Some (`Numeric | `Integer | `Real) -> true | Some (`Text | `Blob) | None -> false let settle aff m = match aff with | Some (`Numeric | `Integer | `Real) -> ( match m.kind with | Text -> ( match Value_ops.whole_number m.s with | Some v -> Register.set_value m v | None -> ()) | Null | Int | Bigint | Real | Blob -> ()) | Some (`Text | `Blob) | None -> () let compare_settled aff a b = match (b.kind, aff) with | Text, Some (`Numeric | `Integer | `Real) -> ( match a.kind with | Int | Bigint | Real -> -1 | Text -> if Value_ops.spells_number a.s ~first:0 ~length:(String.length a.s) then -1 else String.compare a.s b.s | Null | Blob -> compare a b) | _ -> compare_with aff a b (* The numeric affinity of a text/blob register for arithmetic, matching {!Value_ops.numeric_affinity}: the integer or real the text spells (integer when it has no fractional/exponent part), or 0 when not numeric. Tagged so the caller keeps integer op integer in the integer domain. Only the rare text-operand path allocates this variant; integer/real arithmetic never does. *) let num_affinity m = match m.kind with | Int -> `I (Int64.of_int m.i) | Bigint -> `I m.big | Real -> `R m.r | Null -> `I 0L (* unreachable: the caller checks NULL first *) | Text | Blob -> ( (* SQLite reads a text operand by its leading numeric prefix ([5x] is 5), not a strict parse. *) match Value_ops.leading_number m.s with | Value.Int i -> `I i | Value.Float f -> `R f | _ -> `I 0L) let as_float = function `I i -> Int64.to_float i | `R f -> f (* The numeric operators in [int64] with sqlite3's overflow rule: an [int64] sum/ difference/product that overflows becomes real, otherwise it stays integer (stored as a native [Int] or a wide [Bigint]); integer [/] truncates toward zero, [/] by zero is NULL, and the one quotient that overflows, the smallest [int64] by -1, is real (vdbe.c, OP_Divide: "if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math"). *) let arith_i64 op dst x y = match op with | Add -> let r = Int64.add x y in if x >= 0L = (y >= 0L) && r >= 0L <> (x >= 0L) then set_real dst (Int64.to_float x +. Int64.to_float y) else set_int64 dst r | Sub -> let r = Int64.sub x y in if x >= 0L <> (y >= 0L) && r >= 0L <> (x >= 0L) then set_real dst (Int64.to_float x -. Int64.to_float y) else set_int64 dst r | Mul -> let r = Int64.mul x y in let overflow = x <> 0L && ((x = -1L && y = Int64.min_int) || Int64.div r x <> y) in if overflow then set_real dst (Int64.to_float x *. Int64.to_float y) else set_int64 dst r | Div -> if y = 0L then set_null dst else if y = -1L && x = Int64.min_int then set_real dst (Int64.to_float x /. Int64.to_float y) else set_int64 dst (Int64.div x y) | Mod | Band | Bor | Shl | Shr -> assert false (* handled by arith_bits *) (* The slow arithmetic path: at least one text/blob (or wide) operand, coerced by numeric affinity. Integer (in [int64], with overflow to real) when both coerce to integers, otherwise real. Allocates the affinity variant, but a scan over native integer or real columns never reaches here. *) let arith_text op dst a b = match (num_affinity a, num_affinity b) with | `I x, `I y -> arith_i64 op dst x y | na, nb -> ( let x = as_float na and y = as_float nb in match op with | Add -> set_arith_real dst (x +. y) | Sub -> set_arith_real dst (x -. y) | Mul -> set_arith_real dst (x *. y) | Div -> if y = 0. then set_null dst else set_arith_real dst (x /. y) | Mod | Band | Bor | Shl | Shr -> assert false (* handled by arith_bits *) ) (* The integer value of a register for [%]/bitwise, matching {!Value_ops.intify}: an integer passes through, a real truncates toward zero and is held to the int64 range, and text is its leading integer (0 when there is none). *) let intify_mem m = match m.kind with | Int -> Int64.of_int m.i | Bigint -> m.big | Real -> Value_ops.intify (Value.Float m.r) | Null -> 0L (* unreachable: the caller checks NULL first *) | Text | Blob -> Value_ops.leading_integer m.s (* Does a register carry REAL affinity (for [%]'s result type): a real, or text that spells a real but not an integer. Matches {!Value_ops.is_real}. *) let is_real_mem m = match m.kind with | Real -> true | Int | Bigint | Null -> false | Text | Blob -> ( match Value_ops.leading_number m.s with | Value.Float _ -> true | _ -> false) (* The integer-domain operators [%], [&], [|], [<<], [>>]: operands coerced to integers; [%] by zero is NULL and yields a real when either operand is real, the bitwise/shift ops always yield an integer. Computed in Int64; only these rare ops pay it, never a numeric scan. *) let arith_bits op dst a b = let x = intify_mem a and y = intify_mem b in match op with | Band -> set_int64 dst (Int64.logand x y) | Bor -> set_int64 dst (Int64.logor x y) | Shl -> set_int64 dst (Value_ops.shift `Left x y) | Shr -> set_int64 dst (Value_ops.shift `Right x y) | Mod -> if y = 0L then set_null dst else let r = Int64.rem x y in if is_real_mem a || is_real_mem b then set_real dst (Int64.to_float r) else set_int64 dst r | Add | Sub | Mul | Div -> assert false (* handled by arith *) (* The numeric operators [+]/[-]/[*]/[/]: integer when both operands carry integer affinity ([/] truncates toward zero, [/] by zero is NULL), otherwise real. The int-int and all-numeric cases are matched on [kind] directly so they allocate nothing; a text operand takes the affinity path. *) let arith_num op dst a b = match (a.kind, b.kind) with (* the common native-int path stays unboxed; it only re-does the operation in [int64] (with overflow to real) when the native result overflows 63 bits, so a sum/product exceeding the native range still matches the frontend's own arithmetic *) | Int, Int -> ( let x = a.i and y = b.i in let i64 () = arith_i64 op dst (Int64.of_int x) (Int64.of_int y) in match op with | Add -> let r = x + y in if x >= 0 = (y >= 0) && r >= 0 <> (x >= 0) then i64 () else set_int dst r | Sub -> let r = x - y in if x >= 0 <> (y >= 0) && r >= 0 <> (x >= 0) then i64 () else set_int dst r | Mul -> let r = x * y in if x <> 0 && (r / x <> y || (x = -1 && y = min_int)) then i64 () else set_int dst r | Div -> if y = 0 then set_null dst else if y = -1 && x = min_int then i64 () else set_int dst (x / y) | _ -> assert false) (* any integer operand wide enough to be a [Bigint] goes through [int64] *) | (Int | Bigint), (Int | Bigint) -> arith_i64 op dst (i64_of a) (i64_of b) | (Int | Bigint | Real), (Int | Bigint | Real) -> ( let x = num_of a and y = num_of b in match op with | Add -> set_arith_real dst (x +. y) | Sub -> set_arith_real dst (x -. y) | Mul -> set_arith_real dst (x *. y) | Div -> if y = 0. then set_null dst else set_arith_real dst (x /. y) | _ -> assert false) | _ -> arith_text op dst a b (* sqlite3 arithmetic into [dst]: NULL if either operand is NULL; otherwise the numeric operators go to {!arith_num} and the integer-domain operators ([%], bitwise) to {!arith_bits}. *) let arith op dst a b = if Register.is_null a || Register.is_null b then set_null dst else match op with | Mod | Band | Bor | Shl | Shr -> arith_bits op dst a b | Add | Sub | Mul | Div -> arith_num op dst a b type collation = Collation.t type op = Like | Glob | Concat | Json_get | Json_get_text type action = Ignore | Abort | Fail | Rollback let collate = Value_ops.compare_values_coll let key = Collation.key let ast_cmp : Semantics.cmp -> Ast.binop = function | Eq -> Eq | Ne -> Neq | Lt -> Lt | Le -> Le | Gt -> Gt | Ge -> Ge let compare_value op aff coll a b = Value_op.compare_op ?aff ?coll (ast_cmp op) a b let is_eq aff coll a b = Value_ops.is_value ?aff ?coll a b let in_list aff coll v cands = Value_op.in_list_value ?aff ?coll v cands let and_ a b = Value_ops.(value_of_tri (tri_and (tri_of a) (tri_of b))) let or_ a b = Value_ops.(value_of_tri (tri_or (tri_of a) (tri_of b))) let not_ = Value_ops.not_value let ast_op : op -> Ast.binop = function | Like -> Like | Glob -> Glob | Concat -> Concat | Json_get -> Json_get | Json_get_text -> Json_get_text let op_value op a b = Value_op.binop_value (ast_op op) a b (* sqlite3 codes [LIKE], [GLOB] and the JSON accessors as function calls and [||] as OP_Concat (expr.c) *) let op_calls = function | Like | Glob | Json_get | Json_get_text -> true | Concat -> false let deterministic = Func.deterministic let aggregate = Json1.aggregate let by_class aff (k : Register.kind) = match (k, aff) with | (Int | Real | Blob), _ | Text, (None | Some (`Blob | `Text)) -> true | Text, Some (`Numeric | `Integer | `Real) | (Null | Bigint), _ -> false let above_numbers aff s = match aff with | Some (`Numeric | `Integer | `Real) -> Option.is_none (Value_ops.whole_number s) | None | Some (`Blob | `Text) -> false let spells_number = Value_ops.spells_number let stores_reals = function | `Real -> true | `Numeric | `Integer | `Text | `Blob -> false module Sum = Value_ops.Sum let to_int64 (v : Value.t) = match v with | Int n -> n | Null -> 0L | Float _ -> Value_ops.intify v | Text _ | Blob _ -> ( match Value_ops.cast "INTEGER" v with Int n -> n | _ -> 0L) let to_float (v : Value.t) = match v with | Float f -> f | Int n -> Int64.to_float n | Null -> 0. | Text _ | Blob _ -> ( match Value_ops.cast "REAL" v with Float f -> f | _ -> 0.) let to_text (v : Value.t) = match v with | Text s | Blob s -> s | Null -> "" | Int _ | Float _ -> Value_ops.text_of_value v let numeric s = match Value_ops.whole_number s with | Some (Value.Int i) -> Some (Int64.to_float i) | Some (Value.Float f) -> Some f | _ -> None