filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
zeros_native.ml
open Pp_binary_ints.Nativeint open Pp_binary_ints.Flags let configs = [ { default with separators = false; prefix_non_zero = false } ; { default with separators = false; prefix_non_zero = true } ; { default with separators = true; prefix_non_zero = false } ; { default with separators = true; prefix_non_zero = true } ] let zero_ocaml_configs = List.map (fun x -> { x with padding = Zeros; zero_printing = OCaml }) configs let left_ocaml_configs = List.map (fun x -> { x with padding = Left; zero_printing = OCaml }) configs let right_ocaml_configs = List.map (fun x -> { x with padding = Right; zero_printing = OCaml }) configs let zero_inherit_configs = List.map (fun x -> { x with padding = Zeros; zero_printing = InheritNonZero }) configs let left_inherit_configs = List.map (fun x -> { x with padding = Left; zero_printing = InheritNonZero }) configs let right_inherit_configs = List.map (fun x -> { x with padding = Right; zero_printing = InheritNonZero }) configs let test_width configs min_width n : string list = List.map (fun flags -> to_string_with ~flags ~min_width n) configs (** * Zero printing *) let%test "zero default" = "0b0n" = to_string 0n let%test "zero default manual" = "0b0n" = to_string_with ~flags:default ~min_width:1 0n (** ** Zero Padding, OCaml *) (** OCaml's [Printf] does not prefix zeros *) let%test "zero ocaml 1" = ["0n";"0n";"0n";"0n"] = test_width zero_ocaml_configs 1 0n let%test "zero ocaml 2" = ["0n";"0n";"0n";"0n"] = test_width zero_ocaml_configs 2 0n let%test "zero ocaml 3" = ["00n";"00n";"00n";"00n"] = test_width zero_ocaml_configs 3 0n let%test "zero ocaml 4" = ["000n";"000n";"000n";"000n"] = test_width zero_ocaml_configs 4 0n let%test "zero ocaml 5" = ["0000n";"0000n";"0000n";"0000n"] = test_width zero_ocaml_configs 5 0n let%test "zero ocaml 6" = ["00000n";"00000n";"00000n";"00000n"] = test_width zero_ocaml_configs 6 0n let%test "zero ocaml 7" = ["000000n";"000000n";"0_0000n";"0_0000n"] = test_width zero_ocaml_configs 7 0n let%test "zero ocaml 16" = ["000000000000000n" ;"000000000000000n" ;"00000_0000_0000n" ;"00000_0000_0000n" ] = test_width zero_ocaml_configs 16 0n let%test "zero ocaml 17" = ["0000000000000000n" ;"0000000000000000n" ;"0_0000_0000_0000n" ;"0_0000_0000_0000n" ] = test_width zero_ocaml_configs 17 0n (** ** Left Padding, OCaml *) let%test "left ocaml 1" = ["0n";"0n";"0n";"0n"] = test_width left_ocaml_configs 1 0n let%test "left ocaml 2" = ["0n";"0n";"0n";"0n"] = test_width left_ocaml_configs 2 0n let%test "left ocaml 3" = [" 0n";" 0n";" 0n";" 0n"] = test_width left_ocaml_configs 3 0n let%test "left ocaml 4" = [" 0n";" 0n";" 0n";" 0n"] = test_width left_ocaml_configs 4 0n let%test "left ocaml 5" = [" 0n";" 0n";" 0n";" 0n"] = test_width left_ocaml_configs 5 0n (** ** Right Padding, OCaml *) let%test "right ocaml 1" = ["0n";"0n";"0n";"0n"] = test_width right_ocaml_configs 1 0n let%test "right ocaml 2" = ["0n";"0n";"0n";"0n"] = test_width right_ocaml_configs 2 0n let%test "right ocaml 3" = ["0n ";"0n ";"0n ";"0n "] = test_width right_ocaml_configs 3 0n let%test "right ocaml 4" = ["0n ";"0n ";"0n ";"0n "] = test_width right_ocaml_configs 4 0n let%test "right ocaml 5" = ["0n ";"0n ";"0n ";"0n "] = test_width right_ocaml_configs 5 0n (** ** Zero Padding, Inherit *) let%test "zero inherit 1" = ["0n";"0b0n";"0n";"0b0n"] = test_width zero_inherit_configs 1 0n let%test "zero inherit 2" = ["0n";"0b0n";"0n";"0b0n"] = test_width zero_inherit_configs 2 0n let%test "zero inherit 3" = ["00n";"0b0n";"00n";"0b0n"] = test_width zero_inherit_configs 3 0n let%test "zero inherit 4" = ["000n";"0b0n";"000n";"0b0n"] = test_width zero_inherit_configs 4 0n let%test "zero inherit 5" = ["0000n";"0b00n";"0000n";"0b00n"] = test_width zero_inherit_configs 5 0n let%test "zero inherit 6" = ["00000n";"0b000n";"00000n";"0b000n"] = test_width zero_inherit_configs 6 0n let%test "zero inherit 7" = ["000000n";"0b0000n";"0_0000n";"0b0000n"] = test_width zero_inherit_configs 7 0n let%test "zero inherit 8" = ["0000000n";"0b00000n";"00_0000n";"0b00000n"] = test_width zero_inherit_configs 8 0n let%test "zero inherit 9" = ["00000000n";"0b000000n";"000_0000n";"0b0_0000n"] = test_width zero_inherit_configs 9 0n let%test "zero inherit 16" = ["000000000000000n" ;"0b0000000000000n" ;"00000_0000_0000n" ;"0b000_0000_0000n" ] = test_width zero_inherit_configs 16 0n (** ** Left Padding, Inherit *) let%test "left inherit 1" = ["0n";"0b0n";"0n";"0b0n"] = test_width left_inherit_configs 1 0n let%test "left inherit 2" = ["0n";"0b0n";"0n";"0b0n"] = test_width left_inherit_configs 2 0n let%test "left inherit 3" = [" 0n";"0b0n";" 0n";"0b0n"] = test_width left_inherit_configs 3 0n let%test "left inherit 4" = [" 0n";"0b0n";" 0n";"0b0n"] = test_width left_inherit_configs 4 0n let%test "left inherit 5" = [" 0n";" 0b0n";" 0n";" 0b0n"] = test_width left_inherit_configs 5 0n (** ** Right Padding, Inherit *) let%test "right inherit 1" = ["0n";"0b0n";"0n";"0b0n"] = test_width right_inherit_configs 1 0n let%test "right inherit 2" = ["0n";"0b0n";"0n";"0b0n"] = test_width right_inherit_configs 2 0n let%test "right inherit 3" = ["0n ";"0b0n";"0n ";"0b0n"] = test_width right_inherit_configs 3 0n let%test "right inherit 4" = ["0n ";"0b0n";"0n ";"0b0n"] = test_width right_inherit_configs 4 0n let%test "right inherit 5" = ["0n ";"0b0n ";"0n ";"0b0n "] = test_width right_inherit_configs 5 0n
services_registration.ml
open Alpha_context type rpc_context = { block_hash: Block_hash.t ; block_header: Block_header.shell_header ; context: Alpha_context.t ; } let rpc_init ({ block_hash ; block_header ; context } : Updater.rpc_context) = let level = block_header.level in let timestamp = block_header.timestamp in let fitness = block_header.fitness in Alpha_context.prepare ~level ~timestamp ~fitness context >>=? fun context -> return { block_hash ; block_header ; context } let rpc_services = ref (RPC_directory.empty : Updater.rpc_context RPC_directory.t) let register0_fullctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun ctxt q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt q i) let opt_register0_fullctxt s f = rpc_services := RPC_directory.opt_register !rpc_services s (fun ctxt q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt q i) let register0 s f = register0_fullctxt s (fun { context ; _ } -> f context) let register0_noctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun _ q i -> f q i) let register1_fullctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun (ctxt, arg) q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt arg q i) let register1 s f = register1_fullctxt s (fun { context ; _ } x -> f context x) let register1_noctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun (_, arg) q i -> f arg q i) let register2_fullctxt s f = rpc_services := RPC_directory.register !rpc_services s (fun ((ctxt, arg1), arg2) q i -> rpc_init ctxt >>=? fun ctxt -> f ctxt arg1 arg2 q i) let register2 s f = register2_fullctxt s (fun { context ; _ } a1 a2 q i -> f context a1 a2 q i) let get_rpc_services () = let p = RPC_directory.map (fun c -> rpc_init c >>= function | Error _ -> assert false | Ok c -> Lwt.return c.context) (Storage_description.build_directory Alpha_context.description) in RPC_directory.register_dynamic_directory !rpc_services RPC_path.(open_root / "context" / "raw" / "json") (fun _ -> Lwt.return p)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
json.mli
(** In memory JSON data *) type json = [ `O of (string * json) list | `Bool of bool | `Float of float | `A of json list | `Null | `String of string ] (** Read a JSON document from a string. *) val from_string : string -> (json, string) result (** Write a JSON document to a string. This goes via an intermediate buffer and so may be slow on large documents. *) val to_string : json -> string (** Helpers for [Data_encoding] *) val cannot_destruct : ('a, Format.formatter, unit, 'b) format4 -> 'a val wrap_error : ('a -> 'b) -> 'a -> 'b
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
byteswap.h
/* NB: * * This file is from Gnulib, and in accordance with the convention there, the * real license of this file comes from the module definition. It is really * LGPLv2+. * * - RWMJ. 2008/08/23 */ #ifndef _GL_BYTESWAP_H #define _GL_BYTESWAP_H /* * Given an unsigned 16-bit argument X, return the value corresponding to * X with reversed byte order. */ #define bswap_16(x) ((((x) & 0x00FF) << 8) | \ (((x) & 0xFF00) >> 8)) /* * Given an unsigned 32-bit argument X, return the value corresponding to * X with reversed byte order. */ #define bswap_32(x) ((((x) & 0x000000FF) << 24) | \ (((x) & 0x0000FF00) << 8) | \ (((x) & 0x00FF0000) >> 8) | \ (((x) & 0xFF000000) >> 24)) /* * Given an unsigned 64-bit argument X, return the value corresponding to X * with reversed byte order. */ #define bswap_64(x) ((((x) & 0x00000000000000FFULL) << 56) | \ (((x) & 0x000000000000FF00ULL) << 40) | \ (((x) & 0x0000000000FF0000ULL) << 24) | \ (((x) & 0x00000000FF000000ULL) << 8) | \ (((x) & 0x000000FF00000000ULL) >> 8) | \ (((x) & 0x0000FF0000000000ULL) >> 24) | \ (((x) & 0x00FF000000000000ULL) >> 40) | \ (((x) & 0xFF00000000000000ULL) >> 56)) #endif /* _GL_BYTESWAP_H */ // vim: ts=2:sts=2:sw=2:et
/* * byteswap.h - Byte swapping * Copyright (C) 2005, 2007 Free Software Foundation, Inc. * Written by Oskar Liljeblad <oskar@osk.mine.nu>, 2005. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */
pipeline.ml
module Np = Np.Numpy let print f x = Format.printf "%a" f x let print_py x = Format.printf "%s" (Py.Object.to_string x) let print_ndarray = print Np.Ndarray.pp (* Parallel *) (* >>> from math import sqrt >>> from joblib import Parallel, delayed >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] *) (* TEST TODO let%expect_test "Parallel" = let sqrt = Math.sqrt in from joblib import Parallel, delayed Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) [%expect {| [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] |}] *) (* let%expect_test "Parallel" = * let sqrt args = args.(0) |> Py.Number.to_float |> sqrt |> Py.Float.of_float in * let par = Sklearn.Parallel.create ~n_jobs:1 () in * let powi x n = Float.pow (Float.of_int x) n in * let res = Sklearn.Parallel.call par ~f:sqrt ~args:(Array.init 10 (fun i -> Py.Number.of_float (powi i 2.)) in * Format.printf "%s" (Py.Object.to_string res); * [%expect {| * [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] * |}] *) (* Parallel *) (* >>> from math import modf >>> from joblib import Parallel, delayed >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10)) >>> res, i = zip( *r) >>> res (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5) >>> i (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0) *) (* TEST TODO let%expect_test "Parallel" = let modf = Math.modf in from joblib import Parallel, delayed r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10)) let res, i = zip *r in res [%expect {| (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5) |}] i [%expect {| (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0) |}] *) (* Parallel *) (* >>> from time import sleep >>> from joblib import Parallel, delayed >>> r = Parallel(n_jobs=2, verbose=10)(delayed(sleep)(.2) for _ in range(10)) #doctest: +SKIP [Parallel(n_jobs=2)]: Done 1 tasks | elapsed: 0.6s [Parallel(n_jobs=2)]: Done 4 tasks | elapsed: 0.8s [Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 1.4s finished *) (* TEST TODO let%expect_test "Parallel" = let sleep = Time.sleep in from joblib import Parallel, delayed r = Parallel(n_jobs=2, verbose=10)(delayed(sleep)(.2) for _ in range(10)) #doctest: +SKIP [%expect {| [Parallel(n_jobs=2)]: Done 1 tasks | elapsed: 0.6s [Parallel(n_jobs=2)]: Done 4 tasks | elapsed: 0.8s [Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 1.4s finished |}] *) (* Parallel *) (* >>> from heapq import nlargest >>> from joblib import Parallel, delayed >>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP #... --------------------------------------------------------------------------- Sub-process traceback: --------------------------------------------------------------------------- TypeError Mon Nov 12 11:37:46 2012 PID: 12934 Python 2.7.3: /usr/bin/python ........................................................................... /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None) 419 if n >= size: 420 return sorted(iterable, key=key, reverse=True)[:n] 421 422 # When key is none, use simpler decoration 423 if key is None: --> 424 it = izip(iterable, count(0,-1)) # decorate 425 result = _nlargest(n, it) 426 return map(itemgetter(0), result) # undecorate 427 428 # General case, slowest method TypeError: izip argument #1 must support iteration ___________________________________________________________________________ *) (* TEST TODO let%expect_test "Parallel" = let nlargest = Heapq.nlargest in from joblib import Parallel, delayed Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP [%expect {| #... --------------------------------------------------------------------------- Sub-process traceback: --------------------------------------------------------------------------- TypeError Mon Nov 12 11:37:46 2012 PID: 12934 Python 2.7.3: /usr/bin/python ........................................................................... /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None) 419 if n >= size: 420 return sorted(iterable, key=key, reverse=True)[:n] 421 422 # When key is none, use simpler decoration 423 if key is None: --> 424 it = izip(iterable, count(0,-1)) # decorate 425 result = _nlargest(n, it) 426 return map(itemgetter(0), result) # undecorate 427 428 # General case, slowest method TypeError: izip argument #1 must support iteration ___________________________________________________________________________ |}] *) (* make_pipeline *) (* >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.preprocessing import StandardScaler >>> make_pipeline(StandardScaler(), GaussianNB(priors=None)) Pipeline(steps=[('standardscaler', StandardScaler()), ('gaussiannb', GaussianNB())]) *) let%expect_test "make_pipeline" = let open Sklearn in let pipe = Pipeline.make_pipeline [Preprocessing.StandardScaler.(create () |> as_estimator); Naive_bayes.GaussianNB.(create () |> as_estimator)] in print Pipeline.Pipeline.pp pipe; [%expect {| Pipeline(steps=[('standardscaler', StandardScaler()), ('gaussiannb', GaussianNB())]) |}] (* >>> from sklearn.decomposition import PCA, TruncatedSVD * >>> from sklearn.pipeline import make_union * >>> make_union(PCA(), TruncatedSVD()) * FeatureUnion(transformer_list=[('pca', PCA()), * ('truncatedsvd', TruncatedSVD())]) *) let%expect_test "make_union" = let open Sklearn in let union = Pipeline.make_union [Sklearn.Decomposition.PCA.(create () |> as_estimator); Sklearn.Decomposition.TruncatedSVD.(create () |> as_estimator)] in print Pipeline.FeatureUnion.pp union; [%expect {| FeatureUnion(transformer_list=[('pca', PCA()), ('truncatedsvd', TruncatedSVD())]) |}] (* >>> from sklearn.pipeline import FeatureUnion * >>> from sklearn.decomposition import PCA, TruncatedSVD * >>> union = FeatureUnion([("pca", PCA(n_components=1)), * ... ("svd", TruncatedSVD(n_components=2))]) * >>> X = [[0., 1., 3], [2., 2., 5]] * >>> union.fit_transform(X) * array([[ 1.5 , 3.0..., 0.8...], * [-1.5 , 5.7..., -0.4...]]) *) let%expect_test "FeatureUnion" = let open Sklearn in let open Pipeline in let union = FeatureUnion.create ~transformer_list:["pca", Sklearn.Decomposition.PCA.(create ~n_components:(`I 1) () |> as_transformer); "svd", Sklearn.Decomposition.TruncatedSVD.(create ~n_components:2 () |> as_transformer)] () in let x = Np.matrixf [|[|0.; 1.; 3.|]; [|2.; 2.; 5.|]|] in print_ndarray @@ FeatureUnion.fit_transform union ~x; [%expect {| [[ 1.5 3.03954967 0.87243213] [-1.5 5.72586357 -0.46312679]] |}] let%expect_test "complex_pipeline" = let open Sklearn in let open Sklearn.Pipeline in let x, y = Datasets.make_classification ~n_informative:5 ~n_redundant:0 ~random_state:42 () in (* ANOVA SVM-C *) let f_regression = let _ = Py.Run.eval ~start:Py.File "import sklearn.feature_selection" in Py.Run.eval "sklearn.feature_selection.f_regression" in let anova_filter = Feature_selection.SelectKBest.(create ~score_func:f_regression ~k:(`I 5) () |> as_estimator) in let clf = Svm.SVC.(create ~kernel:`Linear () |> as_estimator) in let anova_svm = Pipeline.create ~steps:["anova", anova_filter; "svc", clf] () in let anova_svm = Pipeline.( set_params anova_svm ~kwargs:["anova__k", (Py.Int.of_int 10); "svc__C", (Py.Float.of_float 0.1)] |> fit ~x ~y) in print Pipeline.pp anova_svm; (* filtering out the address printed for f_regression, which is a problem for this test *) print_string @@ Re.replace_string (Re.Perl.compile_pat "0x[a-fA-F0-9]+") ~by:"0x..." [%expect.output]; [%expect {| Pipeline(steps=[('anova', SelectKBest(score_func=<function f_regression at 0x...>)), ('svc', SVC(C=0.1, kernel='linear'))]) |}]; let prediction = Pipeline.predict anova_svm ~x in print_ndarray prediction; [%expect {| [1 0 0 1 1 1 0 1 0 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 0 0 0 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 0 0 1 0 1 0 0 1 1 1 0 1 0 1 0 0 1 0 1 0 1 1 1 1 1 1 0 1 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 0 0] |}]; Format.printf "%g" @@ Pipeline.score anova_svm ~x ~y; [%expect {| 0.83 |}]; (* ouch, this is very ugly compared to anova_svm['anova'] *) let anova = Pipeline.get_item anova_svm ~ind:(`S "anova") |> Feature_selection.SelectKBest.of_pyobject in print_ndarray @@ Feature_selection.SelectKBest.get_support anova; [%expect {| [False False True True False False True True False True False True True False True False True True False False] |}]; let anova = Pipeline.named_steps anova_svm |> Sklearn.Dict.get (module Feature_selection.SelectKBest) ~name:"anova" in print_ndarray @@ Feature_selection.SelectKBest.get_support anova; [%expect {| [False False True True False False True True False True False True True False True False True True False False] |}]; (* anova_svm.names_steps.anova: not wrapping that, won't be easier than the above *) let sub_pipeline = Pipeline.get_item anova_svm ~ind:(Np.slice ~j:1 ()) |> Pipeline.of_pyobject in let svc = Pipeline.get_item anova_svm ~ind:(`I (-1)) |> Svm.SVC.of_pyobject in let coef = Svm.SVC.coef_ svc in Np.(shape coef |> vectori |> print pp); [%expect {| [ 1 10] |}]; Np.(Pipeline.inverse_transform sub_pipeline ~x:coef |> shape |> vectori |> print pp); [%expect {| [ 1 20] |}] (* >>> from sklearn import svm * >>> from sklearn.datasets import make_classification * >>> from sklearn.feature_selection import SelectKBest * >>> from sklearn.feature_selection import f_regression * >>> from sklearn.pipeline import Pipeline * >>> # generate some data to play with * >>> X, y = make_classification( * ... n_informative=5, n_redundant=0, random_state=42) * >>> # ANOVA SVM-C * >>> anova_filter = SelectKBest(f_regression, k=5) * >>> clf = svm.SVC(kernel='linear') * >>> anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)]) * >>> # You can set the parameters using the names issued * >>> # For instance, fit using a k of 10 in the SelectKBest * >>> # and a parameter 'C' of the svm * >>> anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y) * Pipeline(steps=[('anova', SelectKBest(...)), ('svc', SVC(...))]) * >>> prediction = anova_svm.predict(X) * >>> anova_svm.score(X, y) * 0.83 * >>> # getting the selected features chosen by anova_filter * >>> anova_svm['anova'].get_support() * array([False, False, True, True, False, False, True, True, False, * True, False, True, True, False, True, False, True, True, * False, False]) * >>> # Another way to get selected features chosen by anova_filter * >>> anova_svm.named_steps.anova.get_support() * array([False, False, True, True, False, False, True, True, False, * True, False, True, True, False, True, False, True, True, * False, False]) * >>> # Indexing can also be used to extract a sub-pipeline. * >>> sub_pipeline = anova_svm[:1] * >>> sub_pipeline * Pipeline(steps=[('anova', SelectKBest(...))]) * >>> coef = anova_svm[-1].coef_ * >>> anova_svm['svc'] is anova_svm[-1] * True * >>> coef.shape * (1, 10) * >>> sub_pipeline.inverse_transform(coef).shape * (1, 20) *)
client_info.mli
open Core (** Client_info is present for every remote, ui, embedder, host, or plugin attached to neovim. For more details, run `:h nvim_set_client_info` *) module Version : sig type t = { major : int option ; minor : int option ; patch : int option ; prerelease : string option ; commit : string option } end module Client_type : sig type t = [ `Remote | `Ui | `Embedder | `Host | `Plugin ] end module Client_method : sig type t = { async : bool ; nargs : [ `Fixed of int | `Range of int * int ] option } end type t = { version : Version.t option ; methods : Client_method.t String.Map.t ; attributes : string String.Map.t ; name : string option ; type_ : Client_type.t option } [@@deriving sexp_of] val of_msgpack : Msgpack.t -> t Or_error.t
fprint.c
#include "fmpq_vec.h" int _fmpq_vec_fprint(FILE * file, const fmpq * vec, slong len) { int r; slong i; r = flint_fprintf(file, "%li", len); if ((len > 0) && (r > 0)) { r = fputc(' ', file); for (i = 0; (i < len) && (r > 0); i++) { r = fputc(' ', file); if (r > 0) r = fmpq_fprint(file, vec + i); } } return r; }
/* Copyright (C) 2016 Vincent Delecroix This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
t-scalar_mul_mpz.c
#include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpq_poly.h" #include "long_extras.h" #include "ulong_extras.h" int main(void) { int i, result; ulong cflags = UWORD(0); FLINT_TEST_INIT(state); flint_printf("scalar_mul_mpz...."); fflush(stdout); /* Check aliasing of a and b */ for (i = 0; i < 100 * flint_test_multiplier(); i++) { fmpq_poly_t a, b; fmpz_t n; mpz_t m; fmpz_init(n); mpz_init(m); fmpz_randtest(n, state, 200); fmpz_get_mpz(m, n); fmpq_poly_init(a); fmpq_poly_init(b); fmpq_poly_randtest(a, state, n_randint(state, 100), n_randint(state, 200)); fmpq_poly_scalar_mul_mpz(b, a, m); fmpq_poly_scalar_mul_mpz(a, a, m); cflags |= fmpq_poly_is_canonical(a) ? 0 : 1; cflags |= fmpq_poly_is_canonical(b) ? 0 : 2; result = (fmpq_poly_equal(a, b) && !cflags); if (!result) { flint_printf("FAIL:\n"); fmpq_poly_debug(a), flint_printf("\n\n"); fmpq_poly_debug(b), flint_printf("\n\n"); flint_printf("cflags = %wu\n\n", cflags); fflush(stdout); flint_abort(); } fmpz_clear(n); mpz_clear(m); fmpq_poly_clear(a); fmpq_poly_clear(b); } /* Check that n (a + b) == na + nb */ for (i = 0; i < 100 * flint_test_multiplier(); i++) { fmpq_poly_t a, b, lhs, rhs; fmpz_t n; mpz_t m; fmpz_init(n); mpz_init(m); fmpz_randtest(n, state, 200); fmpz_get_mpz(m, n); fmpq_poly_init(a); fmpq_poly_init(b); fmpq_poly_init(lhs); fmpq_poly_init(rhs); fmpq_poly_randtest(a, state, n_randint(state, 100), n_randint(state, 200)); fmpq_poly_randtest(b, state, n_randint(state, 100), n_randint(state, 200)); fmpq_poly_scalar_mul_mpz(lhs, a, m); fmpq_poly_scalar_mul_mpz(rhs, b, m); fmpq_poly_add(rhs, lhs, rhs); fmpq_poly_add(lhs, a, b); fmpq_poly_scalar_mul_mpz(lhs, lhs, m); cflags |= fmpq_poly_is_canonical(lhs) ? 0 : 1; cflags |= fmpq_poly_is_canonical(rhs) ? 0 : 2; result = (fmpq_poly_equal(lhs, rhs) && !cflags); if (!result) { flint_printf("FAIL:\n"); fmpq_poly_debug(a), flint_printf("\n\n"); fmpq_poly_debug(b), flint_printf("\n\n"); flint_printf("cflags = %wu\n\n", cflags); fflush(stdout); flint_abort(); } fmpz_clear(n); mpz_clear(m); fmpq_poly_clear(a); fmpq_poly_clear(b); fmpq_poly_clear(lhs); fmpq_poly_clear(rhs); } /* Compare with fmpq_poly_scalar_mul_si */ for (i = 0; i < 100 * flint_test_multiplier(); i++) { fmpq_poly_t a, b; mpz_t n1; slong n; n = z_randtest(state); mpz_init(n1); flint_mpz_set_si(n1, n); fmpq_poly_init(a); fmpq_poly_init(b); fmpq_poly_randtest(a, state, n_randint(state, 100), n_randint(state, 200)); fmpq_poly_scalar_mul_mpz(b, a, n1); fmpq_poly_scalar_mul_si(a, a, n); cflags |= fmpq_poly_is_canonical(a) ? 0 : 1; cflags |= fmpq_poly_is_canonical(b) ? 0 : 2; result = (fmpq_poly_equal(a, b) && !cflags); if (!result) { flint_printf("FAIL:\n"); fmpq_poly_debug(a), flint_printf("\n\n"); fmpq_poly_debug(b), flint_printf("\n\n"); flint_printf("cflags = %wu\n\n", cflags); fflush(stdout); flint_abort(); } mpz_clear(n1); fmpq_poly_clear(a); fmpq_poly_clear(b); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2009 William Hart Copyright (C) 2010 Sebastian Pancratz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
Test_naming_generic.ml
open Common module H = AST_generic_helpers module V = Visitor_AST let test_naming_generic ~parse_program file = let ast = parse_program file in let lang = List.hd (Lang.langs_of_filename file) in Naming_AST.resolve lang ast; let s = AST_generic.show_any (AST_generic.Pr ast) in pr2 s let actions ~parse_program = [ ( "-naming_generic", " <file>", Arg_helpers.mk_action_1_arg (test_naming_generic ~parse_program) ); ]
typemod.mli
(** Type-checking of the module language and typed ast hooks {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) open Types module Signature_names : sig type t val simplify: Env.t -> t -> signature -> signature end val type_module: Env.t -> Parsetree.module_expr -> Typedtree.module_expr * Shape.t val type_structure: Env.t -> Parsetree.structure -> Typedtree.structure * Types.signature * Signature_names.t * Shape.t * Env.t val type_toplevel_phrase: Env.t -> Parsetree.structure -> Typedtree.structure * Types.signature * (* Signature_names.t * *) Shape.t * Env.t val type_implementation: string -> string -> string -> Env.t -> Parsetree.structure -> Typedtree.implementation val type_interface: Env.t -> Parsetree.signature -> Typedtree.signature val transl_signature: Env.t -> Parsetree.signature -> Typedtree.signature val check_nongen_signature: Env.t -> Types.signature -> unit (* val type_open_: ?used_slot:bool ref -> ?toplevel:bool -> Asttypes.override_flag -> Env.t -> Location.t -> Longident.t Asttypes.loc -> Path.t * Env.t *) val modtype_of_package: Env.t -> Location.t -> Path.t -> (Longident.t * type_expr) list -> module_type val path_of_module : Typedtree.module_expr -> Path.t option val save_signature: string -> Typedtree.signature -> string -> string -> Env.t -> Cmi_format.cmi_infos -> unit val package_units: Env.t -> string list -> string -> string -> Typedtree.module_coercion (* Should be in Envaux, but it breaks the build of the debugger *) val initial_env: loc:Location.t -> initially_opened_module:string option -> open_implicit_modules:string list -> Env.t module Sig_component_kind : sig type t = | Value | Type | Module | Module_type | Extension_constructor | Class | Class_type val to_string : t -> string end type hiding_error = | Illegal_shadowing of { shadowed_item_id: Ident.t; shadowed_item_kind: Sig_component_kind.t; shadowed_item_loc: Location.t; shadower_id: Ident.t; user_id: Ident.t; user_kind: Sig_component_kind.t; user_loc: Location.t; } | Appears_in_signature of { opened_item_id: Ident.t; opened_item_kind: Sig_component_kind.t; user_id: Ident.t; user_kind: Sig_component_kind.t; user_loc: Location.t; } type error = Cannot_apply of module_type | Not_included of Includemod.explanation | Cannot_eliminate_dependency of module_type | Signature_expected | Structure_expected of module_type | With_no_component of Longident.t | With_mismatch of Longident.t * Includemod.explanation | With_makes_applicative_functor_ill_typed of Longident.t * Path.t * Includemod.explanation | With_changes_module_alias of Longident.t * Ident.t * Path.t | With_cannot_remove_constrained_type | Repeated_name of Sig_component_kind.t * string | Non_generalizable of type_expr | Non_generalizable_module of module_type | Implementation_is_required of string | Interface_not_compiled of string | Not_allowed_in_functor_body | Not_a_packed_module of type_expr | Incomplete_packed_module of type_expr | Scoping_pack of Longident.t * type_expr | Recursive_module_require_explicit_type | Apply_generative | Cannot_scrape_alias of Path.t | Cannot_scrape_package_type of Path.t | Badly_formed_signature of string * Typedecl.error | Cannot_hide_id of hiding_error | Invalid_type_subst_rhs | Unpackable_local_modtype_subst of Path.t | With_cannot_remove_packed_modtype of Path.t * module_type exception Error of Location.t * Env.t * error exception Error_forward of Location.error val report_error: Env.t -> loc:Location.t -> error -> Location.error (* merlin *) val normalize_signature : Types.signature -> unit val merlin_type_structure: Env.t -> Parsetree.structure -> Typedtree.structure * Types.signature * (* Signature_names.t * *) Env.t val merlin_transl_signature: Env.t -> Parsetree.signature -> Typedtree.signature
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
dune
(executable (name oacmel) (public_name oacmel) (package letsencrypt-app) (modules oacmel) (libraries letsencrypt letsencrypt-dns ptime.clock.os ipaddr.unix cohttp-lwt-unix fpath bos randomconv cmdliner mirage-crypto-rng.unix fmt.cli fmt.tty logs.fmt logs.cli))
spt_core.c
/* * spt_core.c: Core functionality. */ #define _GNU_SOURCE #include <assert.h> #include <err.h> #include <libgen.h> #include <signal.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/mman.h> #include <time.h> #include <seccomp.h> #include <sys/personality.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/prctl.h> #include <sys/syscall.h> #include <unistd.h> #include <limits.h> #include <linux/filter.h> #include <linux/seccomp.h> #if defined(__x86_64__) #include <asm/prctl.h> #endif #include "spt.h" /* * TODO: Split up the functions in this module better, and introduce something * similar to hvt_gpa_t for clarity. */ /* * Defined by standard GNU ld linker scripts to the lowest address of the text * segment. */ extern long __executable_start; static bool use_exec_heap = false; struct spt *spt_init(size_t mem_size) { struct spt *spt = malloc(sizeof (struct spt)); if (spt == NULL) err(1, "malloc"); memset(spt, 0, sizeof (struct spt)); #if defined(__PIE__) /* * On systems where we are built as a PIE executable: * * The kernel will apply ASLR and map the tender at a high virtual address * (see ELF_ET_DYN_BASE in the kernel source for the arch-specific value, * as we only support 64-bit architectures for now where this should always * be >= 4 GB). * * Therefore, rather than mislead the user with an incorrect error message, * assert that a) the tender has been loaded with a base address of at * least 4GB and b) tender address space does not overlap with guest * address space. We can re-visit this if it turns out that users run on * systems where this does not hold (e.g. kernel ASLR is disabled). */ assert((uint64_t)&__executable_start >= (1ULL << 32)); assert((uint64_t)(mem_size - 1) < (uint64_t)&__executable_start); #else /* * On systems where we are NOT built as a PIE executable, first assert that * -Ttext-segment has been correctly passed at the link step (see * configure.sh), and then check that guest memory size is within limits. */ assert((uint64_t)&__executable_start >= (1ULL << 30)); if ((uint64_t)(mem_size - 1) >= (uint64_t)&__executable_start) { uint64_t max_mem_size_mb = (uint64_t)&__executable_start >> 20; warnx("Maximum guest memory size (%lu MB) exceeded.", max_mem_size_mb); errx(1, "Either decrease --mem-size, or recompile solo5-spt" " as a PIE executable."); } #endif /* * Sooo... it turns out that at least on some distributions, the Linux * "personality" flag READ_IMPLIES_EXEC is the default unless linked with * -z noexecstack. This is bad, as it results in mmap() with PROT_READ * implying PROT_EXEC. Cowardly refuse to run on such systems. */ int persona = -1; persona = personality(0xffffffff); assert(persona >= 0); if (persona & READ_IMPLIES_EXEC) errx(1, "Cowardly refusing to run with a sys_personality of " "READ_IMPLIES_EXEC. Please report a bug, with details of your " "Linux distribution and GCC version"); /* * spt->mem is addressed starting at 0, however we cannot actually map it * at 0 due to restrictions on mapping low memory addresses present in * modern Linux kernels (vm.mmap_min_addr sysctl). Therefore, we map * spt_mem at SPT_HOST_MEM_BASE, adjusting the returned pointer and region * size appropriately. */ int prot = PROT_READ | PROT_WRITE | (use_exec_heap ? PROT_EXEC : 0); spt->mem = mmap((void *)SPT_HOST_MEM_BASE, mem_size - SPT_HOST_MEM_BASE, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); if (spt->mem == MAP_FAILED) err(1, "Error allocating guest memory"); assert(spt->mem == (void *)SPT_HOST_MEM_BASE); spt->mem -= SPT_HOST_MEM_BASE; spt->mem_size = mem_size; spt->epollfd = epoll_create1(0); if (spt->epollfd == -1) err(1, "epoll_create1() failed"); spt->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK); if (spt->timerfd == -1) err(1, "timerfd_create() failed"); struct epoll_event ev; ev.events = EPOLLIN; ev.data.u64 = SPT_INTERNAL_TIMERFD; if (epoll_ctl(spt->epollfd, EPOLL_CTL_ADD, spt->timerfd, &ev) == -1) err(1, "epoll_ctl(EPOLL_CTL_ADD) failed"); spt->sc_ctx = seccomp_init(SCMP_ACT_KILL); assert(spt->sc_ctx != NULL); return spt; } int spt_guest_mprotect(void *t_arg, uint64_t addr_start, uint64_t addr_end, int prot) { struct spt *spt = t_arg; assert(addr_start <= spt->mem_size); assert(addr_end <= spt->mem_size); assert(addr_start < addr_end); uint8_t *vaddr_start = spt->mem + addr_start; assert(vaddr_start >= spt->mem); size_t size = addr_end - addr_start; assert(size > 0 && size <= spt->mem_size); /* * On spt, there is no distinction between host-side and guest-side memory * protection, so just pass through to mprotect() directly, which will do * the right thing. */ return mprotect(vaddr_start, size, prot); } static void setup_cmdline(uint8_t *cmdline, int argc, char **argv) { size_t cmdline_free = SPT_CMDLINE_SIZE; cmdline[0] = 0; for (; *argv; argc--, argv++) { size_t alen = snprintf((char *)cmdline, cmdline_free, "%s%s", *argv, (argc > 1) ? " " : ""); if (alen >= cmdline_free) { errx(1, "Guest command line too long (max=%d characters)", SPT_CMDLINE_SIZE - 1); break; } cmdline_free -= alen; cmdline += alen; } } void spt_boot_info_init(struct spt *spt, uint64_t p_end, int cmdline_argc, char **cmdline_argv, struct mft *mft, size_t mft_size) { uint64_t lowmem_pos = SPT_BOOT_INFO_BASE; struct spt_boot_info *bi = (struct spt_boot_info *)(spt->mem + lowmem_pos); lowmem_pos += sizeof (struct spt_boot_info); bi->mem_size = spt->mem_size; bi->kernel_end = p_end; bi->epollfd = spt->epollfd; bi->timerfd = spt->timerfd; bi->mft = (void *)lowmem_pos; memcpy(spt->mem + lowmem_pos, mft, mft_size); lowmem_pos += mft_size; bi->cmdline = (void *)lowmem_pos; setup_cmdline(spt->mem + lowmem_pos, cmdline_argc, cmdline_argv); lowmem_pos += SPT_CMDLINE_SIZE; } /* * Defined in spt_lauch_<arch>.S. */ extern void spt_launch(uint64_t stack_start, void (*fn)(void *), void *arg); /* * Not all glibc versions still in common use provide a wrapper for * memfd_create(), so we define our own here. */ static inline int _memfd_create(const char *name, unsigned int flags) { return syscall(__NR_memfd_create, name, flags); } void spt_run(struct spt *spt, uint64_t p_entry) { typedef void (*start_fn_t)(void *arg); start_fn_t start_fn = (start_fn_t)(spt->mem + p_entry); /* * Set initial stack alignment based on arch-specific ABI requirements. */ #if defined(__x86_64__) uint64_t sp = spt->mem_size - 0x8; #elif defined(__aarch64__) uint64_t sp = spt->mem_size - 0x10; #elif defined(__powerpc64__) /* * Stack alignment on PPC64 is 0x10, minimum stack frame size is 112 bytes. */ uint64_t sp = spt->mem_size - 112; #else #error Unsupported architecture #endif /* * We cannot use seccomp_load() to load the filter, as this calls free() * which may call brk(), which we do not have in our seccomp whitelist. * Instead, we export the BPF program via an anonymous memfd, release all * resources from the libseccomp context and load the filter manually. */ int bpf_fd = _memfd_create("bpf_filter", 0); if (bpf_fd < 0) err(1, "memfd_create() failed"); int rc = -1; rc = seccomp_export_bpf(spt->sc_ctx, bpf_fd); if (rc != 0) errx(1, "seccomp_export_bpf() failed: %s", strerror(-rc)); struct stat sb; rc = fstat(bpf_fd, &sb); if (rc != 0) err(1, "fstat() failed"); if (lseek(bpf_fd, 0, SEEK_SET) == (off_t)-1) err(1, "lseek() failed"); /* * bpf_prgm is intentionally allocated on our stack, that way libc malloc * is not involved. */ char bpf_prgm[sb.st_size]; ssize_t nbytes = read(bpf_fd, bpf_prgm, sb.st_size); assert(nbytes == sb.st_size); close(bpf_fd); seccomp_release(spt->sc_ctx); spt->sc_ctx = NULL; rc = prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); if (rc != 0) err(1, "prctl(PR_SET_NO_NEW_PRIVS) failed"); struct sock_filter dummy[1]; struct sock_fprog prog = { .len = (unsigned short) (sb.st_size / sizeof dummy[0]), .filter = (struct sock_filter *)bpf_prgm }; /* * Check that we did not truncate the BPF filter due to overflow in the * calculation above. */ assert((sb.st_size / sizeof dummy[0]) <= USHRT_MAX); rc = syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog); if (rc != 0) err(1, "seccomp(SECCOMP_SET_MODE_FILTER) failed"); spt_launch(sp, start_fn, spt->mem + SPT_BOOT_INFO_BASE); abort(); /* spt_launch() does not return */ } static int handle_cmdarg(char *cmdarg, struct mft *mft) { if (!strncmp("--x-exec-heap", cmdarg, 13)) { warnx("WARNING: The use of --x-exec-heap is dangerous and not" " recommended as it makes the heap and stack executable."); use_exec_heap = true; return 0; } return -1; } static int setup(struct spt *spt, struct mft *mft) { int rc = -1; rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 1, SCMP_A0(SCMP_CMP_EQ, 1)); if (rc != 0) errx(1, "seccomp_rule_add(write, fd=1) failed: %s", strerror(-rc)); rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0); if (rc != 0) errx(1, "seccomp_rule_add(exit_group) failed: %s", strerror(-rc)); rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(epoll_pwait), 1, SCMP_A0(SCMP_CMP_EQ, spt->epollfd)); if (rc != 0) errx(1, "seccomp_rule_add(epoll_pwait) failed: %s", strerror(-rc)); rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(timerfd_settime), 1, SCMP_A0(SCMP_CMP_EQ, spt->timerfd)); if (rc != 0) errx(1, "seccomp_rule_add(timerfd_settime) failed: %s", strerror(-rc)); rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(clock_gettime), 1, SCMP_A0(SCMP_CMP_EQ, CLOCK_MONOTONIC)); if (rc != 0) errx(1, "seccomp_rule_add(clock_gettime, CLOCK_MONOTONIC) failed: %s", strerror(-rc)); rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(clock_gettime), 1, SCMP_A0(SCMP_CMP_EQ, CLOCK_REALTIME)); if (rc != 0) errx(1, "seccomp_rule_add(clock_gettime, CLOCK_REALTIME) failed: %s", strerror(-rc)); #if defined(__x86_64__) rc = seccomp_rule_add(spt->sc_ctx, SCMP_ACT_ALLOW, SCMP_SYS(arch_prctl), 1, SCMP_A0(SCMP_CMP_EQ, ARCH_SET_FS)); if (rc != 0) errx(1, "seccomp_rule_add(arch_prctl, ARCH_SET_FS) failed: %s", strerror(-rc)); #endif return 0; } static char *usage(void) { return "--x-exec-heap (make the heap executable)." " WARNING: This option is dangerous and not recommended as it" " makes the heap and stack executable."; } DECLARE_MODULE(core, .setup = setup, .handle_cmdarg = handle_cmdarg, .usage = usage )
/* * Copyright (c) 2015-2019 Contributors as noted in the AUTHORS file * * This file is part of Solo5, a sandboxed execution environment. * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
opamPrinter.mli
(** {2 Printers for the [value] and [opamfile] formats} *) open OpamParserTypes val relop: [< relop ] -> string val logop: [< logop ] -> string val pfxop: [< pfxop ] -> string val env_update_op: env_update_op -> string val value : value -> string val value_list: value list -> string val items: opamfile_item list -> string val opamfile: opamfile -> string val format_opamfile: Format.formatter -> opamfile -> unit (** {2 Normalised output for opam syntax files} *) module Normalise : sig val escape_string : string -> string val value : value -> string val item : opamfile_item -> string val item_order : opamfile_item -> opamfile_item -> int val items : opamfile_item list -> string val opamfile : opamfile -> string end (** {2 Format-preserving reprinter} *) module Preserved : sig (** [items str orig_its its] converts [its] to string, while attempting to preserve the layout and comments of the original [str] for unmodified elements. The function assumes that [str] parses to the items [orig_its]. *) val items: string -> opamfile_item list -> opamfile_item list -> string (** [opamfile f] converts [f] to string, respecting the layout and comments in the corresponding on-disk file for unmodified items. [format_from] can be specified instead of using the filename specified in [f]. *) val opamfile: ?format_from:file_name -> opamfile -> string end (** {2 Random utility functions} *) (** Compares structurally, without considering file positions *) val value_equals: value -> value -> bool (** Compares structurally, without considering file positions *) val opamfile_item_equals: opamfile_item -> opamfile_item -> bool
(**************************************************************************) (* *) (* Copyright 2012-2015 OCamlPro *) (* Copyright 2012 INRIA *) (* *) (* All rights reserved. This file is distributed under the terms of the *) (* GNU Lesser General Public License version 2.1, with the special *) (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
odoc.ml
open Import open Dune_file open Memo.O let ( ++ ) = Path.Build.relative let find_project_by_key = let memo = let make_map projects = Dune_project.File_key.Map.of_list_map_exn projects ~f:(fun project -> (Dune_project.file_key project, project)) |> Memo.return in let module Input = struct type t = Dune_project.t list let equal = List.equal Dune_project.equal let hash = List.hash Dune_project.hash let to_dyn = Dyn.list Dune_project.to_dyn end in Memo.create "project-by-keys" ~input:(module Input) make_map in fun key -> let* { projects; _ } = Dune_load.load () in let+ map = Memo.exec memo projects in Dune_project.File_key.Map.find_exn map key module Scope_key : sig val of_string : Context.t -> string -> (Lib_name.t * Lib.DB.t) Memo.t val to_string : Lib_name.t -> Dune_project.t -> string end = struct let of_string context s = match String.rsplit2 s ~on:'@' with | None -> let+ public_libs = Scope.DB.public_libs context in (Lib_name.parse_string_exn (Loc.none, s), public_libs) | Some (lib, key) -> let+ scope = let key = Dune_project.File_key.of_string key in find_project_by_key key >>= Scope.DB.find_by_project context in (Lib_name.parse_string_exn (Loc.none, lib), Scope.libs scope) let to_string lib project = let key = Dune_project.file_key project in sprintf "%s@%s" (Lib_name.to_string lib) (Dune_project.File_key.to_string key) end let lib_unique_name lib = let name = Lib.name lib in let info = Lib.info lib in let status = Lib_info.status info in match status with | Installed_private | Installed -> assert false | Public _ -> Lib_name.to_string name | Private (project, _) -> Scope_key.to_string name project let pkg_or_lnu lib = match Lib_info.package (Lib.info lib) with | Some p -> Package.Name.to_string p | None -> lib_unique_name lib type target = | Lib of Lib.Local.t | Pkg of Package.Name.t type source = | Module | Mld type odoc_artefact = { odoc_file : Path.Build.t ; odocl_file : Path.Build.t ; html_dir : Path.Build.t ; html_file : Path.Build.t ; source : source (** source of the [odoc_file], either module or mld *) } let add_rule sctx = let dir = (Super_context.context sctx).build_dir in Super_context.add_rule sctx ~dir module Paths = struct let root (context : Context.t) = Path.Build.relative context.Context.build_dir "_doc" let odocs ctx = function | Lib lib -> let obj_dir = Lib.Local.obj_dir lib in Obj_dir.odoc_dir obj_dir | Pkg pkg -> root ctx ++ sprintf "_odoc/pkg/%s" (Package.Name.to_string pkg) let html_root ctx = root ctx ++ "_html" let odocl_root ctx = root ctx ++ "_odocls" let add_pkg_lnu base m = base ++ match m with | Pkg pkg -> Package.Name.to_string pkg | Lib lib -> pkg_or_lnu (Lib.Local.to_lib lib) let html ctx m = add_pkg_lnu (html_root ctx) m let odocl ctx m = add_pkg_lnu (odocl_root ctx) m let gen_mld_dir ctx pkg = root ctx ++ "_mlds" ++ Package.Name.to_string pkg let css_file ctx = html_root ctx ++ "odoc.css" let highlight_pack_js ctx = html_root ctx ++ "highlight.pack.js" let toplevel_index ctx = html_root ctx ++ "index.html" end module Dep : sig (** [html_alias ctx target] returns the alias that depends on all html targets produced by odoc for [target] *) val html_alias : Context.t -> target -> Alias.t (** [deps ctx pkg libraries] returns all odoc dependencies of [libraries]. If [libraries] are all part of a package [pkg], then the odoc dependencies of the package are also returned*) val deps : Context.t -> Package.Name.t option -> Lib.t list Resolve.t -> unit Action_builder.t (*** [setup_deps ctx target odocs] Adds [odocs] as dependencies for [target]. These dependencies may be used using the [deps] function *) val setup_deps : Context.t -> target -> Path.Set.t -> unit Memo.t end = struct let html_alias ctx m = Alias.doc ~dir:(Paths.html ctx m) let alias = Alias.make (Alias.Name.of_string ".odoc-all") let deps ctx pkg requires = let open Action_builder.O in let* libs = Resolve.read requires in Action_builder.deps (let init = match pkg with | Some p -> Dep.Set.singleton (Dep.alias (alias ~dir:(Paths.odocs ctx (Pkg p)))) | None -> Dep.Set.empty in List.fold_left libs ~init ~f:(fun acc (lib : Lib.t) -> match Lib.Local.of_lib lib with | None -> acc | Some lib -> let dir = Paths.odocs ctx (Lib lib) in let alias = alias ~dir in Dep.Set.add acc (Dep.alias alias))) let alias ctx m = alias ~dir:(Paths.odocs ctx m) let setup_deps ctx m files = Rules.Produce.Alias.add_deps (alias ctx m) (Action_builder.path_set files) end let odoc_ext = ".odoc" module Mld : sig type t val create : Path.Build.t -> t val odoc_file : doc_dir:Path.Build.t -> t -> Path.Build.t val odoc_input : t -> Path.Build.t end = struct type t = Path.Build.t let create p = p let odoc_file ~doc_dir t = let t = Filename.chop_extension (Path.Build.basename t) in Path.Build.relative doc_dir (sprintf "page-%s%s" t odoc_ext) let odoc_input t = t end let odoc_base_flags sctx build_dir = let open Memo.O in let+ conf = Super_context.odoc sctx ~dir:build_dir in match conf.Env_node.Odoc.warnings with | Fatal -> Command.Args.A "--warn-error" | Nonfatal -> S [] let run_odoc sctx ~dir command ~flags_for args = let build_dir = (Super_context.context sctx).build_dir in let open Memo.O in let* program = Super_context.resolve_program sctx ~dir:build_dir "odoc" ~loc:None ~hint:"opam install odoc" in let+ base_flags = match flags_for with | None -> Memo.return Command.Args.empty | Some path -> odoc_base_flags sctx path in let deps = Action_builder.env_var "ODOC_SYNTAX" in let open Action_builder.With_targets.O in Action_builder.with_no_targets deps >>> Command.run ~dir program [ A command; base_flags; S args ] let module_deps (m : Module.t) ~obj_dir ~(dep_graphs : Dep_graph.Ml_kind.t) = Action_builder.dyn_paths_unit (let open Action_builder.O in let+ deps = if Module.has m ~ml_kind:Intf then Dep_graph.deps_of dep_graphs.intf m else (* When a module has no .mli, use the dependencies for the .ml *) Dep_graph.deps_of dep_graphs.impl m in List.map deps ~f:(fun m -> Path.build (Obj_dir.Module.odoc obj_dir m))) let compile_module sctx ~obj_dir (m : Module.t) ~includes:(file_deps, iflags) ~dep_graphs ~pkg_or_lnu = let odoc_file = Obj_dir.Module.odoc obj_dir m in let open Memo.O in let+ () = let* action_with_targets = let doc_dir = Path.build (Obj_dir.odoc_dir obj_dir) in let+ run_odoc = run_odoc sctx ~dir:doc_dir "compile" ~flags_for:(Some odoc_file) [ A "-I" ; Path doc_dir ; iflags ; As [ "--pkg"; pkg_or_lnu ] ; A "-o" ; Target odoc_file ; Dep (Path.build (Obj_dir.Module.cmti_file ~cm_kind:(Ocaml Cmi) obj_dir m)) ] in let open Action_builder.With_targets.O in Action_builder.with_no_targets file_deps >>> Action_builder.with_no_targets (module_deps m ~obj_dir ~dep_graphs) >>> run_odoc in add_rule sctx action_with_targets in (m, odoc_file) let compile_mld sctx (m : Mld.t) ~includes ~doc_dir ~pkg = let open Memo.O in let odoc_file = Mld.odoc_file m ~doc_dir in let odoc_input = Mld.odoc_input m in let* run_odoc = run_odoc sctx ~dir:(Path.build doc_dir) "compile" ~flags_for:(Some odoc_input) [ Command.Args.dyn includes ; As [ "--pkg"; Package.Name.to_string pkg ] ; A "-o" ; Target odoc_file ; Dep (Path.build odoc_input) ] in let+ () = add_rule sctx run_odoc in odoc_file let odoc_include_flags ctx pkg requires = Resolve.args (let open Resolve.O in let+ libs = requires in let paths = List.fold_left libs ~init:Path.Set.empty ~f:(fun paths lib -> match Lib.Local.of_lib lib with | None -> paths | Some lib -> Path.Set.add paths (Path.build (Paths.odocs ctx (Lib lib)))) in let paths = match pkg with | Some p -> Path.Set.add paths (Path.build (Paths.odocs ctx (Pkg p))) | None -> paths in Command.Args.S (List.concat_map (Path.Set.to_list paths) ~f:(fun dir -> [ Command.Args.A "-I"; Path dir ]))) let link_odoc_rules sctx (odoc_file : odoc_artefact) ~pkg ~requires = let ctx = Super_context.context sctx in let deps = Dep.deps ctx pkg requires in let open Memo.O in let* run_odoc = run_odoc sctx ~dir:(Path.build (Paths.html_root ctx)) "link" ~flags_for:(Some odoc_file.odoc_file) [ odoc_include_flags ctx pkg requires ; A "-o" ; Target odoc_file.odocl_file ; Dep (Path.build odoc_file.odoc_file) ] in add_rule sctx (let open Action_builder.With_targets.O in Action_builder.with_no_targets deps >>> run_odoc) let setup_library_odoc_rules cctx (local_lib : Lib.Local.t) = let open Memo.O in (* Using the proper package name doesn't actually work since odoc assumes that a package contains only 1 library *) let pkg_or_lnu = pkg_or_lnu (Lib.Local.to_lib local_lib) in let sctx = Compilation_context.super_context cctx in let ctx = Super_context.context sctx in let* requires = Compilation_context.requires_compile cctx in let info = Lib.Local.info local_lib in let package = Lib_info.package info in let odoc_include_flags = Command.Args.memo (odoc_include_flags ctx package requires) in let obj_dir = Compilation_context.obj_dir cctx in let modules = Compilation_context.modules cctx in let includes = (Dep.deps ctx package requires, odoc_include_flags) in let modules_and_odoc_files = Modules.fold_no_vlib modules ~init:[] ~f:(fun m acc -> let compiled = compile_module sctx ~includes ~dep_graphs:(Compilation_context.dep_graphs cctx) ~obj_dir ~pkg_or_lnu m in compiled :: acc) in let* modules_and_odoc_files = Memo.all_concurrently modules_and_odoc_files in Dep.setup_deps ctx (Lib local_lib) (Path.Set.of_list_map modules_and_odoc_files ~f:(fun (_, p) -> Path.build p)) let setup_html sctx (odoc_file : odoc_artefact) = let ctx = Super_context.context sctx in let to_remove, dummy = match odoc_file.source with | Mld -> (odoc_file.html_file, []) | Module -> (* Dummy target so that the below rule as at least one target. We do this because we don't know the targets of odoc in this case. The proper way to support this would be to have directory targets. *) let dummy = Action_builder.create_file (odoc_file.html_dir ++ ".dummy") in (odoc_file.html_dir, [ dummy ]) in let open Memo.O in let* run_odoc = run_odoc sctx ~dir:(Path.build (Paths.html_root ctx)) "html-generate" ~flags_for:None [ A "-o" ; Path (Path.build (Paths.html_root ctx)) ; Dep (Path.build odoc_file.odocl_file) ; Hidden_targets [ odoc_file.html_file ] ] in add_rule sctx (Action_builder.progn (Action_builder.with_no_targets (Action_builder.return (Action.Full.make (Action.Progn [ Action.Remove_tree to_remove ; Action.Mkdir odoc_file.html_dir ]))) :: run_odoc :: dummy)) let setup_css_rule sctx = let open Memo.O in let ctx = Super_context.context sctx in let* run_odoc = run_odoc sctx ~dir:(Path.build ctx.build_dir) "support-files" ~flags_for:None [ A "-o" ; Path (Path.build (Paths.html_root ctx)) ; Hidden_targets [ Paths.css_file ctx; Paths.highlight_pack_js ctx ] ] in add_rule sctx run_odoc let sp = Printf.sprintf let setup_toplevel_index_rule sctx = let* list_items = let+ packages = Only_packages.get () in Package.Name.Map.to_list packages |> List.filter_map ~f:(fun (name, pkg) -> let name = Package.Name.to_string name in let link = sp {|<a href="%s/index.html">%s</a>|} name name in let version_suffix = match pkg.Package.version with | None -> "" | Some v -> sp {| <span class="version">%s</span>|} v in Some (sp "<li>%s%s</li>" link version_suffix)) |> String.concat ~sep:"\n " in let html = sp {|<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>index</title> <link rel="stylesheet" href="./odoc.css"/> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width,initial-scale=1.0"/> </head> <body> <main class="content"> <div class="by-name"> <h2>OCaml package documentation</h2> <ol> %s </ol> </div> </main> </body> </html>|} list_items in let ctx = Super_context.context sctx in add_rule sctx (Action_builder.write_file (Paths.toplevel_index ctx) html) let libs_of_pkg ctx ~pkg = let+ entries = Scope.DB.lib_entries_of_package ctx pkg in (* Filter out all implementations of virtual libraries *) List.filter_map entries ~f:(fun (entry : Scope.DB.Lib_entry.t) -> match entry with | Library lib -> let is_impl = Lib.Local.to_lib lib |> Lib.info |> Lib_info.implements |> Option.is_some in Option.some_if (not is_impl) lib | Deprecated_library_name _ -> None) let load_all_odoc_rules_pkg sctx ~pkg = let* pkg_libs = libs_of_pkg sctx ~pkg in let+ () = Memo.parallel_iter (Pkg pkg :: List.map pkg_libs ~f:(fun lib -> Lib lib)) ~f:(fun _ -> Memo.return ()) in pkg_libs let entry_modules_by_lib sctx lib = let info = Lib.Local.info lib in let dir = Lib_info.src_dir info in let name = Lib.name (Lib.Local.to_lib lib) in Dir_contents.get sctx ~dir >>= Dir_contents.ocaml >>| Ml_sources.modules ~for_:(Library name) >>| Modules.entry_modules let entry_modules sctx ~pkg = let* l = libs_of_pkg (Super_context.context sctx) ~pkg >>| List.filter ~f:(fun lib -> Lib.Local.info lib |> Lib_info.status |> Lib_info.Status.is_private |> not) in let+ l = Memo.parallel_map l ~f:(fun l -> let+ m = entry_modules_by_lib sctx l in (l, m)) in Lib.Local.Map.of_list_exn l let create_odoc ctx ~target odoc_file = let html_base = Paths.html ctx target in let odocl_base = Paths.odocl ctx target in let basename = Path.Build.basename odoc_file |> Filename.chop_extension in let odocl_file = odocl_base ++ (basename ^ ".odocl") in match target with | Lib _ -> let html_dir = html_base ++ Stdune.String.capitalize basename in { odoc_file ; odocl_file ; html_dir ; html_file = html_dir ++ "index.html" ; source = Module } | Pkg _ -> { odoc_file ; odocl_file ; html_dir = html_base ; html_file = html_base ++ sprintf "%s.html" (basename |> String.drop_prefix ~prefix:"page-" |> Option.value_exn) ; source = Mld } let static_html ctx = let open Paths in [ css_file ctx; highlight_pack_js ctx; toplevel_index ctx ] let check_mlds_no_dupes ~pkg ~mlds = match List.map mlds ~f:(fun mld -> (Filename.chop_extension (Path.Build.basename mld), mld)) |> String.Map.of_list with | Ok m -> m | Error (_, p1, p2) -> User_error.raise [ Pp.textf "Package %s has two mld's with the same basename %s, %s" (Package.Name.to_string pkg) (Path.to_string_maybe_quoted (Path.build p1)) (Path.to_string_maybe_quoted (Path.build p2)) ] let odoc_artefacts sctx target = let ctx = Super_context.context sctx in let dir = Paths.odocs ctx target in match target with | Pkg pkg -> let+ mlds = let+ mlds = Packages.mlds sctx pkg in let mlds = check_mlds_no_dupes ~pkg ~mlds in if String.Map.mem mlds "index" then mlds else let gen_mld = Paths.gen_mld_dir ctx pkg ++ "index.mld" in String.Map.add_exn mlds "index" gen_mld in String.Map.values mlds |> List.map ~f:(fun mld -> Mld.create mld |> Mld.odoc_file ~doc_dir:dir |> create_odoc ctx ~target) | Lib lib -> let info = Lib.Local.info lib in let obj_dir = Lib_info.obj_dir info in let* modules = entry_modules_by_lib sctx lib in List.map ~f:(fun m -> let odoc_file = Obj_dir.Module.odoc obj_dir m in create_odoc ctx ~target odoc_file) modules |> Memo.return let setup_lib_odocl_rules_def = let module Input = struct module Super_context = Super_context.As_memo_key type t = Super_context.t * Lib.Local.t * Lib.t list Resolve.t let equal (sc1, l1, r1) (sc2, l2, r2) = Super_context.equal sc1 sc2 && Lib.Local.equal l1 l2 && Resolve.equal (List.equal Lib.equal) r1 r2 let hash (sc, l, r) = Poly.hash ( Super_context.hash sc , Lib.Local.hash l , Resolve.hash (List.hash Lib.hash) r ) let to_dyn _ = Dyn.Opaque end in let f (sctx, lib, requires) = let* odocs = odoc_artefacts sctx (Lib lib) in let pkg = Lib_info.package (Lib.Local.info lib) in Memo.parallel_iter odocs ~f:(fun odoc -> link_odoc_rules sctx ~pkg ~requires odoc) in Memo.With_implicit_output.create "setup_library_odocls_rules" ~implicit_output:Rules.implicit_output ~input:(module Input) f let setup_lib_odocl_rules sctx lib ~requires = Memo.With_implicit_output.exec setup_lib_odocl_rules_def (sctx, lib, requires) let setup_pkg_rules_def memo_name f = let module Input = struct module Super_context = Super_context.As_memo_key type t = Super_context.t * Package.Name.t * Lib.Local.t list let equal (s1, p1, l1) (s2, p2, l2) = Package.Name.equal p1 p2 && List.equal Lib.Local.equal l1 l2 && Super_context.equal s1 s2 let hash (sctx, p, ls) = Poly.hash ( Super_context.hash sctx , Package.Name.hash p , List.hash Lib.Local.hash ls ) let to_dyn (_, package, libs) = let open Dyn in Tuple [ Package.Name.to_dyn package ; List (List.map ~f:Lib.Local.to_dyn libs) ] end in Memo.With_implicit_output.create memo_name ~input:(module Input) ~implicit_output:Rules.implicit_output f let setup_pkg_odocl_rules_def = let f (sctx, pkg, (libs : Lib.Local.t list)) = let* requires = let libs = (libs :> Lib.t list) in Lib.closure libs ~linking:false in let* () = Memo.parallel_iter libs ~f:(setup_lib_odocl_rules sctx ~requires) and* _ = let* pkg_odocs = odoc_artefacts sctx (Pkg pkg) in let pkg = Some pkg in let+ () = Memo.parallel_iter pkg_odocs ~f:(fun odoc -> link_odoc_rules sctx ~pkg ~requires odoc) in pkg_odocs and* _ = Memo.parallel_map libs ~f:(fun lib -> odoc_artefacts sctx (Lib lib)) in Memo.return () in setup_pkg_rules_def "setup-package-odocls-rules" f let setup_pkg_odocl_rules sctx ~pkg ~libs : unit Memo.t = Memo.With_implicit_output.exec setup_pkg_odocl_rules_def (sctx, pkg, libs) let setup_lib_html_rules_def = let module Input = struct module Super_context = Super_context.As_memo_key type t = Super_context.t * Lib.Local.t let equal (sc1, l1) (sc2, l2) = Super_context.equal sc1 sc2 && Lib.Local.equal l1 l2 let hash (sc, l) = Poly.hash (Super_context.hash sc, Lib.Local.hash l) let to_dyn _ = Dyn.Opaque end in let f (sctx, lib) = let ctx = Super_context.context sctx in let* odocs = odoc_artefacts sctx (Lib lib) in let* () = Memo.parallel_iter odocs ~f:(fun odoc -> setup_html sctx odoc) in let html_files = List.map ~f:(fun o -> Path.build o.html_file) odocs in let static_html = List.map ~f:Path.build (static_html ctx) in Rules.Produce.Alias.add_deps (Dep.html_alias ctx (Lib lib)) (Action_builder.paths (List.rev_append static_html html_files)) in Memo.With_implicit_output.create "setup-library-html-rules" ~implicit_output:Rules.implicit_output ~input:(module Input) f let setup_lib_html_rules sctx lib = Memo.With_implicit_output.exec setup_lib_html_rules_def (sctx, lib) let setup_pkg_html_rules_def = let f (sctx, pkg, (libs : Lib.Local.t list)) = let ctx = Super_context.context sctx in let* () = Memo.parallel_iter libs ~f:(setup_lib_html_rules sctx) and* pkg_odocs = let* pkg_odocs = odoc_artefacts sctx (Pkg pkg) in let+ () = Memo.parallel_iter pkg_odocs ~f:(fun o -> setup_html sctx o) in pkg_odocs and* lib_odocs = Memo.parallel_map libs ~f:(fun lib -> odoc_artefacts sctx (Lib lib)) in let odocs = List.concat (pkg_odocs :: lib_odocs) in let html_files = List.map ~f:(fun o -> Path.build o.html_file) odocs in let static_html = List.map ~f:Path.build (static_html ctx) in Rules.Produce.Alias.add_deps (Dep.html_alias ctx (Pkg pkg)) (Action_builder.paths (List.rev_append static_html html_files)) in setup_pkg_rules_def "setup-package-html-rules" f let setup_pkg_html_rules sctx ~pkg ~libs : unit Memo.t = Memo.With_implicit_output.exec setup_pkg_html_rules_def (sctx, pkg, libs) let setup_package_aliases sctx (pkg : Package.t) = let ctx = Super_context.context sctx in let name = Package.name pkg in let alias = let pkg_dir = Package.dir pkg in let dir = Path.Build.append_source ctx.build_dir pkg_dir in Alias.doc ~dir in let* libs = libs_of_pkg ctx ~pkg:name >>| List.map ~f:(fun lib -> Dep.html_alias ctx (Lib lib)) in Dep.html_alias ctx (Pkg name) :: libs |> Dune_engine.Dep.Set.of_list_map ~f:(fun f -> Dune_engine.Dep.alias f) |> Action_builder.deps |> Rules.Produce.Alias.add_deps alias let default_index ~pkg entry_modules = let b = Buffer.create 512 in Printf.bprintf b "{0 %s index}\n" (Package.Name.to_string pkg); Lib.Local.Map.to_list entry_modules |> List.sort ~compare:(fun (x, _) (y, _) -> let name lib = Lib.name (Lib.Local.to_lib lib) in Lib_name.compare (name x) (name y)) |> List.iter ~f:(fun (lib, modules) -> let lib = Lib.Local.to_lib lib in Printf.bprintf b "{1 Library %s}\n" (Lib_name.to_string (Lib.name lib)); Buffer.add_string b (match modules with | [ x ] -> sprintf "The entry point of this library is the module:\n{!module-%s}.\n" (Module_name.to_string (Module.name x)) | _ -> sprintf "This library exposes the following toplevel modules:\n\ {!modules:%s}\n" (modules |> List.filter ~f:(fun m -> Module.visibility m = Visibility.Public) |> List.sort ~compare:(fun x y -> Module_name.compare (Module.name x) (Module.name y)) |> List.map ~f:(fun m -> Module_name.to_string (Module.name m)) |> String.concat ~sep:" "))); Buffer.contents b let package_mlds = let memo = Memo.create "package-mlds" ~input:(module Super_context.As_memo_key.And_package) (fun (sctx, pkg) -> Rules.collect (fun () -> (* CR-someday jeremiedimino: it is weird that we drop the [Package.t] and go back to a package name here. Need to try and change that one day. *) let pkg = Package.name pkg in let* mlds = Packages.mlds sctx pkg in let mlds = check_mlds_no_dupes ~pkg ~mlds in let ctx = Super_context.context sctx in if String.Map.mem mlds "index" then Memo.return mlds else let gen_mld = Paths.gen_mld_dir ctx pkg ++ "index.mld" in let* entry_modules = entry_modules sctx ~pkg in let+ () = add_rule sctx (Action_builder.write_file gen_mld (default_index ~pkg entry_modules)) in String.Map.set mlds "index" gen_mld)) in fun sctx ~pkg -> Memo.exec memo (sctx, pkg) let setup_package_odoc_rules sctx ~pkg = let* mlds = package_mlds sctx ~pkg >>| fst in let ctx = Super_context.context sctx in (* CR-someday jeremiedimino: it is weird that we drop the [Package.t] and go back to a package name here. Need to try and change that one day. *) let pkg = Package.name pkg in let* odocs = Memo.parallel_map (String.Map.values mlds) ~f:(fun mld -> compile_mld sctx (Mld.create mld) ~pkg ~doc_dir:(Paths.odocs ctx (Pkg pkg)) ~includes:(Action_builder.return [])) in Dep.setup_deps ctx (Pkg pkg) (Path.set_of_build_paths_list odocs) let gen_project_rules sctx project = let* packages = Only_packages.packages_of_project project in Package.Name.Map_traversals.parallel_iter packages ~f:(fun _ (pkg : Package.t) -> (* setup @doc to build the correct html for the package *) setup_package_aliases sctx pkg) let setup_private_library_doc_alias sctx ~scope ~dir (l : Dune_file.Library.t) = match l.visibility with | Public _ -> Memo.return () | Private _ -> let ctx = Super_context.context sctx in let* lib = Lib.DB.find_even_when_hidden (Scope.libs scope) (Library.best_name l) >>| Option.value_exn in let lib = Lib (Lib.Local.of_lib_exn lib) in Rules.Produce.Alias.add_deps (Alias.private_doc ~dir) (lib |> Dep.html_alias ctx |> Dune_engine.Dep.alias |> Action_builder.dep) let has_rules m = let rules = Rules.collect_unit (fun () -> m) in Memo.return (Build_config.Rules { rules ; build_dir_only_sub_dirs = Subdir_set.empty ; directory_targets = Path.Build.Map.empty }) let with_package pkg ~f = let pkg = Package.Name.of_string pkg in let* packages = Only_packages.get () in match Package.Name.Map.find packages pkg with | None -> Memo.return (Build_config.Rules { rules = Memo.return Rules.empty ; build_dir_only_sub_dirs = Subdir_set.empty ; directory_targets = Path.Build.Map.empty }) | Some pkg -> has_rules (f pkg) let gen_rules sctx ~dir:_ rest = match rest with | [] -> Memo.return (Build_config.Rules { rules = Memo.return Rules.empty ; build_dir_only_sub_dirs = Subdir_set.All ; directory_targets = Path.Build.Map.empty }) | [ "_html" ] -> has_rules (setup_css_rule sctx >>> setup_toplevel_index_rule sctx) | [ "_mlds"; pkg ] -> with_package pkg ~f:(fun pkg -> let* _mlds, rules = package_mlds sctx ~pkg in Rules.produce rules) | [ "_odoc"; "pkg"; pkg ] -> with_package pkg ~f:(fun pkg -> setup_package_odoc_rules sctx ~pkg) | [ "_odocls"; lib_unique_name_or_pkg ] -> has_rules ((* TODO we can be a better with the error handling in the case where lib_unique_name_or_pkg is neither a valid pkg or lnu *) let ctx = Super_context.context sctx in let* lib, lib_db = Scope_key.of_string ctx lib_unique_name_or_pkg in let setup_pkg_odocl_rules pkg = let* pkg_libs = load_all_odoc_rules_pkg ctx ~pkg in setup_pkg_odocl_rules sctx ~pkg ~libs:pkg_libs in (* jeremiedimino: why isn't [None] some kind of error here? *) let* lib = let+ lib = Lib.DB.find lib_db lib in Option.bind ~f:Lib.Local.of_lib lib in let+ () = match lib with | None -> Memo.return () | Some lib -> ( match Lib_info.package (Lib.Local.info lib) with | None -> let* requires = Lib.closure [ Lib.Local.to_lib lib ] ~linking:false in setup_lib_odocl_rules sctx lib ~requires | Some pkg -> setup_pkg_odocl_rules pkg) and+ () = let* packages = Only_packages.get () in match Package.Name.Map.find packages (Package.Name.of_string lib_unique_name_or_pkg) with | None -> Memo.return () | Some pkg -> let name = Package.name pkg in setup_pkg_odocl_rules name in ()) | [ "_html"; lib_unique_name_or_pkg ] -> has_rules ((* TODO we can be a better with the error handling in the case where lib_unique_name_or_pkg is neither a valid pkg or lnu *) let ctx = Super_context.context sctx in let* lib, lib_db = Scope_key.of_string ctx lib_unique_name_or_pkg in let setup_pkg_html_rules pkg = let* pkg_libs = load_all_odoc_rules_pkg (Super_context.context sctx) ~pkg in setup_pkg_html_rules sctx ~pkg ~libs:pkg_libs in (* jeremiedimino: why isn't [None] some kind of error here? *) let* lib = let+ lib = Lib.DB.find lib_db lib in Option.bind ~f:Lib.Local.of_lib lib in let+ () = match lib with | None -> Memo.return () | Some lib -> ( match Lib_info.package (Lib.Local.info lib) with | None -> setup_lib_html_rules sctx lib | Some pkg -> setup_pkg_html_rules pkg) and+ () = let* packages = Only_packages.get () in match Package.Name.Map.find packages (Package.Name.of_string lib_unique_name_or_pkg) with | None -> Memo.return () | Some pkg -> let name = Package.name pkg in setup_pkg_html_rules name in ()) | _ -> Memo.return Build_config.Redirect_to_parent
dune
(library (public_name goblint-cil.pta) (name ptranal) (libraries goblint-cil stdlib-shims) )
parser.h
#ifndef TREE_SITTER_PARSER_H_ #define TREE_SITTER_PARSER_H_ #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #define ts_builtin_sym_error ((TSSymbol)-1) #define ts_builtin_sym_end 0 #define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024 typedef uint16_t TSStateId; #ifndef TREE_SITTER_API_H_ typedef uint16_t TSSymbol; typedef uint16_t TSFieldId; typedef struct TSLanguage TSLanguage; #endif typedef struct { TSFieldId field_id; uint8_t child_index; bool inherited; } TSFieldMapEntry; typedef struct { uint16_t index; uint16_t length; } TSFieldMapSlice; typedef struct { bool visible; bool named; bool supertype; } TSSymbolMetadata; typedef struct TSLexer TSLexer; struct TSLexer { int32_t lookahead; TSSymbol result_symbol; void (*advance)(TSLexer *, bool); void (*mark_end)(TSLexer *); uint32_t (*get_column)(TSLexer *); bool (*is_at_included_range_start)(const TSLexer *); bool (*eof)(const TSLexer *); }; typedef enum { TSParseActionTypeShift, TSParseActionTypeReduce, TSParseActionTypeAccept, TSParseActionTypeRecover, } TSParseActionType; typedef union { struct { uint8_t type; TSStateId state; bool extra; bool repetition; } shift; struct { uint8_t type; uint8_t child_count; TSSymbol symbol; int16_t dynamic_precedence; uint16_t production_id; } reduce; uint8_t type; } TSParseAction; typedef struct { uint16_t lex_state; uint16_t external_lex_state; } TSLexMode; typedef union { TSParseAction action; struct { uint8_t count; bool reusable; } entry; } TSParseActionEntry; struct TSLanguage { uint32_t version; uint32_t symbol_count; uint32_t alias_count; uint32_t token_count; uint32_t external_token_count; uint32_t state_count; uint32_t large_state_count; uint32_t production_id_count; uint32_t field_count; uint16_t max_alias_sequence_length; const uint16_t *parse_table; const uint16_t *small_parse_table; const uint32_t *small_parse_table_map; const TSParseActionEntry *parse_actions; const char **symbol_names; const char **field_names; const TSFieldMapSlice *field_map_slices; const TSFieldMapEntry *field_map_entries; const TSSymbolMetadata *symbol_metadata; const TSSymbol *public_symbol_map; const uint16_t *alias_map; const TSSymbol *alias_sequences; const TSLexMode *lex_modes; bool (*lex_fn)(TSLexer *, TSStateId); bool (*keyword_lex_fn)(TSLexer *, TSStateId); TSSymbol keyword_capture_token; struct { const bool *states; const TSSymbol *symbol_map; void *(*create)(void); void (*destroy)(void *); bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist); unsigned (*serialize)(void *, char *); void (*deserialize)(void *, const char *, unsigned); } external_scanner; }; /* * Lexer Macros */ #define START_LEXER() \ bool result = false; \ bool skip = false; \ bool eof = false; \ int32_t lookahead; \ goto start; \ next_state: \ lexer->advance(lexer, skip); \ start: \ skip = false; \ lookahead = lexer->lookahead; #define ADVANCE(state_value) \ { \ state = state_value; \ goto next_state; \ } #define SKIP(state_value) \ { \ skip = true; \ state = state_value; \ goto next_state; \ } #define ACCEPT_TOKEN(symbol_value) \ result = true; \ lexer->result_symbol = symbol_value; \ lexer->mark_end(lexer); #define END_STATE() return result; /* * Parse Table Macros */ #define SMALL_STATE(id) id - LARGE_STATE_COUNT #define STATE(id) id #define ACTIONS(id) id #define SHIFT(state_value) \ {{ \ .shift = { \ .type = TSParseActionTypeShift, \ .state = state_value \ } \ }} #define SHIFT_REPEAT(state_value) \ {{ \ .shift = { \ .type = TSParseActionTypeShift, \ .state = state_value, \ .repetition = true \ } \ }} #define SHIFT_EXTRA() \ {{ \ .shift = { \ .type = TSParseActionTypeShift, \ .extra = true \ } \ }} #define REDUCE(symbol_val, child_count_val, ...) \ {{ \ .reduce = { \ .type = TSParseActionTypeReduce, \ .symbol = symbol_val, \ .child_count = child_count_val, \ __VA_ARGS__ \ }, \ }} #define RECOVER() \ {{ \ .type = TSParseActionTypeRecover \ }} #define ACCEPT_INPUT() \ {{ \ .type = TSParseActionTypeAccept \ }} #ifdef __cplusplus } #endif #endif // TREE_SITTER_PARSER_H_
sc_rollup_outbox_message_repr.ml
type error += | (* `Permanent *) Error_encode_outbox_message | (* `Permanent *) Error_decode_outbox_message let () = let open Data_encoding in let msg = "Failed to encode a rollup management protocol outbox message value" in register_error_kind `Permanent ~id:"sc_rollup_outbox_message_repr.error_encoding_outbox_message" ~title:msg ~pp:(fun fmt () -> Format.fprintf fmt "%s" msg) ~description:msg unit (function Error_encode_outbox_message -> Some () | _ -> None) (fun () -> Error_encode_outbox_message) ; let msg = "Failed to decode a rollup management protocol outbox message value" in register_error_kind `Permanent ~id:"sc_rollup_outbox_message_repr.error_decoding_outbox_message" ~title:msg ~pp:(fun fmt () -> Format.fprintf fmt "%s" msg) ~description:msg unit (function Error_decode_outbox_message -> Some () | _ -> None) (fun () -> Error_decode_outbox_message) type transaction = { unparsed_parameters : Script_repr.expr; (** The payload. *) destination : Contract_hash.t; (** The recipient contract. *) entrypoint : Entrypoint_repr.t; (** Entrypoint of the destination. *) } type t = Atomic_transaction_batch of {transactions : transaction list} let transaction_encoding = let open Data_encoding in conv (fun {unparsed_parameters; destination; entrypoint} -> (unparsed_parameters, destination, entrypoint)) (fun (unparsed_parameters, destination, entrypoint) -> {unparsed_parameters; destination; entrypoint}) @@ obj3 (req "parameters" Script_repr.expr_encoding) (req "destination" Contract_repr.originated_encoding) Entrypoint_repr.(dft "entrypoint" simple_encoding default) let encoding = let open Data_encoding in (* We use a union encoding in order to guarantee backwards compatibility when outbox messages are extended with more constructors. Each new constructor must be added with an increased tag number. *) check_size Constants_repr.sc_rollup_message_size_limit (union [ case (Tag 0) ~title:"Atomic_transaction_batch" (obj1 (req "transactions" (list transaction_encoding))) (fun (Atomic_transaction_batch {transactions}) -> Some transactions) (fun transactions -> Atomic_transaction_batch {transactions}); ]) let pp_transaction fmt {destination; entrypoint; unparsed_parameters} = let json = Data_encoding.Json.construct Script_repr.expr_encoding unparsed_parameters in Format.fprintf fmt "@[%a@;%a@;%a@]" Contract_hash.pp destination Entrypoint_repr.pp entrypoint Data_encoding.Json.pp json let pp fmt (Atomic_transaction_batch {transactions}) = Format.pp_print_list ~pp_sep:Format.pp_print_space pp_transaction fmt transactions type serialized = string let deserialize data = let open Tzresult_syntax in match Data_encoding.Binary.of_string_opt encoding data with | Some x -> return x | None -> fail Error_decode_outbox_message let serialize outbox_message = let open Tzresult_syntax in match Data_encoding.Binary.to_string_opt encoding outbox_message with | Some str -> return str | None -> fail Error_encode_outbox_message let unsafe_of_string s = s let unsafe_to_string s = s
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Trili Tech, <contact@trili.tech> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(library (name spelll) (public_name spelll) (libraries seq stdlib-shims) (flags :standard -warn-error -a+8 -safe-string))
generic_map.mli
open! Base open Ppxlib (** This module constructs a generic type-directed map function. Given - a map from type names [n] to functions [t_n : n -> r_n] - an input type [tau] Define the output type [tau'] to be the same as [tau] but with all (most) instances of [n] replaced by [r_n]. This module constructs a function that maps values of type [tau] to values of type [tau'] *) type replace_result = | Unchanged | Replaced val build : loc:location -> map:(string, expression, 'a) Base.Map.t -> core_type -> expression -> replace_result * expression
lexer_parser_ruby.ml
type state = | Bol (* beginning of line *) | AfterCommand (* after command, before args *) | EndOfExpr (* end of expr / literal *) | AfterDef (* after a 'def' or '.' token *) | AfterLocal (* after a local variable *) (* alternatives: * - THIS FILE: use continuation and special epsilon trick in * Lexer_ruby.token to do the switch * - instead of passing continuations, have a state for each lexer rule * and let the lexer caller do the switch (see parse_php.ml) *) type t = { mutable state : state; lexer_stack : (string (* to debug *) * cps_lexer) Stack.t; } and cps_lexer = t -> Lexing.lexbuf -> Parser_ruby.token let beg_state t = t.state <- Bol let mid_state t = t.state <- AfterCommand let end_state t = t.state <- EndOfExpr let def_state t = t.state <- AfterDef let local_state t = t.state <- AfterLocal let create entry = let stk = Stack.create () in Stack.push entry stk; { state = Bol; lexer_stack = stk } let string_of_state = function | Bol -> "Bol" | AfterCommand -> "AfterCommand" | EndOfExpr -> "EndOfExpr" | AfterDef -> "AfterDef" | AfterLocal -> "AfterLocal" let string_of_t x = Common.spf "state = %s, stack = [%s]" (string_of_state x.state) (x.lexer_stack |> Stack.to_seq |> List.of_seq |> List.map fst |> String.concat ",")
stuff.ml
type a = A1 | A2 of string type b = {b1 : a; b2 : string; b3 : Int64.t} type c = [`A | `B | `C of string] type d = Int64.t type e = string * int module type S = sig type f = int end type 'a g = Foo of 'a type h = Zero | Succ of h module MI = struct type i = int end open MI type nonrec i = I of i module type S_rec = sig type t = A of u and u = B of t end module type S_optional = sig val f : ?opt:int -> unit -> unit end
glical.mli
(* -*- coding: utf-8; -*- *) (* ********************************************************************* *) (* glical: A library to glance at iCal data using OCaml *) (* (c) 2013/2014, Philippe Wang <philippe.wang@cl.cam.ac.uk> *) (* Licence: ISC *) (* ********************************************************************* *) module Kernel : module type of Glical_kernel include module type of Kernel module SSet : Set.S with type elt = String.t (** Set of strings. *) (** [channel_contents ic] eats all contents of [ic] and returns it as a string. Beware: if the contents is very big, it might fail, cf. [Sys.max_string_length] *) val channel_contents : in_channel -> string (** [file_contents filename] eats all contents of [filename] and returns it as a string. Beware: if the contents is very big, it might fail, cf. [Sys.max_string_length] *) val file_contents : string -> string (** [simple_cat ic oc] reads some iCalendar data from [ic] and outputs it on [oc]. Note that this fails if there are syntax errors. *) val simple_cat : in_channel -> out_channel -> unit (** [get ?maxdepth ?kl ?ks ?k ical] returns the iCalendar elements (blocks and associations) that are associated with the names or keys specified in [kl], [ks] and/or [k]. [maxdepth] is the number of authorized traversals of [Block _] elements. If [maxdepth = 0] then no [Block _] will ever be returned. The default value of [maxdepth] is [max_int]. *) val get : ?maxdepth:int -> ?kl:key list -> ?ks:SSet.t -> ?k:string -> ([> `Raw of string ] as 'a) Ical.t -> 'a Ical.t (** [extract_assocs ?maxdepth ?kl ?ks ?k ical] returns the iCalendar values that are associated with the keys specified in [kl], [ks] and/or [k]. Empty blocks are not kept. [maxdepth] is the number of authorized traversals of [Block _] elements. If [maxdepth = 0] then no [Block _] will ever be returned. *) val extract_assocs : ?maxdepth:int -> ?kl:key list -> ?ks:SSet.t -> ?k:string -> ([> `Raw of string ] as 'a) Ical.t -> 'a Ical.t (** [extract_values ?kl ?ks ?k ical] is like [extract_assocs ?kl ?ks ?k ical] except that it returns a list of values instead. *) val extract_values : ?kl:key list -> ?ks:SSet.t -> ?k:string -> ([> `Raw of string ] as 'a) Ical.t -> 'a Ical.value list (** [list_keys_rev ical] is like [list_keys ical] except that the result is reversed and performs faster. *) val list_keys_rev : [> `Raw of string ] Ical.t -> string list (** [list_keys ical] returns the list of keys from [ical]. Each key only appears once. *) val list_keys : [> `Raw of string ] Ical.t -> string list (** [list_keys_ordered ?compare ical] is like [list_keys ical] except that the result is ordered according to [String.compare] unless [~compare] is specified. *) val list_keys_ordered : ?compare:(string -> string -> int) -> [> `Raw of string ] Ical.t -> string list (** [combine ical1 ical2] returns the combination of the two iCalendars [ical1] and [ical2]. *) val combine : ([> `Raw of string ] as 'a) Ical.t -> 'a Ical.t -> 'a Ical.t (** [combine_many icals] returns the combination of the all iCalendars of [icals]. *) val combine_many : ([> `Raw of string ] as 'a) Ical.t list -> 'a Ical.t (* ********************************************************************* *) (* Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED “AS IS” AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (* ********************************************************************* *)
(* -*- coding: utf-8; -*- *) (* ********************************************************************* *) (* glical: A library to glance at iCal data using OCaml *) (* (c) 2013/2014, Philippe Wang <philippe.wang@cl.cam.ac.uk> *) (* Licence: ISC *) (* ********************************************************************* *)
dune
(executables (names main simple) (libraries opium))
dune
(library (name coq) (public_name coq-lsp.coq) ; Unfortunate we have to link the STM due to the LTAC plugin ; depending on it, we should fix this upstream (libraries lang coq-core.vernac coq-core.stm coq-serapi.serlib))
test_signature.ml
(* utils *) let read_file filename = let lines = ref [] in let chan = open_in filename in try while true do lines := input_line chan :: !lines done ; !lines with End_of_file -> close_in chan ; List.rev !lines let generate_random_byte () = char_of_int (Random.int 256) let generate_random_bytes size = Bytes.init size (fun _ -> generate_random_byte ()) (* Related to sk *) let test_sk_size_in_bytes () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in assert ( Bls12_381.Signature.sk_size_in_bytes = Bytes.length (Bls12_381.Signature.sk_to_bytes sk)) let test_keygen_raise_invalid_argument_if_ikm_too_small () = ignore @@ Alcotest.check_raises "" (Invalid_argument "generate_sk: ikm argument must be at least 32 bytes long") (fun () -> let ikm = generate_random_bytes (Random.int 32) in ignore @@ Bls12_381.Signature.generate_sk ikm) (* Both can be used i.e. MinPk or MinSig. They must share the same interface. *) module type SIGNATURE_INSTANTIATION = module type of Bls12_381.Signature.MinPk module MakeTestsForInstantiation (MISC : sig val sig_basic_filenames : string list val sig_aug_filenames : string list val sig_pop_filenames : string list val pop_filenames : string list val pk_not_in_subgroup : string list val signature_not_in_subgroup : string list end) (PkGroup : Test_ec_make.G_SIG) (SigGroup : Test_ec_make.G_SIG) (SignatureM : SIGNATURE_INSTANTIATION) = struct let test_pk_size_in_bytes () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let pk = SignatureM.derive_pk sk in assert ( SignatureM.pk_size_in_bytes = Bytes.length (SignatureM.pk_to_bytes pk)) let test_signature_size_in_bytes () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let msg_length = 1 + Random.int 512 in let msg = generate_random_bytes msg_length in let signature = SignatureM.Basic.sign sk msg in assert ( SignatureM.signature_size_in_bytes = Bytes.length (SignatureM.signature_to_bytes signature)) ; let signature = SignatureM.Aug.sign sk msg in assert ( SignatureM.signature_size_in_bytes = Bytes.length (SignatureM.signature_to_bytes signature)) ; let signature = SignatureM.Pop.sign sk msg in assert ( SignatureM.signature_size_in_bytes = Bytes.length (SignatureM.signature_to_bytes signature)) let test_unsafe_pk_of_bytes_does_no_check_on_the_input () = let bytes = generate_random_bytes (Random.int 1000) in ignore @@ SignatureM.unsafe_pk_of_bytes bytes let test_pk_of_bytes_opt_does_check_the_input () = let bytes = generate_random_bytes (Random.int 1000) in assert (Option.is_none (SignatureM.pk_of_bytes_opt bytes)) let test_pk_of_bytes_exn_does_check_the_input () = let bytes = generate_random_bytes (Random.int 1000) in let err_msg = Printf.sprintf "%s is not a valid public key" Hex.(show (`Hex (Bytes.to_string bytes))) in Alcotest.check_raises "" (Invalid_argument err_msg) (fun () -> ignore @@ SignatureM.pk_of_bytes_exn bytes) let test_pk_of_bytes_opt_accepts_points_in_the_subgroup_and_in_compressed_form () = let pk = PkGroup.random () in let pk_compressed_bytes = PkGroup.to_compressed_bytes pk in assert (Option.is_some (SignatureM.pk_of_bytes_opt pk_compressed_bytes)) let test_pk_of_bytes_exn_accepts_points_in_the_subgroup_and_in_compressed_form () = let pk = PkGroup.random () in let pk_compressed_bytes = PkGroup.to_compressed_bytes pk in ignore @@ SignatureM.pk_of_bytes_exn pk_compressed_bytes let test_pk_of_bytes_exn_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form () = let pk = PkGroup.random () in let pk_uncompressed_bytes = PkGroup.to_bytes pk in let err_msg = Printf.sprintf "%s is not a valid public key" Hex.(show (`Hex (Bytes.to_string pk_uncompressed_bytes))) in Alcotest.check_raises "" (Invalid_argument err_msg) (fun () -> ignore @@ SignatureM.pk_of_bytes_exn pk_uncompressed_bytes) let test_pk_of_bytes_opt_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form () = let pk = PkGroup.random () in let pk_uncompressed_bytes = PkGroup.to_bytes pk in assert (Option.is_none (SignatureM.pk_of_bytes_opt pk_uncompressed_bytes)) let test_pk_to_bytes_of_bytes_exn_are_inverse_functions_on_valid_inputs () = let pk = PkGroup.random () in let pk_bytes = PkGroup.to_compressed_bytes pk in assert ( Bytes.equal pk_bytes (SignatureM.pk_to_bytes (SignatureM.pk_of_bytes_exn pk_bytes))) let test_pk_to_bytes_of_bytes_opt_are_inverse_functions_on_valid_inputs () = let pk = PkGroup.random () in let pk_bytes = PkGroup.to_compressed_bytes pk in assert ( Bytes.equal pk_bytes (SignatureM.pk_to_bytes (Option.get (SignatureM.pk_of_bytes_opt pk_bytes)))) let test_pk_to_bytes_unsafe_of_bytes_are_inverse_functions_on_valid_inputs () = let pk = PkGroup.random () in let pk_bytes = PkGroup.to_compressed_bytes pk in assert ( Bytes.equal pk_bytes (SignatureM.pk_to_bytes (SignatureM.unsafe_pk_of_bytes pk_bytes))) let test_pk_to_bytes_unsafe_of_bytes_are_inverse_functions_on_any_input () = let pk_bytes = Bytes.init (Random.int 1000) (fun _ -> char_of_int (Random.int 256)) in assert ( Bytes.equal pk_bytes (SignatureM.pk_to_bytes (SignatureM.unsafe_pk_of_bytes pk_bytes))) let test_unsafe_pk_of_bytes_copies_the_input () = let initial_pk_bytes = Bytes.init (1 + Random.int 1000) (fun _ -> char_of_int (Random.int 256)) in let pk_bytes = SignatureM.(pk_to_bytes (unsafe_pk_of_bytes initial_pk_bytes)) in let i = Random.int (Bytes.length initial_pk_bytes) in let b_i = Bytes.get initial_pk_bytes i in Bytes.set initial_pk_bytes i (char_of_int ((int_of_char b_i + 1) mod 256)) ; let res = Bytes.equal pk_bytes initial_pk_bytes in assert (not res) let test_pk_of_bytes_exn_copies_the_input () = let pk = PkGroup.random () in let initial_pk_bytes = PkGroup.to_compressed_bytes pk in let pk_bytes = SignatureM.(pk_to_bytes (pk_of_bytes_exn initial_pk_bytes)) in let i = Random.int (Bytes.length initial_pk_bytes) in let b_i = Bytes.get initial_pk_bytes i in Bytes.set initial_pk_bytes i (char_of_int ((int_of_char b_i + 1) mod 256)) ; let res = Bytes.equal pk_bytes initial_pk_bytes in assert (not res) let test_pk_of_bytes_opt_copies_the_input () = let pk = PkGroup.random () in let initial_pk_bytes = PkGroup.to_compressed_bytes pk in let pk_bytes = SignatureM.(pk_to_bytes (Option.get @@ pk_of_bytes_opt initial_pk_bytes)) in let i = Random.int (Bytes.length initial_pk_bytes) in let b_i = Bytes.get initial_pk_bytes i in Bytes.set initial_pk_bytes i (char_of_int ((int_of_char b_i + 1) mod 256)) ; let res = Bytes.equal pk_bytes initial_pk_bytes in assert (not res) let test_unsafe_pk_of_bytes_accepts_points_not_in_the_subgroup () = List.iter (fun pk_bytes_str -> let pk_bytes = Hex.(to_bytes (`Hex pk_bytes_str)) in ignore @@ SignatureM.unsafe_pk_of_bytes pk_bytes) MISC.pk_not_in_subgroup let test_pk_of_bytes_exn_does_verify_the_input_represents_a_point_in_the_subgroup () = List.iter (fun pk_bytes_str -> let pk_bytes = Hex.(to_bytes (`Hex pk_bytes_str)) in let err_msg = Printf.sprintf "%s is not a valid public key" Hex.(show (`Hex (Bytes.to_string pk_bytes))) in Alcotest.check_raises "" (Invalid_argument err_msg) (fun () -> ignore @@ SignatureM.pk_of_bytes_exn pk_bytes)) MISC.pk_not_in_subgroup let test_pk_of_bytes_opt_does_verify_the_input_represents_a_point_in_the_subgroup () = List.iter (fun pk_bytes_str -> let pk_bytes = Hex.(to_bytes (`Hex pk_bytes_str)) in assert (Option.is_none (SignatureM.pk_of_bytes_opt pk_bytes))) MISC.pk_not_in_subgroup let test_unsafe_signature_of_bytes_does_no_check_on_the_input () = let bytes = generate_random_bytes (Random.int 1000) in ignore @@ SignatureM.unsafe_signature_of_bytes bytes let test_signature_of_bytes_opt_does_check_the_input () = let bytes = generate_random_bytes (Random.int 1000) in assert (Option.is_none (SignatureM.signature_of_bytes_opt bytes)) let test_signature_of_bytes_exn_does_check_the_input () = let bytes = generate_random_bytes (Random.int 1000) in let err_msg = Printf.sprintf "%s is not a valid signature" Hex.(show (`Hex (Bytes.to_string bytes))) in Alcotest.check_raises "" (Invalid_argument err_msg) (fun () -> ignore @@ SignatureM.signature_of_bytes_exn bytes) let test_signature_of_bytes_opt_accepts_points_in_the_subgroup_and_in_compressed_form () = let r = SigGroup.random () in let compressed_bytes = SigGroup.to_compressed_bytes r in assert (Option.is_some (SignatureM.signature_of_bytes_opt compressed_bytes)) let test_signature_of_bytes_exn_accepts_points_in_the_subgroup_and_in_compressed_form () = let r = SigGroup.random () in let compressed_bytes = SigGroup.to_compressed_bytes r in ignore @@ SignatureM.signature_of_bytes_exn compressed_bytes let test_signature_of_bytes_exn_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form () = let r = SigGroup.random () in let uncompressed_bytes = SigGroup.to_bytes r in let err_msg = Printf.sprintf "%s is not a valid signature" Hex.(show (`Hex (Bytes.to_string uncompressed_bytes))) in Alcotest.check_raises "" (Invalid_argument err_msg) (fun () -> ignore @@ SignatureM.signature_of_bytes_exn uncompressed_bytes) let test_signature_of_bytes_opt_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form () = let r = SigGroup.random () in let uncompressed_bytes = SigGroup.to_bytes r in assert ( Option.is_none (SignatureM.signature_of_bytes_opt uncompressed_bytes)) let test_signature_to_bytes_of_bytes_exn_are_inverse_functions_on_valid_inputs () = let r = SigGroup.random () in let bytes = SigGroup.to_compressed_bytes r in assert ( Bytes.equal bytes (SignatureM.signature_to_bytes (SignatureM.signature_of_bytes_exn bytes))) let test_signature_to_bytes_of_bytes_opt_are_inverse_functions_on_valid_inputs () = let r = SigGroup.random () in let bytes = SigGroup.to_compressed_bytes r in assert ( Bytes.equal bytes (SignatureM.signature_to_bytes (Option.get (SignatureM.signature_of_bytes_opt bytes)))) let test_signature_to_bytes_unsafe_of_bytes_are_inverse_functions_on_valid_inputs () = let r = SigGroup.random () in let bytes = SigGroup.to_compressed_bytes r in assert ( Bytes.equal bytes (SignatureM.signature_to_bytes (SignatureM.unsafe_signature_of_bytes bytes))) let test_signature_to_bytes_unsafe_of_bytes_are_inverse_functions_on_any_input () = let bytes = generate_random_bytes (Random.int 1000) in assert ( Bytes.equal bytes (SignatureM.signature_to_bytes (SignatureM.unsafe_signature_of_bytes bytes))) let test_unsafe_signature_of_bytes_copies_the_input () = let initial_bytes = generate_random_bytes (1 + Random.int 1000) in let bytes = SignatureM.(signature_to_bytes (unsafe_signature_of_bytes initial_bytes)) in let i = Random.int (Bytes.length initial_bytes) in let b_i = Bytes.get initial_bytes i in Bytes.set initial_bytes i (char_of_int ((int_of_char b_i + 1) mod 256)) ; let res = Bytes.equal bytes initial_bytes in assert (not res) let test_signature_of_bytes_exn_copies_the_input () = let r = SigGroup.random () in let initial_bytes = SigGroup.to_compressed_bytes r in let bytes = SignatureM.(signature_to_bytes (signature_of_bytes_exn initial_bytes)) in let i = Random.int (Bytes.length initial_bytes) in let b_i = Bytes.get initial_bytes i in Bytes.set initial_bytes i (char_of_int ((int_of_char b_i + 1) mod 256)) ; let res = Bytes.equal bytes initial_bytes in assert (not res) let test_signature_of_bytes_opt_copies_the_input () = let r = SigGroup.random () in let initial_bytes = SigGroup.to_compressed_bytes r in let bytes = SignatureM.( signature_to_bytes (Option.get @@ signature_of_bytes_opt initial_bytes)) in let i = Random.int (Bytes.length initial_bytes) in let b_i = Bytes.get initial_bytes i in Bytes.set initial_bytes i (char_of_int ((int_of_char b_i + 1) mod 256)) ; let res = Bytes.equal bytes initial_bytes in assert (not res) let test_unsafe_signature_of_bytes_accepts_points_not_in_the_subgroup () = List.iter (fun bytes_str -> let bytes = Hex.(to_bytes (`Hex bytes_str)) in ignore @@ SignatureM.unsafe_signature_of_bytes bytes) MISC.signature_not_in_subgroup let test_signature_of_bytes_exn_does_verify_the_input_represents_a_point_in_the_subgroup () = List.iter (fun bytes_str -> let bytes = Hex.(to_bytes (`Hex bytes_str)) in let err_msg = Printf.sprintf "%s is not a valid signature" Hex.(show (`Hex (Bytes.to_string bytes))) in Alcotest.check_raises "" (Invalid_argument err_msg) (fun () -> ignore @@ SignatureM.signature_of_bytes_exn bytes)) MISC.signature_not_in_subgroup let test_signature_of_bytes_opt_does_verify_the_input_represents_a_point_in_the_subgroup () = List.iter (fun bytes_str -> let bytes = Hex.(to_bytes (`Hex bytes_str)) in assert (Option.is_none (SignatureM.signature_of_bytes_opt bytes))) MISC.signature_not_in_subgroup let test_pop_prove_verify_with_correct_keys () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let pk = SignatureM.derive_pk sk in (* sign a random message *) let proof = SignatureM.Pop.pop_prove sk in assert (SignatureM.Pop.pop_verify pk proof) let test_pop_prove_verify_with_different_pk_for_verify () = let ikm = generate_random_bytes 32 in let ikm' = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let pk' = SignatureM.(derive_pk (Bls12_381.Signature.generate_sk ikm')) in (* sign a random message *) let proof = SignatureM.Pop.pop_prove sk in assert (not (SignatureM.Pop.pop_verify pk' proof)) let test_pop_verify_random_proof () = let ikm = generate_random_bytes 32 in let pk = SignatureM.(derive_pk (Bls12_381.Signature.generate_sk ikm)) in let proof = generate_random_bytes (PkGroup.size_in_bytes / 2) in assert (not (SignatureM.Pop.pop_verify pk proof)) module MakeProperties (Scheme : sig val test_vector_filenames : string list val sign : Bls12_381.Signature.sk -> Bytes.t -> SignatureM.signature val verify : SignatureM.pk -> Bytes.t -> SignatureM.signature -> bool val name : string end) = struct let test_sign_and_verify_same_message_with_correct_keys () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let pk = SignatureM.derive_pk sk in (* sign a random message *) let msg_length = 1 + Random.int 512 in let msg = generate_random_bytes msg_length in let signature = Scheme.sign sk msg in assert (Scheme.verify pk msg signature) let test_sign_and_verify_different_message_with_correct_keys () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let pk = SignatureM.derive_pk sk in (* sign a random message *) let msg_length = 1 + Random.int 512 in let msg = generate_random_bytes msg_length in let msg'_length = 1 + Random.int 512 in let msg' = generate_random_bytes msg'_length in let signature = Scheme.sign sk msg in assert (not (Scheme.verify pk msg' signature)) let test_sign_and_verify_different_message_with_different_keys () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let _pk = SignatureM.derive_pk sk in let ikm' = generate_random_bytes 32 in let sk' = Bls12_381.Signature.generate_sk ikm' in let pk' = SignatureM.derive_pk sk' in (* sign a random message *) let msg_length = 1 + Random.int 512 in let msg = generate_random_bytes msg_length in let msg'_length = 1 + Random.int 512 in let msg' = generate_random_bytes msg'_length in let signature = Scheme.sign sk msg in assert (not (Scheme.verify pk' msg' signature)) let test_sign_and_verify_same_message_with_different_keys () = let ikm = generate_random_bytes 32 in let sk = Bls12_381.Signature.generate_sk ikm in let _pk = SignatureM.derive_pk sk in let ikm' = generate_random_bytes 32 in let sk' = Bls12_381.Signature.generate_sk ikm' in let pk' = SignatureM.derive_pk sk' in (* sign a random message *) let msg_length = 1 + Random.int 512 in let msg = generate_random_bytes msg_length in let signature = Scheme.sign sk msg in assert (not (Scheme.verify pk' msg signature)) let test_full_sign_and_verify_with_different_ikm_sizes () = let ikm = generate_random_bytes (32 + Random.int 1000) in let sk = Bls12_381.Signature.generate_sk ikm in let pk = SignatureM.derive_pk sk in (* sign a random message *) let msg_length = 1 + Random.int 512 in let msg = generate_random_bytes msg_length in let signature = Scheme.sign sk msg in assert (Scheme.verify pk msg signature) let test_verify_signature_which_represents_point_on_the_curve_but_not_in_the_prime_subgroup () = List.iter (fun signature_hex -> let ikm = Bytes.init 32 (fun _i -> char_of_int @@ Random.int 256) in let sk = Bls12_381.Signature.generate_sk ikm in let pk = SignatureM.derive_pk sk in let msg = Bytes.of_string "Hello" in let signature = Hex.(to_bytes (`Hex signature_hex)) in let signature = SignatureM.unsafe_signature_of_bytes signature in assert (not (Scheme.verify pk msg signature))) MISC.signature_not_in_subgroup let test_sign_and_verify_with_a_pk_not_in_the_subgroup () = List.iter (fun invalid_pk_bytes -> let invalid_pk_bytes = Hex.(to_bytes (`Hex invalid_pk_bytes)) in let sk = Bls12_381.(Signature.sk_of_bytes_exn Bls12_381.Fr.(to_bytes one)) in let pk = SignatureM.unsafe_pk_of_bytes invalid_pk_bytes in let msg = Bytes.of_string "Hello" in let signature = Scheme.sign sk msg in (* Even when not checking the pk belongs to the subgroup in the core_verify algorithm, the verification fails. Better attacks must be implemented. *) assert (not (Scheme.verify pk msg signature))) MISC.pk_not_in_subgroup let test_vectors_from_bls_sigs_ref_files () = let aux filename = let contents = read_file filename in List.iter (fun content -> let contents = String.split_on_char ' ' content in let msg_str, ikm_str, expected_result_str = (List.nth contents 0, List.nth contents 1, List.nth contents 2) in let msg = Hex.(to_bytes (`Hex msg_str)) in let ikm = Hex.to_bytes (`Hex ikm_str) in if Bytes.length ikm < 32 then () else let sk = Bls12_381.Signature.generate_sk ikm in let expected_result = Hex.(to_bytes (`Hex expected_result_str)) in let res = Scheme.sign sk msg in let res = SignatureM.signature_to_bytes res in if not @@ Bytes.equal res expected_result then Alcotest.failf "Expected result is %s on input %s with ikm %s, but computed \ %s" Hex.(show (Hex.of_bytes expected_result)) msg_str ikm_str Hex.(show (Hex.of_bytes res))) contents in List.iter (fun filename -> aux filename) Scheme.test_vector_filenames let get_tests () = let open Alcotest in ( Printf.sprintf "Properties and test vectors for %s" Scheme.name, [ test_case "Sign and verify same message with correct keys" `Quick (Test_ec_make.repeat 100 test_sign_and_verify_same_message_with_correct_keys); test_case "Sign and verify different message with correct keys" `Quick (Test_ec_make.repeat 100 test_sign_and_verify_different_message_with_correct_keys); test_case "Sign and verify same message with different keys" `Quick (Test_ec_make.repeat 100 test_sign_and_verify_same_message_with_different_keys); test_case "Sign and verify different message with different keys" `Quick (Test_ec_make.repeat 100 test_sign_and_verify_different_message_with_different_keys); test_case "Test full sign and verify with different ikm sizes" `Quick (Test_ec_make.repeat 100 test_full_sign_and_verify_with_different_ikm_sizes); test_case "Sign and verify with a pk not in the prime subgroup" `Quick test_sign_and_verify_with_a_pk_not_in_the_subgroup; test_case "Test vectors from bls_sigs_ref" `Quick test_vectors_from_bls_sigs_ref_files ] ) end module BasicProperties = MakeProperties (struct let test_vector_filenames = MISC.sig_basic_filenames let name = "Basic" let sign = SignatureM.Basic.sign let verify = SignatureM.Basic.verify end) module AugProperties = MakeProperties (struct let test_vector_filenames = MISC.sig_aug_filenames let name = "Message augmentation" let sign = SignatureM.Aug.sign let verify = SignatureM.Aug.verify end) module PopProperties = MakeProperties (struct let test_vector_filenames = MISC.sig_pop_filenames let name = "Proof of possession" let sign = SignatureM.Pop.sign let verify = SignatureM.Pop.verify end) let test_pop_g2_from_blst_sigs_ref_files () = let aux filename = let contents = read_file filename in List.iter (fun content -> let contents = String.split_on_char ' ' content in let ikm_str, exp_result_str = (List.nth contents 1, List.nth contents 2) in let ikm_bytes = Hex.(to_bytes (`Hex ikm_str)) in if Bytes.length ikm_bytes < 32 then () else let sk = Bls12_381.Signature.generate_sk ikm_bytes in let exp_result_bytes = Hex.(to_bytes (`Hex exp_result_str)) in let res = SignatureM.Pop.pop_prove sk in if not @@ Bytes.equal res exp_result_bytes then Alcotest.failf "Expected result is %s with ikm %s, but computed %s" exp_result_str ikm_str Hex.(show (Hex.of_bytes res))) contents in List.iter (fun filename -> aux filename) MISC.pop_filenames let get_tests () = let open Alcotest in [ ( "Size in bytes", [ test_case "pk" `Quick test_pk_size_in_bytes; test_case "signature" `Quick test_signature_size_in_bytes ] ); ( "Auxiliary functions", [ test_case "unsafe_pk_of_bytes does no check on the input" `Quick test_unsafe_pk_of_bytes_does_no_check_on_the_input; test_case "pk_of_bytes_exn accepts points in the subgroup and in compressed \ form" `Quick (Test_ec_make.repeat 1000 test_pk_of_bytes_exn_accepts_points_in_the_subgroup_and_in_compressed_form); test_case "pk_of_bytes_opt accepts points in the subgroup and in compressed \ form" `Quick (Test_ec_make.repeat 1000 test_pk_of_bytes_opt_accepts_points_in_the_subgroup_and_in_compressed_form); test_case "pk_of_bytes_exn does not accept points in the subgroup and in \ uncompressed form" `Quick (Test_ec_make.repeat 1000 test_pk_of_bytes_exn_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form); test_case "pk_of_bytes_opt does not accept points in the subgroup and in \ uncompressed form" `Quick (Test_ec_make.repeat 1000 test_pk_of_bytes_opt_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form); test_case "unsafe_pk_of_bytes copies the input" `Quick (Test_ec_make.repeat 1000 test_unsafe_pk_of_bytes_copies_the_input); test_case "pk_of_bytes_exn copies the input" `Quick (Test_ec_make.repeat 1000 test_pk_of_bytes_exn_copies_the_input); test_case "pk_of_bytes_opt copies the input" `Quick (Test_ec_make.repeat 1000 test_pk_of_bytes_opt_copies_the_input); test_case "unsafe_pk_of_bytes accepts points not in the subgroup" `Quick test_unsafe_pk_of_bytes_accepts_points_not_in_the_subgroup; test_case "pk_of_bytes_exn does check the input" `Quick test_pk_of_bytes_exn_does_check_the_input; test_case "pk_of_bytes_opt and pk_to_bytes are inverse functions on valid \ inputs" `Quick (Test_ec_make.repeat 1000 test_pk_to_bytes_of_bytes_opt_are_inverse_functions_on_valid_inputs); test_case "unsafe_pk_of_bytes and pk_to_bytes are inverse functions on valid \ inputs" `Quick (Test_ec_make.repeat 1000 test_pk_to_bytes_unsafe_of_bytes_are_inverse_functions_on_valid_inputs); test_case "pk_of_bytes_exn and pk_to_bytes are inverse functions on valid \ inputs" `Quick (Test_ec_make.repeat 1000 test_pk_to_bytes_of_bytes_exn_are_inverse_functions_on_valid_inputs); test_case "unsafe_pk_of_bytes and pk_to_bytes are inverse functions on any \ valid input" `Quick (Test_ec_make.repeat 1000 test_pk_to_bytes_unsafe_of_bytes_are_inverse_functions_on_any_input); test_case "pk_of_bytes_exn does verify the input represents a point in the \ subgroup" `Quick test_pk_of_bytes_exn_does_verify_the_input_represents_a_point_in_the_subgroup; test_case "pk_of_bytes_opt does verify the input represents a point in the \ subgroup" `Quick test_pk_of_bytes_opt_does_verify_the_input_represents_a_point_in_the_subgroup; test_case "pk_of_bytes_opt does check the input" `Quick test_pk_of_bytes_opt_does_check_the_input; test_case "unsafe_signature_of_bytes does no check on the input" `Quick test_unsafe_signature_of_bytes_does_no_check_on_the_input; test_case "signature_of_bytes_exn accepts points in the subgroup and in \ compressed form" `Quick (Test_ec_make.repeat 1000 test_signature_of_bytes_exn_accepts_points_in_the_subgroup_and_in_compressed_form); test_case "signature_of_bytes_opt accepts points in the subgroup and in \ compressed form" `Quick (Test_ec_make.repeat 1000 test_signature_of_bytes_opt_accepts_points_in_the_subgroup_and_in_compressed_form); test_case "signature_of_bytes_exn does not accept points in the subgroup and \ in uncompressed form" `Quick (Test_ec_make.repeat 1000 test_signature_of_bytes_exn_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form); test_case "signature_of_bytes_opt does not accept points in the subgroup and \ in uncompressed form" `Quick (Test_ec_make.repeat 1000 test_signature_of_bytes_opt_does_not_accept_points_in_the_subgroup_and_in_uncompressed_form); test_case "unsafe_signature_of_bytes copies the input" `Quick (Test_ec_make.repeat 1000 test_unsafe_signature_of_bytes_copies_the_input); test_case "signature_of_bytes_exn copies the input" `Quick (Test_ec_make.repeat 1000 test_signature_of_bytes_exn_copies_the_input); test_case "signature_of_bytes_opt copies the input" `Quick (Test_ec_make.repeat 1000 test_signature_of_bytes_opt_copies_the_input); test_case "unsafe_signature_of_bytes accepts points not in the subgroup" `Quick test_unsafe_signature_of_bytes_accepts_points_not_in_the_subgroup; test_case "signature_of_bytes_exn does check the input" `Quick test_signature_of_bytes_exn_does_check_the_input; test_case "signature_of_bytes_opt and signature_to_bytes are inverse \ functions on valid inputs" `Quick (Test_ec_make.repeat 1000 test_signature_to_bytes_of_bytes_opt_are_inverse_functions_on_valid_inputs); test_case "unsafe_signature_of_bytes and signature_to_bytes are inverse \ functions on valid inputs" `Quick (Test_ec_make.repeat 1000 test_signature_to_bytes_unsafe_of_bytes_are_inverse_functions_on_valid_inputs); test_case "signature_of_bytes_exn and signature_to_bytes are inverse \ functions on valid inputs" `Quick (Test_ec_make.repeat 1000 test_signature_to_bytes_of_bytes_exn_are_inverse_functions_on_valid_inputs); test_case "unsafe_signature_of_bytes and signature_to_bytes are inverse \ functions on any valid input" `Quick (Test_ec_make.repeat 1000 test_signature_to_bytes_unsafe_of_bytes_are_inverse_functions_on_any_input); test_case "signature_of_bytes_exn does verify the input represents a point \ in the subgroup" `Quick test_signature_of_bytes_exn_does_verify_the_input_represents_a_point_in_the_subgroup; test_case "signature_of_bytes_opt does verify the input represents a point \ in the subgroup" `Quick test_signature_of_bytes_opt_does_verify_the_input_represents_a_point_in_the_subgroup; test_case "signature_of_bytes_opt does check the input" `Quick test_signature_of_bytes_opt_does_check_the_input ] ); BasicProperties.get_tests (); AugProperties.get_tests (); PopProperties.get_tests (); ( "Proof of possession proof/verify properties and test vectors", [ test_case "Pop G2 from file" `Quick test_pop_g2_from_blst_sigs_ref_files; test_case "Prove and verify with correct keys" `Quick (Test_ec_make.repeat 1000 test_pop_prove_verify_with_correct_keys); test_case "Prove and verify with different pk for verify" `Quick (Test_ec_make.repeat 1000 test_pop_prove_verify_with_different_pk_for_verify); test_case "Verify random proof" `Quick (Test_ec_make.repeat 1000 test_pop_verify_random_proof) ] ) ] end let () = let open Alcotest in let module TestMinPk = MakeTestsForInstantiation (struct let sig_basic_filenames = [ "sig_g2_basic_fips_186_3_B233_blst"; "sig_g2_basic_fips_186_3_B283_blst"; "sig_g2_basic_fips_186_3_B409_blst"; "sig_g2_basic_fips_186_3_B571_blst"; "sig_g2_basic_fips_186_3_K233_blst"; "sig_g2_basic_fips_186_3_K409_blst"; "sig_g2_basic_fips_186_3_K571_blst"; "sig_g2_basic_fips_186_3_P224_blst"; "sig_g2_basic_fips_186_3_P256_blst"; "sig_g2_basic_fips_186_3_P384_blst"; "sig_g2_basic_fips_186_3_P521_blst"; "sig_g2_basic_rfc6979_blst" ] let sig_aug_filenames = [ "sig_g2_aug_fips_186_3_B233_blst"; "sig_g2_aug_fips_186_3_B283_blst"; "sig_g2_aug_fips_186_3_B409_blst"; "sig_g2_aug_fips_186_3_B571_blst"; "sig_g2_aug_fips_186_3_K233_blst"; "sig_g2_aug_fips_186_3_K409_blst"; "sig_g2_aug_fips_186_3_K571_blst"; "sig_g2_aug_fips_186_3_P224_blst"; "sig_g2_aug_fips_186_3_P256_blst"; "sig_g2_aug_fips_186_3_P384_blst"; "sig_g2_aug_fips_186_3_P521_blst"; "sig_g2_aug_rfc6979_blst" ] let sig_pop_filenames = [ "sig_g2_pop_fips_186_3_B233_blst"; "sig_g2_pop_fips_186_3_B283_blst"; "sig_g2_pop_fips_186_3_B409_blst"; "sig_g2_pop_fips_186_3_B571_blst"; "sig_g2_pop_fips_186_3_K233_blst"; "sig_g2_pop_fips_186_3_K409_blst"; "sig_g2_pop_fips_186_3_K571_blst"; "sig_g2_pop_fips_186_3_P224_blst"; "sig_g2_pop_fips_186_3_P256_blst"; "sig_g2_pop_fips_186_3_P384_blst"; "sig_g2_pop_fips_186_3_P521_blst"; "sig_g2_pop_rfc6979_blst" ] (* These elements have been generated by bls12-381-unix-blst, commit ffa2ad5f1c882f05d64c7cb1633c6256b08513bf, by removing the multiplication by the cofactor in the random generator. It can be verified the elements are not in the prime subgroup by checking multiplying by Fr.order does not give zero. *) let pk_not_in_subgroup = [ "a4c9678ad327129f4388e7f7ff781fc8e98d181add820b79d15facdca422b3ee7fb20f7082a7f9b7c7915053191cb013"; "97ae9b4dc6a05cda8bc833dfb983e41423d224bbf6954ce4721a50364a2b37643e18a276ce19b07b83a333f90e2de6c2"; "b1be8c9f94c1435227b9a18fb57a6d9932c1670d16c514d2d9d67839cc0cc19afdcd114d6e06bf8eb8394061bf880bd4"; "b173357ce7e2340dc64c6a5633e6800683fb0a6c0f4af92b383425bd76d915819252ac9459e79a1bae530ea0145338cb"; "a53944773013669c2722949399322703c0b92d877e52b95e0309bdf286d8290314763d61952d6812da50c1826bcaf4c3"; "8fd2557441f4076917ffe8dfb0e12270994351661600e72f48fe654198199f6cc625a041ce3c9b7c765b32cb53e77192" ] (* These points are on the curve, but not in the subgroup, see test_g2.ml to see how it has been generated. It is given in the compressed form as required for the signature. *) let signature_not_in_subgroup = [ "a7da246233ad216e60ee03070a0916154ae9f9dc23310c1191dfb4e277fc757f58a5cf5bdf7a9f322775143c37539cb90798205fd56217b682d5656f7ac7bc0da111dee59d3f863f1b040be659eda7941afb9f1bc5d0fe2beb5e2385e2cfe9ee"; "b112717bbcd089ea99e8216eab455ea5cd462b0b3e3530303b83477f8e1bb7abca269fec10b3eb998f7f6fd1799d58ff11ed0a53bf75f91d2bf73d11bd52d061f401ac6a6ec0ef4a163e480bac85e75b97cb556f500057b9ef4b28bfe196791d"; "86e5fa411047d9632c95747bea64d973757904c935ac0741b9eeefa2c7c4e439baf1d2c1e8633ba6c884ed9fdf1ffbdd129a32c046f355c5126254973115d6df32904498db6ca959d5bf1869f235be4c0e60fc334ed493f864476907cadfef2c"; "88c83e90520a5ea31733cc01e3589e10b2ed755e2faade29199f97645fbf73f52b29297c22a3b1c4fcd3379bceeec832091df6fb3b9d23f04e8267fc41e578002484155562e70f488c2a4c6b11522c66736bc977755c257478f3022656abb630"; "a25099811f52ad463c762197466c476a03951afdb3f0a457efa2b9475376652fba7b2d56f3184dad540a234d471c53a113203f73dd661694586c75d9c418d34cd16504356253e3ba4618f61cbee02880a43efeacb8f9fe1fdc84ceec4f780ba2"; "990f5e1d200d1b9ab842c516ce50992730917a8b2e95ee1a4b830d7d9507c6846ace7a0eed8831a8d1f1e233cd24581215fe8fe85a99f4ca3fe046dba8ac6377fc3c10d73fa94b25c2d534d7a587a507b498754a2534cd85777b2a7f2978eec6"; "a29415562a1d18b11ec8ab2e0b347a9417f9e904cf25f9b1dc40f235507814371fb4568cc1070a0b8c7baf39e0039d1e0b49d4352b095883ccc262e23d8651c49c39c06d0a920d40b2765d550a78c4c1940c8a2b6843a0063402c169f079f0ae"; "8a257ed6d95cb226c3eb57218bd075ba27164fc1b972c4230ee70c7b81c89d38253ccf7ed2896aa5eb3d9fd6021fac000e368080e705f2a65c919539e2d28e6dd1117296b4210fd56db8d96891f8586bd333e9c47f838ed436659a1dafaee16c" ] let pop_filenames = [ "pop_g2_fips_186_3_B233_blst"; "pop_g2_fips_186_3_B283_blst"; "pop_g2_fips_186_3_B409_blst"; "pop_g2_fips_186_3_B571_blst"; "pop_g2_fips_186_3_K233_blst"; "pop_g2_fips_186_3_K409_blst"; "pop_g2_fips_186_3_K571_blst"; "pop_g2_fips_186_3_P224_blst"; "pop_g2_fips_186_3_P256_blst"; "pop_g2_fips_186_3_P384_blst"; "pop_g2_fips_186_3_P521_blst"; "pop_g2_rfc6979_blst" ] end) (Bls12_381.G1) (Bls12_381.G2) (Bls12_381.Signature.MinPk) in let module TestMinSig = MakeTestsForInstantiation (struct let sig_basic_filenames = [ "sig_g1_basic_fips_186_3_B233_blst"; "sig_g1_basic_fips_186_3_B283_blst"; "sig_g1_basic_fips_186_3_B409_blst"; "sig_g1_basic_fips_186_3_B571_blst"; "sig_g1_basic_fips_186_3_K233_blst"; "sig_g1_basic_fips_186_3_K409_blst"; "sig_g1_basic_fips_186_3_K571_blst"; "sig_g1_basic_fips_186_3_P224_blst"; "sig_g1_basic_fips_186_3_P256_blst"; "sig_g1_basic_fips_186_3_P384_blst"; "sig_g1_basic_fips_186_3_P521_blst"; "sig_g1_basic_rfc6979_blst" ] let sig_aug_filenames = [ "sig_g1_aug_fips_186_3_B233_blst"; "sig_g1_aug_fips_186_3_B283_blst"; "sig_g1_aug_fips_186_3_B409_blst"; "sig_g1_aug_fips_186_3_B571_blst"; "sig_g1_aug_fips_186_3_K233_blst"; "sig_g1_aug_fips_186_3_K409_blst"; "sig_g1_aug_fips_186_3_K571_blst"; "sig_g1_aug_fips_186_3_P224_blst"; "sig_g1_aug_fips_186_3_P256_blst"; "sig_g1_aug_fips_186_3_P384_blst"; "sig_g1_aug_fips_186_3_P521_blst"; "sig_g1_aug_rfc6979_blst" ] let sig_pop_filenames = [ "sig_g1_pop_fips_186_3_B233_blst"; "sig_g1_pop_fips_186_3_B283_blst"; "sig_g1_pop_fips_186_3_B409_blst"; "sig_g1_pop_fips_186_3_B571_blst"; "sig_g1_pop_fips_186_3_K233_blst"; "sig_g1_pop_fips_186_3_K409_blst"; "sig_g1_pop_fips_186_3_K571_blst"; "sig_g1_pop_fips_186_3_P224_blst"; "sig_g1_pop_fips_186_3_P256_blst"; "sig_g1_pop_fips_186_3_P384_blst"; "sig_g1_pop_fips_186_3_P521_blst"; "sig_g1_pop_rfc6979_blst" ] (* These elements have been generated by bls12-381-unix-blst, commit ffa2ad5f1c882f05d64c7cb1633c6256b08513bf, by removing the multiplication by the cofactor in the random generator. It can be verified the elements are not in the prime subgroup by checking multiplying by Fr.order does not give zero. *) let signature_not_in_subgroup = [ "a4c9678ad327129f4388e7f7ff781fc8e98d181add820b79d15facdca422b3ee7fb20f7082a7f9b7c7915053191cb013"; "97ae9b4dc6a05cda8bc833dfb983e41423d224bbf6954ce4721a50364a2b37643e18a276ce19b07b83a333f90e2de6c2"; "b1be8c9f94c1435227b9a18fb57a6d9932c1670d16c514d2d9d67839cc0cc19afdcd114d6e06bf8eb8394061bf880bd4"; "b173357ce7e2340dc64c6a5633e6800683fb0a6c0f4af92b383425bd76d915819252ac9459e79a1bae530ea0145338cb"; "a53944773013669c2722949399322703c0b92d877e52b95e0309bdf286d8290314763d61952d6812da50c1826bcaf4c3"; "8fd2557441f4076917ffe8dfb0e12270994351661600e72f48fe654198199f6cc625a041ce3c9b7c765b32cb53e77192" ] (* These points are on the curve, but not in the subgroup, see test_g2.ml to see how it has been generated. It is given in the compressed form as required for the signature. *) let pk_not_in_subgroup = [ "a7da246233ad216e60ee03070a0916154ae9f9dc23310c1191dfb4e277fc757f58a5cf5bdf7a9f322775143c37539cb90798205fd56217b682d5656f7ac7bc0da111dee59d3f863f1b040be659eda7941afb9f1bc5d0fe2beb5e2385e2cfe9ee"; "b112717bbcd089ea99e8216eab455ea5cd462b0b3e3530303b83477f8e1bb7abca269fec10b3eb998f7f6fd1799d58ff11ed0a53bf75f91d2bf73d11bd52d061f401ac6a6ec0ef4a163e480bac85e75b97cb556f500057b9ef4b28bfe196791d"; "86e5fa411047d9632c95747bea64d973757904c935ac0741b9eeefa2c7c4e439baf1d2c1e8633ba6c884ed9fdf1ffbdd129a32c046f355c5126254973115d6df32904498db6ca959d5bf1869f235be4c0e60fc334ed493f864476907cadfef2c"; "88c83e90520a5ea31733cc01e3589e10b2ed755e2faade29199f97645fbf73f52b29297c22a3b1c4fcd3379bceeec832091df6fb3b9d23f04e8267fc41e578002484155562e70f488c2a4c6b11522c66736bc977755c257478f3022656abb630"; "a25099811f52ad463c762197466c476a03951afdb3f0a457efa2b9475376652fba7b2d56f3184dad540a234d471c53a113203f73dd661694586c75d9c418d34cd16504356253e3ba4618f61cbee02880a43efeacb8f9fe1fdc84ceec4f780ba2"; "990f5e1d200d1b9ab842c516ce50992730917a8b2e95ee1a4b830d7d9507c6846ace7a0eed8831a8d1f1e233cd24581215fe8fe85a99f4ca3fe046dba8ac6377fc3c10d73fa94b25c2d534d7a587a507b498754a2534cd85777b2a7f2978eec6"; "a29415562a1d18b11ec8ab2e0b347a9417f9e904cf25f9b1dc40f235507814371fb4568cc1070a0b8c7baf39e0039d1e0b49d4352b095883ccc262e23d8651c49c39c06d0a920d40b2765d550a78c4c1940c8a2b6843a0063402c169f079f0ae"; "8a257ed6d95cb226c3eb57218bd075ba27164fc1b972c4230ee70c7b81c89d38253ccf7ed2896aa5eb3d9fd6021fac000e368080e705f2a65c919539e2d28e6dd1117296b4210fd56db8d96891f8586bd333e9c47f838ed436659a1dafaee16c" ] let pop_filenames = [ "pop_g1_fips_186_3_B233_blst"; "pop_g1_fips_186_3_B283_blst"; "pop_g1_fips_186_3_B409_blst"; "pop_g1_fips_186_3_B571_blst"; "pop_g1_fips_186_3_K233_blst"; "pop_g1_fips_186_3_K409_blst"; "pop_g1_fips_186_3_K571_blst"; "pop_g1_fips_186_3_P224_blst"; "pop_g1_fips_186_3_P256_blst"; "pop_g1_fips_186_3_P384_blst"; "pop_g1_fips_186_3_P521_blst"; "pop_g1_rfc6979_blst" ] end) (Bls12_381.G2) (Bls12_381.G1) (Bls12_381.Signature.MinSig) in let min_pk_tests = TestMinPk.get_tests () in let min_pk_tests = List.map (fun (s, tests) -> ("MinPk " ^ s, tests)) min_pk_tests in let min_sig_tests = TestMinSig.get_tests () in let min_sig_tests = List.map (fun (s, tests) -> ("MinSig " ^ s, tests)) min_sig_tests in let all_tests = List.concat [min_pk_tests; min_sig_tests] in run "BLS Signature" (( "Common features to both instanciations", [ test_case "Size in bytes of sk" `Quick test_sk_size_in_bytes; test_case "generate_sk raises Invalid_argument is ikm is smaller than 32 bytes" `Quick test_keygen_raise_invalid_argument_if_ikm_too_small ] ) :: all_tests)
(* utils *) let read_file filename =
dune
; This file was automatically generated, do not edit. ; Edit file manifest/main.ml instead. (library (name tezos_client_002_PsYLVpVv) (public_name tezos-client-002-PsYLVpVv) (libraries tezos-base tezos-clic tezos-shell-services tezos-client-base tezos-protocol-002-PsYLVpVv tezos-signer-backends tezos-rpc uri) (library_flags (:standard -linkall)) (flags (:standard) -open Tezos_base.TzPervasives -open Tezos_base.TzPervasives.Error_monad.Legacy_monad_globals -open Tezos_shell_services -open Tezos_client_base -open Tezos_protocol_002_PsYLVpVv))
fitness_repr.ml
type error += Invalid_fitness (* `Permanent *) let () = register_error_kind `Permanent ~id:"invalid_fitness" ~title:"Invalid fitness" ~description:"Fitness representation should be exactly 8 bytes long." ~pp:(fun ppf () -> Format.fprintf ppf "Invalid fitness") Data_encoding.empty (function Invalid_fitness -> Some () | _ -> None) (fun () -> Invalid_fitness) let int64_to_bytes i = let b = MBytes.create 8 in MBytes.set_int64 b 0 i; b let int64_of_bytes b = if Compare.Int.(MBytes.length b <> 8) then error Invalid_fitness else ok (MBytes.get_int64 b 0) let from_int64 fitness = [ MBytes.of_string Constants_repr.version_number ; int64_to_bytes fitness ] let to_int64 = function | [ version ; fitness ] when Compare.String. (MBytes.to_string version = Constants_repr.version_number) -> int64_of_bytes fitness | [] -> ok 0L | _ -> error Invalid_fitness
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
storage_functors.ml
open Storage_sigs module Registered = struct let ghost = false end module Ghost = struct let ghost = true end module type ENCODER = sig type t val of_bytes : key:(unit -> string list) -> bytes -> t tzresult val to_bytes : t -> bytes end module Make_encoder (V : VALUE) : ENCODER with type t := V.t = struct let of_bytes ~key b = match Data_encoding.Binary.of_bytes_opt V.encoding b with | None -> error (Raw_context.Storage_error (Corrupted_data (key ()))) | Some v -> Ok v let to_bytes v = match Data_encoding.Binary.to_bytes_opt V.encoding v with | Some b -> b | None -> Bytes.empty end let len_name = "len" let data_name = "data" let encode_len_value bytes = let length = Bytes.length bytes in Data_encoding.(Binary.to_bytes_exn int31) length let decode_len_value key len = match Data_encoding.(Binary.of_bytes_opt int31) len with | None -> error (Raw_context.Storage_error (Corrupted_data key)) | Some len -> ok len module Make_subcontext (R : REGISTER) (C : Raw_context.T) (N : NAME) : Raw_context.T with type t = C.t = struct type t = C.t let to_key k = N.name @ k let mem t k = C.mem t (to_key k) let mem_tree t k = C.mem_tree t (to_key k) let get t k = C.get t (to_key k) let get_tree t k = C.get_tree t (to_key k) let find t k = C.find t (to_key k) let find_tree t k = C.find_tree t (to_key k) let add t k v = C.add t (to_key k) v let add_tree t k v = C.add_tree t (to_key k) v let init t k v = C.init t (to_key k) v let init_tree t k v = C.init_tree t (to_key k) v let update t k v = C.update t (to_key k) v let update_tree t k v = C.update_tree t (to_key k) v let add_or_remove t k v = C.add_or_remove t (to_key k) v let add_or_remove_tree t k v = C.add_or_remove_tree t (to_key k) v let remove_existing t k = C.remove_existing t (to_key k) let remove_existing_tree t k = C.remove_existing_tree t (to_key k) let remove t k = C.remove t (to_key k) let list t ?offset ?length k = C.list t ?offset ?length (to_key k) let fold ?depth t k ~order ~init ~f = C.fold ?depth t (to_key k) ~order ~init ~f let config t = C.config t module Tree = C.Tree module Proof = C.Proof let verify_tree_proof = C.verify_tree_proof let verify_stream_proof = C.verify_stream_proof let equal_config = C.equal_config let project = C.project let absolute_key c k = C.absolute_key c (to_key k) type error += Block_quota_exceeded = C.Block_quota_exceeded type error += Operation_quota_exceeded = C.Operation_quota_exceeded let consume_gas = C.consume_gas let check_enough_gas = C.check_enough_gas let description = let description = if R.ghost then Storage_description.create () else C.description in Storage_description.register_named_subcontext description N.name let length = C.length end module Make_single_data_storage (R : REGISTER) (C : Raw_context.T) (N : NAME) (V : VALUE) : Single_data_storage with type t = C.t and type value = V.t = struct type t = C.t type context = t type value = V.t let mem t = C.mem t N.name include Make_encoder (V) let get t = C.get t N.name >>=? fun b -> let key () = C.absolute_key t N.name in Lwt.return (of_bytes ~key b) let find t = C.find t N.name >|= function | None -> Result.return_none | Some b -> let key () = C.absolute_key t N.name in of_bytes ~key b >|? fun v -> Some v let init t v = C.init t N.name (to_bytes v) >|=? fun t -> C.project t let update t v = C.update t N.name (to_bytes v) >|=? fun t -> C.project t let add t v = C.add t N.name (to_bytes v) >|= fun t -> C.project t let add_or_remove t v = C.add_or_remove t N.name (Option.map to_bytes v) >|= fun t -> C.project t let remove t = C.remove t N.name >|= fun t -> C.project t let remove_existing t = C.remove_existing t N.name >|=? fun t -> C.project t let () = let open Storage_description in let description = if R.ghost then Storage_description.create () else C.description in register_value ~get:find (register_named_subcontext description N.name) V.encoding [@@coq_axiom_with_reason "stack overflow in Coq"] end module type INDEX = sig type t include Path_encoding.S with type t := t type 'a ipath val args : ('a, t, 'a ipath) Storage_description.args end module Pair (I1 : INDEX) (I2 : INDEX) : INDEX with type t = I1.t * I2.t = struct type t = I1.t * I2.t let path_length = I1.path_length + I2.path_length let to_path (x, y) l = I1.to_path x (I2.to_path y l) let of_path l = match Misc.take I1.path_length l with | None -> None | Some (l1, l2) -> ( match (I1.of_path l1, I2.of_path l2) with | Some x, Some y -> Some (x, y) | _ -> None) type 'a ipath = 'a I1.ipath I2.ipath let args = Storage_description.Pair (I1.args, I2.args) end module Make_data_set_storage (C : Raw_context.T) (I : INDEX) : Data_set_storage with type t = C.t and type elt = I.t = struct type t = C.t type context = t type elt = I.t let inited = Bytes.of_string "inited" let mem s i = C.mem s (I.to_path i []) let add s i = C.add s (I.to_path i []) inited >|= fun t -> C.project t let remove s i = C.remove s (I.to_path i []) >|= fun t -> C.project t let clear s = C.remove s [] >|= fun t -> C.project t let fold s ~order ~init ~f = C.fold ~depth:(`Eq I.path_length) s [] ~order ~init ~f:(fun file tree acc -> match C.Tree.kind tree with | `Value -> ( match I.of_path file with None -> assert false | Some p -> f p acc) | `Tree -> Lwt.return acc) let elements s = fold s ~order:`Sorted ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc)) let () = let open Storage_description in let unpack = unpack I.args in register_value (* TODO fixme 'elements...' *) ~get:(fun c -> let c, k = unpack c in mem c k >>= function true -> return_some true | false -> return_none) (register_indexed_subcontext ~list:(fun c -> elements c >|= ok) C.description I.args) Data_encoding.bool [@@coq_axiom_with_reason "stack overflow in Coq"] end module Make_indexed_data_storage (C : Raw_context.T) (I : INDEX) (V : VALUE) : Indexed_data_storage with type t = C.t and type key = I.t and type value = V.t = struct type t = C.t type context = t type key = I.t type value = V.t include Make_encoder (V) let mem s i = C.mem s (I.to_path i []) let get s i = C.get s (I.to_path i []) >>=? fun b -> let key () = C.absolute_key s (I.to_path i []) in Lwt.return (of_bytes ~key b) let find s i = C.find s (I.to_path i []) >|= function | None -> Result.return_none | Some b -> let key () = C.absolute_key s (I.to_path i []) in of_bytes ~key b >|? fun v -> Some v let update s i v = C.update s (I.to_path i []) (to_bytes v) >|=? fun t -> C.project t let init s i v = C.init s (I.to_path i []) (to_bytes v) >|=? fun t -> C.project t let add s i v = C.add s (I.to_path i []) (to_bytes v) >|= fun t -> C.project t let add_or_remove s i v = C.add_or_remove s (I.to_path i []) (Option.map to_bytes v) >|= fun t -> C.project t let remove s i = C.remove s (I.to_path i []) >|= fun t -> C.project t let remove_existing s i = C.remove_existing s (I.to_path i []) >|=? fun t -> C.project t let clear s = C.remove s [] >|= fun t -> C.project t let fold s ~order ~init ~f = C.fold ~depth:(`Eq I.path_length) s [] ~order ~init ~f:(fun file tree acc -> C.Tree.to_value tree >>= function | Some v -> ( match I.of_path file with | None -> assert false | Some path -> ( let key () = C.absolute_key s file in match of_bytes ~key v with | Ok v -> f path v acc | Error _ -> Lwt.return acc)) | None -> Lwt.return acc) let fold_keys s ~order ~init ~f = fold s ~order ~init ~f:(fun k _ acc -> f k acc) let bindings s = fold s ~order:`Sorted ~init:[] ~f:(fun p v acc -> Lwt.return ((p, v) :: acc)) let keys s = fold_keys s ~order:`Sorted ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc)) let () = let open Storage_description in let unpack = unpack I.args in register_value ~get:(fun c -> let c, k = unpack c in find c k) (register_indexed_subcontext ~list:(fun c -> keys c >|= ok) C.description I.args) V.encoding [@@coq_axiom_with_reason "stack overflow in Coq"] end (* Internal-use-only version of {!Make_indexed_carbonated_data_storage} to expose fold_keys_unaccounted *) module Make_indexed_carbonated_data_storage_INTERNAL (C : Raw_context.T) (I : INDEX) (V : VALUE) : Non_iterable_indexed_carbonated_data_storage_INTERNAL with type t = C.t and type key = I.t and type value = V.t = struct type t = C.t type context = t type key = I.t type value = V.t include Make_encoder (V) let data_key i = I.to_path i [data_name] let len_key i = I.to_path i [len_name] let consume_mem_gas c key = let path_length = List.length @@ C.absolute_key c key in C.consume_gas c (Storage_costs.read_access ~path_length ~read_bytes:0) let existing_size c i = C.find c (len_key i) >|= function | None -> ok (0, false) | Some len -> decode_len_value (len_key i) len >|? fun len -> (len, true) let consume_read_gas get c i = let len_key = len_key i in get c len_key >>=? fun len -> let path_length = List.length @@ C.absolute_key c len_key in Lwt.return ( decode_len_value len_key len >>? fun read_bytes -> let cost = Storage_costs.read_access ~path_length ~read_bytes in C.consume_gas c cost ) (* For the future: here, we bill a generic cost for encoding the value to bytes. It would be cleaner for users of this functor to provide gas costs for the encoding. *) let consume_serialize_write_gas set c i v = let bytes = to_bytes v in let len = Bytes.length bytes in C.consume_gas c (Gas_limit_repr.alloc_mbytes_cost len) >>?= fun c -> let cost = Storage_costs.write_access ~written_bytes:len in C.consume_gas c cost >>?= fun c -> set c (len_key i) (encode_len_value bytes) >|=? fun c -> (c, bytes) let consume_remove_gas del c i = C.consume_gas c (Storage_costs.write_access ~written_bytes:0) >>?= fun c -> del c (len_key i) let mem s i = let key = data_key i in consume_mem_gas s key >>?= fun s -> C.mem s key >|= fun exists -> ok (C.project s, exists) let get_unprojected s i = consume_read_gas C.get s i >>=? fun s -> C.get s (data_key i) >>=? fun b -> let key () = C.absolute_key s (data_key i) in Lwt.return (of_bytes ~key b >|? fun v -> (s, v)) let get s i = get_unprojected s i >|=? fun (s, v) -> (C.project s, v) let find s i = let key = data_key i in consume_mem_gas s key >>?= fun s -> C.mem s key >>= fun exists -> if exists then get s i >|=? fun (s, v) -> (s, Some v) else return (C.project s, None) let update s i v = existing_size s i >>=? fun (prev_size, _) -> consume_serialize_write_gas C.update s i v >>=? fun (s, bytes) -> C.update s (data_key i) bytes >|=? fun t -> let size_diff = Bytes.length bytes - prev_size in (C.project t, size_diff) let init s i v = consume_serialize_write_gas C.init s i v >>=? fun (s, bytes) -> C.init s (data_key i) bytes >|=? fun t -> let size = Bytes.length bytes in (C.project t, size) let add s i v = let add s i v = C.add s i v >|= ok in existing_size s i >>=? fun (prev_size, existed) -> consume_serialize_write_gas add s i v >>=? fun (s, bytes) -> add s (data_key i) bytes >|=? fun t -> let size_diff = Bytes.length bytes - prev_size in (C.project t, size_diff, existed) let remove s i = let remove s i = C.remove s i >|= ok in existing_size s i >>=? fun (prev_size, existed) -> consume_remove_gas remove s i >>=? fun s -> remove s (data_key i) >|=? fun t -> (C.project t, prev_size, existed) let remove_existing s i = existing_size s i >>=? fun (prev_size, _) -> consume_remove_gas C.remove_existing s i >>=? fun s -> C.remove_existing s (data_key i) >|=? fun t -> (C.project t, prev_size) let add_or_remove s i v = match v with None -> remove s i | Some v -> add s i v (** Because big map values are not stored under some common key, we have no choice but to fold over all nodes with a path of length [I.path_length] to retrieve actual keys and then paginate. While this is inefficient and will traverse the whole tree ([O(n)]), there currently isn't a better decent alternative. Once https://gitlab.com/tezos/tezos/-/merge_requests/2771 which flattens paths is done, {!C.list} could be used instead here. *) let list_values ?(offset = 0) ?(length = max_int) s = let root = [] in let depth = `Eq I.path_length in C.fold s root ~depth ~order:`Sorted ~init:(ok (s, [], offset, length)) ~f:(fun file tree acc -> match (C.Tree.kind tree, acc) with | `Tree, Ok (s, rev_values, offset, length) -> ( if Compare.Int.(length <= 0) then (* Keep going until the end, we have no means of short-circuiting *) Lwt.return acc else if Compare.Int.(offset > 0) then (* Offset (first element) not reached yet *) let offset = pred offset in Lwt.return (Ok (s, rev_values, offset, length)) else (* Nominal case *) match I.of_path file with | None -> assert false | Some key -> get_unprojected s key >|=? fun (s, value) -> (s, value :: rev_values, 0, pred length)) | _ -> Lwt.return acc) >|=? fun (s, rev_values, _offset, _length) -> (C.project s, List.rev rev_values) let fold_keys_unaccounted s ~order ~init ~f = C.fold ~depth:(`Eq (1 + I.path_length)) s [] ~order ~init ~f:(fun file tree acc -> match C.Tree.kind tree with | `Value -> ( match List.rev file with | last :: _ when Compare.String.(last = len_name) -> Lwt.return acc | last :: rest when Compare.String.(last = data_name) -> ( let file = List.rev rest in match I.of_path file with | None -> assert false | Some path -> f path acc) | _ -> assert false) | `Tree -> Lwt.return acc) let keys_unaccounted s = fold_keys_unaccounted s ~order:`Sorted ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc)) let () = let open Storage_description in let unpack = unpack I.args in register_value (* TODO export consumed gas ?? *) ~get:(fun c -> let c, k = unpack c in find c k >|=? fun (_, v) -> v) (register_indexed_subcontext ~list:(fun c -> keys_unaccounted c >|= ok) C.description I.args) V.encoding [@@coq_axiom_with_reason "stack overflow in Coq"] end module Make_indexed_carbonated_data_storage : functor (C : Raw_context.T) (I : INDEX) (V : VALUE) -> Non_iterable_indexed_carbonated_data_storage_with_values with type t = C.t and type key = I.t and type value = V.t = Make_indexed_carbonated_data_storage_INTERNAL module Make_carbonated_data_set_storage (C : Raw_context.T) (I : INDEX) : Carbonated_data_set_storage with type t = C.t and type elt = I.t = struct module V = struct type t = unit let encoding = Data_encoding.unit end module M = Make_indexed_carbonated_data_storage_INTERNAL (C) (I) (V) type t = M.t type context = t type elt = I.t let mem = M.mem let init s i = M.init s i () let add s i = M.add s i () let remove s i = M.remove s i let fold_keys_unaccounted = M.fold_keys_unaccounted end module Make_indexed_data_snapshotable_storage (C : Raw_context.T) (Snapshot_index : INDEX) (I : INDEX) (V : VALUE) : Indexed_data_snapshotable_storage with type t = C.t and type snapshot = Snapshot_index.t and type key = I.t and type value = V.t = struct type snapshot = Snapshot_index.t let data_name = ["current"] let snapshot_name = ["snapshot"] module C_data = Make_subcontext (Registered) (C) (struct let name = data_name end) module C_snapshot = Make_subcontext (Registered) (C) (struct let name = snapshot_name end) module V_encoder = Make_encoder (V) include Make_indexed_data_storage (C_data) (I) (V) module Snapshot = Make_indexed_data_storage (C_snapshot) (Pair (Snapshot_index) (I)) (V) let snapshot_path id = snapshot_name @ Snapshot_index.to_path id [] let snapshot_exists s id = C.mem_tree s (snapshot_path id) let err_missing_key key = Raw_context.storage_error (Missing_key (key, Copy)) let snapshot s id = C.find_tree s data_name >>= function | None -> Lwt.return (err_missing_key data_name) | Some tree -> C.add_tree s (snapshot_path id) tree >|= (fun t -> C.project t) >|= ok let fold_snapshot s id ~order ~init ~f = C.find_tree s (snapshot_path id) >>= function | None -> Lwt.return (err_missing_key data_name) | Some tree -> C_data.Tree.fold tree ~depth:(`Eq I.path_length) [] ~order ~init:(Ok init) ~f:(fun file tree acc -> acc >>?= fun acc -> C.Tree.to_value tree >>= function | Some v -> ( match I.of_path file with | None -> assert false | Some path -> ( let key () = C.absolute_key s file in match V_encoder.of_bytes ~key v with | Ok v -> f path v acc | Error _ -> return acc)) | None -> return acc) let delete_snapshot s id = C.remove s (snapshot_path id) >|= fun t -> C.project t end module Make_indexed_subcontext (C : Raw_context.T) (I : INDEX) : Indexed_raw_context with type t = C.t and type key = I.t and type 'a ipath = 'a I.ipath = struct type t = C.t type context = t type key = I.t type 'a ipath = 'a I.ipath let clear t = C.remove t [] >|= fun t -> C.project t let fold_keys t ~order ~init ~f = C.fold ~depth:(`Eq I.path_length) t [] ~order ~init ~f:(fun path tree acc -> match C.Tree.kind tree with | `Tree -> ( match I.of_path path with | None -> assert false | Some path -> f path acc) | `Value -> Lwt.return acc) let keys t = fold_keys t ~order:`Sorted ~init:[] ~f:(fun i acc -> Lwt.return (i :: acc)) let err_missing_key key = Raw_context.storage_error (Missing_key (key, Copy)) let copy t ~from ~to_ = let from = I.to_path from [] in let to_ = I.to_path to_ [] in C.find_tree t from >>= function | None -> Lwt.return (err_missing_key from) | Some tree -> C.add_tree t to_ tree >|= ok let remove t k = C.remove t (I.to_path k []) let description = Storage_description.register_indexed_subcontext ~list:(fun c -> keys c >|= ok) C.description I.args let unpack = Storage_description.unpack I.args let pack = Storage_description.pack I.args module Raw_context : Raw_context.T with type t = C.t I.ipath = struct type t = C.t I.ipath let to_key i k = I.to_path i k let mem c k = let t, i = unpack c in C.mem t (to_key i k) let mem_tree c k = let t, i = unpack c in C.mem_tree t (to_key i k) let get c k = let t, i = unpack c in C.get t (to_key i k) let get_tree c k = let t, i = unpack c in C.get_tree t (to_key i k) let find c k = let t, i = unpack c in C.find t (to_key i k) let find_tree c k = let t, i = unpack c in C.find_tree t (to_key i k) let list c ?offset ?length k = let t, i = unpack c in C.list t ?offset ?length (to_key i k) let init c k v = let t, i = unpack c in C.init t (to_key i k) v >|=? fun t -> pack t i let init_tree c k v = let t, i = unpack c in C.init_tree t (to_key i k) v >|=? fun t -> pack t i let update c k v = let t, i = unpack c in C.update t (to_key i k) v >|=? fun t -> pack t i let update_tree c k v = let t, i = unpack c in C.update_tree t (to_key i k) v >|=? fun t -> pack t i let add c k v = let t, i = unpack c in C.add t (to_key i k) v >|= fun t -> pack t i let add_tree c k v = let t, i = unpack c in C.add_tree t (to_key i k) v >|= fun t -> pack t i let add_or_remove c k v = let t, i = unpack c in C.add_or_remove t (to_key i k) v >|= fun t -> pack t i let add_or_remove_tree c k v = let t, i = unpack c in C.add_or_remove_tree t (to_key i k) v >|= fun t -> pack t i let remove_existing c k = let t, i = unpack c in C.remove_existing t (to_key i k) >|=? fun t -> pack t i let remove_existing_tree c k = let t, i = unpack c in C.remove_existing_tree t (to_key i k) >|=? fun t -> pack t i let remove c k = let t, i = unpack c in C.remove t (to_key i k) >|= fun t -> pack t i let fold ?depth c k ~order ~init ~f = let t, i = unpack c in C.fold ?depth t (to_key i k) ~order ~init ~f let config c = let t, _ = unpack c in C.config t module Tree = struct include C.Tree let empty c = let t, _ = unpack c in C.Tree.empty t end module Proof = C.Proof let verify_tree_proof = C.verify_tree_proof let verify_stream_proof = C.verify_stream_proof let equal_config = C.equal_config let project c = let t, _ = unpack c in C.project t let absolute_key c k = let t, i = unpack c in C.absolute_key t (to_key i k) type error += Block_quota_exceeded = C.Block_quota_exceeded type error += Operation_quota_exceeded = C.Operation_quota_exceeded let consume_gas c g = let t, i = unpack c in C.consume_gas t g >>? fun t -> ok (pack t i) let check_enough_gas c g = let t, _i = unpack c in C.check_enough_gas t g let description = description let length c = let t, _i = unpack c in C.length t end module Make_set (R : REGISTER) (N : NAME) : Data_set_storage with type t = t and type elt = key = struct type t = C.t type context = t type elt = I.t let inited = Bytes.of_string "inited" let mem s i = Raw_context.mem (pack s i) N.name let add s i = Raw_context.add (pack s i) N.name inited >|= fun c -> let s, _ = unpack c in C.project s let remove s i = Raw_context.remove (pack s i) N.name >|= fun c -> let s, _ = unpack c in C.project s let clear s = fold_keys s ~init:s ~order:`Sorted ~f:(fun i s -> Raw_context.remove (pack s i) N.name >|= fun c -> let s, _ = unpack c in s) >|= fun t -> C.project t let fold s ~order ~init ~f = fold_keys s ~order ~init ~f:(fun i acc -> mem s i >>= function true -> f i acc | false -> Lwt.return acc) let elements s = fold s ~order:`Sorted ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc)) let () = let open Storage_description in let unpack = unpack I.args in let description = if R.ghost then Storage_description.create () else Raw_context.description in register_value ~get:(fun c -> let c, k = unpack c in mem c k >>= function true -> return_some true | false -> return_none) (register_named_subcontext description N.name) Data_encoding.bool [@@coq_axiom_with_reason "stack overflow in Coq"] end module Make_map (N : NAME) (V : VALUE) : Indexed_data_storage with type t = t and type key = key and type value = V.t = struct type t = C.t type context = t type key = I.t type value = V.t include Make_encoder (V) let mem s i = Raw_context.mem (pack s i) N.name let get s i = Raw_context.get (pack s i) N.name >>=? fun b -> let key () = Raw_context.absolute_key (pack s i) N.name in Lwt.return (of_bytes ~key b) let find s i = Raw_context.find (pack s i) N.name >|= function | None -> Result.return_none | Some b -> let key () = Raw_context.absolute_key (pack s i) N.name in of_bytes ~key b >|? fun v -> Some v let update s i v = Raw_context.update (pack s i) N.name (to_bytes v) >|=? fun c -> let s, _ = unpack c in C.project s let init s i v = Raw_context.init (pack s i) N.name (to_bytes v) >|=? fun c -> let s, _ = unpack c in C.project s let add s i v = Raw_context.add (pack s i) N.name (to_bytes v) >|= fun c -> let s, _ = unpack c in C.project s let add_or_remove s i v = Raw_context.add_or_remove (pack s i) N.name (Option.map to_bytes v) >|= fun c -> let s, _ = unpack c in C.project s let remove s i = Raw_context.remove (pack s i) N.name >|= fun c -> let s, _ = unpack c in C.project s let remove_existing s i = Raw_context.remove_existing (pack s i) N.name >|=? fun c -> let s, _ = unpack c in C.project s let clear s = fold_keys s ~order:`Sorted ~init:s ~f:(fun i s -> Raw_context.remove (pack s i) N.name >|= fun c -> let s, _ = unpack c in s) >|= fun t -> C.project t let fold s ~order ~init ~f = fold_keys s ~order ~init ~f:(fun i acc -> get s i >>= function Error _ -> Lwt.return acc | Ok v -> f i v acc) let bindings s = fold s ~order:`Sorted ~init:[] ~f:(fun p v acc -> Lwt.return ((p, v) :: acc)) let fold_keys s ~order ~init ~f = fold_keys s ~order ~init ~f:(fun i acc -> mem s i >>= function false -> Lwt.return acc | true -> f i acc) let keys s = fold_keys s ~order:`Sorted ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc)) let () = let open Storage_description in let unpack = unpack I.args in register_value ~get:(fun c -> let c, k = unpack c in find c k) (register_named_subcontext Raw_context.description N.name) V.encoding [@@coq_axiom_with_reason "stack overflow in Coq"] end module Make_carbonated_map (N : NAME) (V : VALUE) : Non_iterable_indexed_carbonated_data_storage with type t = t and type key = key and type value = V.t = struct type t = C.t type context = t type key = I.t type value = V.t include Make_encoder (V) let len_name = len_name :: N.name let data_name = data_name :: N.name let consume_mem_gas c = let path_length = List.length (Raw_context.absolute_key c N.name) + 1 in Raw_context.consume_gas c (Storage_costs.read_access ~path_length ~read_bytes:0) let existing_size c = Raw_context.find c len_name >|= function | None -> ok (0, false) | Some len -> decode_len_value len_name len >|? fun len -> (len, true) let consume_read_gas get c = let path_length = List.length (Raw_context.absolute_key c N.name) + 1 in get c len_name >>=? fun len -> Lwt.return ( decode_len_value len_name len >>? fun read_bytes -> Raw_context.consume_gas c (Storage_costs.read_access ~path_length ~read_bytes) ) let consume_write_gas set c v = let bytes = to_bytes v in let len = Bytes.length bytes in Raw_context.consume_gas c (Storage_costs.write_access ~written_bytes:len) >>?= fun c -> set c len_name (encode_len_value bytes) >|=? fun c -> (c, bytes) let consume_remove_gas del c = Raw_context.consume_gas c (Storage_costs.write_access ~written_bytes:0) >>?= fun c -> del c len_name let mem s i = consume_mem_gas (pack s i) >>?= fun c -> Raw_context.mem c data_name >|= fun res -> ok (Raw_context.project c, res) let get s i = consume_read_gas Raw_context.get (pack s i) >>=? fun c -> Raw_context.get c data_name >>=? fun b -> let key () = Raw_context.absolute_key c data_name in Lwt.return (of_bytes ~key b >|? fun v -> (Raw_context.project c, v)) let find s i = consume_mem_gas (pack s i) >>?= fun c -> let s, _ = unpack c in Raw_context.mem (pack s i) data_name >>= fun exists -> if exists then get s i >|=? fun (s, v) -> (s, Some v) else return (C.project s, None) let update s i v = existing_size (pack s i) >>=? fun (prev_size, _) -> consume_write_gas Raw_context.update (pack s i) v >>=? fun (c, bytes) -> Raw_context.update c data_name bytes >|=? fun c -> let size_diff = Bytes.length bytes - prev_size in (Raw_context.project c, size_diff) let init s i v = consume_write_gas Raw_context.init (pack s i) v >>=? fun (c, bytes) -> Raw_context.init c data_name bytes >|=? fun c -> let size = Bytes.length bytes in (Raw_context.project c, size) let add s i v = let add c k v = Raw_context.add c k v >|= ok in existing_size (pack s i) >>=? fun (prev_size, existed) -> consume_write_gas add (pack s i) v >>=? fun (c, bytes) -> add c data_name bytes >|=? fun c -> let size_diff = Bytes.length bytes - prev_size in (Raw_context.project c, size_diff, existed) let remove s i = let remove c k = Raw_context.remove c k >|= ok in existing_size (pack s i) >>=? fun (prev_size, existed) -> consume_remove_gas remove (pack s i) >>=? fun c -> remove c data_name >|=? fun c -> (Raw_context.project c, prev_size, existed) let remove_existing s i = existing_size (pack s i) >>=? fun (prev_size, _) -> consume_remove_gas Raw_context.remove_existing (pack s i) >>=? fun c -> Raw_context.remove_existing c data_name >|=? fun c -> (Raw_context.project c, prev_size) let add_or_remove s i v = match v with None -> remove s i | Some v -> add s i v let () = let open Storage_description in let unpack = unpack I.args in register_value ~get:(fun c -> let c, k = unpack c in find c k >|=? fun (_, v) -> v) (register_named_subcontext Raw_context.description N.name) V.encoding [@@coq_axiom_with_reason "stack overflow in Coq"] end end module type WRAPPER = sig type t type key val wrap : t -> key val unwrap : key -> t option end module Wrap_indexed_data_storage (C : Indexed_data_storage) (K : WRAPPER with type key := C.key) : Indexed_data_storage with type t = C.t and type key = K.t and type value = C.value = struct type t = C.t type context = C.t type key = K.t type value = C.value let mem ctxt k = C.mem ctxt (K.wrap k) let get ctxt k = C.get ctxt (K.wrap k) let find ctxt k = C.find ctxt (K.wrap k) let update ctxt k v = C.update ctxt (K.wrap k) v let init ctxt k v = C.init ctxt (K.wrap k) v let add ctxt k v = C.add ctxt (K.wrap k) v let add_or_remove ctxt k v = C.add_or_remove ctxt (K.wrap k) v let remove_existing ctxt k = C.remove_existing ctxt (K.wrap k) let remove ctxt k = C.remove ctxt (K.wrap k) let clear ctxt = C.clear ctxt let fold ctxt ~order ~init ~f = C.fold ctxt ~order ~init ~f:(fun k v acc -> match K.unwrap k with None -> Lwt.return acc | Some k -> f k v acc) let bindings s = fold s ~order:`Sorted ~init:[] ~f:(fun p v acc -> Lwt.return ((p, v) :: acc)) let fold_keys s ~order ~init ~f = C.fold_keys s ~order ~init ~f:(fun k acc -> match K.unwrap k with None -> Lwt.return acc | Some k -> f k acc) let keys s = fold_keys s ~order:`Sorted ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc)) end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
SFTcpListener_cstub.c
#include <SFML/Network/TcpListener.h> #include "sf_caml_incs_c.h" #include "SFTcpListener_cstub.h" #include "SFTcpSocket_cstub.h" #include "SFSocket_cstub.h" #include <stdlib.h> #include <stdio.h> #include <string.h> CAMLprim value caml_sfTcpListener_create(value unit) { sfTcpListener *list = sfTcpListener_create(); return Val_sfTcpListener(list); } CAMLprim value caml_sfTcpListener_destroy(value listener) { sfTcpListener_destroy(SfTcpListener_val(listener)); return Val_unit; } CAMLprim value caml_sfTcpListener_setBlocking(value listener, value blocking) { sfTcpListener_setBlocking(SfTcpListener_val(listener), Bool_val(blocking)); return Val_unit; } CAMLprim value caml_sfTcpListener_isBlocking(value listener) { return Val_bool( sfTcpListener_isBlocking(SfTcpListener_val(listener))); } CAMLprim value caml_sfTcpListener_getLocalPort(value listener) { unsigned short port = sfTcpListener_getLocalPort(SfTcpListener_val(listener)); return Val_long(port); } CAMLprim value caml_sfTcpListener_listen(value listener, value port) { sfSocketStatus st = sfTcpListener_listen(SfTcpListener_val(listener), Int_val(port)); check_sfSocketStatus(st, "SFTcpListener") return Val_unit; } CAMLprim value caml_sfTcpListener_accept(value listener) { sfTcpSocket *connected = NULL; sfSocketStatus st = sfTcpListener_accept(SfTcpListener_val(listener), &connected); check_sfSocketStatus(st, "SFTcpListener") if (connected == NULL) caml_failwith("SFTcpListener.accept"); return Val_sfTcpSocket(connected); } /* vim: sw=4 sts=4 ts=4 et */
/* * OCaml-SFML - OCaml bindings for the SFML library. * Copyright (C) 2010 Florent Monnier <monnier.florent(_)gmail.com> * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from the * use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; * you must not claim that you wrote the original software. * If you use this software in a product, an acknowledgment * in the product documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, * and must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */
javascript.ml
open! Stdlib module Num : sig type t (** Conversions *) val of_string_unsafe : string -> t val of_int32 : int32 -> t val of_float : float -> t val to_string : t -> string val to_int32 : t -> int32 (** Predicates *) val is_zero : t -> bool val is_one : t -> bool val is_neg : t -> bool (** Arithmetic *) val add : t -> t -> t val neg : t -> t end = struct type t = string let of_string_unsafe s = s let to_string s = s let to_int32 s = if String.is_prefix s ~prefix:"0" && String.length s > 1 && String.for_all s ~f:(function | '0' .. '7' -> true | _ -> false) then (* legacy octal notation *) Int32.of_string ("0o" ^ s) else Int32.of_string s let of_int32 = Int32.to_string external format_float : string -> float -> string = "caml_format_float" let fmts = Array.init 19 ~f:(fun i -> "%." ^ string_of_int i ^ "g") let float_to_string prec v = format_float fmts.(prec) v let rec find_smaller ~f ~bad ~good ~good_s = if bad + 1 = good then good_s else let mid = (good + bad) / 2 in assert (mid <> good); assert (mid <> bad); match f mid with | None -> find_smaller ~f ~bad:mid ~good ~good_s | Some s -> find_smaller ~f ~bad ~good:mid ~good_s:s (* Windows uses 3 digits for the exponent, let's fix it. *) let fix_exponent s = try let start = String.index_from s 0 'e' + 1 in let start = match String.get s start with | '-' | '+' -> succ start | _ -> start in let stop = ref start in while Char.equal (String.get s !stop) '0' do incr stop done; if start = !stop then s else String.sub s ~pos:0 ~len:start ^ String.sub s ~pos:!stop ~len:(String.length s - !stop) with Not_found -> s let of_float v = match Float.classify_float v with | FP_nan -> "NaN" | FP_zero -> (* [1/-0] < 0. seems to be the only way to detect -0 in JavaScript *) if Float.(1. /. v < 0.) then "-0." else "0." | FP_infinite -> if Float.(v < 0.) then "-Infinity" else "Infinity" | FP_normal | FP_subnormal -> ( let vint = int_of_float v in if Float.equal (float_of_int vint) v then Printf.sprintf "%d." vint else match find_smaller ~f:(fun prec -> let s = float_to_string prec v in if Float.equal v (float_of_string s) then Some s else None) ~bad:0 ~good:18 ~good_s:"max" with | "max" -> float_to_string 18 v |> fix_exponent | s -> fix_exponent s) let is_zero s = String.equal s "0" let is_one s = String.equal s "1" let is_neg s = Char.equal s.[0] '-' let neg s = match String.drop_prefix s ~prefix:"-" with | None -> "-" ^ s | Some s -> s let add a b = of_int32 (Int32.add (to_int32 a) (to_int32 b)) end module Label = struct type t = | L of int | S of Utf8_string.t let printer = Var_printer.create Var_printer.Alphabet.javascript let zero = L 0 let succ = function | L t -> L (succ t) | S _ -> assert false let to_string = function | L t -> Utf8_string.of_string_exn (Var_printer.to_string printer t) | S s -> s let of_string s = S s end type location = | Pi of Parse_info.t | N | U type identifier = Utf8_string.t type ident_string = { name : identifier ; var : Code.Var.t option ; loc : location } type early_error = { loc : Parse_info.t ; reason : string option } type ident = | S of ident_string | V of Code.Var.t (* A.3 Expressions *) and array_litteral = element_list and element_list = element list and element = | ElementHole | Element of expression | ElementSpread of expression and binop = | Eq | StarEq | SlashEq | ModEq | PlusEq | MinusEq | LslEq | AsrEq | LsrEq | BandEq | BxorEq | BorEq | Or | OrEq | And | AndEq | Bor | Bxor | Band | EqEq | NotEq | EqEqEq | NotEqEq | Lt | Le | Gt | Ge | LtInt | LeInt | GtInt | GeInt | InstanceOf | In | Lsl | Lsr | Asr | Plus | Minus | Mul | Div | Mod | Exp | ExpEq | Coalesce | CoalesceEq and unop = | Not | Neg | Pl | Typeof | Void | Delete | Bnot | IncrA | DecrA | IncrB | DecrB | Await and arguments = argument list and argument = | Arg of expression | ArgSpread of expression and property_list = property list and property = | Property of property_name * expression | PropertySpread of expression | PropertyMethod of property_name * method_ | CoverInitializedName of early_error * ident * initialiser and method_ = | MethodGet of function_declaration | MethodSet of function_declaration | Method of function_declaration and property_name = | PNI of identifier | PNS of Utf8_string.t | PNN of Num.t | PComputed of expression and expression = | ESeq of expression * expression | ECond of expression * expression * expression | EAssignTarget of binding_pattern | EBin of binop * expression * expression | EUn of unop * expression | ECall of expression * access_kind * arguments * location | ECallTemplate of expression * template * location | EAccess of expression * access_kind * expression | EDot of expression * access_kind * identifier | ENew of expression * arguments option | EVar of ident | EFun of ident option * function_declaration | EClass of ident option * class_declaration | EArrow of function_declaration * arrow_info | EStr of Utf8_string.t | ETemplate of template | EArr of array_litteral | EBool of bool | ENum of Num.t | EObj of property_list | ERegexp of string * string option | EYield of expression option | CoverParenthesizedExpressionAndArrowParameterList of early_error | CoverCallExpressionAndAsyncArrowHead of early_error and arrow_info = | AUnknown | AUse_parent_fun_context | ANo_fun_context and template = template_part list and template_part = | TStr of Utf8_string.t | TExp of expression and access_kind = | ANormal | ANullish (****) (* A.4 Statements *) and statement = | Block of block | Variable_statement of variable_declaration_kind * variable_declaration list | Function_declaration of ident * function_declaration | Class_declaration of ident * class_declaration | Empty_statement | Expression_statement of expression | If_statement of expression * (statement * location) * (statement * location) option | Do_while_statement of (statement * location) * expression | While_statement of expression * (statement * location) | For_statement of (expression option, variable_declaration_kind * variable_declaration list) either * expression option * expression option * (statement * location) | ForIn_statement of (expression, variable_declaration_kind * for_binding) either * expression * (statement * location) | ForOf_statement of (expression, variable_declaration_kind * for_binding) either * expression * (statement * location) | Continue_statement of Label.t option | Break_statement of Label.t option | Return_statement of expression option (* | With_statement of expression * statement *) | Labelled_statement of Label.t * (statement * location) | Switch_statement of expression * case_clause list * statement_list option * case_clause list | Throw_statement of expression | Try_statement of block * (formal_parameter option * block) option * block option | Debugger_statement and ('left, 'right) either = | Left of 'left | Right of 'right and block = statement_list and statement_list = (statement * location) list and variable_declaration = | DeclIdent of binding_ident * initialiser option | DeclPattern of binding_pattern * initialiser and variable_declaration_kind = | Var | Let | Const and case_clause = expression * statement_list and initialiser = expression * location (****) and function_declaration = function_kind * formal_parameter_list * function_body * location and function_kind = { async : bool ; generator : bool } and class_declaration = { extends : expression option ; body : class_element list } and class_element = | CEMethod of bool * class_element_name * method_ | CEField of bool * class_element_name * initialiser option | CEStaticBLock of statement_list and class_element_name = | PropName of property_name | PrivName of ident and ('a, 'b) list_with_rest = { list : 'a list ; rest : 'b option } and formal_parameter_list = (formal_parameter, binding) list_with_rest and formal_parameter = binding_element and for_binding = binding and binding_element = binding * initialiser option and binding = | BindingIdent of binding_ident | BindingPattern of binding_pattern and binding_pattern = | ObjectBinding of (binding_property, binding_ident) list_with_rest | ArrayBinding of (binding_element option, binding) list_with_rest and binding_ident = ident and binding_property = | Prop_binding of property_name * binding_element | Prop_ident of binding_ident * initialiser option and function_body = statement_list and program = statement_list and program_with_annots = (statement_list * (Js_token.Annot.t * Parse_info.t) list) list let compare_ident t1 t2 = match t1, t2 with | V v1, V v2 -> Code.Var.compare v1 v2 | S { name = Utf8 s1; var = v1; loc = _ }, S { name = Utf8 s2; var = v2; loc = _ } -> ( (* ignore locations *) match String.compare s1 s2 with | 0 -> Option.compare Code.Var.compare v1 v2 | n -> n) | S _, V _ -> -1 | V _, S _ -> 1 let is_ident = Flow_lexer.is_valid_identifier_name let is_ident' (Utf8_string.Utf8 s) = is_ident s let ident ?(loc = N) ?var (Utf8_string.Utf8 n as name) = if not (is_ident' name) then failwith (Printf.sprintf "%s not a valid ident" n); S { name; var; loc } let param' id = BindingIdent id, None let param ?loc ?var name = param' (ident ?loc ?var name) let ident_unsafe ?(loc = N) ?var name = S { name; var; loc } let rec bound_idents_of_binding p = match p with | BindingIdent id -> [ id ] | BindingPattern p -> bound_idents_of_pattern p and bound_idents_of_params { list; rest } = List.concat_map list ~f:bound_idents_of_element @ match rest with | None -> [] | Some p -> bound_idents_of_binding p and bound_idents_of_pattern p = match p with | ObjectBinding { list; rest } -> ( List.concat_map list ~f:(function | Prop_ident (i, _) -> [ i ] | Prop_binding (_, e) -> bound_idents_of_element e) @ match rest with | None -> [] | Some x -> [ x ]) | ArrayBinding { list; rest } -> ( List.concat_map list ~f:(function | None -> [] | Some e -> bound_idents_of_element e) @ match rest with | None -> [] | Some x -> bound_idents_of_binding x) and bound_idents_of_variable_declaration = function | DeclIdent (id, _) -> [ id ] | DeclPattern (p, _) -> bound_idents_of_pattern p and bound_idents_of_element (b, _) = bound_idents_of_binding b module IdentSet = Set.Make (struct type t = ident let compare = compare_ident end) module IdentMap = Map.Make (struct type t = ident let compare = compare_ident end) let dot e l = EDot (e, ANormal, l) let variable_declaration l = Variable_statement (Var, List.map l ~f:(fun (i, e) -> DeclIdent (i, Some e))) let array l = EArr (List.map l ~f:(fun x -> Element x)) let call f args loc = ECall (f, ANormal, List.map args ~f:(fun x -> Arg x), loc) let list list = { list; rest = None } let early_error ?reason loc = { loc; reason } let fun_ params body loc = ( { async = false; generator = false } , list (List.map params ~f:(fun x -> BindingIdent x, None)) , body , loc ) let rec assignment_pattern_of_expr x = match x with | EObj l -> let rest, l = match List.rev l with | PropertySpread (EVar x) :: l -> Some x, List.rev l | _ -> None, l in let list = List.map l ~f:(function | Property (PNI (Utf8 i), EVar (S { name = Utf8 i2; loc = N; _ } as ident)) when String.equal i i2 -> Prop_ident (ident, None) | Property (n, e) -> Prop_binding (n, binding_element_of_expression e) | CoverInitializedName (_, i, e) -> Prop_ident (i, Some e) | _ -> raise Not_found) in ObjectBinding { list; rest } | EArr l -> let rest, l = match List.rev l with | ElementSpread e :: l -> Some (binding_of_expression e), List.rev l | _ -> None, l in let list = List.map l ~f:(function | ElementHole -> None | Element e -> Some (binding_element_of_expression e) | ElementSpread _ -> raise Not_found) in ArrayBinding { list; rest } | _ -> raise Not_found and binding_element_of_expression e = match e with | EBin (Eq, e1, e2) -> binding_of_expression e1, Some (e2, N) | e -> binding_of_expression e, None and binding_of_expression e = match e with | EVar x -> BindingIdent x | EObj _ as x -> BindingPattern (assignment_pattern_of_expr x) | EArr _ as x -> BindingPattern (assignment_pattern_of_expr x) | _ -> raise Not_found let assignment_pattern_of_expr op x = match op with | None | Some Eq -> ( try Some (assignment_pattern_of_expr x) with Not_found -> None) | _ -> None
(* Js_of_ocaml compiler * http://www.ocsigen.org/js_of_ocaml/ * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
ast_sig.ml
open Clang__bindings open Clang__utils [@@ocaml.warning "-33"] (* unused-open: cxerrorcode with clang <3.5.0 *) (** Common part of AST node signatures *) module type S = sig type t val compare : t -> t -> int val equal : t -> t -> bool val hash : t -> int val pp : Format.formatter -> t -> unit val show : t -> string module Set : Set.S with type elt = t module Map : Map.S with type key = t module Hashtbl : Hashtbl.S with type key = t end module type PrinterS = sig module Node : Clang__ast.NodeS val qual_type : Format.formatter -> Clang__ast.Custom (Node).qual_type -> unit val typed_value : (Format.formatter -> unit) -> Format.formatter -> Clang__ast.Custom (Node).qual_type -> unit val expr : Format.formatter -> Clang__ast.Custom (Node).expr -> unit val decl : Format.formatter -> Clang__ast.Custom (Node).decl -> unit val decls : Format.formatter -> Clang__ast.Custom (Node).decl list -> unit val stmt : Format.formatter -> Clang__ast.Custom (Node).stmt -> unit val translation_unit : Format.formatter -> Clang__ast.Custom (Node).translation_unit -> unit end module type CustomS = sig module Node : Clang__ast.NodeS module Ast : sig (** The module includes {!module:Clang__ast} which contains the declaration of the abstract syntax tree. Since the abstract syntax tree is a pure type declaration without value definition, the declaration is written in a separate module, written in an implementation file (.ml) without interface file (.mli)). *) include module type of struct include Clang__ast.Common include Clang__ast.Custom (Node) end (** The following functions provides convenient ways to build some AST nodes. *) val var : ?linkage:linkage_kind -> ?storage:storage_class -> ?var_init:expr -> ?constexpr:bool -> ?attributes:attribute list -> string -> qual_type -> var_decl_desc val function_decl : ?linkage:linkage_kind -> ?storage:storage_class -> ?body:stmt -> ?deleted:bool -> ?constexpr:bool -> ?inline_specified:bool -> ?inlined:bool -> ?nested_name_specifier:nested_name_specifier -> ?attributes:attribute list -> ?has_written_prototype:bool -> function_type -> declaration_name -> function_decl val function_type : ?calling_conv:calling_conv -> ?parameters:parameters -> ?exception_spec:exception_spec -> ?ref_qualifier:cxrefqualifierkind -> qual_type -> function_type val parameters : ?variadic:bool -> parameter list -> parameters val parameter : ?default:expr -> qual_type -> string -> parameter_desc val ident_ref : ?nested_name_specifier:nested_name_specifier -> ?template_arguments:template_argument list -> declaration_name -> ident_ref val identifier_name : ?nested_name_specifier:nested_name_specifier -> ?template_arguments:template_argument list -> string -> ident_ref val new_instance : ?placement_args:expr list -> ?array_size:expr -> ?init:expr -> ?args:expr list -> qual_type -> expr_desc val delete : ?global_delete:bool -> ?array_form:bool -> expr -> expr_desc val enum_decl : ?complete_definition: bool -> ?attributes:attribute list -> string -> enum_constant list -> decl_desc val if_ : ?init:stmt -> ?condition_variable:var_decl -> ?else_branch:stmt -> expr -> stmt -> stmt_desc (** {!type:Options.t} stores flags that change the construction of the abstract syntax tree. Beware that the nodes that are ignored by default can differ from one version of Clang to the other. *) module Options : module type of struct include Clang__ast_options end val parse_file : ?index:cxindex -> ?command_line_args:string list -> ?unsaved_files:cxunsavedfile list -> ?clang_options:Cxtranslationunit_flags.t -> ?options:Options.t -> string -> translation_unit (** [parse_file ?index ?command_line_args ?unsaved_files ?clang_options ?options filename] parses file [filename] and returns its translation unit. This function is equivalent to {!val:Clang.parse_file} (where [options] becomes [clang_options]), but returns the high-level representation of the translation unit (as obtained by {!val:of_cxtranslationunit}). *) val parse_file_res : ?index:cxindex -> ?command_line_args:string list -> ?unsaved_files:cxunsavedfile list -> ?clang_options:Cxtranslationunit_flags.t -> ?options:Options.t -> string -> (translation_unit, cxerrorcode) result (** Equivalent to {!val:parse_file} but returns a [result] instead of raising [Failure _] if parsing fails. *) val parse_string : ?index:cxindex -> ?filename:string -> ?command_line_args:string list -> ?unsaved_files:cxunsavedfile list -> ?clang_options:Cxtranslationunit_flags.t -> ?options:Options.t -> string -> translation_unit (** [parse_string ?index ?filename ?command_line_args ?unsaved_files ?clang_options ?options contents] parses string [contents] and returns its translation unit. This function is equivalent to {!val:Clang.parse_string} (where [options] becomes [clang_options]), but returns the high-level representation of the translation unit (as obtained by {!val:of_cxtranslationunit}). *) val parse_string_res : ?index:cxindex -> ?filename:string -> ?command_line_args:string list -> ?unsaved_files:cxunsavedfile list -> ?clang_options:Cxtranslationunit_flags.t -> ?options:Options.t -> string -> (translation_unit, cxerrorcode) result (** Equivalent to {!val:parse_string_res} but returns a [result] instead of raising [Failure _] if parsing fails. *) val of_cxtranslationunit : ?options:Options.t -> cxtranslationunit -> translation_unit (** [of_cxtranslationunit ?options tu] translates [tu] into its high-level representation. *) val node : ?decoration:decoration -> ?cursor:cxcursor -> ?location:source_location -> ?qual_type:qual_type -> 'a Node.t -> 'a node (** [node ?decoration desc] returns a node with the given [desc] value and [decoration]. [decoration] can be given by one of the three following forms: (1) a value for [?decoration], or (2) a value for [?cursor], or (3) by either a value for [location], or a value for [qual_type], or both. These three forms cannot be mixed, otherwise [Invalid_arg _] is raised. *) val cursor_of_decoration : decoration -> cxcursor (** [cursor_of_decoration decoration] returns the cursor associated to [decoration] if any, or the null cursor otherwise (as returned by {!val:get_null_cursor}). *) val cursor_of_node : 'a node -> cxcursor (** [cursor_of_node node] is equivalent to {!val:cursor_of_decoration}[ node.decoration]. *) val location_of_decoration : decoration -> source_location (** [location_of_decoration decoration] returns the location associated to [decoration] if any, or the location of the null cursor otherwise (as returned by {!val:get_null_cursor}). *) val location_of_node : 'a node -> source_location (** [location_of_node node] is equivalent to {!val:location_of_decoration}[ node.decoration]. *) val tokens_of_node : 'a node -> string array (** [tokens_of_node node] returns the token at the beginning of [node] if available. *) val seq_of_diagnostics : translation_unit -> cxdiagnostic Seq.t (** [seq_of_diagnostics tu] returns the diagnostics (notes, warnings, errors, ...) produced for the given translation unit *) val format_diagnostics : ?pp:((Format.formatter -> unit -> unit) -> Format.formatter -> unit -> unit) -> cxdiagnosticseverity list -> Format.formatter -> translation_unit -> unit (** [format_diagnostics ?pp severities fmt tu] formats the diagnostics produced for the given translation unit. Only the diagnostics, the severity of which is listed in [severities] are displayed. If there is a printer given in [pp], then this printer is called once if and only if there is at least one diagnostic to display, and [pp] should call the printer passed in its first argument to display the diagnostics. In the case there is no diagnostic to display, nothing is printed. *) val has_severity : cxdiagnosticseverity list -> translation_unit -> bool (** [has_severity l tu] returns whether the translation unit [tu] produced a diagnostic, the severity of which belongs to [l]. *) include module type of struct include Clang__ast_utils end end (** AST types. *) module Type : sig type t = Ast.qual_type [@@deriving refl] val of_node : ?options:Ast.Options.t -> 'a Ast.node -> t (** [of_node ?options node] returns the type associated to [node]. If [node] comes from libclang's AST, the function calls {!val:get_cursor_type} to the associated cursor. If [node] has been constructed and decorated with a type [ty], [ty] is returned. If [node] has been constructed without type decoration, [Invalid_arg _] is raised. It is equivalent to [Clang.Type.of_decoration ?options (Clang.Ast.decoration_of_node node)].*) val make : ?const:bool -> ?volatile:bool -> ?restrict:bool -> Ast.type_desc Node.t -> t (** [make ?const ?volatile ?restrict desc] returns a type from a description, associated to an invalid libclang's type. This function can be useful to construct types from OCaml programs, for instance to describe a program transformation. *) val of_cxtype : ?options:Ast.Options.t -> cxtype -> t (** [of_cxtype ?options ty] translates [ty] into its high-level representation. *) val of_type_loc : ?options:Ast.Options.t -> clang_ext_typeloc -> t (** [of_type_loc ?options ty] translates [ty] into its high-level representation. *) val of_cursor : ?options:Ast.Options.t -> cxcursor -> t (** [of_cxcursor ?options cu] returns the type associated to [cu]. *) val of_decoration : ?options:Ast.Options.t -> Ast.decoration -> t (** [of_decoration ?options d] returns the type associated to [d]. *) val iter_fields : ?options:Ast.Options.t -> (Ast.decl -> unit) -> t -> unit (** [iter_fields ?options f ty] calls [f] over all the declaration nodes of the fields belonging to the record type [ty] (either a struct or union). It is equivalent to [Clang.iter_type_fields (fun d -> f (Clang.Decl.of_cursor ?options d)) ty.cxtype]. *) val list_of_fields : ?options:Ast.Options.t -> t -> Ast.decl list (** [list_of_fields ?options f ty] returns the list of all the declaration nodes of the fields belonging to the record type [ty] (either a struct or union). It is equivalent to [List.map (Clang.Decl.of_cursor ?options) (Clang.list_of_type_fields ty.cxtype)]. *) val get_declaration : ?options:Ast.Options.t -> t -> Ast.decl (** [get_declaration ?options ty] returns the declaration node of [ty]. It is equivalent to [Clang.Decl.of_cxcursor ?options (Clang.get_type_declaration ty.cxtype)]. *) val get_typedef_underlying_type : ?options:Ast.Options.t -> ?recursive:bool -> t -> t (** [get_typedef_underlying_type ?options ?recursive ty] returns the underlying type of [ty] if [ty] is a typedef, and [ty] otherwise. If [recursive] is [true] (default: [false]), typedefs are followed until the underlying type is not a typedef. *) val get_align_of : t -> int (** [get_align_of ty] returns the alignment of [ty] in bytes. It is equivalent to [Clang.type_get_align_of ty.cxtype]. *) val get_size_of : t -> int (** [get_align_of ty] returns the size of [ty] in bytes. It is equivalent to [Clang.type_get_size_of ty.cxtype]. *) val get_offset_of : t -> string -> int (** [get_offset_of ty field] returns the offset of [field] in the elaborated type [ty] in bits. *) include S with type t := t end (** AST expressions as ordered types. *) module Expr : sig type t = Ast.expr [@@deriving refl] val of_cxcursor : ?options:Ast.Options.t -> cxcursor -> t (** [of_cxcursor ?options cu] translates [cu] into its high-level representation, supposing that [cu] points to an expression. *) val get_definition : t -> cxcursor (** [get_definition e] retrieves a cursor that describes the definition of the entity referenced by [e]. Returns a [NULL] cursor of [e] has no corresponding definition. *) type radix = Decimal | Octal | Hexadecimal | Binary [@@deriving refl] val radix_of_integer_literal : t -> radix option (** [radix_of_integer_literal e] returns the radix of the integer literal [e] if available. Note that, by convention, [0] is octal. *) val parse_string : ?index:cxindex -> ?clang_options:Cxtranslationunit_flags.t -> ?options:Ast.Options.t -> ?filename:string -> ?line:int -> ?context:Ast.decl list -> string -> t option * Ast.translation_unit (** [parse_string ?index ?clang_options ?options ?filename ?line ?context contents] parses string [contents] as a C expression and returns [(o, tu)] where [o] is [Some e] if [contents] has been successfully parsed as the expression [e], and [tu] is the translation unit created for parsing. [tu] can be used to retrieve diagnostics if any. [context] provides some declaration context. [filename] and [line] specifies respectively the file name and the line number to use in diagnostics. *) include S with type t := t end (** AST statements. *) module Stmt : sig type t = Ast.stmt [@@deriving refl] val of_cxcursor : ?options:Ast.Options.t -> cxcursor -> t (** [of_cxcursor ?options cu] translates [cu] into its high-level representation, supposing that [cu] points to a statement. *) include S with type t := t end (** AST not-transformed types. *) module Type_loc : sig type t = Ast.type_loc [@@deriving refl] val to_qual_type : ?options:Ast.Options.t -> t -> Type.t include S with type t := t end (** AST declarations. *) module Decl : sig type t = Ast.decl [@@deriving refl] val of_cxcursor : ?options:Ast.Options.t -> cxcursor -> t (** [of_cxcursor ?options cu] translates [cu] into its high-level representation, supposing that [cu] points to a declaration. *) val get_typedef_underlying_type : ?options:Ast.Options.t -> ?recursive:bool -> t -> Type.t (** [get_typedef_underlying_type ?options ?recursive decl] returns the underlying type of a typedef [decl]. If [recursive] is [true] (default: [false]), typedefs are followed until the underlying type is not a typedef. *) val get_field_bit_width : t -> int (** [get_field_bit_width d] returns the bit width of the field declaration [d]. *) val get_size_expr : ?options:Ast.Options.t -> t -> Expr.t (** [get_size_expr ?options d] returns the expression specifying the size of the array declared by [d], and fails if [d] is not an array declaration. *) val get_type_loc : ?options:Ast.Options.t -> t -> Type_loc.t val get_canonical : t -> cxcursor (** [get_canonical d] retrieves the canonical cursor declaring an entity. *) type annotated_field = { specifier : Ast.cxx_access_specifier; decl : Ast.decl; } val annotate_access_specifier : Ast.cxx_access_specifier -> Ast.decl list -> annotated_field list (** [annotate_access_specifier default_specifier fields] returns the elements of [fields], except [AccessSpecifier] nodes, annotated with the current access specifier, starting with [default_specifier]. *) include S with type t := t end (** AST parameters. *) module Parameter : sig type t = Ast.parameter [@@deriving refl] val get_size_expr : ?options:Ast.Options.t -> t -> Expr.t (** [get_size_expr ?options p] returns the expression specifying the size of the array declared by [p], and fails if [p] is not an array parameter. *) val get_type_loc : ?options:Ast.Options.t -> t -> Type_loc.t include S with type t := t end (** AST enumeration constants. *) module Enum_constant : sig type t = Ast.enum_constant [@@deriving refl] val of_cxcursor : ?options:Ast.Options.t -> cxcursor -> t (** [of_cxcursor ?options cu] translates [cu] into its high-level representation, supposing that [cu] points to a enumeration constant. *) val get_value : t -> int (** [get_value c] returns the value associated to the constant [c].*) include S with type t := t end (** AST translation units. *) module Translation_unit : sig type t = Ast.translation_unit [@@deriving refl] val make : ?filename:string -> Ast.decl list -> Ast.translation_unit_desc include S with type t := t end module Printer : PrinterS with module Node := Node end
dune
(executable (name lreplay) (public_name lreplay) (package lreplay) (libraries str unix) ) (ocamlyacc parser) (ocamllex lexer) (rule (target foreignCode.ml) (action (with-stdout-to %{target} (progn (echo "let uthash_h = ForeignCodeUtils.lazy_create_file \"") (run sed -e "s/[\"\\]/\\\\&/g" %{dep:uthash.h}) (echo "\" \"lreplay_uthash\" \".h\"\n") (echo "let utlist_h = ForeignCodeUtils.lazy_create_file \"") (run sed -e "s/[\"\\]/\\\\&/g" %{dep:utlist.h}) (echo "\" \"lreplay_utlist\" \".h\"\n") (echo "let runtime_h = ForeignCodeUtils.lazy_create_file \"") (run sed -e "s/[\"\\]/\\\\&/g" %{dep:runtime.h}) (echo "\" \"lreplay_runtime\" \".h\"\n") (echo "let runtime_c = ForeignCodeUtils.lazy_create_file \"") (run sed -e "s/[\"\\]/\\\\&/g" %{dep:runtime.c}) (echo "\" \"lreplay_runtime\" \".c\"\n") (echo "let detection_h = ForeignCodeUtils.lazy_create_file \"") (run sed -e "s/[\"\\]/\\\\&/g" %{dep:detection.h}) (echo "\" \"lreplay_detection\" \".h\"\n") ))))
Parsing_plugin.ml
(* External parsers to be registered here by proprietary extensions of semgrep. *) open Common exception Missing_plugin of string type pattern_parser = string -> AST_generic.any Tree_sitter_run.Parsing_result.t type target_file_parser = Common.filename -> AST_generic.program Tree_sitter_run.Parsing_result.t (* Create and manage the reference holding a plugin. *) let make lang = let parsers = ref None in let register ~parse_pattern ~parse_target = match !parsers with | None -> parsers := Some (parse_pattern, parse_target) | Some _existing_parsers -> (* This is a bug *) let msg = spf "Plugin initialization error: a %s parser is being registered \ twice." (Lang.to_string lang) in failwith msg in let is_available () = !parsers <> None in let parse_pattern file = match !parsers with | None -> let msg = spf "Missing Semgrep extension needed for parsing %s target." (Lang.to_string lang) in raise (Missing_plugin msg) | Some (parse_pattern, _) -> parse_pattern file in let parse_target file = match !parsers with | None -> let msg = spf "Missing Semgrep extension needed for parsing %s pattern." (Lang.to_string lang) in raise (Missing_plugin msg) | Some (_, parse_target) -> parse_target file in (register, is_available, parse_pattern, parse_target) module type T = sig val register_parsers : parse_pattern:pattern_parser -> parse_target:target_file_parser -> unit val is_available : unit -> bool val parse_pattern : pattern_parser val parse_target : target_file_parser end module Apex = struct let register_parsers, is_available, parse_pattern, parse_target = make Lang.Apex end
(* External parsers to be registered here by proprietary extensions of semgrep. *)
t-det_howell.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <gmp.h> #include "flint.h" #include "nmod_mat.h" #include "ulong_extras.h" #include "fmpz.h" #include "fmpz_mat.h" int main(void) { slong m, mod, rep; FLINT_TEST_INIT(state); flint_printf("det_howell...."); fflush(stdout); for (rep = 0; rep < 1000 * flint_test_multiplier(); rep++) { nmod_mat_t A; fmpz_mat_t B; mp_limb_t Adet; fmpz_t Bdet; ulong t; m = n_randint(state, 30); mod = n_randtest(state); mod += mod == 0; nmod_mat_init(A, m, m, mod); fmpz_mat_init(B, m, m); switch (rep % 3) { case 0: nmod_mat_randrank(A, state, m); nmod_mat_randops(A, n_randint(state, 2*m + 1), state); break; case 1: t = n_randint(state, m); t = FLINT_MIN(t, m); nmod_mat_randrank(A, state, t); nmod_mat_randops(A, n_randint(state, 2*m + 1), state); break; default: nmod_mat_randtest(A, state); } fmpz_mat_set_nmod_mat_unsigned(B, A); Adet = nmod_mat_det_howell(A); fmpz_init(Bdet); fmpz_mat_det_bareiss(Bdet, B); fmpz_mod_ui(Bdet, Bdet, mod); if (Adet != fmpz_get_ui(Bdet)) { flint_printf("FAIL\n"); flint_printf("Adet = %wu, Bdet = %wu\n", Adet, fmpz_get_ui(Bdet)); fflush(stdout); flint_abort(); } nmod_mat_clear(A); fmpz_mat_clear(B); fmpz_clear(Bdet); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2010 Fredrik Johansson This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
domain_id.ml
(* TEST *) open Domain let test_main_domain () = assert ((Domain.self () :> int) = 0); assert (Domain.is_main_domain ()); () let id () = () let newdom_id () = let d = Domain.spawn id in let n = Domain.get_id d in join d; (n :> int) let test_different_ids () = let d1 = Domain.spawn id in let d2 = Domain.spawn id in assert (get_id d1 <> get_id d2); join d1; join d2; let d3 = Domain.spawn id in assert (get_id d1 <> get_id d3); join d3 let () = test_main_domain (); test_different_ids (); print_endline "ok"
(* TEST *)
evaluate2_acb.c
#include "arb_poly.h" void _arb_poly_evaluate2_acb(acb_t y, acb_t z, arb_srcptr f, slong len, const acb_t x, slong prec) { _arb_poly_evaluate2_acb_rectangular(y, z, f, len, x, prec); } void arb_poly_evaluate2_acb(acb_t r, acb_t s, const arb_poly_t f, const acb_t a, slong prec) { _arb_poly_evaluate2_acb(r, s, f->coeffs, f->length, a, prec); }
/* Copyright (C) 2013 Fredrik Johansson This file is part of Arb. Arb is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */
dune
; This file was automatically generated, do not edit. ; Edit file manifest/main.ml instead. (library (name tezos_protocol_environment_007_PsDELPH1) (public_name tezos-protocol-007-PsDELPH1.environment) (instrumentation (backend bisect_ppx)) (libraries tezos-protocol-environment) (library_flags (:standard -linkall)) (modules Tezos_protocol_environment_007_PsDELPH1)) (rule (targets tezos_protocol_environment_007_PsDELPH1.ml) (action (write-file %{targets} "module Name = struct let name = \"007-PsDELPH1\" end\ninclude Tezos_protocol_environment.V0.Make(Name)()\n"))) (library (name tezos_raw_protocol_007_PsDELPH1) (public_name tezos-protocol-007-PsDELPH1.raw) (instrumentation (backend bisect_ppx)) (libraries tezos-protocol-007-PsDELPH1.environment) (library_flags (:standard -linkall)) (flags (:standard) -w -6-7-9-16-29-32-51-68 -nostdlib -nopervasives -open Tezos_protocol_environment_007_PsDELPH1 -open Tezos_protocol_environment_007_PsDELPH1.Pervasives -open Tezos_protocol_environment_007_PsDELPH1.Error_monad) (modules Misc Storage_description State_hash Nonce_hash Script_expr_hash Contract_hash Blinded_public_key_hash Qty_repr Tez_repr Period_repr Time_repr Fixed_point_repr Gas_limit_repr Constants_repr Fitness_repr Raw_level_repr Voting_period_repr Cycle_repr Level_repr Seed_repr Script_int_repr Script_timestamp_repr Michelson_v1_primitives Script_repr Legacy_script_support_repr Contract_repr Roll_repr Vote_repr Block_header_repr Operation_repr Manager_repr Commitment_repr Parameters_repr Raw_context Storage_costs Storage_sigs Storage_functors Storage Constants_storage Level_storage Nonce_storage Seed_storage Roll_storage Delegate_storage Contract_storage Bootstrap_storage Fitness_storage Vote_storage Commitment_storage Init_storage Fees_storage Alpha_context Script_typed_ir Script_tc_errors Michelson_v1_gas Script_ir_annot Script_ir_translator Script_tc_errors_registration Script_interpreter Baking Amendment Apply_results Apply Services_registration Constants_services Contract_services Delegate_services Helpers_services Voting_services Alpha_services Main)) (library (name tezos_protocol_007_PsDELPH1) (public_name tezos-protocol-007-PsDELPH1) (instrumentation (backend bisect_ppx)) (libraries tezos-protocol-environment tezos-protocol-environment.sigs tezos-protocol-007-PsDELPH1.raw) (flags (:standard) -w -6-7-9-16-29-32-51-68 -nopervasives) (modules Protocol Tezos_protocol_007_PsDELPH1)) (install (package tezos-protocol-007-PsDELPH1) (section lib) (files (TEZOS_PROTOCOL as raw/TEZOS_PROTOCOL))) (rule (targets protocol.ml) (action (write-file %{targets} "\nlet hash = Tezos_crypto.Hashed.Protocol_hash.of_b58check_exn \"PsDELPH1Kxsxt8f9eWbxQeRxkjfbxoqM52jvs5Y5fBxWWh4ifpo\"\nlet name = Tezos_protocol_environment_007_PsDELPH1.Name.name\ninclude Tezos_raw_protocol_007_PsDELPH1\ninclude Tezos_raw_protocol_007_PsDELPH1.Main\n"))) (rule (targets tezos_protocol_007_PsDELPH1.ml) (action (write-file %{targets} "\nmodule Environment = Tezos_protocol_environment_007_PsDELPH1\nmodule Protocol = Protocol\n"))) (rule (alias runtest_compile_protocol) (deps misc.ml misc.mli storage_description.ml storage_description.mli state_hash.ml nonce_hash.ml script_expr_hash.ml contract_hash.ml blinded_public_key_hash.ml blinded_public_key_hash.mli qty_repr.ml tez_repr.ml tez_repr.mli period_repr.ml period_repr.mli time_repr.ml time_repr.mli fixed_point_repr.ml fixed_point_repr.mli gas_limit_repr.ml gas_limit_repr.mli constants_repr.ml fitness_repr.ml raw_level_repr.ml raw_level_repr.mli voting_period_repr.ml voting_period_repr.mli cycle_repr.ml cycle_repr.mli level_repr.ml level_repr.mli seed_repr.ml seed_repr.mli script_int_repr.ml script_int_repr.mli script_timestamp_repr.ml script_timestamp_repr.mli michelson_v1_primitives.ml michelson_v1_primitives.mli script_repr.ml script_repr.mli legacy_script_support_repr.ml legacy_script_support_repr.mli contract_repr.ml contract_repr.mli roll_repr.ml roll_repr.mli vote_repr.ml vote_repr.mli block_header_repr.ml block_header_repr.mli operation_repr.ml operation_repr.mli manager_repr.ml manager_repr.mli commitment_repr.ml commitment_repr.mli parameters_repr.ml parameters_repr.mli raw_context.ml raw_context.mli storage_costs.ml storage_costs.mli storage_sigs.ml storage_functors.ml storage_functors.mli storage.ml storage.mli constants_storage.ml level_storage.ml level_storage.mli nonce_storage.ml nonce_storage.mli seed_storage.ml seed_storage.mli roll_storage.ml roll_storage.mli delegate_storage.ml delegate_storage.mli contract_storage.ml contract_storage.mli bootstrap_storage.ml bootstrap_storage.mli fitness_storage.ml vote_storage.ml vote_storage.mli commitment_storage.ml commitment_storage.mli init_storage.ml fees_storage.ml fees_storage.mli alpha_context.ml alpha_context.mli script_typed_ir.ml script_tc_errors.ml michelson_v1_gas.ml michelson_v1_gas.mli script_ir_annot.ml script_ir_annot.mli script_ir_translator.ml script_ir_translator.mli script_tc_errors_registration.ml script_interpreter.ml script_interpreter.mli baking.ml baking.mli amendment.ml amendment.mli apply_results.ml apply_results.mli apply.ml services_registration.ml constants_services.ml constants_services.mli contract_services.ml contract_services.mli delegate_services.ml delegate_services.mli helpers_services.ml helpers_services.mli voting_services.ml voting_services.mli alpha_services.ml alpha_services.mli main.ml main.mli (:src_dir TEZOS_PROTOCOL)) (action (run %{bin:octez-protocol-compiler} -warning -6-7-9-16-29-32-51-68 -warn-error +a .))) (library (name tezos_protocol_007_PsDELPH1_functor) (libraries tezos-protocol-environment tezos-protocol-environment.sigs) (flags (:standard) -w -6-7-9-16-29-32-51-68 -nopervasives) (modules Functor)) (rule (targets functor.ml) (deps misc.ml misc.mli storage_description.ml storage_description.mli state_hash.ml nonce_hash.ml script_expr_hash.ml contract_hash.ml blinded_public_key_hash.ml blinded_public_key_hash.mli qty_repr.ml tez_repr.ml tez_repr.mli period_repr.ml period_repr.mli time_repr.ml time_repr.mli fixed_point_repr.ml fixed_point_repr.mli gas_limit_repr.ml gas_limit_repr.mli constants_repr.ml fitness_repr.ml raw_level_repr.ml raw_level_repr.mli voting_period_repr.ml voting_period_repr.mli cycle_repr.ml cycle_repr.mli level_repr.ml level_repr.mli seed_repr.ml seed_repr.mli script_int_repr.ml script_int_repr.mli script_timestamp_repr.ml script_timestamp_repr.mli michelson_v1_primitives.ml michelson_v1_primitives.mli script_repr.ml script_repr.mli legacy_script_support_repr.ml legacy_script_support_repr.mli contract_repr.ml contract_repr.mli roll_repr.ml roll_repr.mli vote_repr.ml vote_repr.mli block_header_repr.ml block_header_repr.mli operation_repr.ml operation_repr.mli manager_repr.ml manager_repr.mli commitment_repr.ml commitment_repr.mli parameters_repr.ml parameters_repr.mli raw_context.ml raw_context.mli storage_costs.ml storage_costs.mli storage_sigs.ml storage_functors.ml storage_functors.mli storage.ml storage.mli constants_storage.ml level_storage.ml level_storage.mli nonce_storage.ml nonce_storage.mli seed_storage.ml seed_storage.mli roll_storage.ml roll_storage.mli delegate_storage.ml delegate_storage.mli contract_storage.ml contract_storage.mli bootstrap_storage.ml bootstrap_storage.mli fitness_storage.ml vote_storage.ml vote_storage.mli commitment_storage.ml commitment_storage.mli init_storage.ml fees_storage.ml fees_storage.mli alpha_context.ml alpha_context.mli script_typed_ir.ml script_tc_errors.ml michelson_v1_gas.ml michelson_v1_gas.mli script_ir_annot.ml script_ir_annot.mli script_ir_translator.ml script_ir_translator.mli script_tc_errors_registration.ml script_interpreter.ml script_interpreter.mli baking.ml baking.mli amendment.ml amendment.mli apply_results.ml apply_results.mli apply.ml services_registration.ml constants_services.ml constants_services.mli contract_services.ml contract_services.mli delegate_services.ml delegate_services.mli helpers_services.ml helpers_services.mli voting_services.ml voting_services.mli alpha_services.ml alpha_services.mli main.ml main.mli (:src_dir TEZOS_PROTOCOL)) (action (with-stdout-to %{targets} (chdir %{workspace_root} (run %{bin:octez-protocol-compiler.octez-protocol-packer} %{src_dir}))))) (library (name tezos_embedded_protocol_007_PsDELPH1) (public_name tezos-embedded-protocol-007-PsDELPH1) (instrumentation (backend bisect_ppx)) (libraries tezos-protocol-007-PsDELPH1 tezos-protocol-updater tezos-protocol-environment) (library_flags (:standard -linkall)) (flags (:standard) -w -6-7-9-16-29-32-51-68) (modules Registerer)) (rule (targets registerer.ml) (deps misc.ml misc.mli storage_description.ml storage_description.mli state_hash.ml nonce_hash.ml script_expr_hash.ml contract_hash.ml blinded_public_key_hash.ml blinded_public_key_hash.mli qty_repr.ml tez_repr.ml tez_repr.mli period_repr.ml period_repr.mli time_repr.ml time_repr.mli fixed_point_repr.ml fixed_point_repr.mli gas_limit_repr.ml gas_limit_repr.mli constants_repr.ml fitness_repr.ml raw_level_repr.ml raw_level_repr.mli voting_period_repr.ml voting_period_repr.mli cycle_repr.ml cycle_repr.mli level_repr.ml level_repr.mli seed_repr.ml seed_repr.mli script_int_repr.ml script_int_repr.mli script_timestamp_repr.ml script_timestamp_repr.mli michelson_v1_primitives.ml michelson_v1_primitives.mli script_repr.ml script_repr.mli legacy_script_support_repr.ml legacy_script_support_repr.mli contract_repr.ml contract_repr.mli roll_repr.ml roll_repr.mli vote_repr.ml vote_repr.mli block_header_repr.ml block_header_repr.mli operation_repr.ml operation_repr.mli manager_repr.ml manager_repr.mli commitment_repr.ml commitment_repr.mli parameters_repr.ml parameters_repr.mli raw_context.ml raw_context.mli storage_costs.ml storage_costs.mli storage_sigs.ml storage_functors.ml storage_functors.mli storage.ml storage.mli constants_storage.ml level_storage.ml level_storage.mli nonce_storage.ml nonce_storage.mli seed_storage.ml seed_storage.mli roll_storage.ml roll_storage.mli delegate_storage.ml delegate_storage.mli contract_storage.ml contract_storage.mli bootstrap_storage.ml bootstrap_storage.mli fitness_storage.ml vote_storage.ml vote_storage.mli commitment_storage.ml commitment_storage.mli init_storage.ml fees_storage.ml fees_storage.mli alpha_context.ml alpha_context.mli script_typed_ir.ml script_tc_errors.ml michelson_v1_gas.ml michelson_v1_gas.mli script_ir_annot.ml script_ir_annot.mli script_ir_translator.ml script_ir_translator.mli script_tc_errors_registration.ml script_interpreter.ml script_interpreter.mli baking.ml baking.mli amendment.ml amendment.mli apply_results.ml apply_results.mli apply.ml services_registration.ml constants_services.ml constants_services.mli contract_services.ml contract_services.mli delegate_services.ml delegate_services.mli helpers_services.ml helpers_services.mli voting_services.ml voting_services.mli alpha_services.ml alpha_services.mli main.ml main.mli (:src_dir TEZOS_PROTOCOL)) (action (with-stdout-to %{targets} (chdir %{workspace_root} (run %{bin:octez-embedded-protocol-packer} %{src_dir} 007_PsDELPH1)))))
imageLib_unix.mli
(** This module provides an easy-to-use interface for imagelib. In most cases, you'd want to use these functions rather than those in imagelib. *) (** [writefile fn img] writes the image [img] to the file [fn]. This function guesses the desired format using the extension. Raises {!Corrupted_image} if it encounters a problem. If the file extension is unknown to imagelib, this will first write out a png and then convert that to the desired format using the "convert" command from imagemagick. *) val writefile : string -> Image.image -> unit (** [size fn] reads the image from the file [fn]. It returns the pixel dimensions of the image as the tuple [width, heigth]. *) val size : string -> int * int (** [openfile fn] reads the image from the file [fn]. This function guesses the file format using the extension. Raises {!Corrupted_image} if it encounters a problem. If the file extension is unknown to imagelib, this will attempt to convert to png using imagemagick and then read in the png file. *) val openfile : string -> Image.image
(** This module provides an easy-to-use interface for imagelib. In most cases, you'd want to use these functions rather than those in imagelib. *)
bytesobject.h
/* Bytes object interface */ #ifndef Py_BYTESOBJECT_H #define Py_BYTESOBJECT_H #ifdef __cplusplus extern "C" { #endif #include <stdarg.h> // va_list /* Type PyBytesObject represents a byte string. An extra zero byte is reserved at the end to ensure it is zero-terminated, but a size is present so strings with null bytes in them can be represented. This is an immutable object type. There are functions to create new bytes objects, to test an object for bytes-ness, and to get the byte string value. The latter function returns a null pointer if the object is not of the proper type. There is a variant that takes an explicit size as well as a variant that assumes a zero-terminated string. Note that none of the functions should be applied to NULL pointer. */ PyAPI_DATA(PyTypeObject) PyBytes_Type; PyAPI_DATA(PyTypeObject) PyBytesIter_Type; #define PyBytes_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_BYTES_SUBCLASS) #define PyBytes_CheckExact(op) Py_IS_TYPE(op, &PyBytes_Type) PyAPI_FUNC(PyObject *) PyBytes_FromStringAndSize(const char *, Py_ssize_t); PyAPI_FUNC(PyObject *) PyBytes_FromString(const char *); PyAPI_FUNC(PyObject *) PyBytes_FromObject(PyObject *); PyAPI_FUNC(PyObject *) PyBytes_FromFormatV(const char*, va_list) Py_GCC_ATTRIBUTE((format(printf, 1, 0))); PyAPI_FUNC(PyObject *) PyBytes_FromFormat(const char*, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); PyAPI_FUNC(Py_ssize_t) PyBytes_Size(PyObject *); PyAPI_FUNC(char *) PyBytes_AsString(PyObject *); PyAPI_FUNC(PyObject *) PyBytes_Repr(PyObject *, int); PyAPI_FUNC(void) PyBytes_Concat(PyObject **, PyObject *); PyAPI_FUNC(void) PyBytes_ConcatAndDel(PyObject **, PyObject *); PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t, const char *, Py_ssize_t, const char *); /* Provides access to the internal data buffer and size of a bytes object. Passing NULL as len parameter will force the string buffer to be 0-terminated (passing a string with embedded NUL characters will cause an exception). */ PyAPI_FUNC(int) PyBytes_AsStringAndSize( PyObject *obj, /* bytes object */ char **s, /* pointer to buffer variable */ Py_ssize_t *len /* pointer to length variable or NULL */ ); #ifndef Py_LIMITED_API # define Py_CPYTHON_BYTESOBJECT_H # include "cpython/bytesobject.h" # undef Py_CPYTHON_BYTESOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_BYTESOBJECT_H */
funcobject.c
/* Function object implementation */ #include "Python.h" #include "pycore_ceval.h" // _PyEval_BuiltinsFromGlobals() #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_pyerrors.h" // _PyErr_Occurred() #include "structmember.h" // PyMemberDef static uint32_t next_func_version = 1; PyFunctionObject * _PyFunction_FromConstructor(PyFrameConstructor *constr) { PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type); if (op == NULL) { return NULL; } Py_INCREF(constr->fc_globals); op->func_globals = constr->fc_globals; Py_INCREF(constr->fc_builtins); op->func_builtins = constr->fc_builtins; Py_INCREF(constr->fc_name); op->func_name = constr->fc_name; Py_INCREF(constr->fc_qualname); op->func_qualname = constr->fc_qualname; Py_INCREF(constr->fc_code); op->func_code = constr->fc_code; op->func_defaults = NULL; op->func_kwdefaults = NULL; Py_XINCREF(constr->fc_closure); op->func_closure = constr->fc_closure; Py_INCREF(Py_None); op->func_doc = Py_None; op->func_dict = NULL; op->func_weakreflist = NULL; op->func_module = NULL; op->func_annotations = NULL; op->vectorcall = _PyFunction_Vectorcall; op->func_version = 0; _PyObject_GC_TRACK(op); return op; } PyObject * PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname) { assert(globals != NULL); assert(PyDict_Check(globals)); Py_INCREF(globals); PyThreadState *tstate = _PyThreadState_GET(); PyCodeObject *code_obj = (PyCodeObject *)code; Py_INCREF(code_obj); PyObject *name = code_obj->co_name; assert(name != NULL); Py_INCREF(name); if (!qualname) { qualname = code_obj->co_qualname; } assert(qualname != NULL); Py_INCREF(qualname); PyObject *consts = code_obj->co_consts; assert(PyTuple_Check(consts)); PyObject *doc; if (PyTuple_Size(consts) >= 1) { doc = PyTuple_GetItem(consts, 0); if (!PyUnicode_Check(doc)) { doc = Py_None; } } else { doc = Py_None; } Py_INCREF(doc); // __module__: Use globals['__name__'] if it exists, or NULL. PyObject *module = PyDict_GetItemWithError(globals, &_Py_ID(__name__)); PyObject *builtins = NULL; if (module == NULL && _PyErr_Occurred(tstate)) { goto error; } Py_XINCREF(module); builtins = _PyEval_BuiltinsFromGlobals(tstate, globals); // borrowed ref if (builtins == NULL) { goto error; } Py_INCREF(builtins); PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type); if (op == NULL) { goto error; } /* Note: No failures from this point on, since func_dealloc() does not expect a partially-created object. */ op->func_globals = globals; op->func_builtins = builtins; op->func_name = name; op->func_qualname = qualname; op->func_code = (PyObject*)code_obj; op->func_defaults = NULL; // No default positional arguments op->func_kwdefaults = NULL; // No default keyword arguments op->func_closure = NULL; op->func_doc = doc; op->func_dict = NULL; op->func_weakreflist = NULL; op->func_module = module; op->func_annotations = NULL; op->vectorcall = _PyFunction_Vectorcall; op->func_version = 0; _PyObject_GC_TRACK(op); return (PyObject *)op; error: Py_DECREF(globals); Py_DECREF(code_obj); Py_DECREF(name); Py_DECREF(qualname); Py_DECREF(doc); Py_XDECREF(module); Py_XDECREF(builtins); return NULL; } uint32_t _PyFunction_GetVersionForCurrentState(PyFunctionObject *func) { if (func->func_version != 0) { return func->func_version; } if (next_func_version == 0) { return 0; } uint32_t v = next_func_version++; func->func_version = v; return v; } PyObject * PyFunction_New(PyObject *code, PyObject *globals) { return PyFunction_NewWithQualName(code, globals, NULL); } PyObject * PyFunction_GetCode(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_code; } PyObject * PyFunction_GetGlobals(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_globals; } PyObject * PyFunction_GetModule(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_module; } PyObject * PyFunction_GetDefaults(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_defaults; } int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (defaults == Py_None) defaults = NULL; else if (defaults && PyTuple_Check(defaults)) { Py_INCREF(defaults); } else { PyErr_SetString(PyExc_SystemError, "non-tuple default args"); return -1; } ((PyFunctionObject *)op)->func_version = 0; Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults); return 0; } PyObject * PyFunction_GetKwDefaults(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_kwdefaults; } int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (defaults == Py_None) defaults = NULL; else if (defaults && PyDict_Check(defaults)) { Py_INCREF(defaults); } else { PyErr_SetString(PyExc_SystemError, "non-dict keyword only default args"); return -1; } ((PyFunctionObject *)op)->func_version = 0; Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults); return 0; } PyObject * PyFunction_GetClosure(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_closure; } int PyFunction_SetClosure(PyObject *op, PyObject *closure) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (closure == Py_None) closure = NULL; else if (PyTuple_Check(closure)) { Py_INCREF(closure); } else { PyErr_Format(PyExc_SystemError, "expected tuple for closure, got '%.100s'", Py_TYPE(closure)->tp_name); return -1; } ((PyFunctionObject *)op)->func_version = 0; Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure); return 0; } static PyObject * func_get_annotation_dict(PyFunctionObject *op) { if (op->func_annotations == NULL) { return NULL; } if (PyTuple_CheckExact(op->func_annotations)) { PyObject *ann_tuple = op->func_annotations; PyObject *ann_dict = PyDict_New(); if (ann_dict == NULL) { return NULL; } assert(PyTuple_GET_SIZE(ann_tuple) % 2 == 0); for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(ann_tuple); i += 2) { int err = PyDict_SetItem(ann_dict, PyTuple_GET_ITEM(ann_tuple, i), PyTuple_GET_ITEM(ann_tuple, i + 1)); if (err < 0) { return NULL; } } Py_SETREF(op->func_annotations, ann_dict); } Py_INCREF(op->func_annotations); assert(PyDict_Check(op->func_annotations)); return op->func_annotations; } PyObject * PyFunction_GetAnnotations(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return func_get_annotation_dict((PyFunctionObject *)op); } int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (annotations == Py_None) annotations = NULL; else if (annotations && PyDict_Check(annotations)) { Py_INCREF(annotations); } else { PyErr_SetString(PyExc_SystemError, "non-dict annotations"); return -1; } ((PyFunctionObject *)op)->func_version = 0; Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations); return 0; } /* Methods */ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { {"__closure__", T_OBJECT, OFF(func_closure), READONLY}, {"__doc__", T_OBJECT, OFF(func_doc), 0}, {"__globals__", T_OBJECT, OFF(func_globals), READONLY}, {"__module__", T_OBJECT, OFF(func_module), 0}, {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY}, {NULL} /* Sentinel */ }; static PyObject * func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (PySys_Audit("object.__getattr__", "Os", op, "__code__") < 0) { return NULL; } Py_INCREF(op->func_code); return op->func_code; } static int func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { Py_ssize_t nclosure; int nfree; /* Not legal to del f.func_code or to set it to anything * other than a code object. */ if (value == NULL || !PyCode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__code__ must be set to a code object"); return -1; } if (PySys_Audit("object.__setattr__", "OsO", op, "__code__", value) < 0) { return -1; } nfree = ((PyCodeObject *)value)->co_nfreevars; nclosure = (op->func_closure == NULL ? 0 : PyTuple_GET_SIZE(op->func_closure)); if (nclosure != nfree) { PyErr_Format(PyExc_ValueError, "%U() requires a code object with %zd free vars," " not %zd", op->func_name, nclosure, nfree); return -1; } op->func_version = 0; Py_INCREF(value); Py_XSETREF(op->func_code, value); return 0; } static PyObject * func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->func_name); return op->func_name; } static int func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Not legal to del f.func_name or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } Py_INCREF(value); Py_XSETREF(op->func_name, value); return 0; } static PyObject * func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->func_qualname); return op->func_qualname; } static int func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Not legal to del f.__qualname__ or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } Py_INCREF(value); Py_XSETREF(op->func_qualname, value); return 0; } static PyObject * func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (PySys_Audit("object.__getattr__", "Os", op, "__defaults__") < 0) { return NULL; } if (op->func_defaults == NULL) { Py_RETURN_NONE; } Py_INCREF(op->func_defaults); return op->func_defaults; } static int func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Legal to del f.func_defaults. * Can only set func_defaults to NULL or a tuple. */ if (value == Py_None) value = NULL; if (value != NULL && !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, "__defaults__ must be set to a tuple object"); return -1; } if (value) { if (PySys_Audit("object.__setattr__", "OsO", op, "__defaults__", value) < 0) { return -1; } } else if (PySys_Audit("object.__delattr__", "Os", op, "__defaults__") < 0) { return -1; } op->func_version = 0; Py_XINCREF(value); Py_XSETREF(op->func_defaults, value); return 0; } static PyObject * func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (PySys_Audit("object.__getattr__", "Os", op, "__kwdefaults__") < 0) { return NULL; } if (op->func_kwdefaults == NULL) { Py_RETURN_NONE; } Py_INCREF(op->func_kwdefaults); return op->func_kwdefaults; } static int func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { if (value == Py_None) value = NULL; /* Legal to del f.func_kwdefaults. * Can only set func_kwdefaults to NULL or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__kwdefaults__ must be set to a dict object"); return -1; } if (value) { if (PySys_Audit("object.__setattr__", "OsO", op, "__kwdefaults__", value) < 0) { return -1; } } else if (PySys_Audit("object.__delattr__", "Os", op, "__kwdefaults__") < 0) { return -1; } op->func_version = 0; Py_XINCREF(value); Py_XSETREF(op->func_kwdefaults, value); return 0; } static PyObject * func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (op->func_annotations == NULL) { op->func_annotations = PyDict_New(); if (op->func_annotations == NULL) return NULL; } return func_get_annotation_dict(op); } static int func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { if (value == Py_None) value = NULL; /* Legal to del f.func_annotations. * Can only set func_annotations to NULL (through C api) * or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__annotations__ must be set to a dict object"); return -1; } op->func_version = 0; Py_XINCREF(value); Py_XSETREF(op->func_annotations, value); return 0; } static PyGetSetDef func_getsetlist[] = { {"__code__", (getter)func_get_code, (setter)func_set_code}, {"__defaults__", (getter)func_get_defaults, (setter)func_set_defaults}, {"__kwdefaults__", (getter)func_get_kwdefaults, (setter)func_set_kwdefaults}, {"__annotations__", (getter)func_get_annotations, (setter)func_set_annotations}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {"__name__", (getter)func_get_name, (setter)func_set_name}, {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname}, {NULL} /* Sentinel */ }; /*[clinic input] class function "PyFunctionObject *" "&PyFunction_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=70af9c90aa2e71b0]*/ #include "clinic/funcobject.c.h" /* function.__new__() maintains the following invariants for closures. The closure must correspond to the free variables of the code object. if len(code.co_freevars) == 0: closure = NULL else: len(closure) == len(code.co_freevars) for every elt in closure, type(elt) == cell */ /*[clinic input] @classmethod function.__new__ as func_new code: object(type="PyCodeObject *", subclass_of="&PyCode_Type") a code object globals: object(subclass_of="&PyDict_Type") the globals dictionary name: object = None a string that overrides the name from the code object argdefs as defaults: object = None a tuple that specifies the default argument values closure: object = None a tuple that supplies the bindings for free variables Create a function object. [clinic start generated code]*/ static PyObject * func_new_impl(PyTypeObject *type, PyCodeObject *code, PyObject *globals, PyObject *name, PyObject *defaults, PyObject *closure) /*[clinic end generated code: output=99c6d9da3a24e3be input=93611752fc2daf11]*/ { PyFunctionObject *newfunc; Py_ssize_t nclosure; if (name != Py_None && !PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "arg 3 (name) must be None or string"); return NULL; } if (defaults != Py_None && !PyTuple_Check(defaults)) { PyErr_SetString(PyExc_TypeError, "arg 4 (defaults) must be None or tuple"); return NULL; } if (!PyTuple_Check(closure)) { if (code->co_nfreevars && closure == Py_None) { PyErr_SetString(PyExc_TypeError, "arg 5 (closure) must be tuple"); return NULL; } else if (closure != Py_None) { PyErr_SetString(PyExc_TypeError, "arg 5 (closure) must be None or tuple"); return NULL; } } /* check that the closure is well-formed */ nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); if (code->co_nfreevars != nclosure) return PyErr_Format(PyExc_ValueError, "%U requires closure of length %zd, not %zd", code->co_name, code->co_nfreevars, nclosure); if (nclosure) { Py_ssize_t i; for (i = 0; i < nclosure; i++) { PyObject *o = PyTuple_GET_ITEM(closure, i); if (!PyCell_Check(o)) { return PyErr_Format(PyExc_TypeError, "arg 5 (closure) expected cell, found %s", Py_TYPE(o)->tp_name); } } } if (PySys_Audit("function.__new__", "O", code) < 0) { return NULL; } newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, globals); if (newfunc == NULL) { return NULL; } if (name != Py_None) { Py_INCREF(name); Py_SETREF(newfunc->func_name, name); } if (defaults != Py_None) { Py_INCREF(defaults); newfunc->func_defaults = defaults; } if (closure != Py_None) { Py_INCREF(closure); newfunc->func_closure = closure; } return (PyObject *)newfunc; } static int func_clear(PyFunctionObject *op) { op->func_version = 0; Py_CLEAR(op->func_globals); Py_CLEAR(op->func_builtins); Py_CLEAR(op->func_module); Py_CLEAR(op->func_defaults); Py_CLEAR(op->func_kwdefaults); Py_CLEAR(op->func_doc); Py_CLEAR(op->func_dict); Py_CLEAR(op->func_closure); Py_CLEAR(op->func_annotations); // Don't Py_CLEAR(op->func_code), since code is always required // to be non-NULL. Similarly, name and qualname shouldn't be NULL. // However, name and qualname could be str subclasses, so they // could have reference cycles. The solution is to replace them // with a genuinely immutable string. Py_SETREF(op->func_name, Py_NewRef(&_Py_STR(empty))); Py_SETREF(op->func_qualname, Py_NewRef(&_Py_STR(empty))); return 0; } static void func_dealloc(PyFunctionObject *op) { _PyObject_GC_UNTRACK(op); if (op->func_weakreflist != NULL) { PyObject_ClearWeakRefs((PyObject *) op); } (void)func_clear(op); // These aren't cleared by func_clear(). Py_DECREF(op->func_code); Py_DECREF(op->func_name); Py_DECREF(op->func_qualname); PyObject_GC_Del(op); } static PyObject* func_repr(PyFunctionObject *op) { return PyUnicode_FromFormat("<function %U at %p>", op->func_qualname, op); } static int func_traverse(PyFunctionObject *f, visitproc visit, void *arg) { Py_VISIT(f->func_code); Py_VISIT(f->func_globals); Py_VISIT(f->func_builtins); Py_VISIT(f->func_module); Py_VISIT(f->func_defaults); Py_VISIT(f->func_kwdefaults); Py_VISIT(f->func_doc); Py_VISIT(f->func_name); Py_VISIT(f->func_dict); Py_VISIT(f->func_closure); Py_VISIT(f->func_annotations); Py_VISIT(f->func_qualname); return 0; } /* Bind a function to an object */ static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { if (obj == Py_None || obj == NULL) { Py_INCREF(func); return func; } return PyMethod_New(func, obj); } PyTypeObject PyFunction_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "function", sizeof(PyFunctionObject), 0, (destructor)func_dealloc, /* tp_dealloc */ offsetof(PyFunctionObject, vectorcall), /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ (reprfunc)func_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ PyVectorcall_Call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_METHOD_DESCRIPTOR, /* tp_flags */ func_new__doc__, /* tp_doc */ (traverseproc)func_traverse, /* tp_traverse */ (inquiry)func_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ func_memberlist, /* tp_members */ func_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ func_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ func_new, /* tp_new */ }; static int functools_copy_attr(PyObject *wrapper, PyObject *wrapped, PyObject *name) { PyObject *value = PyObject_GetAttr(wrapped, name); if (value == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); return 0; } return -1; } int res = PyObject_SetAttr(wrapper, name, value); Py_DECREF(value); return res; } // Similar to functools.wraps(wrapper, wrapped) static int functools_wraps(PyObject *wrapper, PyObject *wrapped) { #define COPY_ATTR(ATTR) \ do { \ if (functools_copy_attr(wrapper, wrapped, &_Py_ID(ATTR)) < 0) { \ return -1; \ } \ } while (0) \ COPY_ATTR(__module__); COPY_ATTR(__name__); COPY_ATTR(__qualname__); COPY_ATTR(__doc__); COPY_ATTR(__annotations__); return 0; #undef COPY_ATTR } /* Class method object */ /* A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: @classmethod def f(cls, arg1, arg2, ...): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see static methods below. */ typedef struct { PyObject_HEAD PyObject *cm_callable; PyObject *cm_dict; } classmethod; static void cm_dealloc(classmethod *cm) { _PyObject_GC_UNTRACK((PyObject *)cm); Py_XDECREF(cm->cm_callable); Py_XDECREF(cm->cm_dict); Py_TYPE(cm)->tp_free((PyObject *)cm); } static int cm_traverse(classmethod *cm, visitproc visit, void *arg) { Py_VISIT(cm->cm_callable); Py_VISIT(cm->cm_dict); return 0; } static int cm_clear(classmethod *cm) { Py_CLEAR(cm->cm_callable); Py_CLEAR(cm->cm_dict); return 0; } static PyObject * cm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { classmethod *cm = (classmethod *)self; if (cm->cm_callable == NULL) { PyErr_SetString(PyExc_RuntimeError, "uninitialized classmethod object"); return NULL; } if (type == NULL) type = (PyObject *)(Py_TYPE(obj)); if (Py_TYPE(cm->cm_callable)->tp_descr_get != NULL) { return Py_TYPE(cm->cm_callable)->tp_descr_get(cm->cm_callable, type, type); } return PyMethod_New(cm->cm_callable, type); } static int cm_init(PyObject *self, PyObject *args, PyObject *kwds) { classmethod *cm = (classmethod *)self; PyObject *callable; if (!_PyArg_NoKeywords("classmethod", kwds)) return -1; if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) return -1; Py_INCREF(callable); Py_XSETREF(cm->cm_callable, callable); if (functools_wraps((PyObject *)cm, cm->cm_callable) < 0) { return -1; } return 0; } static PyMemberDef cm_memberlist[] = { {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, {"__wrapped__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, {NULL} /* Sentinel */ }; static PyObject * cm_get___isabstractmethod__(classmethod *cm, void *closure) { int res = _PyObject_IsAbstract(cm->cm_callable); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyGetSetDef cm_getsetlist[] = { {"__isabstractmethod__", (getter)cm_get___isabstractmethod__, NULL, NULL, NULL}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL}, {NULL} /* Sentinel */ }; static PyObject* cm_repr(classmethod *cm) { return PyUnicode_FromFormat("<classmethod(%R)>", cm->cm_callable); } PyDoc_STRVAR(classmethod_doc, "classmethod(function) -> method\n\ \n\ Convert a function to be a class method.\n\ \n\ A class method receives the class as implicit first argument,\n\ just like an instance method receives the instance.\n\ To declare a class method, use this idiom:\n\ \n\ class C:\n\ @classmethod\n\ def f(cls, arg1, arg2, ...):\n\ ...\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ If a class method is called for a derived class, the derived class\n\ object is passed as the implied first argument.\n\ \n\ Class methods are different than C++ or Java static methods.\n\ If you want those, see the staticmethod builtin."); PyTypeObject PyClassMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "classmethod", sizeof(classmethod), 0, (destructor)cm_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ (reprfunc)cm_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, classmethod_doc, /* tp_doc */ (traverseproc)cm_traverse, /* tp_traverse */ (inquiry)cm_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ cm_memberlist, /* tp_members */ cm_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ cm_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(classmethod, cm_dict), /* tp_dictoffset */ cm_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * PyClassMethod_New(PyObject *callable) { classmethod *cm = (classmethod *) PyType_GenericAlloc(&PyClassMethod_Type, 0); if (cm != NULL) { Py_INCREF(callable); cm->cm_callable = callable; } return (PyObject *)cm; } /* Static method object */ /* A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C: @staticmethod def f(arg1, arg2, ...): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). Both the class and the instance are ignored, and neither is passed implicitly as the first argument to the method. Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see class methods above. */ typedef struct { PyObject_HEAD PyObject *sm_callable; PyObject *sm_dict; } staticmethod; static void sm_dealloc(staticmethod *sm) { _PyObject_GC_UNTRACK((PyObject *)sm); Py_XDECREF(sm->sm_callable); Py_XDECREF(sm->sm_dict); Py_TYPE(sm)->tp_free((PyObject *)sm); } static int sm_traverse(staticmethod *sm, visitproc visit, void *arg) { Py_VISIT(sm->sm_callable); Py_VISIT(sm->sm_dict); return 0; } static int sm_clear(staticmethod *sm) { Py_CLEAR(sm->sm_callable); Py_CLEAR(sm->sm_dict); return 0; } static PyObject * sm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { staticmethod *sm = (staticmethod *)self; if (sm->sm_callable == NULL) { PyErr_SetString(PyExc_RuntimeError, "uninitialized staticmethod object"); return NULL; } Py_INCREF(sm->sm_callable); return sm->sm_callable; } static int sm_init(PyObject *self, PyObject *args, PyObject *kwds) { staticmethod *sm = (staticmethod *)self; PyObject *callable; if (!_PyArg_NoKeywords("staticmethod", kwds)) return -1; if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) return -1; Py_INCREF(callable); Py_XSETREF(sm->sm_callable, callable); if (functools_wraps((PyObject *)sm, sm->sm_callable) < 0) { return -1; } return 0; } static PyObject* sm_call(PyObject *callable, PyObject *args, PyObject *kwargs) { staticmethod *sm = (staticmethod *)callable; return PyObject_Call(sm->sm_callable, args, kwargs); } static PyMemberDef sm_memberlist[] = { {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, {"__wrapped__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, {NULL} /* Sentinel */ }; static PyObject * sm_get___isabstractmethod__(staticmethod *sm, void *closure) { int res = _PyObject_IsAbstract(sm->sm_callable); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyGetSetDef sm_getsetlist[] = { {"__isabstractmethod__", (getter)sm_get___isabstractmethod__, NULL, NULL, NULL}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL}, {NULL} /* Sentinel */ }; static PyObject* sm_repr(staticmethod *sm) { return PyUnicode_FromFormat("<staticmethod(%R)>", sm->sm_callable); } PyDoc_STRVAR(staticmethod_doc, "staticmethod(function) -> method\n\ \n\ Convert a function to be a static method.\n\ \n\ A static method does not receive an implicit first argument.\n\ To declare a static method, use this idiom:\n\ \n\ class C:\n\ @staticmethod\n\ def f(arg1, arg2, ...):\n\ ...\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). Both the class and the instance are ignored, and\n\ neither is passed implicitly as the first argument to the method.\n\ \n\ Static methods in Python are similar to those found in Java or C++.\n\ For a more advanced concept, see the classmethod builtin."); PyTypeObject PyStaticMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "staticmethod", sizeof(staticmethod), 0, (destructor)sm_dealloc, /* tp_dealloc */ 0, /* tp_vectorcall_offset */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ (reprfunc)sm_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ sm_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, staticmethod_doc, /* tp_doc */ (traverseproc)sm_traverse, /* tp_traverse */ (inquiry)sm_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ sm_memberlist, /* tp_members */ sm_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ sm_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(staticmethod, sm_dict), /* tp_dictoffset */ sm_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * PyStaticMethod_New(PyObject *callable) { staticmethod *sm = (staticmethod *) PyType_GenericAlloc(&PyStaticMethod_Type, 0); if (sm != NULL) { Py_INCREF(callable); sm->sm_callable = callable; } return (PyObject *)sm; }
int64.ml
open! Import open! Caml.Int64 module T = struct type t = int64 [@@deriving_inline hash, sexp, sexp_grammar] let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) = hash_fold_int64 and (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) = let func = hash_int64 in fun x -> func x ;; let t_of_sexp = (int64_of_sexp : Sexplib0.Sexp.t -> t) let sexp_of_t = (sexp_of_int64 : t -> Sexplib0.Sexp.t) let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) = int64_sexp_grammar [@@@end] let hashable : t Hashable.t = { hash; compare; sexp_of_t } let compare = Int64_replace_polymorphic_compare.compare let to_string = to_string let of_string = of_string end include T include Comparator.Make (T) let num_bits = 64 let float_lower_bound = Float0.lower_bound_for_int num_bits let float_upper_bound = Float0.upper_bound_for_int num_bits let float_of_bits = float_of_bits let bits_of_float = bits_of_float let shift_right_logical = shift_right_logical let shift_right = shift_right let shift_left = shift_left let bit_not = lognot let bit_xor = logxor let bit_or = logor let bit_and = logand let min_value = min_int let max_value = max_int let abs = abs let pred = pred let succ = succ let pow = Int_math.Private.int64_pow let rem = rem let neg = neg let minus_one = minus_one let one = one let zero = zero let to_float = to_float let of_float_unchecked = Caml.Int64.of_float let of_float f = if Float_replace_polymorphic_compare.( >= ) f float_lower_bound && Float_replace_polymorphic_compare.( <= ) f float_upper_bound then Caml.Int64.of_float f else Printf.invalid_argf "Int64.of_float: argument (%f) is out of range or NaN" (Float0.box f) () ;; let ( ** ) b e = pow b e external bswap64 : t -> t = "%bswap_int64" let[@inline always] bswap16 x = Caml.Int64.shift_right_logical (bswap64 x) 48 let[@inline always] bswap32 x = (* This is strictly better than coercing to an int32 to perform byteswap. Coercing from an int32 will add unnecessary shift operations to sign extend the number appropriately. *) Caml.Int64.shift_right_logical (bswap64 x) 32 ;; let[@inline always] bswap48 x = Caml.Int64.shift_right_logical (bswap64 x) 16 include Comparable.With_zero (struct include T let zero = zero end) (* Open replace_polymorphic_compare after including functor instantiations so they do not shadow its definitions. This is here so that efficient versions of the comparison functions are available within this module. *) open Int64_replace_polymorphic_compare let invariant (_ : t) = () let between t ~low ~high = low <= t && t <= high let clamp_unchecked t ~min ~max = if t < min then min else if t <= max then t else max let clamp_exn t ~min ~max = assert (min <= max); clamp_unchecked t ~min ~max ;; let clamp t ~min ~max = if min > max then Or_error.error_s (Sexp.message "clamp requires [min <= max]" [ "min", T.sexp_of_t min; "max", T.sexp_of_t max ]) else Ok (clamp_unchecked t ~min ~max) ;; let incr r = r := add !r one let decr r = r := sub !r one external of_int64 : t -> t = "%identity" let of_int64_exn = of_int64 let to_int64 t = t let popcount = Popcount.int64_popcount module Conv = Int_conversions external to_int_trunc : t -> int = "%int64_to_int" external to_int32_trunc : int64 -> int32 = "%int64_to_int32" external to_nativeint_trunc : int64 -> nativeint = "%int64_to_nativeint" external of_int : int -> int64 = "%int64_of_int" external of_int32 : int32 -> int64 = "%int64_of_int32" let of_int_exn = of_int let to_int = Conv.int64_to_int let to_int_exn = Conv.int64_to_int_exn let of_int32_exn = of_int32 let to_int32 = Conv.int64_to_int32 let to_int32_exn = Conv.int64_to_int32_exn let of_nativeint = Conv.nativeint_to_int64 let of_nativeint_exn = of_nativeint let to_nativeint = Conv.int64_to_nativeint let to_nativeint_exn = Conv.int64_to_nativeint_exn module Pow2 = struct open! Import open Int64_replace_polymorphic_compare let raise_s = Error.raise_s let non_positive_argument () = Printf.invalid_argf "argument must be strictly positive" () ;; let ( lor ) = Caml.Int64.logor let ( lsr ) = Caml.Int64.shift_right_logical let ( land ) = Caml.Int64.logand (** "ceiling power of 2" - Least power of 2 greater than or equal to x. *) let ceil_pow2 x = if x <= Caml.Int64.zero then non_positive_argument (); let x = Caml.Int64.pred x in let x = x lor (x lsr 1) in let x = x lor (x lsr 2) in let x = x lor (x lsr 4) in let x = x lor (x lsr 8) in let x = x lor (x lsr 16) in let x = x lor (x lsr 32) in Caml.Int64.succ x ;; (** "floor power of 2" - Largest power of 2 less than or equal to x. *) let floor_pow2 x = if x <= Caml.Int64.zero then non_positive_argument (); let x = x lor (x lsr 1) in let x = x lor (x lsr 2) in let x = x lor (x lsr 4) in let x = x lor (x lsr 8) in let x = x lor (x lsr 16) in let x = x lor (x lsr 32) in Caml.Int64.sub x (x lsr 1) ;; let is_pow2 x = if x <= Caml.Int64.zero then non_positive_argument (); x land Caml.Int64.pred x = Caml.Int64.zero ;; (* C stubs for int clz and ctz to use the CLZ/BSR/CTZ/BSF instruction where possible *) external clz : (int64[@unboxed]) -> (int[@untagged]) = "Base_int_math_int64_clz" "Base_int_math_int64_clz_unboxed" [@@noalloc] external ctz : (int64[@unboxed]) -> (int[@untagged]) = "Base_int_math_int64_ctz" "Base_int_math_int64_ctz_unboxed" [@@noalloc] (** Hacker's Delight Second Edition p106 *) let floor_log2 i = if i <= Caml.Int64.zero then raise_s (Sexp.message "[Int64.floor_log2] got invalid input" [ "", sexp_of_int64 i ]); num_bits - 1 - clz i ;; (** Hacker's Delight Second Edition p106 *) let ceil_log2 i = if Poly.( <= ) i Caml.Int64.zero then raise_s (Sexp.message "[Int64.ceil_log2] got invalid input" [ "", sexp_of_int64 i ]); if Caml.Int64.equal i Caml.Int64.one then 0 else num_bits - clz (Caml.Int64.pred i) ;; end include Pow2 include Conv.Make (T) include Conv.Make_hex (struct type t = int64 [@@deriving_inline compare, hash] let compare = (compare_int64 : t -> t -> int) let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) = hash_fold_int64 and (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) = let func = hash_int64 in fun x -> func x ;; [@@@end] let zero = zero let neg = neg let ( < ) = ( < ) let to_string i = Printf.sprintf "%Lx" i let of_string s = Caml.Scanf.sscanf s "%Lx" Fn.id let module_name = "Base.Int64.Hex" end) include Pretty_printer.Register (struct type nonrec t = t let to_string = to_string let module_name = "Base.Int64" end) module Pre_O = struct external ( + ) : t -> t -> t = "%int64_add" external ( - ) : t -> t -> t = "%int64_sub" external ( * ) : t -> t -> t = "%int64_mul" external ( / ) : t -> t -> t = "%int64_div" external ( ~- ) : t -> t = "%int64_neg" let ( ** ) = ( ** ) include Int64_replace_polymorphic_compare let abs = abs external neg : t -> t = "%int64_neg" let zero = zero let of_int_exn = of_int_exn end module O = struct include Pre_O include Int_math.Make (struct type nonrec t = t include Pre_O let rem = rem let to_float = to_float let of_float = of_float let of_string = T.of_string let to_string = T.to_string end) external ( land ) : t -> t -> t = "%int64_and" external ( lor ) : t -> t -> t = "%int64_or" external ( lxor ) : t -> t -> t = "%int64_xor" let lnot = bit_not external ( lsl ) : t -> int -> t = "%int64_lsl" external ( asr ) : t -> int -> t = "%int64_asr" external ( lsr ) : t -> int -> t = "%int64_lsr" end include O (* [Int64] and [Int64.O] agree value-wise *) (* Include type-specific [Replace_polymorphic_compare] at the end, after including functor application that could shadow its definitions. This is here so that efficient versions of the comparison functions are exported by this module. *) include Int64_replace_polymorphic_compare
client_proto_multisig.ml
open Protocol_client_context open Protocol open Alpha_context open Michelson_v1_helpers type error += Contract_has_no_script of Contract.t type error += Not_a_supported_multisig_contract of Script_expr_hash.t type error += Contract_has_no_storage of Contract.t type error += Contract_has_unexpected_storage of Contract.t type error += Invalid_signature of signature type error += Not_enough_signatures of int * int type error += Action_deserialisation_error of Script.expr type error += Bytes_deserialisation_error of Bytes.t type error += Bad_deserialized_contract of (Contract.t * Contract.t) type error += Bad_deserialized_counter of (counter * counter) type error += Non_positive_threshold of int type error += Threshold_too_high of int * int type error += Unsupported_feature_generic_call of Script.expr type error += Unsupported_feature_generic_call_ty of Script.expr type error += Unsupported_feature_lambda of string type error += | Ill_typed_argument of Contract.t * string * Script.expr * Script.expr type error += Ill_typed_lambda of Script.expr * Script.expr let () = register_error_kind `Permanent ~id:"contractHasNoScript" ~title: "The given contract is not a multisig contract because it has no script" ~description: "A multisig command has referenced a scriptless smart contract instead \ of a multisig smart contract." ~pp:(fun ppf contract -> Format.fprintf ppf "Contract has no script %a." Contract.pp contract) Data_encoding.(obj1 (req "contract" Contract.encoding)) (function Contract_has_no_script c -> Some c | _ -> None) (fun c -> Contract_has_no_script c) ; register_error_kind `Permanent ~id:"notASupportedMultisigContract" ~title:"The given contract is not one of the supported contracts" ~description: "A multisig command has referenced a smart contract whose script is not \ one of the known multisig contract scripts." ~pp:(fun ppf hash -> Format.fprintf ppf "Not a supported multisig contract.@\n\ The hash of this script is %a, it was not found among in the list of \ known multisig script hashes." Script_expr_hash.pp hash) Data_encoding.(obj1 (req "hash" Script_expr_hash.encoding)) (function Not_a_supported_multisig_contract h -> Some h | _ -> None) (fun h -> Not_a_supported_multisig_contract h) ; register_error_kind `Permanent ~id:"contractHasNoStorage" ~title: "The given contract is not a multisig contract because it has no storage" ~description: "A multisig command has referenced a smart contract without storage \ instead of a multisig smart contract." ~pp:(fun ppf contract -> Format.fprintf ppf "Contract has no storage %a." Contract.pp contract) Data_encoding.(obj1 (req "contract" Contract.encoding)) (function Contract_has_no_storage c -> Some c | _ -> None) (fun c -> Contract_has_no_storage c) ; register_error_kind `Permanent ~id:"contractHasUnexpectedStorage" ~title: "The storage of the given contract is not of the shape expected for a \ multisig contract" ~description: "A multisig command has referenced a smart contract whose storage is of \ a different shape than the expected one." ~pp:(fun ppf contract -> Format.fprintf ppf "Contract has unexpected storage %a." Contract.pp contract) Data_encoding.(obj1 (req "contract" Contract.encoding)) (function Contract_has_unexpected_storage c -> Some c | _ -> None) (fun c -> Contract_has_unexpected_storage c) ; register_error_kind `Permanent ~id:"invalidSignature" ~title: "The following signature did not match a public key in the given \ multisig contract" ~description: "A signature was given for a multisig contract that matched none of the \ public keys of the contract signers" ~pp:(fun ppf s -> Format.fprintf ppf "Invalid signature %s." (Signature.to_b58check s)) Data_encoding.(obj1 (req "invalid_signature" Signature.encoding)) (function Invalid_signature s -> Some s | _ -> None) (fun s -> Invalid_signature s) ; register_error_kind `Permanent ~id:"notEnoughSignatures" ~title:"Not enough signatures were provided for this multisig action" ~description: "To run an action on a multisig contract, you should provide at least as \ many signatures as indicated by the threshold stored in the multisig \ contract." ~pp:(fun ppf (threshold, nsigs) -> Format.fprintf ppf "Not enough signatures: only %d signatures were given but the \ threshold is currently %d" nsigs threshold) Data_encoding.(obj1 (req "threshold_nsigs" (tup2 int31 int31))) (function | Not_enough_signatures (threshold, nsigs) -> Some (threshold, nsigs) | _ -> None) (fun (threshold, nsigs) -> Not_enough_signatures (threshold, nsigs)) ; register_error_kind `Permanent ~id:"actionDeserialisation" ~title:"The expression is not a valid multisig action" ~description: "When trying to deserialise an action from a sequence of bytes, we got \ an expression that does not correspond to a known multisig action" ~pp:(fun ppf e -> Format.fprintf ppf "Action deserialisation error %a." Michelson_v1_printer.print_expr e) Data_encoding.(obj1 (req "expr" Script.expr_encoding)) (function Action_deserialisation_error e -> Some e | _ -> None) (fun e -> Action_deserialisation_error e) ; register_error_kind `Permanent ~id:"bytesDeserialisation" ~title:"The byte sequence is not a valid multisig action" ~description: "When trying to deserialise an action from a sequence of bytes, we got \ an error" ~pp:(fun ppf b -> Format.fprintf ppf "Bytes deserialisation error %s." (Bytes.to_string b)) Data_encoding.(obj1 (req "expr" bytes)) (function Bytes_deserialisation_error b -> Some b | _ -> None) (fun b -> Bytes_deserialisation_error b) ; register_error_kind `Permanent ~id:"badDeserializedContract" ~title:"The byte sequence is not for the given multisig contract" ~description: "When trying to deserialise an action from a sequence of bytes, we got \ an action for another multisig contract" ~pp:(fun ppf (received, expected) -> Format.fprintf ppf "Bad deserialized contract, received %a expected %a." Contract.pp received Contract.pp expected) Data_encoding.( obj1 (req "received_expected" (tup2 Contract.encoding Contract.encoding))) (function Bad_deserialized_contract b -> Some b | _ -> None) (fun b -> Bad_deserialized_contract b) ; register_error_kind `Permanent ~id:"Bad deserialized counter" ~title:"Deserialized counter does not match the stored one" ~description: "The byte sequence references a multisig counter that does not match the \ one currently stored in the given multisig contract" ~pp:(fun ppf (received, expected) -> Format.fprintf ppf "Bad deserialized counter, received %d expected %d." received expected) Data_encoding.(obj1 (req "received_expected" (tup2 int31 int31))) (function | Bad_deserialized_counter (c1, c2) -> Some (Z.to_int c1, Z.to_int c2) | _ -> None) (fun (c1, c2) -> Bad_deserialized_counter (Z.of_int c1, Z.of_int c2)) ; register_error_kind `Permanent ~id:"thresholdTooHigh" ~title:"Given threshold is too high" ~description: "The given threshold is higher than the number of keys, this would lead \ to a frozen multisig contract" ~pp:(fun ppf (threshold, nkeys) -> Format.fprintf ppf "Threshold too high: %d expected at most %d." threshold nkeys) Data_encoding.(obj1 (req "received_expected" (tup2 int31 int31))) (function Threshold_too_high (c1, c2) -> Some (c1, c2) | _ -> None) (fun (c1, c2) -> Threshold_too_high (c1, c2)) ; register_error_kind `Permanent ~id:"nonPositiveThreshold" ~title:"Given threshold is not positive" ~description:"A multisig threshold should be a positive number" ~pp:(fun ppf threshold -> Format.fprintf ppf "Multisig threshold %d should be positive." threshold) Data_encoding.(obj1 (req "threshold" int31)) (function Non_positive_threshold t -> Some t | _ -> None) (fun t -> Non_positive_threshold t) ; register_error_kind `Permanent ~id:"unsupportedGenericMultisigFeature" ~title:"Unsupported multisig feature: generic call" ~description: "This multisig contract does not feature calling contracts with arguments" ~pp:(fun ppf arg -> Format.fprintf ppf "This multisig contract can only transfer tokens to contracts of type \ unit; calling a contract with argument %a is not supported." Michelson_v1_printer.print_expr arg) Data_encoding.(obj1 (req "arg" Script.expr_encoding)) (function Unsupported_feature_generic_call arg -> Some arg | _ -> None) (fun arg -> Unsupported_feature_generic_call arg) ; register_error_kind `Permanent ~id:"unsupportedGenericMultisigFeatureTy" ~title:"Unsupported multisig feature: generic call to non-unit entrypoint" ~description: "This multisig contract does not feature calling contracts with arguments" ~pp:(fun ppf ty -> Format.fprintf ppf "This multisig contract can only transfer tokens to contracts of type \ unit; calling a contract of type %a is not supported." Michelson_v1_printer.print_expr ty) Data_encoding.(obj1 (req "ty" Script.expr_encoding)) (function Unsupported_feature_generic_call_ty ty -> Some ty | _ -> None) (fun ty -> Unsupported_feature_generic_call_ty ty) ; register_error_kind `Permanent ~id:"unsupportedGenericMultisigLambda" ~title:"Unsupported multisig feature: running lambda" ~description:"This multisig contract does not feature running lambdas" ~pp:(fun ppf lam -> Format.fprintf ppf "This multisig contract has a fixed set of actions, it cannot run the \ following lambda: %s." lam) Data_encoding.(obj1 (req "lam" string)) (function Unsupported_feature_lambda lam -> Some lam | _ -> None) (fun lam -> Unsupported_feature_lambda lam) ; register_error_kind `Permanent ~id:"illTypedArgumentForMultisig" ~title:"Ill-typed argument in multi-signed transfer" ~description: "The provided argument for a transfer from a multisig contract is \ ill-typed" ~pp:(fun ppf (destination, entrypoint, parameter_ty, parameter) -> Format.fprintf ppf "The entrypoint %s of contract %a called from a multisig contract is \ of type %a; the provided parameter %a is ill-typed." entrypoint Contract.pp destination Michelson_v1_printer.print_expr parameter_ty Michelson_v1_printer.print_expr parameter) Data_encoding.( obj4 (req "destination" Contract.encoding) (req "entrypoint" string) (req "parameter_ty" Script.expr_encoding) (req "parameter" Script.expr_encoding)) (function | Ill_typed_argument (destination, entrypoint, parameter_ty, parameter) -> Some (destination, entrypoint, parameter_ty, parameter) | _ -> None) (fun (destination, entrypoint, parameter_ty, parameter) -> Ill_typed_argument (destination, entrypoint, parameter_ty, parameter)) ; register_error_kind `Permanent ~id:"illTypedLambdaForMultisig" ~title:"Ill-typed lambda for multi-signed transfer" ~description: "The provided lambda for a transfer from a multisig contract is ill-typed" ~pp:(fun ppf (lam, exp) -> Format.fprintf ppf "The provided lambda %a for multisig contract is ill-typed; %a is \ expected." Michelson_v1_printer.print_expr lam Michelson_v1_printer.print_expr exp) Data_encoding.( obj2 (req "lam" Script.expr_encoding) (req "exp" Script.expr_encoding)) (function Ill_typed_lambda (lam, exp) -> Some (lam, exp) | _ -> None) (fun (lam, exp) -> Ill_typed_lambda (lam, exp)) (* The multisig contract script written by Arthur Breitman https://github.com/murbard/smart-contracts/blob/abdb582d8f1fe7ba7eb15975867d8862cb70acfe/multisig/michelson/generic.tz *) let multisig_script_string = {| parameter (or (unit %default) (pair %main (pair :payload (nat %counter) # counter, used to prevent replay attacks (or :action # payload to sign, represents the requested action (lambda %operation unit (list operation)) (pair %change_keys # change the keys controlling the multisig (nat %threshold) # new threshold (list %keys key)))) # new list of keys (list %sigs (option signature)))); # signatures storage (pair (nat %stored_counter) (pair (nat %threshold) (list %keys key))) ; code { UNPAIR ; IF_LEFT { # Default entry point: do nothing # This entry point can be used to send tokens to this contract DROP ; NIL operation ; PAIR } { # Main entry point # Assert no token was sent: # to send tokens, the default entry point should be used PUSH mutez 0 ; AMOUNT ; ASSERT_CMPEQ ; SWAP ; DUP ; DIP { SWAP } ; DIP { UNPAIR ; # pair the payload with the current contract address, to ensure signatures # can't be replayed accross different contracts if a key is reused. DUP ; SELF ; ADDRESS ; CHAIN_ID ; PAIR ; PAIR ; PACK ; # form the binary payload that we expect to be signed DIP { UNPAIR @counter ; DIP { SWAP } } ; SWAP } ; # Check that the counters match UNPAIR @stored_counter; DIP { SWAP }; ASSERT_CMPEQ ; # Compute the number of valid signatures DIP { SWAP } ; UNPAIR @threshold @keys; DIP { # Running count of valid signatures PUSH @valid nat 0; SWAP ; ITER { DIP { SWAP } ; SWAP ; IF_CONS { IF_SOME { SWAP ; DIP { SWAP ; DIIP { DUUP } ; # Checks signatures, fails if invalid { DUUUP; DIP {CHECK_SIGNATURE}; SWAP; IF {DROP} {FAILWITH} }; PUSH nat 1 ; ADD @valid } } { SWAP ; DROP } } { # There were fewer signatures in the list # than keys. Not all signatures must be present, but # they should be marked as absent using the option type. FAIL } ; SWAP } } ; # Assert that the threshold is less than or equal to the # number of valid signatures. ASSERT_CMPLE ; # Assert no unchecked signature remains IF_CONS {FAIL} {} ; DROP ; # Increment counter and place in storage DIP { UNPAIR ; PUSH nat 1 ; ADD @new_counter ; PAIR} ; # We have now handled the signature verification part, # produce the operation requested by the signers. IF_LEFT { # Get operation UNIT ; EXEC } { # Change set of signatures DIP { CAR } ; SWAP ; PAIR ; NIL operation }; PAIR } } |} (* Client_proto_context.originate expects the contract script as a Script.expr *) let multisig_script : Script.expr = Michelson_v1_parser.parse_toplevel ?check:(Some true) multisig_script_string |> Tezos_micheline.Micheline_parser.no_parsing_error |> function | Error _ -> assert false (* This is a top level assertion, it is asserted when the client's process runs. *) | Ok parsing_result -> parsing_result.Michelson_v1_parser.expanded let multisig_script_hash = let bytes = Data_encoding.Binary.to_bytes_exn Script.expr_encoding multisig_script in Script_expr_hash.hash_bytes [bytes] (* The previous multisig script is the only one that the client can originate but the client knows how to interact with several versions of the multisig contract. For each version, the description indicates which features are available and how to interact with the contract. *) type multisig_contract_description = { hash : Script_expr_hash.t; (* The hash of the contract script *) requires_chain_id : bool; (* The signatures should contain the chain identifier *) main_entrypoint : string option; (* name of the main entrypoint of the multisig contract, None means use the default entrypoint *) generic : bool; (* False means that the contract uses a custom action type, true means that the contract expects the action as a (lambda unit (list operation)). *) } (* List of known multisig contracts hashes with their kinds *) let known_multisig_contracts : multisig_contract_description list = [ { (* First supported version of the generic multisig contract. Supports incoming transfers from unauthenticated senders and outgoing transfers of arbitrary operation lists. See docs/user/multisig.rst for more details. *) hash = multisig_script_hash; requires_chain_id = true; main_entrypoint = Some "main"; generic = true; }; { (* Fourth supported version of the legacy multisig contract. This script is functionally equivalent to the third version but uses the [DUP 2] instruction introduced in Edo instead of the macro for [DIG 2; DUP; DUG 3]. *) hash = Script_expr_hash.of_b58check_exn "exprutz4BVGJ3Qms6qjmqvUF8sEk27H1cfqhRT17qpTdhEs5hEjbWm"; requires_chain_id = true; main_entrypoint = None; generic = false; }; { (* Third supported version of the legacy multisig contract. This script is functionally equivalent to the second version but uses the [DIP 2] instruction introduced in Babylon instead of the [DIIP] macro. *) hash = Script_expr_hash.of_b58check_exn "exprumpS39YZd26Cn4kyKUK5ezTR3at838iGWg7i6uETv8enDeAnfb"; requires_chain_id = true; main_entrypoint = None; generic = false; }; { (* Second supported version of the legacy multisig contract. This script is the one resulting from the stitching of the Babylon protocol, the only difference with the first version is that the chain id is part of the data to sign. *) hash = Script_expr_hash.of_b58check_exn "exprtw1v4KvQN414oEXdGuA1U3eQizuCdS8cipx8QGK8TbNLRwc3qL"; requires_chain_id = true; main_entrypoint = None; generic = false; }; { (* First supported version of the legacy multisig contract. This script should not be used anymore because it is subject to a small replay attack: when the test chain is forked both instances have the same address and counter so whatever happens on the test chain can be replayed on the main chain. The script has been fixed during the activation of the Babylon protocol. *) hash = Script_expr_hash.of_b58check_exn "expru4Ju9kf6MQ216FxUEsb9P6j8UhkPtsFcYP8r9XhQSRb47FZGfM"; requires_chain_id = false; main_entrypoint = None; generic = false; }; ] let known_multisig_hashes = List.map (fun descr -> descr.hash) known_multisig_contracts let check_multisig_script_hash hash : multisig_contract_description tzresult Lwt.t = match List.find_opt (fun d -> Script_expr_hash.(d.hash = hash)) known_multisig_contracts with | None -> fail (Not_a_supported_multisig_contract hash) | Some d -> return d (* Returns [Ok ()] if [~contract] is an originated contract whose code is [multisig_script] *) let check_multisig_contract (cctxt : #Protocol_client_context.full) ~chain ~block contract = Client_proto_context.get_script_hash cctxt ~chain ~block contract >>=? function | None -> fail (Contract_has_no_script contract) | Some hash -> check_multisig_script_hash hash (* Some Michelson building functions, specific to the needs of the multisig interface.*) (* The type of the lambdas consumed by the generic script *) let lambda_action_t ~loc = lambda_t ~loc (unit_t ~loc) (operations_t ~loc) (* Conversion functions from common types to Script_expr using the optimized representation *) let mutez ~loc (amount : Tez.t) = int ~loc (Z.of_int64 (Tez.to_mutez amount)) let optimized_key_hash ~loc (key_hash : Signature.Public_key_hash.t) = bytes ~loc (Data_encoding.Binary.to_bytes_exn Signature.Public_key_hash.encoding key_hash) let optimized_address ~loc ~(address : Contract.t) ~(entrypoint : string) = let entrypoint = match entrypoint with "default" -> "" | name -> name in bytes ~loc (Data_encoding.Binary.to_bytes_exn Data_encoding.(tup2 Contract.encoding Variable.string) (address, entrypoint)) let optimized_key ~loc (key : Signature.Public_key.t) = bytes ~loc (Data_encoding.Binary.to_bytes_exn Signature.Public_key.encoding key) (** * Actions *) type multisig_action = | Transfer of { amount : Tez.t; destination : Contract.t; entrypoint : string; parameter_type : Script.expr; parameter : Script.expr; } | Change_delegate of public_key_hash option | Lambda of Script.expr | Change_keys of Z.t * public_key list let action_to_expr_generic ~loc = function | Transfer {amount; destination; entrypoint; parameter_type; parameter} -> ( match Contract.is_implicit destination with | Some destination -> lambda_from_string @@ Managed_contract.build_lambda_for_transfer_to_implicit ~destination ~amount >|? left ~loc | None -> lambda_from_string @@ Managed_contract.build_lambda_for_transfer_to_originated ~destination ~entrypoint ~parameter_type ~parameter ~amount >|? left ~loc) | Lambda code -> ok Tezos_micheline.Micheline.(left ~loc (root code)) | Change_delegate delegate -> lambda_from_string @@ Managed_contract.build_lambda_for_set_delegate ~delegate >|? left ~loc | Change_keys (threshold, keys) -> let optimized_keys = seq ~loc (List.map (optimized_key ~loc) keys) in let expr = right ~loc (pair ~loc (int ~loc threshold) optimized_keys) in ok expr let action_to_expr_legacy ~loc = function | Transfer {amount; destination; entrypoint; parameter_type; parameter} -> if parameter <> Tezos_micheline.Micheline.strip_locations (unit ~loc:()) then error @@ Unsupported_feature_generic_call parameter else if parameter_type <> Tezos_micheline.Micheline.strip_locations (unit_t ~loc:()) then error @@ Unsupported_feature_generic_call_ty parameter_type else ok @@ left ~loc (pair ~loc (mutez ~loc amount) (optimized_address ~loc ~address:destination ~entrypoint)) | Lambda _ -> error @@ Unsupported_feature_lambda "" | Change_delegate delegate -> let delegate_opt = match delegate with | None -> none ~loc () | Some delegate -> some ~loc (optimized_key_hash ~loc delegate) in ok @@ right ~loc (left ~loc delegate_opt) | Change_keys (threshold, keys) -> let optimized_keys = seq ~loc (List.map (optimized_key ~loc) keys) in let expr = right ~loc (pair ~loc (int ~loc threshold) optimized_keys) in ok (right ~loc expr) let action_to_expr ~loc ~generic action = if generic then action_to_expr_generic ~loc action else action_to_expr_legacy ~loc action let action_of_expr_generic e = let fail () = fail (Action_deserialisation_error (Tezos_micheline.Micheline.strip_locations e)) in match e with | Tezos_micheline.Micheline.Prim (_, Script.D_Left, [lam], []) -> return @@ Lambda (Tezos_micheline.Micheline.strip_locations lam) | Tezos_micheline.Micheline.Prim ( _, Script.D_Right, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Int (_, threshold); Tezos_micheline.Micheline.Seq (_, key_bytes); ], [] ); ], [] ) -> List.map_es (function | Tezos_micheline.Micheline.Bytes (_, s) -> return @@ Data_encoding.Binary.of_bytes_exn Signature.Public_key.encoding s | _ -> fail ()) key_bytes >>=? fun keys -> return @@ Change_keys (threshold, keys) | _ -> fail () let action_of_expr_not_generic e = let fail () = fail (Action_deserialisation_error (Tezos_micheline.Micheline.strip_locations e)) in match e with | Tezos_micheline.Micheline.Prim ( _, Script.D_Left, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Int (_, i); Tezos_micheline.Micheline.Bytes (_, s); ], [] ); ], [] ) -> ( match Tez.of_mutez (Z.to_int64 i) with | None -> fail () | Some amount -> return @@ Transfer { amount; destination = Data_encoding.Binary.of_bytes_exn Contract.encoding s; entrypoint = "default"; parameter_type = Tezos_micheline.Micheline.strip_locations @@ unit_t ~loc:(); parameter = Tezos_micheline.Micheline.strip_locations @@ unit ~loc:(); }) | Tezos_micheline.Micheline.Prim ( _, Script.D_Right, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Left, [Tezos_micheline.Micheline.Prim (_, Script.D_None, [], [])], [] ); ], [] ) -> return @@ Change_delegate None | Tezos_micheline.Micheline.Prim ( _, Script.D_Right, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Left, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Some, [Tezos_micheline.Micheline.Bytes (_, s)], [] ); ], [] ); ], [] ) -> return @@ Change_delegate (Some (Data_encoding.Binary.of_bytes_exn Signature.Public_key_hash.encoding s)) | Tezos_micheline.Micheline.Prim ( _, Script.D_Right, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Right, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Int (_, threshold); Tezos_micheline.Micheline.Seq (_, key_bytes); ], [] ); ], [] ); ], [] ) -> List.map_es (function | Tezos_micheline.Micheline.Bytes (_, s) -> return @@ Data_encoding.Binary.of_bytes_exn Signature.Public_key.encoding s | _ -> fail ()) key_bytes >>=? fun keys -> return @@ Change_keys (threshold, keys) | _ -> fail () let action_of_expr ~generic = if generic then action_of_expr_generic else action_of_expr_not_generic type key_list = Signature.Public_key.t list (* The relevant information that we can get about a multisig smart contract *) type multisig_contract_information = { counter : Z.t; threshold : Z.t; keys : key_list; } let multisig_get_information (cctxt : #Protocol_client_context.full) ~chain ~block contract = let open Client_proto_context in let open Tezos_micheline.Micheline in get_storage cctxt ~chain ~block ~unparsing_mode:Readable contract >>=? fun storage_opt -> match storage_opt with | None -> fail (Contract_has_no_storage contract) | Some storage -> ( match root storage with | Prim ( _, D_Pair, [Int (_, counter); Int (_, threshold); Seq (_, key_nodes)], _ ) -> List.map_es (function | String (_, key_str) -> return @@ Signature.Public_key.of_b58check_exn key_str | _ -> fail (Contract_has_unexpected_storage contract)) key_nodes >>=? fun keys -> return {counter; threshold; keys} | _ -> fail (Contract_has_unexpected_storage contract)) let multisig_create_storage ~counter ~threshold ~keys () : Script.expr tzresult Lwt.t = let loc = Tezos_micheline.Micheline_parser.location_zero in let open Tezos_micheline.Micheline in List.map_es (fun key -> let key_str = Signature.Public_key.to_b58check key in return (String (loc, key_str))) keys >>=? fun l -> return @@ strip_locations @@ pair ~loc (int ~loc counter) (pair ~loc (int ~loc threshold) (seq ~loc l)) (* Client_proto_context.originate expects the initial storage as a string *) let multisig_storage_string ~counter ~threshold ~keys () = multisig_create_storage ~counter ~threshold ~keys () >>=? fun expr -> return @@ Format.asprintf "%a" Michelson_v1_printer.print_expr expr let multisig_create_param ~counter ~generic ~action ~optional_signatures () : Script.expr tzresult Lwt.t = let loc = 0 in let open Tezos_micheline.Micheline in List.map_es (fun sig_opt -> match sig_opt with | None -> return @@ none ~loc () | Some signature -> return @@ some ~loc (String (loc, Signature.to_b58check signature))) optional_signatures >>=? fun l -> Lwt.return @@ action_to_expr ~loc ~generic action >>=? fun expr -> return @@ strip_locations @@ pair ~loc (pair ~loc (int ~loc counter) expr) (Seq (loc, l)) let multisig_param_string ~counter ~action ~optional_signatures ~generic () = multisig_create_param ~counter ~action ~optional_signatures ~generic () >>=? fun expr -> return @@ Format.asprintf "%a" Michelson_v1_printer.print_expr expr let get_contract_address_maybe_chain_id ~descr ~loc ~chain_id contract = let address = bytes ~loc (Data_encoding.Binary.to_bytes_exn Contract.encoding contract) in if descr.requires_chain_id then let chain_id_bytes = bytes ~loc (Data_encoding.Binary.to_bytes_exn Chain_id.encoding chain_id) in pair ~loc chain_id_bytes address else address let multisig_bytes ~counter ~action ~contract ~chain_id ~descr () = let loc = 0 in Lwt.return @@ action_to_expr ~loc ~generic:descr.generic action >>=? fun expr -> let triple = pair ~loc (get_contract_address_maybe_chain_id ~descr ~loc ~chain_id contract) (pair ~loc (int ~loc counter) expr) in let bytes = Data_encoding.Binary.to_bytes_exn Script.expr_encoding @@ Tezos_micheline.Micheline.strip_locations @@ triple in return @@ Bytes.cat (Bytes.of_string "\005") bytes let check_threshold ~threshold ~keys () = let threshold = Z.to_int threshold in if Compare.List_length_with.(keys < threshold) then fail (Threshold_too_high (threshold, List.length keys)) else if Compare.Int.(threshold <= 0) then fail (Non_positive_threshold threshold) else return_unit let originate_multisig (cctxt : #Protocol_client_context.full) ~chain ~block ?confirmations ?dry_run ?branch ?fee ?gas_limit ?storage_limit ?verbose_signing ~delegate ~threshold ~keys ~balance ~source ~src_pk ~src_sk ~fee_parameter () = multisig_storage_string ~counter:Z.zero ~threshold ~keys () >>=? fun initial_storage -> check_threshold ~threshold ~keys () >>=? fun () -> Client_proto_context.originate_contract cctxt ~chain ~block ?branch ?confirmations ?dry_run ?fee ?gas_limit ?storage_limit ?verbose_signing ~delegate ~initial_storage ~balance ~source ~src_pk ~src_sk ~code:multisig_script ~fee_parameter () type multisig_prepared_action = { bytes : Bytes.t; threshold : Z.t; keys : public_key list; counter : Z.t; entrypoint : string option; generic : bool; } let check_parameter_type (cctxt : #Protocol_client_context.full) ?gas ?legacy ~destination ~entrypoint ~parameter_type ~parameter () = trace (Ill_typed_argument (destination, entrypoint, parameter_type, parameter)) @@ Plugin.RPC.Scripts.typecheck_data cctxt (cctxt#chain, cctxt#block) ~data:parameter ~ty:parameter_type ?gas ?legacy >>=? fun _ -> return_unit let check_action (cctxt : #Protocol_client_context.full) ~action ~balance ?gas ?legacy () = match action with | Change_keys (threshold, keys) -> check_threshold ~threshold ~keys () >>=? fun () -> return_unit | Transfer {amount; destination; entrypoint; parameter_type; parameter} -> check_parameter_type cctxt ~destination ~entrypoint ~parameter_type ~parameter () >>=? fun () -> if Tez.(amount > balance) then (* This is warning only because the contract can be filled before sending the signatures or even in the same transaction *) Format.eprintf "Transferred amount is bigger than current multisig balance" ; return_unit | Lambda code -> let action_t = Tezos_micheline.Micheline.strip_locations (lambda_action_t ~loc:()) in trace (Ill_typed_lambda (code, action_t)) @@ Plugin.RPC.Scripts.typecheck_data cctxt (cctxt#chain, cctxt#block) ~data:code ~ty:action_t ?gas ?legacy >>=? fun _remaining_gas -> return_unit | _ -> return_unit let prepare_multisig_transaction (cctxt : #Protocol_client_context.full) ~chain ~block ~multisig_contract ~action () = let contract = multisig_contract in check_multisig_contract cctxt ~chain ~block contract >>=? fun descr -> multisig_get_information cctxt ~chain ~block contract >>=? fun {counter; threshold; keys} -> Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> multisig_bytes ~counter ~action ~contract ~descr ~chain_id () >>=? fun bytes -> Client_proto_context.get_balance cctxt ~chain:cctxt#chain ~block:cctxt#block contract >>=? fun balance -> check_action cctxt ~action ~balance () >>=? fun () -> return { bytes; threshold; keys; counter; entrypoint = descr.main_entrypoint; generic = descr.generic; } let check_multisig_signatures ~bytes ~threshold ~keys signatures = let key_array = Array.of_list keys in let nkeys = Array.length key_array in let opt_sigs_arr = Array.make nkeys None in let matching_key_found = ref false in let check_signature_against_key_number signature i key = if Signature.check key signature bytes then ( matching_key_found := true ; opt_sigs_arr.(i) <- Some signature) in List.iter_ep (fun signature -> matching_key_found := false ; List.iteri (check_signature_against_key_number signature) keys ; fail_unless !matching_key_found (Invalid_signature signature)) signatures >>=? fun () -> let opt_sigs = Array.to_list opt_sigs_arr in let signature_count = List.fold_left (fun n sig_opt -> match sig_opt with Some _ -> n + 1 | None -> n) 0 opt_sigs in let threshold_int = Z.to_int threshold in if signature_count >= threshold_int then return opt_sigs else fail (Not_enough_signatures (threshold_int, signature_count)) let call_multisig (cctxt : #Protocol_client_context.full) ~chain ~block ?confirmations ?dry_run ?verbose_signing ?branch ~source ~src_pk ~src_sk ~multisig_contract ~action ~signatures ~amount ?fee ?gas_limit ?storage_limit ?counter ~fee_parameter () = prepare_multisig_transaction cctxt ~chain ~block ~multisig_contract ~action () >>=? fun { bytes; threshold; keys; counter = stored_counter; entrypoint; generic; } -> check_multisig_signatures ~bytes ~threshold ~keys signatures >>=? fun optional_signatures -> multisig_param_string ~counter:stored_counter ~action ~optional_signatures ~generic () >>=? fun arg -> Client_proto_context.transfer cctxt ~chain ~block ?confirmations ?dry_run ?branch ~source ~src_pk ~src_sk ~destination:multisig_contract ?entrypoint ~arg ~amount ?fee ?gas_limit ?storage_limit ?counter ~fee_parameter ?verbose_signing () let action_of_bytes ~multisig_contract ~stored_counter ~descr ~chain_id bytes = if Compare.Int.(Bytes.length bytes >= 1) && Compare.Int.(TzEndian.get_uint8 bytes 0 = 0x05) then let nbytes = Bytes.sub bytes 1 (Bytes.length bytes - 1) in match Data_encoding.Binary.of_bytes_opt Script.expr_encoding nbytes with | None -> fail (Bytes_deserialisation_error bytes) | Some e -> ( match Tezos_micheline.Micheline.root e with | Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Bytes (_, contract_bytes); Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [Tezos_micheline.Micheline.Int (_, counter); e], [] ); ], [] ) when not descr.requires_chain_id -> let contract = Data_encoding.Binary.of_bytes_exn Contract.encoding contract_bytes in if counter = stored_counter then if Contract.(multisig_contract = contract) then action_of_expr ~generic:descr.generic e else fail (Bad_deserialized_contract (contract, multisig_contract)) else fail (Bad_deserialized_counter (counter, stored_counter)) | Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [ Tezos_micheline.Micheline.Bytes (_, chain_id_bytes); Tezos_micheline.Micheline.Bytes (_, contract_bytes); ], [] ); Tezos_micheline.Micheline.Prim ( _, Script.D_Pair, [Tezos_micheline.Micheline.Int (_, counter); e], [] ); ], [] ) when descr.requires_chain_id -> let contract = Data_encoding.Binary.of_bytes_exn Contract.encoding contract_bytes in let cid = Data_encoding.Binary.of_bytes_exn Chain_id.encoding chain_id_bytes in if counter = stored_counter then if multisig_contract = contract && chain_id = cid then action_of_expr ~generic:descr.generic e else fail (Bad_deserialized_contract (contract, multisig_contract)) else fail (Bad_deserialized_counter (counter, stored_counter)) | _ -> fail (Bytes_deserialisation_error bytes)) else fail (Bytes_deserialisation_error bytes) let call_multisig_on_bytes (cctxt : #Protocol_client_context.full) ~chain ~block ?confirmations ?dry_run ?verbose_signing ?branch ~source ~src_pk ~src_sk ~multisig_contract ~bytes ~signatures ~amount ?fee ?gas_limit ?storage_limit ?counter ~fee_parameter () = multisig_get_information cctxt ~chain ~block multisig_contract >>=? fun info -> check_multisig_contract cctxt ~chain ~block multisig_contract >>=? fun descr -> Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> action_of_bytes ~multisig_contract ~stored_counter:info.counter ~chain_id ~descr bytes >>=? fun action -> call_multisig cctxt ~chain ~block ?confirmations ?dry_run ?branch ~source ~src_pk ~src_sk ~multisig_contract ~action ~signatures ~amount ?fee ?gas_limit ?storage_limit ?counter ~fee_parameter ?verbose_signing ()
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2019-2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(library (name quad) (modules quad) (foreign_stubs (language cxx) (names baz))) (executable (name main) (libraries quad) (foreign_stubs (language cxx) (names bazexe)) (modules main))
main.mli
val argspec : (Arg.key * Arg.spec * Arg.doc) list;; val parse_command_line : (Arg.key * Arg.spec * Arg.doc) list -> unit;; val do_main : unit -> unit;;
(* Copyright 2000 INRIA *)
numbers.mli
(** Modules about numbers, some of which satisfy {!Identifiable.S}. {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) module Int : sig include Identifiable.S with type t = int (** [zero_to_n n] is the set of numbers \{0, ..., n\} (inclusive). *) val zero_to_n : int -> Set.t val to_string : int -> string end module Int8 : sig type t val zero : t val one : t val of_int_exn : int -> t val to_int : t -> int end module Int16 : sig type t val of_int_exn : int -> t val of_int64_exn : Int64.t -> t val to_int : t -> int end module Float : Identifiable.S with type t = float
(**************************************************************************) (* *) (* OCaml *) (* *) (* Pierre Chambart, OCamlPro *) (* Mark Shinwell and Leo White, Jane Street Europe *) (* *) (* Copyright 2013--2016 OCamlPro SAS *) (* Copyright 2014--2016 Jane Street Group LLC *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
stb_truetype.h
// stb_truetype.h - v1.26 - public domain // authored from 2009-2021 by Sean Barrett / RAD Game Tools // // ======================================================================= // // NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES // // This library does no range checking of the offsets found in the file, // meaning an attacker can use it to read arbitrary memory. // // ======================================================================= // // This library processes TrueType files: // parse files // extract glyph metrics // extract glyph shapes // render glyphs to one-channel bitmaps with antialiasing (box filter) // render glyphs to one-channel SDF bitmaps (signed-distance field/function) // // Todo: // non-MS cmaps // crashproof on bad data // hinting? (no longer patented) // cleartype-style AA? // optimize: use simple memory allocator for intermediates // optimize: build edge-list directly from curves // optimize: rasterize directly from curves? // // ADDITIONAL CONTRIBUTORS // // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // Dougall Johnson: OpenType / Type 2 font handling // Daniel Ribeiro Maciel: basic GPOS-based kerning // // Misc other: // Ryan Gordon // Simon Glass // github:IntellectualKitty // Imanol Celaya // Daniel Ribeiro Maciel // // Bug/warning reports/fixes: // "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe // Cass Everitt Martins Mozeiko github:aloucks // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam // Brian Hook Omar Cornut github:vassvik // Walter van Niftrik Ryan Griege // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor // Anthony Pesch Higor Euripedes // Johan Duparc Thomas Fields // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. Brian Costabile // Ken Voskuil (kaesve) // // VERSION HISTORY // // 1.26 (2021-08-28) fix broken rasterizer // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning // 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) // 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined // 1.21 (2019-02-25) fix warning // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // variant PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer // // Full history can be found at the end of this file. // // LICENSE // // See end of file for license information. // // USAGE // // Include this file in whatever places need to refer to it. In ONE C/C++ // file, write: // #define STB_TRUETYPE_IMPLEMENTATION // before the #include of this file. This expands out the actual // implementation into that C/C++ file. // // To make the implementation private to the file that generates the implementation, // #define STBTT_STATIC // // Simple 3D API (don't ship this, but it's fine for tools and quick start) // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture // stbtt_GetBakedQuad() -- compute quad to draw for a given char // // Improved 3D API (more shippable): // #include "stb_rect_pack.h" -- optional, but you really want it // stbtt_PackBegin() // stbtt_PackSetOversampling() -- for improved quality on small fonts // stbtt_PackFontRanges() -- pack and renders // stbtt_PackEnd() // stbtt_GetPackedQuad() // // "Load" a font file from a memory buffer (you have to keep the buffer loaded) // stbtt_InitFont() // stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections // stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections // // Render a unicode codepoint to a bitmap // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be // // Character advance/positioning // stbtt_GetCodepointHMetrics() // stbtt_GetFontVMetrics() // stbtt_GetFontVMetricsOS2() // stbtt_GetCodepointKernAdvance() // // Starting with version 1.06, the rasterizer was replaced with a new, // faster and generally-more-precise rasterizer. The new rasterizer more // accurately measures pixel coverage for anti-aliasing, except in the case // where multiple shapes overlap, in which case it overestimates the AA pixel // coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If // this turns out to be a problem, you can re-enable the old rasterizer with // #define STBTT_RASTERIZER_VERSION 1 // which will incur about a 15% speed hit. // // ADDITIONAL DOCUMENTATION // // Immediately after this block comment are a series of sample programs. // // After the sample programs is the "header file" section. This section // includes documentation for each API function. // // Some important concepts to understand to use this library: // // Codepoint // Characters are defined by unicode codepoints, e.g. 65 is // uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is // the hiragana for "ma". // // Glyph // A visual character shape (every codepoint is rendered as // some glyph) // // Glyph index // A font-specific integer ID representing a glyph // // Baseline // Glyph shapes are defined relative to a baseline, which is the // bottom of uppercase characters. Characters extend both above // and below the baseline. // // Current Point // As you draw text to the screen, you keep track of a "current point" // which is the origin of each character. The current point's vertical // position is the baseline. Even "baked fonts" use this model. // // Vertical Font Metrics // The vertical qualities of the font, used to vertically position // and space the characters. See docs for stbtt_GetFontVMetrics. // // Font Size in Pixels or Points // The preferred interface for specifying font sizes in stb_truetype // is to specify how tall the font's vertical extent should be in pixels. // If that sounds good enough, skip the next paragraph. // // Most font APIs instead use "points", which are a common typographic // measurement for describing font size, defined as 72 points per inch. // stb_truetype provides a point API for compatibility. However, true // "per inch" conventions don't make much sense on computer displays // since different monitors have different number of pixels per // inch. For example, Windows traditionally uses a convention that // there are 96 pixels per inch, thus making 'inch' measurements have // nothing to do with inches, and thus effectively defining a point to // be 1.333 pixels. Additionally, the TrueType font data provides // an explicit scale factor to scale a given font's glyphs to points, // but the author has observed that this scale factor is often wrong // for non-commercial fonts, thus making fonts scaled in points // according to the TrueType spec incoherently sized in practice. // // DETAILED USAGE: // // Scale: // Select how high you want the font to be, in points or pixels. // Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute // a scale factor SF that will be used by all other functions. // // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative // bounding box for all characters. SF*-y0 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the // screen where y=0, then you would set the baseline to SF*-y0. // // Current point: // Set the current point where the first character will appear. The // first character could extend left of the current point; this is font // dependent. You can either choose a current point that is the leftmost // point and hope, or add some padding, or check the bounding box or // left-side-bearing of the first character to be displayed and set // the current point based on that. // // Displaying a character: // Compute the bounding box of the character. It will contain signed values // relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1, // then the character should be displayed in the rectangle from // <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1). // // Advancing for the next character: // Call GlyphHMetrics, and compute 'current_point += SF * advance'. // // // ADVANCED USAGE // // Quality: // // - Use the functions with Subpixel at the end to allow your characters // to have subpixel positioning. Since the font is anti-aliased, not // hinted, this is very import for quality. (This is not possible with // baked fonts.) // // - Kerning is now supported, and if you're supporting subpixel rendering // then kerning is worth using to give your text a polished look. // // Performance: // // - Convert Unicode codepoints to glyph indexes and operate on the glyphs; // if you don't do this, stb_truetype is forced to do the conversion on // every call. // // - There are a lot of memory allocations. We should modify it to take // a temp buffer and allocate from the temp buffer (without freeing), // should help performance a lot. // // NOTES // // The system uses the raw data found in the .ttf file without changing it // and without building auxiliary data structures. This is a bit inefficient // on little-endian systems (the data is big-endian), but assuming you're // caching the bitmaps or glyph shapes this shouldn't be a big deal. // // It appears to be very hard to programmatically determine what font a // given file is in a general way. I provide an API for this, but I don't // recommend it. // // // PERFORMANCE MEASUREMENTS FOR 1.06: // // 32-bit 64-bit // Previous release: 8.83 s 7.68 s // Pool allocations: 7.72 s 6.34 s // Inline sort : 6.54 s 5.65 s // New rasterizer : 5.63 s 5.00 s ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// SAMPLE PROGRAMS //// // // Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless. // See "tests/truetype_demo_win32.c" for a complete version. #if 0 #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" unsigned char ttf_buffer[1<<20]; unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs GLuint ftex; void my_stbtt_initfont(void) { fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); // can free temp_bitmap at this point glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void my_stbtt_print(float x, float y, char *text) { // assume orthographic projection with units = screen pixels, origin at top left glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { if (*text >= 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } #endif // // ////////////////////////////////////////////////////////////////////////////// // // Complete program (this compiles): get a single bitmap, print as ASCII art // #if 0 #include <stdio.h> #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" char ttf_buffer[1<<25]; int main(int argc, char **argv) { stbtt_fontinfo font; unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); putchar('\n'); } return 0; } #endif // // Output: // // .ii. // @@@@@@. // V@Mio@@o // :i. V@V // :oM@@M // :@@@MM@M // @@o o@M // :@@. M@M // @@@o@@@@ // :M@@V:@@. // ////////////////////////////////////////////////////////////////////////////// // // Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; unsigned char screen[20][79]; int main(int arg, char **argv) { stbtt_fontinfo font; int i,j,ascent,baseline,ch=0; float scale, xpos=2; // leave a little padding in case the character extends left char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); scale = stbtt_ScaleForPixelHeight(&font, 15); stbtt_GetFontVMetrics(&font, &ascent,0,0); baseline = (int) (ascent*scale); while (text[ch]) { int advance,lsb,x0,y0,x1,y1; float x_shift = xpos - (float) floor(xpos); stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong // because this API is really for baking character bitmaps into textures. if you want to render // a sequence of characters, you really need to render each bitmap to a temp buffer, then // "alpha blend" that into the working buffer xpos += (advance * scale); if (text[ch+1]) xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); ++ch; } for (j=0; j < 20; ++j) { for (i=0; i < 78; ++i) putchar(" .:ioVM@"[screen[j][i]>>5]); putchar('\n'); } return 0; } #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //// //// INTEGRATION WITH YOUR CODEBASE //// //// The following sections allow you to supply alternate definitions //// of C library functions used by stb_truetype, e.g. if you don't //// link with the C runtime library. #ifdef STB_TRUETYPE_IMPLEMENTATION // #define your own (u)stbtt_int8/16/32 before including to override this #ifndef stbtt_uint8 typedef unsigned char stbtt_uint8; typedef signed char stbtt_int8; typedef unsigned short stbtt_uint16; typedef signed short stbtt_int16; typedef unsigned int stbtt_uint32; typedef signed int stbtt_int32; #endif typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include <math.h> #define STBTT_ifloor(x) ((int) floor(x)) #define STBTT_iceil(x) ((int) ceil(x)) #endif #ifndef STBTT_sqrt #include <math.h> #define STBTT_sqrt(x) sqrt(x) #define STBTT_pow(x,y) pow(x,y) #endif #ifndef STBTT_fmod #include <math.h> #define STBTT_fmod(x,y) fmod(x,y) #endif #ifndef STBTT_cos #include <math.h> #define STBTT_cos(x) cos(x) #define STBTT_acos(x) acos(x) #endif #ifndef STBTT_fabs #include <math.h> #define STBTT_fabs(x) fabs(x) #endif // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include <stdlib.h> #define STBTT_malloc(x,u) ((void)(u),malloc(x)) #define STBTT_free(x,u) ((void)(u),free(x)) #endif #ifndef STBTT_assert #include <assert.h> #define STBTT_assert(x) assert(x) #endif #ifndef STBTT_strlen #include <string.h> #define STBTT_strlen(x) strlen(x) #endif #ifndef STBTT_memcpy #include <string.h> #define STBTT_memcpy memcpy #define STBTT_memset memset #endif #endif /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// INTERFACE //// //// #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ #define __STB_INCLUDE_STB_TRUETYPE_H__ #ifdef STBTT_STATIC #define STBTT_DEF static #else #define STBTT_DEF extern #endif #ifdef __cplusplus extern "C" { #endif // private structure typedef struct { unsigned char *data; int cursor; int size; } stbtt__buf; ////////////////////////////////////////////////////////////////////////////// // // TEXTURE BAKING API // // If you use this API, you only have to call two functions ever. // typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; } stbtt_bakedchar; STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata); // you allocate this, it's num_chars long // if return is positive, the first unused row of the bitmap // if return is negative, returns the negative of the number of characters that fit // if return is 0, no characters fit and no rows were used // This uses a very crappy packing. typedef struct { float x0,y0,s0,t0; // top-left float x1,y1,s1,t1; // bottom-right } stbtt_aligned_quad; STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier // Call GetBakedQuad with char_index = 'character - first_char', and it // creates the quad you need to draw and advances the current position. // // The coordinate system used assumes y increases downwards. // // Characters will extend both above and below the current position; // see discussion of "BASELINE" above. // // It's inefficient; you might want to c&p it and optimize it. STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); // Query the font vertical metrics without having to create a font first. ////////////////////////////////////////////////////////////////////////////// // // NEW TEXTURE BAKING API // // This provides options for packing multiple fonts into one atlas, not // perfectly but better than nothing. typedef struct { unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap float xoff,yoff,xadvance; float xoff2,yoff2; } stbtt_packedchar; typedef struct stbtt_pack_context stbtt_pack_context; typedef struct stbtt_fontinfo stbtt_fontinfo; #ifndef STB_RECT_PACK_VERSION typedef struct stbrp_rect stbrp_rect; #endif STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); // Initializes a packing context stored in the passed-in stbtt_pack_context. // Future calls using this context will pack characters into the bitmap passed // in here: a 1-channel bitmap that is width * height. stride_in_bytes is // the distance from one row to the next (or 0 to mean they are packed tightly // together). "padding" is the amount of padding to leave between each // character (normally you want '1' for bitmaps you'll use as textures with // bilinear filtering). // // Returns 0 on failure, 1 on success. STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); // Cleans up the packing context and frees all memory. #define STBTT_POINT_SIZE(x) (-(x)) STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); // Creates character bitmaps from the font_index'th font found in fontdata (use // font_index=0 if you don't know what that is). It creates num_chars_in_range // bitmaps for characters with unicode values starting at first_unicode_char_in_range // and increasing. Data for how to render them is stored in chardata_for_range; // pass these to stbtt_GetPackedQuad to get back renderable quads. // // font_size is the full height of the character from ascender to descender, // as computed by stbtt_ScaleForPixelHeight. To use a point size as computed // by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() // and pass that result as 'font_size': // ..., 20 , ... // font max minus min y is 20 pixels tall // ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall typedef struct { float font_size; int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints int num_chars; stbtt_packedchar *chardata_for_range; // output unsigned char h_oversample, v_oversample; // don't set these, they're used internally } stbtt_pack_range; STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); // Creates character bitmaps from multiple ranges of characters stored in // ranges. This will usually create a better-packed bitmap than multiple // calls to stbtt_PackFontRange. Note that you can call this multiple // times within a single PackBegin/PackEnd. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); // Oversampling a font increases the quality by allowing higher-quality subpixel // positioning, and is especially valuable at smaller text sizes. // // This function sets the amount of oversampling for all following calls to // stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given // pack context. The default (no oversampling) is achieved by h_oversample=1 // and v_oversample=1. The total number of pixels required is // h_oversample*v_oversample larger than the default; for example, 2x2 // oversampling requires 4x the storage of 1x1. For best results, render // oversampled textures with bilinear filtering. Look at the readme in // stb/tests/oversample for information about oversampled fonts // // To use with PackFontRangesGather etc., you must set it before calls // call to PackFontRangesGatherRects. STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); // If skip != 0, this tells stb_truetype to skip any codepoints for which // there is no corresponding glyph. If skip=0, which is the default, then // codepoints without a glyph recived the font's "missing character" glyph, // typically an empty box by convention. STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); // Calling these functions in sequence is roughly equivalent to calling // stbtt_PackFontRanges(). If you more control over the packing of multiple // fonts, or if you want to pack custom data into a font texture, take a look // at the source to of stbtt_PackFontRanges() and create a custom version // using these functions, e.g. call GatherRects multiple times, // building up a single array of rects, then call PackRects once, // then call RenderIntoRects repeatedly. This may result in a // better packing than calling PackFontRanges multiple times // (or it may not). // this is an opaque structure that you shouldn't mess with which holds // all the context needed from PackBegin to PackEnd. struct stbtt_pack_context { void *user_allocator_context; void *pack_info; int width; int height; int stride_in_bytes; int padding; int skip_missing; unsigned int h_oversample, v_oversample; unsigned char *pixels; void *nodes; }; ////////////////////////////////////////////////////////////////////////////// // // FONT LOADING // // STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); // This function will determine the number of fonts in a font file. TrueType // collection (.ttc) files may contain multiple fonts, while TrueType font // (.ttf) files only contain one font. The number of fonts can be used for // indexing with the previous function where the index is between zero and one // less than the total fonts. If an error occurs, -1 is returned. STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // Each .ttf/.ttc file may have more than one font. Each font has a sequential // index number starting from 0. Call this function to get the font offset for // a given index; it returns -1 if the index is out of range. A regular .ttf // file will only define one font and it always be at offset 0, so it will // return '0' for index 0, and -1 for all other indices. // The following structure is defined publicly so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file int fontstart; // offset of start of font int numGlyphs; // number of glyphs, needed for range checking int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph stbtt__buf cff; // cff font data stbtt__buf charstrings; // the charstring index stbtt__buf gsubrs; // global charstring subroutines index stbtt__buf subrs; // private charstring subroutines index stbtt__buf fontdicts; // array of font dicts stbtt__buf fdselect; // map from glyph to fontdict }; STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds // the necessary cached info for the rest of the system. You must allocate // the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't // need to do anything special to free it, because the contents are pure // value data with no additional data structures. Returns 0 on failure. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER TO GLYPH-INDEX CONVERSIOn STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character // and you want a speed-up, call this function with the character you're // going to process, then use glyph-based functions instead of the // codepoint-based functions. // Returns 0 if the character codepoint is not defined in the font. ////////////////////////////////////////////////////////////////////////////// // // CHARACTER PROPERTIES // STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose "height" is 'pixels' tall. // Height is measured as the distance from the highest ascender to the lowest // descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics // and computing: // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but // I'm not positive. STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); // ascent is the coordinate above the baseline the font extends; descent // is the coordinate below the baseline the font extends (i.e. it is typically negative) // lineGap is the spacing between one row's descent and the next row's ascent... // so you should advance the vertical position by "*ascent - *descent + *lineGap" // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). // // Returns 1 on success (table present), 0 on failure. STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position // these are expressed in unscaled coordinates STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); // an additional amount to add to the 'advance' value between ch1 and ch2 STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency typedef struct stbtt_kerningentry { int glyph1; // use stbtt_FindGlyphIndex int glyph2; int advance; } stbtt_kerningentry; STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); // Retrieves a complete list of all of the kerning pairs provided by the font // stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. // The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) ////////////////////////////////////////////////////////////////////////////// // // GLYPH SHAPES (you probably don't need these, but they have to go before // the bitmaps for C declaration-order reasons) // #ifndef STBTT_vmove // you can predefine these to use different values (but why?) enum { STBTT_vmove=1, STBTT_vline, STBTT_vcurve, STBTT_vcubic }; #endif #ifndef stbtt_vertex // you can predefine this to use different values // (we share this with other code at RAD) #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file typedef struct { stbtt_vertex_type x,y,cx,cy,cx1,cy1; unsigned char type,padding; } stbtt_vertex; #endif STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); // returns non-zero if nothing is drawn for this glyph STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); // returns # of vertices and fills *vertices with the pointer to them // these are expressed in "unscaled" coordinates // // The shape is a series of contours. Each one starts with // a STBTT_moveto, then consists of a series of mixed // STBTT_lineto and STBTT_curveto segments. A lineto // draws a line from previous endpoint to its x,y; a curveto // draws a quadratic bezier from previous endpoint to // its x,y, using cx,cy as the bezier control point. STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); // frees the data allocated above STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); // fills svg with the character's SVG data. // returns data size or 0 if SVG not found. ////////////////////////////////////////////////////////////////////////////// // // BITMAP RENDERING // STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); // frees the bitmap allocated below STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // allocates a large-enough single-channel 8bpp bitmap and renders the // specified character/glyph at the specified scale into it, with // antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). // *width & *height are filled out with the width & height of the bitmap, // which is stored left-to-right, top-to-bottom. // // xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); // the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); // the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap // in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap // is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the // width and height and positioning info for it first. STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); // same as stbtt_MakeCodepointBitmap, but you can specify a subpixel // shift for the character STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); // same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering // is performed (see stbtt_PackSetOversampling) STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); // get the bbox of the bitmap centered around the glyph origin; so the // bitmap width is ix1-ix0, height is iy1-iy0, and location to place // the bitmap top left is (leftSideBearing*scale,iy0). // (Note that the bitmap uses y-increases-down, but the shape uses // y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel // shift for the character // the following functions are equivalent to the above functions, but operate // on glyph indices instead of Unicode codepoints (for efficiency) STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); // @TODO: don't expose this structure typedef struct { int w,h,stride; unsigned char *pixels; } stbtt__bitmap; // rasterize a shape with quadratic beziers into a bitmap STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into float flatness_in_pixels, // allowable error of curve in pixels stbtt_vertex *vertices, // array of vertices defining shape int num_verts, // number of vertices in above array float scale_x, float scale_y, // scale applied to input vertices float shift_x, float shift_y, // translation applied to input vertices int x_off, int y_off, // another translation applied to input int invert, // if non-zero, vertically flip shape void *userdata); // context for to STBTT_MALLOC ////////////////////////////////////////////////////////////////////////////// // // Signed Distance Function (or Field) rendering STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); // frees the SDF bitmap allocated below STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); // These functions compute a discretized SDF field for a single character, suitable for storing // in a single-channel texture, sampling with bilinear filtering, and testing against // larger than some threshold to produce scalable fonts. // info -- the font // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap // glyph/codepoint -- the character to generate the SDF for // padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), // which allows effects like bit outlines // onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) // pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) // if positive, > onedge_value is inside; if negative, < onedge_value is inside // width,height -- output height & width of the SDF bitmap (including padding) // xoff,yoff -- output origin of the character // return value -- a 2D array of bytes 0..255, width*height in size // // pixel_dist_scale & onedge_value are a scale & bias that allows you to make // optimal use of the limited 0..255 for your application, trading off precision // and special effects. SDF values outside the range 0..255 are clamped to 0..255. // // Example: // scale = stbtt_ScaleForPixelHeight(22) // padding = 5 // onedge_value = 180 // pixel_dist_scale = 180/5.0 = 36.0 // // This will create an SDF bitmap in which the character is about 22 pixels // high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled // shape, sample the SDF at each pixel and fill the pixel if the SDF value // is greater than or equal to 180/255. (You'll actually want to antialias, // which is beyond the scope of this example.) Additionally, you can compute // offset outlines (e.g. to stroke the character border inside & outside, // or only outside). For example, to fill outside the character up to 3 SDF // pixels, you would compare against (180-36.0*3)/255 = 72/255. The above // choice of variables maps a range from 5 pixels outside the shape to // 2 pixels inside the shape to 0..255; this is intended primarily for apply // outside effects only (the interior range is needed to allow proper // antialiasing of the font at *smaller* sizes) // // The function computes the SDF analytically at each SDF pixel, not by e.g. // building a higher-res bitmap and approximating it. In theory the quality // should be as high as possible for an SDF of this size & representation, but // unclear if this is true in practice (perhaps building a higher-res bitmap // and computing from that can allow drop-out prevention). // // The algorithm has not been optimized at all, so expect it to be slow // if computing lots of characters or very large sizes. ////////////////////////////////////////////////////////////////////////////// // // Finding the right font... // // You should really just solve this offline, keep your own tables // of what font is what, and don't try to get it out of the .ttf file. // That's because getting it out of the .ttf file is really hard, because // the names in the file can appear in many possible encodings, in many // possible languages, and e.g. if you need a case-insensitive comparison, // the details of that depend on the encoding & language in a complex way // (actually underspecified in truetype, but also gigantic). // // But you can use the provided functions in two possible ways: // stbtt_FindMatchingFont() will use *case-sensitive* comparisons on // unicode-encoded names to try to find the font you want; // you can run this before calling stbtt_InitFont() // // stbtt_GetFontNameString() lets you get any of the various strings // from the file yourself and do your own comparisons on them. // You have to have called stbtt_InitFont() first. STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); // returns the offset (not index) of the font that matches, or -1 if none // if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". // if you use any other flag, use a font name like "Arial"; this checks // the 'macStyle' header field; i don't know if fonts set this consistently #define STBTT_MACSTYLE_DONTCARE 0 #define STBTT_MACSTYLE_BOLD 1 #define STBTT_MACSTYLE_ITALIC 2 #define STBTT_MACSTYLE_UNDERSCORE 4 #define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); // returns 1/0 whether the first string interpreted as utf8 is identical to // the second string interpreted as big-endian utf16... useful for strings from next func STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); // returns the string (which may be big-endian double byte, e.g. for unicode) // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: // http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, STBTT_PLATFORM_ID_ISO =2, STBTT_PLATFORM_ID_MICROSOFT =3 }; enum { // encodingID for STBTT_PLATFORM_ID_UNICODE STBTT_UNICODE_EID_UNICODE_1_0 =0, STBTT_UNICODE_EID_UNICODE_1_1 =1, STBTT_UNICODE_EID_ISO_10646 =2, STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 }; enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT STBTT_MS_EID_SYMBOL =0, STBTT_MS_EID_UNICODE_BMP =1, STBTT_MS_EID_SHIFTJIS =2, STBTT_MS_EID_UNICODE_FULL =10 }; enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 }; enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D }; enum { // languageID for STBTT_PLATFORM_ID_MAC STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 }; #ifdef __cplusplus } #endif #endif // __STB_INCLUDE_STB_TRUETYPE_H__ /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //// //// IMPLEMENTATION //// //// #ifdef STB_TRUETYPE_IMPLEMENTATION #ifndef STBTT_MAX_OVERSAMPLE #define STBTT_MAX_OVERSAMPLE 8 #endif #if STBTT_MAX_OVERSAMPLE > 255 #error "STBTT_MAX_OVERSAMPLE cannot be > 255" #endif typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; #ifndef STBTT_RASTERIZER_VERSION #define STBTT_RASTERIZER_VERSION 2 #endif #ifdef _MSC_VER #define STBTT__NOTUSED(v) (void)(v) #else #define STBTT__NOTUSED(v) (void)sizeof(v) #endif ////////////////////////////////////////////////////////////////////////// // // stbtt__buf helpers to parse data from file // static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor++]; } static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) { if (b->cursor >= b->size) return 0; return b->data[b->cursor]; } static void stbtt__buf_seek(stbtt__buf *b, int o) { STBTT_assert(!(o > b->size || o < 0)); b->cursor = (o > b->size || o < 0) ? b->size : o; } static void stbtt__buf_skip(stbtt__buf *b, int o) { stbtt__buf_seek(b, b->cursor + o); } static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) { stbtt_uint32 v = 0; int i; STBTT_assert(n >= 1 && n <= 4); for (i = 0; i < n; i++) v = (v << 8) | stbtt__buf_get8(b); return v; } static stbtt__buf stbtt__new_buf(const void *p, size_t size) { stbtt__buf r; STBTT_assert(size < 0x40000000); r.data = (stbtt_uint8*) p; r.size = (int) size; r.cursor = 0; return r; } #define stbtt__buf_get16(b) stbtt__buf_get((b), 2) #define stbtt__buf_get32(b) stbtt__buf_get((b), 4) static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) { stbtt__buf r = stbtt__new_buf(NULL, 0); if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; r.data = b->data + o; r.size = s; return r; } static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) { int count, start, offsize; start = b->cursor; count = stbtt__buf_get16(b); if (count) { offsize = stbtt__buf_get8(b); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(b, offsize * count); stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); } return stbtt__buf_range(b, start, b->cursor - start); } static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) { int b0 = stbtt__buf_get8(b); if (b0 >= 32 && b0 <= 246) return b0 - 139; else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; else if (b0 == 28) return stbtt__buf_get16(b); else if (b0 == 29) return stbtt__buf_get32(b); STBTT_assert(0); return 0; } static void stbtt__cff_skip_operand(stbtt__buf *b) { int v, b0 = stbtt__buf_peek8(b); STBTT_assert(b0 >= 28); if (b0 == 30) { stbtt__buf_skip(b, 1); while (b->cursor < b->size) { v = stbtt__buf_get8(b); if ((v & 0xF) == 0xF || (v >> 4) == 0xF) break; } } else { stbtt__cff_int(b); } } static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) { stbtt__buf_seek(b, 0); while (b->cursor < b->size) { int start = b->cursor, end, op; while (stbtt__buf_peek8(b) >= 28) stbtt__cff_skip_operand(b); end = b->cursor; op = stbtt__buf_get8(b); if (op == 12) op = stbtt__buf_get8(b) | 0x100; if (op == key) return stbtt__buf_range(b, start, end-start); } return stbtt__buf_range(b, 0, 0); } static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) { int i; stbtt__buf operands = stbtt__dict_get(b, key); for (i = 0; i < outcount && operands.cursor < operands.size; i++) out[i] = stbtt__cff_int(&operands); } static int stbtt__cff_index_count(stbtt__buf *b) { stbtt__buf_seek(b, 0); return stbtt__buf_get16(b); } static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) { int count, offsize, start, end; stbtt__buf_seek(&b, 0); count = stbtt__buf_get16(&b); offsize = stbtt__buf_get8(&b); STBTT_assert(i >= 0 && i < count); STBTT_assert(offsize >= 1 && offsize <= 4); stbtt__buf_skip(&b, i*offsize); start = stbtt__buf_get(&b, offsize); end = stbtt__buf_get(&b, offsize); return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); } ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file // // on platforms that don't allow misaligned reads, if we want to allow // truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE #define ttBYTE(p) (* (stbtt_uint8 *) (p)) #define ttCHAR(p) (* (stbtt_int8 *) (p)) #define ttFixed(p) ttLONG(p) static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } #define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) #define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) static int stbtt__isfont(stbtt_uint8 *font) { // check the version number if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts return 0; } // @OPTIMIZE: binary search static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) { stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); stbtt_uint32 tabledir = fontstart + 12; stbtt_int32 i; for (i=0; i < num_tables; ++i) { stbtt_uint32 loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } return 0; } static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) { // if it's just a font, there's only one valid index if (stbtt__isfont(font_collection)) return index == 0 ? 0 : -1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*4); } } return -1; } static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) { // if it's just a font, there's only one valid font if (stbtt__isfont(font_collection)) return 1; // check if it's a TTC if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { return ttLONG(font_collection+8); } } return 0; } static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) { stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; stbtt__buf pdict; stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); if (!subrsoff) return stbtt__new_buf(NULL, 0); stbtt__buf_seek(&cff, private_loc[1]+subrsoff); return stbtt__cff_get_index(&cff); } // since most people won't use this, find this table the first time it's needed static int stbtt__get_svg(stbtt_fontinfo *info) { stbtt_uint32 t; if (info->svg < 0) { t = stbtt__find_table(info->data, info->fontstart, "SVG "); if (t) { stbtt_uint32 offset = ttULONG(info->data + t + 2); info->svg = t + offset; } else { info->svg = 0; } } return info->svg; } static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; info->data = data; info->fontstart = fontstart; info->cff = stbtt__new_buf(NULL, 0); cmap = stbtt__find_table(data, fontstart, "cmap"); // required info->loca = stbtt__find_table(data, fontstart, "loca"); // required info->head = stbtt__find_table(data, fontstart, "head"); // required info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required if (!cmap || !info->head || !info->hhea || !info->hmtx) return 0; if (info->glyf) { // required for truetype if (!info->loca) return 0; } else { // initialization for CFF / Type2 fonts (OTF) stbtt__buf b, topdict, topdictidx; stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; stbtt_uint32 cff; cff = stbtt__find_table(data, fontstart, "CFF "); if (!cff) return 0; info->fontdicts = stbtt__new_buf(NULL, 0); info->fdselect = stbtt__new_buf(NULL, 0); // @TODO this should use size from table (not 512MB) info->cff = stbtt__new_buf(data+cff, 512*1024*1024); b = info->cff; // read the header stbtt__buf_skip(&b, 2); stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize // @TODO the name INDEX could list multiple fonts, // but we just use the first one. stbtt__cff_get_index(&b); // name INDEX topdictidx = stbtt__cff_get_index(&b); topdict = stbtt__cff_index_get(topdictidx, 0); stbtt__cff_get_index(&b); // string INDEX info->gsubrs = stbtt__cff_get_index(&b); stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); info->subrs = stbtt__get_subrs(b, topdict); // we only support Type 2 charstrings if (cstype != 2) return 0; if (charstrings == 0) return 0; if (fdarrayoff) { // looks like a CID font if (!fdselectoff) return 0; stbtt__buf_seek(&b, fdarrayoff); info->fontdicts = stbtt__cff_get_index(&b); info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); } stbtt__buf_seek(&b, charstrings); info->charstrings = stbtt__cff_get_index(&b); } t = stbtt__find_table(data, fontstart, "maxp"); if (t) info->numGlyphs = ttUSHORT(data+t+4); else info->numGlyphs = 0xffff; info->svg = -1; // find a cmap encoding table we understand *now* to avoid searching // later. (todo: could make this installable) // the same regardless of glyph. numTables = ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { stbtt_uint32 encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: switch (ttUSHORT(data+encoding_record+2)) { case STBTT_MS_EID_UNICODE_BMP: case STBTT_MS_EID_UNICODE_FULL: // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; } break; case STBTT_PLATFORM_ID_UNICODE: // Mac/iOS has these // all the encodingIDs are unicode, so we don't bother to check it info->index_map = cmap + ttULONG(data+encoding_record+4); break; } } if (info->index_map == 0) return 0; info->indexToLocFormat = ttUSHORT(data+info->head + 50); return 1; } STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) { stbtt_uint8 *data = info->data; stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { stbtt_uint32 first = ttUSHORT(data + index_map + 6); stbtt_uint32 count = ttUSHORT(data + index_map + 8); if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; } else if (format == 2) { STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean return 0; } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; stbtt_uint32 search = endCount; if (unicode_codepoint > 0xffff) return 0; // they lie from endCount .. endCount + segCount // but searchRange is the nearest power of two, so... if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) search += rangeShift*2; // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { stbtt_uint16 end; searchRange >>= 1; end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; --entrySelector; } search += 2; { stbtt_uint16 offset, start, last; stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); last = ttUSHORT(data + endCount + 2*item); if (unicode_codepoint < start || unicode_codepoint > last) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); if (offset == 0) return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; low = 0; high = (stbtt_int32)ngroups; // Binary search the right group. while (low < high) { stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); if ((stbtt_uint32) unicode_codepoint < start_char) high = mid; else if ((stbtt_uint32) unicode_codepoint > end_char) low = mid+1; else { stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 return start_glyph; } } return 0; // not found } // @TODO STBTT_assert(0); return 0; } STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) { return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); } static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) { v->type = type; v->x = (stbtt_int16) x; v->y = (stbtt_int16) y; v->cx = (stbtt_int16) cx; v->cy = (stbtt_int16) cy; } static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) { int g1,g2; STBTT_assert(!info->cff.size); if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format if (info->indexToLocFormat == 0) { g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; } else { g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); } return g1==g2 ? -1 : g1; // if length is 0, return -1 } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info->data + g + 2); if (y0) *y0 = ttSHORT(info->data + g + 4); if (x1) *x1 = ttSHORT(info->data + g + 6); if (y1) *y1 = ttSHORT(info->data + g + 8); } return 1; } STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) { return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); } STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) { stbtt_int16 numberOfContours; int g; if (info->cff.size) return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 1; numberOfContours = ttSHORT(info->data + g); return numberOfContours == 0; } static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) { if (start_off) { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); } return num_vertices; } static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { stbtt_int16 numberOfContours; stbtt_uint8 *endPtsOfContours; stbtt_uint8 *data = info->data; stbtt_vertex *vertices=0; int num_vertices=0; int g = stbtt__GetGlyfOffset(info, glyph_index); *pvertices = NULL; if (g < 0) return 0; numberOfContours = ttSHORT(data + g); if (numberOfContours > 0) { stbtt_uint8 flags=0,flagcount; stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; stbtt_uint8 *points; endPtsOfContours = (data + g + 10); ins = ttUSHORT(data + g + 10 + numberOfContours * 2); points = data + g + 10 + numberOfContours * 2 + 2 + ins; n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); m = n + 2*numberOfContours; // a loose bound on how many vertices we might need vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); if (vertices == 0) return 0; next_move = 0; flagcount=0; // in first pass, we load uninterpreted data into the allocated array // above, shifted to the end of the array so we won't overwrite it when // we create our final data starting from the front off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated // first load flags for (i=0; i < n; ++i) { if (flagcount == 0) { flags = *points++; if (flags & 8) flagcount = *points++; } else --flagcount; vertices[off+i].type = flags; } // now load x coordinates x=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 2) { stbtt_int16 dx = *points++; x += (flags & 16) ? dx : -dx; // ??? } else { if (!(flags & 16)) { x = x + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].x = (stbtt_int16) x; } // now load y coordinates y=0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; if (flags & 4) { stbtt_int16 dy = *points++; y += (flags & 32) ? dy : -dy; // ??? } else { if (!(flags & 32)) { y = y + (stbtt_int16) (points[0]*256 + points[1]); points += 2; } } vertices[off+i].y = (stbtt_int16) y; } // now convert them to our format num_vertices=0; sx = sy = cx = cy = scx = scy = 0; for (i=0; i < n; ++i) { flags = vertices[off+i].type; x = (stbtt_int16) vertices[off+i].x; y = (stbtt_int16) vertices[off+i].y; if (next_move == i) { if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); // now start the new one start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. scx = x; scy = y; if (!(vertices[off+i+1].type & 1)) { // next point is also a curve point, so interpolate an on-point curve sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; } else { // otherwise just use the next point as our start point sx = (stbtt_int32) vertices[off+i+1].x; sy = (stbtt_int32) vertices[off+i+1].y; ++i; // we're using point i+1 as the starting point, so skip it } } else { sx = x; sy = y; } stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); was_off = 0; next_move = 1 + ttUSHORT(endPtsOfContours+j*2); ++j; } else { if (!(flags & 1)) { // if it's a curve if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); cx = x; cy = y; was_off = 1; } else { if (was_off) stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); else stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); was_off = 0; } } } num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); } else if (numberOfContours < 0) { // Compound shapes. int more = 1; stbtt_uint8 *comp = data + g + 10; num_vertices = 0; vertices = 0; while (more) { stbtt_uint16 flags, gidx; int comp_num_verts = 0, i; stbtt_vertex *comp_verts = 0, *tmp = 0; float mtx[6] = {1,0,0,1,0,0}, m, n; flags = ttSHORT(comp); comp+=2; gidx = ttSHORT(comp); comp+=2; if (flags & 2) { // XY values if (flags & 1) { // shorts mtx[4] = ttSHORT(comp); comp+=2; mtx[5] = ttSHORT(comp); comp+=2; } else { mtx[4] = ttCHAR(comp); comp+=1; mtx[5] = ttCHAR(comp); comp+=1; } } else { // @TODO handle matching point STBTT_assert(0); } if (flags & (1<<3)) { // WE_HAVE_A_SCALE mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = mtx[2] = 0; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); if (!tmp) { if (vertices) STBTT_free(vertices, info->userdata); if (comp_verts) STBTT_free(comp_verts, info->userdata); return 0; } if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); if (vertices) STBTT_free(vertices, info->userdata); vertices = tmp; STBTT_free(comp_verts, info->userdata); num_vertices += comp_num_verts; } // More components ? more = flags & (1<<5); } } else { // numberOfCounters == 0, do nothing } *pvertices = vertices; return num_vertices; } typedef struct { int bounds; int started; float first_x, first_y; float x, y; stbtt_int32 min_x, max_x, min_y, max_y; stbtt_vertex *pvertices; int num_vertices; } stbtt__csctx; #define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) { if (x > c->max_x || !c->started) c->max_x = x; if (y > c->max_y || !c->started) c->max_y = y; if (x < c->min_x || !c->started) c->min_x = x; if (y < c->min_y || !c->started) c->min_y = y; c->started = 1; } static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) { if (c->bounds) { stbtt__track_vertex(c, x, y); if (type == STBTT_vcubic) { stbtt__track_vertex(c, cx, cy); stbtt__track_vertex(c, cx1, cy1); } } else { stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; } c->num_vertices++; } static void stbtt__csctx_close_shape(stbtt__csctx *ctx) { if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); } static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) { stbtt__csctx_close_shape(ctx); ctx->first_x = ctx->x = ctx->x + dx; ctx->first_y = ctx->y = ctx->y + dy; stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) { ctx->x += dx; ctx->y += dy; stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); } static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { float cx1 = ctx->x + dx1; float cy1 = ctx->y + dy1; float cx2 = cx1 + dx2; float cy2 = cy1 + dy2; ctx->x = cx2 + dx3; ctx->y = cy2 + dy3; stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); } static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) { int count = stbtt__cff_index_count(&idx); int bias = 107; if (count >= 33900) bias = 32768; else if (count >= 1240) bias = 1131; n += bias; if (n < 0 || n >= count) return stbtt__new_buf(NULL, 0); return stbtt__cff_index_get(idx, n); } static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) { stbtt__buf fdselect = info->fdselect; int nranges, start, end, v, fmt, fdselector = -1, i; stbtt__buf_seek(&fdselect, 0); fmt = stbtt__buf_get8(&fdselect); if (fmt == 0) { // untested stbtt__buf_skip(&fdselect, glyph_index); fdselector = stbtt__buf_get8(&fdselect); } else if (fmt == 3) { nranges = stbtt__buf_get16(&fdselect); start = stbtt__buf_get16(&fdselect); for (i = 0; i < nranges; i++) { v = stbtt__buf_get8(&fdselect); end = stbtt__buf_get16(&fdselect); if (glyph_index >= start && glyph_index < end) { fdselector = v; break; } start = end; } } if (fdselector == -1) stbtt__new_buf(NULL, 0); return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) { int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; int has_subrs = 0, clear_stack; float s[48]; stbtt__buf subr_stack[10], subrs = info->subrs, b; float f; #define STBTT__CSERR(s) (0) // this currently ignores the initial width value, which isn't needed if we have hmtx b = stbtt__cff_index_get(info->charstrings, glyph_index); while (b.cursor < b.size) { i = 0; clear_stack = 1; b0 = stbtt__buf_get8(&b); switch (b0) { // @TODO implement hinting case 0x13: // hintmask case 0x14: // cntrmask if (in_header) maskbits += (sp / 2); // implicit "vstem" in_header = 0; stbtt__buf_skip(&b, (maskbits + 7) / 8); break; case 0x01: // hstem case 0x03: // vstem case 0x12: // hstemhm case 0x17: // vstemhm maskbits += (sp / 2); break; case 0x15: // rmoveto in_header = 0; if (sp < 2) return STBTT__CSERR("rmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); break; case 0x04: // vmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("vmoveto stack"); stbtt__csctx_rmove_to(c, 0, s[sp-1]); break; case 0x16: // hmoveto in_header = 0; if (sp < 1) return STBTT__CSERR("hmoveto stack"); stbtt__csctx_rmove_to(c, s[sp-1], 0); break; case 0x05: // rlineto if (sp < 2) return STBTT__CSERR("rlineto stack"); for (; i + 1 < sp; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); break; // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical // starting from a different place. case 0x07: // vlineto if (sp < 1) return STBTT__CSERR("vlineto stack"); goto vlineto; case 0x06: // hlineto if (sp < 1) return STBTT__CSERR("hlineto stack"); for (;;) { if (i >= sp) break; stbtt__csctx_rline_to(c, s[i], 0); i++; vlineto: if (i >= sp) break; stbtt__csctx_rline_to(c, 0, s[i]); i++; } break; case 0x1F: // hvcurveto if (sp < 4) return STBTT__CSERR("hvcurveto stack"); goto hvcurveto; case 0x1E: // vhcurveto if (sp < 4) return STBTT__CSERR("vhcurveto stack"); for (;;) { if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); i += 4; hvcurveto: if (i + 3 >= sp) break; stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); i += 4; } break; case 0x08: // rrcurveto if (sp < 6) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x18: // rcurveline if (sp < 8) return STBTT__CSERR("rcurveline stack"); for (; i + 5 < sp - 2; i += 6) stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); stbtt__csctx_rline_to(c, s[i], s[i+1]); break; case 0x19: // rlinecurve if (sp < 8) return STBTT__CSERR("rlinecurve stack"); for (; i + 1 < sp - 6; i += 2) stbtt__csctx_rline_to(c, s[i], s[i+1]); if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); break; case 0x1A: // vvcurveto case 0x1B: // hhcurveto if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); f = 0.0; if (sp & 1) { f = s[i]; i++; } for (; i + 3 < sp; i += 4) { if (b0 == 0x1B) stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); else stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); f = 0.0; } break; case 0x0A: // callsubr if (!has_subrs) { if (info->fdselect.size) subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); has_subrs = 1; } // FALLTHROUGH case 0x1D: // callgsubr if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); v = (int) s[--sp]; if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); subr_stack[subr_stack_height++] = b; b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); if (b.size == 0) return STBTT__CSERR("subr not found"); b.cursor = 0; clear_stack = 0; break; case 0x0B: // return if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); b = subr_stack[--subr_stack_height]; clear_stack = 0; break; case 0x0E: // endchar stbtt__csctx_close_shape(c); return 1; case 0x0C: { // two-byte escape float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; float dx, dy; int b1 = stbtt__buf_get8(&b); switch (b1) { // @TODO These "flex" implementations ignore the flex-depth and resolution, // and always draw beziers. case 0x22: // hflex if (sp < 7) return STBTT__CSERR("hflex stack"); dx1 = s[0]; dx2 = s[1]; dy2 = s[2]; dx3 = s[3]; dx4 = s[4]; dx5 = s[5]; dx6 = s[6]; stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); break; case 0x23: // flex if (sp < 13) return STBTT__CSERR("flex stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = s[10]; dy6 = s[11]; //fd is s[12] stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; case 0x24: // hflex1 if (sp < 9) return STBTT__CSERR("hflex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dx4 = s[5]; dx5 = s[6]; dy5 = s[7]; dx6 = s[8]; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); break; case 0x25: // flex1 if (sp < 11) return STBTT__CSERR("flex1 stack"); dx1 = s[0]; dy1 = s[1]; dx2 = s[2]; dy2 = s[3]; dx3 = s[4]; dy3 = s[5]; dx4 = s[6]; dy4 = s[7]; dx5 = s[8]; dy5 = s[9]; dx6 = dy6 = s[10]; dx = dx1+dx2+dx3+dx4+dx5; dy = dy1+dy2+dy3+dy4+dy5; if (STBTT_fabs(dx) > STBTT_fabs(dy)) dy6 = -dy; else dx6 = -dx; stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); break; default: return STBTT__CSERR("unimplemented"); } } break; default: if (b0 != 255 && b0 != 28 && b0 < 32) return STBTT__CSERR("reserved operator"); // push immediate if (b0 == 255) { f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; } else { stbtt__buf_skip(&b, -1); f = (float)(stbtt_int16)stbtt__cff_int(&b); } if (sp >= 48) return STBTT__CSERR("push stack overflow"); s[sp++] = f; clear_stack = 0; break; } if (clear_stack) sp = 0; } return STBTT__CSERR("no endchar"); #undef STBTT__CSERR } static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { // runs the charstring twice, once to count and once to output (to avoid realloc) stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); output_ctx.pvertices = *pvertices; if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); return output_ctx.num_vertices; } } *pvertices = NULL; return 0; } static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { stbtt__csctx c = STBTT__CSCTX_INIT(1); int r = stbtt__run_charstring(info, glyph_index, &c); if (x0) *x0 = r ? c.min_x : 0; if (y0) *y0 = r ? c.min_y : 0; if (x1) *x1 = r ? c.max_x : 0; if (y1) *y1 = r ? c.max_y : 0; return r ? c.num_vertices : 0; } STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) { if (!info->cff.size) return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); else return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); } STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); } else { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); } } STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) { stbtt_uint8 *data = info->data + info->kern; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; return ttUSHORT(data+10); } STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) { stbtt_uint8 *data = info->data + info->kern; int k, length; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; length = ttUSHORT(data+10); if (table_length < length) length = table_length; for (k = 0; k < length; k++) { table[k].glyph1 = ttUSHORT(data+18+(k*6)); table[k].glyph2 = ttUSHORT(data+20+(k*6)); table[k].advance = ttSHORT(data+22+(k*6)); } return length; } static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint8 *data = info->data + info->kern; stbtt_uint32 needle, straw; int l, r, m; // we only look at the first table. it must be 'horizontal' and format 0. if (!info->kern) return 0; if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 return 0; if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format return 0; l = 0; r = ttUSHORT(data+10) - 1; needle = glyph1 << 16 | glyph2; while (l <= r) { m = (l + r) >> 1; straw = ttULONG(data+18+(m*6)); // note: unaligned read if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else return ttSHORT(data+22+(m*6)); } return 0; } static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) { stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); switch (coverageFormat) { case 1: { stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); // Binary search. stbtt_int32 l=0, r=glyphCount-1, m; int straw, needle=glyph; while (l <= r) { stbtt_uint8 *glyphArray = coverageTable + 4; stbtt_uint16 glyphID; m = (l + r) >> 1; glyphID = ttUSHORT(glyphArray + 2 * m); straw = glyphID; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { return m; } } break; } case 2: { stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); stbtt_uint8 *rangeArray = coverageTable + 4; // Binary search. stbtt_int32 l=0, r=rangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *rangeRecord; m = (l + r) >> 1; rangeRecord = rangeArray + 6 * m; strawStart = ttUSHORT(rangeRecord); strawEnd = ttUSHORT(rangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else { stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); return startCoverageIndex + glyph - strawStart; } } break; } default: return -1; // unsupported } return -1; } static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) { stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); switch (classDefFormat) { case 1: { stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); stbtt_uint8 *classDef1ValueArray = classDefTable + 6; if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); break; } case 2: { stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); stbtt_uint8 *classRangeRecords = classDefTable + 4; // Binary search. stbtt_int32 l=0, r=classRangeCount-1, m; int strawStart, strawEnd, needle=glyph; while (l <= r) { stbtt_uint8 *classRangeRecord; m = (l + r) >> 1; classRangeRecord = classRangeRecords + 6 * m; strawStart = ttUSHORT(classRangeRecord); strawEnd = ttUSHORT(classRangeRecord + 2); if (needle < strawStart) r = m - 1; else if (needle > strawEnd) l = m + 1; else return (stbtt_int32)ttUSHORT(classRangeRecord + 4); } break; } default: return -1; // Unsupported definition type, return an error. } // "All glyphs not assigned to a class fall into class 0". (OpenType spec) return 0; } // Define to STBTT_assert(x) if you want to break on unimplemented formats. #define STBTT_GPOS_TODO_assert(x) static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) { stbtt_uint16 lookupListOffset; stbtt_uint8 *lookupList; stbtt_uint16 lookupCount; stbtt_uint8 *data; stbtt_int32 i, sti; if (!info->gpos) return 0; data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; lookupCount = ttUSHORT(lookupList); for (i=0; i<lookupCount; ++i) { stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i); stbtt_uint8 *lookupTable = lookupList + lookupOffset; stbtt_uint16 lookupType = ttUSHORT(lookupTable); stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4); stbtt_uint8 *subTableOffsets = lookupTable + 6; if (lookupType != 2) // Pair Adjustment Positioning Subtable continue; for (sti=0; sti<subTableCount; sti++) { stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti); stbtt_uint8 *table = lookupTable + subtableOffset; stbtt_uint16 posFormat = ttUSHORT(table); stbtt_uint16 coverageOffset = ttUSHORT(table + 2); stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1); if (coverageIndex == -1) continue; switch (posFormat) { case 1: { stbtt_int32 l, r, m; int straw, needle; stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? stbtt_int32 valueRecordPairSizeInBytes = 2; stbtt_uint16 pairSetCount = ttUSHORT(table + 8); stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex); stbtt_uint8 *pairValueTable = table + pairPosOffset; stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable); stbtt_uint8 *pairValueArray = pairValueTable + 2; if (coverageIndex >= pairSetCount) return 0; needle=glyph2; r=pairValueCount-1; l=0; // Binary search. while (l <= r) { stbtt_uint16 secondGlyph; stbtt_uint8 *pairValue; m = (l + r) >> 1; pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; secondGlyph = ttUSHORT(pairValue); straw = secondGlyph; if (needle < straw) r = m - 1; else if (needle > straw) l = m + 1; else { stbtt_int16 xAdvance = ttSHORT(pairValue + 2); return xAdvance; } } } else return 0; break; } case 2: { stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); stbtt_uint16 class1Count = ttUSHORT(table + 12); stbtt_uint16 class2Count = ttUSHORT(table + 14); stbtt_uint8 *class1Records, *class2Records; stbtt_int16 xAdvance; if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed class1Records = table + 16; class2Records = class1Records + 2 * (glyph1class * class2Count); xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } else return 0; break; } default: return 0; // Unsupported position format } } } return 0; } STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) { int xAdvance = 0; if (info->gpos) xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); else if (info->kern) xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) { if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs return 0; return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); } STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) { stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); if (descent) *descent = ttSHORT(info->data+info->hhea + 6); if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); if (!tab) return 0; if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); return 1; } STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) { *x0 = ttSHORT(info->data + info->head + 36); *y0 = ttSHORT(info->data + info->head + 38); *x1 = ttSHORT(info->data + info->head + 40); *y1 = ttSHORT(info->data + info->head + 42); } STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); return pixels / unitsPerEm; } STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) { STBTT_free(v, info->userdata); } STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) { int i; stbtt_uint8 *data = info->data; stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); int numEntries = ttUSHORT(svg_doc_list); stbtt_uint8 *svg_docs = svg_doc_list + 2; for(i=0; i<numEntries; i++) { stbtt_uint8 *svg_doc = svg_docs + (12 * i); if ((gl >= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) return svg_doc; } return 0; } STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) { stbtt_uint8 *data = info->data; stbtt_uint8 *svg_doc; if (info->svg == 0) return 0; svg_doc = stbtt_FindSVGDoc(info, gl); if (svg_doc != NULL) { *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); return ttULONG(svg_doc + 8); } else { return 0; } } STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) { return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); } ////////////////////////////////////////////////////////////////////////////// // // antialiasing software rasterizer // STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { // e.g. space character if (ix0) *ix0 = 0; if (iy0) *iy0 = 0; if (ix1) *ix1 = 0; if (iy1) *iy1 = 0; } else { // move to integral bboxes (treating pixels as little squares, what pixels get touched)? if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); } } STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); } STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) { stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } ////////////////////////////////////////////////////////////////////////////// // // Rasterizer typedef struct stbtt__hheap_chunk { struct stbtt__hheap_chunk *next; } stbtt__hheap_chunk; typedef struct stbtt__hheap { struct stbtt__hheap_chunk *head; void *first_free; int num_remaining_in_head_chunk; } stbtt__hheap; static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) { if (hh->first_free) { void *p = hh->first_free; hh->first_free = * (void **) p; return p; } else { if (hh->num_remaining_in_head_chunk == 0) { int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); if (c == NULL) return NULL; c->next = hh->head; hh->head = c; hh->num_remaining_in_head_chunk = count; } --hh->num_remaining_in_head_chunk; return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; } } static void stbtt__hheap_free(stbtt__hheap *hh, void *p) { *(void **) p = hh->first_free; hh->first_free = p; } static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) { stbtt__hheap_chunk *c = hh->head; while (c) { stbtt__hheap_chunk *n = c->next; STBTT_free(c, userdata); c = n; } } typedef struct stbtt__edge { float x0,y0, x1,y1; int invert; } stbtt__edge; typedef struct stbtt__active_edge { struct stbtt__active_edge *next; #if STBTT_RASTERIZER_VERSION==1 int x,dx; float ey; int direction; #elif STBTT_RASTERIZER_VERSION==2 float fx,fdx,fdy; float direction; float sy; float ey; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif } stbtt__active_edge; #if STBTT_RASTERIZER_VERSION == 1 #define STBTT_FIXSHIFT 10 #define STBTT_FIX (1 << STBTT_FIXSHIFT) #define STBTT_FIXMASK (STBTT_FIX-1) static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(z != NULL); if (!z) return z; // round dx down to avoid overshooting if (dxdy < 0) z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); else z->dx = STBTT_ifloor(STBTT_FIX * dxdy); z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount z->x -= off_x * STBTT_FIX; z->ey = e->y1; z->next = 0; z->direction = e->invert ? 1 : -1; return z; } #elif STBTT_RASTERIZER_VERSION == 2 static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); STBTT_assert(z != NULL); //STBTT_assert(e->y0 <= start_point); if (!z) return z; z->fdx = dxdy; z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; z->fx = e->x0 + dxdy * (start_point - e->y0); z->fx -= off_x; z->direction = e->invert ? 1.0f : -1.0f; z->sy = e->y0; z->ey = e->y1; z->next = 0; return z; } #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif #if STBTT_RASTERIZER_VERSION == 1 // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) { // non-zero winding fill int x0=0, w=0; while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point x0 = e->x; w += e->direction; } else { int x1 = e->x; w += e->direction; // if we went to zero, we need to draw if (w == 0) { int i = x0 >> STBTT_FIXSHIFT; int j = x1 >> STBTT_FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); else i = -1; // clip if (j < len) // add antialiasing for x1 scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); else j = len; // clip for (++i; i < j; ++i) // fill pixels between x0 and x1 scanline[i] = scanline[i] + (stbtt_uint8) max_weight; } } } } e = e->next; } } static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline int s; // vertical subsample index unsigned char scanline_data[512], *scanline; if (result->w > 512) scanline = (unsigned char *) STBTT_malloc(result->w, userdata); else scanline = scanline_data; y = off_y * vsubsample; e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; while (j < result->h) { STBTT_memset(scanline, 0, result->w); for (s=0; s < vsubsample; ++s) { // find center of pixel for this scanline float scan_y = y + 0.5f; stbtt__active_edge **step = &active; // update all active edges; // remove all active edges that terminate before the center of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list STBTT_assert(z->direction); z->direction = 0; stbtt__hheap_free(&hh, z); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list } } // resort the list if needed for(;;) { int changed=0; step = &active; while (*step && (*step)->next) { if ((*step)->x > (*step)->next->x) { stbtt__active_edge *t = *step; stbtt__active_edge *q = t->next; t->next = q->next; q->next = t; *step = q; changed = 1; } step = &(*step)->next; } if (!changed) break; } // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e->y0 <= scan_y) { if (e->y1 > scan_y) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); if (z != NULL) { // find insertion point if (active == NULL) active = z; else if (z->x < active->x) { // insert at front z->next = active; active = z; } else { // find thing to insert AFTER stbtt__active_edge *p = active; while (p->next && p->next->x < z->x) p = p->next; // at this point, p->next->x is NOT < z->x z->next = p->next; p->next = z; } } } ++e; } // now process all active edges in XOR fashion if (active) stbtt__fill_active_edges(scanline, result->w, active, max_weight); ++y; } STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); ++j; } stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } #elif STBTT_RASTERIZER_VERSION == 2 // the edge passed in here does not cross the vertical line at x or the vertical line at x+1 // (i.e. it has already been clipped to those) static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) { if (y0 == y1) return; STBTT_assert(y0 < y1); STBTT_assert(e->sy <= e->ey); if (y0 > e->ey) return; if (y1 < e->sy) return; if (y0 < e->sy) { x0 += (x1-x0) * (e->sy - y0) / (y1-y0); y0 = e->sy; } if (y1 > e->ey) { x1 += (x1-x0) * (e->ey - y1) / (y1-y0); y1 = e->ey; } if (x0 == x) STBTT_assert(x1 <= x+1); else if (x0 == x+1) STBTT_assert(x1 >= x); else if (x0 <= x) STBTT_assert(x1 <= x); else if (x0 >= x+1) STBTT_assert(x1 >= x+1); else STBTT_assert(x1 >= x && x1 <= x+1); if (x0 <= x && x1 <= x) scanline[x] += e->direction * (y1-y0); else if (x0 >= x+1 && x1 >= x+1) ; else { STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position } } static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) { STBTT_assert(top_width >= 0); STBTT_assert(bottom_width >= 0); return (top_width + bottom_width) / 2.0f * height; } static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) { return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); } static float stbtt__sized_triangle_area(float height, float width) { return height * width / 2; } static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) { float y_bottom = y_top+1; while (e) { // brute force every pixel // compute intersection points with top & bottom STBTT_assert(e->ey >= y_top); if (e->fdx == 0) { float x0 = e->fx; if (x0 < len) { if (x0 >= 0) { stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); } else { stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); } } } else { float x0 = e->fx; float dx = e->fdx; float xb = x0 + dx; float x_top, x_bottom; float sy0,sy1; float dy = e->fdy; STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); // compute endpoints of line segment clipped to this scanline (if the // line segment starts on this scanline. x0 is the intersection of the // line with y_top, but that may be off the line segment. if (e->sy > y_top) { x_top = x0 + dx * (e->sy - y_top); sy0 = e->sy; } else { x_top = x0; sy0 = y_top; } if (e->ey < y_bottom) { x_bottom = x0 + dx * (e->ey - y_top); sy1 = e->ey; } else { x_bottom = xb; sy1 = y_bottom; } if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { // from here on, we don't have to range check x values if ((int) x_top == (int) x_bottom) { float height; // simple case, only spans one pixel int x = (int) x_top; height = (sy1 - sy0) * e->direction; STBTT_assert(x >= 0 && x < len); scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); scanline_fill[x] += height; // everything right of this pixel is filled } else { int x,x1,x2; float y_crossing, y_final, step, sign, area; // covers 2+ pixels if (x_top > x_bottom) { // flip scanline vertically; signed area is the same float t; sy0 = y_bottom - (sy0 - y_top); sy1 = y_bottom - (sy1 - y_top); t = sy0, sy0 = sy1, sy1 = t; t = x_bottom, x_bottom = x_top, x_top = t; dx = -dx; dy = -dy; t = x0, x0 = xb, xb = t; } STBTT_assert(dy >= 0); STBTT_assert(dx >= 0); x1 = (int) x_top; x2 = (int) x_bottom; // compute intersection with y axis at x1+1 y_crossing = y_top + dy * (x1+1 - x0); // compute intersection with y axis at x2 y_final = y_top + dy * (x2 - x0); // x1 x_top x2 x_bottom // y_top +------|-----+------------+------------+--------|---+------------+ // | | | | | | // | | | | | | // sy0 | Txxxxx|............|............|............|............| // y_crossing | *xxxxx.......|............|............|............| // | | xxxxx..|............|............|............| // | | /- xx*xxxx........|............|............| // | | dy < | xxxxxx..|............|............| // y_final | | \- | xx*xxx.........|............| // sy1 | | | | xxxxxB...|............| // | | | | | | // | | | | | | // y_bottom +------------+------------+------------+------------+------------+ // // goal is to measure the area covered by '.' in each pixel // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 // @TODO: maybe test against sy1 rather than y_bottom? if (y_crossing > y_bottom) y_crossing = y_bottom; sign = e->direction; // area of the rectangle covered from sy0..y_crossing area = sign * (y_crossing-sy0); // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); // check if final y_crossing is blown up; no test case for this if (y_final > y_bottom) { y_final = y_bottom; dy = (y_final - y_crossing ) / (x2 - (x1+1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom } // in second pixel, area covered by line segment found in first pixel // is always a rectangle 1 wide * the height of that line segment; this // is exactly what the variable 'area' stores. it also gets a contribution // from the line segment within it. the THIRD pixel will get the first // pixel's rectangle contribution, the second pixel's rectangle contribution, // and its own contribution. the 'own contribution' is the same in every pixel except // the leftmost and rightmost, a trapezoid that slides down in each pixel. // the second pixel's contribution to the third pixel will be the // rectangle 1 wide times the height change in the second pixel, which is dy. step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, // which multiplied by 1-pixel-width is how much pixel area changes for each step in x // so the area advances by 'step' every time for (x = x1+1; x < x2; ++x) { scanline[x] += area + step/2; // area of trapezoid is 1*step/2 area += step; } STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down STBTT_assert(sy1 > y_final-0.01f); // area covered in the last pixel is the rectangle from all the pixels to the left, // plus the trapezoid filled by the line segment in this pixel all the way to the right edge scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); // the rest of the line is filled based on the total height of the line segment in this pixel scanline_fill[x2] += sign * (sy1-sy0); } } else { // if edge goes outside of box we're drawing, we require // clipping logic. since this does not match the intended use // of this library, we use a different, very slow brute // force implementation // note though that this does happen some of the time because // x_top and x_bottom can be extrapolated at the top & bottom of // the shape and actually lie outside the bounding box int x; for (x=0; x < len; ++x) { // cases: // // there can be up to two intersections with the pixel. any intersection // with left or right edges can be handled by splitting into two (or three) // regions. intersections with top & bottom do not necessitate case-wise logic. // // the old way of doing this found the intersections with the left & right edges, // then used some simple logic to produce up to three segments in sorted order // from top-to-bottom. however, this had a problem: if an x edge was epsilon // across the x border, then the corresponding y position might not be distinct // from the other y segment, and it might ignored as an empty segment. to avoid // that, we need to explicitly produce segments based on x positions. // rename variables to clearly-defined pairs float y0 = y_top; float x1 = (float) (x); float x2 = (float) (x+1); float x3 = xb; float y3 = y_bottom; // x = e->x + e->dx * (y-y_top) // (y-y_top) = (x - e->x) / e->dx // y = (x - e->x) / e->dx + y_top float y1 = (x - x0) / dx + y_top; float y2 = (x+1 - x0) / dx + y_top; if (x0 < x1 && x3 > x2) { // three segments descending down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x1 && x0 > x2) { // three segments descending down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); } else { // one segment stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); } } } } e = e->next; } } // directly AA rasterize edges w/o supersampling static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0, i; float scanline_data[129], *scanline, *scanline2; STBTT__NOTUSED(vsubsample); if (result->w > 64) scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); else scanline = scanline_data; scanline2 = scanline + result->w; y = off_y; e[n].y0 = (float) (off_y + result->h) + 1; while (j < result->h) { // find center of pixel for this scanline float scan_y_top = y + 0.0f; float scan_y_bottom = y + 1.0f; stbtt__active_edge **step = &active; STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); // update all active edges; // remove all active edges that terminate before the top of this scanline while (*step) { stbtt__active_edge * z = *step; if (z->ey <= scan_y_top) { *step = z->next; // delete from list STBTT_assert(z->direction); z->direction = 0; stbtt__hheap_free(&hh, z); } else { step = &((*step)->next); // advance through list } } // insert all edges that start before the bottom of this scanline while (e->y0 <= scan_y_bottom) { if (e->y0 != e->y1) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); if (z != NULL) { if (j == 0 && off_y != 0) { if (z->ey < scan_y_top) { // this can happen due to subpixel positioning and some kind of fp rounding error i think z->ey = scan_y_top; } } STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds // insert at front z->next = active; active = z; } } ++e; } // now process all active edges if (active) stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); { float sum = 0; for (i=0; i < result->w; ++i) { float k; int m; sum += scanline2[i]; k = scanline[i] + sum; k = (float) STBTT_fabs(k)*255 + 0.5f; m = (int) k; if (m > 255) m = 255; result->pixels[j*result->stride + i] = (unsigned char) m; } } // advance all the edges step = &active; while (*step) { stbtt__active_edge *z = *step; z->fx += z->fdx; // advance to position for current scanline step = &((*step)->next); // advance through list } ++y; ++j; } stbtt__hheap_cleanup(&hh, userdata); if (scanline != scanline_data) STBTT_free(scanline, userdata); } #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif #define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) { int i,j; for (i=1; i < n; ++i) { stbtt__edge t = p[i], *a = &t; j = i; while (j > 0) { stbtt__edge *b = &p[j-1]; int c = STBTT__COMPARE(a,b); if (!c) break; p[j] = p[j-1]; --j; } if (i != j) p[j] = t; } } static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) { /* threshold for transitioning to insertion sort */ while (n > 12) { stbtt__edge t; int c01,c12,c,m,i,j; /* compute median of three */ m = n >> 1; c01 = STBTT__COMPARE(&p[0],&p[m]); c12 = STBTT__COMPARE(&p[m],&p[n-1]); /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ if (c01 != c12) { /* otherwise, we'll need to swap something else to middle */ int z; c = STBTT__COMPARE(&p[0],&p[n-1]); /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ /* 0<mid && mid>n: 0>n => 0; 0<n => n */ z = (c == c12) ? 0 : n-1; t = p[z]; p[z] = p[m]; p[m] = t; } /* now p[m] is the median-of-three */ /* swap it to the beginning so it won't move around */ t = p[0]; p[0] = p[m]; p[m] = t; /* partition loop */ i=1; j=n-1; for(;;) { /* handling of equality is crucial here */ /* for sentinels & efficiency with duplicates */ for (;;++i) { if (!STBTT__COMPARE(&p[i], &p[0])) break; } for (;;--j) { if (!STBTT__COMPARE(&p[0], &p[j])) break; } /* make sure we haven't crossed */ if (i >= j) break; t = p[i]; p[i] = p[j]; p[j] = t; ++i; --j; } /* recurse on smaller side, iterate on larger */ if (j < (n-i)) { stbtt__sort_edges_quicksort(p,j); p = p+i; n = n-i; } else { stbtt__sort_edges_quicksort(p+i, n-i); n = j; } } } static void stbtt__sort_edges(stbtt__edge *p, int n) { stbtt__sort_edges_quicksort(p, n); stbtt__sort_edges_ins_sort(p, n); } typedef struct { float x,y; } stbtt__point; static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) { float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; #if STBTT_RASTERIZER_VERSION == 1 int vsubsample = result->h < 8 ? 15 : 5; #elif STBTT_RASTERIZER_VERSION == 2 int vsubsample = 1; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists n = 0; for (i=0; i < windings; ++i) n += wcount[i]; e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel if (e == 0) return; n = 0; m=0; for (i=0; i < windings; ++i) { stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { int a=k,b=j; // skip the edge if horizontal if (p[j].y == p[k].y) continue; // add edge from j to k to the list e[n].invert = 0; if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { e[n].invert = 1; a=j,b=k; } e[n].x0 = p[a].x * scale_x + shift_x; e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; e[n].x1 = p[b].x * scale_x + shift_x; e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; ++n; } } // now sort the edges by their highest point (should snap to integer, and then by x) //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); stbtt__sort_edges(e, n); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); STBTT_free(e, userdata); } static void stbtt__add_point(stbtt__point *points, int n, float x, float y) { if (!points) return; // during first pass, it's unallocated points[n].x = x; points[n].y = y; } // tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint float mx = (x0 + 2*x1 + x2)/4; float my = (y0 + 2*y1 + y2)/4; // versus directly drawn line float dx = (x0+x2)/2 - mx; float dy = (y0+y2)/2 - my; if (n > 16) // 65536 segments on one curve better be enough! return 1; if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x2,y2); *num_points = *num_points+1; } return 1; } static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) { // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough float dx0 = x1-x0; float dy0 = y1-y0; float dx1 = x2-x1; float dy1 = y2-y1; float dx2 = x3-x2; float dy2 = y3-y2; float dx = x3-x0; float dy = y3-y0; float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); float flatness_squared = longlen*longlen-shortlen*shortlen; if (n > 16) // 65536 segments on one curve better be enough! return; if (flatness_squared > objspace_flatness_squared) { float x01 = (x0+x1)/2; float y01 = (y0+y1)/2; float x12 = (x1+x2)/2; float y12 = (y1+y2)/2; float x23 = (x2+x3)/2; float y23 = (y2+y3)/2; float xa = (x01+x12)/2; float ya = (y01+y12)/2; float xb = (x12+x23)/2; float yb = (y12+y23)/2; float mx = (xa+xb)/2; float my = (ya+yb)/2; stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); } else { stbtt__add_point(points, *num_points,x3,y3); *num_points = *num_points+1; } } // returns number of contours static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) { stbtt__point *points=0; int num_points=0; float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count for (i=0; i < num_verts; ++i) if (vertices[i].type == STBTT_vmove) ++n; *num_contours = n; if (n == 0) return 0; *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); if (*contour_lengths == 0) { *num_contours = 0; return 0; } // make two passes through the points so we don't need to realloc for (pass=0; pass < 2; ++pass) { float x=0,y=0; if (pass == 1) { points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); if (points == NULL) goto error; } num_points = 0; n= -1; for (i=0; i < num_verts; ++i) { switch (vertices[i].type) { case STBTT_vmove: // start the next contour if (n >= 0) (*contour_lengths)[n] = num_points - start; ++n; start = num_points; x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x,y); break; case STBTT_vline: x = vertices[i].x, y = vertices[i].y; stbtt__add_point(points, num_points++, x, y); break; case STBTT_vcurve: stbtt__tesselate_curve(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; case STBTT_vcubic: stbtt__tesselate_cubic(points, &num_points, x,y, vertices[i].cx, vertices[i].cy, vertices[i].cx1, vertices[i].cy1, vertices[i].x, vertices[i].y, objspace_flatness_squared, 0); x = vertices[i].x, y = vertices[i].y; break; } } (*contour_lengths)[n] = num_points - start; } return points; error: STBTT_free(points, userdata); STBTT_free(*contour_lengths, userdata); *contour_lengths = 0; *num_contours = 0; return NULL; } STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) { float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count = 0; int *winding_lengths = NULL; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); if (windings) { stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); STBTT_free(winding_lengths, userdata); STBTT_free(windings, userdata); } } STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { if (scale_x == 0) { STBTT_free(vertices, info->userdata); return NULL; } scale_y = scale_x; } stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); // now we get the size gbm.w = (ix1 - ix0); gbm.h = (iy1 - iy0); gbm.pixels = NULL; // in case we error if (width ) *width = gbm.w; if (height) *height = gbm.h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; if (gbm.w && gbm.h) { gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); if (gbm.pixels) { gbm.stride = gbm.w; stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); } } STBTT_free(vertices, info->userdata); return gbm.pixels; } STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) { int ix0,iy0; stbtt_vertex *vertices; int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); gbm.pixels = output; gbm.w = out_w; gbm.h = out_h; gbm.stride = out_stride; if (gbm.w && gbm.h) stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); STBTT_free(vertices, info->userdata); } STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); } STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); } STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) { stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); } ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-CRAPPY packing to keep source code small static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) float pixel_height, // height of font in pixels unsigned char *pixels, int pw, int ph, // bitmap to be filled in int first_char, int num_chars, // characters to bake stbtt_bakedchar *chardata) { float scale; int x,y,bottom_y, i; stbtt_fontinfo f; f.userdata = NULL; if (!stbtt_InitFont(&f, data, offset)) return -1; STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels x=y=1; bottom_y = 1; scale = stbtt_ScaleForPixelHeight(&f, pixel_height); for (i=0; i < num_chars; ++i) { int advance, lsb, x0,y0,x1,y1,gw,gh; int g = stbtt_FindGlyphIndex(&f, first_char + i); stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); gw = x1-x0; gh = y1-y0; if (x + gw + 1 >= pw) y = bottom_y, x = 1; // advance to next row if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row return -i; STBTT_assert(x+gw < pw); STBTT_assert(y+gh < ph); stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); chardata[i].x0 = (stbtt_int16) x; chardata[i].y0 = (stbtt_int16) y; chardata[i].x1 = (stbtt_int16) (x + gw); chardata[i].y1 = (stbtt_int16) (y + gh); chardata[i].xadvance = scale * advance; chardata[i].xoff = (float) x0; chardata[i].yoff = (float) y0; x = x + gw + 1; if (y+gh+1 > bottom_y) bottom_y = y+gh+1; } return bottom_y; } STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) { float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_bakedchar *b = chardata + char_index; int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; q->x1 = round_x + b->x1 - b->x0 + d3d_bias; q->y1 = round_y + b->y1 - b->y0 + d3d_bias; q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // rectangle packing replacement routines if you don't have stb_rect_pack.h // #ifndef STB_RECT_PACK_VERSION typedef int stbrp_coord; //////////////////////////////////////////////////////////////////////////////////// // // // // // COMPILER WARNING ?!?!? // // // // // // if you get a compile warning due to these symbols being defined more than // // once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // // // //////////////////////////////////////////////////////////////////////////////////// typedef struct { int width,height; int x,y,bottom_y; } stbrp_context; typedef struct { unsigned char x; } stbrp_node; struct stbrp_rect { stbrp_coord x,y; int id,w,h,was_packed; }; static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) { con->width = pw; con->height = ph; con->x = 0; con->y = 0; con->bottom_y = 0; STBTT__NOTUSED(nodes); STBTT__NOTUSED(num_nodes); } static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) { int i; for (i=0; i < num_rects; ++i) { if (con->x + rects[i].w > con->width) { con->x = 0; con->y = con->bottom_y; } if (con->y + rects[i].h > con->height) break; rects[i].x = con->x; rects[i].y = con->y; rects[i].was_packed = 1; con->x += rects[i].w; if (con->y + rects[i].h > con->bottom_y) con->bottom_y = con->y + rects[i].h; } for ( ; i < num_rects; ++i) rects[i].was_packed = 0; } #endif ////////////////////////////////////////////////////////////////////////////// // // bitmap baking // // This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If // stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) { stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); int num_nodes = pw - padding; stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); if (context == NULL || nodes == NULL) { if (context != NULL) STBTT_free(context, alloc_context); if (nodes != NULL) STBTT_free(nodes , alloc_context); return 0; } spc->user_allocator_context = alloc_context; spc->width = pw; spc->height = ph; spc->pixels = pixels; spc->pack_info = context; spc->nodes = nodes; spc->padding = padding; spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; spc->h_oversample = 1; spc->v_oversample = 1; spc->skip_missing = 0; stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); if (pixels) STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels return 1; } STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) { STBTT_free(spc->nodes , spc->user_allocator_context); STBTT_free(spc->pack_info, spc->user_allocator_context); } STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) { STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); if (h_oversample <= STBTT_MAX_OVERSAMPLE) spc->h_oversample = h_oversample; if (v_oversample <= STBTT_MAX_OVERSAMPLE) spc->v_oversample = v_oversample; } STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) { spc->skip_missing = skip; } #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { int i; unsigned int total; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; pixels[i] = (unsigned char) (total / kernel_width); } break; } for (; i < w; ++i) { STBTT_assert(pixels[i] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i] = (unsigned char) (total / kernel_width); } pixels += stride_in_bytes; } } static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { int i; unsigned int total; STBTT_memset(buffer, 0, kernel_width); total = 0; // make kernel_width a constant in common cases so compiler can optimize out the divide switch (kernel_width) { case 2: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 2); } break; case 3: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 3); } break; case 4: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 4); } break; case 5: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / 5); } break; default: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } break; } for (; i < h; ++i) { STBTT_assert(pixels[i*stride_in_bytes] == 0); total -= buffer[i & STBTT__OVER_MASK]; pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); } pixels += 1; } } static float stbtt__oversample_shift(int oversample) { if (!oversample) return 0.0f; // The prefilter is a box filter of width "oversample", // which shifts phase by (oversample - 1)/2 pixels in // oversampled space. We want to shift in the opposite // direction to counter this. return (float)-(oversample - 1) / (2.0f * (float)oversample); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k; int missing_glyph_added = 0; k=0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); ranges[i].h_oversample = (unsigned char) spc->h_oversample; ranges[i].v_oversample = (unsigned char) spc->v_oversample; for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { rects[k].w = rects[k].h = 0; } else { stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, &x0,&y0,&x1,&y1); rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); if (glyph == 0) missing_glyph_added = 1; } ++k; } } return k; } STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) { stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph); if (prefilter_x > 1) stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); if (prefilter_y > 1) stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); *sub_x = stbtt__oversample_shift(prefilter_x); *sub_y = stbtt__oversample_shift(prefilter_y); } // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { int i,j,k, missing_glyph = -1, return_value = 1; // save current values int old_h_over = spc->h_oversample; int old_v_over = spc->v_oversample; k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); float recip_h,recip_v,sub_x,sub_y; spc->h_oversample = ranges[i].h_oversample; spc->v_oversample = ranges[i].v_oversample; recip_h = 1.0f / spc->h_oversample; recip_v = 1.0f / spc->v_oversample; sub_x = stbtt__oversample_shift(spc->h_oversample); sub_y = stbtt__oversample_shift(spc->v_oversample); for (j=0; j < ranges[i].num_chars; ++j) { stbrp_rect *r = &rects[k]; if (r->was_packed && r->w != 0 && r->h != 0) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); stbrp_coord pad = (stbrp_coord) spc->padding; // pad on left and top r->x += pad; r->y += pad; r->w -= pad; r->h -= pad; stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); stbtt_GetGlyphBitmapBox(info, glyph, scale * spc->h_oversample, scale * spc->v_oversample, &x0,&y0,&x1,&y1); stbtt_MakeGlyphBitmapSubpixel(info, spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w - spc->h_oversample+1, r->h - spc->v_oversample+1, spc->stride_in_bytes, scale * spc->h_oversample, scale * spc->v_oversample, 0,0, glyph); if (spc->h_oversample > 1) stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->h_oversample); if (spc->v_oversample > 1) stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, r->w, r->h, spc->stride_in_bytes, spc->v_oversample); bc->x0 = (stbtt_int16) r->x; bc->y0 = (stbtt_int16) r->y; bc->x1 = (stbtt_int16) (r->x + r->w); bc->y1 = (stbtt_int16) (r->y + r->h); bc->xadvance = scale * advance; bc->xoff = (float) x0 * recip_h + sub_x; bc->yoff = (float) y0 * recip_v + sub_y; bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; if (glyph == 0) missing_glyph = j; } else if (spc->skip_missing) { return_value = 0; } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; } else { return_value = 0; // if any fail, report failure } ++k; } } // restore original values spc->h_oversample = old_h_over; spc->v_oversample = old_v_over; return return_value; } STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) { stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); } STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; int i,j,n, return_value = 1; //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; // flag all characters as NOT packed for (i=0; i < num_ranges; ++i) for (j=0; j < ranges[i].num_chars; ++j) ranges[i].chardata_for_range[j].x0 = ranges[i].chardata_for_range[j].y0 = ranges[i].chardata_for_range[j].x1 = ranges[i].chardata_for_range[j].y1 = 0; n = 0; for (i=0; i < num_ranges; ++i) n += ranges[i].num_chars; rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); if (rects == NULL) return 0; info.userdata = spc->user_allocator_context; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); stbtt_PackFontRangesPackRects(spc, rects, n); return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); STBTT_free(rects, spc->user_allocator_context); return return_value; } STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) { stbtt_pack_range range; range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; range.array_of_unicode_codepoints = NULL; range.num_chars = num_chars_in_range; range.chardata_for_range = chardata_for_range; range.font_size = font_size; return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); } STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) { int i_ascent, i_descent, i_lineGap; float scale; stbtt_fontinfo info; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); *ascent = (float) i_ascent * scale; *descent = (float) i_descent * scale; *lineGap = (float) i_lineGap * scale; } STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) { float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; q->y1 = y + b->yoff2 - b->yoff; } else { q->x0 = *xpos + b->xoff; q->y0 = *ypos + b->yoff; q->x1 = *xpos + b->xoff2; q->y1 = *ypos + b->yoff2; } q->s0 = b->x0 * ipw; q->t0 = b->y0 * iph; q->s1 = b->x1 * ipw; q->t1 = b->y1 * iph; *xpos += b->xadvance; } ////////////////////////////////////////////////////////////////////////////// // // sdf computation // #define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) #define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) { float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; float roperp = orig[1]*ray[0] - orig[0]*ray[1]; float a = q0perp - 2*q1perp + q2perp; float b = q1perp - q0perp; float c = q0perp - roperp; float s0 = 0., s1 = 0.; int num_s = 0; if (a != 0.0) { float discr = b*b - a*c; if (discr > 0.0) { float rcpna = -1 / a; float d = (float) STBTT_sqrt(discr); s0 = (b+d) * rcpna; s1 = (b-d) * rcpna; if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { if (num_s == 0) s0 = s1; ++num_s; } } } else { // 2*b*s + c = 0 // s = -c / (2*b) s0 = c / (-2 * b); if (s0 >= 0.0 && s0 <= 1.0) num_s = 1; } if (num_s == 0) return 0; else { float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; float q0d = q0[0]*rayn_x + q0[1]*rayn_y; float q1d = q1[0]*rayn_x + q1[1]*rayn_y; float q2d = q2[0]*rayn_x + q2[1]*rayn_y; float rod = orig[0]*rayn_x + orig[1]*rayn_y; float q10d = q1d - q0d; float q20d = q2d - q0d; float q0rd = q0d - rod; hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; hits[0][1] = a*s0+b; if (num_s > 1) { hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; hits[1][1] = a*s1+b; return 2; } else { return 1; } } } static int equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) { int i; float orig[2], ray[2] = { 1, 0 }; float y_frac; int winding = 0; // make sure y never passes through a vertex of the shape y_frac = (float) STBTT_fmod(y, 1.0f); if (y_frac < 0.01f) y += 0.01f; else if (y_frac > 0.99f) y -= 0.01f; orig[0] = x; orig[1] = y; // test a ray from (-infinity,y) to (x,y) for (i=0; i < nverts; ++i) { if (verts[i].type == STBTT_vline) { int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } if (verts[i].type == STBTT_vcurve) { int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); int by = STBTT_max(y0,STBTT_max(y1,y2)); if (y > ay && y < by && x > ax) { float q0[2],q1[2],q2[2]; float hits[2][2]; q0[0] = (float)x0; q0[1] = (float)y0; q1[0] = (float)x1; q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; if (equal(q0,q1) || equal(q1,q2)) { x0 = (int)verts[i-1].x; y0 = (int)verts[i-1].y; x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } else { int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); if (num_hits >= 1) if (hits[0][0] < 0) winding += (hits[0][1] < 0 ? -1 : 1); if (num_hits >= 2) if (hits[1][0] < 0) winding += (hits[1][1] < 0 ? -1 : 1); } } } } return winding; } static float stbtt__cuberoot( float x ) { if (x<0) return -(float) STBTT_pow(-x,1.0f/3.0f); else return (float) STBTT_pow( x,1.0f/3.0f); } // x^3 + a*x^2 + b*x + c = 0 static int stbtt__solve_cubic(float a, float b, float c, float* r) { float s = -a / 3; float p = b - a*a / 3; float q = a * (2*a*a - 9*b) / 27 + c; float p3 = p*p*p; float d = q*q + 4*p3 / 27; if (d >= 0) { float z = (float) STBTT_sqrt(d); float u = (-q + z) / 2; float v = (-q - z) / 2; u = stbtt__cuberoot(u); v = stbtt__cuberoot(v); r[0] = s + u + v; return 1; } else { float u = (float) STBTT_sqrt(-p/3); float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative float m = (float) STBTT_cos(v); float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; r[0] = s + u * 2 * m; r[1] = s - u * (m + n); r[2] = s - u * (m - n); //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); return 3; } } STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { float scale_x = scale, scale_y = scale; int ix0,iy0,ix1,iy1; int w,h; unsigned char *data; if (scale == 0) return NULL; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL if (ix0 == ix1 || iy0 == iy1) return NULL; ix0 -= padding; iy0 -= padding; ix1 += padding; iy1 += padding; w = (ix1 - ix0); h = (iy1 - iy0); if (width ) *width = w; if (height) *height = h; if (xoff ) *xoff = ix0; if (yoff ) *yoff = iy0; // invert for y-downwards bitmaps scale_y = -scale_y; { int x,y,i,j; float *precompute; stbtt_vertex *verts; int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); data = (unsigned char *) STBTT_malloc(w * h, info->userdata); precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); for (i=0,j=num_verts-1; i < num_verts; j=i++) { if (verts[i].type == STBTT_vline) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; if (len2 != 0.0f) precompute[i] = 1.0f / (bx*bx + by*by); else precompute[i] = 0.0f; } else precompute[i] = 0.0f; } for (y=iy0; y < iy1; ++y) { for (x=ix0; x < ix1; ++x) { float val; float min_dist = 999999.0f; float sx = (float) x + 0.5f; float sy = (float) y + 0.5f; float x_gspace = (sx / scale_x); float y_gspace = (sy / scale_y); int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path for (i=0; i < num_verts; ++i) { float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); if (dist2 < min_dist*min_dist) min_dist = (float) STBTT_sqrt(dist2); // coarse culling against bbox //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; STBTT_assert(i != 0); if (dist < min_dist) { // check position along line // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) float dx = x1-x0, dy = y1-y0; float px = x0-sx, py = y0-sy; // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve float t = -(px*dx + py*dy) / (dx*dx + dy*dy); if (t >= 0.0f && t <= 1.0f) min_dist = dist; } } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); // coarse culling against bbox to avoid computing cubic unnecessarily if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { int num=0; float ax = x1-x0, ay = y1-y0; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float mx = x0 - sx, my = y0 - sy; float res[3] = {0.f,0.f,0.f}; float px,py,t,it,dist2; float a_inv = precompute[i]; if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; if (a == 0.0) { // if a is 0, it's linear if (b != 0.0) { res[num++] = -c/b; } } else { float discriminant = b*b - 4*a*c; if (discriminant < 0) num = 0; else { float root = (float) STBTT_sqrt(discriminant); res[0] = (-b - root)/(2*a); res[1] = (-b + root)/(2*a); num = 2; // don't bother distinguishing 1-solution case, as code below will still work } } } else { float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; float d = (mx*ax+my*ay) * a_inv; num = stbtt__solve_cubic(b, c, d, res); } dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); if (dist2 < min_dist*min_dist) min_dist = (float) STBTT_sqrt(dist2); if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { t = res[0], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { t = res[1], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { t = res[2], it = 1.0f - t; px = it*it*x0 + 2*t*it*x1 + t*t*x2; py = it*it*y0 + 2*t*it*y1 + t*t*y2; dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); if (dist2 < min_dist * min_dist) min_dist = (float) STBTT_sqrt(dist2); } } } } if (winding == 0) min_dist = -min_dist; // if outside the shape, value is negative val = onedge_value + pixel_dist_scale * min_dist; if (val < 0) val = 0; else if (val > 255) val = 255; data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; } } STBTT_free(precompute, info->userdata); STBTT_free(verts, info->userdata); } return data; } STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) { return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); } STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) { STBTT_free(bitmap, userdata); } ////////////////////////////////////////////////////////////////////////////// // // font name matching -- recommended not to use this // // check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) { stbtt_int32 i=0; // convert utf16 to utf8 and compare the results while converting while (len2) { stbtt_uint16 ch = s2[0]*256 + s2[1]; if (ch < 0x80) { if (i >= len1) return -1; if (s1[i++] != ch) return -1; } else if (ch < 0x800) { if (i+1 >= len1) return -1; if (s1[i++] != 0xc0 + (ch >> 6)) return -1; if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; } else if (ch >= 0xd800 && ch < 0xdc00) { stbtt_uint32 c; stbtt_uint16 ch2 = s2[2]*256 + s2[3]; if (i+3 >= len1) return -1; c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; if (s1[i++] != 0xf0 + (c >> 18)) return -1; if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; s2 += 2; // plus another 2 below len2 -= 2; } else if (ch >= 0xdc00 && ch < 0xe000) { return -1; } else { if (i+2 >= len1) return -1; if (s1[i++] != 0xe0 + (ch >> 12)) return -1; if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; } s2 += 2; len2 -= 2; } return i; } static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) { return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); } // returns results in whatever encoding you request... but note that 2-byte encodings // will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) { stbtt_int32 i,count,stringOffset; stbtt_uint8 *fc = font->data; stbtt_uint32 offset = font->fontstart; stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); if (!nm) return NULL; count = ttUSHORT(fc+nm+2); stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { *length = ttUSHORT(fc+loc+8); return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); } } return NULL; } static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; stbtt_int32 count = ttUSHORT(fc+nm+2); stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { stbtt_uint32 loc = nm + 6 + 12 * i; stbtt_int32 id = ttUSHORT(fc+loc+6); if (id == target_id) { // find the encoding stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); // is this a Unicode encoding? if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { stbtt_int32 slen = ttUSHORT(fc+loc+8); stbtt_int32 off = ttUSHORT(fc+loc+10); // check if there's a prefix match stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); if (matchlen >= 0) { // check for target_id+1 immediately following, with same encoding & language if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { slen = ttUSHORT(fc+loc+12+8); off = ttUSHORT(fc+loc+12+10); if (slen == 0) { if (matchlen == nlen) return 1; } else if (matchlen < nlen && name[matchlen] == ' ') { ++matchlen; if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) return 1; } } else { // if nothing immediately following if (matchlen == nlen) return 1; } } } // @TODO handle other encodings } } return 0; } static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) { stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); stbtt_uint32 nm,hd; if (!stbtt__isfont(fc+offset)) return 0; // check italics/bold/underline flags in macStyle... if (flags) { hd = stbtt__find_table(fc, offset, "head"); if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; } nm = stbtt__find_table(fc, offset, "name"); if (!nm) return 0; if (flags) { // if we checked the macStyle flags, then just check the family and ignore the subfamily if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } else { if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; } return 0; } static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) { stbtt_int32 i; for (i=0;;++i) { stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); if (off < 0) return off; if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) return off; } } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, float pixel_height, unsigned char *pixels, int pw, int ph, int first_char, int num_chars, stbtt_bakedchar *chardata) { return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); } STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) { return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); } STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) { return stbtt_GetNumberOfFonts_internal((unsigned char *) data); } STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) { return stbtt_InitFont_internal(info, (unsigned char *) data, offset); } STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) { return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); } STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) { return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif #endif // STB_TRUETYPE_IMPLEMENTATION // FULL VERSION HISTORY // // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning // 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) // 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined // 1.21 (2019-02-25) fix warning // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix // 1.16 (2017-07-12) SDF support // 1.15 (2017-03-03) make more arguments const // 1.14 (2017-01-16) num-fonts-in-TTC function // 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts // 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual // 1.11 (2016-04-02) fix unused-variable warning // 1.10 (2016-04-02) allow user-defined fabs() replacement // fix memory leak if fontsize=0.0 // fix warning from duplicate typedef // 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges // 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges // 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; // allow PackFontRanges to pack and render in separate phases; // fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); // fixed an assert() bug in the new rasterizer // replace assert() with STBTT_assert() in new rasterizer // 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) // also more precise AA rasterizer, except if shapes overlap // remove need for STBTT_sort // 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC // 1.04 (2015-04-15) typo in example // 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes // 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ // 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match // non-oversampled; STBTT_POINT_SIZE for packed case only // 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling // 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) // 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID // 0.8b (2014-07-07) fix a warning // 0.8 (2014-05-25) fix a few more warnings // 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back // 0.6c (2012-07-24) improve documentation // 0.6b (2012-07-20) fix a few more warnings // 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, // stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty // 0.5 (2011-12-09) bugfixes: // subpixel glyph renderer computed wrong bounding box // first vertex of shape can be off-curve (FreeSans) // 0.4b (2011-12-03) fixed an error in the font baking example // 0.4 (2011-12-01) kerning, subpixel rendering (tor) // bugfixes for: // codepoint-to-glyph conversion using table fmt=12 // codepoint-to-glyph conversion using table fmt=4 // stbtt_GetBakedQuad with non-square texture (Zer) // updated Hello World! sample to use kerning and subpixel // fixed some warnings // 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) // userdata, malloc-from-userdata, non-zero fill (stb) // 0.2 (2009-03-11) Fix unsigned/signed char warnings // 0.1 (2009-03-09) First public release // /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
construct.ml
open Std open Typedtree let {Logger. log} = Logger.for_section "construct" type values_scope = Null | Local type what = Modtype | Mod exception Not_allowed of string exception Not_a_hole exception Modtype_not_found of what * string exception No_constraint let () = Location.register_error_of_exn (function | Not_a_hole -> Some (Location.error "Construct only works on holes.") | Modtype_not_found (Modtype, s) -> let txt = Format.sprintf "Module type not found: %s" s in Some (Location.error txt) | Modtype_not_found (Mod, s) -> let txt = Format.sprintf "Module not found: %s" s in Some (Location.error txt) | No_constraint -> Some (Location.error "Could not find a module type to construct from. \ Check that you used a correct constraint.") | _ -> None ) module Util = struct open Misc_utils.Path open Types let predef_types = let tbl = Hashtbl.create 14 in let () = let constant c = Ast_helper.Exp.constant c in let construct s = Ast_helper.Exp.construct (Location.mknoloc (Longident.Lident s)) None in let ident s = Ast_helper.Exp.ident (Location.mknoloc (Longident.Lident s)) in List.iter ~f:(fun (k, v) -> Hashtbl.add tbl k v) Parsetree.[ Predef.path_int, constant (Pconst_integer("0", None)) ; Predef.path_float, constant (Pconst_float("0.0", None)) ; Predef.path_char, constant (Pconst_char 'c') ; Predef.path_string, constant (Pconst_string("", Location.none, None)) ; Predef.path_bool, construct "true" ; Predef.path_unit, construct "()" ; Predef.path_exn, ident "exn" ; Predef.path_array, Ast_helper.Exp.array [] ; Predef.path_nativeint, constant (Pconst_integer("0", Some 'n')) ; Predef.path_int32, constant (Pconst_integer("0", Some 'l')) ; Predef.path_int64, constant (Pconst_integer("0", Some 'L')) ; Predef.path_lazy_t, Ast_helper.Exp.lazy_ (construct "()") ] in tbl let prefix env ~env_check path name = to_shortest_lid ~env ~env_check ~name path let var_of_id id = Location.mknoloc @@ Ident.name id let type_to_string t = Printtyp.type_expr (Format.str_formatter) t; Format.flush_str_formatter () let unifiable env type_expr type_expected = let snap = Btype.snapshot () in try Ctype.unify env type_expected type_expr |> ignore; Some snap with Ctype.Unify _ -> (* Unification failure *) Btype.backtrack snap; None let is_in_stdlib path = Path.head path |> Ident.name = "Stdlib" (** [find_values_for_type env typ] searches the environment [env] for {i values} with a return type compatible with [typ] *) let find_values_for_type env typ = let aux name path value_description acc = (* [check_type| checks return type compatibility and lists parameters *) let rec check_type type_expr params = let type_expr = Transient_expr.repr type_expr in (* TODO is this test general enough ? *) match unifiable env (Transient_expr.type_expr type_expr) typ with | Some snap -> (* This will be called multiple times so we need to backtrack See c-simple, test 6.2b for an example *) Btype.backtrack snap; Some params | None -> begin match type_expr.desc with | Tarrow (arg_label, _, te, _) -> check_type te (arg_label::params) | _ -> None end in (* TODO we should probably sort the results better *) match is_in_stdlib path, check_type value_description.val_type [] with | false, Some params -> Path.Map.add path (name, value_description, params) acc | _, _ -> acc in (* We look for values in the current scope and in local unonpend submodules. We also exclude the Stdlib modules from the search. *) let fold_values path acc = Env.fold_values aux path env acc in let init = fold_values None Path.Map.empty in Env.fold_modules (fun _name path _module_decl acc -> if not (is_in_stdlib path) && not (is_opened env path) then (* We ignore opened modules. That means that is a value of an opened module has been shadowed we won't suggest the one in the opened module. *) fold_values (Some (Untypeast.lident_of_path path)) acc else acc) None env init (** The idents_table is used to keep track of already used names when generating function arguments in the same expression *) let idents_table ~keywords = let table = Hashtbl.create 50 in (* We add keywords to the table so they are always numbered *) List.iter keywords ~f:(fun k -> Hashtbl.add table k (-1)); table (* Given a list [l] of n elements which are lists of choices, [combination l] is a list of all possible combinations of these choices (cartesian product). For example: let l = [["a";"b"];["1";"2"]; ["x"]];; combinations l;; - : string list list = [["a"; "1"; "x"]; ["b"; "1"; "x"]; ["a"; "2"; "x"]; ["b"; "2"; "x"]] If the input is the empty list, the result is the empty list singleton list. *) let combinations l = List.fold_left l ~init:[[]] ~f:(fun acc_l choices_for_arg_i -> List.fold_left choices_for_arg_i ~init:[] ~f:(fun acc choice_arg_i -> let choices = List.map acc_l ~f:(fun l -> List.rev (choice_arg_i :: l)) in List.rev_append acc choices)) (** [panache2 l1 l2] returns a new list containing an interleaving of the values in [l1] and [l2] *) let panache2 l1 l2 = let rec aux acc l1 l2 = match l1, l2 with | [], [] -> List.rev acc | tl, [] | [], tl -> List.rev_append acc tl | a::tl1, b::tl2 -> aux (a::b::acc) tl1 tl2 in aux [] l1 l2 (* Given a list [l] of n lists, [panache l] flattens the list by starting with the first element of each, then the second one etc. *) let panache l = List.fold_left ~init:[] ~f:panache2 l end module Gen = struct open Types (* [make_value] generates the PAST repr of a value applied to holes *) let make_value env (path, (name, _value_description, params)) = let open Ast_helper in let env_check = Env.find_value_by_name in let lid = Location.mknoloc (Util.prefix env ~env_check path name) in let params = List.map params ~f:(fun label -> label, Exp.hole ()) in if List.length params > 0 then Exp.(apply (ident lid) params) else Exp.ident lid (* We never perform deep search when constructing modules *) let rec module_ env = let open Ast_helper in function | Mty_ident path -> begin try let m = Env.find_modtype path env in match m.mtd_type with | Some t -> module_ env t | None -> raise Not_found with Not_found -> let name = Ident.name (Path.head path) in raise (Modtype_not_found (Modtype, name)) end | Mty_signature sig_items -> let env = Env.add_signature sig_items env in Mod.structure @@ structure env sig_items | Mty_functor (param, out) -> let param = match param with | Unit -> Parsetree.Unit | Named (id, in_) -> Parsetree.Named ( Location.mknoloc (Option.map ~f:Ident.name id), Ptyp_of_type.module_type in_) in Mod.functor_ param @@ module_ env out | Mty_alias path -> begin try let m = Env.find_module path env in module_ env m.md_type with Not_found -> let name = Ident.name (Path.head path) in raise (Modtype_not_found (Mod, name)) end | Mty_for_hole -> Mod.hole () and structure_item env = let open Ast_helper in function | Sig_value (id, _vd, _visibility) -> let vb = Vb.mk (Pat.var (Util.var_of_id id)) (Exp.hole ()) in Str.value Nonrecursive [ vb ] | Sig_type (id, type_declaration, rec_flag, _visibility) -> let td = Ptyp_of_type.type_declaration id type_declaration in let rec_flag = match rec_flag with | Trec_first | Trec_next -> Asttypes.Recursive | Trec_not -> Nonrecursive in (* mutually recursive types are really handled by [structure] *) Str.type_ rec_flag [td] | Sig_modtype (id, { mtd_type; _ }, _visibility) -> let mtd = Ast_helper.Mtd.mk ?typ:(Option.map ~f:Ptyp_of_type.module_type mtd_type) @@ Util.var_of_id id in Ast_helper.Str.modtype mtd | Sig_module (id, _, mod_decl, _, _) -> let module_binding = Ast_helper.Mb.mk (Location.mknoloc (Some (Ident.name id))) @@ module_ env mod_decl.md_type in Str.module_ module_binding | Sig_typext (id, ext_constructor, _, _) -> let lid = Untypeast.lident_of_path ext_constructor.ext_type_path |> Location.mknoloc in Str.type_extension @@ Ast_helper.Te.mk ~attrs:ext_constructor.ext_attributes ~params:[] ~priv:ext_constructor.ext_private lid [Ptyp_of_type.extension_constructor id ext_constructor] | Sig_class_type (id, _class_type_decl, _, _) -> let str = Format.asprintf "Construct does not handle class types yet. \ Please replace this comment by [%s]'s definition." (Ident.name id) in Str.text [ Docstrings.docstring str Location.none ] |> List.hd | Sig_class (id, _class_decl, _, _) -> let str = Format.asprintf "Construct does not handle classes yet. \ Please replace this comment by [%s]'s definition." (Ident.name id) in Str.text [ Docstrings.docstring str Location.none ] |> List.hd and structure env (items : Types.signature_item list) = List.map (Ptyp_of_type.group_items items) ~f:(function | Ptyp_of_type.Item item -> structure_item env item | Ptyp_of_type.Type (rec_flag, type_decls) -> Ast_helper.Str.type_ rec_flag type_decls) (* [expression values_scope ~depth env ty] generates a list of PAST expressions that could fill a hole of type [ty] in the environment [env]. [depth] regulates the deep construction of recursive values. If [values_scope] is set to [Local] the returned list will also contains local values to choose from *) let rec expression ~idents_table values_scope ~depth = let exp_or_hole env typ = if depth > 1 then (* If max_depth has not been reached we recurse *) expression ~idents_table values_scope ~depth:(depth - 1) env typ else (* else we return a hole *) [ Ast_helper.Exp.hole () ] in let arrow_rhs env typ = match (Transient_expr.repr typ).desc with | Tarrow _ -> expression ~idents_table values_scope ~depth env typ | _ -> exp_or_hole env typ in (* [make_arg] tries to provide a nice default name for function args *) let make_arg = let make_i n i = Hashtbl.replace idents_table n i; Printf.sprintf "%s_%i" n i in let uniq_name env n = let id = Ident.create_local n in try let i = Hashtbl.find idents_table n + 1 in make_i n i with Not_found -> try let _ = Env.find_value (Path.Pident id) env in make_i n 0 with Not_found -> Hashtbl.add idents_table n 0; n in fun env label ty -> let open Asttypes in match label with | Labelled s | Optional s -> (* Pun for labelled arguments *) Ast_helper.Pat.var ( Location.mknoloc s), s | Nolabel -> begin match get_desc ty with | Tconstr (path, _, _) -> let name = uniq_name env (Path.last path) in Ast_helper.Pat.var (Location.mknoloc name), name | _ -> Ast_helper.Pat.any (), "_" end in let constructor env type_expr path constrs = log ~title:"constructors" "[%s]" (String.concat ~sep:"; " (List.map constrs ~f:(fun c -> c.Types.cstr_name))); (* [make_constr] builds the PAST repr of a type constructor applied to holes *) let make_constr env path type_expr cstr_descr = let ty_args, ty_res, _ = Ctype.instance_constructor Keep_existentials_flexible cstr_descr in match Util.unifiable env type_expr ty_res with | Some snap -> let lid = Util.prefix env ~env_check:Env.find_constructor_by_name path cstr_descr.cstr_name |> Location.mknoloc in let args = List.map ty_args ~f:(exp_or_hole env) in let args_combinations = Util.combinations args in let exps = List.map args_combinations ~f:(function | [] -> None | [e] -> Some e | l -> Some (Ast_helper.Exp.tuple l)) in Btype.backtrack snap; List.filter_map exps ~f:(fun exp -> let exp = Ast_helper.Exp.construct lid exp in (* For gadts not all combinations will be valid. See Test 6.1b in c-simple.t for an example. We therefore check that constructed expressions can be typed. *) try Typecore.type_expression env exp |> ignore; Some exp with _ -> None) | None -> [] in List.map constrs ~f:(make_constr env path type_expr) |> Util.panache in let variant env _typ row_desc = let fields = List.filter ~f:(fun (_lbl, row_field) -> match row_field_repr row_field with | Rpresent _ | Reither (true, [], _) | Reither (false, [_], _) -> true | _ -> false) (row_fields row_desc) in match fields with | [] -> raise (Not_allowed "empty variant type") | row_descrs -> List.map row_descrs ~f:(fun (lbl, row_field) -> (match row_field_repr row_field with | Reither (false, [ty], _) | Rpresent (Some ty) -> List.map ~f:(fun s -> Some s) (exp_or_hole env ty) | _ -> [None]) |> List.map ~f:(fun e -> Ast_helper.Exp.variant lbl e) ) |> List.flatten in let record env typ path labels = log ~title:"record labels" "[%s]" (String.concat ~sep:"; " (List.map labels ~f:(fun l -> l.Types.lbl_name))); let labels = List.map labels ~f:(fun ({ lbl_name; _ } as lbl) -> let _, arg, res = Ctype.instance_label true lbl in Ctype.unify env res typ ; let lid = Util.prefix env ~env_check:Env.find_label_by_name path lbl_name |> Location.mknoloc in let exprs = exp_or_hole env arg in lid, exprs) in let lbl_lids, lbl_exprs = List.split labels in Util.combinations lbl_exprs |> List.map ~f:(fun lbl_exprs -> let labels = List.map2 lbl_lids lbl_exprs ~f:(fun lid exp -> (lid, exp)) in Ast_helper.Exp.record labels None) in (* Given a typed hole, there is two possible forms of constructions: - Use the type's definition to propose the correct type constructors, - Look for values in the environment with compatible return type. *) fun env typ -> log ~title:"construct expr" "Looking for expressions of type %s" (Util.type_to_string typ); let rtyp = Ctype.full_expand ~may_forget_scope:true env typ in let constructed_from_type = match get_desc rtyp with | Tlink _ | Tsubst _ -> assert false | Tpoly (texp, _) -> (* We are not going "deeper" so we don't call [exp_or_hole] here *) expression ~idents_table values_scope ~depth env texp | Tunivar _ | Tvar _ -> [ ] | Tconstr (path, [texp], _) when path = Predef.path_lazy_t -> (* Special case for lazy *) let exps = exp_or_hole env texp in List.map exps ~f:Ast_helper.Exp.lazy_ | Tconstr (path, _params, _) -> (* If this is a "basic" type we propose a default value *) begin try [ Hashtbl.find Util.predef_types path ] with Not_found -> let def = Env.find_type_descrs path env in match def with | Type_variant (constrs, _) -> constructor env rtyp path constrs | Type_record (labels, _) -> record env rtyp path labels | Type_abstract | Type_open -> [] end | Tarrow (label, tyleft, tyright, _) -> let argument, name = make_arg env label tyleft in let value_description = { val_type = tyleft; val_kind = Val_reg; val_loc = Location.none; val_attributes = []; val_uid = Uid.mk ~current_unit:(Env.get_unit_name ()); } in let env = Env.add_value (Ident.create_local name) value_description env in let exps = arrow_rhs env tyright in List.map exps ~f:(Ast_helper.Exp.fun_ label None argument) | Ttuple types -> let choices = List.map types ~f:(exp_or_hole env) |> Util.combinations in List.map choices ~f:Ast_helper.Exp.tuple | Tvariant row_desc -> variant env rtyp row_desc | Tpackage (path, lids_args) -> begin let open Ast_helper in try let ty = Typemod.modtype_of_package env Location.none path lids_args in let ast = Exp.constraint_ (Exp.pack (module_ env ty)) (Ptyp_of_type.core_type typ) in [ ast ] with Typemod.Error _ -> let name = Ident.name (Path.head path) in raise (Modtype_not_found (Modtype, name)) end | Tobject (fields, _) -> let rec aux acc fields = match get_desc fields with | Tnil -> acc | Tvar _ | Tunivar _ -> acc | Tfield ("*dummy method*", _, _, fields) -> aux acc fields | Tfield (name, _, type_expr, fields) -> let exprs = exp_or_hole env type_expr |> List.map ~f:(fun expr -> let open Ast_helper in Cf.method_ (Location.mknoloc name) Asttypes.Public @@ Ast_helper.Cf.concrete Asttypes.Fresh expr) in aux (exprs :: acc) fields | _ -> failwith @@ Format.asprintf "Unexpected type constructor in fields list: %a" Printtyp.type_expr fields in let all_fields = aux [] fields |> Util.combinations in List.map all_fields ~f:(fun fields -> let open Ast_helper in Exp.object_ @@ Ast_helper.Cstr.mk (Pat.any ()) fields) | Tfield _ | Tnil -> failwith "Found a field type outside an object" in let matching_values = if values_scope = Local then Path.Map.bindings (Util.find_values_for_type env typ) |> List.map ~f:(make_value env) else [] in List.append constructed_from_type matching_values end let needs_parentheses e = match e.Parsetree.pexp_desc with | Pexp_fun _ | Pexp_lazy _ | Pexp_apply _ | Pexp_variant (_, Some _) | Pexp_construct (_, Some _) -> true | _ -> false let to_string_with_parentheses exp = let f : _ format6 = if needs_parentheses exp then "(%a)" else "%a" in Format.asprintf f Pprintast.expression exp let node ?(depth = 1) ~keywords ~values_scope node = match node with | Browse_raw.Expression { exp_type; exp_env; _ } -> let idents_table = Util.idents_table ~keywords in Gen.expression ~idents_table values_scope ~depth exp_env exp_type |> List.map ~f:to_string_with_parentheses | Browse_raw.Module_expr { mod_desc = Tmod_constraint _ ; mod_type; mod_env; _ } | Browse_raw.Module_expr { mod_desc = Tmod_apply _; mod_type; mod_env; _ } -> let m = Gen.module_ mod_env mod_type in [ Format.asprintf "%a" Pprintast.module_expr m ] | Browse_raw.Module_expr _ | Browse_raw.Module_binding _ -> (* Constructible modules have an explicit constraint or are functor applications. In other cases we do not know what to construct. *) raise No_constraint | _ -> raise Not_a_hole
rts.h
#pragma once #include<inttypes.h> #include<stdlib.h> #include<stdio.h> #include"sail.h" /* * This function should be called whenever a pattern match failure * occurs. Pattern match failures are always fatal. */ void sail_match_failure(sail_string msg); /* * sail_assert implements the assert construct in Sail. If any * assertion fails we immediately exit the model. */ unit sail_assert(bool b, sail_string msg); unit sail_exit(unit); /* * sail_get_verbosity reads a 64-bit value that the C runtime allows you to set * on the command line. * The intention is that you can use individual bits to turn on/off different * pieces of debugging output. */ fbits sail_get_verbosity(const unit u); /* * Put processor to sleep until an external device calls wakeup_request(). */ unit sleep_request(const unit u); /* * Stop processor sleeping. * (Typically called when a device generates an interrupt.) */ unit wakeup_request(const unit u); /* * Test whether processor is sleeping. * (Typically used to disable execution of instructions.) */ bool sleeping(const unit u); /* ***** Memory builtins ***** */ void write_mem(uint64_t, uint64_t); uint64_t read_mem(uint64_t); // These memory builtins are intended to match the semantics for the // __ReadRAM and __WriteRAM functions in ASL. bool write_ram(const sail_int addr_size, // Either 32 or 64 const sail_int data_size_mpz, // Number of bytes const lbits hex_ram, // Currently unused const lbits addr_bv, const lbits data); void read_ram(lbits *data, const sail_int addr_size, const sail_int data_size_mpz, const lbits hex_ram, const lbits addr_bv); sbits fast_read_ram(const int64_t data_size, const uint64_t addr_bv); unit write_tag_bool(const fbits, const bool); bool read_tag_bool(const fbits); unit load_raw(fbits addr, const sail_string file); void load_image(char *); /* * Functions for counting and limiting cycles */ // increment cycle count and test if over limit bool cycle_limit_reached(const unit); // increment cycle count and abort if over unit cycle_count(const unit); // read cycle count sail_int get_cycle_count(const unit); /* * Functions to get info from ELF files. */ sail_int elf_entry(const unit u); sail_int elf_tohost(const unit u); int process_arguments(int, char**); /* * setup_rts and cleanup_rts are responsible for calling setup_library * and cleanup_library in sail.h. */ void setup_rts(void); void cleanup_rts(void); unit z__SetConfig(sail_string, sail_int); unit z__ListConfig(const unit u);
bechamel_html.ml
(* [string_find str target] returns [None] if the string [target] cannot be find in [str] and [Some i] if the first occurence of [target] begins at position [i]. *) let string_find str target = let exception Not_equal in let substring_equal a a_i b = String.iteri (fun i c -> if c <> a.[a_i + i] then raise Not_equal) b in let rec loop i = match String.index_from_opt str i target.[0] with | None -> None | Some i when String.length str - i < String.length target -> None | Some i -> ( match substring_equal str i target with | exception Not_equal -> loop (i + 1) | () -> Some i) in if String.length target = 0 then None else loop 0 let stdin_to_stdout () = try while true do print_endline (read_line ()) done with End_of_file -> () (* [cut ~error_msg str sep] cuts the string [str] into the two parts before and after [sep]. If [sep] not appears in [str] an error is raised with the text [error_msg]. *) let cut ~error_msg str separator = match string_find str separator with | None -> failwith error_msg | Some i -> let ends = i + String.length separator in (String.sub str 0 i, String.sub str ends (String.length str - ends)) (* [cut_html html] cuts in 3 parts: the part before "/*style*/", the part between "/*style*/" and "//js_script" and the rest of the text *) let cut_html html = let sep1 = "/*style*/" in let sep2 = "//js_script" in let part1, rest = cut ~error_msg:("Separator " ^ sep1 ^ " not found in html file.") html sep1 in let part2, part3 = cut ~error_msg:("Separator " ^ sep2 ^ " not found in html file.") rest sep2 in (part1, part2, part3) (* Print the java script file, including the json data passed as stdin. *) let print_js_script () = (* Read first line so we don't show [head] if user forgot to redirect its json file and if it's already end of input, it will be an explicit uncaught exception instead of generating an invalid HTML file *) let first_line = read_line () in let js = Js_file.data in let separator = "//BECHAMEL_CONTENTS//" in let head, tail = cut ~error_msg:"Separator not found in js file" js separator in print_string head; print_string "contents = "; print_endline first_line; stdin_to_stdout (); print_string tail let () = let html = Html_file.data in let css = Css_file.data in let html1, html2, html3 = cut_html html in print_string html1; print_string css; print_string html2; print_js_script (); print_string html3
(* [string_find str target] returns [None] if the string [target] cannot be find in [str] and [Some i] if the first occurence of [target] begins at position [i]. *)
test_html_writer.ml
(* This file is part of Markup.ml, released under the MIT license. See LICENSE.md for details, or visit https://github.com/aantron/markup.ml. *) open OUnit2 open Test_support open Markup__Common let expect id signals strings = let _, iterate, ended = expect_strings id strings in signals |> Markup__Kstream.of_list |> Markup__Html_writer.write |> iter iterate; ended () let tests = [ ("html.writer.empty" >:: fun _ -> expect "empty" [] []); ("html.writer.text" >:: fun _ -> expect "text" [`Text ["foo"]] [S "foo"]; expect "adjacent text" [`Text ["foo"]; `Text ["bar"]] [S "foo"; S "bar"]; expect "empty text" [`Text [""]] []); ("html.writer.text-escaping" >:: fun _ -> expect "text escaping" [`Text ["<foo&bar>\xc2\xa0baz"]] [S "&lt;foo&amp;bar&gt;&nbsp;baz"]); ("html.writer.doctype" >:: fun _ -> let doctype = {doctype_name = Some "html"; public_identifier = None; system_identifier = None; raw_text = None; force_quirks = false} in expect "doctype" [`Doctype doctype] [S "<!DOCTYPE html>"]; let doctype = {doctype with doctype_name = None} in expect "bad doctype" [`Doctype doctype] [S "<!DOCTYPE>"]); ("html.writer.comment" >:: fun _ -> expect "comment" [`Comment "foo"] [S "<!--"; S "foo"; S "-->"]); ("html.writer.processing-instruction" >:: fun _ -> expect "processing instruction" [`PI ("foo", "bar")] [S "<?"; S "foo"; S " "; S "bar"; S ">"]); ("html.writer.xml-declaration" >:: fun _ -> let xml = {version = "1.0"; encoding = None; standalone = None} in expect "xml declaration" [`Xml xml] []); ("html.writer.element" >:: fun _ -> expect "element" [`Start_element ((html_ns, "p"), []); `End_element] [S "<"; S "p"; S ">"; S "</"; S "p"; S ">"]); ("html.writer.void-element" >:: fun _ -> expect "void element" [`Start_element ((html_ns, "head"), []); `Start_element ((html_ns, "meta"), []); `End_element; `Start_element ((html_ns, "meta"), []); `End_element; `End_element] [S "<"; S "head"; S ">"; S "<"; S "meta"; S ">"; S "<"; S "meta"; S ">"; S "</"; S "head"; S ">"]); ("html.writer.void-element-with-content" >:: fun _ -> expect "void element with content" [`Start_element ((html_ns, "head"), []); `Start_element ((html_ns, "meta"), []); `Text ["foo"]; `End_element; `Start_element ((html_ns, "meta"), []); `End_element; `End_element] [S "<"; S "head"; S ">"; S "<"; S "meta"; S ">"; S "foo"; S "</"; S "meta"; S ">"; S "<"; S "meta"; S ">"; S "</"; S "head"; S ">"]); ("html.writer.pre" >:: fun _ -> expect "pre" [`Start_element ((html_ns, "pre"), []); `Text ["\nfoo"]; `End_element] [S "<"; S "pre"; S ">"; S "\n"; S "\nfoo"; S "</"; S "pre"; S ">"]); ("html.writer.attributes" >:: fun _ -> expect "attributes" [`Start_element ((html_ns, "p"), [("", "id"), "foo"; ("", "class"), "bar"]); `End_element] [S "<"; S "p"; S " "; S "id"; S "=\""; S "foo"; S "\""; S " "; S "class"; S "=\""; S "bar"; S "\""; S ">"; S "</"; S "p"; S ">"]); ("html.writer.attribute-escaping" >:: fun _ -> expect "attribute escaping" [`Start_element ((html_ns, "p"), [("", "id"), "foo<>\"&\xc2\xa0"]); `End_element] [S "<"; S "p"; S " "; S "id"; S "=\""; S "foo<>&quot;&amp;&nbsp;"; S "\""; S ">"; S "</"; S "p"; S ">"]); ("html.writer.foreign-element" >:: fun _ -> expect "foreign element" [`Start_element ((svg_ns, "use"), [(xlink_ns, "href"), "#foo"]); `End_element] [S "<"; S "use"; S " "; S "xlink:href"; S "=\""; S "#foo"; S "\""; S ">"; S "</"; S "use"; S ">"]); ("html.writer.script-element" >:: fun _ -> expect "script element" [ `Start_element ((html_ns, "script"), []); `Text ["true && false"]; `End_element ] [ S "<"; S "script"; S ">"; S "true && false"; S "</"; S "script"; S ">" ]); ]
(* This file is part of Markup.ml, released under the MIT license. See LICENSE.md for details, or visit https://github.com/aantron/markup.ml. *)
dune
(alias (name runtest) (deps rpc_test.exe) (action (bash "./rpc_test.exe regression"))) (executables (names rpc_test rpc_latency_test test_low_latency_transport_close) (libraries async async_rpc_kernel async_rpc core_unix.command_unix core cpu_usage jane async_kernel.limiter_async netkit netkit_rpc netkit_sockets) (preprocess (pps ppx_jane)))
editor.ml
(**************************************************************************) (* Lablgtk - Applications *) (* *) (* * You are free to do anything you want with this code as long *) (* as it is for personal use. *) (* *) (* * Redistribution can only be "as is". Binary distribution *) (* and bug fixes are allowed, but you cannot extensively *) (* modify the code without asking the authors. *) (* *) (* The authors may choose to remove any of the above *) (* restrictions on a per request basis. *) (* *) (* Authors: *) (* Jacques Garrigue <garrigue@kurims.kyoto-u.ac.jp> *) (* Benjamin Monate <Benjamin.Monate@free.fr> *) (* Olivier Andrieu <oandrieu@nerim.net> *) (* Jun Furuse <Jun.Furuse@inria.fr> *) (* Hubert Fauque <hubert.fauque@wanadoo.fr> *) (* Koji Kagawa <kagawa@eng.kagawa-u.ac.jp> *) (* *) (**************************************************************************) (* $Id$ *) open StdLabels open GMain class editor ?packing ?show () = object (self) val view = GText.view ?packing ?show () val mutable filename = None method view = view method buffer = view#buffer method load_file name = try let b = Buffer.create 1024 in File.with_file name ~f:(File.input_channel b); let s = Glib.Convert.locale_to_utf8 (Buffer.contents b) in let n_buff = GText.buffer ~text:s () in Lexical.init_tags n_buff; Lexical.tag n_buff; view#set_buffer n_buff; filename <- Some name; n_buff#place_cursor n_buff#start_iter with exn -> prerr_endline ("Load failed: " ^ Printexc.to_string exn) method open_file () = File.dialog ~title:"Open" ~callback:self#load_file () method save_dialog () = File.dialog ~title:"Save" ?filename ~callback:(fun file -> self#output ~file) () method save_file () = match filename with Some file -> self#output ~file | None -> self#save_dialog () method output ~file = try if Sys.file_exists file then Sys.rename file (file ^ "~"); let s = view#buffer#get_text () in let oc = open_out file in output_string oc (Glib.Convert.locale_from_utf8 s); close_out oc; filename <- Some file with _ -> prerr_endline "Save failed" initializer Lexical.init_tags view#buffer; view#buffer#connect#after#insert_text ~callback: begin fun it s -> let start = it#backward_chars (String.length s) in Lexical.tag view#buffer ~start:(start#set_line_index 0) ~stop:it#forward_to_line_end; end; view#buffer#connect#after#delete_range ~callback: begin fun ~start ~stop -> let start = start#set_line_index 0 and stop = start#forward_to_line_end in Lexical.tag view#buffer ~start ~stop end; view#misc#modify_font_by_name "monospace"; view#misc#set_size_chars ~width:80 ~height:25 ~lang:"C" (); () end open GdkKeysyms class editor_window ?(show=false) () = let window = GWindow.window ~title:"Program Editor" () in let vbox = GPack.vbox ~packing:window#add () in let menubar = GMenu.menu_bar ~packing:vbox#pack () in let factory = new GMenu.factory menubar in let accel_group = factory#accel_group and file_menu = factory#add_submenu "File" and edit_menu = factory#add_submenu "Edit" and comp_menu = factory#add_submenu "Compiler" in let sw = GBin.scrolled_window ~hpolicy:`AUTOMATIC ~packing:vbox#add () in let editor = new editor ~packing:sw#add () in object (self) inherit GObj.widget window#as_widget method window = window method editor = editor method show = window#show initializer window#connect#destroy ~callback:(fun () -> Gc.full_major(); Main.quit()); let factory = new GMenu.factory file_menu ~accel_group in factory#add_item "Open..." ~key:_O ~callback:editor#open_file; factory#add_item "Save..." ~key:_S ~callback:editor#save_file; factory#add_item "Shell" ~callback:(fun () -> Shell.f ~prog:"ocaml" ~title:"Objective Caml Shell"); factory#add_separator (); factory#add_item "Quit" ~key:_Q ~callback:window#destroy; let factory = new GMenu.factory edit_menu ~accel_group in factory#add_item "Copy" ~key:_C ~callback: (fun () -> editor#buffer#copy_clipboard GMain.clipboard); factory#add_item "Cut" ~key:_X ~callback: (fun () -> editor#buffer#cut_clipboard GMain.clipboard); factory#add_item "Paste" ~key:_V ~callback: (fun () -> editor#buffer#paste_clipboard GMain.clipboard); factory#add_separator (); factory#add_check_item "Word wrap" ~active:false ~callback: (fun b -> editor#view#set_wrap_mode (if b then `WORD else `NONE)); factory#add_check_item "Read only" ~active:false ~callback:(fun b -> editor#view#set_editable (not b)); let factory = new GMenu.factory comp_menu ~accel_group in factory#add_item "Lex" ~key:_L ~callback:(fun () -> Lexical.tag editor#buffer); window#add_accel_group accel_group; if show then self#show (); end let _ = Main.init (); if Array.length Sys.argv >= 2 && Sys.argv.(1) = "-shell" then Shell.f ~prog:"ocaml" ~title:"Objective Caml Shell" else ignore (new editor_window ~show:true ()); Main.main ()
(**************************************************************************) (* Lablgtk - Applications *) (* *) (* * You are free to do anything you want with this code as long *) (* as it is for personal use. *) (* *) (* * Redistribution can only be "as is". Binary distribution *) (* and bug fixes are allowed, but you cannot extensively *) (* modify the code without asking the authors. *) (* *) (* The authors may choose to remove any of the above *) (* restrictions on a per request basis. *) (* *) (* Authors: *) (* Jacques Garrigue <garrigue@kurims.kyoto-u.ac.jp> *) (* Benjamin Monate <Benjamin.Monate@free.fr> *) (* Olivier Andrieu <oandrieu@nerim.net> *) (* Jun Furuse <Jun.Furuse@inria.fr> *) (* Hubert Fauque <hubert.fauque@wanadoo.fr> *) (* Koji Kagawa <kagawa@eng.kagawa-u.ac.jp> *) (* *) (**************************************************************************)
test.mli
type packed = V : ([ `Init ] -> unit -> 'a) -> packed module Elt : sig type t val unsafe_make : name:string -> (unit -> 'a) Staged.t -> t val key : t -> int val name : t -> string val fn : t -> packed end type t type fmt_indexed = (string -> int -> string, Format.formatter, unit, string) format4 type fmt_grouped = (string -> string -> string, Format.formatter, unit, string) format4 val make : name:string -> (unit -> 'a) Staged.t -> t (** [make ~name fn] is a naming benchmark measuring [fn]. [fn] can be constructed with {!Staged.stage}: {[ let write = Test.make ~name:"unix-write" (Staged.stage @@ fun () -> Unix.write Unix.stdout "Hello World!") ]} *) val make_indexed : name:string -> ?fmt:fmt_indexed -> args:int list -> (int -> (unit -> 'a) Staged.t) -> t (** [make_indexed ~name ~fmt ~args fn] is naming benchmarks indexed by an argument (by [args]). Name of each benchmark is [Fmt.strf fmt name arg] (default to ["%s:%d"]). {[ let make_list words = Staged.stage @@ fun () -> let rec go n acc = if n = 0 then acc else go (n - 1) (n :: acc) in go ((words / 3) + 1) [] let test = make_indexed ~name:"make_list" ~args:[ 0; 10; 100; 100 ] make_list ]} This kind of test is helpful to see results of the {b same} implementation with differents arguments (indexed by the given [int]). *) val make_grouped : name:string -> ?fmt:fmt_grouped -> t list -> t (** [make_grouped ~name ~fmt tests] is naming benchmarks. Name of each benchmark is [Fmt.strf fmt name arg] (default to [%s/%s]). {[ let f0 = Test.make ~name:"fib1" ... ;; let f1 = Test.make ~name:"fib0" ... ;; let test = Test.make_grouped ~name:"fibonacci" [ f0; f1; ] ;; ]} This kind of test is helpful to compare results betwen many implementations. *) val name : t -> string (** [name t] returns the name of the test. *) val names : t -> string list (** [names t] returns names of sub-tests of [t] (such as {i indexed} tests or {i grouped} tests). *) val elements : t -> Elt.t list (** [elements t] returns all measuring functions of [t]. *) val expand : t list -> Elt.t list
visitor_js.ml
open OCaml open Ast_js (* generated by ocamltarzan with: camlp4o -o /tmp/yyy.ml -I pa/ pa_type_conv.cmo pa_visitor.cmo pr_o.cmo /tmp/xxx.ml *) (* Disable warnings against unused variables *) [@@@warning "-26"] (*****************************************************************************) (* Prelude *) (*****************************************************************************) (* hooks *) type visitor_in = { kexpr : (expr -> unit) * visitor_out -> expr -> unit; kstmt : (stmt -> unit) * visitor_out -> stmt -> unit; ktop : (a_toplevel -> unit) * visitor_out -> a_toplevel -> unit; kprop : (property -> unit) * visitor_out -> property -> unit; kparam : (parameter_classic -> unit) * visitor_out -> parameter_classic -> unit; kinfo : (tok -> unit) * visitor_out -> tok -> unit; } and visitor_out = any -> unit let default_visitor = { kexpr = (fun (k, _) x -> k x); kstmt = (fun (k, _) x -> k x); ktop = (fun (k, _) x -> k x); kprop = (fun (k, _) x -> k x); kparam = (fun (k, _) x -> k x); kinfo = (fun (k, _) x -> k x); } let v_id _ = () let (mk_visitor : visitor_in -> visitor_out) = fun vin -> let rec v_info x = let k x = match x with | { Parse_info.token = _v_pinfox; transfo = _v_transfo } -> (* let arg = Parse_info.v_pinfo v_pinfox in let arg = v_unit v_comments in let arg = Parse_info.v_transformation v_transfo in *) () in vin.kinfo (k, all_functions) x (* start of auto generation *) and v_tok v = v_info v and v_wrap : 'a. ('a -> unit) -> 'a wrap -> unit = fun of_a (v1, v2) -> let v1 = of_a v1 and v2 = v_info v2 in () and v_bracket : 'a. ('a -> unit) -> 'a bracket -> unit = fun of_a (v1, v2, v3) -> let v1 = v_info v1 and v2 = of_a v2 and v3 = v_info v3 in () and v_name v = v_wrap v_string v and v_ident x = v_name x and v_filename v = v_wrap v_string v and v_special = function | UseStrict -> () | Null -> () | Undefined -> () | This -> () | Super -> () | Require -> () | Exports -> () | Module -> () | Define -> () | Arguments -> () | NewTarget -> () | Eval -> () | Seq -> () | Typeof -> () | Instanceof -> () | In -> () | Delete -> () | Void -> () | Spread -> () | Yield -> () | YieldStar -> () | Await -> () | Encaps v1 -> let v1 = v_bool v1 in () | ArithOp v -> let v = v_arith_op v in () | IncrDecr v -> let v = v_inc_dec v in () and v_inc_dec _ = () and v_arith_op _ = () and v_property_name = function | PN v1 -> let v1 = v_name v1 in () | PN_Computed v1 -> let v1 = v_expr v1 in () and v_label v = v_wrap v_string v and v_xml_attribute v = match v with | XmlAttr (v1, t, v2) -> v_ident v1; v_tok t; v_xml_attr v2 | XmlAttrExpr v -> v_bracket v_expr v | XmlEllipsis v -> v_tok v and v_xml { xml_kind = v_xmlkind; xml_attrs = v_xml_attrs; xml_body = vv_xml_body } = let v_xmlkind = v_xml_kind v_xmlkind in let v_xml_attrs = v_list v_xml_attribute v_xml_attrs in let vv_xml_body = v_list v_xml_body vv_xml_body in () and v_xml_attr v = v_expr v and v_xml_body = function | XmlText v1 -> let v1 = v_wrap v_string v1 in () | XmlExpr v1 -> let v1 = v_bracket (v_option v_expr) v1 in () | XmlXml v1 -> let v1 = v_xml v1 in () and v_xml_kind = function | XmlClassic (v0, v1, v2, v3) -> v_tok v0; v_ident v1; v_tok v2; v_tok v3 | XmlSingleton (v0, v1, v2) -> v_tok v0; v_ident v1; v_tok v2 | XmlFragment (v1, v2) -> v_tok v1; v_tok v2 and v_todo_category v1 = v_wrap v_string v1 and v_expr (x : expr) = (* tweak *) let k x = match x with | ObjAccessEllipsis (v1, v2) -> v_expr v1; v_tok v2 | Cast (v1, v2, v3) -> v_expr v1; v_tok v2; v_type_ v3 | TypeAssert (v1, v2, v3) -> v_expr v1; v_tok v2; v_type_ v3 | ExprTodo (v1, v2) -> v_todo_category v1; v_list v_expr v2 | Xml v1 -> let v1 = v_xml v1 in () | L x -> ( match x with | Bool v1 -> let v1 = v_wrap v_bool v1 in () | Num v1 -> let v1 = v_wrap v_id v1 in () | String v1 -> let v1 = v_wrap v_string v1 in () | Regexp (v1, v2) -> let v1 = v_bracket (v_wrap v_string) v1 in let v2 = v_option (v_wrap v_string) v2 in ()) | Id v1 -> let v1 = v_name v1 in () | IdSpecial v1 -> let v1 = v_wrap v_special v1 in () | Assign (v1, v2, v3) -> let v1 = v_expr v1 and v2 = v_tok v2 and v3 = v_expr v3 in () | ArrAccess (v1, v2) -> let v1 = v_expr v1 and v2 = v_bracket v_expr v2 in () | Obj v1 -> let v1 = v_obj_ v1 in () | Ellipsis v1 -> let v1 = v_tok v1 in () | DeepEllipsis v1 -> let v1 = v_bracket v_expr v1 in () | TypedMetavar (v1, t, v2) -> let v1 = v_ident v1 and v2 = v_type_ v2 in let t = v_tok t in () | Class (v1, v2) -> let v1 = v_class_definition v1 in let v2 = v_option v_name v2 in () | ObjAccess (v1, dot, v2) -> let v1 = v_expr v1 and v2 = v_property_name v2 in let t = v_dot_operator dot in () | Fun (v1, v2) -> let v1 = v_function_definition v1 and v2 = v_option v_name v2 in () | Apply (v1, v2) -> let v1 = v_expr v1 and v2 = v_bracket (v_list v_expr) v2 in () | New (t, v1, v2) -> let t = v_tok t in let v1 = v_expr v1 and v2 = v_bracket (v_list v_expr) v2 in () | Arr v1 -> let v1 = v_bracket (v_list v_expr) v1 in () | Conditional (v1, v2, v3) -> let v1 = v_expr v1 and v2 = v_expr v2 and v3 = v_expr v3 in () in vin.kexpr (k, all_functions) x and v_stmt x = let k x = match x with | StmtTodo (v1, v2) -> v_todo_category v1; v_list v_any v2 | M v1 -> let v1 = v_module_directive v1 in () | DefStmt v1 -> let v1 = v_def v1 in () | Block v1 -> let v1 = v_bracket (v_list v_stmt) v1 in () | ExprStmt (v1, t) -> let v1 = v_expr v1 in let t = v_tok t in () | If (t, v1, v2, v3) -> let t = v_tok t in let v1 = v_expr v1 and v2 = v_stmt v2 and v3 = v_option v_stmt v3 in () | Do (t, v1, v2) -> let t = v_tok t in let v1 = v_stmt v1 and v2 = v_expr v2 in () | While (t, v1, v2) -> let t = v_tok t in let v1 = v_expr v1 and v2 = v_stmt v2 in () | For (t, v1, v2) -> let t = v_tok t in let v1 = v_for_header v1 and v2 = v_stmt v2 in () | Switch (v0, v1, v2) -> let v0 = v_tok v0 in let v1 = v_expr v1 and v2 = v_list v_case v2 in () | Continue (t, v1, sc) -> let t = v_tok t in let v1 = v_option v_label v1 in v_tok sc | Break (t, v1, sc) -> let t = v_tok t in let v1 = v_option v_label v1 in v_tok sc | Return (t, v1, sc) -> let t = v_tok t in let v1 = v_option v_expr v1 in v_tok sc | Label (v1, v2) -> let v1 = v_label v1 and v2 = v_stmt v2 in () | Throw (t, v1, sc) -> let t = v_tok t in let v1 = v_expr v1 in v_tok sc | Try (t, v1, v2, v3) -> let t = v_tok t in let v1 = v_stmt v1 and v2 = v_option v_catch_block v2 and v3 = v_option v_finally v3 in () | With (v1, v2, v3) -> v_tok v1; v_expr v2; v_stmt v3 in vin.kstmt (k, all_functions) x and v_finally x = v_tok_and_stmt x and v_catch_block = function | BoundCatch (t, v1, v2) -> let t = v_tok t and v1 = v_expr v1 and v2 = v_stmt v2 in () | UnboundCatch (t, v1) -> let t = v_tok t and v1 = v_stmt v1 in () and v_tok_and_stmt (t, v) = let t = v_tok t in let v = v_stmt v in () and v_for_header = function | ForEllipsis v1 -> v_tok v1 | ForClassic (v1, v2, v3) -> let v1 = v_either (v_list v_var) v_expr v1 and v2 = v_option v_expr v2 and v3 = v_option v_expr v3 in () | ForIn (v1, t, v2) | ForOf (v1, t, v2) -> let t = v_tok t in let v1 = v_either v_var v_expr v1 and v2 = v_expr v2 in () and v_case = function | Case (t, v1, v2) -> let t = v_tok t in let v1 = v_expr v1 and v2 = v_stmt v2 in () | Default (t, v1) -> let t = v_tok t in let v1 = v_stmt v1 in () and v_dot_operator _ = () and v_resolved_name _ = () and v_def (ent, defkind) = v_entity ent; v_definition_kind defkind and v_entity { name; attrs } = v_ident name; v_list v_attribute attrs and v_definition_kind = function | FuncDef def -> v_function_definition def | ClassDef def -> v_class_definition def | VarDef def -> v_variable_definition def | DefTodo (v1, v2) -> v_todo_category v1; v_list v_any v2 and v_var (ent, def) = v_entity ent; v_variable_definition def and v_variable_definition { v_kind = v_v_kind; v_init = v_v_init; v_type = vt } = let arg = v_wrap v_var_kind v_v_kind in let arg = v_option v_expr v_v_init in v_option v_type_ vt; () and v_var_kind = function | Var -> () | Let -> () | Const -> () and v_function_definition { f_attrs = v_f_props; f_params = v_f_params; f_body = v_f_body; f_rettype; f_kind; } = v_wrap v_function_kind f_kind; let arg = v_list v_attribute v_f_props in let arg = v_list v_parameter_binding v_f_params in let arg = v_stmt v_f_body in v_option v_type_ f_rettype; () and v_function_kind _ = () and v_parameter_binding = function | ParamClassic v1 -> let v1 = v_parameter v1 in () | ParamPattern v1 -> v_pattern v1 | ParamEllipsis v1 -> let v1 = v_tok v1 in () and v_pattern x = v_expr x and v_parameter x = let k x = match x with | { p_name = v_p_name; p_default = v_p_default; p_dots = v_p_dots; p_type; p_attrs; } -> let arg = v_name v_p_name in let arg = v_option v_expr v_p_default in let arg = v_option v_tok v_p_dots in v_option v_type_ p_type; v_list v_attribute p_attrs; () in vin.kparam (k, all_functions) x and v_dotted_ident xs = v_list v_ident xs and v_argument x = v_expr x and v_attribute = function | KeywordAttr x -> v_keyword_attribute x | NamedAttr (v1, v2, v3) -> v_tok v1; v_dotted_ident v2; v_option (v_bracket (v_list v_argument)) v3 and v_fun_prop x = v_keyword_attribute x and v_keyword_attribute _ = () and v_class_kind _ = () and v_parent = function | Common.Left e -> v_expr e | Common.Right t -> v_type_ t and v_obj_ v = v_bracket (v_list v_property) v and v_class_definition { c_extends = v_c_extends; c_body = v_c_body; c_kind; c_attrs; c_implements; } = let arg = v_wrap v_class_kind c_kind in let arg = v_list v_parent v_c_extends in let arg = v_bracket (v_list v_property) v_c_body in let arg = v_list v_attribute c_attrs in v_list v_type_ c_implements; () (* TODO? call Visitor_AST with local kinfo? meh *) and v_type_ _x = () and v_property x = (* tweak *) let k x = match x with | FieldTodo (v1, v2) -> v_todo_category v1; v_stmt v2 | Field v1 -> v_field_classic v1 | FieldColon v1 -> v_field_classic v1 | FieldSpread (t, v1) -> let t = v_tok t in let v1 = v_expr v1 in () | FieldEllipsis v1 -> let v1 = v_tok v1 in () | FieldPatDefault (v1, v2, v3) -> v_pattern v1; v_tok v2; v_expr v3 in vin.kprop (k, all_functions) x and v_field_classic { fld_name; fld_attrs; fld_type; fld_body } = let v1 = v_property_name fld_name and v2 = v_list v_attribute fld_attrs and ty = v_option v_type_ fld_type and v3 = v_option v_expr fld_body in () and v_property_prop _ = () and v_toplevel x = let k x = v_stmt x in vin.ktop (k, all_functions) x and v_module_directive x = match x with | ReExportNamespace (v1, v2, opt_as, v4, v5) -> v_tok v1; v_tok v2; (match opt_as with | Some name -> v_name name | None -> ()); v_tok v4; v_filename v5 | Import (t, v1, v2) -> let t = v_tok t in let v1 = v_list (fun (v1, v2) -> let v1 = v_name v1 and v2 = v_option v_name v2 in ()) v1 in let v2 = v_filename v2 in () | ImportFile (t, v1) -> let t = v_tok t in let v1 = v_name v1 in () | ModuleAlias (t, v1, v2) -> let t = v_tok t in let v1 = v_name v1 and v2 = v_filename v2 in () | Export (t, v1) -> let t = v_tok t in let v1 = v_name v1 in () and v_any = function | Property v1 -> v_property v1 | Expr v1 -> let v1 = v_expr v1 in () | Stmt v1 -> let v1 = v_stmt v1 in () | Stmts v1 -> let v1 = v_list v_stmt v1 in () | Pattern v1 -> v_pattern v1 | Type v1 -> v_type_ v1 | Program v1 -> let v1 = v_program v1 in () | Partial v1 -> v_partial v1 | Tk v1 -> v_tok v1 and v_partial = function | PartialFunOrFuncDef (v1, v2) -> v_tok v1; v_function_definition v2 | PartialDef def -> v_def def | PartialIf (v1, v2) -> v_tok v1; v_expr v2 | PartialTry (v1, v2) | PartialFinally (v1, v2) -> v_tok v1; v_stmt v2 | PartialCatch v1 -> v_catch_block v1 | PartialSingleField (v1, v2, v3) -> v_wrap v_string v1; v_tok v2; v_expr v3 | PartialSwitchCase x -> v_case x and v_program v = v_list v_toplevel v and all_functions x = v_any x in all_functions (*****************************************************************************) (* Helpers *) (*****************************************************************************) let do_visit_with_ref mk_hooks any = let res = ref [] in let hooks = mk_hooks res in let vout = mk_visitor hooks in vout any; List.rev !res
(* Yoann Padioleau * * Copyright (C) 2019 r2c * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *)
test_block_time_instructions.ml
(** Testing ------- Component: Protocol (Michelson block-time instructions) Invocation: dune exec src/proto_alpha/lib_protocol/test/integration/michelson/main.exe \ -- test "^block time instructions$" Subject: This module tests that Michelson instructions related to block time are correct. *) open Tezos_protocol_015_PtLimaPt_parameters open Protocol open Alpha_context let context_with_constants constants = let open Lwt_result_syntax in let* block, _contracts = Context.init_with_constants1 constants in let+ incremental = Incremental.begin_construction block in Incremental.alpha_ctxt incremental let test_min_block_time () = let open Lwt_result_syntax in let* context = context_with_constants Default_parameters.constants_mainnet in let* result, _ = Contract_helpers.run_script context ~storage:"0" ~parameter:"Unit" {| { parameter unit; storage nat; code { DROP; MIN_BLOCK_TIME; NIL operation; PAIR } } |} () in let expected_value = Default_parameters.constants_mainnet.minimal_block_delay |> Period.to_seconds |> Z.of_int64 in match Micheline.root result.storage with | Int (_, result_storage) when Z.equal result_storage expected_value -> return_unit | _ -> failwith "Expected storage to be %a, but got %a" Z.pp_print expected_value Micheline_printer.print_expr (Micheline_printer.printable Michelson_v1_primitives.string_of_prim result.storage) let tests = [ Tztest.tztest "MIN_BLOCK_TIME gives current minimal block delay" `Quick test_min_block_time; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 TriliTech <contact@trili.tech> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
fsevents.ml
open Stdune external available : unit -> bool = "dune_fsevents_available" module State : sig type 'a t val create : 'a -> 'a t type 'a ref val get : 'a ref -> 'a val set : 'a ref -> 'a -> unit val critical_section : 'a t -> ('a ref -> 'b) -> 'b end = struct type 'a t = { mutex : Mutex.t ; mutable data : 'a } type 'a ref = 'a t let set t a = t.data <- a let get t = t.data let create data = { mutex = Mutex.create (); data } let critical_section (type a) (t : a t) f = Mutex.lock t.mutex; Fun.protect (fun () -> f t) ~finally:(fun () -> Mutex.unlock t.mutex) end module RunLoop = struct module Raw = struct type t external in_current_thread : unit -> t = "dune_fsevents_runloop_current" (* After this function terminates, the reference to [t] is no longer valid *) external run_current_thread : t -> unit = "dune_fsevents_runloop_run" end type state = | Idle of Raw.t | Running of Raw.t | Stopped type t = state State.t let in_current_thread () = State.create (Idle (Raw.in_current_thread ())) let stop (t : t) = State.critical_section t (fun t -> match State.get t with | Running _ -> State.set t Stopped | Stopped -> () | Idle _ -> Code_error.raise "RunLoop.stop: not started" []) let run_current_thread t = let w = State.critical_section t (fun t -> match State.get t with | Stopped -> Code_error.raise "RunLoop.run_current_thread: stopped" [] | Running _ -> Code_error.raise "RunLoop.run_current_thread: running" [] | Idle w -> State.set t (Running w); w) in let res = try Ok (Raw.run_current_thread w) with exn -> Error exn in stop t; res end module Event = struct module Id = struct type t end type t = { path : string ; id : Id.t ; flags : Int32.t } module Raw = struct type t = { must_scan_subdirs : bool ; user_dropped : bool ; kernel_dropped : bool ; event_ids_wrapped : bool ; history_done : bool ; root_changed : bool ; mount : bool ; unmount : bool ; item_created : bool ; item_removed : bool ; item_inode_meta_mod : bool ; item_renamed : bool ; item_modified : bool ; item_finder_info_mod : bool ; item_change_owner : bool ; item_xattr_mod : bool ; item_is_file : bool ; item_is_dir : bool ; item_is_symlink : bool ; own_event : bool ; item_is_hardlink : bool ; item_is_last_hardlink : bool ; item_cloned : bool } let to_dyn { must_scan_subdirs ; user_dropped ; kernel_dropped ; event_ids_wrapped ; history_done ; root_changed ; mount ; unmount ; own_event ; item_created ; item_removed ; item_inode_meta_mod ; item_renamed ; item_modified ; item_finder_info_mod ; item_change_owner ; item_xattr_mod ; item_is_file ; item_is_dir ; item_is_symlink ; item_is_hardlink ; item_is_last_hardlink ; item_cloned } = let open Dyn in record [ ("must_scan_subdirs", bool must_scan_subdirs) ; ("user_dropped", bool user_dropped) ; ("kernel_dropped", bool kernel_dropped) ; ("event_ids_wrapped", bool event_ids_wrapped) ; ("history_done", bool history_done) ; ("root_changed", bool root_changed) ; ("mount", bool mount) ; ("unmount", bool unmount) ; ("own_event", bool own_event) ; ("item_created", bool item_created) ; ("item_removed", bool item_removed) ; ("item_inode_meta_mod", bool item_inode_meta_mod) ; ("item_renamed", bool item_renamed) ; ("item_modified", bool item_modified) ; ("item_finder_info_mod", bool item_finder_info_mod) ; ("item_change_owner", bool item_change_owner) ; ("item_xattr_mod", bool item_xattr_mod) ; ("item_is_file", bool item_is_file) ; ("item_is_dir", bool item_is_dir) ; ("item_is_symlink", bool item_is_symlink) ; ("item_is_hardlink", bool item_is_hardlink) ; ("item_is_last_hardlink", bool item_is_last_hardlink) ; ("item_cloned", bool item_cloned) ] end external raw : Int32.t -> Raw.t = "dune_fsevents_raw" let to_dyn_raw t = let open Dyn in record [ ("flags", Raw.to_dyn (raw t.flags)); ("path", string t.path) ] let id t = t.id let path t = t.path type kind = | Dir | File | Dir_and_descendants let dyn_of_kind kind = Dyn.string (match kind with | Dir -> "Dir" | File -> "File" | Dir_and_descendants -> "Dir_and_descendants") external kind : Int32.t -> kind = "dune_fsevents_kind" let kind t = kind t.flags type action = | Create | Remove | Modify | Rename | Unknown external action : Int32.t -> action = "dune_fsevents_action" let action t = action t.flags let dyn_of_action a = Dyn.string (match a with | Create -> "Create" | Remove -> "Remove" | Modify -> "Modify" | Unknown -> "Unknown" | Rename -> "Rename") let to_dyn t = let open Dyn in record [ ("action", dyn_of_action (action t)) ; ("kind", dyn_of_kind (kind t)) ; ("path", string t.path) ] end module Raw = struct type t external stop : t -> unit = "dune_fsevents_stop" external start : t -> RunLoop.Raw.t -> unit = "dune_fsevents_start" external create : string list -> float -> (Event.t list -> unit) -> t = "dune_fsevents_create" external set_exclusion_paths : t -> string list -> unit = "dune_fsevents_set_exclusion_paths" external flush_sync : t -> unit = "dune_fsevents_flush_sync" (* external flush_async : t -> Event.Id.t = "dune_fsevents_flush_async" *) end type state = | Idle of Raw.t | Start of Raw.t * RunLoop.t | Stop of RunLoop.t type t = state State.t let stop t = State.critical_section t (fun t -> match State.get t with | Idle _ -> Code_error.raise "Fsevents.stop: idle" [] | Stop _ -> () | Start (raw, rl) -> State.set t (Stop rl); Raw.stop raw) let start t (rl : RunLoop.t) = State.critical_section t (fun t -> match State.get t with | Stop _ -> Code_error.raise "Fsevents.start: stop" [] | Start _ -> Code_error.raise "Fsevents.start: start" [] | Idle r -> State.critical_section rl (fun rl' -> match State.get rl' with | Stopped -> Code_error.raise "Fsevents.start: runloop stopped" [] | Idle rl' | Running rl' -> State.set t (Start (r, rl)); Raw.start r rl')) let runloop t = State.critical_section t (fun t -> match State.get t with | Idle _ -> None | Start (_, rl) | Stop rl -> Some rl) let flush_sync t = let t = State.critical_section t (fun t -> match State.get t with | Idle _ -> Code_error.raise "Fsevents.flush_sync: idle" [] | Stop _ -> Code_error.raise "Fsevents.flush_sync: stop" [] | Start (r, _) -> r) in Raw.flush_sync t let create ~paths ~latency ~f = (match paths with | [] -> Code_error.raise "Fsevents.create: paths empty" [] | _ -> ()); State.create (Idle (Raw.create paths latency f)) let set_exclusion_paths t ~paths = if List.length paths > 8 then Code_error.raise "Fsevents.set_exclusion_paths: 8 directories should be enough for anybody" [ ("paths", Dyn.(list string) paths) ]; State.critical_section t (fun t -> match State.get t with | Stop _ -> Code_error.raise "Fsevents.set_exclusion_paths: stop" [] | Idle r | Start (r, _) -> ( try Raw.set_exclusion_paths r paths with Failure msg -> Code_error.raise msg [ ("paths", Dyn.(list string) paths) ])) (* let flush_async t = *) (* let res = flush_async t in *) (* if UInt64.equal res UInt64.zero then *) (* `No_events_queued *) (* else *) (* `Last res *) let flush_async _ = failwith "temporarily disabled"
repo.ml
module Map = Map.Make (String) module type Sig = sig val lifecycles : Sihl.Container.lifecycle list val register_migration : unit -> unit val register_cleaner : unit -> unit val enqueue : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance -> unit Lwt.t val enqueue_all : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance list -> unit Lwt.t val find_workable : ?ctx:(string * string) list -> unit -> Sihl.Contract.Queue.instance list Lwt.t val find : ?ctx:(string * string) list -> string -> Sihl.Contract.Queue.instance option Lwt.t val query : ?ctx:(string * string) list -> unit -> Sihl.Contract.Queue.instance list Lwt.t val update : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance -> unit Lwt.t val delete : ?ctx:(string * string) list -> Sihl.Contract.Queue.instance -> unit Lwt.t end module InMemory : Sig = Repo_inmemory module MariaDb : Sig = Repo_sql.MakeMariaDb (Sihl.Database.Migration.MariaDb) module PostgreSql : Sig = Repo_sql.MakePostgreSql (Sihl.Database.Migration.PostgreSql)
traverse_bfs.mli
module type STORE = sig module Hash : S.HASH module Value : Value.S with type hash = Hash.t type t val root : t -> Fpath.t val read_exn : t -> Hash.t -> Value.t Lwt.t val is_shallowed : t -> Hash.t -> bool Lwt.t end module Make (Store : STORE) : sig val fold : Store.t -> ('a -> ?name:Fpath.t -> length:int64 -> Store.Hash.t -> Store.Value.t -> 'a Lwt.t) -> path:Fpath.t -> 'a -> Store.Hash.t -> 'a Lwt.t val iter : Store.t -> (Store.Hash.t -> Store.Value.t -> unit Lwt.t) -> Store.Hash.t -> unit Lwt.t end
(* * Copyright (c) 2013-2017 Thomas Gazagnaire <thomas@gazagnaire.org> * and Romain Calascibetta <romain.calascibetta@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
modifyDBProxyTargetGroup.mli
open Types type input = ModifyDBProxyTargetGroupRequest.t type output = ModifyDBProxyTargetGroupResponse.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
indent.ml
open Js_of_ocaml let textarea (textbox : Dom_html.textAreaElement Js.t) : unit = let rec loop s acc (i, pos') = try let pos = String.index_from s pos' '\n' in loop s ((i, (pos', pos)) :: acc) (succ i, succ pos) with _ -> List.rev ((i, (pos', String.length s)) :: acc) in let rec find (l : (int * (int * int)) list) c = match l with | [] -> assert false | (i, (lo, up)) :: _ when up >= c -> c, i, lo, up | (_, (_lo, _up)) :: rem -> find rem c in let v = textbox##.value in let pos = let c1 = textbox##.selectionStart and c2 = textbox##.selectionEnd in if Js.Opt.test (Js.Opt.return c1) && Js.Opt.test (Js.Opt.return c2) then let l = loop (Js.to_string v) [] (0, 0) in Some (find l c1, find l c2) else None in let f = match pos with | None -> fun _ -> true | Some ((_c1, line1, _lo1, _up1), (_c2, line2, _lo2, _up2)) -> fun l -> l >= line1 + 1 && l <= line2 + 1 in let v = Ocp_indent.indent (Js.to_string v) f in textbox##.value := Js.string v; match pos with | Some ((c1, line1, _lo1, up1), (c2, line2, _lo2, up2)) -> let l = loop v [] (0, 0) in let lo1'', up1'' = List.assoc line1 l in let lo2'', up2'' = List.assoc line2 l in let n1 = max (c1 + up1'' - up1) lo1'' in let n2 = max (c2 + up2'' - up2) lo2'' in let () = (Obj.magic textbox)##setSelectionRange n1 n2 in textbox##focus; () | None -> ()
factor_content.c
#include "fmpz_mod_mpoly_factor.h" /* either give a non-trivial split a = f*g or establish that a is primitive wrt all variables return: 1: split a = f*g 0: a is primitve wrt all variables (f & g undefined) -1: failed */ static int _split( fmpz_mod_mpoly_t f, fmpz_mod_mpoly_t g, fmpz_mod_mpoly_t a, fmpz_t a_vars_left, const fmpz_mod_mpoly_ctx_t ctx, fmpz_mod_mpoly_univar_struct * u, /* temp */ slong * vars) { slong i, j, v; slong nvars = ctx->minfo->nvars; slong mvars = 0; FLINT_ASSERT(fmpz_mod_mpoly_is_canonical(f, ctx)); FLINT_ASSERT(fmpz_mod_mpoly_is_canonical(g, ctx)); FLINT_ASSERT(fmpz_mod_mpoly_is_canonical(a, ctx)); for (v = 0; v < nvars; v++) { if (!fmpz_tstbit(a_vars_left, v)) continue; fmpz_mod_mpoly_to_univar(u + v, a, v, ctx); vars[mvars] = v; mvars++; } if (mvars < 1) return 0; /* sort vars by decreasing length */ for (i = 1; i < mvars; i++) for (j = i; j > 0 && u[vars[j]].length > u[vars[j - 1]].length; j--) SLONG_SWAP(vars[j], vars[j - 1]); for (i = 0; i < mvars; i++) { v = vars[i]; FLINT_ASSERT(fmpz_tstbit(a_vars_left, v)); fmpz_clrbit(a_vars_left, v); if (u[v].length < 2) { FLINT_ASSERT(u[v].length == 1); FLINT_ASSERT(fmpz_is_zero(u[v].exps + 0)); continue; } if (!_fmpz_mod_mpoly_vec_content_mpoly(g, u[v].coeffs, u[v].length, ctx)) return -1; FLINT_ASSERT(fmpz_mod_mpoly_is_canonical(g, ctx)); if (g->length < 2) { FLINT_ASSERT(fmpz_mod_mpoly_is_one(g, ctx)); continue; } fmpz_mod_mpoly_divides(f, a, g, ctx); FLINT_ASSERT(f->length > 1); return 1; } return 0; } /* return factors that are primitive wrt each variable */ int fmpz_mod_mpoly_factor_content( fmpz_mod_mpoly_factor_t f, const fmpz_mod_mpoly_t A, const fmpz_mod_mpoly_ctx_t ctx) { int success; slong nvars = ctx->minfo->nvars; slong v; fmpz_mod_mpoly_univar_struct * u; fmpz_mod_mpoly_factor_t g; /* exponents are bitsets */ slong * vars; f->num = 0; if (fmpz_mod_mpoly_is_fmpz(A, ctx)) { fmpz_mod_mpoly_get_fmpz(f->constant, A, ctx); return 1; } vars = FLINT_ARRAY_ALLOC(nvars, slong); fmpz_mod_mpoly_factor_init(g, ctx); u = FLINT_ARRAY_ALLOC(nvars, fmpz_mod_mpoly_univar_struct); for (v = 0; v < nvars; v++) fmpz_mod_mpoly_univar_init(u + v, ctx); /* remove leading coefficient */ FLINT_ASSERT(A->length > 0); fmpz_set(f->constant, A->coeffs + 0); fmpz_mod_mpoly_factor_fit_length(g, nvars, ctx); fmpz_mod_mpoly_make_monic(g->poly + 0, A, ctx); /* remove monomial divisors */ mpoly_remove_var_powers(g->exp, g->poly[0].exps, g->poly[0].bits, g->poly[0].length, ctx->minfo); for (v = 0; v < nvars; v++) { if (fmpz_is_zero(g->exp + v)) continue; fmpz_mod_mpoly_factor_fit_length(f, f->num + 1, ctx); fmpz_mod_mpoly_gen(f->poly + f->num, v, ctx); fmpz_swap(f->exp + f->num, g->exp + v); f->num++; } /* done if g->poly[0] is constant */ if (g->poly[0].length == 1) { success = 1; goto cleanup; } /* g has length one and no variable has been checked yet */ fmpz_one(g->exp + 0); fmpz_mul_2exp(g->exp + 0, g->exp + 0, nvars); fmpz_sub_ui(g->exp + 0, g->exp + 0, 1); g->num = 1; while (g->num > 0) { slong t = g->num - 1; fmpz_mod_mpoly_factor_fit_length(g, t + 3, ctx); success = _split(g->poly + t + 2, g->poly + t + 1, g->poly + t, g->exp + t, ctx, u, vars); if (success < 0) { success = 0; goto cleanup; } else if (success == 0) { FLINT_ASSERT(!fmpz_mod_mpoly_is_fmpz(g->poly + t, ctx)); fmpz_mod_mpoly_factor_fit_length(f, f->num + 1, ctx); fmpz_mod_mpoly_swap(f->poly + f->num, g->poly + t, ctx); fmpz_one(f->exp + f->num); f->num++; g->num = t; } else { FLINT_ASSERT(!fmpz_mod_mpoly_is_fmpz(g->poly + t + 1, ctx)); FLINT_ASSERT(!fmpz_mod_mpoly_is_fmpz(g->poly + t + 2, ctx)); fmpz_mod_mpoly_swap(g->poly + t, g->poly + t + 2, ctx); fmpz_set(g->exp + t + 1, g->exp + t); g->num = t + 2; } } success = 1; cleanup: fmpz_mod_mpoly_factor_clear(g, ctx); for (v = 0; v < nvars; v++) fmpz_mod_mpoly_univar_clear(u + v, ctx); flint_free(u); flint_free(vars); FLINT_ASSERT(!success || fmpz_mod_mpoly_factor_matches(A, f, ctx)); return success; }
/* Copyright (C) 2020 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
client_baking_scheduling.mli
val sleep_until : Time.Protocol.t -> unit Lwt.t option (* val wait_for_first_event : * name:string -> 'event tzresult Lwt_stream.t -> 'event Lwt.t * * val main : * name:string -> * cctxt:(#Protocol_client_context.full as 'a) -> * stream:'event tzresult Lwt_stream.t -> * state_maker:('event -> 'state tzresult Lwt.t) -> * pre_loop:('a -> 'state -> 'event -> unit tzresult Lwt.t) -> * compute_timeout:('state -> 'timesup Lwt.t) -> * timeout_k:('a -> 'state -> 'timesup -> unit tzresult Lwt.t) -> * event_k:('a -> 'state -> 'event -> unit tzresult Lwt.t) -> * finalizer:('state -> unit Lwt.t) -> * unit tzresult Lwt.t *) (** [main ~name ~cctxt ~stream ~state_maker ~pre_loop ~timeout_maker ~timeout_k ~event_k] is an infinitely running loop that monitors new events arriving on [stream]. The loop exits when the [stream] gives an error. The function [pre_loop] is called before the loop starts. The loop maintains a state (of type ['state]) initialized by [state_maker] and passed to the callbacks [timeout_maker] (used to set up waking-up timeouts), [timeout_k] (when a computed timeout happens), and [event_k] (when a new event arrives on the stream). *)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
vote_storage.ml
let recorded_proposal_count_for_delegate ctxt proposer = Storage.Vote.Proposals_count.find ctxt proposer >|=? Option.value ~default:0 let record_proposal ctxt proposal proposer = recorded_proposal_count_for_delegate ctxt proposer >>=? fun count -> Storage.Vote.Proposals_count.add ctxt proposer (count + 1) >>= fun ctxt -> Storage.Vote.Proposals.add ctxt (proposal, proposer) >|= ok let get_proposals ctxt = Storage.Vote.Proposals.fold ctxt ~order:`Sorted ~init:(ok Protocol_hash.Map.empty) ~f:(fun (proposal, delegate) acc -> (* Assuming the same listings is used at votings *) Storage.Vote.Listings.get ctxt delegate >>=? fun weight -> Lwt.return ( acc >|? fun acc -> let previous = match Protocol_hash.Map.find proposal acc with | None -> 0L | Some x -> x in Protocol_hash.Map.add proposal (Int64.add weight previous) acc )) let clear_proposals ctxt = Storage.Vote.Proposals_count.clear ctxt >>= fun ctxt -> Storage.Vote.Proposals.clear ctxt type ballots = {yay : int64; nay : int64; pass : int64} let ballots_encoding = let open Data_encoding in conv (fun {yay; nay; pass} -> (yay, nay, pass)) (fun (yay, nay, pass) -> {yay; nay; pass}) @@ obj3 (req "yay" int64) (req "nay" int64) (req "pass" int64) let has_recorded_ballot = Storage.Vote.Ballots.mem let record_ballot = Storage.Vote.Ballots.init let get_ballots ctxt = Storage.Vote.Ballots.fold ctxt ~order:`Sorted ~f:(fun delegate ballot (ballots : ballots tzresult) -> (* Assuming the same listings is used at votings *) Storage.Vote.Listings.get ctxt delegate >>=? fun weight -> let count = Int64.add weight in Lwt.return ( ballots >|? fun ballots -> match ballot with | Yay -> {ballots with yay = count ballots.yay} | Nay -> {ballots with nay = count ballots.nay} | Pass -> {ballots with pass = count ballots.pass} )) ~init:(ok {yay = 0L; nay = 0L; pass = 0L}) let get_ballot_list = Storage.Vote.Ballots.bindings let clear_ballots = Storage.Vote.Ballots.clear let listings_encoding = Data_encoding.( list (obj2 (req "pkh" Signature.Public_key_hash.encoding) (req "voting_power" int64))) let update_listings ctxt = Storage.Vote.Listings.clear ctxt >>= fun ctxt -> Stake_storage.fold ctxt (ctxt, 0L) ~order:`Sorted ~f:(fun (delegate, stake) (ctxt, total) -> let weight = Tez_repr.to_mutez stake in Storage.Vote.Listings.init ctxt delegate weight >>=? fun ctxt -> return (ctxt, Int64.add total weight)) >>=? fun (ctxt, total) -> Storage.Vote.Voting_power_in_listings.add ctxt total >>= fun ctxt -> return ctxt type delegate_info = { voting_power : Int64.t option; current_ballot : Vote_repr.ballot option; current_proposals : Protocol_hash.t list; remaining_proposals : int; } let pp_delegate_info ppf info = match info.voting_power with | None -> Format.fprintf ppf "Voting power: none" | Some p -> ( Format.fprintf ppf "Voting power: %a" Tez_repr.pp (Tez_repr.of_mutez_exn p) ; (match info.current_ballot with | None -> () | Some ballot -> Format.fprintf ppf "@,Current ballot: %a" Vote_repr.pp_ballot ballot) ; match info.current_proposals with | [] -> if Compare.Int.(info.remaining_proposals <> 0) then Format.fprintf ppf "@,Remaining proposals: %d" info.remaining_proposals | proposals -> Format.fprintf ppf "@,@[<v 2>Current proposals:" ; List.iter (fun p -> Format.fprintf ppf "@,- %a" Protocol_hash.pp p) proposals ; Format.fprintf ppf "@]" ; Format.fprintf ppf "@,Remaining proposals: %d" info.remaining_proposals) let delegate_info_encoding = let open Data_encoding in conv (fun {voting_power; current_ballot; current_proposals; remaining_proposals} -> (voting_power, current_ballot, current_proposals, remaining_proposals)) (fun (voting_power, current_ballot, current_proposals, remaining_proposals) -> {voting_power; current_ballot; current_proposals; remaining_proposals}) (obj4 (opt "voting_power" int64) (opt "current_ballot" Vote_repr.ballot_encoding) (dft "current_proposals" (list Protocol_hash.encoding) []) (dft "remaining_proposals" int31 0)) let in_listings = Storage.Vote.Listings.mem let get_listings = Storage.Vote.Listings.bindings let get_delegate_info ctxt delegate = Storage.Vote.Listings.find ctxt delegate >>=? fun voting_power -> match voting_power with | None -> return { voting_power; current_proposals = []; current_ballot = None; remaining_proposals = 0; } | Some _ -> Voting_period_storage.get_current_kind ctxt >>=? fun period -> (match period with | Exploration | Promotion -> Storage.Vote.Ballots.find ctxt delegate | Proposal | Cooldown | Adoption -> return None) >>=? fun current_ballot -> (match period with | Exploration | Promotion | Cooldown | Adoption -> Lwt.return [] | Proposal -> Storage.Vote.Proposals.fold ctxt ~order:`Undefined ~init:[] ~f:(fun (h, d) acc -> if Signature.Public_key_hash.equal d delegate then Lwt.return (h :: acc) else Lwt.return acc)) >>= fun current_proposals -> let remaining_proposals = match period with | Proposal -> Constants_repr.max_proposals_per_delegate - List.length current_proposals | _ -> 0 in return {voting_power; current_ballot; current_proposals; remaining_proposals} let get_voting_power_free ctxt owner = Storage.Vote.Listings.find ctxt owner >|=? Option.value ~default:0L (* This function bypasses the carbonated functors to account for gas consumption. This is a temporary situation intended to be fixed by adding the right carbonated functors in a future amendment *) let get_voting_power ctxt owner = let open Raw_context in (* Always consume read access to memory *) (* Accessing an int64 at /votes/listings/<KeyKind>/<hash> *) consume_gas ctxt (Storage_costs.read_access ~path_length:4 ~read_bytes:8) >>?= fun ctxt -> Storage.Vote.Listings.find ctxt owner >|=? function | None -> (ctxt, 0L) | Some power -> (ctxt, power) let get_total_voting_power_free = Storage.Vote.Voting_power_in_listings.get (* This function bypasses the carbonated functors to account for gas consumption. This is a temporary situation intended to be fixed by adding the right carbonated functors in a future amendment *) let get_total_voting_power ctxt = let open Raw_context in (* Accessing an int64 at /votes/total_voting_power *) consume_gas ctxt (Storage_costs.read_access ~path_length:2 ~read_bytes:8) >>?= fun ctxt -> get_total_voting_power_free ctxt >|=? fun total_voting_power -> (ctxt, total_voting_power) let get_current_quorum ctxt = Storage.Vote.Participation_ema.get ctxt >|=? fun participation_ema -> let quorum_min = Constants_storage.quorum_min ctxt in let quorum_max = Constants_storage.quorum_max ctxt in let quorum_diff = Int32.sub quorum_max quorum_min in Int32.(add quorum_min (div (mul participation_ema quorum_diff) 100_00l)) let get_participation_ema = Storage.Vote.Participation_ema.get let set_participation_ema = Storage.Vote.Participation_ema.update let get_current_proposal = Storage.Vote.Current_proposal.get let find_current_proposal = Storage.Vote.Current_proposal.find let init_current_proposal = Storage.Vote.Current_proposal.init let clear_current_proposal ctxt = Storage.Vote.Current_proposal.remove ctxt >|= ok let init ctxt ~start_position = (* participation EMA is in centile of a percentage *) let participation_ema = Constants_storage.quorum_max ctxt in Storage.Vote.Participation_ema.init ctxt participation_ema >>=? fun ctxt -> Voting_period_storage.init_first_period ctxt ~start_position
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(executables (names hfun) (modules hfun) (libraries) (modes js)) (executables (names htbl) (modules htbl) (enabled_if (>= %{ocaml_version} 5)) (libraries) (modes js)) (rule (target hfun.referencejs) (deps hfun.bc.js ../../../LICENSE) (action (with-stdout-to %{target} (run node ./hfun.bc.js)))) (rule (alias runtest) (deps hfun.referencejs hfun.reference) (action (diff hfun.referencejs hfun.reference))) (rule (target htbl.referencejs) (enabled_if (>= %{ocaml_version} 5)) (deps htbl.bc.js ../../../LICENSE) (action (with-stdout-to %{target} (run node ./htbl.bc.js)))) (rule (alias runtest) (enabled_if (>= %{ocaml_version} 5)) (deps htbl.reference htbl.referencejs) (action (diff htbl.reference htbl.referencejs)))
ocamlbuild_atdgen.ml
open Ocamlbuild_plugin let () = Options.use_ocamlfind := true let atdgen = "atdgen" let tag_atdgen env patterns = patterns |> List.iter begin fun p -> ["package(atdgen)"] |> Tags.of_list |> Tags.elements |> tag_file (env p) end let init () = rule "atdgen: .atd -> _t.ml*" ~prods:["%_t.ml";"%_t.mli"] ~dep:"%.atd" (begin fun env build -> tag_atdgen env ["%_t.ml";"%_t.mli"]; Cmd (S [A atdgen; A "-t"; P (env "%.atd")]); end); rule "atdgen: .atd -> _j.ml*" ~prods:["%_j.ml";"%_j.mli";] ~dep:"%.atd" (begin fun env build -> tag_atdgen env ["%_j.ml"; "%_j.mli"]; Cmd (S [A atdgen; A "-j"; A "-j-std"; P (env "%.atd")]); end); rule "atdgen: .atd -> _v.ml*" ~prods:["%_v.ml";"%_v.mli";] ~dep:"%.atd" (begin fun env build -> tag_atdgen env ["%_v.ml";"%_v.mli";]; Cmd (S [A atdgen; A "-v"; P (env "%.atd")]); end) let dispatcher = function | After_rules -> init () | _ -> ()
level_storage.ml
open Level_repr let from_raw c ?offset l = let cycle_eras = Raw_context.cycle_eras c in Level_repr.from_raw ~cycle_eras ?offset l let root c = Raw_context.cycle_eras c |> Level_repr.root_level let succ c (l : Level_repr.t) = from_raw c (Raw_level_repr.succ l.level) let pred c (l : Level_repr.t) = match Raw_level_repr.pred l.Level_repr.level with | None -> None | Some l -> Some (from_raw c l) let current ctxt = Raw_context.current_level ctxt let previous ctxt = let l = current ctxt in match pred ctxt l with | None -> assert false (* We never validate the Genesis... *) | Some p -> p let first_level_in_cycle ctxt cycle = let cycle_eras = Raw_context.cycle_eras ctxt in Level_repr.first_level_in_cycle cycle_eras cycle let last_level_in_cycle ctxt c = match pred ctxt (first_level_in_cycle ctxt (Cycle_repr.succ c)) with | None -> assert false | Some x -> x let levels_in_cycle ctxt cycle = let first = first_level_in_cycle ctxt cycle in let rec loop (n : Level_repr.t) acc = if Cycle_repr.(n.cycle = first.cycle) then loop (succ ctxt n) (n :: acc) else acc in loop first [] let levels_in_current_cycle ctxt ?(offset = 0l) () = let current_cycle = Cycle_repr.to_int32 (current ctxt).cycle in let cycle = Int32.add current_cycle offset in if Compare.Int32.(cycle < 0l) then [] else let cycle = Cycle_repr.of_int32_exn cycle in levels_in_cycle ctxt cycle let levels_with_commitments_in_cycle ctxt c = let first = first_level_in_cycle ctxt c in let rec loop (n : Level_repr.t) acc = if Cycle_repr.(n.cycle = first.cycle) then if n.expected_commitment then loop (succ ctxt n) (n :: acc) else loop (succ ctxt n) acc else acc in loop first [] let last_allowed_fork_level c = let level = Raw_context.current_level c in let preserved_cycles = Constants_storage.preserved_cycles c in match Cycle_repr.sub level.cycle preserved_cycles with | None -> Raw_level_repr.root | Some cycle -> (first_level_in_cycle c cycle).level let last_of_a_cycle ctxt level = let cycle_eras = Raw_context.cycle_eras ctxt in Level_repr.last_of_cycle cycle_eras level let dawn_of_a_new_cycle ctxt = let level = current ctxt in if last_of_a_cycle ctxt level then Some level.cycle else None let may_snapshot_rolls ctxt = let level = current ctxt in let blocks_per_roll_snapshot = Constants_storage.blocks_per_roll_snapshot ctxt in Compare.Int32.equal (Int32.rem level.cycle_position blocks_per_roll_snapshot) (Int32.pred blocks_per_roll_snapshot)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
nonce_hash.mli
(** A specialized Blake2B implementation for hashing nonces. *) include S.HASH include Path_encoding.S with type t := t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020-2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
bin_prot_test.ml
open Bigarray open Printf open OUnit open Bin_prot open Common open Utils open ReadError open Type_class open Bin_prot.Std module Bigstring = struct type t = buf let create = create_buf let of_string str = let len = String.length str in let buf = create len in blit_string_buf str buf ~len; buf ;; let length buf = Array1.dim buf end let expect_exc test_exc f = try ignore (f ()); false with | exc -> test_exc exc ;; let expect_bounds_error f = let test_exc = function | Invalid_argument "index out of bounds" -> true | _ -> false in expect_exc test_exc f ;; let expect_buffer_short f = let exc = Buffer_short in expect_exc (( = ) exc) f ;; let expect_read_error exp_re exp_pos f = let test_exc = function | Read_error (re, pos) -> exp_re = re && exp_pos = pos | _ -> false in expect_exc test_exc f ;; let expect_no_error f = try ignore (f ()); true with | _ -> false ;; let check_write_bounds_checks name buf write arg = (name ^ ": negative bound") @? expect_bounds_error (fun () -> write buf ~pos:~-1 arg); (name ^ ": positive bound") @? expect_buffer_short (fun () -> write buf ~pos:(Bigstring.length buf) arg) ;; let check_read_bounds_checks name buf read = (name ^ ": negative bound") @? expect_bounds_error (fun () -> read buf ~pos_ref:(ref ~-1)); (name ^ ": positive bound") @? expect_buffer_short (fun () -> read buf ~pos_ref:(ref (Bigstring.length buf))) ;; let check_write_result name buf pos write arg exp_len = let res_pos = write buf ~pos arg in sprintf "%s: returned wrong write position (%d, expected %d)" name res_pos (pos + exp_len) @? (res_pos = pos + exp_len) ;; let check_read_result name buf pos read exp_ret exp_len = let pos_ref = ref pos in (name ^ ": returned wrong result") @? (read buf ~pos_ref = exp_ret); sprintf "%s: returned wrong read position (%d, expected %d)" name !pos_ref (pos + exp_len) @? (!pos_ref - pos = exp_len) ;; let check_all_args tp_name read write buf args = let write_name = "write_" ^ tp_name ^ " " in let read_name = "read_" ^ tp_name ^ " " in let buf_len = Bigstring.length buf in let act (arg, str_arg, arg_len) = let write_name_arg = write_name ^ str_arg in let read_name_arg = read_name ^ str_arg in for pos = 0 to 8 do check_write_bounds_checks write_name buf write arg; check_read_bounds_checks read_name buf read; check_write_result write_name_arg buf pos write arg arg_len; check_read_result read_name_arg buf pos read arg arg_len done; (write_name_arg ^ ": write failed near bound") @? expect_no_error (fun () -> write buf ~pos:(buf_len - arg_len) arg); (read_name_arg ^ ": read failed near bound") @? expect_no_error (fun () -> if read buf ~pos_ref:(ref (buf_len - arg_len)) <> arg then failwith (read_name_arg ^ ": read near bound returned wrong result")); let small_buf = Array1.sub buf 0 (buf_len - 1) in (write_name_arg ^ ": write exceeds bound") @? expect_buffer_short (fun () -> write small_buf ~pos:(buf_len - arg_len) arg); (read_name_arg ^ ": read exceeds bound") @? expect_buffer_short (fun () -> read small_buf ~pos_ref:(ref (buf_len - arg_len))) in List.iter act args ;; let mk_buf n = let bstr = Bigstring.create n in for i = 0 to n - 1 do bstr.{i} <- '\255' done; bstr ;; let check_all extra_buf_size tp_name read write args = let buf_len = extra_buf_size + 8 in let buf = mk_buf buf_len in match args with | [] -> assert false | (arg, _, _) :: _ -> let write_name = "write_" ^ tp_name in check_write_bounds_checks write_name buf write arg; let read_name = "read_" ^ tp_name in check_read_bounds_checks read_name buf read; check_all_args tp_name read write buf args ;; let random_string n = String.init n (fun _ -> Char.chr (Random.int 256)) let mk_int_test ~n ~len = n, Printf.sprintf "%x" n, len let mk_nat0_test ~n ~len = Nat0.of_int n, Printf.sprintf "%x" n, len let mk_float_test n = n, Printf.sprintf "%g" n, 8 let mk_int32_test ~n ~len = n, Printf.sprintf "%lx" n, len let mk_int64_test ~n ~len = n, Printf.sprintf "%Lx" n, len let mk_nativeint_test ~n ~len = n, Printf.sprintf "%nx" n, len let mk_gen_float_vec tp n = let vec = Array1.create tp fortran_layout n in for i = 1 to n do vec.{i} <- float i done; vec ;; let mk_float32_vec = mk_gen_float_vec float32 let mk_float64_vec = mk_gen_float_vec float64 let mk_bigstring n = let bstr = Array1.create char c_layout n in for i = 0 to n - 1 do bstr.{i} <- Char.chr (Random.int 256) done; bstr ;; let mk_gen_float_mat tp m n = let mat = Array2.create tp fortran_layout m n in let fn = float m in for c = 1 to n do let ofs = float (c - 1) *. fn in for r = 1 to m do mat.{r, c} <- ofs +. float r done done; mat ;; let mk_float32_mat = mk_gen_float_mat float32 let mk_float64_mat = mk_gen_float_mat float64 let test = "Bin_prot" >::: [ ("unit" >:: fun () -> check_all 1 "unit" Read.bin_read_unit Write.bin_write_unit [ (), "()", 1 ]) ; ("bool" >:: fun () -> check_all 1 "bool" Read.bin_read_bool Write.bin_write_bool [ true, "true", 1; false, "false", 1 ]) ; ("string" >:: fun () -> check_all 66000 "string" Read.bin_read_string Write.bin_write_string [ "", "\"\"", 1 ; random_string 1, "random 1", 1 + 1 ; random_string 10, "random 10", 10 + 1 ; random_string 127, "random 127", 127 + 1 ; random_string 128, "long 128", 128 + 3 ; random_string 65535, "long 65535", 65535 + 3 ; random_string 65536, "long 65536", 65536 + 5 ]; if Sys.word_size = 32 then ( let bad_buf = Bigstring.of_string "\253\252\255\255\000" in "String_too_long" @? expect_read_error String_too_long 0 (fun () -> Read.bin_read_string bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\253\251\255\255\000" in "StringMaximimum" @? expect_buffer_short (fun () -> Read.bin_read_string bad_buf ~pos_ref:(ref 0))) else ( let bad_buf = Bigstring.of_string "\252\248\255\255\255\255\255\255\001" in "String_too_long" @? expect_read_error String_too_long 0 (fun () -> Read.bin_read_string bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\252\247\255\255\255\255\255\255\001" in "StringMaximimum" @? expect_buffer_short (fun () -> Read.bin_read_string bad_buf ~pos_ref:(ref 0)))) ; ("char" >:: fun () -> check_all 1 "char" Read.bin_read_char Write.bin_write_char [ 'x', "x", 1; 'y', "y", 1 ]) ; ("int" >:: fun () -> let small_int_tests = [ mk_int_test ~n:~-0x01 ~len:2 ; mk_int_test ~n:0x00 ~len:1 ; mk_int_test ~n:0x01 ~len:1 ; mk_int_test ~n:0x7e ~len:1 ; mk_int_test ~n:0x7f ~len:1 ; mk_int_test ~n:0x80 ~len:3 ; mk_int_test ~n:0x81 ~len:3 ; mk_int_test ~n:0x7ffe ~len:3 ; mk_int_test ~n:0x7fff ~len:3 ; mk_int_test ~n:0x8000 ~len:5 ; mk_int_test ~n:0x8001 ~len:5 ; mk_int_test ~n:0x3ffffffe ~len:5 ; mk_int_test ~n:0x3fffffff ~len:5 ; mk_int_test ~n:~-0x7f ~len:2 ; mk_int_test ~n:~-0x80 ~len:2 ; mk_int_test ~n:~-0x81 ~len:3 ; mk_int_test ~n:~-0x82 ~len:3 ; mk_int_test ~n:~-0x7fff ~len:3 ; mk_int_test ~n:~-0x8000 ~len:3 ; mk_int_test ~n:~-0x8001 ~len:5 ; mk_int_test ~n:~-0x8002 ~len:5 ; mk_int_test ~n:~-0x40000001 ~len:5 ; mk_int_test ~n:~-0x40000000 ~len:5 ] in let all_int_tests = if Sys.word_size = 32 then small_int_tests else mk_int_test ~n:(int_of_string "0x7ffffffe") ~len:5 :: mk_int_test ~n:(int_of_string "0x7fffffff") ~len:5 :: mk_int_test ~n:(int_of_string "0x80000000") ~len:9 :: mk_int_test ~n:(int_of_string "0x80000001") ~len:9 :: mk_int_test ~n:max_int ~len:9 :: mk_int_test ~n:(int_of_string "-0x000000007fffffff") ~len:5 :: mk_int_test ~n:(int_of_string "-0x0000000080000000") ~len:5 :: mk_int_test ~n:(int_of_string "-0x0000000080000001") ~len:9 :: mk_int_test ~n:(int_of_string "-0x0000000080000002") ~len:9 :: mk_int_test ~n:min_int ~len:9 :: small_int_tests in check_all 9 "int" Read.bin_read_int Write.bin_write_int all_int_tests; let bad_buf = Bigstring.of_string "\132" in "Int_code" @? expect_read_error Int_code 0 (fun () -> Read.bin_read_int bad_buf ~pos_ref:(ref 0)); if Sys.word_size = 32 then ( let bad_buf = Bigstring.of_string "\253\255\255\255\064" in "Int_overflow (positive)" @? expect_read_error Int_overflow 0 (fun () -> Read.bin_read_int bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\253\255\255\255\191" in "Int_overflow (negative)" @? expect_read_error Int_overflow 0 (fun () -> Read.bin_read_int bad_buf ~pos_ref:(ref 0))) else ( let bad_buf = Bigstring.of_string "\252\255\255\255\255\255\255\255\064" in "Int_overflow (positive)" @? expect_read_error Int_overflow 0 (fun () -> Read.bin_read_int bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\252\255\255\255\255\255\255\255\191" in "Int_overflow (negative)" @? expect_read_error Int_overflow 0 (fun () -> Read.bin_read_int bad_buf ~pos_ref:(ref 0)))) ; ("nat0" >:: fun () -> let small_int_tests = [ mk_nat0_test ~n:0x00 ~len:1 ; mk_nat0_test ~n:0x01 ~len:1 ; mk_nat0_test ~n:0x7e ~len:1 ; mk_nat0_test ~n:0x7f ~len:1 ; mk_nat0_test ~n:0x80 ~len:3 ; mk_nat0_test ~n:0x81 ~len:3 ; mk_nat0_test ~n:0x7fff ~len:3 ; mk_nat0_test ~n:0x8000 ~len:3 ; mk_nat0_test ~n:0xffff ~len:3 ; mk_nat0_test ~n:0x10000 ~len:5 ; mk_nat0_test ~n:0x10001 ~len:5 ; mk_nat0_test ~n:0x3ffffffe ~len:5 ; mk_nat0_test ~n:0x3fffffff ~len:5 ] in let all_int_tests = if Sys.word_size = 32 then small_int_tests else mk_nat0_test ~n:(int_of_string "0x7fffffff") ~len:5 :: mk_nat0_test ~n:(int_of_string "0x80000000") ~len:5 :: mk_nat0_test ~n:(int_of_string "0xffffffff") ~len:5 :: mk_nat0_test ~n:(int_of_string "0x100000000") ~len:9 :: mk_nat0_test ~n:(int_of_string "0x100000001") ~len:9 :: mk_nat0_test ~n:max_int ~len:9 :: small_int_tests in check_all 9 "nat0" Read.bin_read_nat0 Write.bin_write_nat0 all_int_tests; let bad_buf = Bigstring.of_string "\128" in "Nat0_code" @? expect_read_error Nat0_code 0 (fun () -> Read.bin_read_nat0 bad_buf ~pos_ref:(ref 0)); if Sys.word_size = 32 then ( let bad_buf = Bigstring.of_string "\253\255\255\255\064" in "Nat0_overflow" @? expect_read_error Nat0_overflow 0 (fun () -> Read.bin_read_nat0 bad_buf ~pos_ref:(ref 0))) else ( let bad_buf = Bigstring.of_string "\252\255\255\255\255\255\255\255\064" in "Nat0_overflow" @? expect_read_error Nat0_overflow 0 (fun () -> Read.bin_read_nat0 bad_buf ~pos_ref:(ref 0)))) ; ("float" >:: fun () -> let float_tests = [ mk_float_test 0. ; mk_float_test (-0.) ; mk_float_test (-1.) ; mk_float_test 1. ; mk_float_test infinity ; mk_float_test (-.infinity) ; mk_float_test 1e-310 ; (* subnormal *) mk_float_test (-1e-310) ; (* subnormal *) mk_float_test 3.141595 ] in check_all 8 "float" Read.bin_read_float Write.bin_write_float float_tests) ; ("int32" >:: fun () -> let int32_tests = [ mk_int32_test ~n:(-0x01l) ~len:2 ; mk_int32_test ~n:0x00l ~len:1 ; mk_int32_test ~n:0x01l ~len:1 ; mk_int32_test ~n:0x7el ~len:1 ; mk_int32_test ~n:0x7fl ~len:1 ; mk_int32_test ~n:0x80l ~len:3 ; mk_int32_test ~n:0x81l ~len:3 ; mk_int32_test ~n:0x7ffel ~len:3 ; mk_int32_test ~n:0x7fffl ~len:3 ; mk_int32_test ~n:0x8000l ~len:5 ; mk_int32_test ~n:0x8001l ~len:5 ; mk_int32_test ~n:0x7ffffffel ~len:5 ; mk_int32_test ~n:0x7fffffffl ~len:5 ; mk_int32_test ~n:(-0x7fl) ~len:2 ; mk_int32_test ~n:(-0x80l) ~len:2 ; mk_int32_test ~n:(-0x81l) ~len:3 ; mk_int32_test ~n:(-0x82l) ~len:3 ; mk_int32_test ~n:(-0x7fffl) ~len:3 ; mk_int32_test ~n:(-0x8000l) ~len:3 ; mk_int32_test ~n:(-0x8001l) ~len:5 ; mk_int32_test ~n:(-0x8002l) ~len:5 ; mk_int32_test ~n:(-0x80000001l) ~len:5 ; mk_int32_test ~n:(-0x80000000l) ~len:5 ] in check_all 5 "int32" Read.bin_read_int32 Write.bin_write_int32 int32_tests; let bad_buf = Bigstring.of_string "\132" in "Int32_code" @? expect_read_error Int32_code 0 (fun () -> Read.bin_read_int32 bad_buf ~pos_ref:(ref 0))) ; ("int64" >:: fun () -> let int64_tests = [ mk_int64_test ~n:(-0x01L) ~len:2 ; mk_int64_test ~n:0x00L ~len:1 ; mk_int64_test ~n:0x01L ~len:1 ; mk_int64_test ~n:0x7eL ~len:1 ; mk_int64_test ~n:0x7fL ~len:1 ; mk_int64_test ~n:0x80L ~len:3 ; mk_int64_test ~n:0x81L ~len:3 ; mk_int64_test ~n:0x7ffeL ~len:3 ; mk_int64_test ~n:0x7fffL ~len:3 ; mk_int64_test ~n:0x8000L ~len:5 ; mk_int64_test ~n:0x8001L ~len:5 ; mk_int64_test ~n:0x7ffffffeL ~len:5 ; mk_int64_test ~n:0x7fffffffL ~len:5 ; mk_int64_test ~n:0x80000000L ~len:9 ; mk_int64_test ~n:0x80000001L ~len:9 ; mk_int64_test ~n:0x7ffffffffffffffeL ~len:9 ; mk_int64_test ~n:0x7fffffffffffffffL ~len:9 ; mk_int64_test ~n:(-0x7fL) ~len:2 ; mk_int64_test ~n:(-0x80L) ~len:2 ; mk_int64_test ~n:(-0x81L) ~len:3 ; mk_int64_test ~n:(-0x82L) ~len:3 ; mk_int64_test ~n:(-0x7fffL) ~len:3 ; mk_int64_test ~n:(-0x8000L) ~len:3 ; mk_int64_test ~n:(-0x8001L) ~len:5 ; mk_int64_test ~n:(-0x8002L) ~len:5 ; mk_int64_test ~n:(-0x7fffffffL) ~len:5 ; mk_int64_test ~n:(-0x80000000L) ~len:5 ; mk_int64_test ~n:(-0x80000001L) ~len:9 ; mk_int64_test ~n:(-0x80000002L) ~len:9 ; mk_int64_test ~n:(-0x8000000000000001L) ~len:9 ; mk_int64_test ~n:(-0x8000000000000000L) ~len:9 ] in check_all 9 "int64" Read.bin_read_int64 Write.bin_write_int64 int64_tests; let bad_buf = Bigstring.of_string "\132" in "Int64_code" @? expect_read_error Int64_code 0 (fun () -> Read.bin_read_int64 bad_buf ~pos_ref:(ref 0))) ; ("nativeint" >:: fun () -> let small_nativeint_tests = [ mk_nativeint_test ~n:(-0x01n) ~len:2 ; mk_nativeint_test ~n:0x00n ~len:1 ; mk_nativeint_test ~n:0x01n ~len:1 ; mk_nativeint_test ~n:0x7en ~len:1 ; mk_nativeint_test ~n:0x7fn ~len:1 ; mk_nativeint_test ~n:0x80n ~len:3 ; mk_nativeint_test ~n:0x81n ~len:3 ; mk_nativeint_test ~n:0x7ffen ~len:3 ; mk_nativeint_test ~n:0x7fffn ~len:3 ; mk_nativeint_test ~n:0x8000n ~len:5 ; mk_nativeint_test ~n:0x8001n ~len:5 ; mk_nativeint_test ~n:0x7ffffffen ~len:5 ; mk_nativeint_test ~n:0x7fffffffn ~len:5 ; mk_nativeint_test ~n:(-0x7fn) ~len:2 ; mk_nativeint_test ~n:(-0x80n) ~len:2 ; mk_nativeint_test ~n:(-0x81n) ~len:3 ; mk_nativeint_test ~n:(-0x82n) ~len:3 ; mk_nativeint_test ~n:(-0x7fffn) ~len:3 ; mk_nativeint_test ~n:(-0x8000n) ~len:3 ; mk_nativeint_test ~n:(-0x8001n) ~len:5 ; mk_nativeint_test ~n:(-0x8002n) ~len:5 ; mk_nativeint_test ~n:(-0x7fffffffn) ~len:5 ; mk_nativeint_test ~n:(-0x80000000n) ~len:5 ] in let nativeint_tests = if Sys.word_size = 32 then small_nativeint_tests else mk_nativeint_test ~n:0x80000000n ~len:9 :: mk_nativeint_test ~n:0x80000001n ~len:9 :: mk_nativeint_test ~n:(-0x80000001n) ~len:9 :: mk_nativeint_test ~n:(-0x80000002n) ~len:9 :: mk_nativeint_test ~n:(Nativeint.of_string "0x7ffffffffffffffe") ~len:9 :: mk_nativeint_test ~n:(Nativeint.of_string "0x7fffffffffffffff") ~len:9 :: mk_nativeint_test ~n:(Nativeint.of_string "-0x8000000000000001") ~len:9 :: mk_nativeint_test ~n:(Nativeint.of_string "-0x8000000000000000") ~len:9 :: small_nativeint_tests in let size = if Sys.word_size = 32 then 5 else 9 in check_all size "nativeint" Read.bin_read_nativeint Write.bin_write_nativeint nativeint_tests; let bad_buf = Bigstring.of_string "\251" in "Nativeint_code" @? expect_read_error Nativeint_code 0 (fun () -> Read.bin_read_nativeint bad_buf ~pos_ref:(ref 0)); if Sys.word_size = 32 then ( let bad_buf = Bigstring.of_string "\252\255\255\255\255\255\255\255\255" in "Nativeint_code (overflow)" @? expect_read_error Nativeint_code 0 (fun () -> Read.bin_read_nativeint bad_buf ~pos_ref:(ref 0)))) ; ("ref" >:: fun () -> check_all 1 "ref" (Read.bin_read_ref Read.bin_read_int) (Write.bin_write_ref Write.bin_write_int) [ ref 42, "ref 42", 1 ]) ; ("option" >:: fun () -> check_all 2 "option" (Read.bin_read_option Read.bin_read_int) (Write.bin_write_option Write.bin_write_int) [ Some 42, "Some 42", 2; None, "None", 1 ]) ; ("pair" >:: fun () -> check_all 9 "pair" (Read.bin_read_pair Read.bin_read_float Read.bin_read_int) (Write.bin_write_pair Write.bin_write_float Write.bin_write_int) [ (3.141, 42), "(3.141, 42)", 9 ]) ; ("triple" >:: fun () -> check_all 14 "triple" (Read.bin_read_triple Read.bin_read_float Read.bin_read_int Read.bin_read_string) (Write.bin_write_triple Write.bin_write_float Write.bin_write_int Write.bin_write_string) [ (3.141, 42, "test"), "(3.141, 42, \"test\")", 14 ]) ; ("list" >:: fun () -> check_all 12 "list" (Read.bin_read_list Read.bin_read_int) (Write.bin_write_list Write.bin_write_int) [ [ 42; -1; 200; 33000 ], "[42; -1; 200; 33000]", 12; [], "[]", 1 ]) ; ("array" >:: fun () -> let bin_read_int_array = Read.bin_read_array Read.bin_read_int in check_all 12 "array" bin_read_int_array (Write.bin_write_array Write.bin_write_int) [ [| 42; -1; 200; 33000 |], "[|42; -1; 200; 33000|]", 12; [||], "[||]", 1 ]; if Sys.word_size = 32 then ( let bad_buf = Bigstring.of_string "\253\000\000\064\000" in "Array_too_long" @? expect_read_error Array_too_long 0 (fun () -> bin_read_int_array bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\253\255\255\063\000" in "ArrayMaximimum" @? expect_buffer_short (fun () -> bin_read_int_array bad_buf ~pos_ref:(ref 0))) else ( let bad_buf = Bigstring.of_string "\252\000\000\000\000\000\000\064\000" in "Array_too_long" @? expect_read_error Array_too_long 0 (fun () -> bin_read_int_array bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\252\255\255\255\255\255\255\063\000" in "ArrayMaximimum" @? expect_buffer_short (fun () -> bin_read_int_array bad_buf ~pos_ref:(ref 0))) ) ; ("float_array" >:: fun () -> ((check_all 33 "float_array" Read.bin_read_float_array Write.bin_write_float_array [ [| 42.; -1.; 200.; 33000. |], "[|42.; -1.; 200.; 33000.|]", 33 ; [||], "[||]", 1 ]; if Sys.word_size = 32 then ( let bad_buf = Bigstring.of_string "\253\000\000\032\000" in "Array_too_long (float)" @? expect_read_error Array_too_long 0 (fun () -> Read.bin_read_float_array bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\253\255\255\031\000" in "ArrayMaximimum (float)" @? expect_buffer_short (fun () -> Read.bin_read_float_array bad_buf ~pos_ref:(ref 0))) else ( let bad_buf = Bigstring.of_string "\252\000\000\000\000\000\000\064\000" in "Array_too_long (float)" @? expect_read_error Array_too_long 0 (fun () -> Read.bin_read_float_array bad_buf ~pos_ref:(ref 0)); let bad_buf = Bigstring.of_string "\252\255\255\255\255\255\255\063\000" in "ArrayMaximimum (float)" @? expect_buffer_short (fun () -> Read.bin_read_float_array bad_buf ~pos_ref:(ref 0)); (* Test that the binary forms of [float array] and [float_array] are the same *) let arrays = let rec loop acc len = if len < 0 then acc else ( let a = Array.init len (fun i -> float_of_int (i + len)) in let txt = Printf.sprintf "float array, len = %d" len in let buf = (len * 8) + Size.bin_size_nat0 (Nat0.unsafe_of_int len) in loop ((a, txt, buf) :: acc) (len - 1)) in loop [] 255 in let len = (255 * 8) + Size.bin_size_nat0 (Nat0.unsafe_of_int 255) in check_all len "float array -> float_array" Read.bin_read_float_array (Write.bin_write_array Write.bin_write_float) arrays; check_all len "float_array -> float array" (Read.bin_read_array Read.bin_read_float) Write.bin_write_float_array arrays; (* Check that the canonical closures used in the short circuit test of float arrays are indeed allocated closures as opposed to [compare] for example which is a primitive. Even if it looks like a tautology, it is not. (for example, [compare == compare] is false. *) assert (bin_write_float == bin_write_float); assert (bin_read_float == bin_read_float); assert (bin_size_float == bin_size_float))) [@ocaml.alert "-deprecated"])) ; ("hashtbl" >:: fun () -> let bindings = List.rev [ 42, 3.; 17, 2.; 42, 4. ] in let htbl = Hashtbl.create (List.length bindings) in List.iter (fun (k, v) -> Hashtbl.add htbl k v) bindings; check_all 28 "hashtbl" (Read.bin_read_hashtbl Read.bin_read_int Read.bin_read_float) (Write.bin_write_hashtbl Write.bin_write_int Write.bin_write_float) [ htbl, "[(42, 3.); (17, 2.); (42, 4.)]", 28; Hashtbl.create 0, "[]", 1 ]) ; ("float32_vec" >:: fun () -> let n = 128 in let header = 3 in let size = header + (n * 4) in let vec = mk_float32_vec n in check_all size "float32_vec" Read.bin_read_float32_vec Write.bin_write_float32_vec [ vec, "[| ... |]", size; mk_float32_vec 0, "[||]", 1 ]) ; ("float64_vec" >:: fun () -> let n = 127 in let header = 1 in let size = header + (n * 8) in let vec = mk_float64_vec n in check_all size "float64_vec" Read.bin_read_float64_vec Write.bin_write_float64_vec [ vec, "[| ... |]", size; mk_float64_vec 0, "[||]", 1 ]) ; ("vec" >:: fun () -> let n = 128 in let header = 3 in let size = header + (n * 8) in let vec = mk_float64_vec n in check_all size "vec" Read.bin_read_vec Write.bin_write_vec [ vec, "[| ... |]", size; mk_float64_vec 0, "[||]", 1 ]) ; ("float32_mat" >:: fun () -> let m = 128 in let n = 127 in let header = 3 + 1 in let size = header + (m * n * 4) in let mat = mk_float32_mat m n in check_all size "float32_mat" Read.bin_read_float32_mat Write.bin_write_float32_mat [ mat, "[| ... |]", size; mk_float32_mat 0 0, "[||]", 2 ]) ; ("float64_mat" >:: fun () -> let m = 10 in let n = 12 in let header = 1 + 1 in let size = header + (m * n * 8) in let mat = mk_float64_mat m n in check_all size "float64_mat" Read.bin_read_float64_mat Write.bin_write_float64_mat [ mat, "[| ... |]", size; mk_float64_mat 0 0, "[||]", 2 ]) ; ("mat" >:: fun () -> let m = 128 in let n = 128 in let header = 3 + 3 in let size = header + (m * n * 8) in let mat = mk_float64_mat m n in check_all size "mat" Read.bin_read_mat Write.bin_write_mat [ mat, "[| ... |]", size; mk_float64_mat 0 0, "[||]", 2 ]) ; ("bigstring" >:: fun () -> let n = 128 in let header = 3 in let size = header + n in let bstr = mk_bigstring n in check_all size "bigstring" Read.bin_read_bigstring Write.bin_write_bigstring [ bstr, "[| ... |]", size; mk_bigstring 0, "[||]", 1 ]) ; ("bigstring (big)" >:: fun () -> (* [n] is a 16bits integer that will be serialized differently depending on whether it is considered as an integer or an unsigned integer. *) let n = 40_000 in let header = 3 in let size = header + n in let bstr = mk_bigstring n in check_all size "bigstring" Read.bin_read_bigstring Write.bin_write_bigstring [ bstr, "[| ... |]", size; mk_bigstring 0, "[||]", 1 ]) ; ("variant_tag" >:: fun () -> check_all 4 "variant_tag" Read.bin_read_variant_int Write.bin_write_variant_int [ (Obj.magic `Foo : int), "`Foo", 4; (Obj.magic `Bar : int), "`Bar", 4 ]; let bad_buf = Bigstring.of_string "\000\000\000\000" in "Variant_tag" @? expect_read_error Variant_tag 0 (fun () -> Read.bin_read_variant_int bad_buf ~pos_ref:(ref 0))) ; ("int64_bits" >:: fun () -> check_all 8 "int64_bits" Read.bin_read_int64_bits Write.bin_write_int64_bits [ Int64.min_int, "min_int", 8 ; Int64.add Int64.min_int Int64.one, "min_int + 1", 8 ; Int64.minus_one, "-1", 8 ; Int64.zero, "0", 8 ; Int64.one, "1", 8 ; Int64.sub Int64.max_int Int64.one, "max_int - 1", 8 ; Int64.max_int, "max_int", 8 ]) ; ("int_64bit" >:: fun () -> check_all 8 "int_64bit" Read.bin_read_int_64bit Write.bin_write_int_64bit [ min_int, "min_int", 8 ; min_int + 1, "min_int + 1", 8 ; -1, "-1", 8 ; 0, "0", 8 ; 1, "1", 8 ; max_int - 1, "max_int - 1", 8 ; max_int, "max_int", 8 ]; let bad_buf_max = bin_dump bin_int64_bits.writer (Int64.succ (Int64.of_int max_int)) in "Int_overflow (positive)" @? expect_read_error Int_overflow 0 (fun () -> Read.bin_read_int_64bit bad_buf_max ~pos_ref:(ref 0)); let bad_buf_min = bin_dump bin_int64_bits.writer (Int64.pred (Int64.of_int min_int)) in "Int_overflow (negative)" @? expect_read_error Int_overflow 0 (fun () -> Read.bin_read_int_64bit bad_buf_min ~pos_ref:(ref 0))) ; ("network16_int" >:: fun () -> check_all 2 "network16_int" Read.bin_read_network16_int Write.bin_write_network16_int [ (* No negative numbers - ambiguous on 64bit platforms *) 0, "0", 2 ; 1, "1", 2 ]) ; ("network32_int" >:: fun () -> check_all 4 "network32_int" Read.bin_read_network32_int Write.bin_write_network32_int [ (* No negative numbers - ambiguous on 64bit platforms *) 0, "0", 4 ; 1, "1", 4 ]) ; ("network32_int32" >:: fun () -> check_all 4 "network32_int32" Read.bin_read_network32_int32 Write.bin_write_network32_int32 [ -1l, "-1", 4; 0l, "0", 4; 1l, "1", 4 ]) ; ("network64_int" >:: fun () -> check_all 8 "network64_int" Read.bin_read_network64_int Write.bin_write_network64_int [ -1, "-1", 8; 0, "0", 8; 1, "1", 8 ]) ; ("network64_int64" >:: fun () -> check_all 8 "network64_int64" Read.bin_read_network64_int64 Write.bin_write_network64_int64 [ -1L, "-1", 8; 0L, "0", 8; 1L, "1", 8 ]) ] ;; module Common = struct type tuple = float * string * int64 [@@deriving bin_io] type 'a record = { a : int ; b : 'a ; c : 'a option } [@@deriving bin_io] type 'a singleton_record = { y : 'a } [@@deriving bin_io] type 'a inline_record = | IR of { mutable ir_a : int ; ir_b : 'a ; ir_c : 'a option } | Other of int [@@deriving bin_io] type 'a sum = | Foo | Bar of int | Bla of 'a * string [@@deriving bin_io] type 'a variant = [ `Foo | `Bar of int | `Bla of 'a * string ] [@@deriving bin_io] type 'a poly_app = (tuple * int singleton_record * 'a record * 'a inline_record) variant sum list [@@deriving bin_io] type 'a rec_t1 = RecFoo1 of 'a rec_t2 and 'a rec_t2 = | RecFoo2 of 'a poly_app * 'a rec_t1 | RecNone [@@deriving bin_io] type 'a poly_id = 'a rec_t1 [@@deriving bin_io] type el = float poly_id [@@deriving bin_io] type els = el array [@@deriving bin_io] module Wildcard : sig type _ transparent = int [@@deriving bin_io] type _ opaque [@@deriving bin_io] val opaque_examples : int opaque list end = struct type _ transparent = int [@@deriving bin_io] type 'a opaque = 'a option [@@deriving bin_io] let opaque_examples = [ None; Some 0; Some 1 ] end let test = "Bin_prot_common" >::: [ ("Utils.bin_dump" >:: fun () -> let el = let record = { a = 17; b = 2.78; c = None } in let inline_record = IR { ir_a = 18; ir_b = 43210.; ir_c = None } in let arg = (3.1, "foo", 42L), { y = 4321 }, record, inline_record in let variant = `Bla (arg, "fdsa") in let sum = Bla (variant, "asdf") in let poly_app = [ sum ] in RecFoo1 (RecFoo2 (poly_app, RecFoo1 RecNone)) in let els = Array.make 10 el in let buf = bin_dump ~header:true bin_els.writer els in let pos_ref = ref 0 in let els_len = Read.bin_read_int_64bit buf ~pos_ref in "pos_ref for length incorrect" @? (!pos_ref = 8); "els_len disagrees with bin_size" @? (els_len = bin_size_els els); let new_els = bin_read_els buf ~pos_ref in "new_els and els not equal" @? (els = new_els)) ] ;; end module Inline = struct let compatible xs derived_tc inline_writer inline_reader inline_tc = ListLabels.map xs ~f:(fun x -> "" >:: fun () -> "incorrect size from inline writer" @? (derived_tc.writer.size x = inline_writer.size x); "incorrect size from inline type class" @? (derived_tc.writer.size x = inline_tc.writer.size x); let buf = bin_dump derived_tc.writer x in "incorrect bin dump from inline writer" @? (buf = bin_dump inline_writer x); "incorrect bin dump from inline type class" @? (buf = bin_dump inline_tc.writer x); let val_and_len reader = let pos_ref = ref 0 in let x = reader.read buf ~pos_ref in x, !pos_ref in let _, len = val_and_len derived_tc.reader in let x', len' = val_and_len inline_reader in "incorrect value from inline reader" @? (x = x'); "incorrect length from inline reader" @? (len = len'); let x', len' = val_and_len inline_tc.reader in "incorrect value from inline type class" @? (x = x'); "incorrect length from inline type class" @? (len = len')) ;; type variant_extension = [ float Common.variant | `Baz of int * float ] [@@deriving bin_io] let test = "Bin_prot.Inline" >::: [ "simple tuple" >::: compatible [ 50.5, "hello", 1234L ] Common.bin_tuple [%bin_writer: Common.tuple] [%bin_reader: Common.tuple] [%bin_type_class: Common.tuple] ; "redefine tuple" >::: compatible [ 50.5, "hello", 1234L ] Common.bin_tuple [%bin_writer: float * string * int64] [%bin_reader: float * string * int64] [%bin_type_class: float * string * int64] ; "simple variant" >::: compatible [ `Foo; `Bar 8; `Bla (33.3, "world") ] (Common.bin_variant bin_float) [%bin_writer: float Common.variant] [%bin_reader: float Common.variant] [%bin_type_class: float Common.variant] ; "redefine variant" >::: compatible [ `Foo; `Bar 8; `Bla (33.3, "world") ] (Common.bin_variant bin_float) [%bin_writer: [ `Foo | `Bar of int | `Bla of float * string ]] [%bin_reader: [ `Foo | `Bar of int | `Bla of float * string ]] [%bin_type_class: [ `Foo | `Bar of int | `Bla of float * string ]] ; "variant_extension" >::: compatible [ `Foo; `Bar 8; `Bla (33.3, "world"); `Baz (17, 17.71) ] bin_variant_extension [%bin_writer: [ float Common.variant | `Baz of int * float ]] [%bin_reader: [ float Common.variant | `Baz of int * float ]] [%bin_type_class: [ float Common.variant | `Baz of int * float ]] ; "sub variant" >::: compatible [ { Common.y = `Foo }; { y = `Bar 42 }; { y = `Bla (42, "world") } ] (Common.bin_singleton_record (Common.bin_variant bin_int)) [%bin_writer: [ `Foo | `Bar of int | `Bla of int * string ] Common.singleton_record] [%bin_reader: [ `Foo | `Bar of int | `Bla of int * string ] Common.singleton_record] [%bin_type_class: [ `Foo | `Bar of int | `Bla of int * string ] Common.singleton_record] ; "transparent wildcard" >::: compatible [ 1; 2; 3 ] (Common.Wildcard.bin_transparent bin_string) [%bin_writer: string Common.Wildcard.transparent] [%bin_reader: string Common.Wildcard.transparent] [%bin_type_class: string Common.Wildcard.transparent] ; "opaque wildcard" >::: compatible Common.Wildcard.opaque_examples (Common.Wildcard.bin_opaque bin_int) [%bin_writer: int Common.Wildcard.opaque] [%bin_reader: int Common.Wildcard.opaque] [%bin_type_class: int Common.Wildcard.opaque] ] ;; end
mpdecimal.c
#include "mpdecimal.h" #include <assert.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "basearith.h" #include "bits.h" #include "constants.h" #include "convolute.h" #include "crt.h" #include "mpalloc.h" #include "typearith.h" #ifdef PPRO #if defined(_MSC_VER) #include <float.h> #pragma float_control(precise, on) #pragma fenv_access(on) #elif !defined(__OpenBSD__) && !defined(__NetBSD__) /* C99 */ #include <fenv.h> #pragma STDC FENV_ACCESS ON #endif #endif /* Disable warning that is part of -Wextra since gcc 7.0. */ #if defined(__GNUC__) && !defined(__INTEL_COMPILER) && __GNUC__ >= 7 #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" #endif #if defined(_MSC_VER) #define ALWAYS_INLINE __forceinline #elif defined (__IBMC__) || defined(LEGACY_COMPILER) #define ALWAYS_INLINE #undef inline #define inline #else #ifdef TEST_COVERAGE #define ALWAYS_INLINE #else #define ALWAYS_INLINE inline __attribute__ ((always_inline)) #endif #endif #define MPD_NEWTONDIV_CUTOFF 1024L #define MPD_NEW_STATIC(name, flags, exp, digits, len) \ mpd_uint_t name##_data[MPD_MINALLOC_MAX]; \ mpd_t name = {flags|MPD_STATIC|MPD_STATIC_DATA, exp, digits, \ len, MPD_MINALLOC_MAX, name##_data} #define MPD_NEW_CONST(name, flags, exp, digits, len, alloc, initval) \ mpd_uint_t name##_data[alloc] = {initval}; \ mpd_t name = {flags|MPD_STATIC|MPD_CONST_DATA, exp, digits, \ len, alloc, name##_data} #define MPD_NEW_SHARED(name, a) \ mpd_t name = {(a->flags&~MPD_DATAFLAGS)|MPD_STATIC|MPD_SHARED_DATA, \ a->exp, a->digits, a->len, a->alloc, a->data} static mpd_uint_t data_one[1] = {1}; static mpd_uint_t data_zero[1] = {0}; static const mpd_t one = {MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_one}; static const mpd_t minus_one = {MPD_NEG|MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_one}; static const mpd_t zero = {MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_zero}; static inline void _mpd_check_exp(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status); static void _settriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp); static inline mpd_ssize_t _mpd_real_size(mpd_uint_t *data, mpd_ssize_t size); static int _mpd_cmp_abs(const mpd_t *a, const mpd_t *b); static void _mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); static inline void _mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status); static void _mpd_base_ndivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, uint32_t *status); static inline void _mpd_qpow_uint(mpd_t *result, const mpd_t *base, mpd_uint_t exp, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status); static mpd_uint_t mpd_qsshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n); /******************************************************************************/ /* Version */ /******************************************************************************/ const char * mpd_version(void) { return MPD_VERSION; } /******************************************************************************/ /* Performance critical inline functions */ /******************************************************************************/ #ifdef CONFIG_64 /* Digits in a word, primarily useful for the most significant word. */ ALWAYS_INLINE int mpd_word_digits(mpd_uint_t word) { if (word < mpd_pow10[9]) { if (word < mpd_pow10[4]) { if (word < mpd_pow10[2]) { return (word < mpd_pow10[1]) ? 1 : 2; } return (word < mpd_pow10[3]) ? 3 : 4; } if (word < mpd_pow10[6]) { return (word < mpd_pow10[5]) ? 5 : 6; } if (word < mpd_pow10[8]) { return (word < mpd_pow10[7]) ? 7 : 8; } return 9; } if (word < mpd_pow10[14]) { if (word < mpd_pow10[11]) { return (word < mpd_pow10[10]) ? 10 : 11; } if (word < mpd_pow10[13]) { return (word < mpd_pow10[12]) ? 12 : 13; } return 14; } if (word < mpd_pow10[18]) { if (word < mpd_pow10[16]) { return (word < mpd_pow10[15]) ? 15 : 16; } return (word < mpd_pow10[17]) ? 17 : 18; } return (word < mpd_pow10[19]) ? 19 : 20; } #else ALWAYS_INLINE int mpd_word_digits(mpd_uint_t word) { if (word < mpd_pow10[4]) { if (word < mpd_pow10[2]) { return (word < mpd_pow10[1]) ? 1 : 2; } return (word < mpd_pow10[3]) ? 3 : 4; } if (word < mpd_pow10[6]) { return (word < mpd_pow10[5]) ? 5 : 6; } if (word < mpd_pow10[8]) { return (word < mpd_pow10[7]) ? 7 : 8; } return (word < mpd_pow10[9]) ? 9 : 10; } #endif /* Adjusted exponent */ ALWAYS_INLINE mpd_ssize_t mpd_adjexp(const mpd_t *dec) { return (dec->exp + dec->digits) - 1; } /* Etiny */ ALWAYS_INLINE mpd_ssize_t mpd_etiny(const mpd_context_t *ctx) { return ctx->emin - (ctx->prec - 1); } /* Etop: used for folding down in IEEE clamping */ ALWAYS_INLINE mpd_ssize_t mpd_etop(const mpd_context_t *ctx) { return ctx->emax - (ctx->prec - 1); } /* Most significant word */ ALWAYS_INLINE mpd_uint_t mpd_msword(const mpd_t *dec) { assert(dec->len > 0); return dec->data[dec->len-1]; } /* Most significant digit of a word */ inline mpd_uint_t mpd_msd(mpd_uint_t word) { int n; n = mpd_word_digits(word); return word / mpd_pow10[n-1]; } /* Least significant digit of a word */ ALWAYS_INLINE mpd_uint_t mpd_lsd(mpd_uint_t word) { return word % 10; } /* Coefficient size needed to store 'digits' */ mpd_ssize_t mpd_digits_to_size(mpd_ssize_t digits) { mpd_ssize_t q, r; _mpd_idiv_word(&q, &r, digits, MPD_RDIGITS); return (r == 0) ? q : q+1; } /* Number of digits in the exponent. Not defined for MPD_SSIZE_MIN. */ inline int mpd_exp_digits(mpd_ssize_t exp) { exp = (exp < 0) ? -exp : exp; return mpd_word_digits(exp); } /* Canonical */ ALWAYS_INLINE int mpd_iscanonical(const mpd_t *dec) { (void)dec; return 1; } /* Finite */ ALWAYS_INLINE int mpd_isfinite(const mpd_t *dec) { return !(dec->flags & MPD_SPECIAL); } /* Infinite */ ALWAYS_INLINE int mpd_isinfinite(const mpd_t *dec) { return dec->flags & MPD_INF; } /* NaN */ ALWAYS_INLINE int mpd_isnan(const mpd_t *dec) { return dec->flags & (MPD_NAN|MPD_SNAN); } /* Negative */ ALWAYS_INLINE int mpd_isnegative(const mpd_t *dec) { return dec->flags & MPD_NEG; } /* Positive */ ALWAYS_INLINE int mpd_ispositive(const mpd_t *dec) { return !(dec->flags & MPD_NEG); } /* qNaN */ ALWAYS_INLINE int mpd_isqnan(const mpd_t *dec) { return dec->flags & MPD_NAN; } /* Signed */ ALWAYS_INLINE int mpd_issigned(const mpd_t *dec) { return dec->flags & MPD_NEG; } /* sNaN */ ALWAYS_INLINE int mpd_issnan(const mpd_t *dec) { return dec->flags & MPD_SNAN; } /* Special */ ALWAYS_INLINE int mpd_isspecial(const mpd_t *dec) { return dec->flags & MPD_SPECIAL; } /* Zero */ ALWAYS_INLINE int mpd_iszero(const mpd_t *dec) { return !mpd_isspecial(dec) && mpd_msword(dec) == 0; } /* Test for zero when specials have been ruled out already */ ALWAYS_INLINE int mpd_iszerocoeff(const mpd_t *dec) { return mpd_msword(dec) == 0; } /* Normal */ inline int mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx) { if (mpd_isspecial(dec)) return 0; if (mpd_iszerocoeff(dec)) return 0; return mpd_adjexp(dec) >= ctx->emin; } /* Subnormal */ inline int mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx) { if (mpd_isspecial(dec)) return 0; if (mpd_iszerocoeff(dec)) return 0; return mpd_adjexp(dec) < ctx->emin; } /* Odd word */ ALWAYS_INLINE int mpd_isoddword(mpd_uint_t word) { return word & 1; } /* Odd coefficient */ ALWAYS_INLINE int mpd_isoddcoeff(const mpd_t *dec) { return mpd_isoddword(dec->data[0]); } /* 0 if dec is positive, 1 if dec is negative */ ALWAYS_INLINE uint8_t mpd_sign(const mpd_t *dec) { return dec->flags & MPD_NEG; } /* 1 if dec is positive, -1 if dec is negative */ ALWAYS_INLINE int mpd_arith_sign(const mpd_t *dec) { return 1 - 2 * mpd_isnegative(dec); } /* Radix */ ALWAYS_INLINE long mpd_radix(void) { return 10; } /* Dynamic decimal */ ALWAYS_INLINE int mpd_isdynamic(const mpd_t *dec) { return !(dec->flags & MPD_STATIC); } /* Static decimal */ ALWAYS_INLINE int mpd_isstatic(const mpd_t *dec) { return dec->flags & MPD_STATIC; } /* Data of decimal is dynamic */ ALWAYS_INLINE int mpd_isdynamic_data(const mpd_t *dec) { return !(dec->flags & MPD_DATAFLAGS); } /* Data of decimal is static */ ALWAYS_INLINE int mpd_isstatic_data(const mpd_t *dec) { return dec->flags & MPD_STATIC_DATA; } /* Data of decimal is shared */ ALWAYS_INLINE int mpd_isshared_data(const mpd_t *dec) { return dec->flags & MPD_SHARED_DATA; } /* Data of decimal is const */ ALWAYS_INLINE int mpd_isconst_data(const mpd_t *dec) { return dec->flags & MPD_CONST_DATA; } /******************************************************************************/ /* Inline memory handling */ /******************************************************************************/ /* Fill destination with zeros */ ALWAYS_INLINE void mpd_uint_zero(mpd_uint_t *dest, mpd_size_t len) { mpd_size_t i; for (i = 0; i < len; i++) { dest[i] = 0; } } /* Free a decimal */ ALWAYS_INLINE void mpd_del(mpd_t *dec) { if (mpd_isdynamic_data(dec)) { mpd_free(dec->data); } if (mpd_isdynamic(dec)) { mpd_free(dec); } } /* * Resize the coefficient. Existing data up to 'nwords' is left untouched. * Return 1 on success, 0 otherwise. * * Input invariant: MPD_MINALLOC <= result->alloc. * * Case nwords == result->alloc: * 'result' is unchanged. Return 1. * * Case nwords > result->alloc: * Case realloc success: * The value of 'result' does not change. Return 1. * Case realloc failure: * 'result' is NaN, status is updated with MPD_Malloc_error. Return 0. * * Case nwords < result->alloc: * Case is_static_data or realloc failure [1]: * 'result' is unchanged. Return 1. * Case realloc success: * The value of result is undefined (expected). Return 1. * * * [1] In that case the old (now oversized) area is still valid. */ ALWAYS_INLINE int mpd_qresize(mpd_t *result, mpd_ssize_t nwords, uint32_t *status) { assert(!mpd_isconst_data(result)); /* illegal operation for a const */ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */ assert(MPD_MINALLOC <= result->alloc); nwords = (nwords <= MPD_MINALLOC) ? MPD_MINALLOC : nwords; if (nwords == result->alloc) { return 1; } if (mpd_isstatic_data(result)) { if (nwords > result->alloc) { return mpd_switch_to_dyn(result, nwords, status); } return 1; } return mpd_realloc_dyn(result, nwords, status); } /* Same as mpd_qresize, but do not set the result no NaN on failure. */ static ALWAYS_INLINE int mpd_qresize_cxx(mpd_t *result, mpd_ssize_t nwords) { assert(!mpd_isconst_data(result)); /* illegal operation for a const */ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */ assert(MPD_MINALLOC <= result->alloc); nwords = (nwords <= MPD_MINALLOC) ? MPD_MINALLOC : nwords; if (nwords == result->alloc) { return 1; } if (mpd_isstatic_data(result)) { if (nwords > result->alloc) { return mpd_switch_to_dyn_cxx(result, nwords); } return 1; } return mpd_realloc_dyn_cxx(result, nwords); } /* Same as mpd_qresize, but the complete coefficient (including the old * memory area!) is initialized to zero. */ ALWAYS_INLINE int mpd_qresize_zero(mpd_t *result, mpd_ssize_t nwords, uint32_t *status) { assert(!mpd_isconst_data(result)); /* illegal operation for a const */ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */ assert(MPD_MINALLOC <= result->alloc); nwords = (nwords <= MPD_MINALLOC) ? MPD_MINALLOC : nwords; if (nwords != result->alloc) { if (mpd_isstatic_data(result)) { if (nwords > result->alloc) { return mpd_switch_to_dyn_zero(result, nwords, status); } } else if (!mpd_realloc_dyn(result, nwords, status)) { return 0; } } mpd_uint_zero(result->data, nwords); return 1; } /* * Reduce memory size for the coefficient to MPD_MINALLOC. In theory, * realloc may fail even when reducing the memory size. But in that case * the old memory area is always big enough, so checking for MPD_Malloc_error * is not imperative. */ ALWAYS_INLINE void mpd_minalloc(mpd_t *result) { assert(!mpd_isconst_data(result)); /* illegal operation for a const */ assert(!mpd_isshared_data(result)); /* illegal operation for a shared */ if (!mpd_isstatic_data(result) && result->alloc > MPD_MINALLOC) { uint8_t err = 0; result->data = mpd_realloc(result->data, MPD_MINALLOC, sizeof *result->data, &err); if (!err) { result->alloc = MPD_MINALLOC; } } } int mpd_resize(mpd_t *result, mpd_ssize_t nwords, mpd_context_t *ctx) { uint32_t status = 0; if (!mpd_qresize(result, nwords, &status)) { mpd_addstatus_raise(ctx, status); return 0; } return 1; } int mpd_resize_zero(mpd_t *result, mpd_ssize_t nwords, mpd_context_t *ctx) { uint32_t status = 0; if (!mpd_qresize_zero(result, nwords, &status)) { mpd_addstatus_raise(ctx, status); return 0; } return 1; } /******************************************************************************/ /* Set attributes of a decimal */ /******************************************************************************/ /* Set digits. Assumption: result->len is initialized and > 0. */ inline void mpd_setdigits(mpd_t *result) { mpd_ssize_t wdigits = mpd_word_digits(mpd_msword(result)); result->digits = wdigits + (result->len-1) * MPD_RDIGITS; } /* Set sign */ ALWAYS_INLINE void mpd_set_sign(mpd_t *result, uint8_t sign) { result->flags &= ~MPD_NEG; result->flags |= sign; } /* Copy sign from another decimal */ ALWAYS_INLINE void mpd_signcpy(mpd_t *result, const mpd_t *a) { uint8_t sign = a->flags&MPD_NEG; result->flags &= ~MPD_NEG; result->flags |= sign; } /* Set infinity */ ALWAYS_INLINE void mpd_set_infinity(mpd_t *result) { result->flags &= ~MPD_SPECIAL; result->flags |= MPD_INF; } /* Set qNaN */ ALWAYS_INLINE void mpd_set_qnan(mpd_t *result) { result->flags &= ~MPD_SPECIAL; result->flags |= MPD_NAN; } /* Set sNaN */ ALWAYS_INLINE void mpd_set_snan(mpd_t *result) { result->flags &= ~MPD_SPECIAL; result->flags |= MPD_SNAN; } /* Set to negative */ ALWAYS_INLINE void mpd_set_negative(mpd_t *result) { result->flags |= MPD_NEG; } /* Set to positive */ ALWAYS_INLINE void mpd_set_positive(mpd_t *result) { result->flags &= ~MPD_NEG; } /* Set to dynamic */ ALWAYS_INLINE void mpd_set_dynamic(mpd_t *result) { result->flags &= ~MPD_STATIC; } /* Set to static */ ALWAYS_INLINE void mpd_set_static(mpd_t *result) { result->flags |= MPD_STATIC; } /* Set data to dynamic */ ALWAYS_INLINE void mpd_set_dynamic_data(mpd_t *result) { result->flags &= ~MPD_DATAFLAGS; } /* Set data to static */ ALWAYS_INLINE void mpd_set_static_data(mpd_t *result) { result->flags &= ~MPD_DATAFLAGS; result->flags |= MPD_STATIC_DATA; } /* Set data to shared */ ALWAYS_INLINE void mpd_set_shared_data(mpd_t *result) { result->flags &= ~MPD_DATAFLAGS; result->flags |= MPD_SHARED_DATA; } /* Set data to const */ ALWAYS_INLINE void mpd_set_const_data(mpd_t *result) { result->flags &= ~MPD_DATAFLAGS; result->flags |= MPD_CONST_DATA; } /* Clear flags, preserving memory attributes. */ ALWAYS_INLINE void mpd_clear_flags(mpd_t *result) { result->flags &= (MPD_STATIC|MPD_DATAFLAGS); } /* Set flags, preserving memory attributes. */ ALWAYS_INLINE void mpd_set_flags(mpd_t *result, uint8_t flags) { result->flags &= (MPD_STATIC|MPD_DATAFLAGS); result->flags |= flags; } /* Copy flags, preserving memory attributes of result. */ ALWAYS_INLINE void mpd_copy_flags(mpd_t *result, const mpd_t *a) { uint8_t aflags = a->flags; result->flags &= (MPD_STATIC|MPD_DATAFLAGS); result->flags |= (aflags & ~(MPD_STATIC|MPD_DATAFLAGS)); } /* Initialize a workcontext from ctx. Set traps, flags and newtrap to 0. */ static inline void mpd_workcontext(mpd_context_t *workctx, const mpd_context_t *ctx) { workctx->prec = ctx->prec; workctx->emax = ctx->emax; workctx->emin = ctx->emin; workctx->round = ctx->round; workctx->traps = 0; workctx->status = 0; workctx->newtrap = 0; workctx->clamp = ctx->clamp; workctx->allcr = ctx->allcr; } /******************************************************************************/ /* Getting and setting parts of decimals */ /******************************************************************************/ /* Flip the sign of a decimal */ static inline void _mpd_negate(mpd_t *dec) { dec->flags ^= MPD_NEG; } /* Set coefficient to zero */ void mpd_zerocoeff(mpd_t *result) { mpd_minalloc(result); result->digits = 1; result->len = 1; result->data[0] = 0; } /* Set the coefficient to all nines. */ void mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status) { mpd_ssize_t len, r; _mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS); len = (r == 0) ? len : len+1; if (!mpd_qresize(result, len, status)) { return; } result->len = len; result->digits = ctx->prec; --len; if (r > 0) { result->data[len--] = mpd_pow10[r]-1; } for (; len >= 0; --len) { result->data[len] = MPD_RADIX-1; } } /* * Cut off the most significant digits so that the rest fits in ctx->prec. * Cannot fail. */ static void _mpd_cap(mpd_t *result, const mpd_context_t *ctx) { uint32_t dummy; mpd_ssize_t len, r; if (result->len > 0 && result->digits > ctx->prec) { _mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS); len = (r == 0) ? len : len+1; if (r != 0) { result->data[len-1] %= mpd_pow10[r]; } len = _mpd_real_size(result->data, len); /* resize to fewer words cannot fail */ mpd_qresize(result, len, &dummy); result->len = len; mpd_setdigits(result); } if (mpd_iszero(result)) { _settriple(result, mpd_sign(result), 0, result->exp); } } /* * Cut off the most significant digits of a NaN payload so that the rest * fits in ctx->prec - ctx->clamp. Cannot fail. */ static void _mpd_fix_nan(mpd_t *result, const mpd_context_t *ctx) { uint32_t dummy; mpd_ssize_t prec; mpd_ssize_t len, r; prec = ctx->prec - ctx->clamp; if (result->len > 0 && result->digits > prec) { if (prec == 0) { mpd_minalloc(result); result->len = result->digits = 0; } else { _mpd_idiv_word(&len, &r, prec, MPD_RDIGITS); len = (r == 0) ? len : len+1; if (r != 0) { result->data[len-1] %= mpd_pow10[r]; } len = _mpd_real_size(result->data, len); /* resize to fewer words cannot fail */ mpd_qresize(result, len, &dummy); result->len = len; mpd_setdigits(result); if (mpd_iszerocoeff(result)) { /* NaN0 is not a valid representation */ result->len = result->digits = 0; } } } } /* * Get n most significant digits from a decimal, where 0 < n <= MPD_UINT_DIGITS. * Assumes MPD_UINT_DIGITS == MPD_RDIGITS+1, which is true for 32 and 64 bit * machines. * * The result of the operation will be in lo. If the operation is impossible, * hi will be nonzero. This is used to indicate an error. */ static inline void _mpd_get_msdigits(mpd_uint_t *hi, mpd_uint_t *lo, const mpd_t *dec, unsigned int n) { mpd_uint_t r, tmp; assert(0 < n && n <= MPD_RDIGITS+1); _mpd_div_word(&tmp, &r, dec->digits, MPD_RDIGITS); r = (r == 0) ? MPD_RDIGITS : r; /* digits in the most significant word */ *hi = 0; *lo = dec->data[dec->len-1]; if (n <= r) { *lo /= mpd_pow10[r-n]; } else if (dec->len > 1) { /* at this point 1 <= r < n <= MPD_RDIGITS+1 */ _mpd_mul_words(hi, lo, *lo, mpd_pow10[n-r]); tmp = dec->data[dec->len-2] / mpd_pow10[MPD_RDIGITS-(n-r)]; *lo = *lo + tmp; if (*lo < tmp) (*hi)++; } } /******************************************************************************/ /* Gathering information about a decimal */ /******************************************************************************/ /* The real size of the coefficient without leading zero words. */ static inline mpd_ssize_t _mpd_real_size(mpd_uint_t *data, mpd_ssize_t size) { while (size > 1 && data[size-1] == 0) { size--; } return size; } /* Return number of trailing zeros. No errors are possible. */ mpd_ssize_t mpd_trail_zeros(const mpd_t *dec) { mpd_uint_t word; mpd_ssize_t i, tz = 0; for (i=0; i < dec->len; ++i) { if (dec->data[i] != 0) { word = dec->data[i]; tz = i * MPD_RDIGITS; while (word % 10 == 0) { word /= 10; tz++; } break; } } return tz; } /* Integer: Undefined for specials */ static int _mpd_isint(const mpd_t *dec) { mpd_ssize_t tz; if (mpd_iszerocoeff(dec)) { return 1; } tz = mpd_trail_zeros(dec); return (dec->exp + tz >= 0); } /* Integer */ int mpd_isinteger(const mpd_t *dec) { if (mpd_isspecial(dec)) { return 0; } return _mpd_isint(dec); } /* Word is a power of 10 */ static int mpd_word_ispow10(mpd_uint_t word) { int n; n = mpd_word_digits(word); if (word == mpd_pow10[n-1]) { return 1; } return 0; } /* Coefficient is a power of 10 */ static int mpd_coeff_ispow10(const mpd_t *dec) { if (mpd_word_ispow10(mpd_msword(dec))) { if (_mpd_isallzero(dec->data, dec->len-1)) { return 1; } } return 0; } /* All digits of a word are nines */ static int mpd_word_isallnine(mpd_uint_t word) { int n; n = mpd_word_digits(word); if (word == mpd_pow10[n]-1) { return 1; } return 0; } /* All digits of the coefficient are nines */ static int mpd_coeff_isallnine(const mpd_t *dec) { if (mpd_word_isallnine(mpd_msword(dec))) { if (_mpd_isallnine(dec->data, dec->len-1)) { return 1; } } return 0; } /* Odd decimal: Undefined for non-integers! */ int mpd_isodd(const mpd_t *dec) { mpd_uint_t q, r; assert(mpd_isinteger(dec)); if (mpd_iszerocoeff(dec)) return 0; if (dec->exp < 0) { _mpd_div_word(&q, &r, -dec->exp, MPD_RDIGITS); q = dec->data[q] / mpd_pow10[r]; return mpd_isoddword(q); } return dec->exp == 0 && mpd_isoddword(dec->data[0]); } /* Even: Undefined for non-integers! */ int mpd_iseven(const mpd_t *dec) { return !mpd_isodd(dec); } /******************************************************************************/ /* Getting and setting decimals */ /******************************************************************************/ /* Internal function: Set a static decimal from a triple, no error checking. */ static void _ssettriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp) { mpd_set_flags(result, sign); result->exp = exp; _mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX); result->len = (result->data[1] == 0) ? 1 : 2; mpd_setdigits(result); } /* Internal function: Set a decimal from a triple, no error checking. */ static void _settriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp) { mpd_minalloc(result); mpd_set_flags(result, sign); result->exp = exp; _mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX); result->len = (result->data[1] == 0) ? 1 : 2; mpd_setdigits(result); } /* Set a special number from a triple */ void mpd_setspecial(mpd_t *result, uint8_t sign, uint8_t type) { mpd_minalloc(result); result->flags &= ~(MPD_NEG|MPD_SPECIAL); result->flags |= (sign|type); result->exp = result->digits = result->len = 0; } /* Set result of NaN with an error status */ void mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status) { mpd_minalloc(result); mpd_set_qnan(result); mpd_set_positive(result); result->exp = result->digits = result->len = 0; *status |= flags; } /* quietly set a static decimal from an mpd_ssize_t */ void mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_uint_t u; uint8_t sign = MPD_POS; if (a < 0) { if (a == MPD_SSIZE_MIN) { u = (mpd_uint_t)MPD_SSIZE_MAX + (-(MPD_SSIZE_MIN+MPD_SSIZE_MAX)); } else { u = -a; } sign = MPD_NEG; } else { u = a; } _ssettriple(result, sign, u, 0); mpd_qfinalize(result, ctx, status); } /* quietly set a static decimal from an mpd_uint_t */ void mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status) { _ssettriple(result, MPD_POS, a, 0); mpd_qfinalize(result, ctx, status); } /* quietly set a static decimal from an int32_t */ void mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_qsset_ssize(result, a, ctx, status); } /* quietly set a static decimal from a uint32_t */ void mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_qsset_uint(result, a, ctx, status); } #ifdef CONFIG_64 /* quietly set a static decimal from an int64_t */ void mpd_qsset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_qsset_ssize(result, a, ctx, status); } /* quietly set a static decimal from a uint64_t */ void mpd_qsset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_qsset_uint(result, a, ctx, status); } #endif /* quietly set a decimal from an mpd_ssize_t */ void mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_minalloc(result); mpd_qsset_ssize(result, a, ctx, status); } /* quietly set a decimal from an mpd_uint_t */ void mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx, uint32_t *status) { _settriple(result, MPD_POS, a, 0); mpd_qfinalize(result, ctx, status); } /* quietly set a decimal from an int32_t */ void mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_qset_ssize(result, a, ctx, status); } /* quietly set a decimal from a uint32_t */ void mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx, uint32_t *status) { mpd_qset_uint(result, a, ctx, status); } #if defined(CONFIG_32) && !defined(LEGACY_COMPILER) /* set a decimal from a uint64_t */ static void _c32setu64(mpd_t *result, uint64_t u, uint8_t sign, uint32_t *status) { mpd_uint_t w[3]; uint64_t q; int i, len; len = 0; do { q = u / MPD_RADIX; w[len] = (mpd_uint_t)(u - q * MPD_RADIX); u = q; len++; } while (u != 0); if (!mpd_qresize(result, len, status)) { return; } for (i = 0; i < len; i++) { result->data[i] = w[i]; } mpd_set_flags(result, sign); result->exp = 0; result->len = len; mpd_setdigits(result); } static void _c32_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status) { _c32setu64(result, a, MPD_POS, status); mpd_qfinalize(result, ctx, status); } /* set a decimal from an int64_t */ static void _c32_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status) { uint64_t u; uint8_t sign = MPD_POS; if (a < 0) { if (a == INT64_MIN) { u = (uint64_t)INT64_MAX + (-(INT64_MIN+INT64_MAX)); } else { u = -a; } sign = MPD_NEG; } else { u = a; } _c32setu64(result, u, sign, status); mpd_qfinalize(result, ctx, status); } #endif /* CONFIG_32 && !LEGACY_COMPILER */ #ifndef LEGACY_COMPILER /* quietly set a decimal from an int64_t */ void mpd_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx, uint32_t *status) { #ifdef CONFIG_64 mpd_qset_ssize(result, a, ctx, status); #else _c32_qset_i64(result, a, ctx, status); #endif } /* quietly set a decimal from an int64_t, use a maxcontext for conversion */ void mpd_qset_i64_exact(mpd_t *result, int64_t a, uint32_t *status) { mpd_context_t maxcontext; mpd_maxcontext(&maxcontext); #ifdef CONFIG_64 mpd_qset_ssize(result, a, &maxcontext, status); #else _c32_qset_i64(result, a, &maxcontext, status); #endif if (*status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) { /* we want exact results */ mpd_seterror(result, MPD_Invalid_operation, status); } *status &= MPD_Errors; } /* quietly set a decimal from a uint64_t */ void mpd_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx, uint32_t *status) { #ifdef CONFIG_64 mpd_qset_uint(result, a, ctx, status); #else _c32_qset_u64(result, a, ctx, status); #endif } /* quietly set a decimal from a uint64_t, use a maxcontext for conversion */ void mpd_qset_u64_exact(mpd_t *result, uint64_t a, uint32_t *status) { mpd_context_t maxcontext; mpd_maxcontext(&maxcontext); #ifdef CONFIG_64 mpd_qset_uint(result, a, &maxcontext, status); #else _c32_qset_u64(result, a, &maxcontext, status); #endif if (*status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) { /* we want exact results */ mpd_seterror(result, MPD_Invalid_operation, status); } *status &= MPD_Errors; } #endif /* !LEGACY_COMPILER */ /* * Quietly get an mpd_uint_t from a decimal. Assumes * MPD_UINT_DIGITS == MPD_RDIGITS+1, which is true for * 32 and 64 bit machines. * * If the operation is impossible, MPD_Invalid_operation is set. */ static mpd_uint_t _mpd_qget_uint(int use_sign, const mpd_t *a, uint32_t *status) { mpd_t tmp; mpd_uint_t tmp_data[2]; mpd_uint_t lo, hi; if (mpd_isspecial(a)) { *status |= MPD_Invalid_operation; return MPD_UINT_MAX; } if (mpd_iszero(a)) { return 0; } if (use_sign && mpd_isnegative(a)) { *status |= MPD_Invalid_operation; return MPD_UINT_MAX; } if (a->digits+a->exp > MPD_RDIGITS+1) { *status |= MPD_Invalid_operation; return MPD_UINT_MAX; } if (a->exp < 0) { if (!_mpd_isint(a)) { *status |= MPD_Invalid_operation; return MPD_UINT_MAX; } /* At this point a->digits+a->exp <= MPD_RDIGITS+1, * so the shift fits. */ tmp.data = tmp_data; tmp.flags = MPD_STATIC|MPD_STATIC_DATA; tmp.alloc = 2; mpd_qsshiftr(&tmp, a, -a->exp); tmp.exp = 0; a = &tmp; } _mpd_get_msdigits(&hi, &lo, a, MPD_RDIGITS+1); if (hi) { *status |= MPD_Invalid_operation; return MPD_UINT_MAX; } if (a->exp > 0) { _mpd_mul_words(&hi, &lo, lo, mpd_pow10[a->exp]); if (hi) { *status |= MPD_Invalid_operation; return MPD_UINT_MAX; } } return lo; } /* * Sets Invalid_operation for: * - specials * - negative numbers (except negative zero) * - non-integers * - overflow */ mpd_uint_t mpd_qget_uint(const mpd_t *a, uint32_t *status) { return _mpd_qget_uint(1, a, status); } /* Same as above, but gets the absolute value, i.e. the sign is ignored. */ mpd_uint_t mpd_qabs_uint(const mpd_t *a, uint32_t *status) { return _mpd_qget_uint(0, a, status); } /* quietly get an mpd_ssize_t from a decimal */ mpd_ssize_t mpd_qget_ssize(const mpd_t *a, uint32_t *status) { uint32_t workstatus = 0; mpd_uint_t u; int isneg; u = mpd_qabs_uint(a, &workstatus); if (workstatus&MPD_Invalid_operation) { *status |= workstatus; return MPD_SSIZE_MAX; } isneg = mpd_isnegative(a); if (u <= MPD_SSIZE_MAX) { return isneg ? -((mpd_ssize_t)u) : (mpd_ssize_t)u; } else if (isneg && u+(MPD_SSIZE_MIN+MPD_SSIZE_MAX) == MPD_SSIZE_MAX) { return MPD_SSIZE_MIN; } *status |= MPD_Invalid_operation; return MPD_SSIZE_MAX; } #if defined(CONFIG_32) && !defined(LEGACY_COMPILER) /* * Quietly get a uint64_t from a decimal. If the operation is impossible, * MPD_Invalid_operation is set. */ static uint64_t _c32_qget_u64(int use_sign, const mpd_t *a, uint32_t *status) { MPD_NEW_STATIC(tmp,0,0,20,3); mpd_context_t maxcontext; uint64_t ret; tmp_data[0] = 709551615; tmp_data[1] = 446744073; tmp_data[2] = 18; if (mpd_isspecial(a)) { *status |= MPD_Invalid_operation; return UINT64_MAX; } if (mpd_iszero(a)) { return 0; } if (use_sign && mpd_isnegative(a)) { *status |= MPD_Invalid_operation; return UINT64_MAX; } if (!_mpd_isint(a)) { *status |= MPD_Invalid_operation; return UINT64_MAX; } if (_mpd_cmp_abs(a, &tmp) > 0) { *status |= MPD_Invalid_operation; return UINT64_MAX; } mpd_maxcontext(&maxcontext); mpd_qrescale(&tmp, a, 0, &maxcontext, &maxcontext.status); maxcontext.status &= ~MPD_Rounded; if (maxcontext.status != 0) { *status |= (maxcontext.status|MPD_Invalid_operation); /* GCOV_NOT_REACHED */ return UINT64_MAX; /* GCOV_NOT_REACHED */ } ret = 0; switch (tmp.len) { case 3: ret += (uint64_t)tmp_data[2] * 1000000000000000000ULL; case 2: ret += (uint64_t)tmp_data[1] * 1000000000ULL; case 1: ret += tmp_data[0]; break; default: abort(); /* GCOV_NOT_REACHED */ } return ret; } static int64_t _c32_qget_i64(const mpd_t *a, uint32_t *status) { uint64_t u; int isneg; u = _c32_qget_u64(0, a, status); if (*status&MPD_Invalid_operation) { return INT64_MAX; } isneg = mpd_isnegative(a); if (u <= INT64_MAX) { return isneg ? -((int64_t)u) : (int64_t)u; } else if (isneg && u+(INT64_MIN+INT64_MAX) == INT64_MAX) { return INT64_MIN; } *status |= MPD_Invalid_operation; return INT64_MAX; } #endif /* CONFIG_32 && !LEGACY_COMPILER */ #ifdef CONFIG_64 /* quietly get a uint64_t from a decimal */ uint64_t mpd_qget_u64(const mpd_t *a, uint32_t *status) { return mpd_qget_uint(a, status); } /* quietly get an int64_t from a decimal */ int64_t mpd_qget_i64(const mpd_t *a, uint32_t *status) { return mpd_qget_ssize(a, status); } /* quietly get a uint32_t from a decimal */ uint32_t mpd_qget_u32(const mpd_t *a, uint32_t *status) { uint32_t workstatus = 0; uint64_t x = mpd_qget_uint(a, &workstatus); if (workstatus&MPD_Invalid_operation) { *status |= workstatus; return UINT32_MAX; } if (x > UINT32_MAX) { *status |= MPD_Invalid_operation; return UINT32_MAX; } return (uint32_t)x; } /* quietly get an int32_t from a decimal */ int32_t mpd_qget_i32(const mpd_t *a, uint32_t *status) { uint32_t workstatus = 0; int64_t x = mpd_qget_ssize(a, &workstatus); if (workstatus&MPD_Invalid_operation) { *status |= workstatus; return INT32_MAX; } if (x < INT32_MIN || x > INT32_MAX) { *status |= MPD_Invalid_operation; return INT32_MAX; } return (int32_t)x; } #else #ifndef LEGACY_COMPILER /* quietly get a uint64_t from a decimal */ uint64_t mpd_qget_u64(const mpd_t *a, uint32_t *status) { uint32_t workstatus = 0; uint64_t x = _c32_qget_u64(1, a, &workstatus); *status |= workstatus; return x; } /* quietly get an int64_t from a decimal */ int64_t mpd_qget_i64(const mpd_t *a, uint32_t *status) { uint32_t workstatus = 0; int64_t x = _c32_qget_i64(a, &workstatus); *status |= workstatus; return x; } #endif /* quietly get a uint32_t from a decimal */ uint32_t mpd_qget_u32(const mpd_t *a, uint32_t *status) { return mpd_qget_uint(a, status); } /* quietly get an int32_t from a decimal */ int32_t mpd_qget_i32(const mpd_t *a, uint32_t *status) { return mpd_qget_ssize(a, status); } #endif /******************************************************************************/ /* Filtering input of functions, finalizing output of functions */ /******************************************************************************/ /* * Check if the operand is NaN, copy to result and return 1 if this is * the case. Copying can fail since NaNs are allowed to have a payload that * does not fit in MPD_MINALLOC. */ int mpd_qcheck_nan(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isnan(a)) { *status |= mpd_issnan(a) ? MPD_Invalid_operation : 0; mpd_qcopy(result, a, status); mpd_set_qnan(result); _mpd_fix_nan(result, ctx); return 1; } return 0; } /* * Check if either operand is NaN, copy to result and return 1 if this * is the case. Copying can fail since NaNs are allowed to have a payload * that does not fit in MPD_MINALLOC. */ int mpd_qcheck_nans(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { if ((a->flags|b->flags)&(MPD_NAN|MPD_SNAN)) { const mpd_t *choice = b; if (mpd_issnan(a)) { choice = a; *status |= MPD_Invalid_operation; } else if (mpd_issnan(b)) { *status |= MPD_Invalid_operation; } else if (mpd_isqnan(a)) { choice = a; } mpd_qcopy(result, choice, status); mpd_set_qnan(result); _mpd_fix_nan(result, ctx); return 1; } return 0; } /* * Check if one of the operands is NaN, copy to result and return 1 if this * is the case. Copying can fail since NaNs are allowed to have a payload * that does not fit in MPD_MINALLOC. */ static int mpd_qcheck_3nans(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, const mpd_context_t *ctx, uint32_t *status) { if ((a->flags|b->flags|c->flags)&(MPD_NAN|MPD_SNAN)) { const mpd_t *choice = c; if (mpd_issnan(a)) { choice = a; *status |= MPD_Invalid_operation; } else if (mpd_issnan(b)) { choice = b; *status |= MPD_Invalid_operation; } else if (mpd_issnan(c)) { *status |= MPD_Invalid_operation; } else if (mpd_isqnan(a)) { choice = a; } else if (mpd_isqnan(b)) { choice = b; } mpd_qcopy(result, choice, status); mpd_set_qnan(result); _mpd_fix_nan(result, ctx); return 1; } return 0; } /* Check if rounding digit 'rnd' leads to an increment. */ static inline int _mpd_rnd_incr(const mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx) { int ld; switch (ctx->round) { case MPD_ROUND_DOWN: case MPD_ROUND_TRUNC: return 0; case MPD_ROUND_HALF_UP: return (rnd >= 5); case MPD_ROUND_HALF_EVEN: return (rnd > 5) || ((rnd == 5) && mpd_isoddcoeff(dec)); case MPD_ROUND_CEILING: return !(rnd == 0 || mpd_isnegative(dec)); case MPD_ROUND_FLOOR: return !(rnd == 0 || mpd_ispositive(dec)); case MPD_ROUND_HALF_DOWN: return (rnd > 5); case MPD_ROUND_UP: return !(rnd == 0); case MPD_ROUND_05UP: ld = (int)mpd_lsd(dec->data[0]); return (!(rnd == 0) && (ld == 0 || ld == 5)); default: /* Without a valid context, further results will be undefined. */ return 0; /* GCOV_NOT_REACHED */ } } /* * Apply rounding to a decimal that has been right-shifted into a full * precision decimal. If an increment leads to an overflow of the precision, * adjust the coefficient and the exponent and check the new exponent for * overflow. */ static inline void _mpd_apply_round(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx, uint32_t *status) { if (_mpd_rnd_incr(dec, rnd, ctx)) { /* We have a number with exactly ctx->prec digits. The increment * can only lead to an overflow if the decimal is all nines. In * that case, the result is a power of ten with prec+1 digits. * * If the precision is a multiple of MPD_RDIGITS, this situation is * detected by _mpd_baseincr returning a carry. * If the precision is not a multiple of MPD_RDIGITS, we have to * check if the result has one digit too many. */ mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len); if (carry) { dec->data[dec->len-1] = mpd_pow10[MPD_RDIGITS-1]; dec->exp += 1; _mpd_check_exp(dec, ctx, status); return; } mpd_setdigits(dec); if (dec->digits > ctx->prec) { mpd_qshiftr_inplace(dec, 1); dec->exp += 1; dec->digits = ctx->prec; _mpd_check_exp(dec, ctx, status); } } } /* * Apply rounding to a decimal. Allow overflow of the precision. */ static inline void _mpd_apply_round_excess(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx, uint32_t *status) { if (_mpd_rnd_incr(dec, rnd, ctx)) { mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len); if (carry) { if (!mpd_qresize(dec, dec->len+1, status)) { return; } dec->data[dec->len] = 1; dec->len += 1; } mpd_setdigits(dec); } } /* * Apply rounding to a decimal that has been right-shifted into a decimal * with full precision or less. Return failure if an increment would * overflow the precision. */ static inline int _mpd_apply_round_fit(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx, uint32_t *status) { if (_mpd_rnd_incr(dec, rnd, ctx)) { mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len); if (carry) { if (!mpd_qresize(dec, dec->len+1, status)) { return 0; } dec->data[dec->len] = 1; dec->len += 1; } mpd_setdigits(dec); if (dec->digits > ctx->prec) { mpd_seterror(dec, MPD_Invalid_operation, status); return 0; } } return 1; } /* Check a normal number for overflow, underflow, clamping. If the operand is modified, it will be zero, special or (sub)normal with a coefficient that fits into the current context precision. */ static inline void _mpd_check_exp(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status) { mpd_ssize_t adjexp, etiny, shift; int rnd; adjexp = mpd_adjexp(dec); if (adjexp > ctx->emax) { if (mpd_iszerocoeff(dec)) { dec->exp = ctx->emax; if (ctx->clamp) { dec->exp -= (ctx->prec-1); } mpd_zerocoeff(dec); *status |= MPD_Clamped; return; } switch (ctx->round) { case MPD_ROUND_HALF_UP: case MPD_ROUND_HALF_EVEN: case MPD_ROUND_HALF_DOWN: case MPD_ROUND_UP: case MPD_ROUND_TRUNC: mpd_setspecial(dec, mpd_sign(dec), MPD_INF); break; case MPD_ROUND_DOWN: case MPD_ROUND_05UP: mpd_qmaxcoeff(dec, ctx, status); dec->exp = ctx->emax - ctx->prec + 1; break; case MPD_ROUND_CEILING: if (mpd_isnegative(dec)) { mpd_qmaxcoeff(dec, ctx, status); dec->exp = ctx->emax - ctx->prec + 1; } else { mpd_setspecial(dec, MPD_POS, MPD_INF); } break; case MPD_ROUND_FLOOR: if (mpd_ispositive(dec)) { mpd_qmaxcoeff(dec, ctx, status); dec->exp = ctx->emax - ctx->prec + 1; } else { mpd_setspecial(dec, MPD_NEG, MPD_INF); } break; default: /* debug */ abort(); /* GCOV_NOT_REACHED */ } *status |= MPD_Overflow|MPD_Inexact|MPD_Rounded; } /* fold down */ else if (ctx->clamp && dec->exp > mpd_etop(ctx)) { /* At this point adjexp=exp+digits-1 <= emax and exp > etop=emax-prec+1: * (1) shift = exp -emax+prec-1 > 0 * (2) digits+shift = exp+digits-1 - emax + prec <= prec */ shift = dec->exp - mpd_etop(ctx); if (!mpd_qshiftl(dec, dec, shift, status)) { return; } dec->exp -= shift; *status |= MPD_Clamped; if (!mpd_iszerocoeff(dec) && adjexp < ctx->emin) { /* Underflow is impossible, since exp < etiny=emin-prec+1 * and exp > etop=emax-prec+1 would imply emax < emin. */ *status |= MPD_Subnormal; } } else if (adjexp < ctx->emin) { etiny = mpd_etiny(ctx); if (mpd_iszerocoeff(dec)) { if (dec->exp < etiny) { dec->exp = etiny; mpd_zerocoeff(dec); *status |= MPD_Clamped; } return; } *status |= MPD_Subnormal; if (dec->exp < etiny) { /* At this point adjexp=exp+digits-1 < emin and exp < etiny=emin-prec+1: * (1) shift = emin-prec+1 - exp > 0 * (2) digits-shift = exp+digits-1 - emin + prec < prec */ shift = etiny - dec->exp; rnd = (int)mpd_qshiftr_inplace(dec, shift); dec->exp = etiny; /* We always have a spare digit in case of an increment. */ _mpd_apply_round_excess(dec, rnd, ctx, status); *status |= MPD_Rounded; if (rnd) { *status |= (MPD_Inexact|MPD_Underflow); if (mpd_iszerocoeff(dec)) { mpd_zerocoeff(dec); *status |= MPD_Clamped; } } } /* Case exp >= etiny=emin-prec+1: * (1) adjexp=exp+digits-1 < emin * (2) digits < emin-exp+1 <= prec */ } } /* Transcendental functions do not always set Underflow reliably, * since they only use as much precision as is necessary for correct * rounding. If a result like 1.0000000000e-101 is finalized, there * is no rounding digit that would trigger Underflow. But we can * assume Inexact, so a short check suffices. */ static inline void mpd_check_underflow(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status) { if (mpd_adjexp(dec) < ctx->emin && !mpd_iszero(dec) && dec->exp < mpd_etiny(ctx)) { *status |= MPD_Underflow; } } /* Check if a normal number must be rounded after the exponent has been checked. */ static inline void _mpd_check_round(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status) { mpd_uint_t rnd; mpd_ssize_t shift; /* must handle specials: _mpd_check_exp() can produce infinities or NaNs */ if (mpd_isspecial(dec)) { return; } if (dec->digits > ctx->prec) { shift = dec->digits - ctx->prec; rnd = mpd_qshiftr_inplace(dec, shift); dec->exp += shift; _mpd_apply_round(dec, rnd, ctx, status); *status |= MPD_Rounded; if (rnd) { *status |= MPD_Inexact; } } } /* Finalize all operations. */ void mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(result)) { if (mpd_isnan(result)) { _mpd_fix_nan(result, ctx); } return; } _mpd_check_exp(result, ctx, status); _mpd_check_round(result, ctx, status); } /******************************************************************************/ /* Copying */ /******************************************************************************/ /* Internal function: Copy a decimal, share data with src: USE WITH CARE! */ static inline void _mpd_copy_shared(mpd_t *dest, const mpd_t *src) { dest->flags = src->flags; dest->exp = src->exp; dest->digits = src->digits; dest->len = src->len; dest->alloc = src->alloc; dest->data = src->data; mpd_set_shared_data(dest); } /* * Copy a decimal. In case of an error, status is set to MPD_Malloc_error. */ int mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status) { if (result == a) return 1; if (!mpd_qresize(result, a->len, status)) { return 0; } mpd_copy_flags(result, a); result->exp = a->exp; result->digits = a->digits; result->len = a->len; memcpy(result->data, a->data, a->len * (sizeof *result->data)); return 1; } /* Same as mpd_qcopy, but do not set the result to NaN on failure. */ int mpd_qcopy_cxx(mpd_t *result, const mpd_t *a) { if (result == a) return 1; if (!mpd_qresize_cxx(result, a->len)) { return 0; } mpd_copy_flags(result, a); result->exp = a->exp; result->digits = a->digits; result->len = a->len; memcpy(result->data, a->data, a->len * (sizeof *result->data)); return 1; } /* * Copy to a decimal with a static buffer. The caller has to make sure that * the buffer is big enough. Cannot fail. */ static void mpd_qcopy_static(mpd_t *result, const mpd_t *a) { if (result == a) return; memcpy(result->data, a->data, a->len * (sizeof *result->data)); mpd_copy_flags(result, a); result->exp = a->exp; result->digits = a->digits; result->len = a->len; } /* * Return a newly allocated copy of the operand. In case of an error, * status is set to MPD_Malloc_error and the return value is NULL. */ mpd_t * mpd_qncopy(const mpd_t *a) { mpd_t *result; if ((result = mpd_qnew_size(a->len)) == NULL) { return NULL; } memcpy(result->data, a->data, a->len * (sizeof *result->data)); mpd_copy_flags(result, a); result->exp = a->exp; result->digits = a->digits; result->len = a->len; return result; } /* * Copy a decimal and set the sign to positive. In case of an error, the * status is set to MPD_Malloc_error. */ int mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status) { if (!mpd_qcopy(result, a, status)) { return 0; } mpd_set_positive(result); return 1; } /* * Copy a decimal and negate the sign. In case of an error, the * status is set to MPD_Malloc_error. */ int mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status) { if (!mpd_qcopy(result, a, status)) { return 0; } _mpd_negate(result); return 1; } /* * Copy a decimal, setting the sign of the first operand to the sign of the * second operand. In case of an error, the status is set to MPD_Malloc_error. */ int mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status) { uint8_t sign_b = mpd_sign(b); /* result may equal b! */ if (!mpd_qcopy(result, a, status)) { return 0; } mpd_set_sign(result, sign_b); return 1; } /******************************************************************************/ /* Comparisons */ /******************************************************************************/ /* * For all functions that compare two operands and return an int the usual * convention applies to the return value: * * -1 if op1 < op2 * 0 if op1 == op2 * 1 if op1 > op2 * * INT_MAX for error */ /* Convenience macro. If a and b are not equal, return from the calling * function with the correct comparison value. */ #define CMP_EQUAL_OR_RETURN(a, b) \ if (a != b) { \ if (a < b) { \ return -1; \ } \ return 1; \ } /* * Compare the data of big and small. This function does the equivalent * of first shifting small to the left and then comparing the data of * big and small, except that no allocation for the left shift is needed. */ static int _mpd_basecmp(mpd_uint_t *big, mpd_uint_t *small, mpd_size_t n, mpd_size_t m, mpd_size_t shift) { #if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !defined(__clang__) /* spurious uninitialized warnings */ mpd_uint_t l=l, lprev=lprev, h=h; #else mpd_uint_t l, lprev, h; #endif mpd_uint_t q, r; mpd_uint_t ph, x; assert(m > 0 && n >= m && shift > 0); _mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS); if (r != 0) { ph = mpd_pow10[r]; --m; --n; _mpd_divmod_pow10(&h, &lprev, small[m--], MPD_RDIGITS-r); if (h != 0) { CMP_EQUAL_OR_RETURN(big[n], h) --n; } for (; m != MPD_SIZE_MAX; m--,n--) { _mpd_divmod_pow10(&h, &l, small[m], MPD_RDIGITS-r); x = ph * lprev + h; CMP_EQUAL_OR_RETURN(big[n], x) lprev = l; } x = ph * lprev; CMP_EQUAL_OR_RETURN(big[q], x) } else { while (--m != MPD_SIZE_MAX) { CMP_EQUAL_OR_RETURN(big[m+q], small[m]) } } return !_mpd_isallzero(big, q); } /* Compare two decimals with the same adjusted exponent. */ static int _mpd_cmp_same_adjexp(const mpd_t *a, const mpd_t *b) { mpd_ssize_t shift, i; if (a->exp != b->exp) { /* Cannot wrap: a->exp + a->digits = b->exp + b->digits, so * a->exp - b->exp = b->digits - a->digits. */ shift = a->exp - b->exp; if (shift > 0) { return -1 * _mpd_basecmp(b->data, a->data, b->len, a->len, shift); } else { return _mpd_basecmp(a->data, b->data, a->len, b->len, -shift); } } /* * At this point adjexp(a) == adjexp(b) and a->exp == b->exp, * so a->digits == b->digits, therefore a->len == b->len. */ for (i = a->len-1; i >= 0; --i) { CMP_EQUAL_OR_RETURN(a->data[i], b->data[i]) } return 0; } /* Compare two numerical values. */ static int _mpd_cmp(const mpd_t *a, const mpd_t *b) { mpd_ssize_t adjexp_a, adjexp_b; /* equal pointers */ if (a == b) { return 0; } /* infinities */ if (mpd_isinfinite(a)) { if (mpd_isinfinite(b)) { return mpd_isnegative(b) - mpd_isnegative(a); } return mpd_arith_sign(a); } if (mpd_isinfinite(b)) { return -mpd_arith_sign(b); } /* zeros */ if (mpd_iszerocoeff(a)) { if (mpd_iszerocoeff(b)) { return 0; } return -mpd_arith_sign(b); } if (mpd_iszerocoeff(b)) { return mpd_arith_sign(a); } /* different signs */ if (mpd_sign(a) != mpd_sign(b)) { return mpd_sign(b) - mpd_sign(a); } /* different adjusted exponents */ adjexp_a = mpd_adjexp(a); adjexp_b = mpd_adjexp(b); if (adjexp_a != adjexp_b) { if (adjexp_a < adjexp_b) { return -1 * mpd_arith_sign(a); } return mpd_arith_sign(a); } /* same adjusted exponents */ return _mpd_cmp_same_adjexp(a, b) * mpd_arith_sign(a); } /* Compare the absolutes of two numerical values. */ static int _mpd_cmp_abs(const mpd_t *a, const mpd_t *b) { mpd_ssize_t adjexp_a, adjexp_b; /* equal pointers */ if (a == b) { return 0; } /* infinities */ if (mpd_isinfinite(a)) { if (mpd_isinfinite(b)) { return 0; } return 1; } if (mpd_isinfinite(b)) { return -1; } /* zeros */ if (mpd_iszerocoeff(a)) { if (mpd_iszerocoeff(b)) { return 0; } return -1; } if (mpd_iszerocoeff(b)) { return 1; } /* different adjusted exponents */ adjexp_a = mpd_adjexp(a); adjexp_b = mpd_adjexp(b); if (adjexp_a != adjexp_b) { if (adjexp_a < adjexp_b) { return -1; } return 1; } /* same adjusted exponents */ return _mpd_cmp_same_adjexp(a, b); } /* Compare two values and return an integer result. */ int mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status) { if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_isnan(a) || mpd_isnan(b)) { *status |= MPD_Invalid_operation; return INT_MAX; } } return _mpd_cmp(a, b); } /* * Compare a and b, convert the usual integer result to a decimal and * store it in 'result'. For convenience, the integer result of the comparison * is returned. Comparisons involving NaNs return NaN/INT_MAX. */ int mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return INT_MAX; } } c = _mpd_cmp(a, b); _settriple(result, (c < 0), (c != 0), 0); return c; } /* Same as mpd_compare(), but signal for all NaNs, i.e. also for quiet NaNs. */ int mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { *status |= MPD_Invalid_operation; return INT_MAX; } } c = _mpd_cmp(a, b); _settriple(result, (c < 0), (c != 0), 0); return c; } /* Compare the operands using a total order. */ int mpd_cmp_total(const mpd_t *a, const mpd_t *b) { mpd_t aa, bb; int nan_a, nan_b; int c; if (mpd_sign(a) != mpd_sign(b)) { return mpd_sign(b) - mpd_sign(a); } if (mpd_isnan(a)) { c = 1; if (mpd_isnan(b)) { nan_a = (mpd_isqnan(a)) ? 1 : 0; nan_b = (mpd_isqnan(b)) ? 1 : 0; if (nan_b == nan_a) { if (a->len > 0 && b->len > 0) { _mpd_copy_shared(&aa, a); _mpd_copy_shared(&bb, b); aa.exp = bb.exp = 0; /* compare payload */ c = _mpd_cmp_abs(&aa, &bb); } else { c = (a->len > 0) - (b->len > 0); } } else { c = nan_a - nan_b; } } } else if (mpd_isnan(b)) { c = -1; } else { c = _mpd_cmp_abs(a, b); if (c == 0 && a->exp != b->exp) { c = (a->exp < b->exp) ? -1 : 1; } } return c * mpd_arith_sign(a); } /* * Compare a and b according to a total order, convert the usual integer result * to a decimal and store it in 'result'. For convenience, the integer result * of the comparison is returned. */ int mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b) { int c; c = mpd_cmp_total(a, b); _settriple(result, (c < 0), (c != 0), 0); return c; } /* Compare the magnitude of the operands using a total order. */ int mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b) { mpd_t aa, bb; _mpd_copy_shared(&aa, a); _mpd_copy_shared(&bb, b); mpd_set_positive(&aa); mpd_set_positive(&bb); return mpd_cmp_total(&aa, &bb); } /* * Compare the magnitude of a and b according to a total order, convert the * the usual integer result to a decimal and store it in 'result'. * For convenience, the integer result of the comparison is returned. */ int mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b) { int c; c = mpd_cmp_total_mag(a, b); _settriple(result, (c < 0), (c != 0), 0); return c; } /* Determine an ordering for operands that are numerically equal. */ static inline int _mpd_cmp_numequal(const mpd_t *a, const mpd_t *b) { int sign_a, sign_b; int c; sign_a = mpd_sign(a); sign_b = mpd_sign(b); if (sign_a != sign_b) { c = sign_b - sign_a; } else { c = (a->exp < b->exp) ? -1 : 1; c *= mpd_arith_sign(a); } return c; } /******************************************************************************/ /* Shifting the coefficient */ /******************************************************************************/ /* * Shift the coefficient of the operand to the left, no check for specials. * Both operands may be the same pointer. If the result length has to be * increased, mpd_qresize() might fail with MPD_Malloc_error. */ int mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status) { mpd_ssize_t size; assert(!mpd_isspecial(a)); assert(n >= 0); if (mpd_iszerocoeff(a) || n == 0) { return mpd_qcopy(result, a, status); } size = mpd_digits_to_size(a->digits+n); if (!mpd_qresize(result, size, status)) { return 0; /* result is NaN */ } _mpd_baseshiftl(result->data, a->data, size, a->len, n); mpd_copy_flags(result, a); result->exp = a->exp; result->digits = a->digits+n; result->len = size; return 1; } /* Determine the rounding indicator if all digits of the coefficient are shifted * out of the picture. */ static mpd_uint_t _mpd_get_rnd(const mpd_uint_t *data, mpd_ssize_t len, int use_msd) { mpd_uint_t rnd = 0, rest = 0, word; word = data[len-1]; /* special treatment for the most significant digit if shift == digits */ if (use_msd) { _mpd_divmod_pow10(&rnd, &rest, word, mpd_word_digits(word)-1); if (len > 1 && rest == 0) { rest = !_mpd_isallzero(data, len-1); } } else { rest = !_mpd_isallzero(data, len); } return (rnd == 0 || rnd == 5) ? rnd + !!rest : rnd; } /* * Same as mpd_qshiftr(), but 'result' is an mpd_t with a static coefficient. * It is the caller's responsibility to ensure that the coefficient is big * enough. The function cannot fail. */ static mpd_uint_t mpd_qsshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n) { mpd_uint_t rnd; mpd_ssize_t size; assert(!mpd_isspecial(a)); assert(n >= 0); if (mpd_iszerocoeff(a) || n == 0) { mpd_qcopy_static(result, a); return 0; } if (n >= a->digits) { rnd = _mpd_get_rnd(a->data, a->len, (n==a->digits)); mpd_zerocoeff(result); } else { result->digits = a->digits-n; size = mpd_digits_to_size(result->digits); rnd = _mpd_baseshiftr(result->data, a->data, a->len, n); result->len = size; } mpd_copy_flags(result, a); result->exp = a->exp; return rnd; } /* * Inplace shift of the coefficient to the right, no check for specials. * Returns the rounding indicator for mpd_rnd_incr(). * The function cannot fail. */ mpd_uint_t mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n) { uint32_t dummy; mpd_uint_t rnd; mpd_ssize_t size; assert(!mpd_isspecial(result)); assert(n >= 0); if (mpd_iszerocoeff(result) || n == 0) { return 0; } if (n >= result->digits) { rnd = _mpd_get_rnd(result->data, result->len, (n==result->digits)); mpd_zerocoeff(result); } else { rnd = _mpd_baseshiftr(result->data, result->data, result->len, n); result->digits -= n; size = mpd_digits_to_size(result->digits); /* reducing the size cannot fail */ mpd_qresize(result, size, &dummy); result->len = size; } return rnd; } /* * Shift the coefficient of the operand to the right, no check for specials. * Both operands may be the same pointer. Returns the rounding indicator to * be used by mpd_rnd_incr(). If the result length has to be increased, * mpd_qcopy() or mpd_qresize() might fail with MPD_Malloc_error. In those * cases, MPD_UINT_MAX is returned. */ mpd_uint_t mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status) { mpd_uint_t rnd; mpd_ssize_t size; assert(!mpd_isspecial(a)); assert(n >= 0); if (mpd_iszerocoeff(a) || n == 0) { if (!mpd_qcopy(result, a, status)) { return MPD_UINT_MAX; } return 0; } if (n >= a->digits) { rnd = _mpd_get_rnd(a->data, a->len, (n==a->digits)); mpd_zerocoeff(result); } else { result->digits = a->digits-n; size = mpd_digits_to_size(result->digits); if (result == a) { rnd = _mpd_baseshiftr(result->data, a->data, a->len, n); /* reducing the size cannot fail */ mpd_qresize(result, size, status); } else { if (!mpd_qresize(result, size, status)) { return MPD_UINT_MAX; } rnd = _mpd_baseshiftr(result->data, a->data, a->len, n); } result->len = size; } mpd_copy_flags(result, a); result->exp = a->exp; return rnd; } /******************************************************************************/ /* Miscellaneous operations */ /******************************************************************************/ /* Logical And */ void mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { const mpd_t *big = a, *small = b; mpd_uint_t x, y, z, xbit, ybit; int k, mswdigits; mpd_ssize_t i; if (mpd_isspecial(a) || mpd_isspecial(b) || mpd_isnegative(a) || mpd_isnegative(b) || a->exp != 0 || b->exp != 0) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (b->digits > a->digits) { big = b; small = a; } if (!mpd_qresize(result, big->len, status)) { return; } /* full words */ for (i = 0; i < small->len-1; i++) { x = small->data[i]; y = big->data[i]; z = 0; for (k = 0; k < MPD_RDIGITS; k++) { xbit = x % 10; x /= 10; ybit = y % 10; y /= 10; if (xbit > 1 || ybit > 1) { goto invalid_operation; } z += (xbit&ybit) ? mpd_pow10[k] : 0; } result->data[i] = z; } /* most significant word of small */ x = small->data[i]; y = big->data[i]; z = 0; mswdigits = mpd_word_digits(x); for (k = 0; k < mswdigits; k++) { xbit = x % 10; x /= 10; ybit = y % 10; y /= 10; if (xbit > 1 || ybit > 1) { goto invalid_operation; } z += (xbit&ybit) ? mpd_pow10[k] : 0; } result->data[i++] = z; /* scan the rest of y for digits > 1 */ for (; k < MPD_RDIGITS; k++) { ybit = y % 10; y /= 10; if (ybit > 1) { goto invalid_operation; } } /* scan the rest of big for digits > 1 */ for (; i < big->len; i++) { y = big->data[i]; for (k = 0; k < MPD_RDIGITS; k++) { ybit = y % 10; y /= 10; if (ybit > 1) { goto invalid_operation; } } } mpd_clear_flags(result); result->exp = 0; result->len = _mpd_real_size(result->data, small->len); mpd_qresize(result, result->len, status); mpd_setdigits(result); _mpd_cap(result, ctx); return; invalid_operation: mpd_seterror(result, MPD_Invalid_operation, status); } /* Class of an operand. Returns a pointer to the constant name. */ const char * mpd_class(const mpd_t *a, const mpd_context_t *ctx) { if (mpd_isnan(a)) { if (mpd_isqnan(a)) return "NaN"; else return "sNaN"; } else if (mpd_ispositive(a)) { if (mpd_isinfinite(a)) return "+Infinity"; else if (mpd_iszero(a)) return "+Zero"; else if (mpd_isnormal(a, ctx)) return "+Normal"; else return "+Subnormal"; } else { if (mpd_isinfinite(a)) return "-Infinity"; else if (mpd_iszero(a)) return "-Zero"; else if (mpd_isnormal(a, ctx)) return "-Normal"; else return "-Subnormal"; } } /* Logical Xor */ void mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_uint_t x, z, xbit; mpd_ssize_t i, digits, len; mpd_ssize_t q, r; int k; if (mpd_isspecial(a) || mpd_isnegative(a) || a->exp != 0) { mpd_seterror(result, MPD_Invalid_operation, status); return; } digits = (a->digits < ctx->prec) ? ctx->prec : a->digits; _mpd_idiv_word(&q, &r, digits, MPD_RDIGITS); len = (r == 0) ? q : q+1; if (!mpd_qresize(result, len, status)) { return; } for (i = 0; i < len; i++) { x = (i < a->len) ? a->data[i] : 0; z = 0; for (k = 0; k < MPD_RDIGITS; k++) { xbit = x % 10; x /= 10; if (xbit > 1) { goto invalid_operation; } z += !xbit ? mpd_pow10[k] : 0; } result->data[i] = z; } mpd_clear_flags(result); result->exp = 0; result->len = _mpd_real_size(result->data, len); mpd_qresize(result, result->len, status); mpd_setdigits(result); _mpd_cap(result, ctx); return; invalid_operation: mpd_seterror(result, MPD_Invalid_operation, status); } /* Exponent of the magnitude of the most significant digit of the operand. */ void mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } mpd_setspecial(result, MPD_POS, MPD_INF); } else if (mpd_iszerocoeff(a)) { mpd_setspecial(result, MPD_NEG, MPD_INF); *status |= MPD_Division_by_zero; } else { mpd_qset_ssize(result, mpd_adjexp(a), ctx, status); } } /* Logical Or */ void mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { const mpd_t *big = a, *small = b; mpd_uint_t x, y, z, xbit, ybit; int k, mswdigits; mpd_ssize_t i; if (mpd_isspecial(a) || mpd_isspecial(b) || mpd_isnegative(a) || mpd_isnegative(b) || a->exp != 0 || b->exp != 0) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (b->digits > a->digits) { big = b; small = a; } if (!mpd_qresize(result, big->len, status)) { return; } /* full words */ for (i = 0; i < small->len-1; i++) { x = small->data[i]; y = big->data[i]; z = 0; for (k = 0; k < MPD_RDIGITS; k++) { xbit = x % 10; x /= 10; ybit = y % 10; y /= 10; if (xbit > 1 || ybit > 1) { goto invalid_operation; } z += (xbit|ybit) ? mpd_pow10[k] : 0; } result->data[i] = z; } /* most significant word of small */ x = small->data[i]; y = big->data[i]; z = 0; mswdigits = mpd_word_digits(x); for (k = 0; k < mswdigits; k++) { xbit = x % 10; x /= 10; ybit = y % 10; y /= 10; if (xbit > 1 || ybit > 1) { goto invalid_operation; } z += (xbit|ybit) ? mpd_pow10[k] : 0; } /* scan for digits > 1 and copy the rest of y */ for (; k < MPD_RDIGITS; k++) { ybit = y % 10; y /= 10; if (ybit > 1) { goto invalid_operation; } z += ybit*mpd_pow10[k]; } result->data[i++] = z; /* scan for digits > 1 and copy the rest of big */ for (; i < big->len; i++) { y = big->data[i]; for (k = 0; k < MPD_RDIGITS; k++) { ybit = y % 10; y /= 10; if (ybit > 1) { goto invalid_operation; } } result->data[i] = big->data[i]; } mpd_clear_flags(result); result->exp = 0; result->len = _mpd_real_size(result->data, big->len); mpd_qresize(result, result->len, status); mpd_setdigits(result); _mpd_cap(result, ctx); return; invalid_operation: mpd_seterror(result, MPD_Invalid_operation, status); } /* * Rotate the coefficient of 'a' by 'b' digits. 'b' must be an integer with * exponent 0. */ void mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; MPD_NEW_STATIC(tmp,0,0,0,0); MPD_NEW_STATIC(big,0,0,0,0); MPD_NEW_STATIC(small,0,0,0,0); mpd_ssize_t n, lshift, rshift; if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } } if (b->exp != 0 || mpd_isinfinite(b)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } n = mpd_qget_ssize(b, &workstatus); if (workstatus&MPD_Invalid_operation) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (n > ctx->prec || n < -ctx->prec) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_isinfinite(a)) { mpd_qcopy(result, a, status); return; } if (n >= 0) { lshift = n; rshift = ctx->prec-n; } else { lshift = ctx->prec+n; rshift = -n; } if (a->digits > ctx->prec) { if (!mpd_qcopy(&tmp, a, status)) { mpd_seterror(result, MPD_Malloc_error, status); goto finish; } _mpd_cap(&tmp, ctx); a = &tmp; } if (!mpd_qshiftl(&big, a, lshift, status)) { mpd_seterror(result, MPD_Malloc_error, status); goto finish; } _mpd_cap(&big, ctx); if (mpd_qshiftr(&small, a, rshift, status) == MPD_UINT_MAX) { mpd_seterror(result, MPD_Malloc_error, status); goto finish; } _mpd_qadd(result, &big, &small, ctx, status); finish: mpd_del(&tmp); mpd_del(&big); mpd_del(&small); } /* * b must be an integer with exponent 0 and in the range +-2*(emax + prec). * XXX: In my opinion +-(2*emax + prec) would be more sensible. * The result is a with the value of b added to its exponent. */ void mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_uint_t n, maxjump; #ifndef LEGACY_COMPILER int64_t exp; #else mpd_uint_t x; int x_sign, n_sign; mpd_ssize_t exp; #endif if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } } if (b->exp != 0 || mpd_isinfinite(b)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } n = mpd_qabs_uint(b, &workstatus); /* the spec demands this */ maxjump = 2 * (mpd_uint_t)(ctx->emax + ctx->prec); if (n > maxjump || workstatus&MPD_Invalid_operation) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_isinfinite(a)) { mpd_qcopy(result, a, status); return; } #ifndef LEGACY_COMPILER exp = a->exp + (int64_t)n * mpd_arith_sign(b); exp = (exp > MPD_EXP_INF) ? MPD_EXP_INF : exp; exp = (exp < MPD_EXP_CLAMP) ? MPD_EXP_CLAMP : exp; #else x = (a->exp < 0) ? -a->exp : a->exp; x_sign = (a->exp < 0) ? 1 : 0; n_sign = mpd_isnegative(b) ? 1 : 0; if (x_sign == n_sign) { x = x + n; if (x < n) x = MPD_UINT_MAX; } else { x_sign = (x >= n) ? x_sign : n_sign; x = (x >= n) ? x - n : n - x; } if (!x_sign && x > MPD_EXP_INF) x = MPD_EXP_INF; if (x_sign && x > -MPD_EXP_CLAMP) x = -MPD_EXP_CLAMP; exp = x_sign ? -((mpd_ssize_t)x) : (mpd_ssize_t)x; #endif mpd_qcopy(result, a, status); result->exp = (mpd_ssize_t)exp; mpd_qfinalize(result, ctx, status); } /* * Shift the coefficient by n digits, positive n is a left shift. In the case * of a left shift, the result is decapitated to fit the context precision. If * you don't want that, use mpd_shiftl(). */ void mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } mpd_qcopy(result, a, status); return; } if (n >= 0 && n <= ctx->prec) { mpd_qshiftl(result, a, n, status); _mpd_cap(result, ctx); } else if (n < 0 && n >= -ctx->prec) { if (!mpd_qcopy(result, a, status)) { return; } _mpd_cap(result, ctx); mpd_qshiftr_inplace(result, -n); } else { mpd_seterror(result, MPD_Invalid_operation, status); } } /* * Same as mpd_shiftn(), but the shift is specified by the decimal b, which * must be an integer with a zero exponent. Infinities remain infinities. */ void mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_ssize_t n; if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } } if (b->exp != 0 || mpd_isinfinite(b)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } n = mpd_qget_ssize(b, &workstatus); if (workstatus&MPD_Invalid_operation) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (n > ctx->prec || n < -ctx->prec) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_isinfinite(a)) { mpd_qcopy(result, a, status); return; } if (n >= 0) { mpd_qshiftl(result, a, n, status); _mpd_cap(result, ctx); } else { if (!mpd_qcopy(result, a, status)) { return; } _mpd_cap(result, ctx); mpd_qshiftr_inplace(result, -n); } } /* Logical Xor */ void mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { const mpd_t *big = a, *small = b; mpd_uint_t x, y, z, xbit, ybit; int k, mswdigits; mpd_ssize_t i; if (mpd_isspecial(a) || mpd_isspecial(b) || mpd_isnegative(a) || mpd_isnegative(b) || a->exp != 0 || b->exp != 0) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (b->digits > a->digits) { big = b; small = a; } if (!mpd_qresize(result, big->len, status)) { return; } /* full words */ for (i = 0; i < small->len-1; i++) { x = small->data[i]; y = big->data[i]; z = 0; for (k = 0; k < MPD_RDIGITS; k++) { xbit = x % 10; x /= 10; ybit = y % 10; y /= 10; if (xbit > 1 || ybit > 1) { goto invalid_operation; } z += (xbit^ybit) ? mpd_pow10[k] : 0; } result->data[i] = z; } /* most significant word of small */ x = small->data[i]; y = big->data[i]; z = 0; mswdigits = mpd_word_digits(x); for (k = 0; k < mswdigits; k++) { xbit = x % 10; x /= 10; ybit = y % 10; y /= 10; if (xbit > 1 || ybit > 1) { goto invalid_operation; } z += (xbit^ybit) ? mpd_pow10[k] : 0; } /* scan for digits > 1 and copy the rest of y */ for (; k < MPD_RDIGITS; k++) { ybit = y % 10; y /= 10; if (ybit > 1) { goto invalid_operation; } z += ybit*mpd_pow10[k]; } result->data[i++] = z; /* scan for digits > 1 and copy the rest of big */ for (; i < big->len; i++) { y = big->data[i]; for (k = 0; k < MPD_RDIGITS; k++) { ybit = y % 10; y /= 10; if (ybit > 1) { goto invalid_operation; } } result->data[i] = big->data[i]; } mpd_clear_flags(result); result->exp = 0; result->len = _mpd_real_size(result->data, big->len); mpd_qresize(result, result->len, status); mpd_setdigits(result); _mpd_cap(result, ctx); return; invalid_operation: mpd_seterror(result, MPD_Invalid_operation, status); } /******************************************************************************/ /* Arithmetic operations */ /******************************************************************************/ /* * The absolute value of a. If a is negative, the result is the same * as the result of the minus operation. Otherwise, the result is the * result of the plus operation. */ void mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } } if (mpd_isnegative(a)) { mpd_qminus(result, a, ctx, status); } else { mpd_qplus(result, a, ctx, status); } } static inline void _mpd_ptrswap(const mpd_t **a, const mpd_t **b) { const mpd_t *t = *a; *a = *b; *b = t; } /* Add or subtract infinities. */ static void _mpd_qaddsub_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, uint8_t sign_b, uint32_t *status) { if (mpd_isinfinite(a)) { if (mpd_sign(a) != sign_b && mpd_isinfinite(b)) { mpd_seterror(result, MPD_Invalid_operation, status); } else { mpd_setspecial(result, mpd_sign(a), MPD_INF); } return; } assert(mpd_isinfinite(b)); mpd_setspecial(result, sign_b, MPD_INF); } /* Add or subtract non-special numbers. */ static void _mpd_qaddsub(mpd_t *result, const mpd_t *a, const mpd_t *b, uint8_t sign_b, const mpd_context_t *ctx, uint32_t *status) { const mpd_t *big, *small; MPD_NEW_STATIC(big_aligned,0,0,0,0); MPD_NEW_CONST(tiny,0,0,1,1,1,1); mpd_uint_t carry; mpd_ssize_t newsize, shift; mpd_ssize_t exp, i; int swap = 0; /* compare exponents */ big = a; small = b; if (big->exp != small->exp) { if (small->exp > big->exp) { _mpd_ptrswap(&big, &small); swap++; } /* align the coefficients */ if (!mpd_iszerocoeff(big)) { exp = big->exp - 1; exp += (big->digits > ctx->prec) ? 0 : big->digits-ctx->prec-1; if (mpd_adjexp(small) < exp) { /* * Avoid huge shifts by substituting a value for small that is * guaranteed to produce the same results. * * adjexp(small) < exp if and only if: * * bdigits <= prec AND * bdigits+shift >= prec+2+sdigits AND * exp = bexp+bdigits-prec-2 * * 1234567000000000 -> bdigits + shift * ----------XX1234 -> sdigits * ----------X1 -> tiny-digits * |- prec -| * * OR * * bdigits > prec AND * shift > sdigits AND * exp = bexp-1 * * 1234567892100000 -> bdigits + shift * ----------XX1234 -> sdigits * ----------X1 -> tiny-digits * |- prec -| * * If tiny is zero, adding or subtracting is a no-op. * Otherwise, adding tiny generates a non-zero digit either * below the rounding digit or the least significant digit * of big. When subtracting, tiny is in the same position as * the carry that would be generated by subtracting sdigits. */ mpd_copy_flags(&tiny, small); tiny.exp = exp; tiny.digits = 1; tiny.len = 1; tiny.data[0] = mpd_iszerocoeff(small) ? 0 : 1; small = &tiny; } /* This cannot wrap: the difference is positive and <= maxprec */ shift = big->exp - small->exp; if (!mpd_qshiftl(&big_aligned, big, shift, status)) { mpd_seterror(result, MPD_Malloc_error, status); goto finish; } big = &big_aligned; } } result->exp = small->exp; /* compare length of coefficients */ if (big->len < small->len) { _mpd_ptrswap(&big, &small); swap++; } newsize = big->len; if (!mpd_qresize(result, newsize, status)) { goto finish; } if (mpd_sign(a) == sign_b) { carry = _mpd_baseadd(result->data, big->data, small->data, big->len, small->len); if (carry) { newsize = big->len + 1; if (!mpd_qresize(result, newsize, status)) { goto finish; } result->data[newsize-1] = carry; } result->len = newsize; mpd_set_flags(result, sign_b); } else { if (big->len == small->len) { for (i=big->len-1; i >= 0; --i) { if (big->data[i] != small->data[i]) { if (big->data[i] < small->data[i]) { _mpd_ptrswap(&big, &small); swap++; } break; } } } _mpd_basesub(result->data, big->data, small->data, big->len, small->len); newsize = _mpd_real_size(result->data, big->len); /* resize to smaller cannot fail */ (void)mpd_qresize(result, newsize, status); result->len = newsize; sign_b = (swap & 1) ? sign_b : mpd_sign(a); mpd_set_flags(result, sign_b); if (mpd_iszerocoeff(result)) { mpd_set_positive(result); if (ctx->round == MPD_ROUND_FLOOR) { mpd_set_negative(result); } } } mpd_setdigits(result); finish: mpd_del(&big_aligned); } /* Add a and b. No specials, no finalizing. */ static void _mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { _mpd_qaddsub(result, a, b, mpd_sign(b), ctx, status); } /* Subtract b from a. No specials, no finalizing. */ static void _mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { _mpd_qaddsub(result, a, b, !mpd_sign(b), ctx, status); } /* Add a and b. */ void mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } _mpd_qaddsub_inf(result, a, b, mpd_sign(b), status); return; } _mpd_qaddsub(result, a, b, mpd_sign(b), ctx, status); mpd_qfinalize(result, ctx, status); } /* Add a and b. Set NaN/Invalid_operation if the result is inexact. */ static void _mpd_qadd_exact(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_qadd(result, a, b, ctx, &workstatus); *status |= workstatus; if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) { mpd_seterror(result, MPD_Invalid_operation, status); } } /* Subtract b from a. */ void mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } _mpd_qaddsub_inf(result, a, b, !mpd_sign(b), status); return; } _mpd_qaddsub(result, a, b, !mpd_sign(b), ctx, status); mpd_qfinalize(result, ctx, status); } /* Subtract b from a. Set NaN/Invalid_operation if the result is inexact. */ static void _mpd_qsub_exact(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_qsub(result, a, b, ctx, &workstatus); *status |= workstatus; if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) { mpd_seterror(result, MPD_Invalid_operation, status); } } /* Add decimal and mpd_ssize_t. */ void mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_ssize(&bb, b, &maxcontext, status); mpd_qadd(result, a, &bb, ctx, status); mpd_del(&bb); } /* Add decimal and mpd_uint_t. */ void mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_uint(&bb, b, &maxcontext, status); mpd_qadd(result, a, &bb, ctx, status); mpd_del(&bb); } /* Subtract mpd_ssize_t from decimal. */ void mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_ssize(&bb, b, &maxcontext, status); mpd_qsub(result, a, &bb, ctx, status); mpd_del(&bb); } /* Subtract mpd_uint_t from decimal. */ void mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_uint(&bb, b, &maxcontext, status); mpd_qsub(result, a, &bb, ctx, status); mpd_del(&bb); } /* Add decimal and int32_t. */ void mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qadd_ssize(result, a, b, ctx, status); } /* Add decimal and uint32_t. */ void mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qadd_uint(result, a, b, ctx, status); } #ifdef CONFIG_64 /* Add decimal and int64_t. */ void mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qadd_ssize(result, a, b, ctx, status); } /* Add decimal and uint64_t. */ void mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qadd_uint(result, a, b, ctx, status); } #elif !defined(LEGACY_COMPILER) /* Add decimal and int64_t. */ void mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_i64(&bb, b, &maxcontext, status); mpd_qadd(result, a, &bb, ctx, status); mpd_del(&bb); } /* Add decimal and uint64_t. */ void mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_u64(&bb, b, &maxcontext, status); mpd_qadd(result, a, &bb, ctx, status); mpd_del(&bb); } #endif /* Subtract int32_t from decimal. */ void mpd_qsub_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qsub_ssize(result, a, b, ctx, status); } /* Subtract uint32_t from decimal. */ void mpd_qsub_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qsub_uint(result, a, b, ctx, status); } #ifdef CONFIG_64 /* Subtract int64_t from decimal. */ void mpd_qsub_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qsub_ssize(result, a, b, ctx, status); } /* Subtract uint64_t from decimal. */ void mpd_qsub_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qsub_uint(result, a, b, ctx, status); } #elif !defined(LEGACY_COMPILER) /* Subtract int64_t from decimal. */ void mpd_qsub_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_i64(&bb, b, &maxcontext, status); mpd_qsub(result, a, &bb, ctx, status); mpd_del(&bb); } /* Subtract uint64_t from decimal. */ void mpd_qsub_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_u64(&bb, b, &maxcontext, status); mpd_qsub(result, a, &bb, ctx, status); mpd_del(&bb); } #endif /* Divide infinities. */ static void _mpd_qdiv_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isinfinite(a)) { if (mpd_isinfinite(b)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF); return; } assert(mpd_isinfinite(b)); _settriple(result, mpd_sign(a)^mpd_sign(b), 0, mpd_etiny(ctx)); *status |= MPD_Clamped; } enum {NO_IDEAL_EXP, SET_IDEAL_EXP}; /* Divide a by b. */ static void _mpd_qdiv(int action, mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_STATIC(aligned,0,0,0,0); mpd_uint_t ld; mpd_ssize_t shift, exp, tz; mpd_ssize_t newsize; mpd_ssize_t ideal_exp; mpd_uint_t rem; uint8_t sign_a = mpd_sign(a); uint8_t sign_b = mpd_sign(b); if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(q, a, b, ctx, status)) { return; } _mpd_qdiv_inf(q, a, b, ctx, status); return; } if (mpd_iszerocoeff(b)) { if (mpd_iszerocoeff(a)) { mpd_seterror(q, MPD_Division_undefined, status); } else { mpd_setspecial(q, sign_a^sign_b, MPD_INF); *status |= MPD_Division_by_zero; } return; } if (mpd_iszerocoeff(a)) { exp = a->exp - b->exp; _settriple(q, sign_a^sign_b, 0, exp); mpd_qfinalize(q, ctx, status); return; } shift = (b->digits - a->digits) + ctx->prec + 1; ideal_exp = a->exp - b->exp; exp = ideal_exp - shift; if (shift > 0) { if (!mpd_qshiftl(&aligned, a, shift, status)) { mpd_seterror(q, MPD_Malloc_error, status); goto finish; } a = &aligned; } else if (shift < 0) { shift = -shift; if (!mpd_qshiftl(&aligned, b, shift, status)) { mpd_seterror(q, MPD_Malloc_error, status); goto finish; } b = &aligned; } newsize = a->len - b->len + 1; if ((q != b && q != a) || (q == b && newsize > b->len)) { if (!mpd_qresize(q, newsize, status)) { mpd_seterror(q, MPD_Malloc_error, status); goto finish; } } if (b->len == 1) { rem = _mpd_shortdiv(q->data, a->data, a->len, b->data[0]); } else if (b->len <= MPD_NEWTONDIV_CUTOFF) { int ret = _mpd_basedivmod(q->data, NULL, a->data, b->data, a->len, b->len); if (ret < 0) { mpd_seterror(q, MPD_Malloc_error, status); goto finish; } rem = ret; } else { MPD_NEW_STATIC(r,0,0,0,0); _mpd_base_ndivmod(q, &r, a, b, status); if (mpd_isspecial(q) || mpd_isspecial(&r)) { mpd_setspecial(q, MPD_POS, MPD_NAN); mpd_del(&r); goto finish; } rem = !mpd_iszerocoeff(&r); mpd_del(&r); newsize = q->len; } newsize = _mpd_real_size(q->data, newsize); /* resize to smaller cannot fail */ mpd_qresize(q, newsize, status); mpd_set_flags(q, sign_a^sign_b); q->len = newsize; mpd_setdigits(q); shift = ideal_exp - exp; if (rem) { ld = mpd_lsd(q->data[0]); if (ld == 0 || ld == 5) { q->data[0] += 1; } } else if (action == SET_IDEAL_EXP && shift > 0) { tz = mpd_trail_zeros(q); shift = (tz > shift) ? shift : tz; mpd_qshiftr_inplace(q, shift); exp += shift; } q->exp = exp; finish: mpd_del(&aligned); mpd_qfinalize(q, ctx, status); } /* Divide a by b. */ void mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_STATIC(aa,0,0,0,0); MPD_NEW_STATIC(bb,0,0,0,0); uint32_t xstatus = 0; if (q == a) { if (!mpd_qcopy(&aa, a, status)) { mpd_seterror(q, MPD_Malloc_error, status); goto out; } a = &aa; } if (q == b) { if (!mpd_qcopy(&bb, b, status)) { mpd_seterror(q, MPD_Malloc_error, status); goto out; } b = &bb; } _mpd_qdiv(SET_IDEAL_EXP, q, a, b, ctx, &xstatus); if (xstatus & (MPD_Malloc_error|MPD_Division_impossible)) { /* Inexact quotients (the usual case) fill the entire context precision, * which can lead to the above errors for very high precisions. Retry * the operation with a lower precision in case the result is exact. * * We need an upper bound for the number of digits of a_coeff / b_coeff * when the result is exact. If a_coeff' * 1 / b_coeff' is in lowest * terms, then maxdigits(a_coeff') + maxdigits(1 / b_coeff') is a suitable * bound. * * 1 / b_coeff' is exact iff b_coeff' exclusively has prime factors 2 or 5. * The largest amount of digits is generated if b_coeff' is a power of 2 or * a power of 5 and is less than or equal to log5(b_coeff') <= log2(b_coeff'). * * We arrive at a total upper bound: * * maxdigits(a_coeff') + maxdigits(1 / b_coeff') <= * log10(a_coeff) + log2(b_coeff) = * log10(a_coeff) + log10(b_coeff) / log10(2) <= * a->digits + b->digits * 4; */ mpd_context_t workctx = *ctx; uint32_t ystatus = 0; workctx.prec = a->digits + b->digits * 4; if (workctx.prec >= ctx->prec) { *status |= (xstatus&MPD_Errors); goto out; /* No point in retrying, keep the original error. */ } _mpd_qdiv(SET_IDEAL_EXP, q, a, b, &workctx, &ystatus); if (ystatus != 0) { ystatus = *status | ((ystatus|xstatus)&MPD_Errors); mpd_seterror(q, ystatus, status); } } else { *status |= xstatus; } out: mpd_del(&aa); mpd_del(&bb); } /* Internal function. */ static void _mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_STATIC(aligned,0,0,0,0); mpd_ssize_t qsize, rsize; mpd_ssize_t ideal_exp, expdiff, shift; uint8_t sign_a = mpd_sign(a); uint8_t sign_ab = mpd_sign(a)^mpd_sign(b); ideal_exp = (a->exp > b->exp) ? b->exp : a->exp; if (mpd_iszerocoeff(a)) { if (!mpd_qcopy(r, a, status)) { goto nanresult; /* GCOV_NOT_REACHED */ } r->exp = ideal_exp; _settriple(q, sign_ab, 0, 0); return; } expdiff = mpd_adjexp(a) - mpd_adjexp(b); if (expdiff < 0) { if (a->exp > b->exp) { /* positive and less than b->digits - a->digits */ shift = a->exp - b->exp; if (!mpd_qshiftl(r, a, shift, status)) { goto nanresult; } r->exp = ideal_exp; } else { if (!mpd_qcopy(r, a, status)) { goto nanresult; } } _settriple(q, sign_ab, 0, 0); return; } if (expdiff > ctx->prec) { *status |= MPD_Division_impossible; goto nanresult; } /* * At this point we have: * (1) 0 <= a->exp + a->digits - b->exp - b->digits <= prec * (2) a->exp - b->exp >= b->digits - a->digits * (3) a->exp - b->exp <= prec + b->digits - a->digits */ if (a->exp != b->exp) { shift = a->exp - b->exp; if (shift > 0) { /* by (3), after the shift a->digits <= prec + b->digits */ if (!mpd_qshiftl(&aligned, a, shift, status)) { goto nanresult; } a = &aligned; } else { shift = -shift; /* by (2), after the shift b->digits <= a->digits */ if (!mpd_qshiftl(&aligned, b, shift, status)) { goto nanresult; } b = &aligned; } } qsize = a->len - b->len + 1; if (!(q == a && qsize < a->len) && !(q == b && qsize < b->len)) { if (!mpd_qresize(q, qsize, status)) { goto nanresult; } } rsize = b->len; if (!(r == a && rsize < a->len)) { if (!mpd_qresize(r, rsize, status)) { goto nanresult; } } if (b->len == 1) { assert(b->data[0] != 0); /* annotation for scan-build */ if (a->len == 1) { _mpd_div_word(&q->data[0], &r->data[0], a->data[0], b->data[0]); } else { r->data[0] = _mpd_shortdiv(q->data, a->data, a->len, b->data[0]); } } else if (b->len <= MPD_NEWTONDIV_CUTOFF) { int ret; ret = _mpd_basedivmod(q->data, r->data, a->data, b->data, a->len, b->len); if (ret == -1) { *status |= MPD_Malloc_error; goto nanresult; } } else { _mpd_base_ndivmod(q, r, a, b, status); if (mpd_isspecial(q) || mpd_isspecial(r)) { goto nanresult; } qsize = q->len; rsize = r->len; } qsize = _mpd_real_size(q->data, qsize); /* resize to smaller cannot fail */ mpd_qresize(q, qsize, status); q->len = qsize; mpd_setdigits(q); mpd_set_flags(q, sign_ab); q->exp = 0; if (q->digits > ctx->prec) { *status |= MPD_Division_impossible; goto nanresult; } rsize = _mpd_real_size(r->data, rsize); /* resize to smaller cannot fail */ mpd_qresize(r, rsize, status); r->len = rsize; mpd_setdigits(r); mpd_set_flags(r, sign_a); r->exp = ideal_exp; out: mpd_del(&aligned); return; nanresult: mpd_setspecial(q, MPD_POS, MPD_NAN); mpd_setspecial(r, MPD_POS, MPD_NAN); goto out; } /* Integer division with remainder. */ void mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint8_t sign = mpd_sign(a)^mpd_sign(b); if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(q, a, b, ctx, status)) { mpd_qcopy(r, q, status); return; } if (mpd_isinfinite(a)) { if (mpd_isinfinite(b)) { mpd_setspecial(q, MPD_POS, MPD_NAN); } else { mpd_setspecial(q, sign, MPD_INF); } mpd_setspecial(r, MPD_POS, MPD_NAN); *status |= MPD_Invalid_operation; return; } if (mpd_isinfinite(b)) { if (!mpd_qcopy(r, a, status)) { mpd_seterror(q, MPD_Malloc_error, status); return; } mpd_qfinalize(r, ctx, status); _settriple(q, sign, 0, 0); return; } /* debug */ abort(); /* GCOV_NOT_REACHED */ } if (mpd_iszerocoeff(b)) { if (mpd_iszerocoeff(a)) { mpd_setspecial(q, MPD_POS, MPD_NAN); mpd_setspecial(r, MPD_POS, MPD_NAN); *status |= MPD_Division_undefined; } else { mpd_setspecial(q, sign, MPD_INF); mpd_setspecial(r, MPD_POS, MPD_NAN); *status |= (MPD_Division_by_zero|MPD_Invalid_operation); } return; } _mpd_qdivmod(q, r, a, b, ctx, status); mpd_qfinalize(q, ctx, status); mpd_qfinalize(r, ctx, status); } void mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_STATIC(r,0,0,0,0); uint8_t sign = mpd_sign(a)^mpd_sign(b); if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(q, a, b, ctx, status)) { return; } if (mpd_isinfinite(a) && mpd_isinfinite(b)) { mpd_seterror(q, MPD_Invalid_operation, status); return; } if (mpd_isinfinite(a)) { mpd_setspecial(q, sign, MPD_INF); return; } if (mpd_isinfinite(b)) { _settriple(q, sign, 0, 0); return; } /* debug */ abort(); /* GCOV_NOT_REACHED */ } if (mpd_iszerocoeff(b)) { if (mpd_iszerocoeff(a)) { mpd_seterror(q, MPD_Division_undefined, status); } else { mpd_setspecial(q, sign, MPD_INF); *status |= MPD_Division_by_zero; } return; } _mpd_qdivmod(q, &r, a, b, ctx, status); mpd_del(&r); mpd_qfinalize(q, ctx, status); } /* Divide decimal by mpd_ssize_t. */ void mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_ssize(&bb, b, &maxcontext, status); mpd_qdiv(result, a, &bb, ctx, status); mpd_del(&bb); } /* Divide decimal by mpd_uint_t. */ void mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_uint(&bb, b, &maxcontext, status); mpd_qdiv(result, a, &bb, ctx, status); mpd_del(&bb); } /* Divide decimal by int32_t. */ void mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qdiv_ssize(result, a, b, ctx, status); } /* Divide decimal by uint32_t. */ void mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qdiv_uint(result, a, b, ctx, status); } #ifdef CONFIG_64 /* Divide decimal by int64_t. */ void mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qdiv_ssize(result, a, b, ctx, status); } /* Divide decimal by uint64_t. */ void mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qdiv_uint(result, a, b, ctx, status); } #elif !defined(LEGACY_COMPILER) /* Divide decimal by int64_t. */ void mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_i64(&bb, b, &maxcontext, status); mpd_qdiv(result, a, &bb, ctx, status); mpd_del(&bb); } /* Divide decimal by uint64_t. */ void mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_u64(&bb, b, &maxcontext, status); mpd_qdiv(result, a, &bb, ctx, status); mpd_del(&bb); } #endif /* Pad the result with trailing zeros if it has fewer digits than prec. */ static void _mpd_zeropad(mpd_t *result, const mpd_context_t *ctx, uint32_t *status) { if (!mpd_isspecial(result) && !mpd_iszero(result) && result->digits < ctx->prec) { mpd_ssize_t shift = ctx->prec - result->digits; mpd_qshiftl(result, result, shift, status); result->exp -= shift; } } /* Check if the result is guaranteed to be one. */ static int _mpd_qexp_check_one(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_CONST(lim,0,-(ctx->prec+1),1,1,1,9); MPD_NEW_SHARED(aa, a); mpd_set_positive(&aa); /* abs(a) <= 9 * 10**(-prec-1) */ if (_mpd_cmp(&aa, &lim) <= 0) { _settriple(result, 0, 1, 0); *status |= MPD_Rounded|MPD_Inexact; return 1; } return 0; } /* * Get the number of iterations for the Horner scheme in _mpd_qexp(). */ static inline mpd_ssize_t _mpd_get_exp_iterations(const mpd_t *r, mpd_ssize_t p) { mpd_ssize_t log10pbyr; /* lower bound for log10(p / abs(r)) */ mpd_ssize_t n; assert(p >= 10); assert(!mpd_iszero(r)); assert(-p < mpd_adjexp(r) && mpd_adjexp(r) <= -1); #ifdef CONFIG_64 if (p > (mpd_ssize_t)(1ULL<<52)) { return MPD_SSIZE_MAX; } #endif /* * Lower bound for log10(p / abs(r)): adjexp(p) - (adjexp(r) + 1) * At this point (for CONFIG_64, CONFIG_32 is not problematic): * 1) 10 <= p <= 2**52 * 2) -p < adjexp(r) <= -1 * 3) 1 <= log10pbyr <= 2**52 + 14 */ log10pbyr = (mpd_word_digits(p)-1) - (mpd_adjexp(r)+1); /* * The numerator in the paper is 1.435 * p - 1.182, calculated * exactly. We compensate for rounding errors by using 1.43503. * ACL2 proofs: * 1) exp-iter-approx-lower-bound: The term below evaluated * in 53-bit floating point arithmetic is greater than or * equal to the exact term used in the paper. * 2) exp-iter-approx-upper-bound: The term below is less than * or equal to 3/2 * p <= 3/2 * 2**52. */ n = (mpd_ssize_t)ceil((1.43503*(double)p - 1.182) / (double)log10pbyr); return n >= 3 ? n : 3; } /* * Internal function, specials have been dealt with. Apart from Overflow * and Underflow, two cases must be considered for the error of the result: * * 1) abs(a) <= 9 * 10**(-prec-1) ==> result == 1 * * Absolute error: abs(1 - e**x) < 10**(-prec) * ------------------------------------------- * * 2) abs(a) > 9 * 10**(-prec-1) * * Relative error: abs(result - e**x) < 0.5 * 10**(-prec) * e**x * ------------------------------------------------------------- * * The algorithm is from Hull&Abrham, Variable Precision Exponential Function, * ACM Transactions on Mathematical Software, Vol. 12, No. 2, June 1986. * * Main differences: * * - The number of iterations for the Horner scheme is calculated using * 53-bit floating point arithmetic. * * - In the error analysis for ER (relative error accumulated in the * evaluation of the truncated series) the reduced operand r may * have any number of digits. * ACL2 proof: exponent-relative-error * * - The analysis for early abortion has been adapted for the mpd_t * ranges. */ static void _mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_STATIC(tmp,0,0,0,0); MPD_NEW_STATIC(sum,0,0,0,0); MPD_NEW_CONST(word,0,0,1,1,1,1); mpd_ssize_t j, n, t; assert(!mpd_isspecial(a)); if (mpd_iszerocoeff(a)) { _settriple(result, MPD_POS, 1, 0); return; } /* * We are calculating e^x = e^(r*10^t) = (e^r)^(10^t), where abs(r) < 1 and t >= 0. * * If t > 0, we have: * * (1) 0.1 <= r < 1, so e^0.1 <= e^r. If t > MAX_T, overflow occurs: * * MAX-EMAX+1 < log10(e^(0.1*10*t)) <= log10(e^(r*10^t)) < adjexp(e^(r*10^t))+1 * * (2) -1 < r <= -0.1, so e^r <= e^-0.1. If t > MAX_T, underflow occurs: * * adjexp(e^(r*10^t)) <= log10(e^(r*10^t)) <= log10(e^(-0.1*10^t)) < MIN-ETINY */ #if defined(CONFIG_64) #define MPD_EXP_MAX_T 19 #elif defined(CONFIG_32) #define MPD_EXP_MAX_T 10 #endif t = a->digits + a->exp; t = (t > 0) ? t : 0; if (t > MPD_EXP_MAX_T) { if (mpd_ispositive(a)) { mpd_setspecial(result, MPD_POS, MPD_INF); *status |= MPD_Overflow|MPD_Inexact|MPD_Rounded; } else { _settriple(result, MPD_POS, 0, mpd_etiny(ctx)); *status |= (MPD_Inexact|MPD_Rounded|MPD_Subnormal| MPD_Underflow|MPD_Clamped); } return; } /* abs(a) <= 9 * 10**(-prec-1) */ if (_mpd_qexp_check_one(result, a, ctx, status)) { return; } mpd_maxcontext(&workctx); workctx.prec = ctx->prec + t + 2; workctx.prec = (workctx.prec < 10) ? 10 : workctx.prec; workctx.round = MPD_ROUND_HALF_EVEN; if (!mpd_qcopy(result, a, status)) { return; } result->exp -= t; /* * At this point: * 1) 9 * 10**(-prec-1) < abs(a) * 2) 9 * 10**(-prec-t-1) < abs(r) * 3) log10(9) - prec - t - 1 < log10(abs(r)) < adjexp(abs(r)) + 1 * 4) - prec - t - 2 < adjexp(abs(r)) <= -1 */ n = _mpd_get_exp_iterations(result, workctx.prec); if (n == MPD_SSIZE_MAX) { mpd_seterror(result, MPD_Invalid_operation, status); /* GCOV_UNLIKELY */ return; /* GCOV_UNLIKELY */ } _settriple(&sum, MPD_POS, 1, 0); for (j = n-1; j >= 1; j--) { word.data[0] = j; mpd_setdigits(&word); mpd_qdiv(&tmp, result, &word, &workctx, &workctx.status); mpd_qfma(&sum, &sum, &tmp, &one, &workctx, &workctx.status); } #ifdef CONFIG_64 _mpd_qpow_uint(result, &sum, mpd_pow10[t], MPD_POS, &workctx, status); #else if (t <= MPD_MAX_POW10) { _mpd_qpow_uint(result, &sum, mpd_pow10[t], MPD_POS, &workctx, status); } else { t -= MPD_MAX_POW10; _mpd_qpow_uint(&tmp, &sum, mpd_pow10[MPD_MAX_POW10], MPD_POS, &workctx, status); _mpd_qpow_uint(result, &tmp, mpd_pow10[t], MPD_POS, &workctx, status); } #endif mpd_del(&tmp); mpd_del(&sum); *status |= (workctx.status&MPD_Errors); *status |= (MPD_Inexact|MPD_Rounded); } /* exp(a) */ void mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } if (mpd_isnegative(a)) { _settriple(result, MPD_POS, 0, 0); } else { mpd_setspecial(result, MPD_POS, MPD_INF); } return; } if (mpd_iszerocoeff(a)) { _settriple(result, MPD_POS, 1, 0); return; } workctx = *ctx; workctx.round = MPD_ROUND_HALF_EVEN; if (ctx->allcr) { MPD_NEW_STATIC(t1, 0,0,0,0); MPD_NEW_STATIC(t2, 0,0,0,0); MPD_NEW_STATIC(ulp, 0,0,0,0); MPD_NEW_STATIC(aa, 0,0,0,0); mpd_ssize_t prec; mpd_ssize_t ulpexp; uint32_t workstatus; if (result == a) { if (!mpd_qcopy(&aa, a, status)) { mpd_seterror(result, MPD_Malloc_error, status); return; } a = &aa; } workctx.clamp = 0; prec = ctx->prec + 3; while (1) { workctx.prec = prec; workstatus = 0; _mpd_qexp(result, a, &workctx, &workstatus); *status |= workstatus; ulpexp = result->exp + result->digits - workctx.prec; if (workstatus & MPD_Underflow) { /* The effective work precision is result->digits. */ ulpexp = result->exp; } _ssettriple(&ulp, MPD_POS, 1, ulpexp); /* * At this point [1]: * 1) abs(result - e**x) < 0.5 * 10**(-prec) * e**x * 2) result - ulp < e**x < result + ulp * 3) result - ulp < result < result + ulp * * If round(result-ulp)==round(result+ulp), then * round(result)==round(e**x). Therefore the result * is correctly rounded. * * [1] If abs(a) <= 9 * 10**(-prec-1), use the absolute * error for a similar argument. */ workctx.prec = ctx->prec; mpd_qadd(&t1, result, &ulp, &workctx, &workctx.status); mpd_qsub(&t2, result, &ulp, &workctx, &workctx.status); if (mpd_isspecial(result) || mpd_iszerocoeff(result) || mpd_qcmp(&t1, &t2, status) == 0) { workctx.clamp = ctx->clamp; _mpd_zeropad(result, &workctx, status); mpd_check_underflow(result, &workctx, status); mpd_qfinalize(result, &workctx, status); break; } prec += MPD_RDIGITS; } mpd_del(&t1); mpd_del(&t2); mpd_del(&ulp); mpd_del(&aa); } else { _mpd_qexp(result, a, &workctx, status); _mpd_zeropad(result, &workctx, status); mpd_check_underflow(result, &workctx, status); mpd_qfinalize(result, &workctx, status); } } /* Fused multiply-add: (a * b) + c, with a single final rounding. */ void mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_t *cc = NULL; if (result == c) { if ((cc = mpd_qncopy(c)) == NULL) { mpd_seterror(result, MPD_Malloc_error, status); return; } c = cc; } _mpd_qmul(result, a, b, ctx, &workstatus); if (!(workstatus&MPD_Invalid_operation)) { mpd_qadd(result, result, c, ctx, &workstatus); } if (cc) mpd_del(cc); *status |= workstatus; } /* * Schedule the optimal precision increase for the Newton iteration. * v := input operand * z_0 := initial approximation * initprec := natural number such that abs(log(v) - z_0) < 10**-initprec * maxprec := target precision * * For convenience the output klist contains the elements in reverse order: * klist := [k_n-1, ..., k_0], where * 1) k_0 <= initprec and * 2) abs(log(v) - result) < 10**(-2*k_n-1 + 1) <= 10**-maxprec. */ static inline int ln_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec, mpd_ssize_t initprec) { mpd_ssize_t k; int i; assert(maxprec >= 2 && initprec >= 2); if (maxprec <= initprec) return -1; i = 0; k = maxprec; do { k = (k+2) / 2; klist[i++] = k; } while (k > initprec); return i-1; } /* The constants have been verified with both decimal.py and mpfr. */ #ifdef CONFIG_64 #if MPD_RDIGITS != 19 #error "mpdecimal.c: MPD_RDIGITS must be 19." #endif static const mpd_uint_t mpd_ln10_data[MPD_MINALLOC_MAX] = { 6983716328982174407ULL, 9089704281976336583ULL, 1515961135648465461ULL, 4416816335727555703ULL, 2900988039194170265ULL, 2307925037472986509ULL, 107598438319191292ULL, 3466624107184669231ULL, 4450099781311469159ULL, 9807828059751193854ULL, 7713456862091670584ULL, 1492198849978748873ULL, 6528728696511086257ULL, 2385392051446341972ULL, 8692180205189339507ULL, 6518769751037497088ULL, 2375253577097505395ULL, 9095610299291824318ULL, 982748238504564801ULL, 5438635917781170543ULL, 7547331541421808427ULL, 752371033310119785ULL, 3171643095059950878ULL, 9785265383207606726ULL, 2932258279850258550ULL, 5497347726624257094ULL, 2976979522110718264ULL, 9221477656763693866ULL, 1979650047149510504ULL, 6674183485704422507ULL, 9702766860595249671ULL, 9278096762712757753ULL, 9314848524948644871ULL, 6826928280848118428ULL, 754403708474699401ULL, 230105703089634572ULL, 1929203337658714166ULL, 7589402567763113569ULL, 4208241314695689016ULL, 2922455440575892572ULL, 9356734206705811364ULL, 2684916746550586856ULL, 644507064800027750ULL, 9476834636167921018ULL, 5659121373450747856ULL, 2835522011480466371ULL, 6470806855677432162ULL, 7141748003688084012ULL, 9619404400222105101ULL, 5504893431493939147ULL, 6674744042432743651ULL, 2287698219886746543ULL, 7773262884616336622ULL, 1985283935053089653ULL, 4680843799894826233ULL, 8168948290720832555ULL, 8067566662873690987ULL, 6248633409525465082ULL, 9829834196778404228ULL, 3524802359972050895ULL, 3327900967572609677ULL, 110148862877297603ULL, 179914546843642076ULL, 2302585092994045684ULL }; #else #if MPD_RDIGITS != 9 #error "mpdecimal.c: MPD_RDIGITS must be 9." #endif static const mpd_uint_t mpd_ln10_data[MPD_MINALLOC_MAX] = { 401682692UL, 708474699UL, 720754403UL, 30896345UL, 602301057UL, 765871416UL, 192920333UL, 763113569UL, 589402567UL, 956890167UL, 82413146UL, 589257242UL, 245544057UL, 811364292UL, 734206705UL, 868569356UL, 167465505UL, 775026849UL, 706480002UL, 18064450UL, 636167921UL, 569476834UL, 734507478UL, 156591213UL, 148046637UL, 283552201UL, 677432162UL, 470806855UL, 880840126UL, 417480036UL, 210510171UL, 940440022UL, 939147961UL, 893431493UL, 436515504UL, 440424327UL, 654366747UL, 821988674UL, 622228769UL, 884616336UL, 537773262UL, 350530896UL, 319852839UL, 989482623UL, 468084379UL, 720832555UL, 168948290UL, 736909878UL, 675666628UL, 546508280UL, 863340952UL, 404228624UL, 834196778UL, 508959829UL, 23599720UL, 967735248UL, 96757260UL, 603332790UL, 862877297UL, 760110148UL, 468436420UL, 401799145UL, 299404568UL, 230258509UL }; #endif /* _mpd_ln10 is used directly for precisions smaller than MINALLOC_MAX*RDIGITS. Otherwise, it serves as the initial approximation for calculating ln(10). */ static const mpd_t _mpd_ln10 = { MPD_STATIC|MPD_CONST_DATA, -(MPD_MINALLOC_MAX*MPD_RDIGITS-1), MPD_MINALLOC_MAX*MPD_RDIGITS, MPD_MINALLOC_MAX, MPD_MINALLOC_MAX, (mpd_uint_t *)mpd_ln10_data }; /* * Set 'result' to log(10). * Ulp error: abs(result - log(10)) < ulp(log(10)) * Relative error: abs(result - log(10)) < 5 * 10**-prec * log(10) * * NOTE: The relative error is not derived from the ulp error, but * calculated separately using the fact that 23/10 < log(10) < 24/10. */ void mpd_qln10(mpd_t *result, mpd_ssize_t prec, uint32_t *status) { mpd_context_t varcontext, maxcontext; MPD_NEW_STATIC(tmp, 0,0,0,0); MPD_NEW_CONST(static10, 0,0,2,1,1,10); mpd_ssize_t klist[MPD_MAX_PREC_LOG2]; mpd_uint_t rnd; mpd_ssize_t shift; int i; assert(prec >= 1); shift = MPD_MINALLOC_MAX*MPD_RDIGITS-prec; shift = shift < 0 ? 0 : shift; rnd = mpd_qshiftr(result, &_mpd_ln10, shift, status); if (rnd == MPD_UINT_MAX) { mpd_seterror(result, MPD_Malloc_error, status); return; } result->exp = -(result->digits-1); mpd_maxcontext(&maxcontext); if (prec < MPD_MINALLOC_MAX*MPD_RDIGITS) { maxcontext.prec = prec; _mpd_apply_round_excess(result, rnd, &maxcontext, status); *status |= (MPD_Inexact|MPD_Rounded); return; } mpd_maxcontext(&varcontext); varcontext.round = MPD_ROUND_TRUNC; i = ln_schedule_prec(klist, prec+2, -result->exp); for (; i >= 0; i--) { varcontext.prec = 2*klist[i]+3; result->flags ^= MPD_NEG; _mpd_qexp(&tmp, result, &varcontext, status); result->flags ^= MPD_NEG; mpd_qmul(&tmp, &static10, &tmp, &varcontext, status); mpd_qsub(&tmp, &tmp, &one, &maxcontext, status); mpd_qadd(result, result, &tmp, &maxcontext, status); if (mpd_isspecial(result)) { break; } } mpd_del(&tmp); maxcontext.prec = prec; mpd_qfinalize(result, &maxcontext, status); } /* * Initial approximations for the ln() iteration. The values have the * following properties (established with both decimal.py and mpfr): * * Index 0 - 400, logarithms of x in [1.00, 5.00]: * abs(lnapprox[i] * 10**-3 - log((i+100)/100)) < 10**-2 * abs(lnapprox[i] * 10**-3 - log((i+1+100)/100)) < 10**-2 * * Index 401 - 899, logarithms of x in (0.500, 0.999]: * abs(-lnapprox[i] * 10**-3 - log((i+100)/1000)) < 10**-2 * abs(-lnapprox[i] * 10**-3 - log((i+1+100)/1000)) < 10**-2 */ static const uint16_t lnapprox[900] = { /* index 0 - 400: log((i+100)/100) * 1000 */ 0, 10, 20, 30, 39, 49, 58, 68, 77, 86, 95, 104, 113, 122, 131, 140, 148, 157, 166, 174, 182, 191, 199, 207, 215, 223, 231, 239, 247, 255, 262, 270, 278, 285, 293, 300, 308, 315, 322, 329, 336, 344, 351, 358, 365, 372, 378, 385, 392, 399, 406, 412, 419, 425, 432, 438, 445, 451, 457, 464, 470, 476, 482, 489, 495, 501, 507, 513, 519, 525, 531, 536, 542, 548, 554, 560, 565, 571, 577, 582, 588, 593, 599, 604, 610, 615, 621, 626, 631, 637, 642, 647, 652, 658, 663, 668, 673, 678, 683, 688, 693, 698, 703, 708, 713, 718, 723, 728, 732, 737, 742, 747, 751, 756, 761, 766, 770, 775, 779, 784, 788, 793, 798, 802, 806, 811, 815, 820, 824, 829, 833, 837, 842, 846, 850, 854, 859, 863, 867, 871, 876, 880, 884, 888, 892, 896, 900, 904, 908, 912, 916, 920, 924, 928, 932, 936, 940, 944, 948, 952, 956, 959, 963, 967, 971, 975, 978, 982, 986, 990, 993, 997, 1001, 1004, 1008, 1012, 1015, 1019, 1022, 1026, 1030, 1033, 1037, 1040, 1044, 1047, 1051, 1054, 1058, 1061, 1065, 1068, 1072, 1075, 1078, 1082, 1085, 1089, 1092, 1095, 1099, 1102, 1105, 1109, 1112, 1115, 1118, 1122, 1125, 1128, 1131, 1135, 1138, 1141, 1144, 1147, 1151, 1154, 1157, 1160, 1163, 1166, 1169, 1172, 1176, 1179, 1182, 1185, 1188, 1191, 1194, 1197, 1200, 1203, 1206, 1209, 1212, 1215, 1218, 1221, 1224, 1227, 1230, 1233, 1235, 1238, 1241, 1244, 1247, 1250, 1253, 1256, 1258, 1261, 1264, 1267, 1270, 1273, 1275, 1278, 1281, 1284, 1286, 1289, 1292, 1295, 1297, 1300, 1303, 1306, 1308, 1311, 1314, 1316, 1319, 1322, 1324, 1327, 1330, 1332, 1335, 1338, 1340, 1343, 1345, 1348, 1351, 1353, 1356, 1358, 1361, 1364, 1366, 1369, 1371, 1374, 1376, 1379, 1381, 1384, 1386, 1389, 1391, 1394, 1396, 1399, 1401, 1404, 1406, 1409, 1411, 1413, 1416, 1418, 1421, 1423, 1426, 1428, 1430, 1433, 1435, 1437, 1440, 1442, 1445, 1447, 1449, 1452, 1454, 1456, 1459, 1461, 1463, 1466, 1468, 1470, 1472, 1475, 1477, 1479, 1482, 1484, 1486, 1488, 1491, 1493, 1495, 1497, 1500, 1502, 1504, 1506, 1509, 1511, 1513, 1515, 1517, 1520, 1522, 1524, 1526, 1528, 1530, 1533, 1535, 1537, 1539, 1541, 1543, 1545, 1548, 1550, 1552, 1554, 1556, 1558, 1560, 1562, 1564, 1567, 1569, 1571, 1573, 1575, 1577, 1579, 1581, 1583, 1585, 1587, 1589, 1591, 1593, 1595, 1597, 1599, 1601, 1603, 1605, 1607, 1609, /* index 401 - 899: -log((i+100)/1000) * 1000 */ 691, 689, 687, 685, 683, 681, 679, 677, 675, 673, 671, 669, 668, 666, 664, 662, 660, 658, 656, 654, 652, 650, 648, 646, 644, 642, 641, 639, 637, 635, 633, 631, 629, 627, 626, 624, 622, 620, 618, 616, 614, 612, 611, 609, 607, 605, 603, 602, 600, 598, 596, 594, 592, 591, 589, 587, 585, 583, 582, 580, 578, 576, 574, 573, 571, 569, 567, 566, 564, 562, 560, 559, 557, 555, 553, 552, 550, 548, 546, 545, 543, 541, 540, 538, 536, 534, 533, 531, 529, 528, 526, 524, 523, 521, 519, 518, 516, 514, 512, 511, 509, 508, 506, 504, 502, 501, 499, 498, 496, 494, 493, 491, 489, 488, 486, 484, 483, 481, 480, 478, 476, 475, 473, 472, 470, 468, 467, 465, 464, 462, 460, 459, 457, 456, 454, 453, 451, 449, 448, 446, 445, 443, 442, 440, 438, 437, 435, 434, 432, 431, 429, 428, 426, 425, 423, 422, 420, 419, 417, 416, 414, 412, 411, 410, 408, 406, 405, 404, 402, 400, 399, 398, 396, 394, 393, 392, 390, 389, 387, 386, 384, 383, 381, 380, 378, 377, 375, 374, 372, 371, 370, 368, 367, 365, 364, 362, 361, 360, 358, 357, 355, 354, 352, 351, 350, 348, 347, 345, 344, 342, 341, 340, 338, 337, 336, 334, 333, 331, 330, 328, 327, 326, 324, 323, 322, 320, 319, 318, 316, 315, 313, 312, 311, 309, 308, 306, 305, 304, 302, 301, 300, 298, 297, 296, 294, 293, 292, 290, 289, 288, 286, 285, 284, 282, 281, 280, 278, 277, 276, 274, 273, 272, 270, 269, 268, 267, 265, 264, 263, 261, 260, 259, 258, 256, 255, 254, 252, 251, 250, 248, 247, 246, 245, 243, 242, 241, 240, 238, 237, 236, 234, 233, 232, 231, 229, 228, 227, 226, 224, 223, 222, 221, 219, 218, 217, 216, 214, 213, 212, 211, 210, 208, 207, 206, 205, 203, 202, 201, 200, 198, 197, 196, 195, 194, 192, 191, 190, 189, 188, 186, 185, 184, 183, 182, 180, 179, 178, 177, 176, 174, 173, 172, 171, 170, 168, 167, 166, 165, 164, 162, 161, 160, 159, 158, 157, 156, 154, 153, 152, 151, 150, 148, 147, 146, 145, 144, 143, 142, 140, 139, 138, 137, 136, 135, 134, 132, 131, 130, 129, 128, 127, 126, 124, 123, 122, 121, 120, 119, 118, 116, 115, 114, 113, 112, 111, 110, 109, 108, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; /* * Internal ln() function that does not check for specials, zero or one. * Relative error: abs(result - log(a)) < 0.1 * 10**-prec * abs(log(a)) */ static void _mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t varcontext, maxcontext; mpd_t *z = result; MPD_NEW_STATIC(v,0,0,0,0); MPD_NEW_STATIC(vtmp,0,0,0,0); MPD_NEW_STATIC(tmp,0,0,0,0); mpd_ssize_t klist[MPD_MAX_PREC_LOG2]; mpd_ssize_t maxprec, shift, t; mpd_ssize_t a_digits, a_exp; mpd_uint_t dummy, x; int i; assert(!mpd_isspecial(a) && !mpd_iszerocoeff(a)); /* * We are calculating ln(a) = ln(v * 10^t) = ln(v) + t*ln(10), * where 0.5 < v <= 5. */ if (!mpd_qcopy(&v, a, status)) { mpd_seterror(result, MPD_Malloc_error, status); goto finish; } /* Initial approximation: we have at least one non-zero digit */ _mpd_get_msdigits(&dummy, &x, &v, 3); if (x < 10) x *= 10; if (x < 100) x *= 10; x -= 100; /* a may equal z */ a_digits = a->digits; a_exp = a->exp; mpd_minalloc(z); mpd_clear_flags(z); z->data[0] = lnapprox[x]; z->len = 1; z->exp = -3; mpd_setdigits(z); if (x <= 400) { /* Reduce the input operand to 1.00 <= v <= 5.00. Let y = x + 100, * so 100 <= y <= 500. Since y contains the most significant digits * of v, y/100 <= v < (y+1)/100 and abs(z - log(v)) < 10**-2. */ v.exp = -(a_digits - 1); t = a_exp + a_digits - 1; } else { /* Reduce the input operand to 0.500 < v <= 0.999. Let y = x + 100, * so 500 < y <= 999. Since y contains the most significant digits * of v, y/1000 <= v < (y+1)/1000 and abs(z - log(v)) < 10**-2. */ v.exp = -a_digits; t = a_exp + a_digits; mpd_set_negative(z); } mpd_maxcontext(&maxcontext); mpd_maxcontext(&varcontext); varcontext.round = MPD_ROUND_TRUNC; maxprec = ctx->prec + 2; if (t == 0 && (x <= 15 || x >= 800)) { /* 0.900 <= v <= 1.15: Estimate the magnitude of the logarithm. * If ln(v) will underflow, skip the loop. Otherwise, adjust the * precision upwards in order to obtain a sufficient number of * significant digits. * * Case v > 1: * abs((v-1)/10) < abs((v-1)/v) < abs(ln(v)) < abs(v-1) * Case v < 1: * abs(v-1) < abs(ln(v)) < abs((v-1)/v) < abs((v-1)*10) */ int cmp = _mpd_cmp(&v, &one); /* Upper bound (assume v > 1): abs(v-1), unrounded */ _mpd_qsub(&tmp, &v, &one, &maxcontext, &maxcontext.status); if (maxcontext.status & MPD_Errors) { mpd_seterror(result, MPD_Malloc_error, status); goto finish; } if (cmp < 0) { /* v < 1: abs((v-1)*10) */ tmp.exp += 1; } if (mpd_adjexp(&tmp) < mpd_etiny(ctx)) { /* The upper bound is less than etiny: Underflow to zero */ _settriple(result, (cmp<0), 1, mpd_etiny(ctx)-1); goto finish; } /* Lower bound: abs((v-1)/10) or abs(v-1) */ tmp.exp -= 1; if (mpd_adjexp(&tmp) < 0) { /* Absolute error of the loop: abs(z - log(v)) < 10**-p. If * p = ctx->prec+2-adjexp(lower), then the relative error of * the result is (using 10**adjexp(x) <= abs(x)): * * abs(z - log(v)) / abs(log(v)) < 10**-p / abs(log(v)) * <= 10**(-ctx->prec-2) */ maxprec = maxprec - mpd_adjexp(&tmp); } } i = ln_schedule_prec(klist, maxprec, 2); for (; i >= 0; i--) { varcontext.prec = 2*klist[i]+3; z->flags ^= MPD_NEG; _mpd_qexp(&tmp, z, &varcontext, status); z->flags ^= MPD_NEG; if (v.digits > varcontext.prec) { shift = v.digits - varcontext.prec; mpd_qshiftr(&vtmp, &v, shift, status); vtmp.exp += shift; mpd_qmul(&tmp, &vtmp, &tmp, &varcontext, status); } else { mpd_qmul(&tmp, &v, &tmp, &varcontext, status); } mpd_qsub(&tmp, &tmp, &one, &maxcontext, status); mpd_qadd(z, z, &tmp, &maxcontext, status); if (mpd_isspecial(z)) { break; } } /* * Case t == 0: * t * log(10) == 0, the result does not change and the analysis * above applies. If v < 0.900 or v > 1.15, the relative error is * less than 10**(-ctx.prec-1). * Case t != 0: * z := approx(log(v)) * y := approx(log(10)) * p := maxprec = ctx->prec + 2 * Absolute errors: * 1) abs(z - log(v)) < 10**-p * 2) abs(y - log(10)) < 10**-p * The multiplication is exact, so: * 3) abs(t*y - t*log(10)) < t*10**-p * The sum is exact, so: * 4) abs((z + t*y) - (log(v) + t*log(10))) < (abs(t) + 1) * 10**-p * Bounds for log(v) and log(10): * 5) -7/10 < log(v) < 17/10 * 6) 23/10 < log(10) < 24/10 * Using 4), 5), 6) and t != 0, the relative error is: * * 7) relerr < ((abs(t) + 1)*10**-p) / abs(log(v) + t*log(10)) * < 0.5 * 10**(-p + 1) = 0.5 * 10**(-ctx->prec-1) */ mpd_qln10(&v, maxprec+1, status); mpd_qmul_ssize(&tmp, &v, t, &maxcontext, status); mpd_qadd(result, &tmp, z, &maxcontext, status); finish: *status |= (MPD_Inexact|MPD_Rounded); mpd_del(&v); mpd_del(&vtmp); mpd_del(&tmp); } /* ln(a) */ void mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; mpd_ssize_t adjexp, t; if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } mpd_setspecial(result, MPD_POS, MPD_INF); return; } if (mpd_iszerocoeff(a)) { mpd_setspecial(result, MPD_NEG, MPD_INF); return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (_mpd_cmp(a, &one) == 0) { _settriple(result, MPD_POS, 0, 0); return; } /* * Check if the result will overflow (0 < x, x != 1): * 1) log10(x) < 0 iff adjexp(x) < 0 * 2) 0 < x /\ x <= y ==> adjexp(x) <= adjexp(y) * 3) 0 < x /\ x != 1 ==> 2 * abs(log10(x)) < abs(log(x)) * 4) adjexp(x) <= log10(x) < adjexp(x) + 1 * * Case adjexp(x) >= 0: * 5) 2 * adjexp(x) < abs(log(x)) * Case adjexp(x) > 0: * 6) adjexp(2 * adjexp(x)) <= adjexp(abs(log(x))) * Case adjexp(x) == 0: * mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered) * * Case adjexp(x) < 0: * 7) 2 * (-adjexp(x) - 1) < abs(log(x)) * Case adjexp(x) < -1: * 8) adjexp(2 * (-adjexp(x) - 1)) <= adjexp(abs(log(x))) * Case adjexp(x) == -1: * mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered) */ adjexp = mpd_adjexp(a); t = (adjexp < 0) ? -adjexp-1 : adjexp; t *= 2; if (mpd_exp_digits(t)-1 > ctx->emax) { *status |= MPD_Overflow|MPD_Inexact|MPD_Rounded; mpd_setspecial(result, (adjexp<0), MPD_INF); return; } workctx = *ctx; workctx.round = MPD_ROUND_HALF_EVEN; if (ctx->allcr) { MPD_NEW_STATIC(t1, 0,0,0,0); MPD_NEW_STATIC(t2, 0,0,0,0); MPD_NEW_STATIC(ulp, 0,0,0,0); MPD_NEW_STATIC(aa, 0,0,0,0); mpd_ssize_t prec; if (result == a) { if (!mpd_qcopy(&aa, a, status)) { mpd_seterror(result, MPD_Malloc_error, status); return; } a = &aa; } workctx.clamp = 0; prec = ctx->prec + 3; while (1) { workctx.prec = prec; _mpd_qln(result, a, &workctx, status); _ssettriple(&ulp, MPD_POS, 1, result->exp + result->digits-workctx.prec); workctx.prec = ctx->prec; mpd_qadd(&t1, result, &ulp, &workctx, &workctx.status); mpd_qsub(&t2, result, &ulp, &workctx, &workctx.status); if (mpd_isspecial(result) || mpd_iszerocoeff(result) || mpd_qcmp(&t1, &t2, status) == 0) { workctx.clamp = ctx->clamp; mpd_check_underflow(result, &workctx, status); mpd_qfinalize(result, &workctx, status); break; } prec += MPD_RDIGITS; } mpd_del(&t1); mpd_del(&t2); mpd_del(&ulp); mpd_del(&aa); } else { _mpd_qln(result, a, &workctx, status); mpd_check_underflow(result, &workctx, status); mpd_qfinalize(result, &workctx, status); } } /* * Internal log10() function that does not check for specials, zero or one. * Case SKIP_FINALIZE: * Relative error: abs(result - log10(a)) < 0.1 * 10**-prec * abs(log10(a)) * Case DO_FINALIZE: * Ulp error: abs(result - log10(a)) < ulp(log10(a)) */ enum {SKIP_FINALIZE, DO_FINALIZE}; static void _mpd_qlog10(int action, mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_STATIC(ln10,0,0,0,0); mpd_maxcontext(&workctx); workctx.prec = ctx->prec + 3; /* relative error: 0.1 * 10**(-p-3). The specific underflow shortcut * in _mpd_qln() does not change the final result. */ _mpd_qln(result, a, &workctx, status); /* relative error: 5 * 10**(-p-3) */ mpd_qln10(&ln10, workctx.prec, status); if (action == DO_FINALIZE) { workctx = *ctx; workctx.round = MPD_ROUND_HALF_EVEN; } /* SKIP_FINALIZE: relative error: 5 * 10**(-p-3) */ _mpd_qdiv(NO_IDEAL_EXP, result, result, &ln10, &workctx, status); mpd_del(&ln10); } /* log10(a) */ void mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; mpd_ssize_t adjexp, t; workctx = *ctx; workctx.round = MPD_ROUND_HALF_EVEN; if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } mpd_setspecial(result, MPD_POS, MPD_INF); return; } if (mpd_iszerocoeff(a)) { mpd_setspecial(result, MPD_NEG, MPD_INF); return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_coeff_ispow10(a)) { uint8_t sign = 0; adjexp = mpd_adjexp(a); if (adjexp < 0) { sign = 1; adjexp = -adjexp; } _settriple(result, sign, adjexp, 0); mpd_qfinalize(result, &workctx, status); return; } /* * Check if the result will overflow (0 < x, x != 1): * 1) log10(x) < 0 iff adjexp(x) < 0 * 2) 0 < x /\ x <= y ==> adjexp(x) <= adjexp(y) * 3) adjexp(x) <= log10(x) < adjexp(x) + 1 * * Case adjexp(x) >= 0: * 4) adjexp(x) <= abs(log10(x)) * Case adjexp(x) > 0: * 5) adjexp(adjexp(x)) <= adjexp(abs(log10(x))) * Case adjexp(x) == 0: * mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered) * * Case adjexp(x) < 0: * 6) -adjexp(x) - 1 < abs(log10(x)) * Case adjexp(x) < -1: * 7) adjexp(-adjexp(x) - 1) <= adjexp(abs(log(x))) * Case adjexp(x) == -1: * mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered) */ adjexp = mpd_adjexp(a); t = (adjexp < 0) ? -adjexp-1 : adjexp; if (mpd_exp_digits(t)-1 > ctx->emax) { *status |= MPD_Overflow|MPD_Inexact|MPD_Rounded; mpd_setspecial(result, (adjexp<0), MPD_INF); return; } if (ctx->allcr) { MPD_NEW_STATIC(t1, 0,0,0,0); MPD_NEW_STATIC(t2, 0,0,0,0); MPD_NEW_STATIC(ulp, 0,0,0,0); MPD_NEW_STATIC(aa, 0,0,0,0); mpd_ssize_t prec; if (result == a) { if (!mpd_qcopy(&aa, a, status)) { mpd_seterror(result, MPD_Malloc_error, status); return; } a = &aa; } workctx.clamp = 0; prec = ctx->prec + 3; while (1) { workctx.prec = prec; _mpd_qlog10(SKIP_FINALIZE, result, a, &workctx, status); _ssettriple(&ulp, MPD_POS, 1, result->exp + result->digits-workctx.prec); workctx.prec = ctx->prec; mpd_qadd(&t1, result, &ulp, &workctx, &workctx.status); mpd_qsub(&t2, result, &ulp, &workctx, &workctx.status); if (mpd_isspecial(result) || mpd_iszerocoeff(result) || mpd_qcmp(&t1, &t2, status) == 0) { workctx.clamp = ctx->clamp; mpd_check_underflow(result, &workctx, status); mpd_qfinalize(result, &workctx, status); break; } prec += MPD_RDIGITS; } mpd_del(&t1); mpd_del(&t2); mpd_del(&ulp); mpd_del(&aa); } else { _mpd_qlog10(DO_FINALIZE, result, a, &workctx, status); mpd_check_underflow(result, &workctx, status); } } /* * Maximum of the two operands. Attention: If one operand is a quiet NaN and the * other is numeric, the numeric operand is returned. This may not be what one * expects. */ void mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_isqnan(a) && !mpd_isnan(b)) { mpd_qcopy(result, b, status); } else if (mpd_isqnan(b) && !mpd_isnan(a)) { mpd_qcopy(result, a, status); } else if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } else { c = _mpd_cmp(a, b); if (c == 0) { c = _mpd_cmp_numequal(a, b); } if (c < 0) { mpd_qcopy(result, b, status); } else { mpd_qcopy(result, a, status); } } mpd_qfinalize(result, ctx, status); } /* * Maximum magnitude: Same as mpd_max(), but compares the operands with their * sign ignored. */ void mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_isqnan(a) && !mpd_isnan(b)) { mpd_qcopy(result, b, status); } else if (mpd_isqnan(b) && !mpd_isnan(a)) { mpd_qcopy(result, a, status); } else if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } else { c = _mpd_cmp_abs(a, b); if (c == 0) { c = _mpd_cmp_numequal(a, b); } if (c < 0) { mpd_qcopy(result, b, status); } else { mpd_qcopy(result, a, status); } } mpd_qfinalize(result, ctx, status); } /* * Minimum of the two operands. Attention: If one operand is a quiet NaN and the * other is numeric, the numeric operand is returned. This may not be what one * expects. */ void mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_isqnan(a) && !mpd_isnan(b)) { mpd_qcopy(result, b, status); } else if (mpd_isqnan(b) && !mpd_isnan(a)) { mpd_qcopy(result, a, status); } else if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } else { c = _mpd_cmp(a, b); if (c == 0) { c = _mpd_cmp_numequal(a, b); } if (c < 0) { mpd_qcopy(result, a, status); } else { mpd_qcopy(result, b, status); } } mpd_qfinalize(result, ctx, status); } /* * Minimum magnitude: Same as mpd_min(), but compares the operands with their * sign ignored. */ void mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_isqnan(a) && !mpd_isnan(b)) { mpd_qcopy(result, b, status); } else if (mpd_isqnan(b) && !mpd_isnan(a)) { mpd_qcopy(result, a, status); } else if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } else { c = _mpd_cmp_abs(a, b); if (c == 0) { c = _mpd_cmp_numequal(a, b); } if (c < 0) { mpd_qcopy(result, a, status); } else { mpd_qcopy(result, b, status); } } mpd_qfinalize(result, ctx, status); } /* Minimum space needed for the result array in _karatsuba_rec(). */ static inline mpd_size_t _kmul_resultsize(mpd_size_t la, mpd_size_t lb) { mpd_size_t n, m; n = add_size_t(la, lb); n = add_size_t(n, 1); m = (la+1)/2 + 1; m = mul_size_t(m, 3); return (m > n) ? m : n; } /* Work space needed in _karatsuba_rec(). lim >= 4 */ static inline mpd_size_t _kmul_worksize(mpd_size_t n, mpd_size_t lim) { mpd_size_t m; if (n <= lim) { return 0; } m = (n+1)/2 + 1; return add_size_t(mul_size_t(m, 2), _kmul_worksize(m, lim)); } #define MPD_KARATSUBA_BASECASE 16 /* must be >= 4 */ /* * Add the product of a and b to c. * c must be _kmul_resultsize(la, lb) in size. * w is used as a work array and must be _kmul_worksize(a, lim) in size. * Roman E. Maeder, Storage Allocation for the Karatsuba Integer Multiplication * Algorithm. In "Design and implementation of symbolic computation systems", * Springer, 1993, ISBN 354057235X, 9783540572350. */ static void _karatsuba_rec(mpd_uint_t *c, const mpd_uint_t *a, const mpd_uint_t *b, mpd_uint_t *w, mpd_size_t la, mpd_size_t lb) { mpd_size_t m, lt; assert(la >= lb && lb > 0); assert(la <= MPD_KARATSUBA_BASECASE || w != NULL); if (la <= MPD_KARATSUBA_BASECASE) { _mpd_basemul(c, a, b, la, lb); return; } m = (la+1)/2; /* ceil(la/2) */ /* lb <= m < la */ if (lb <= m) { /* lb can now be larger than la-m */ if (lb > la-m) { lt = lb + lb + 1; /* space needed for result array */ mpd_uint_zero(w, lt); /* clear result array */ _karatsuba_rec(w, b, a+m, w+lt, lb, la-m); /* b*ah */ } else { lt = (la-m) + (la-m) + 1; /* space needed for result array */ mpd_uint_zero(w, lt); /* clear result array */ _karatsuba_rec(w, a+m, b, w+lt, la-m, lb); /* ah*b */ } _mpd_baseaddto(c+m, w, (la-m)+lb); /* add ah*b*B**m */ lt = m + m + 1; /* space needed for the result array */ mpd_uint_zero(w, lt); /* clear result array */ _karatsuba_rec(w, a, b, w+lt, m, lb); /* al*b */ _mpd_baseaddto(c, w, m+lb); /* add al*b */ return; } /* la >= lb > m */ memcpy(w, a, m * sizeof *w); w[m] = 0; _mpd_baseaddto(w, a+m, la-m); memcpy(w+(m+1), b, m * sizeof *w); w[m+1+m] = 0; _mpd_baseaddto(w+(m+1), b+m, lb-m); _karatsuba_rec(c+m, w, w+(m+1), w+2*(m+1), m+1, m+1); lt = (la-m) + (la-m) + 1; mpd_uint_zero(w, lt); _karatsuba_rec(w, a+m, b+m, w+lt, la-m, lb-m); _mpd_baseaddto(c+2*m, w, (la-m) + (lb-m)); _mpd_basesubfrom(c+m, w, (la-m) + (lb-m)); lt = m + m + 1; mpd_uint_zero(w, lt); _karatsuba_rec(w, a, b, w+lt, m, m); _mpd_baseaddto(c, w, m+m); _mpd_basesubfrom(c+m, w, m+m); return; } /* * Multiply u and v, using Karatsuba multiplication. Returns a pointer * to the result or NULL in case of failure (malloc error). * Conditions: ulen >= vlen, ulen >= 4 */ static mpd_uint_t * _mpd_kmul(const mpd_uint_t *u, const mpd_uint_t *v, mpd_size_t ulen, mpd_size_t vlen, mpd_size_t *rsize) { mpd_uint_t *result = NULL, *w = NULL; mpd_size_t m; assert(ulen >= 4); assert(ulen >= vlen); *rsize = _kmul_resultsize(ulen, vlen); if ((result = mpd_calloc(*rsize, sizeof *result)) == NULL) { return NULL; } m = _kmul_worksize(ulen, MPD_KARATSUBA_BASECASE); if (m && ((w = mpd_calloc(m, sizeof *w)) == NULL)) { mpd_free(result); return NULL; } _karatsuba_rec(result, u, v, w, ulen, vlen); if (w) mpd_free(w); return result; } /* * Determine the minimum length for the number theoretic transform. Valid * transform lengths are 2**n or 3*2**n, where 2**n <= MPD_MAXTRANSFORM_2N. * The function finds the shortest length m such that rsize <= m. */ static inline mpd_size_t _mpd_get_transform_len(mpd_size_t rsize) { mpd_size_t log2rsize; mpd_size_t x, step; assert(rsize >= 4); log2rsize = mpd_bsr(rsize); if (rsize <= 1024) { /* 2**n is faster in this range. */ x = ((mpd_size_t)1)<<log2rsize; return (rsize == x) ? x : x<<1; } else if (rsize <= MPD_MAXTRANSFORM_2N) { x = ((mpd_size_t)1)<<log2rsize; if (rsize == x) return x; step = x>>1; x += step; return (rsize <= x) ? x : x + step; } else if (rsize <= MPD_MAXTRANSFORM_2N+MPD_MAXTRANSFORM_2N/2) { return MPD_MAXTRANSFORM_2N+MPD_MAXTRANSFORM_2N/2; } else if (rsize <= 3*MPD_MAXTRANSFORM_2N) { return 3*MPD_MAXTRANSFORM_2N; } else { return MPD_SIZE_MAX; } } #ifdef PPRO #ifndef _MSC_VER static inline unsigned short _mpd_get_control87(void) { unsigned short cw; __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); return cw; } static inline void _mpd_set_control87(unsigned short cw) { __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); } #endif static unsigned int mpd_set_fenv(void) { unsigned int cw; #ifdef _MSC_VER unsigned int flags = _EM_INVALID|_EM_DENORMAL|_EM_ZERODIVIDE|_EM_OVERFLOW| _EM_UNDERFLOW|_EM_INEXACT|_RC_CHOP|_PC_64; unsigned int mask = _MCW_EM|_MCW_RC|_MCW_PC; unsigned int dummy; __control87_2(0, 0, &cw, NULL); __control87_2(flags, mask, &dummy, NULL); #else cw = _mpd_get_control87(); _mpd_set_control87(cw|0xF3F); #endif return cw; } static void mpd_restore_fenv(unsigned int cw) { #ifdef _MSC_VER unsigned int mask = _MCW_EM|_MCW_RC|_MCW_PC; unsigned int dummy; __control87_2(cw, mask, &dummy, NULL); #else _mpd_set_control87((unsigned short)cw); #endif } #endif /* PPRO */ /* * Multiply u and v, using the fast number theoretic transform. Returns * a pointer to the result or NULL in case of failure (malloc error). */ static mpd_uint_t * _mpd_fntmul(const mpd_uint_t *u, const mpd_uint_t *v, mpd_size_t ulen, mpd_size_t vlen, mpd_size_t *rsize) { mpd_uint_t *c1 = NULL, *c2 = NULL, *c3 = NULL, *vtmp = NULL; mpd_size_t n; #ifdef PPRO unsigned int cw; cw = mpd_set_fenv(); #endif *rsize = add_size_t(ulen, vlen); if ((n = _mpd_get_transform_len(*rsize)) == MPD_SIZE_MAX) { goto malloc_error; } if ((c1 = mpd_calloc(n, sizeof *c1)) == NULL) { goto malloc_error; } if ((c2 = mpd_calloc(n, sizeof *c2)) == NULL) { goto malloc_error; } if ((c3 = mpd_calloc(n, sizeof *c3)) == NULL) { goto malloc_error; } memcpy(c1, u, ulen * (sizeof *c1)); memcpy(c2, u, ulen * (sizeof *c2)); memcpy(c3, u, ulen * (sizeof *c3)); if (u == v) { if (!fnt_autoconvolute(c1, n, P1) || !fnt_autoconvolute(c2, n, P2) || !fnt_autoconvolute(c3, n, P3)) { goto malloc_error; } } else { if ((vtmp = mpd_calloc(n, sizeof *vtmp)) == NULL) { goto malloc_error; } memcpy(vtmp, v, vlen * (sizeof *vtmp)); if (!fnt_convolute(c1, vtmp, n, P1)) { mpd_free(vtmp); goto malloc_error; } memcpy(vtmp, v, vlen * (sizeof *vtmp)); mpd_uint_zero(vtmp+vlen, n-vlen); if (!fnt_convolute(c2, vtmp, n, P2)) { mpd_free(vtmp); goto malloc_error; } memcpy(vtmp, v, vlen * (sizeof *vtmp)); mpd_uint_zero(vtmp+vlen, n-vlen); if (!fnt_convolute(c3, vtmp, n, P3)) { mpd_free(vtmp); goto malloc_error; } mpd_free(vtmp); } crt3(c1, c2, c3, *rsize); out: #ifdef PPRO mpd_restore_fenv(cw); #endif if (c2) mpd_free(c2); if (c3) mpd_free(c3); return c1; malloc_error: if (c1) mpd_free(c1); c1 = NULL; goto out; } /* * Karatsuba multiplication with FNT/basemul as the base case. */ static int _karatsuba_rec_fnt(mpd_uint_t *c, const mpd_uint_t *a, const mpd_uint_t *b, mpd_uint_t *w, mpd_size_t la, mpd_size_t lb) { mpd_size_t m, lt; assert(la >= lb && lb > 0); assert(la <= 3*(MPD_MAXTRANSFORM_2N/2) || w != NULL); if (la <= 3*(MPD_MAXTRANSFORM_2N/2)) { if (lb <= 192) { _mpd_basemul(c, b, a, lb, la); } else { mpd_uint_t *result; mpd_size_t dummy; if ((result = _mpd_fntmul(a, b, la, lb, &dummy)) == NULL) { return 0; } memcpy(c, result, (la+lb) * (sizeof *result)); mpd_free(result); } return 1; } m = (la+1)/2; /* ceil(la/2) */ /* lb <= m < la */ if (lb <= m) { /* lb can now be larger than la-m */ if (lb > la-m) { lt = lb + lb + 1; /* space needed for result array */ mpd_uint_zero(w, lt); /* clear result array */ if (!_karatsuba_rec_fnt(w, b, a+m, w+lt, lb, la-m)) { /* b*ah */ return 0; /* GCOV_UNLIKELY */ } } else { lt = (la-m) + (la-m) + 1; /* space needed for result array */ mpd_uint_zero(w, lt); /* clear result array */ if (!_karatsuba_rec_fnt(w, a+m, b, w+lt, la-m, lb)) { /* ah*b */ return 0; /* GCOV_UNLIKELY */ } } _mpd_baseaddto(c+m, w, (la-m)+lb); /* add ah*b*B**m */ lt = m + m + 1; /* space needed for the result array */ mpd_uint_zero(w, lt); /* clear result array */ if (!_karatsuba_rec_fnt(w, a, b, w+lt, m, lb)) { /* al*b */ return 0; /* GCOV_UNLIKELY */ } _mpd_baseaddto(c, w, m+lb); /* add al*b */ return 1; } /* la >= lb > m */ memcpy(w, a, m * sizeof *w); w[m] = 0; _mpd_baseaddto(w, a+m, la-m); memcpy(w+(m+1), b, m * sizeof *w); w[m+1+m] = 0; _mpd_baseaddto(w+(m+1), b+m, lb-m); if (!_karatsuba_rec_fnt(c+m, w, w+(m+1), w+2*(m+1), m+1, m+1)) { return 0; /* GCOV_UNLIKELY */ } lt = (la-m) + (la-m) + 1; mpd_uint_zero(w, lt); if (!_karatsuba_rec_fnt(w, a+m, b+m, w+lt, la-m, lb-m)) { return 0; /* GCOV_UNLIKELY */ } _mpd_baseaddto(c+2*m, w, (la-m) + (lb-m)); _mpd_basesubfrom(c+m, w, (la-m) + (lb-m)); lt = m + m + 1; mpd_uint_zero(w, lt); if (!_karatsuba_rec_fnt(w, a, b, w+lt, m, m)) { return 0; /* GCOV_UNLIKELY */ } _mpd_baseaddto(c, w, m+m); _mpd_basesubfrom(c+m, w, m+m); return 1; } /* * Multiply u and v, using Karatsuba multiplication with the FNT as the * base case. Returns a pointer to the result or NULL in case of failure * (malloc error). Conditions: ulen >= vlen, ulen >= 4. */ static mpd_uint_t * _mpd_kmul_fnt(const mpd_uint_t *u, const mpd_uint_t *v, mpd_size_t ulen, mpd_size_t vlen, mpd_size_t *rsize) { mpd_uint_t *result = NULL, *w = NULL; mpd_size_t m; assert(ulen >= 4); assert(ulen >= vlen); *rsize = _kmul_resultsize(ulen, vlen); if ((result = mpd_calloc(*rsize, sizeof *result)) == NULL) { return NULL; } m = _kmul_worksize(ulen, 3*(MPD_MAXTRANSFORM_2N/2)); if (m && ((w = mpd_calloc(m, sizeof *w)) == NULL)) { mpd_free(result); /* GCOV_UNLIKELY */ return NULL; /* GCOV_UNLIKELY */ } if (!_karatsuba_rec_fnt(result, u, v, w, ulen, vlen)) { mpd_free(result); result = NULL; } if (w) mpd_free(w); return result; } /* Deal with the special cases of multiplying infinities. */ static void _mpd_qmul_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status) { if (mpd_isinfinite(a)) { if (mpd_iszero(b)) { mpd_seterror(result, MPD_Invalid_operation, status); } else { mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF); } return; } assert(mpd_isinfinite(b)); if (mpd_iszero(a)) { mpd_seterror(result, MPD_Invalid_operation, status); } else { mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF); } } /* * Internal function: Multiply a and b. _mpd_qmul deals with specials but * does NOT finalize the result. This is for use in mpd_fma(). */ static inline void _mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { const mpd_t *big = a, *small = b; mpd_uint_t *rdata = NULL; mpd_uint_t rbuf[MPD_MINALLOC_MAX]; mpd_size_t rsize, i; if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } _mpd_qmul_inf(result, a, b, status); return; } if (small->len > big->len) { _mpd_ptrswap(&big, &small); } rsize = big->len + small->len; if (big->len == 1) { _mpd_singlemul(result->data, big->data[0], small->data[0]); goto finish; } if (rsize <= (mpd_size_t)MPD_MINALLOC_MAX) { if (big->len == 2) { _mpd_mul_2_le2(rbuf, big->data, small->data, small->len); } else { mpd_uint_zero(rbuf, rsize); if (small->len == 1) { _mpd_shortmul(rbuf, big->data, big->len, small->data[0]); } else { _mpd_basemul(rbuf, small->data, big->data, small->len, big->len); } } if (!mpd_qresize(result, rsize, status)) { return; } for(i = 0; i < rsize; i++) { result->data[i] = rbuf[i]; } goto finish; } if (small->len <= 256) { rdata = mpd_calloc(rsize, sizeof *rdata); if (rdata != NULL) { if (small->len == 1) { _mpd_shortmul(rdata, big->data, big->len, small->data[0]); } else { _mpd_basemul(rdata, small->data, big->data, small->len, big->len); } } } else if (rsize <= 1024) { rdata = _mpd_kmul(big->data, small->data, big->len, small->len, &rsize); } else if (rsize <= 3*MPD_MAXTRANSFORM_2N) { rdata = _mpd_fntmul(big->data, small->data, big->len, small->len, &rsize); } else { rdata = _mpd_kmul_fnt(big->data, small->data, big->len, small->len, &rsize); } if (rdata == NULL) { mpd_seterror(result, MPD_Malloc_error, status); return; } if (mpd_isdynamic_data(result)) { mpd_free(result->data); } result->data = rdata; result->alloc = rsize; mpd_set_dynamic_data(result); finish: mpd_set_flags(result, mpd_sign(a)^mpd_sign(b)); result->exp = big->exp + small->exp; result->len = _mpd_real_size(result->data, rsize); /* resize to smaller cannot fail */ mpd_qresize(result, result->len, status); mpd_setdigits(result); } /* Multiply a and b. */ void mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { _mpd_qmul(result, a, b, ctx, status); mpd_qfinalize(result, ctx, status); } /* Multiply a and b. Set NaN/Invalid_operation if the result is inexact. */ static void _mpd_qmul_exact(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_qmul(result, a, b, ctx, &workstatus); *status |= workstatus; if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) { mpd_seterror(result, MPD_Invalid_operation, status); } } /* Multiply decimal and mpd_ssize_t. */ void mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_ssize(&bb, b, &maxcontext, status); mpd_qmul(result, a, &bb, ctx, status); mpd_del(&bb); } /* Multiply decimal and mpd_uint_t. */ void mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qsset_uint(&bb, b, &maxcontext, status); mpd_qmul(result, a, &bb, ctx, status); mpd_del(&bb); } void mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qmul_ssize(result, a, b, ctx, status); } void mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qmul_uint(result, a, b, ctx, status); } #ifdef CONFIG_64 void mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qmul_ssize(result, a, b, ctx, status); } void mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_qmul_uint(result, a, b, ctx, status); } #elif !defined(LEGACY_COMPILER) /* Multiply decimal and int64_t. */ void mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_i64(&bb, b, &maxcontext, status); mpd_qmul(result, a, &bb, ctx, status); mpd_del(&bb); } /* Multiply decimal and uint64_t. */ void mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(bb,0,0,0,0); mpd_maxcontext(&maxcontext); mpd_qset_u64(&bb, b, &maxcontext, status); mpd_qmul(result, a, &bb, ctx, status); mpd_del(&bb); } #endif /* Like the minus operator. */ void mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } } if (mpd_iszero(a) && ctx->round != MPD_ROUND_FLOOR) { mpd_qcopy_abs(result, a, status); } else { mpd_qcopy_negate(result, a, status); } mpd_qfinalize(result, ctx, status); } /* Like the plus operator. */ void mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } } if (mpd_iszero(a) && ctx->round != MPD_ROUND_FLOOR) { mpd_qcopy_abs(result, a, status); } else { mpd_qcopy(result, a, status); } mpd_qfinalize(result, ctx, status); } /* The largest representable number that is smaller than the operand. */ void mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_CONST(tiny,MPD_POS,mpd_etiny(ctx)-1,1,1,1,1); if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } assert(mpd_isinfinite(a)); if (mpd_isnegative(a)) { mpd_qcopy(result, a, status); return; } else { mpd_clear_flags(result); mpd_qmaxcoeff(result, ctx, status); if (mpd_isnan(result)) { return; } result->exp = mpd_etop(ctx); return; } } mpd_workcontext(&workctx, ctx); workctx.round = MPD_ROUND_FLOOR; if (!mpd_qcopy(result, a, status)) { return; } mpd_qfinalize(result, &workctx, &workctx.status); if (workctx.status&(MPD_Inexact|MPD_Errors)) { *status |= (workctx.status&MPD_Errors); return; } workctx.status = 0; mpd_qsub(result, a, &tiny, &workctx, &workctx.status); *status |= (workctx.status&MPD_Errors); } /* The smallest representable number that is larger than the operand. */ void mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_CONST(tiny,MPD_POS,mpd_etiny(ctx)-1,1,1,1,1); if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } assert(mpd_isinfinite(a)); if (mpd_ispositive(a)) { mpd_qcopy(result, a, status); } else { mpd_clear_flags(result); mpd_qmaxcoeff(result, ctx, status); if (mpd_isnan(result)) { return; } mpd_set_flags(result, MPD_NEG); result->exp = mpd_etop(ctx); } return; } mpd_workcontext(&workctx, ctx); workctx.round = MPD_ROUND_CEILING; if (!mpd_qcopy(result, a, status)) { return; } mpd_qfinalize(result, &workctx, &workctx.status); if (workctx.status & (MPD_Inexact|MPD_Errors)) { *status |= (workctx.status&MPD_Errors); return; } workctx.status = 0; mpd_qadd(result, a, &tiny, &workctx, &workctx.status); *status |= (workctx.status&MPD_Errors); } /* * The number closest to the first operand that is in the direction towards * the second operand. */ void mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { int c; if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } c = _mpd_cmp(a, b); if (c == 0) { mpd_qcopy_sign(result, a, b, status); return; } if (c < 0) { mpd_qnext_plus(result, a, ctx, status); } else { mpd_qnext_minus(result, a, ctx, status); } if (mpd_isinfinite(result)) { *status |= (MPD_Overflow|MPD_Rounded|MPD_Inexact); } else if (mpd_adjexp(result) < ctx->emin) { *status |= (MPD_Underflow|MPD_Subnormal|MPD_Rounded|MPD_Inexact); if (mpd_iszero(result)) { *status |= MPD_Clamped; } } } /* * Internal function: Integer power with mpd_uint_t exponent. The function * can fail with MPD_Malloc_error. * * The error is equal to the error incurred in k-1 multiplications. Assuming * the upper bound for the relative error in each operation: * * abs(err) = 5 * 10**-prec * result = x**k * (1 + err)**(k-1) */ static inline void _mpd_qpow_uint(mpd_t *result, const mpd_t *base, mpd_uint_t exp, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_uint_t n; if (exp == 0) { _settriple(result, resultsign, 1, 0); /* GCOV_NOT_REACHED */ return; /* GCOV_NOT_REACHED */ } if (!mpd_qcopy(result, base, status)) { return; } n = mpd_bits[mpd_bsr(exp)]; while (n >>= 1) { mpd_qmul(result, result, result, ctx, &workstatus); if (exp & n) { mpd_qmul(result, result, base, ctx, &workstatus); } if (mpd_isspecial(result) || (mpd_iszerocoeff(result) && (workstatus & MPD_Clamped))) { break; } } *status |= workstatus; mpd_set_sign(result, resultsign); } /* * Internal function: Integer power with mpd_t exponent, tbase and texp * are modified!! Function can fail with MPD_Malloc_error. * * The error is equal to the error incurred in k multiplications. Assuming * the upper bound for the relative error in each operation: * * abs(err) = 5 * 10**-prec * result = x**k * (1 + err)**k */ static inline void _mpd_qpow_mpd(mpd_t *result, mpd_t *tbase, mpd_t *texp, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_context_t maxctx; MPD_NEW_CONST(two,0,0,1,1,1,2); mpd_maxcontext(&maxctx); /* resize to smaller cannot fail */ mpd_qcopy(result, &one, status); while (!mpd_iszero(texp)) { if (mpd_isodd(texp)) { mpd_qmul(result, result, tbase, ctx, &workstatus); *status |= workstatus; if (mpd_isspecial(result) || (mpd_iszerocoeff(result) && (workstatus & MPD_Clamped))) { break; } } mpd_qmul(tbase, tbase, tbase, ctx, &workstatus); mpd_qdivint(texp, texp, &two, &maxctx, &workstatus); if (mpd_isnan(tbase) || mpd_isnan(texp)) { mpd_seterror(result, workstatus&MPD_Errors, status); return; } } mpd_set_sign(result, resultsign); } /* * The power function for integer exponents. Relative error _before_ the * final rounding to prec: * abs(result - base**exp) < 0.1 * 10**-prec * abs(base**exp) */ static void _mpd_qpow_int(mpd_t *result, const mpd_t *base, const mpd_t *exp, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_STATIC(tbase,0,0,0,0); MPD_NEW_STATIC(texp,0,0,0,0); mpd_uint_t n; mpd_workcontext(&workctx, ctx); workctx.prec += (exp->digits + exp->exp + 2); workctx.round = MPD_ROUND_HALF_EVEN; workctx.clamp = 0; if (mpd_isnegative(exp)) { uint32_t workstatus = 0; workctx.prec += 1; mpd_qdiv(&tbase, &one, base, &workctx, &workstatus); *status |= workstatus; if (workstatus&MPD_Errors) { mpd_setspecial(result, MPD_POS, MPD_NAN); goto finish; } } else { if (!mpd_qcopy(&tbase, base, status)) { mpd_setspecial(result, MPD_POS, MPD_NAN); goto finish; } } n = mpd_qabs_uint(exp, &workctx.status); if (workctx.status&MPD_Invalid_operation) { if (!mpd_qcopy(&texp, exp, status)) { mpd_setspecial(result, MPD_POS, MPD_NAN); /* GCOV_UNLIKELY */ goto finish; /* GCOV_UNLIKELY */ } _mpd_qpow_mpd(result, &tbase, &texp, resultsign, &workctx, status); } else { _mpd_qpow_uint(result, &tbase, n, resultsign, &workctx, status); } if (mpd_isinfinite(result)) { /* for ROUND_DOWN, ROUND_FLOOR, etc. */ _settriple(result, resultsign, 1, MPD_EXP_INF); } finish: mpd_del(&tbase); mpd_del(&texp); mpd_qfinalize(result, ctx, status); } /* * If the exponent is infinite and base equals one, the result is one * with a coefficient of length prec. Otherwise, result is undefined. * Return the value of the comparison against one. */ static int _qcheck_pow_one_inf(mpd_t *result, const mpd_t *base, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status) { mpd_ssize_t shift; int cmp; if ((cmp = _mpd_cmp(base, &one)) == 0) { shift = ctx->prec-1; mpd_qshiftl(result, &one, shift, status); result->exp = -shift; mpd_set_flags(result, resultsign); *status |= (MPD_Inexact|MPD_Rounded); } return cmp; } /* * If abs(base) equals one, calculate the correct power of one result. * Otherwise, result is undefined. Return the value of the comparison * against 1. * * This is an internal function that does not check for specials. */ static int _qcheck_pow_one(mpd_t *result, const mpd_t *base, const mpd_t *exp, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_ssize_t shift; int cmp; if ((cmp = _mpd_cmp_abs(base, &one)) == 0) { if (_mpd_isint(exp)) { if (mpd_isnegative(exp)) { _settriple(result, resultsign, 1, 0); return 0; } /* 1.000**3 = 1.000000000 */ mpd_qmul_ssize(result, exp, -base->exp, ctx, &workstatus); if (workstatus&MPD_Errors) { *status |= (workstatus&MPD_Errors); return 0; } /* digits-1 after exponentiation */ shift = mpd_qget_ssize(result, &workstatus); /* shift is MPD_SSIZE_MAX if result is too large */ if (shift > ctx->prec-1) { shift = ctx->prec-1; *status |= MPD_Rounded; } } else if (mpd_ispositive(base)) { shift = ctx->prec-1; *status |= (MPD_Inexact|MPD_Rounded); } else { return -2; /* GCOV_NOT_REACHED */ } if (!mpd_qshiftl(result, &one, shift, status)) { return 0; } result->exp = -shift; mpd_set_flags(result, resultsign); } return cmp; } /* * Detect certain over/underflow of x**y. * ACL2 proof: pow-bounds.lisp. * * Symbols: * * e: EXP_INF or EXP_CLAMP * x: base * y: exponent * * omega(e) = log10(abs(e)) * zeta(x) = log10(abs(log10(x))) * theta(y) = log10(abs(y)) * * Upper and lower bounds: * * ub_omega(e) = ceil(log10(abs(e))) * lb_theta(y) = floor(log10(abs(y))) * * | floor(log10(floor(abs(log10(x))))) if x < 1/10 or x >= 10 * lb_zeta(x) = | floor(log10(abs(x-1)/10)) if 1/10 <= x < 1 * | floor(log10(abs((x-1)/100))) if 1 < x < 10 * * ub_omega(e) and lb_theta(y) are obviously upper and lower bounds * for omega(e) and theta(y). * * lb_zeta is a lower bound for zeta(x): * * x < 1/10 or x >= 10: * * abs(log10(x)) >= 1, so the outer log10 is well defined. Since log10 * is strictly increasing, the end result is a lower bound. * * 1/10 <= x < 1: * * We use: log10(x) <= (x-1)/log(10) * abs(log10(x)) >= abs(x-1)/log(10) * abs(log10(x)) >= abs(x-1)/10 * * 1 < x < 10: * * We use: (x-1)/(x*log(10)) < log10(x) * abs((x-1)/100) < abs(log10(x)) * * XXX: abs((x-1)/10) would work, need ACL2 proof. * * * Let (0 < x < 1 and y < 0) or (x > 1 and y > 0). (H1) * Let ub_omega(exp_inf) < lb_zeta(x) + lb_theta(y) (H2) * * Then: * log10(abs(exp_inf)) < log10(abs(log10(x))) + log10(abs(y)). (1) * exp_inf < log10(x) * y (2) * 10**exp_inf < x**y (3) * * Let (0 < x < 1 and y > 0) or (x > 1 and y < 0). (H3) * Let ub_omega(exp_clamp) < lb_zeta(x) + lb_theta(y) (H4) * * Then: * log10(abs(exp_clamp)) < log10(abs(log10(x))) + log10(abs(y)). (4) * log10(x) * y < exp_clamp (5) * x**y < 10**exp_clamp (6) * */ static mpd_ssize_t _lower_bound_zeta(const mpd_t *x, uint32_t *status) { mpd_context_t maxctx; MPD_NEW_STATIC(scratch,0,0,0,0); mpd_ssize_t t, u; t = mpd_adjexp(x); if (t > 0) { /* x >= 10 -> floor(log10(floor(abs(log10(x))))) */ return mpd_exp_digits(t) - 1; } else if (t < -1) { /* x < 1/10 -> floor(log10(floor(abs(log10(x))))) */ return mpd_exp_digits(t+1) - 1; } else { mpd_maxcontext(&maxctx); mpd_qsub(&scratch, x, &one, &maxctx, status); if (mpd_isspecial(&scratch)) { mpd_del(&scratch); return MPD_SSIZE_MAX; } u = mpd_adjexp(&scratch); mpd_del(&scratch); /* t == -1, 1/10 <= x < 1 -> floor(log10(abs(x-1)/10)) * t == 0, 1 < x < 10 -> floor(log10(abs(x-1)/100)) */ return (t == 0) ? u-2 : u-1; } } /* * Detect cases of certain overflow/underflow in the power function. * Assumptions: x != 1, y != 0. The proof above is for positive x. * If x is negative and y is an odd integer, x**y == -(abs(x)**y), * so the analysis does not change. */ static int _qcheck_pow_bounds(mpd_t *result, const mpd_t *x, const mpd_t *y, uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_SHARED(abs_x, x); mpd_ssize_t ub_omega, lb_zeta, lb_theta; uint8_t sign; mpd_set_positive(&abs_x); lb_theta = mpd_adjexp(y); lb_zeta = _lower_bound_zeta(&abs_x, status); if (lb_zeta == MPD_SSIZE_MAX) { mpd_seterror(result, MPD_Malloc_error, status); return 1; } sign = (mpd_adjexp(&abs_x) < 0) ^ mpd_sign(y); if (sign == 0) { /* (0 < |x| < 1 and y < 0) or (|x| > 1 and y > 0) */ ub_omega = mpd_exp_digits(ctx->emax); if (ub_omega < lb_zeta + lb_theta) { _settriple(result, resultsign, 1, MPD_EXP_INF); mpd_qfinalize(result, ctx, status); return 1; } } else { /* (0 < |x| < 1 and y > 0) or (|x| > 1 and y < 0). */ ub_omega = mpd_exp_digits(mpd_etiny(ctx)); if (ub_omega < lb_zeta + lb_theta) { _settriple(result, resultsign, 1, mpd_etiny(ctx)-1); mpd_qfinalize(result, ctx, status); return 1; } } return 0; } /* * TODO: Implement algorithm for computing exact powers from decimal.py. * In order to prevent infinite loops, this has to be called before * using Ziv's strategy for correct rounding. */ /* static int _mpd_qpow_exact(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status) { return 0; } */ /* * The power function for real exponents. * Relative error: abs(result - e**y) < e**y * 1/5 * 10**(-prec - 1) */ static void _mpd_qpow_real(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_STATIC(texp,0,0,0,0); if (!mpd_qcopy(&texp, exp, status)) { mpd_seterror(result, MPD_Malloc_error, status); return; } mpd_maxcontext(&workctx); workctx.prec = (base->digits > ctx->prec) ? base->digits : ctx->prec; workctx.prec += (4 + MPD_EXPDIGITS); workctx.round = MPD_ROUND_HALF_EVEN; workctx.allcr = ctx->allcr; /* * extra := MPD_EXPDIGITS = MPD_EXP_MAX_T * wp := prec + 4 + extra * abs(err) < 5 * 10**-wp * y := log(base) * exp * Calculate: * 1) e**(y * (1 + err)**2) * (1 + err) * = e**y * e**(y * (2*err + err**2)) * (1 + err) * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Relative error of the underlined term: * 2) abs(e**(y * (2*err + err**2)) - 1) * Case abs(y) >= 10**extra: * 3) adjexp(y)+1 > log10(abs(y)) >= extra * This triggers the Overflow/Underflow shortcut in _mpd_qexp(), * so no further analysis is necessary. * Case abs(y) < 10**extra: * 4) abs(y * (2*err + err**2)) < 1/5 * 10**(-prec - 2) * Use (see _mpd_qexp): * 5) abs(x) <= 9/10 * 10**-p ==> abs(e**x - 1) < 10**-p * With 2), 4) and 5): * 6) abs(e**(y * (2*err + err**2)) - 1) < 10**(-prec - 2) * The complete relative error of 1) is: * 7) abs(result - e**y) < e**y * 1/5 * 10**(-prec - 1) */ mpd_qln(result, base, &workctx, &workctx.status); mpd_qmul(result, result, &texp, &workctx, &workctx.status); mpd_qexp(result, result, &workctx, status); mpd_del(&texp); *status |= (workctx.status&MPD_Errors); *status |= (MPD_Inexact|MPD_Rounded); } /* The power function: base**exp */ void mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_context_t *ctx, uint32_t *status) { uint8_t resultsign = 0; int intexp = 0; int cmp; if (mpd_isspecial(base) || mpd_isspecial(exp)) { if (mpd_qcheck_nans(result, base, exp, ctx, status)) { return; } } if (mpd_isinteger(exp)) { intexp = 1; resultsign = mpd_isnegative(base) && mpd_isodd(exp); } if (mpd_iszero(base)) { if (mpd_iszero(exp)) { mpd_seterror(result, MPD_Invalid_operation, status); } else if (mpd_isnegative(exp)) { mpd_setspecial(result, resultsign, MPD_INF); } else { _settriple(result, resultsign, 0, 0); } return; } if (mpd_isnegative(base)) { if (!intexp || mpd_isinfinite(exp)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } } if (mpd_isinfinite(exp)) { /* power of one */ cmp = _qcheck_pow_one_inf(result, base, resultsign, ctx, status); if (cmp == 0) { return; } else { cmp *= mpd_arith_sign(exp); if (cmp < 0) { _settriple(result, resultsign, 0, 0); } else { mpd_setspecial(result, resultsign, MPD_INF); } } return; } if (mpd_isinfinite(base)) { if (mpd_iszero(exp)) { _settriple(result, resultsign, 1, 0); } else if (mpd_isnegative(exp)) { _settriple(result, resultsign, 0, 0); } else { mpd_setspecial(result, resultsign, MPD_INF); } return; } if (mpd_iszero(exp)) { _settriple(result, resultsign, 1, 0); return; } if (_qcheck_pow_one(result, base, exp, resultsign, ctx, status) == 0) { return; } if (_qcheck_pow_bounds(result, base, exp, resultsign, ctx, status)) { return; } if (intexp) { _mpd_qpow_int(result, base, exp, resultsign, ctx, status); } else { _mpd_qpow_real(result, base, exp, ctx, status); if (!mpd_isspecial(result) && _mpd_cmp(result, &one) == 0) { mpd_ssize_t shift = ctx->prec-1; mpd_qshiftl(result, &one, shift, status); result->exp = -shift; } if (mpd_isinfinite(result)) { /* for ROUND_DOWN, ROUND_FLOOR, etc. */ _settriple(result, MPD_POS, 1, MPD_EXP_INF); } mpd_qfinalize(result, ctx, status); } } /* * Internal function: Integer powmod with mpd_uint_t exponent, base is modified! * Function can fail with MPD_Malloc_error. */ static inline void _mpd_qpowmod_uint(mpd_t *result, mpd_t *base, mpd_uint_t exp, const mpd_t *mod, uint32_t *status) { mpd_context_t maxcontext; mpd_maxcontext(&maxcontext); /* resize to smaller cannot fail */ mpd_qcopy(result, &one, status); while (exp > 0) { if (exp & 1) { _mpd_qmul_exact(result, result, base, &maxcontext, status); mpd_qrem(result, result, mod, &maxcontext, status); } _mpd_qmul_exact(base, base, base, &maxcontext, status); mpd_qrem(base, base, mod, &maxcontext, status); exp >>= 1; } } /* The powmod function: (base**exp) % mod */ void mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp, const mpd_t *mod, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(tbase,0,0,0,0); MPD_NEW_STATIC(texp,0,0,0,0); MPD_NEW_STATIC(tmod,0,0,0,0); MPD_NEW_STATIC(tmp,0,0,0,0); MPD_NEW_CONST(two,0,0,1,1,1,2); mpd_ssize_t tbase_exp, texp_exp; mpd_ssize_t i; mpd_t t; mpd_uint_t r; uint8_t sign; if (mpd_isspecial(base) || mpd_isspecial(exp) || mpd_isspecial(mod)) { if (mpd_qcheck_3nans(result, base, exp, mod, ctx, status)) { return; } mpd_seterror(result, MPD_Invalid_operation, status); return; } if (!_mpd_isint(base) || !_mpd_isint(exp) || !_mpd_isint(mod)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_iszerocoeff(mod)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mod->digits+mod->exp > ctx->prec) { mpd_seterror(result, MPD_Invalid_operation, status); return; } sign = (mpd_isnegative(base)) && (mpd_isodd(exp)); if (mpd_iszerocoeff(exp)) { if (mpd_iszerocoeff(base)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } r = (_mpd_cmp_abs(mod, &one)==0) ? 0 : 1; _settriple(result, sign, r, 0); return; } if (mpd_isnegative(exp)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_iszerocoeff(base)) { _settriple(result, sign, 0, 0); return; } mpd_maxcontext(&maxcontext); mpd_qrescale(&tmod, mod, 0, &maxcontext, &maxcontext.status); if (maxcontext.status&MPD_Errors) { mpd_seterror(result, maxcontext.status&MPD_Errors, status); goto out; } maxcontext.status = 0; mpd_set_positive(&tmod); mpd_qround_to_int(&tbase, base, &maxcontext, status); mpd_set_positive(&tbase); tbase_exp = tbase.exp; tbase.exp = 0; mpd_qround_to_int(&texp, exp, &maxcontext, status); texp_exp = texp.exp; texp.exp = 0; /* base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo */ mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status); mpd_qshiftl(result, &one, tbase_exp, status); mpd_qrem(result, result, &tmod, &maxcontext, status); _mpd_qmul_exact(&tbase, &tbase, result, &maxcontext, status); mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status); if (mpd_isspecial(&tbase) || mpd_isspecial(&texp) || mpd_isspecial(&tmod)) { goto mpd_errors; } for (i = 0; i < texp_exp; i++) { _mpd_qpowmod_uint(&tmp, &tbase, 10, &tmod, status); t = tmp; tmp = tbase; tbase = t; } if (mpd_isspecial(&tbase)) { goto mpd_errors; /* GCOV_UNLIKELY */ } /* resize to smaller cannot fail */ mpd_qcopy(result, &one, status); while (mpd_isfinite(&texp) && !mpd_iszero(&texp)) { if (mpd_isodd(&texp)) { _mpd_qmul_exact(result, result, &tbase, &maxcontext, status); mpd_qrem(result, result, &tmod, &maxcontext, status); } _mpd_qmul_exact(&tbase, &tbase, &tbase, &maxcontext, status); mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status); mpd_qdivint(&texp, &texp, &two, &maxcontext, status); } if (mpd_isspecial(&texp) || mpd_isspecial(&tbase) || mpd_isspecial(&tmod) || mpd_isspecial(result)) { /* MPD_Malloc_error */ goto mpd_errors; } else { mpd_set_sign(result, sign); } out: mpd_del(&tbase); mpd_del(&texp); mpd_del(&tmod); mpd_del(&tmp); return; mpd_errors: mpd_setspecial(result, MPD_POS, MPD_NAN); goto out; } void mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_ssize_t b_exp = b->exp; mpd_ssize_t expdiff, shift; mpd_uint_t rnd; if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(result, a, b, ctx, status)) { return; } if (mpd_isinfinite(a) && mpd_isinfinite(b)) { mpd_qcopy(result, a, status); return; } mpd_seterror(result, MPD_Invalid_operation, status); return; } if (b->exp > ctx->emax || b->exp < mpd_etiny(ctx)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (mpd_iszero(a)) { _settriple(result, mpd_sign(a), 0, b->exp); mpd_qfinalize(result, ctx, status); return; } expdiff = a->exp - b->exp; if (a->digits + expdiff > ctx->prec) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (expdiff >= 0) { shift = expdiff; if (!mpd_qshiftl(result, a, shift, status)) { return; } result->exp = b_exp; } else { /* At this point expdiff < 0 and a->digits+expdiff <= prec, * so the shift before an increment will fit in prec. */ shift = -expdiff; rnd = mpd_qshiftr(result, a, shift, status); if (rnd == MPD_UINT_MAX) { return; } result->exp = b_exp; if (!_mpd_apply_round_fit(result, rnd, ctx, status)) { return; } workstatus |= MPD_Rounded; if (rnd) { workstatus |= MPD_Inexact; } } if (mpd_adjexp(result) > ctx->emax || mpd_adjexp(result) < mpd_etiny(ctx)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } *status |= workstatus; mpd_qfinalize(result, ctx, status); } void mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_ssize_t shift, maxexp, maxshift; uint8_t sign_a = mpd_sign(a); if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } mpd_qcopy(result, a, status); return; } if (!mpd_qcopy(result, a, status)) { return; } mpd_qfinalize(result, ctx, status); if (mpd_isspecial(result)) { return; } if (mpd_iszero(result)) { _settriple(result, sign_a, 0, 0); return; } shift = mpd_trail_zeros(result); maxexp = (ctx->clamp) ? mpd_etop(ctx) : ctx->emax; /* After the finalizing above result->exp <= maxexp. */ maxshift = maxexp - result->exp; shift = (shift > maxshift) ? maxshift : shift; mpd_qshiftr_inplace(result, shift); result->exp += shift; } void mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_STATIC(q,0,0,0,0); if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(r, a, b, ctx, status)) { return; } if (mpd_isinfinite(a)) { mpd_seterror(r, MPD_Invalid_operation, status); return; } if (mpd_isinfinite(b)) { mpd_qcopy(r, a, status); mpd_qfinalize(r, ctx, status); return; } /* debug */ abort(); /* GCOV_NOT_REACHED */ } if (mpd_iszerocoeff(b)) { if (mpd_iszerocoeff(a)) { mpd_seterror(r, MPD_Division_undefined, status); } else { mpd_seterror(r, MPD_Invalid_operation, status); } return; } _mpd_qdivmod(&q, r, a, b, ctx, status); mpd_del(&q); mpd_qfinalize(r, ctx, status); } void mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; MPD_NEW_STATIC(btmp,0,0,0,0); MPD_NEW_STATIC(q,0,0,0,0); mpd_ssize_t expdiff, qdigits; int cmp, isodd, allnine; assert(r != NULL); /* annotation for scan-build */ if (mpd_isspecial(a) || mpd_isspecial(b)) { if (mpd_qcheck_nans(r, a, b, ctx, status)) { return; } if (mpd_isinfinite(a)) { mpd_seterror(r, MPD_Invalid_operation, status); return; } if (mpd_isinfinite(b)) { mpd_qcopy(r, a, status); mpd_qfinalize(r, ctx, status); return; } /* debug */ abort(); /* GCOV_NOT_REACHED */ } if (mpd_iszerocoeff(b)) { if (mpd_iszerocoeff(a)) { mpd_seterror(r, MPD_Division_undefined, status); } else { mpd_seterror(r, MPD_Invalid_operation, status); } return; } if (r == b) { if (!mpd_qcopy(&btmp, b, status)) { mpd_seterror(r, MPD_Malloc_error, status); return; } b = &btmp; } _mpd_qdivmod(&q, r, a, b, ctx, status); if (mpd_isnan(&q) || mpd_isnan(r)) { goto finish; } if (mpd_iszerocoeff(r)) { goto finish; } expdiff = mpd_adjexp(b) - mpd_adjexp(r); if (-1 <= expdiff && expdiff <= 1) { allnine = mpd_coeff_isallnine(&q); qdigits = q.digits; isodd = mpd_isodd(&q); mpd_maxcontext(&workctx); if (mpd_sign(a) == mpd_sign(b)) { /* sign(r) == sign(b) */ _mpd_qsub(&q, r, b, &workctx, &workctx.status); } else { /* sign(r) != sign(b) */ _mpd_qadd(&q, r, b, &workctx, &workctx.status); } if (workctx.status&MPD_Errors) { mpd_seterror(r, workctx.status&MPD_Errors, status); goto finish; } cmp = _mpd_cmp_abs(&q, r); if (cmp < 0 || (cmp == 0 && isodd)) { /* abs(r) > abs(b)/2 or abs(r) == abs(b)/2 and isodd(quotient) */ if (allnine && qdigits == ctx->prec) { /* abs(quotient) + 1 == 10**prec */ mpd_seterror(r, MPD_Division_impossible, status); goto finish; } mpd_qcopy(r, &q, status); } } finish: mpd_del(&btmp); mpd_del(&q); mpd_qfinalize(r, ctx, status); } static void _mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status) { mpd_ssize_t expdiff, shift; mpd_uint_t rnd; if (mpd_isspecial(a)) { mpd_qcopy(result, a, status); return; } if (mpd_iszero(a)) { _settriple(result, mpd_sign(a), 0, exp); return; } expdiff = a->exp - exp; if (expdiff >= 0) { shift = expdiff; if (a->digits + shift > MPD_MAX_PREC+1) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (!mpd_qshiftl(result, a, shift, status)) { return; } result->exp = exp; } else { shift = -expdiff; rnd = mpd_qshiftr(result, a, shift, status); if (rnd == MPD_UINT_MAX) { return; } result->exp = exp; _mpd_apply_round_excess(result, rnd, ctx, status); *status |= MPD_Rounded; if (rnd) { *status |= MPD_Inexact; } } if (mpd_issubnormal(result, ctx)) { *status |= MPD_Subnormal; } } /* * Rescale a number so that it has exponent 'exp'. Does not regard context * precision, emax, emin, but uses the rounding mode. Special numbers are * quietly copied. Restrictions: * * MPD_MIN_ETINY <= exp <= MPD_MAX_EMAX+1 * result->digits <= MPD_MAX_PREC+1 */ void mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status) { if (exp > MPD_MAX_EMAX+1 || exp < MPD_MIN_ETINY) { mpd_seterror(result, MPD_Invalid_operation, status); return; } _mpd_qrescale(result, a, exp, ctx, status); } /* * Same as mpd_qrescale, but with relaxed restrictions. The result of this * function should only be used for formatting a number and never as input * for other operations. * * MPD_MIN_ETINY-MPD_MAX_PREC <= exp <= MPD_MAX_EMAX+1 * result->digits <= MPD_MAX_PREC+1 */ void mpd_qrescale_fmt(mpd_t *result, const mpd_t *a, mpd_ssize_t exp, const mpd_context_t *ctx, uint32_t *status) { if (exp > MPD_MAX_EMAX+1 || exp < MPD_MIN_ETINY-MPD_MAX_PREC) { mpd_seterror(result, MPD_Invalid_operation, status); return; } _mpd_qrescale(result, a, exp, ctx, status); } /* Round to an integer according to 'action' and ctx->round. */ enum {TO_INT_EXACT, TO_INT_SILENT, TO_INT_TRUNC}; static void _mpd_qround_to_integral(int action, mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_uint_t rnd; if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } mpd_qcopy(result, a, status); return; } if (a->exp >= 0) { mpd_qcopy(result, a, status); return; } if (mpd_iszerocoeff(a)) { _settriple(result, mpd_sign(a), 0, 0); return; } rnd = mpd_qshiftr(result, a, -a->exp, status); if (rnd == MPD_UINT_MAX) { return; } result->exp = 0; if (action == TO_INT_EXACT || action == TO_INT_SILENT) { _mpd_apply_round_excess(result, rnd, ctx, status); if (action == TO_INT_EXACT) { *status |= MPD_Rounded; if (rnd) { *status |= MPD_Inexact; } } } } void mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { (void)_mpd_qround_to_integral(TO_INT_EXACT, result, a, ctx, status); } void mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { (void)_mpd_qround_to_integral(TO_INT_SILENT, result, a, ctx, status); } void mpd_qtrunc(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { if (mpd_isspecial(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } (void)_mpd_qround_to_integral(TO_INT_TRUNC, result, a, ctx, status); } void mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx = *ctx; if (mpd_isspecial(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } workctx.round = MPD_ROUND_FLOOR; (void)_mpd_qround_to_integral(TO_INT_SILENT, result, a, &workctx, status); } void mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx = *ctx; if (mpd_isspecial(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } workctx.round = MPD_ROUND_CEILING; (void)_mpd_qround_to_integral(TO_INT_SILENT, result, a, &workctx, status); } int mpd_same_quantum(const mpd_t *a, const mpd_t *b) { if (mpd_isspecial(a) || mpd_isspecial(b)) { return ((mpd_isnan(a) && mpd_isnan(b)) || (mpd_isinfinite(a) && mpd_isinfinite(b))); } return a->exp == b->exp; } /* Schedule the increase in precision for the Newton iteration. */ static inline int recpr_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec, mpd_ssize_t initprec) { mpd_ssize_t k; int i; assert(maxprec > 0 && initprec > 0); if (maxprec <= initprec) return -1; i = 0; k = maxprec; do { k = (k+1) / 2; klist[i++] = k; } while (k > initprec); return i-1; } /* * Initial approximation for the reciprocal: * k_0 := MPD_RDIGITS-2 * z_0 := 10**(-k_0) * floor(10**(2*k_0 + 2) / floor(v * 10**(k_0 + 2))) * Absolute error: * |1/v - z_0| < 10**(-k_0) * ACL2 proof: maxerror-inverse-approx */ static void _mpd_qreciprocal_approx(mpd_t *z, const mpd_t *v, uint32_t *status) { mpd_uint_t p10data[2] = {0, mpd_pow10[MPD_RDIGITS-2]}; mpd_uint_t dummy, word; int n; assert(v->exp == -v->digits); _mpd_get_msdigits(&dummy, &word, v, MPD_RDIGITS); n = mpd_word_digits(word); word *= mpd_pow10[MPD_RDIGITS-n]; mpd_qresize(z, 2, status); (void)_mpd_shortdiv(z->data, p10data, 2, word); mpd_clear_flags(z); z->exp = -(MPD_RDIGITS-2); z->len = (z->data[1] == 0) ? 1 : 2; mpd_setdigits(z); } /* * Reciprocal, calculated with Newton's Method. Assumption: result != a. * NOTE: The comments in the function show that certain operations are * exact. The proof for the maximum error is too long to fit in here. * ACL2 proof: maxerror-inverse-complete */ static void _mpd_qreciprocal(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t varcontext, maxcontext; mpd_t *z = result; /* current approximation */ mpd_t *v; /* a, normalized to a number between 0.1 and 1 */ MPD_NEW_SHARED(vtmp, a); /* v shares data with a */ MPD_NEW_STATIC(s,0,0,0,0); /* temporary variable */ MPD_NEW_STATIC(t,0,0,0,0); /* temporary variable */ MPD_NEW_CONST(two,0,0,1,1,1,2); /* const 2 */ mpd_ssize_t klist[MPD_MAX_PREC_LOG2]; mpd_ssize_t adj, maxprec, initprec; uint8_t sign = mpd_sign(a); int i; assert(result != a); v = &vtmp; mpd_clear_flags(v); adj = v->digits + v->exp; v->exp = -v->digits; /* Initial approximation */ _mpd_qreciprocal_approx(z, v, status); mpd_maxcontext(&varcontext); mpd_maxcontext(&maxcontext); varcontext.round = maxcontext.round = MPD_ROUND_TRUNC; varcontext.emax = maxcontext.emax = MPD_MAX_EMAX + 100; varcontext.emin = maxcontext.emin = MPD_MIN_EMIN - 100; maxcontext.prec = MPD_MAX_PREC + 100; maxprec = ctx->prec; maxprec += 2; initprec = MPD_RDIGITS-3; i = recpr_schedule_prec(klist, maxprec, initprec); for (; i >= 0; i--) { /* Loop invariant: z->digits <= klist[i]+7 */ /* Let s := z**2, exact result */ _mpd_qmul_exact(&s, z, z, &maxcontext, status); varcontext.prec = 2*klist[i] + 5; if (v->digits > varcontext.prec) { /* Let t := v, truncated to n >= 2*k+5 fraction digits */ mpd_qshiftr(&t, v, v->digits-varcontext.prec, status); t.exp = -varcontext.prec; /* Let t := trunc(v)*s, truncated to n >= 2*k+1 fraction digits */ mpd_qmul(&t, &t, &s, &varcontext, status); } else { /* v->digits <= 2*k+5 */ /* Let t := v*s, truncated to n >= 2*k+1 fraction digits */ mpd_qmul(&t, v, &s, &varcontext, status); } /* Let s := 2*z, exact result */ _mpd_qmul_exact(&s, z, &two, &maxcontext, status); /* s.digits < t.digits <= 2*k+5, |adjexp(s)-adjexp(t)| <= 1, * so the subtraction generates at most 2*k+6 <= klist[i+1]+7 * digits. The loop invariant is preserved. */ _mpd_qsub_exact(z, &s, &t, &maxcontext, status); } if (!mpd_isspecial(z)) { z->exp -= adj; mpd_set_flags(z, sign); } mpd_del(&s); mpd_del(&t); mpd_qfinalize(z, ctx, status); } /* * Internal function for large numbers: * * q, r = divmod(coeff(a), coeff(b)) * * Strategy: Multiply the dividend by the reciprocal of the divisor. The * inexact result is fixed by a small loop, using at most one iteration. * * ACL2 proofs: * ------------ * 1) q is a natural number. (ndivmod-quotient-natp) * 2) r is a natural number. (ndivmod-remainder-natp) * 3) a = q * b + r (ndivmod-q*b+r==a) * 4) r < b (ndivmod-remainder-<-b) */ static void _mpd_base_ndivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b, uint32_t *status) { mpd_context_t workctx; mpd_t *qq = q, *rr = r; mpd_t aa, bb; int k; _mpd_copy_shared(&aa, a); _mpd_copy_shared(&bb, b); mpd_set_positive(&aa); mpd_set_positive(&bb); aa.exp = 0; bb.exp = 0; if (q == a || q == b) { if ((qq = mpd_qnew()) == NULL) { *status |= MPD_Malloc_error; goto nanresult; } } if (r == a || r == b) { if ((rr = mpd_qnew()) == NULL) { *status |= MPD_Malloc_error; goto nanresult; } } mpd_maxcontext(&workctx); /* Let prec := adigits - bdigits + 4 */ workctx.prec = a->digits - b->digits + 1 + 3; if (a->digits > MPD_MAX_PREC || workctx.prec > MPD_MAX_PREC) { *status |= MPD_Division_impossible; goto nanresult; } /* Let x := _mpd_qreciprocal(b, prec) * Then x is bounded by: * 1) 1/b - 10**(-prec - bdigits) < x < 1/b + 10**(-prec - bdigits) * 2) 1/b - 10**(-adigits - 4) < x < 1/b + 10**(-adigits - 4) */ _mpd_qreciprocal(rr, &bb, &workctx, &workctx.status); /* Get an estimate for the quotient. Let q := a * x * Then q is bounded by: * 3) a/b - 10**-4 < q < a/b + 10**-4 */ _mpd_qmul(qq, &aa, rr, &workctx, &workctx.status); /* Truncate q to an integer: * 4) a/b - 2 < trunc(q) < a/b + 1 */ mpd_qtrunc(qq, qq, &workctx, &workctx.status); workctx.prec = aa.digits + 3; workctx.emax = MPD_MAX_EMAX + 3; workctx.emin = MPD_MIN_EMIN - 3; /* Multiply the estimate for q by b: * 5) a - 2 * b < trunc(q) * b < a + b */ _mpd_qmul(rr, &bb, qq, &workctx, &workctx.status); /* Get the estimate for r such that a = q * b + r. */ _mpd_qsub_exact(rr, &aa, rr, &workctx, &workctx.status); /* Fix the result. At this point -b < r < 2*b, so the correction loop takes at most one iteration. */ for (k = 0;; k++) { if (mpd_isspecial(qq) || mpd_isspecial(rr)) { *status |= (workctx.status&MPD_Errors); goto nanresult; } if (k > 2) { /* Allow two iterations despite the proof. */ mpd_err_warn("libmpdec: internal error in " /* GCOV_NOT_REACHED */ "_mpd_base_ndivmod: please report"); /* GCOV_NOT_REACHED */ *status |= MPD_Invalid_operation; /* GCOV_NOT_REACHED */ goto nanresult; /* GCOV_NOT_REACHED */ } /* r < 0 */ else if (_mpd_cmp(&zero, rr) == 1) { _mpd_qadd_exact(rr, rr, &bb, &workctx, &workctx.status); _mpd_qadd_exact(qq, qq, &minus_one, &workctx, &workctx.status); } /* 0 <= r < b */ else if (_mpd_cmp(rr, &bb) == -1) { break; } /* r >= b */ else { _mpd_qsub_exact(rr, rr, &bb, &workctx, &workctx.status); _mpd_qadd_exact(qq, qq, &one, &workctx, &workctx.status); } } if (qq != q) { if (!mpd_qcopy(q, qq, status)) { goto nanresult; /* GCOV_UNLIKELY */ } mpd_del(qq); } if (rr != r) { if (!mpd_qcopy(r, rr, status)) { goto nanresult; /* GCOV_UNLIKELY */ } mpd_del(rr); } *status |= (workctx.status&MPD_Errors); return; nanresult: if (qq && qq != q) mpd_del(qq); if (rr && rr != r) mpd_del(rr); mpd_setspecial(q, MPD_POS, MPD_NAN); mpd_setspecial(r, MPD_POS, MPD_NAN); } /* LIBMPDEC_ONLY */ /* * Schedule the optimal precision increase for the Newton iteration. * v := input operand * z_0 := initial approximation * initprec := natural number such that abs(sqrt(v) - z_0) < 10**-initprec * maxprec := target precision * * For convenience the output klist contains the elements in reverse order: * klist := [k_n-1, ..., k_0], where * 1) k_0 <= initprec and * 2) abs(sqrt(v) - result) < 10**(-2*k_n-1 + 2) <= 10**-maxprec. */ static inline int invroot_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec, mpd_ssize_t initprec) { mpd_ssize_t k; int i; assert(maxprec >= 3 && initprec >= 3); if (maxprec <= initprec) return -1; i = 0; k = maxprec; do { k = (k+3) / 2; klist[i++] = k; } while (k > initprec); return i-1; } /* * Initial approximation for the inverse square root function. * Input: * v := rational number, with 1 <= v < 100 * vhat := floor(v * 10**6) * Output: * z := approximation to 1/sqrt(v), such that abs(z - 1/sqrt(v)) < 10**-3. */ static inline void _invroot_init_approx(mpd_t *z, mpd_uint_t vhat) { mpd_uint_t lo = 1000; mpd_uint_t hi = 10000; mpd_uint_t a, sq; assert(lo*lo <= vhat && vhat < (hi+1)*(hi+1)); for(;;) { a = (lo + hi) / 2; sq = a * a; if (vhat >= sq) { if (vhat < sq + 2*a + 1) { break; } lo = a + 1; } else { hi = a - 1; } } /* * After the binary search we have: * 1) a**2 <= floor(v * 10**6) < (a + 1)**2 * This implies: * 2) a**2 <= v * 10**6 < (a + 1)**2 * 3) a <= sqrt(v) * 10**3 < a + 1 * Since 10**3 <= a: * 4) 0 <= 10**prec/a - 1/sqrt(v) < 10**-prec * We have: * 5) 10**3/a - 10**-3 < floor(10**9/a) * 10**-6 <= 10**3/a * Merging 4) and 5): * 6) abs(floor(10**9/a) * 10**-6 - 1/sqrt(v)) < 10**-3 */ mpd_minalloc(z); mpd_clear_flags(z); z->data[0] = 1000000000UL / a; z->len = 1; z->exp = -6; mpd_setdigits(z); } /* * Set 'result' to 1/sqrt(a). * Relative error: abs(result - 1/sqrt(a)) < 10**-prec * 1/sqrt(a) */ static void _mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { uint32_t workstatus = 0; mpd_context_t varcontext, maxcontext; mpd_t *z = result; /* current approximation */ mpd_t *v; /* a, normalized to a number between 1 and 100 */ MPD_NEW_SHARED(vtmp, a); /* by default v will share data with a */ MPD_NEW_STATIC(s,0,0,0,0); /* temporary variable */ MPD_NEW_STATIC(t,0,0,0,0); /* temporary variable */ MPD_NEW_CONST(one_half,0,-1,1,1,1,5); MPD_NEW_CONST(three,0,0,1,1,1,3); mpd_ssize_t klist[MPD_MAX_PREC_LOG2]; mpd_ssize_t ideal_exp, shift; mpd_ssize_t adj, tz; mpd_ssize_t maxprec, fracdigits; mpd_uint_t vhat, dummy; int i, n; ideal_exp = -(a->exp - (a->exp & 1)) / 2; v = &vtmp; if (result == a) { if ((v = mpd_qncopy(a)) == NULL) { mpd_seterror(result, MPD_Malloc_error, status); return; } } /* normalize a to 1 <= v < 100 */ if ((v->digits+v->exp) & 1) { fracdigits = v->digits - 1; v->exp = -fracdigits; n = (v->digits > 7) ? 7 : (int)v->digits; /* Let vhat := floor(v * 10**(2*initprec)) */ _mpd_get_msdigits(&dummy, &vhat, v, n); if (n < 7) { vhat *= mpd_pow10[7-n]; } } else { fracdigits = v->digits - 2; v->exp = -fracdigits; n = (v->digits > 8) ? 8 : (int)v->digits; /* Let vhat := floor(v * 10**(2*initprec)) */ _mpd_get_msdigits(&dummy, &vhat, v, n); if (n < 8) { vhat *= mpd_pow10[8-n]; } } adj = (a->exp-v->exp) / 2; /* initial approximation */ _invroot_init_approx(z, vhat); mpd_maxcontext(&maxcontext); mpd_maxcontext(&varcontext); varcontext.round = MPD_ROUND_TRUNC; maxprec = ctx->prec + 1; /* initprec == 3 */ i = invroot_schedule_prec(klist, maxprec, 3); for (; i >= 0; i--) { varcontext.prec = 2*klist[i]+2; mpd_qmul(&s, z, z, &maxcontext, &workstatus); if (v->digits > varcontext.prec) { shift = v->digits - varcontext.prec; mpd_qshiftr(&t, v, shift, &workstatus); t.exp += shift; mpd_qmul(&t, &t, &s, &varcontext, &workstatus); } else { mpd_qmul(&t, v, &s, &varcontext, &workstatus); } mpd_qsub(&t, &three, &t, &maxcontext, &workstatus); mpd_qmul(z, z, &t, &varcontext, &workstatus); mpd_qmul(z, z, &one_half, &maxcontext, &workstatus); } z->exp -= adj; tz = mpd_trail_zeros(result); shift = ideal_exp - result->exp; shift = (tz > shift) ? shift : tz; if (shift > 0) { mpd_qshiftr_inplace(result, shift); result->exp += shift; } mpd_del(&s); mpd_del(&t); if (v != &vtmp) mpd_del(v); *status |= (workstatus&MPD_Errors); *status |= (MPD_Rounded|MPD_Inexact); } void mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t workctx; if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } /* positive infinity */ _settriple(result, MPD_POS, 0, mpd_etiny(ctx)); *status |= MPD_Clamped; return; } if (mpd_iszero(a)) { mpd_setspecial(result, mpd_sign(a), MPD_INF); *status |= MPD_Division_by_zero; return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } workctx = *ctx; workctx.prec += 2; workctx.round = MPD_ROUND_HALF_EVEN; _mpd_qinvroot(result, a, &workctx, status); mpd_qfinalize(result, ctx, status); } /* END LIBMPDEC_ONLY */ /* Algorithm from decimal.py */ static void _mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { mpd_context_t maxcontext; MPD_NEW_STATIC(c,0,0,0,0); MPD_NEW_STATIC(q,0,0,0,0); MPD_NEW_STATIC(r,0,0,0,0); MPD_NEW_CONST(two,0,0,1,1,1,2); mpd_ssize_t prec, ideal_exp; mpd_ssize_t l, shift; int exact = 0; ideal_exp = (a->exp - (a->exp & 1)) / 2; if (mpd_isspecial(a)) { if (mpd_qcheck_nan(result, a, ctx, status)) { return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } mpd_setspecial(result, MPD_POS, MPD_INF); return; } if (mpd_iszero(a)) { _settriple(result, mpd_sign(a), 0, ideal_exp); mpd_qfinalize(result, ctx, status); return; } if (mpd_isnegative(a)) { mpd_seterror(result, MPD_Invalid_operation, status); return; } mpd_maxcontext(&maxcontext); prec = ctx->prec + 1; if (!mpd_qcopy(&c, a, status)) { goto malloc_error; } c.exp = 0; if (a->exp & 1) { if (!mpd_qshiftl(&c, &c, 1, status)) { goto malloc_error; } l = (a->digits >> 1) + 1; } else { l = (a->digits + 1) >> 1; } shift = prec - l; if (shift >= 0) { if (!mpd_qshiftl(&c, &c, 2*shift, status)) { goto malloc_error; } exact = 1; } else { exact = !mpd_qshiftr_inplace(&c, -2*shift); } ideal_exp -= shift; /* find result = floor(sqrt(c)) using Newton's method */ if (!mpd_qshiftl(result, &one, prec, status)) { goto malloc_error; } while (1) { _mpd_qdivmod(&q, &r, &c, result, &maxcontext, &maxcontext.status); if (mpd_isspecial(result) || mpd_isspecial(&q)) { mpd_seterror(result, maxcontext.status&MPD_Errors, status); goto out; } if (_mpd_cmp(result, &q) <= 0) { break; } _mpd_qadd_exact(result, result, &q, &maxcontext, &maxcontext.status); if (mpd_isspecial(result)) { mpd_seterror(result, maxcontext.status&MPD_Errors, status); goto out; } _mpd_qdivmod(result, &r, result, &two, &maxcontext, &maxcontext.status); } if (exact) { _mpd_qmul_exact(&r, result, result, &maxcontext, &maxcontext.status); if (mpd_isspecial(&r)) { mpd_seterror(result, maxcontext.status&MPD_Errors, status); goto out; } exact = (_mpd_cmp(&r, &c) == 0); } if (exact) { if (shift >= 0) { mpd_qshiftr_inplace(result, shift); } else { if (!mpd_qshiftl(result, result, -shift, status)) { goto malloc_error; } } ideal_exp += shift; } else { int lsd = (int)mpd_lsd(result->data[0]); if (lsd == 0 || lsd == 5) { result->data[0] += 1; } } result->exp = ideal_exp; out: mpd_del(&c); mpd_del(&q); mpd_del(&r); maxcontext = *ctx; maxcontext.round = MPD_ROUND_HALF_EVEN; mpd_qfinalize(result, &maxcontext, status); return; malloc_error: mpd_seterror(result, MPD_Malloc_error, status); goto out; } void mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx, uint32_t *status) { MPD_NEW_STATIC(aa,0,0,0,0); uint32_t xstatus = 0; if (result == a) { if (!mpd_qcopy(&aa, a, status)) { mpd_seterror(result, MPD_Malloc_error, status); goto out; } a = &aa; } _mpd_qsqrt(result, a, ctx, &xstatus); if (xstatus & (MPD_Malloc_error|MPD_Division_impossible)) { /* The above conditions can occur at very high context precisions * if intermediate values get too large. Retry the operation with * a lower context precision in case the result is exact. * * If the result is exact, an upper bound for the number of digits * is the number of digits in the input. * * NOTE: sqrt(40e9) = 2.0e+5 /\ digits(40e9) = digits(2.0e+5) = 2 */ uint32_t ystatus = 0; mpd_context_t workctx = *ctx; workctx.prec = a->digits; if (workctx.prec >= ctx->prec) { *status |= (xstatus|MPD_Errors); goto out; /* No point in repeating this, keep the original error. */ } _mpd_qsqrt(result, a, &workctx, &ystatus); if (ystatus != 0) { ystatus = *status | ((xstatus|ystatus)&MPD_Errors); mpd_seterror(result, ystatus, status); } } else { *status |= xstatus; } out: mpd_del(&aa); } /******************************************************************************/ /* Base conversions */ /******************************************************************************/ /* Space needed to represent an integer mpd_t in base 'base'. */ size_t mpd_sizeinbase(const mpd_t *a, uint32_t base) { double x; size_t digits; double upper_bound; assert(mpd_isinteger(a)); assert(base >= 2); if (mpd_iszero(a)) { return 1; } digits = a->digits+a->exp; #ifdef CONFIG_64 /* ceil(2711437152599294 / log10(2)) + 4 == 2**53 */ if (digits > 2711437152599294ULL) { return SIZE_MAX; } upper_bound = (double)((1ULL<<53)-1); #else upper_bound = (double)(SIZE_MAX-1); #endif x = (double)digits / log10(base); return (x > upper_bound) ? SIZE_MAX : (size_t)x + 1; } /* Space needed to import a base 'base' integer of length 'srclen'. */ static mpd_ssize_t _mpd_importsize(size_t srclen, uint32_t base) { double x; double upper_bound; assert(srclen > 0); assert(base >= 2); #if SIZE_MAX == UINT64_MAX if (srclen > (1ULL<<53)) { return MPD_SSIZE_MAX; } assert((1ULL<<53) <= MPD_MAXIMPORT); upper_bound = (double)((1ULL<<53)-1); #else upper_bound = MPD_MAXIMPORT-1; #endif x = (double)srclen * (log10(base)/MPD_RDIGITS); return (x > upper_bound) ? MPD_SSIZE_MAX : (mpd_ssize_t)x + 1; } static uint8_t mpd_resize_u16(uint16_t **w, size_t nmemb) { uint8_t err = 0; *w = mpd_realloc(*w, nmemb, sizeof **w, &err); return !err; } static uint8_t mpd_resize_u32(uint32_t **w, size_t nmemb) { uint8_t err = 0; *w = mpd_realloc(*w, nmemb, sizeof **w, &err); return !err; } static size_t _baseconv_to_u16(uint16_t **w, size_t wlen, mpd_uint_t wbase, mpd_uint_t *u, mpd_ssize_t ulen) { size_t n = 0; assert(wlen > 0 && ulen > 0); assert(wbase <= (1U<<16)); do { if (n >= wlen) { if (!mpd_resize_u16(w, n+1)) { return SIZE_MAX; } wlen = n+1; } (*w)[n++] = (uint16_t)_mpd_shortdiv(u, u, ulen, wbase); /* ulen is at least 1. u[ulen-1] can only be zero if ulen == 1. */ ulen = _mpd_real_size(u, ulen); } while (u[ulen-1] != 0); return n; } static size_t _coeff_from_u16(mpd_t *w, mpd_ssize_t wlen, const mpd_uint_t *u, size_t ulen, uint32_t ubase, uint32_t *status) { mpd_ssize_t n = 0; mpd_uint_t carry; assert(wlen > 0 && ulen > 0); assert(ubase <= (1U<<16)); w->data[n++] = u[--ulen]; while (--ulen != SIZE_MAX) { carry = _mpd_shortmul_c(w->data, w->data, n, ubase); if (carry) { if (n >= wlen) { if (!mpd_qresize(w, n+1, status)) { return SIZE_MAX; } wlen = n+1; } w->data[n++] = carry; } carry = _mpd_shortadd(w->data, n, u[ulen]); if (carry) { if (n >= wlen) { if (!mpd_qresize(w, n+1, status)) { return SIZE_MAX; } wlen = n+1; } w->data[n++] = carry; } } return n; } /* target base wbase < source base ubase */ static size_t _baseconv_to_smaller(uint32_t **w, size_t wlen, uint32_t wbase, mpd_uint_t *u, mpd_ssize_t ulen, mpd_uint_t ubase) { size_t n = 0; assert(wlen > 0 && ulen > 0); assert(wbase < ubase); do { if (n >= wlen) { if (!mpd_resize_u32(w, n+1)) { return SIZE_MAX; } wlen = n+1; } (*w)[n++] = (uint32_t)_mpd_shortdiv_b(u, u, ulen, wbase, ubase); /* ulen is at least 1. u[ulen-1] can only be zero if ulen == 1. */ ulen = _mpd_real_size(u, ulen); } while (u[ulen-1] != 0); return n; } #ifdef CONFIG_32 /* target base 'wbase' == source base 'ubase' */ static size_t _copy_equal_base(uint32_t **w, size_t wlen, const uint32_t *u, size_t ulen) { if (wlen < ulen) { if (!mpd_resize_u32(w, ulen)) { return SIZE_MAX; } } memcpy(*w, u, ulen * (sizeof **w)); return ulen; } /* target base 'wbase' > source base 'ubase' */ static size_t _baseconv_to_larger(uint32_t **w, size_t wlen, mpd_uint_t wbase, const mpd_uint_t *u, size_t ulen, mpd_uint_t ubase) { size_t n = 0; mpd_uint_t carry; assert(wlen > 0 && ulen > 0); assert(ubase < wbase); (*w)[n++] = u[--ulen]; while (--ulen != SIZE_MAX) { carry = _mpd_shortmul_b(*w, *w, n, ubase, wbase); if (carry) { if (n >= wlen) { if (!mpd_resize_u32(w, n+1)) { return SIZE_MAX; } wlen = n+1; } (*w)[n++] = carry; } carry = _mpd_shortadd_b(*w, n, u[ulen], wbase); if (carry) { if (n >= wlen) { if (!mpd_resize_u32(w, n+1)) { return SIZE_MAX; } wlen = n+1; } (*w)[n++] = carry; } } return n; } /* target base wbase < source base ubase */ static size_t _coeff_from_larger_base(mpd_t *w, size_t wlen, mpd_uint_t wbase, mpd_uint_t *u, mpd_ssize_t ulen, mpd_uint_t ubase, uint32_t *status) { size_t n = 0; assert(wlen > 0 && ulen > 0); assert(wbase < ubase); do { if (n >= wlen) { if (!mpd_qresize(w, n+1, status)) { return SIZE_MAX; } wlen = n+1; } w->data[n++] = (uint32_t)_mpd_shortdiv_b(u, u, ulen, wbase, ubase); /* ulen is at least 1. u[ulen-1] can only be zero if ulen == 1. */ ulen = _mpd_real_size(u, ulen); } while (u[ulen-1] != 0); return n; } #endif /* target base 'wbase' > source base 'ubase' */ static size_t _coeff_from_smaller_base(mpd_t *w, mpd_ssize_t wlen, mpd_uint_t wbase, const uint32_t *u, size_t ulen, mpd_uint_t ubase, uint32_t *status) { mpd_ssize_t n = 0; mpd_uint_t carry; assert(wlen > 0 && ulen > 0); assert(wbase > ubase); w->data[n++] = u[--ulen]; while (--ulen != SIZE_MAX) { carry = _mpd_shortmul_b(w->data, w->data, n, ubase, wbase); if (carry) { if (n >= wlen) { if (!mpd_qresize(w, n+1, status)) { return SIZE_MAX; } wlen = n+1; } w->data[n++] = carry; } carry = _mpd_shortadd_b(w->data, n, u[ulen], wbase); if (carry) { if (n >= wlen) { if (!mpd_qresize(w, n+1, status)) { return SIZE_MAX; } wlen = n+1; } w->data[n++] = carry; } } return n; } /* * Convert an integer mpd_t to a multiprecision integer with base <= 2**16. * The least significant word of the result is (*rdata)[0]. * * If rdata is NULL, space is allocated by the function and rlen is irrelevant. * In case of an error any allocated storage is freed and rdata is set back to * NULL. * * If rdata is non-NULL, it MUST be allocated by one of libmpdec's allocation * functions and rlen MUST be correct. If necessary, the function will resize * rdata. In case of an error the caller must free rdata. * * Return value: In case of success, the exact length of rdata, SIZE_MAX * otherwise. */ size_t mpd_qexport_u16(uint16_t **rdata, size_t rlen, uint32_t rbase, const mpd_t *src, uint32_t *status) { MPD_NEW_STATIC(tsrc,0,0,0,0); int alloc = 0; /* rdata == NULL */ size_t n; assert(rbase <= (1U<<16)); if (mpd_isspecial(src) || !_mpd_isint(src)) { *status |= MPD_Invalid_operation; return SIZE_MAX; } if (*rdata == NULL) { rlen = mpd_sizeinbase(src, rbase); if (rlen == SIZE_MAX) { *status |= MPD_Invalid_operation; return SIZE_MAX; } *rdata = mpd_alloc(rlen, sizeof **rdata); if (*rdata == NULL) { goto malloc_error; } alloc = 1; } if (mpd_iszero(src)) { **rdata = 0; return 1; } if (src->exp >= 0) { if (!mpd_qshiftl(&tsrc, src, src->exp, status)) { goto malloc_error; } } else { if (mpd_qshiftr(&tsrc, src, -src->exp, status) == MPD_UINT_MAX) { goto malloc_error; } } n = _baseconv_to_u16(rdata, rlen, rbase, tsrc.data, tsrc.len); if (n == SIZE_MAX) { goto malloc_error; } out: mpd_del(&tsrc); return n; malloc_error: if (alloc) { mpd_free(*rdata); *rdata = NULL; } n = SIZE_MAX; *status |= MPD_Malloc_error; goto out; } /* * Convert an integer mpd_t to a multiprecision integer with base<=UINT32_MAX. * The least significant word of the result is (*rdata)[0]. * * If rdata is NULL, space is allocated by the function and rlen is irrelevant. * In case of an error any allocated storage is freed and rdata is set back to * NULL. * * If rdata is non-NULL, it MUST be allocated by one of libmpdec's allocation * functions and rlen MUST be correct. If necessary, the function will resize * rdata. In case of an error the caller must free rdata. * * Return value: In case of success, the exact length of rdata, SIZE_MAX * otherwise. */ size_t mpd_qexport_u32(uint32_t **rdata, size_t rlen, uint32_t rbase, const mpd_t *src, uint32_t *status) { MPD_NEW_STATIC(tsrc,0,0,0,0); int alloc = 0; /* rdata == NULL */ size_t n; if (mpd_isspecial(src) || !_mpd_isint(src)) { *status |= MPD_Invalid_operation; return SIZE_MAX; } if (*rdata == NULL) { rlen = mpd_sizeinbase(src, rbase); if (rlen == SIZE_MAX) { *status |= MPD_Invalid_operation; return SIZE_MAX; } *rdata = mpd_alloc(rlen, sizeof **rdata); if (*rdata == NULL) { goto malloc_error; } alloc = 1; } if (mpd_iszero(src)) { **rdata = 0; return 1; } if (src->exp >= 0) { if (!mpd_qshiftl(&tsrc, src, src->exp, status)) { goto malloc_error; } } else { if (mpd_qshiftr(&tsrc, src, -src->exp, status) == MPD_UINT_MAX) { goto malloc_error; } } #ifdef CONFIG_64 n = _baseconv_to_smaller(rdata, rlen, rbase, tsrc.data, tsrc.len, MPD_RADIX); #else if (rbase == MPD_RADIX) { n = _copy_equal_base(rdata, rlen, tsrc.data, tsrc.len); } else if (rbase < MPD_RADIX) { n = _baseconv_to_smaller(rdata, rlen, rbase, tsrc.data, tsrc.len, MPD_RADIX); } else { n = _baseconv_to_larger(rdata, rlen, rbase, tsrc.data, tsrc.len, MPD_RADIX); } #endif if (n == SIZE_MAX) { goto malloc_error; } out: mpd_del(&tsrc); return n; malloc_error: if (alloc) { mpd_free(*rdata); *rdata = NULL; } n = SIZE_MAX; *status |= MPD_Malloc_error; goto out; } /* * Converts a multiprecision integer with base <= UINT16_MAX+1 to an mpd_t. * The least significant word of the source is srcdata[0]. */ void mpd_qimport_u16(mpd_t *result, const uint16_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t srcbase, const mpd_context_t *ctx, uint32_t *status) { mpd_uint_t *usrc; /* uint16_t src copied to an mpd_uint_t array */ mpd_ssize_t rlen; /* length of the result */ size_t n; assert(srclen > 0); assert(srcbase <= (1U<<16)); rlen = _mpd_importsize(srclen, srcbase); if (rlen == MPD_SSIZE_MAX) { mpd_seterror(result, MPD_Invalid_operation, status); return; } usrc = mpd_alloc((mpd_size_t)srclen, sizeof *usrc); if (usrc == NULL) { mpd_seterror(result, MPD_Malloc_error, status); return; } for (n = 0; n < srclen; n++) { usrc[n] = srcdata[n]; } if (!mpd_qresize(result, rlen, status)) { goto finish; } n = _coeff_from_u16(result, rlen, usrc, srclen, srcbase, status); if (n == SIZE_MAX) { goto finish; } mpd_set_flags(result, srcsign); result->exp = 0; result->len = n; mpd_setdigits(result); mpd_qresize(result, result->len, status); mpd_qfinalize(result, ctx, status); finish: mpd_free(usrc); } /* * Converts a multiprecision integer with base <= UINT32_MAX to an mpd_t. * The least significant word of the source is srcdata[0]. */ void mpd_qimport_u32(mpd_t *result, const uint32_t *srcdata, size_t srclen, uint8_t srcsign, uint32_t srcbase, const mpd_context_t *ctx, uint32_t *status) { mpd_ssize_t rlen; /* length of the result */ size_t n; assert(srclen > 0); rlen = _mpd_importsize(srclen, srcbase); if (rlen == MPD_SSIZE_MAX) { mpd_seterror(result, MPD_Invalid_operation, status); return; } if (!mpd_qresize(result, rlen, status)) { return; } #ifdef CONFIG_64 n = _coeff_from_smaller_base(result, rlen, MPD_RADIX, srcdata, srclen, srcbase, status); #else if (srcbase == MPD_RADIX) { if (!mpd_qresize(result, srclen, status)) { return; } memcpy(result->data, srcdata, srclen * (sizeof *srcdata)); n = srclen; } else if (srcbase < MPD_RADIX) { n = _coeff_from_smaller_base(result, rlen, MPD_RADIX, srcdata, srclen, srcbase, status); } else { mpd_uint_t *usrc = mpd_alloc((mpd_size_t)srclen, sizeof *usrc); if (usrc == NULL) { mpd_seterror(result, MPD_Malloc_error, status); return; } for (n = 0; n < srclen; n++) { usrc[n] = srcdata[n]; } n = _coeff_from_larger_base(result, rlen, MPD_RADIX, usrc, (mpd_ssize_t)srclen, srcbase, status); mpd_free(usrc); } #endif if (n == SIZE_MAX) { return; } mpd_set_flags(result, srcsign); result->exp = 0; result->len = n; mpd_setdigits(result); mpd_qresize(result, result->len, status); mpd_qfinalize(result, ctx, status); } /******************************************************************************/ /* From triple */ /******************************************************************************/ #if defined(CONFIG_64) && defined(__SIZEOF_INT128__) static mpd_ssize_t _set_coeff(uint64_t data[3], uint64_t hi, uint64_t lo) { __uint128_t d = ((__uint128_t)hi << 64) + lo; __uint128_t q, r; q = d / MPD_RADIX; r = d % MPD_RADIX; data[0] = (uint64_t)r; d = q; q = d / MPD_RADIX; r = d % MPD_RADIX; data[1] = (uint64_t)r; d = q; q = d / MPD_RADIX; r = d % MPD_RADIX; data[2] = (uint64_t)r; if (q != 0) { abort(); /* GCOV_NOT_REACHED */ } return data[2] != 0 ? 3 : (data[1] != 0 ? 2 : 1); } #else static size_t _uint_from_u16(mpd_uint_t *w, mpd_ssize_t wlen, const uint16_t *u, size_t ulen) { const mpd_uint_t ubase = 1U<<16; mpd_ssize_t n = 0; mpd_uint_t carry; assert(wlen > 0 && ulen > 0); w[n++] = u[--ulen]; while (--ulen != SIZE_MAX) { carry = _mpd_shortmul_c(w, w, n, ubase); if (carry) { if (n >= wlen) { abort(); /* GCOV_NOT_REACHED */ } w[n++] = carry; } carry = _mpd_shortadd(w, n, u[ulen]); if (carry) { if (n >= wlen) { abort(); /* GCOV_NOT_REACHED */ } w[n++] = carry; } } return n; } static mpd_ssize_t _set_coeff(mpd_uint_t *data, mpd_ssize_t len, uint64_t hi, uint64_t lo) { uint16_t u16[8] = {0}; u16[7] = (uint16_t)((hi & 0xFFFF000000000000ULL) >> 48); u16[6] = (uint16_t)((hi & 0x0000FFFF00000000ULL) >> 32); u16[5] = (uint16_t)((hi & 0x00000000FFFF0000ULL) >> 16); u16[4] = (uint16_t) (hi & 0x000000000000FFFFULL); u16[3] = (uint16_t)((lo & 0xFFFF000000000000ULL) >> 48); u16[2] = (uint16_t)((lo & 0x0000FFFF00000000ULL) >> 32); u16[1] = (uint16_t)((lo & 0x00000000FFFF0000ULL) >> 16); u16[0] = (uint16_t) (lo & 0x000000000000FFFFULL); return (mpd_ssize_t)_uint_from_u16(data, len, u16, 8); } #endif static int _set_uint128_coeff_exp(mpd_t *result, uint64_t hi, uint64_t lo, mpd_ssize_t exp) { mpd_uint_t data[5] = {0}; uint32_t status = 0; mpd_ssize_t len; #if defined(CONFIG_64) && defined(__SIZEOF_INT128__) len = _set_coeff(data, hi, lo); #else len = _set_coeff(data, 5, hi, lo); #endif if (!mpd_qresize(result, len, &status)) { return -1; } for (mpd_ssize_t i = 0; i < len; i++) { result->data[i] = data[i]; } result->exp = exp; result->len = len; mpd_setdigits(result); return 0; } int mpd_from_uint128_triple(mpd_t *result, const mpd_uint128_triple_t *triple, uint32_t *status) { static const mpd_context_t maxcontext = { .prec=MPD_MAX_PREC, .emax=MPD_MAX_EMAX, .emin=MPD_MIN_EMIN, .round=MPD_ROUND_HALF_EVEN, .traps=MPD_Traps, .status=0, .newtrap=0, .clamp=0, .allcr=1, }; const enum mpd_triple_class tag = triple->tag; const uint8_t sign = triple->sign; const uint64_t hi = triple->hi; const uint64_t lo = triple->lo; mpd_ssize_t exp; #ifdef CONFIG_32 if (triple->exp < MPD_SSIZE_MIN || triple->exp > MPD_SSIZE_MAX) { goto conversion_error; } #endif exp = (mpd_ssize_t)triple->exp; switch (tag) { case MPD_TRIPLE_QNAN: case MPD_TRIPLE_SNAN: { if (sign > 1 || exp != 0) { goto conversion_error; } const uint8_t flags = tag == MPD_TRIPLE_QNAN ? MPD_NAN : MPD_SNAN; mpd_setspecial(result, sign, flags); if (hi == 0 && lo == 0) { /* no payload */ return 0; } if (_set_uint128_coeff_exp(result, hi, lo, exp) < 0) { goto malloc_error; } return 0; } case MPD_TRIPLE_INF: { if (sign > 1 || hi != 0 || lo != 0 || exp != 0) { goto conversion_error; } mpd_setspecial(result, sign, MPD_INF); return 0; } case MPD_TRIPLE_NORMAL: { if (sign > 1) { goto conversion_error; } const uint8_t flags = sign ? MPD_NEG : MPD_POS; mpd_set_flags(result, flags); if (exp > MPD_EXP_INF) { exp = MPD_EXP_INF; } if (exp == MPD_SSIZE_MIN) { exp = MPD_SSIZE_MIN+1; } if (_set_uint128_coeff_exp(result, hi, lo, exp) < 0) { goto malloc_error; } uint32_t workstatus = 0; mpd_qfinalize(result, &maxcontext, &workstatus); if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) { goto conversion_error; } return 0; } default: goto conversion_error; } conversion_error: mpd_seterror(result, MPD_Conversion_syntax, status); return -1; malloc_error: mpd_seterror(result, MPD_Malloc_error, status); return -1; } /******************************************************************************/ /* As triple */ /******************************************************************************/ #if defined(CONFIG_64) && defined(__SIZEOF_INT128__) static void _get_coeff(uint64_t *hi, uint64_t *lo, const mpd_t *a) { __uint128_t u128 = 0; switch (a->len) { case 3: u128 = a->data[2]; /* fall through */ case 2: u128 = u128 * MPD_RADIX + a->data[1]; /* fall through */ case 1: u128 = u128 * MPD_RADIX + a->data[0]; break; default: abort(); /* GCOV_NOT_REACHED */ } *hi = u128 >> 64; *lo = (uint64_t)u128; } #else static size_t _uint_to_u16(uint16_t w[8], mpd_uint_t *u, mpd_ssize_t ulen) { const mpd_uint_t wbase = 1U<<16; size_t n = 0; assert(ulen > 0); do { if (n >= 8) { abort(); /* GCOV_NOT_REACHED */ } w[n++] = (uint16_t)_mpd_shortdiv(u, u, ulen, wbase); /* ulen is at least 1. u[ulen-1] can only be zero if ulen == 1. */ ulen = _mpd_real_size(u, ulen); } while (u[ulen-1] != 0); return n; } static void _get_coeff(uint64_t *hi, uint64_t *lo, const mpd_t *a) { uint16_t u16[8] = {0}; mpd_uint_t data[5] = {0}; switch (a->len) { case 5: data[4] = a->data[4]; /* fall through */ case 4: data[3] = a->data[3]; /* fall through */ case 3: data[2] = a->data[2]; /* fall through */ case 2: data[1] = a->data[1]; /* fall through */ case 1: data[0] = a->data[0]; break; default: abort(); /* GCOV_NOT_REACHED */ } _uint_to_u16(u16, data, a->len); *hi = (uint64_t)u16[7] << 48; *hi |= (uint64_t)u16[6] << 32; *hi |= (uint64_t)u16[5] << 16; *hi |= (uint64_t)u16[4]; *lo = (uint64_t)u16[3] << 48; *lo |= (uint64_t)u16[2] << 32; *lo |= (uint64_t)u16[1] << 16; *lo |= (uint64_t)u16[0]; } #endif static enum mpd_triple_class _coeff_as_uint128(uint64_t *hi, uint64_t *lo, const mpd_t *a) { #ifdef CONFIG_64 static mpd_uint_t uint128_max_data[3] = { 3374607431768211455ULL, 4028236692093846346ULL, 3ULL }; static const mpd_t uint128_max = { MPD_STATIC|MPD_CONST_DATA, 0, 39, 3, 3, uint128_max_data }; #else static mpd_uint_t uint128_max_data[5] = { 768211455U, 374607431U, 938463463U, 282366920U, 340U }; static const mpd_t uint128_max = { MPD_STATIC|MPD_CONST_DATA, 0, 39, 5, 5, uint128_max_data }; #endif enum mpd_triple_class ret = MPD_TRIPLE_NORMAL; uint32_t status = 0; mpd_t coeff; *hi = *lo = 0ULL; if (mpd_isspecial(a)) { if (mpd_isinfinite(a)) { return MPD_TRIPLE_INF; } ret = mpd_isqnan(a) ? MPD_TRIPLE_QNAN : MPD_TRIPLE_SNAN; if (a->len == 0) { /* no payload */ return ret; } } else if (mpd_iszero(a)) { return ret; } _mpd_copy_shared(&coeff, a); mpd_set_flags(&coeff, 0); coeff.exp = 0; if (mpd_qcmp(&coeff, &uint128_max, &status) > 0) { return MPD_TRIPLE_ERROR; } _get_coeff(hi, lo, &coeff); return ret; } mpd_uint128_triple_t mpd_as_uint128_triple(const mpd_t *a) { mpd_uint128_triple_t triple = { MPD_TRIPLE_ERROR, 0, 0, 0, 0 }; triple.tag = _coeff_as_uint128(&triple.hi, &triple.lo, a); if (triple.tag == MPD_TRIPLE_ERROR) { return triple; } triple.sign = !!mpd_isnegative(a); if (triple.tag == MPD_TRIPLE_NORMAL) { triple.exp = a->exp; } return triple; }
/* * Copyright (c) 2008-2020 Stefan Krah. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
exceptions.ml
(**pp -syntax camlp5r *) (* camlp5o *) (* pp_MLast.ml,v *) declare type t = exn == ..; value show _ = "<exn>"; value pp pps _ = Fmt.(pf pps "<exn>"); declare value sexp_of_t _ = failwith "no sexp marshallers compiled in yet"; value t_of_sexp _ = failwith "no sexp marshallers compiled in yet"; value to_yojson _ = failwith "no yojson marshaller compiled in yet"; value of_yojson _ = failwith "no yojson marshaller compiled in yet"; value equal _ _ = failwith "no derived equality compiled in yet"; end; end;
(**pp -syntax camlp5r *) (* camlp5o *) (* pp_MLast.ml,v *)
vhdl_to_hardcaml.mli
open! Import (** Generate a module from a component declaration. *) val vhdl_component_to_ocaml_module : Vhdl.Component.t -> string
generic_map.ml
open! Base open Ppxlib open Ast_builder.Default module Pervasive = struct (* this list comes from lib/typerep_lib/lib/type_generic.mli *) type t = | Array | Lazy | List | Option | Ref let of_string = function | "array" -> Some Array | "lazy_t" -> Some Lazy | "list" -> Some List | "option" -> Some Option | "ref" -> Some Ref | _ -> None ;; end (* The specification for which values need to be replaced *) type t = | None | Replace of string | Tuple of t list | Constr_pervasive of Pervasive.t * t | Constr_t of longident * t list let rec needs_mapping = function | None -> false | Replace _ -> true | Constr_pervasive (_, t) -> needs_mapping t | Constr_t (_, ts) | Tuple ts -> List.exists ts ~f:needs_mapping ;; let rec apply ~loc ~map t expr = match t with | None -> expr | Constr_pervasive (pervasive, t) -> (match pervasive with | Option -> [%expr Stdlib.Option.map [%e apply_fn ~loc ~map t] [%e expr]] | List -> [%expr Stdlib.List.map [%e apply_fn ~loc ~map t] [%e expr]] | Ref -> [%expr ref [%e apply ~loc ~map t [%expr ![%e expr]]]] | Array -> [%expr Stdlib.Array.map [%e apply_fn ~loc ~map t] [%e expr]] | Lazy -> [%expr lazy [%e apply ~loc ~map t [%expr Stdlib.Lazy.force [%e expr]]]]) | Constr_t (longident, ts) -> let map_fn = pexp_ident ~loc (Located.mk ~loc (Ldot (longident, "map"))) in (match ts with | [] -> expr | [ t ] -> [%expr [%e map_fn] [%e expr] ~f:[%e apply_fn ~loc ~map t]] | ts -> let exprs = (Nolabel, expr) :: List.mapi ts ~f:(fun i t -> Labelled ("f" ^ Int.to_string (i + 1)), apply_fn ~loc ~map t) in pexp_apply ~loc map_fn exprs) | Replace text -> [%expr [%e Map.find_exn map text] [%e expr]] | Tuple ts -> let names = List.mapi ts ~f:(fun i _ -> "v" ^ Int.to_string i) in pexp_let ~loc Nonrecursive [ value_binding ~loc ~pat:(ppat_tuple ~loc (List.map names ~f:(pvar ~loc))) ~expr ] (pexp_tuple ~loc (List.map2_exn ts names ~f:(fun t name -> apply ~loc ~map t (evar ~loc name)))) and apply_fn ~loc ~map t = pexp_fun ~loc Nolabel None (pvar ~loc "x") (apply ~loc ~map t (evar ~loc "x")) ;; let rec find_targets ~target ~loc core_type = let list tys ~f = let recs = List.map tys ~f:(find_targets ~target ~loc) in if List.exists recs ~f:needs_mapping then f recs else None in match core_type.ptyp_desc with | Ptyp_constr (lid_loc, args) -> (match lid_loc.txt with | Lapply _ -> Location.raise_errorf ~loc "Unexpected Lapply" | Lident text when Set.mem target text -> Replace text | Lident text -> (match Pervasive.of_string text with | None -> None | Some kind -> (match args with | [] | _ :: _ :: _ -> (* Pervasive type with unexpected arity, so it's not a pervasive *) None | [ arg ] -> let t = find_targets ~target ~loc arg in (match needs_mapping t with | false -> None | true -> Constr_pervasive (kind, t)))) | Ldot (l, "t") -> list args ~f:(fun recs -> Constr_t (l, recs)) | Ldot _ -> None) | Ptyp_tuple args -> list args ~f:(fun x -> Tuple x) | _ -> None ;; type replace_result = | Unchanged | Replaced let build ~loc ~map ty expr = let t = find_targets ~target:(Set.of_list (module String) (Map.keys map)) ~loc ty in if needs_mapping t then Replaced, apply ~loc ~map t expr else Unchanged, expr ;;
test_script_typed_ir_size.ml
(** Testing ------- Component: Protocol (script typed IR size) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/michelson/main.exe \ -- test "^script typed ir size$" Subject: Script_typed_ir computes good approximation of values' sizes *) open Protocol open Alpha_context open Script_typed_ir (* Helpers ------- *) exception Script_typed_ir_test_error of string let err x = Exn (Script_typed_ir_test_error x) let dummy_loc = Micheline.dummy_location let get = Stdlib.Option.get let is_ok m = match m with Ok x -> x | _ -> assert false let footprint v = (* This is to turn every statically allocated data into heap-allocated data, to consider the worst-case in-memory representation of values. Note that it does NOT remove sharing.*) let v' = try Marshal.(from_bytes (to_bytes v [Closures]) 0) with _ -> (* Custom blocks are problematic. *) v in let size v = Obj.(reachable_words (repr v) * 8) in max (size v) (size v') (** [gen_string s] returns a heap-allocated string. Notice that a string literal ["foo"] written in the code is statically allocated and is therefore not counted by [Obj.reachable_words]. *) let gen_string s = let s = Bytes.of_string s |> Bytes.to_string in is_ok @@ Script_string.of_string s let boxed_set_elements s = Script_set.fold (fun x s -> x :: s) s [] let boxed_map_bindings s = Script_map.fold (fun k v s -> (k, v) :: s) s [] let big_map_bindings (Big_map s) = Big_map_overlay.bindings s.diff.map let show_script_int fmt x = Z.pp_print fmt (Script_int.to_zint x) let show_bool fmt b = Format.fprintf fmt "%B" b let show_script_string fmt x = Format.fprintf fmt "%s" (Script_string.to_string x) let show_address fmt Script_typed_ir.{destination; entrypoint} = Format.fprintf fmt "%a(%d):%a(%d)" Destination.pp destination (footprint destination) Entrypoint.pp entrypoint (footprint entrypoint) let dont_show _fmt _ = () let size = {Tezos_benchmark.Base_samplers.min = 4; max = 32} module Crypto_samplers = Tezos_benchmark.Crypto_samplers.V0.Make_finite_key_pool (struct let size = 10 let algo = `Default end) include Michelson_samplers.Make (struct let parameters : Michelson_samplers.parameters = { base_parameters = { Michelson_samplers_base.int_size = size; string_size = size; bytes_size = size; }; list_size = size; set_size = size; map_size = size; } end) (Crypto_samplers) let random_state = Random.State.make [|37; 73; 17; 71; 42|] let sample_ty size = Random_type.m_type ~size random_state let sample_value ty = Random_value.value ty random_state type ex = Ex : string * ('a, _) Script_typed_ir.ty * 'a * int -> ex [@@boxed] let ex ?(error = 0) label ty v = Ex (label, ty, v, error) let ex_random ?(error = 0) show ty ?(sample = fun () -> sample_value ty) label = let v = sample () in let label = Format.asprintf "@[%a%s@]@." show v label in ex ~error label ty v let exs ?(error = 0) n show ty ?(sample = fun () -> sample_value ty) label = List.map (fun _ -> ex_random ~error show ty label ~sample) (1 -- n) let nsample = 100 type ex_kinstr = Kinstr : string * ('a, 'b, 'c, 'd) kinstr -> ex_kinstr [@@boxed] (** [check_value_size ()] covers a finite number of cases of Michelson values, checking that the cost model is sound with respect to their memory footprint. One could wonder why we do not simply use a single value generator based on a randomly chosen type. We actually implemented such a strategy in a previous version of this test but this results in a flaky test. Indeed, for some types, the values are overapproximated and it was difficult to correctly handle the accumulation of errors when types were randomly composed. The current strategy requires more code but, in exchange, it provides a finer control over the overapproximation. As a consequence, we can check for example that there is no overapproximation for values for which the model is exact. We can also check that the overapproximation is at least well understood on the values for which size model is not exact. *) let check_value_size () = let check (Ex (what, ty, v, error)) = let expected_size = footprint v in let _, size = Script_typed_ir_size.value_size ty v in let size = Saturation_repr.to_int size in fail_when (expected_size + error < size || size < expected_size) (err (Printf.sprintf "%s was expected to have size %d while the size model answered %d \ (with +%d accepted over approximation error)" what expected_size size error)) in List.iter_es check ((* Unit_t ====== *) [ex "() : unit" Unit_t ()] (* Int_t ===== *) @ (let error = 8 in [ ex ~error "0 : int" Int_t Script_int.zero; ex ~error "2^63 : int" Int_t (Script_int.of_int max_int); ex ~error "37^73 : int" Int_t (Script_int.of_zint Z.(pow (of_int 37) 73)); ex ~error "-37^73 : int" Int_t (Script_int.of_zint Z.(neg (pow (of_int 37) 73))); ex ~error "13270006022583112970 : int" Int_t (get @@ Script_int.of_string "13270006022583112970"); ] @ exs ~error nsample show_script_int Int_t ": int") (* Nat_t ===== *) @ (let error = 8 in [ ex ~error "0 : nat" Nat_t Script_int.zero_n; ex ~error "2^63 : nat" Nat_t (get Script_int.(is_nat @@ of_int max_int)); ex ~error "37^73 : int" Nat_t (get Script_int.(is_nat @@ of_zint Z.(pow (of_int 37) 73))); ] @ exs ~error nsample show_script_int Nat_t ": nat") (* Signature_t =========== *) @ (let show fmt (Script_typed_ir.Script_signature.Signature_tag s) = Tezos_crypto.Signature.V0.pp fmt s in exs ~error:8 nsample show Signature_t ": signature") (* String_t ======== *) @ (let show fmt s = Format.fprintf fmt "%s" (Script_string.to_string s) in exs nsample show String_t ": string") (* Bytes_t ======= *) @ (let show fmt s = Format.fprintf fmt "%s" (Bytes.to_string s) in exs nsample show Bytes_t ": bytes") (* Mutez_t ======= *) @ (let show fmt t = Format.fprintf fmt "%s" (Tez.to_string t) in exs nsample show Mutez_t ": mutez") (* Key_hash_t ========== *) @ (let show = Tezos_crypto.Signature.V0.Public_key_hash.pp in exs nsample show Key_hash_t ": key_hash") (* Key_t ===== *) @ (let show = Tezos_crypto.Signature.V0.Public_key.pp in exs nsample show Key_t ": key_t") (* Timestamp_t =========== *) @ (let show fmt s = Format.fprintf fmt "%s" (Script_timestamp.to_string s) in exs ~error:8 nsample show Timestamp_t ": timestamp_t") (* Address_t ========= *) @ exs nsample show_address Address_t ": address_t" (* Tx_rollup_l2_address_t ====================== *) @ (let show = Indexable.pp Tx_rollup_l2_address.pp in exs nsample show Tx_rollup_l2_address_t ": tx_rollup_l2_t") (* Bool_t ====== *) @ [ex "true : bool" Bool_t true; ex "false : bool" Bool_t false] (* Pair_t ====== *) @ (let module P = struct type ('a, 'b) f = {apply : 'c. ('a * 'b, 'c) ty -> ex} end in let on_pair : type a b. (a, _) ty -> (b, _) ty -> (a, b) P.f -> ex = fun ty1 ty2 f -> let (Ty_ex_c ty) = is_ok @@ pair_t dummy_loc ty1 ty2 in f.apply ty in let open Script_int in [ (* "int * int" *) on_pair int_t int_t {apply = (fun ty -> ex "(0, 0) : int * int" ty (of_int 0, of_int 0))}; (* "string * string" *) on_pair string_t string_t { apply = (fun ty -> let foo = gen_string "foo" in let bar = gen_string "bar" in ex "(foo, bar) : string * string" ty (foo, bar)); }; (* "string * int" *) on_pair string_t int_t { apply = (fun ty -> let foo = gen_string "foo" in ex "(foo, 0) : string * int" ty (foo, of_int 0)); }; (* "int * int * int" *) on_pair int_t int_t { apply = (fun ty -> on_pair int_t ty @@ { apply = (fun ty -> ex "(0, (1, 2)) : int * int * int" ty (of_int 0, (of_int 1, of_int 2))); }); }; ]) (* Union_t ======= *) @ (let module P = struct type ('a, 'b) f = {apply : 'c. (('a, 'b) union, 'c) ty -> ex} end in let on_union : type a b. (a, _) ty -> (b, _) ty -> (a, b) P.f -> ex = fun ty1 ty2 f -> let (Ty_ex_c ty) = is_ok @@ union_t dummy_loc ty1 ty2 in f.apply ty in let open Script_int in [ (* "int + int" *) on_union int_t int_t {apply = (fun ty -> ex "L 0 : int + int" ty (L (of_int 0)))}; on_union int_t int_t {apply = (fun ty -> ex "R 0 : int + int" ty (R (of_int 0)))}; (* "string + string" *) on_union string_t string_t { apply = (fun ty -> let foo = gen_string "foo" in ex "L foo : string * string" ty (L foo)); }; on_union string_t string_t { apply = (fun ty -> let foo = gen_string "foo" in ex "R foo : string * string" ty (R foo)); }; (* "string + int" *) on_union string_t int_t { apply = (fun ty -> let foo = gen_string "foo" in ex "L foo : string * int" ty (L foo)); }; (* "int + int + int" *) on_union int_t int_t { apply = (fun ty -> on_union int_t ty { apply = (fun ty -> ex "L 0 : int + int + int" ty (L (of_int 0))); }); }; on_union int_t int_t { apply = (fun ty -> on_union int_t ty { apply = (fun ty -> ex "R (L 0) : int + int + int" ty (R (L (of_int 0)))); }); }; on_union int_t int_t { apply = (fun ty -> on_union int_t ty { apply = (fun ty -> ex "R (R 0) : int + int + int" ty (R (R (of_int 0)))); }); }; ]) (* Option_t ======== *) @ (let module P = struct type 'a f = {apply : 'c. ('a option, 'c) ty -> ex} end in let on_option : type a. (a, _) ty -> a P.f -> ex = fun ty f -> f.apply @@ is_ok @@ option_t dummy_loc ty in let open Script_int in [ (* "option int" *) on_option int_t {apply = (fun ty -> ex "None : option int" ty None)}; on_option int_t {apply = (fun ty -> ex "Some 0 : option int" ty (Some (of_int 0)))}; (* "option string" *) on_option string_t {apply = (fun ty -> ex "None : option string" ty None)}; on_option string_t { apply = (fun ty -> ex "Some \"foo\" : option string" ty (Some (gen_string "foo"))); }; ]) (* List_t ====== *) @ (let module P = struct type 'a f = {apply : 'c. ('a boxed_list, 'c) ty -> ex list} end in let on_list : type a. (a, _) ty -> a P.f -> ex list = fun ty f -> f.apply @@ is_ok @@ list_t dummy_loc ty in let check ty show_elt = on_list ty { apply = (fun ty -> let show fmt l = Format.pp_print_list show_elt fmt l.elements in exs nsample show ty ": list _"); } in check string_t show_script_string) (* Set_t ====== *) @ (let module P = struct type 'a f = {apply : 'c. ('a set, 'c) ty -> ex list} end in let on_set : type a. (a, _) ty -> a P.f -> ex list = fun ty f -> f.apply @@ is_ok @@ set_t dummy_loc ty in let check ty show_elt = on_set ty { apply = (fun ty -> let show fmt s = Format.fprintf fmt "%a / %a" show_script_int (Script_set.size s) (Format.pp_print_list show_elt) (boxed_set_elements s) in exs nsample show ty ": set _"); } in check string_t show_script_string) (* Map_t ====== *) @ (let module P = struct type ('k, 'v) f = {apply : 'c. (('k, 'v) map, 'c) ty -> ex list} end in let on_map : type k v. (k, _) ty -> (v, _) ty -> (k, v) P.f -> ex list = fun kty vty f -> f.apply @@ is_ok @@ map_t dummy_loc kty vty in let check kty vty show_key show_value = on_map kty vty { apply = (fun ty -> let show_binding fmt (k, v) = Format.fprintf fmt "(%a -> %a)" show_key k show_value v in let show fmt s = Format.pp_print_list show_binding fmt (boxed_map_bindings s) in exs nsample show ty ": map _"); } in check string_t string_t show_script_string show_script_string) (* Big_map_t ====== *) @ (let module P = struct type ('k, 'v) f = {apply : 'c. (('k, 'v) big_map, 'c) ty -> ex list} end in let on_big_map : type k v. (k, _) ty -> (v, _) ty -> (k, v) P.f -> ex list = fun kty vty f -> f.apply @@ is_ok @@ big_map_t dummy_loc kty vty in let check kty vty show_key show_value = on_big_map kty vty { apply = (fun ty -> let show_binding fmt (_, (k, v)) = match v with | Some v -> Format.fprintf fmt "(%a -> %a)" show_key k show_value v | None -> Format.fprintf fmt "(%a?)" show_key k in let show fmt s = Format.pp_print_list show_binding fmt (big_map_bindings s) in exs nsample show ty ": big_map _"); } in check bool_t bool_t show_bool show_bool) (* Contract_t ========= *) @ (let show fmt typed_contract = let destination = Typed_contract.destination typed_contract in let entrypoint = Typed_contract.entrypoint typed_contract in show_address fmt {destination; entrypoint} in exs nsample show (is_ok @@ contract_t dummy_loc string_t) ": contract string") (* Chain_t ========= *) @ exs nsample dont_show chain_id_t ": chain_id" (* Bls12_381_g1_t ============== *) @ exs nsample dont_show bls12_381_g1_t ": bls12_381_g1_t" (* Bls12_381_g2_t ============== *) @ exs nsample dont_show bls12_381_g2_t ": bls12_381_g2_t" (* Bls12_381_fr_t ============== *) @ exs nsample dont_show bls12_381_fr_t ": bls12_381_fr_t" (* Ticket_t ======== *) @ exs ~error:8 nsample dont_show (is_ok @@ ticket_t dummy_loc bool_t) ": ticket bool" (* Missing by lack of fully functional samplers: - Sapling_transaction_t ; - Sapling_transaction_deprecated_t ; - Sapling_state ; - Operation_t ; - Chest_key_t ; - Chest_t ; - Lambda_t. *) ) let check_ty_size () = let check () = match (sample_ty (Random.int 10 + 1) : ex_ty) with | Ex_ty ty -> let expected_size = footprint ty in let _, size = Script_typed_ir_size.Internal_for_tests.ty_size ty in let size = Saturation_repr.to_int size in let what = "some type" in fail_when (size <> expected_size) (err (Printf.sprintf "%s was expected to have size %d while the size model answered \ %d." what expected_size size)) in List.iter_es (fun _ -> check ()) (1 -- nsample) let check_size ~name ~expected item = let open Lwt_result_syntax in let _, e = expected item in let exp = Saturation_repr.to_int e in let actual = 8 * Obj.(reachable_words @@ repr item) in let overapprox = 1_000_000 * (exp - actual) / actual in let msg verb = Printf.sprintf "For %s model predicts the size of %d bytes; while actual measured size \ is %d bytes. The model %s %d.%04d%%" name exp actual verb (abs @@ (overapprox / 10_000)) (abs @@ (overapprox mod 10_000)) in let* () = fail_when (overapprox < 0) (err @@ msg "under-approximates by") in fail_when (overapprox > 0) (err @@ msg "over-approximates by") (* We expected the model to always be exact. *) (* Test that the model accurately predicts instruction sizes. It tests each type of instruction separately as much as possible. Tested values are specifically tailored so that they can't be shared (in particular all reused values are wrapped in functions to discourage sharing). Thanks to this the model gives precise predictions for each instruction. In real life the model will over-approximate due to sharing. It should never under- approximate though. *) let check_kinstr_size () = let open Lwt_result_syntax in let check (Kinstr (name, instr)) = check_size ~name ~expected:Script_typed_ir_size.Internal_for_tests.kinstr_size instr in (* Location is an immediate value, so we don't care if it's shared. *) let loc = Micheline.dummy_location in let str s = (* It's important to transform the string somehow, or else it will be shared and thus not reached by Obj.reachable_words. *) match Script_string.of_string @@ String.uppercase_ascii s with | Ok ss -> ss | Error _ -> assert false in let entrypoint name = Entrypoint.of_string_strict_exn @@ String.uppercase_ascii name in (* Constants below are wrapped in functions to force recomputation and discourage sharing. *) let halt () = IHalt loc in let drop () = IDrop (loc, halt ()) in let cdr = ICdr (loc, halt ()) in let const ty v = IConst (loc, ty, v, halt ()) in let unit_option_t () = WithExceptions.Result.get_ok ~loc:__LOC__ @@ option_t loc Unit_t in let stack_type () = Item_t (unit_option_t (), Bot_t) in let id_lambda () = Lam ( { kloc = loc; kbef = stack_type (); kaft = stack_type (); kinstr = halt (); }, Micheline.Seq (loc, []) ) in (* Following constants are used but once. *) let zero_memo_size = WithExceptions.Result.get_ok ~loc:__LOC__ @@ Alpha_context.Sapling.Memo_size.parse_z Z.zero in (* Check size of the lambda alone. *) let* () = check_size ~name:"id lambda" ~expected:Script_typed_ir_size.lambda_size (id_lambda ()) in (* Testing individual instructions. *) List.iter_es check [ Kinstr ("IDrop", drop ()); Kinstr ("IDup", IDup (loc, halt ())); Kinstr ("ISwap", ISwap (loc, halt ())); Kinstr ("IConst", const String_t @@ str "tezos"); Kinstr ("ICons_pair", ICons_pair (loc, halt ())); Kinstr ("ICar", ICar (loc, halt ())); Kinstr ("ICdr", cdr); Kinstr ("IUnpair", IUnpair (loc, halt ())); Kinstr ("ICons_some", ICons_some (loc, halt ())); Kinstr ("ICons_none", ICons_none (loc, Int_t, halt ())); Kinstr ( "IIf_none", IIf_none { loc; branch_if_some = drop (); branch_if_none = halt (); k = halt (); } ); Kinstr ("IOpt_map", IOpt_map {loc; body = halt (); k = halt ()}); Kinstr ("ICons_left", ICons_left (loc, Nat_t, halt ())); Kinstr ("ICons_right", ICons_right (loc, Int_t, halt ())); Kinstr ( "IIf_left", IIf_left { loc; branch_if_left = drop (); branch_if_right = drop (); k = halt (); } ); Kinstr ("ICons_list", ICons_list (loc, halt ())); Kinstr ("INil", INil (loc, Bytes_t, halt ())); Kinstr ( "IIf_cons", IIf_cons { loc; branch_if_cons = IDrop (loc, drop ()); branch_if_nil = halt (); k = halt (); } ); Kinstr ("IList_map", IList_map (loc, halt (), None, halt ())); Kinstr ("IList_iter", IList_iter (loc, None, drop (), halt ())); Kinstr ("IList_size", IList_size (loc, halt ())); Kinstr ("IEmpty_set", IEmpty_set (loc, String_t, halt ())); Kinstr ("ISet_iter", ISet_iter (loc, None, drop (), halt ())); Kinstr ("ISet_mem", ISet_mem (loc, halt ())); Kinstr ("ISet_update", ISet_update (loc, halt ())); Kinstr ("ISet_size", ISet_size (loc, halt ())); Kinstr ("IEmpty_map", IEmpty_map (loc, Nat_t, None, halt ())); Kinstr ("IMap_map", IMap_map (loc, None, cdr, halt ())); Kinstr ("IMap_iter", IMap_iter (loc, None, drop (), halt ())); Kinstr ("IMap_mem", IMap_mem (loc, halt ())); Kinstr ("IMap_get", IMap_get (loc, halt ())); Kinstr ("IMap_update", IMap_update (loc, halt ())); Kinstr ("IMap_get_and_update", IMap_get_and_update (loc, halt ())); Kinstr ("IMap_size", IMap_size (loc, halt ())); Kinstr ("IEmpty_big_map", IEmpty_big_map (loc, Nat_t, String_t, halt ())); Kinstr ("IBig_map_mem", IBig_map_mem (loc, halt ())); Kinstr ("IBig_map_get", IBig_map_get (loc, halt ())); Kinstr ("IBig_map_update", IBig_map_update (loc, halt ())); Kinstr ("IBig_map_get_and_update", IBig_map_get_and_update (loc, halt ())); Kinstr ("IConcat_string", IConcat_string (loc, halt ())); Kinstr ("IConcat_string_pair", IConcat_string_pair (loc, halt ())); Kinstr ("ISlice_string", ISlice_string (loc, halt ())); Kinstr ("IString_size", IString_size (loc, halt ())); Kinstr ("IConcat_bytes", IConcat_bytes (loc, halt ())); Kinstr ("IConcat_bytes_pair", IConcat_bytes_pair (loc, halt ())); Kinstr ("ISlice_bytes", ISlice_bytes (loc, halt ())); Kinstr ("IBytes_size", IBytes_size (loc, halt ())); Kinstr ("IAdd_seconds_to_timestamp ", IAdd_seconds_to_timestamp (loc, halt ())); Kinstr ("IAdd_timestamp_to_seconds", IAdd_timestamp_to_seconds (loc, halt ())); Kinstr ("ISub_timestamp_seconds", ISub_timestamp_seconds (loc, halt ())); Kinstr ("IDiff_timestamps", IDiff_timestamps (loc, halt ())); Kinstr ("IAdd_tez", IAdd_tez (loc, halt ())); Kinstr ("ISub_tez", ISub_tez (loc, halt ())); Kinstr ("ISub_tez_legacy", ISub_tez_legacy (loc, halt ())); Kinstr ("IMul_tez_nat", IMul_teznat (loc, halt ())); Kinstr ("IMul_nattez", IMul_nattez (loc, halt ())); Kinstr ("IEdiv_teznat", IEdiv_teznat (loc, halt ())); Kinstr ("IEdiv_nattez", IEdiv_tez (loc, halt ())); Kinstr ("IOr", IOr (loc, halt ())); Kinstr ("IAnd", IAnd (loc, halt ())); Kinstr ("IXor", IXor (loc, halt ())); Kinstr ("INot", INot (loc, halt ())); Kinstr ("IIs_nat", IIs_nat (loc, halt ())); Kinstr ("INeg", INeg (loc, halt ())); Kinstr ("IAbs_int", IAbs_int (loc, halt ())); Kinstr ("IInt_nat", IInt_nat (loc, halt ())); Kinstr ("IAdd_int", IAdd_int (loc, halt ())); Kinstr ("IAdd_nat", IAdd_nat (loc, halt ())); Kinstr ("ISub_int", ISub_int (loc, halt ())); Kinstr ("IMul_int", IMul_int (loc, halt ())); Kinstr ("IMul_nat", IMul_nat (loc, halt ())); Kinstr ("IEdiv_int", IEdiv_int (loc, halt ())); Kinstr ("IEdiv_nat", IEdiv_nat (loc, halt ())); Kinstr ("ILsl_nat", ILsl_nat (loc, halt ())); Kinstr ("ILsr_nat", ILsr_nat (loc, halt ())); Kinstr ("IOr_nat", IOr_nat (loc, halt ())); Kinstr ("IAnd_nat", IAnd_nat (loc, halt ())); Kinstr ("IAnd_int_nat", IAnd_int_nat (loc, halt ())); Kinstr ("IXor_nat", IXor_nat (loc, halt ())); Kinstr ("INot_int", INot_int (loc, halt ())); Kinstr ( "IIf", IIf { loc; branch_if_true = halt (); branch_if_false = halt (); k = halt (); } ); Kinstr ("ILoop", ILoop (loc, const Bool_t true, halt ())); Kinstr ("ILoop_left", ILoop_left (loc, INever loc, halt ())); Kinstr ("IDip", IDip (loc, halt (), None, halt ())); Kinstr ("IExec", IExec (loc, None, halt ())); Kinstr ("IApply", IApply (loc, String_t, halt ())); Kinstr ("ILambda", ILambda (loc, id_lambda (), halt ())); Kinstr ("IFailwith", IFailwith (loc, String_t)); Kinstr ("ICompare", ICompare (loc, String_t, halt ())); Kinstr ("IEq", IEq (loc, halt ())); Kinstr ("INeq", INeq (loc, halt ())); Kinstr ("ILt", ILt (loc, halt ())); Kinstr ("IGt", IGt (loc, halt ())); Kinstr ("ILe", ILe (loc, halt ())); Kinstr ("IGe", IGe (loc, halt ())); Kinstr ("IAddress", IAddress (loc, halt ())); Kinstr ("IContract", IContract (loc, Unit_t, entrypoint "entry", halt ())); Kinstr ( "IView", IView ( loc, View_signature { name = str "myview"; input_ty = unit_option_t (); output_ty = unit_option_t (); }, None, halt () ) ); Kinstr ("ITransfer_tokens", ITransfer_tokens (loc, halt ())); Kinstr ("IImplicit_account", IImplicit_account (loc, halt ())); Kinstr ( "ICreate_contract", ICreate_contract { loc; storage_type = Unit_t; code = Micheline.(strip_locations @@ Seq (loc, [])); k = halt (); } ); Kinstr ("ISet_delegate", ISet_delegate (loc, halt ())); Kinstr ("INow", INow (loc, halt ())); Kinstr ("IMin_block_time", IMin_block_time (loc, halt ())); Kinstr ("IBalance", IBalance (loc, halt ())); Kinstr ("ILevel", ILevel (loc, halt ())); Kinstr ("ICheck_signature", ICheck_signature (loc, halt ())); Kinstr ("IHash_key", IHash_key (loc, halt ())); Kinstr ("IPack", IPack (loc, Int_t, halt ())); Kinstr ("IUnpack", IUnpack (loc, Int_t, halt ())); Kinstr ("IBlake2b", IBlake2b (loc, halt ())); Kinstr ("ISha_256", ISha256 (loc, halt ())); Kinstr ("ISha512", ISha512 (loc, halt ())); Kinstr ("ISource", ISource (loc, halt ())); Kinstr ("ISender", ISender (loc, halt ())); Kinstr ("ISelf", ISelf (loc, Unit_t, entrypoint "entry", halt ())); Kinstr ("ISelf_address", ISelf_address (loc, halt ())); Kinstr ("IAmount", IAmount (loc, halt ())); Kinstr ( "ISapling_empty_state", ISapling_empty_state (loc, zero_memo_size, halt ()) ); Kinstr ("ISapling_verify_update", ISapling_verify_update (loc, halt ())); Kinstr ( "ISapling_verify_update_deprecated", ISapling_verify_update_deprecated (loc, halt ()) ); Kinstr ("IDig", IDig (loc, 0, KRest, halt ())); Kinstr ("IDug", IDug (loc, 0, KRest, halt ())); Kinstr ("IDipn", IDipn (loc, 0, KRest, halt (), halt ())); Kinstr ("IDropn", IDropn (loc, 0, KRest, halt ())); Kinstr ("IChainId", IChainId (loc, halt ())); Kinstr ("INever", INever loc); Kinstr ("IVoting_power", IVoting_power (loc, halt ())); Kinstr ("ITotal_voting_power", ITotal_voting_power (loc, halt ())); Kinstr ("IKeccak", IKeccak (loc, halt ())); Kinstr ("ISha3", ISha3 (loc, halt ())); Kinstr ("IAdd_bls12_381_g1", IAdd_bls12_381_g1 (loc, halt ())); Kinstr ("IAdd_bls12_381_2g", IAdd_bls12_381_g2 (loc, halt ())); Kinstr ("IAdd_bls12_381_fr", IAdd_bls12_381_fr (loc, halt ())); Kinstr ("IMul_bls12_381_g1", IMul_bls12_381_g1 (loc, halt ())); Kinstr ("IMul_bls12_381_g2", IMul_bls12_381_g2 (loc, halt ())); Kinstr ("IMul_bls12_381_fr", IMul_bls12_381_fr (loc, halt ())); Kinstr ("IMul_bls12_381_z_fr", IMul_bls12_381_z_fr (loc, halt ())); Kinstr ("IMul_bls12_381_fr_z", IMul_bls12_381_fr_z (loc, halt ())); Kinstr ("IMul_bls12_381_fr_z", IMul_bls12_381_fr_z (loc, halt ())); Kinstr ("IInt_bls12_381_fr", IInt_bls12_381_fr (loc, halt ())); Kinstr ("INeg_bls12_381_g1", INeg_bls12_381_g1 (loc, halt ())); Kinstr ("INeg_bls12_381_g2", INeg_bls12_381_g2 (loc, halt ())); Kinstr ("INeg_bls12_381_fr", INeg_bls12_381_fr (loc, halt ())); Kinstr ("IPairing_check_bls12_381", IPairing_check_bls12_381 (loc, halt ())); Kinstr ("IComb", IComb (loc, 0, Comb_one, halt ())); Kinstr ("IUncomb", IUncomb (loc, 0, Uncomb_one, halt ())); Kinstr ("IComb_get", IComb_get (loc, 0, Comb_get_zero, halt ())); Kinstr ("IComb_set", IComb_set (loc, 0, Comb_set_zero, halt ())); Kinstr ("IDup_n", IDup_n (loc, 0, Dup_n_zero, halt ())); Kinstr ("ITicket", ITicket (loc, None, halt ())); Kinstr ("IRead_ticket", IRead_ticket (loc, None, halt ())); Kinstr ("ISplit_ticket", ISplit_ticket (loc, halt ())); Kinstr ("IJoin_tickets", IJoin_tickets (loc, Unit_t, halt ())); Kinstr ("IOpen_chest", IOpen_chest (loc, halt ())); Kinstr ( "IEmit", IEmit { loc; tag = entrypoint "entry"; ty = Unit_t; unparsed_ty = Micheline.(strip_locations @@ Seq (loc, [])); k = halt (); } ); Kinstr ("IHalt ()", halt ()); ] let check_witness_sizes () = let loc = Micheline.dummy_location in let stack_prefix_preservation = KPrefix ( loc, Unit_t, KPrefix ( loc, Unit_t, KPrefix ( loc, Unit_t, KPrefix ( loc, Unit_t, KPrefix ( loc, Unit_t, KPrefix ( loc, Unit_t, KPrefix (loc, Unit_t, KPrefix (loc, Unit_t, KRest)) ) ) ) ) ) ) in check_size ~name:"stack_prefix_preservation_witness" ~expected: Script_typed_ir_size.Internal_for_tests .stack_prefix_preservation_witness_size stack_prefix_preservation let check_micheline_sizes () = let open Michelson_v1_primitives in let check (name, micheline) = check_size ~name ~expected:Cache_memory_helpers.node_size micheline in let int i = Micheline.(Int (dummy_loc, Z.of_int i)) in let big_int z = Micheline.(Int (dummy_loc, z)) in let str s = Micheline.(String (dummy_location, String.lowercase_ascii s)) in let bytes b = Micheline.(Bytes (dummy_location, Bytes.of_string b)) in let prim ?(annot = []) p args = Micheline.(Prim (dummy_location, p, args, annot)) in let seq xs = Micheline.(Seq (dummy_location, xs)) in List.iter_es check [ ("empty micheline", seq []); ("a single number", int 1024); ("a large number", big_int Z.(of_int 3 * of_int max_int)); ("a short string", str "tezostezostezos"); ("a short bytestring", bytes "tezostezostezos"); ("a prim with no args", prim I_UNIT []); ("a seq of prims", seq [prim I_DUP []; prim I_DROP []]); ("a prim with arg", prim I_DIG [int 2]); ( "combine everything together", seq [ prim I_UNIT []; prim I_DUG [int 3] ~annot:[String.lowercase_ascii "@number"]; prim I_DIP [seq [prim I_DROP [int 2]]]; prim I_PUSH [prim T_string []; str "tezos"]; ] ); ] let tests = let open Tztest in [ tztest "check value size" `Quick check_value_size; tztest "check ty size" `Quick check_ty_size; tztest "check kinstr size" `Quick check_kinstr_size; tztest "check witness sizes" `Quick check_witness_sizes; tztest "check micheline sizes" `Quick check_micheline_sizes; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dummy_context.ml
module M = struct type t = unit type key = string list type value = Bytes.t type tree = | module Tree = struct let pp _ _ = assert false let hash _ = assert false let empty _ = assert false let equal _ _ = assert false let is_empty _ = assert false let mem _ _ = assert false let kind _ = assert false let to_value _ = assert false let of_value _ _ = assert false let find _ _ = assert false let add _ _ _ = assert false let remove _ _ = assert false let mem_tree _ _ = assert false let find_tree _ _ = assert false let add_tree _ _ = assert false let clear ?depth:_ _ = assert false let list _ ?offset:_ ?length:_ _ = assert false let length _ _ = assert false let fold ?depth:_ _ _ ~order:_ ~init:_ ~f:_ = assert false let config _ = assert false end include Tree module Proof = Memory_context.M.Proof let set_protocol _ _ = assert false let get_protocol _ = assert false let fork_test_chain _ ~protocol:_ ~expiration:_ = assert false let set_hash_version _ _ = assert false let get_hash_version _ = assert false let verify_tree_proof _ _ = assert false let verify_stream_proof _ _ = assert false let equal_config _ _ = assert false let config _ = assert false end open Tezos_protocol_environment include Environment_context.Register (M) let empty = Context.make ~ops ~ctxt:() ~kind:Context ~equality_witness ~impl_name:"dummy"
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
types.ml
open Core open! Int.Replace_polymorphic_compare type backend_key = { pid : int ; secret : int } [@@deriving sexp_of] module type Named_or_unnamed = sig type t val unnamed : t val create_named_exn : string -> t val to_string : t -> string end module Named_or_unnamed = struct type t = string let unnamed = "" let create_named_exn s = if String.is_empty s then failwith "Named_or_unnamed.create_named_exn got an empty string"; if String.mem s '\x00' then failwith "Named_or_unnamed.create_named_exn: string must not contain \\x00"; s ;; let to_string (t : t) : string = t end module Statement_name = Named_or_unnamed module Portal_name = Named_or_unnamed module Notification_channel = String
mempool.ml
open Protocol open Alpha_context type error_classification = [ `Branch_delayed of tztrace | `Branch_refused of tztrace | `Refused of tztrace | `Outdated of tztrace ] type nanotez = Q.t let nanotez_enc : nanotez Data_encoding.t = let open Data_encoding in def "nanotez" ~title:"A thousandth of a mutez" ~description:"One thousand nanotez make a mutez (1 tez = 1e9 nanotez)" (conv (fun q -> (q.Q.num, q.Q.den)) (fun (num, den) -> {Q.num; den}) (tup2 z z)) let manager_op_replacement_factor_enc : Q.t Data_encoding.t = let open Data_encoding in def "manager operation replacement factor" ~title:"A manager operation's replacement factor" ~description:"The fee and fee/gas ratio of an operation to replace another" (conv (fun q -> (q.Q.num, q.Q.den)) (fun (num, den) -> {Q.num; den}) (tup2 z z)) type config = { minimal_fees : Tez.t; minimal_nanotez_per_gas_unit : nanotez; minimal_nanotez_per_byte : nanotez; allow_script_failure : bool; (** If [true], this makes [post_filter_manager] unconditionally return [`Passed_postfilter filter_state], no matter the operation's success. *) clock_drift : Period.t option; replace_by_fee_factor : Q.t; (** This field determines the amount of additional fees (given as a factor of the declared fees) a manager should add to an operation in order to (eventually) replace an existing (prechecked) one in the mempool. Note that other criteria, such as the gas ratio, are also taken into account to decide whether to accept the replacement or not. *) max_prechecked_manager_operations : int; (** Maximal number of prechecked operations to keep. The mempool only keeps the [max_prechecked_manager_operations] operations with the highest fee/gas and fee/size ratios. *) } let default_minimal_fees = match Tez.of_mutez 100L with None -> assert false | Some t -> t let default_minimal_nanotez_per_gas_unit = Q.of_int 100 let default_minimal_nanotez_per_byte = Q.of_int 1000 let managers_quota = Stdlib.List.nth Main.validation_passes Operation_repr.manager_pass (* If the drift is not specified, it will be the duration of round zero. It allows only to spam with one future round. /!\ Warning /!\ : current plugin implementation implies that this drift cumulates with the accepted drift regarding the current head's timestamp. *) let default_config = { minimal_fees = default_minimal_fees; minimal_nanotez_per_gas_unit = default_minimal_nanotez_per_gas_unit; minimal_nanotez_per_byte = default_minimal_nanotez_per_byte; allow_script_failure = true; clock_drift = None; replace_by_fee_factor = Q.make (Z.of_int 105) (Z.of_int 100) (* Default value of [replace_by_fee_factor] is set to 5% *); max_prechecked_manager_operations = 5_000; } let config_encoding : config Data_encoding.t = let open Data_encoding in conv (fun { minimal_fees; minimal_nanotez_per_gas_unit; minimal_nanotez_per_byte; allow_script_failure; clock_drift; replace_by_fee_factor; max_prechecked_manager_operations; } -> ( minimal_fees, minimal_nanotez_per_gas_unit, minimal_nanotez_per_byte, allow_script_failure, clock_drift, replace_by_fee_factor, max_prechecked_manager_operations )) (fun ( minimal_fees, minimal_nanotez_per_gas_unit, minimal_nanotez_per_byte, allow_script_failure, clock_drift, replace_by_fee_factor, max_prechecked_manager_operations ) -> { minimal_fees; minimal_nanotez_per_gas_unit; minimal_nanotez_per_byte; allow_script_failure; clock_drift; replace_by_fee_factor; max_prechecked_manager_operations; }) (obj7 (dft "minimal_fees" Tez.encoding default_config.minimal_fees) (dft "minimal_nanotez_per_gas_unit" nanotez_enc default_config.minimal_nanotez_per_gas_unit) (dft "minimal_nanotez_per_byte" nanotez_enc default_config.minimal_nanotez_per_byte) (dft "allow_script_failure" bool default_config.allow_script_failure) (opt "clock_drift" Period.encoding) (dft "replace_by_fee_factor" manager_op_replacement_factor_enc default_config.replace_by_fee_factor) (dft "max_prechecked_manager_operations" int31 default_config.max_prechecked_manager_operations)) (** An Alpha_context manager operation, packed so that the type is not parametrized by ['kind]. *) type manager_op = Manager_op : 'kind Kind.manager operation -> manager_op (** Information stored for each prechecked manager operation. Note that this record does not include the operation hash because it is instead used as key in the map that stores this information in the [state] below. *) type manager_op_info = { manager_op : manager_op; (** Used when we want to remove the operation with {!Validate.remove_manager_operation}. *) fee : Tez.t; gas_limit : Fixed_point_repr.integral_tag Gas.Arith.t; (** Both [fee] and [gas_limit] are used to determine whether a new operation from the same manager should replace this one. *) weight : Q.t; (** Used to update [ops_prechecked] and [min_prechecked_op_weight] in [state] when appropriate. *) } type manager_op_weight = {operation_hash : Operation_hash.t; weight : Q.t} (** Build a {!manager_op_weight} from operation hash and {!manager_op_info}. *) let mk_op_weight oph (info : manager_op_info) = {operation_hash = oph; weight = info.weight} let compare_manager_op_weight op1 op2 = let c = Q.compare op1.weight op2.weight in if c <> 0 then c else Operation_hash.compare op1.operation_hash op2.operation_hash module ManagerOpWeightSet = Set.Make (struct type t = manager_op_weight (* Sort by weight *) let compare = compare_manager_op_weight end) (** Static information to store in the filter state. *) type state_info = { head : Block_header.shell_header; round_durations : Round.round_durations; hard_gas_limit_per_block : Gas.Arith.integral; head_round : Round.t; round_zero_duration : Period.t; grandparent_level_start : Timestamp.t; } (** State that tracks validated manager operations. *) type ops_state = { prechecked_manager_op_count : int; (** Number of prechecked manager operations. Invariants: - [prechecked_manager_op_count = Operation_hash.Map.cardinal prechecked_manager_ops = ManagerOpWeightSet.cardinal prechecked_op_weights] - [prechecked_manager_op_count <= max_prechecked_manager_operations] *) prechecked_manager_ops : manager_op_info Operation_hash.Map.t; (** All prechecked manager operations. See {!manager_op_info}. *) prechecked_op_weights : ManagerOpWeightSet.t; (** The {!manager_op_weight} of all prechecked manager operations. *) min_prechecked_op_weight : manager_op_weight option; (** The prechecked operation in [op_prechecked_managers], if any, with the minimal weight. Invariant: - [min_prechecked_op_weight = min { x | x \in prechecked_op_weights }] *) } type state = {state_info : state_info; ops_state : ops_state} let empty_ops_state = { prechecked_manager_op_count = 0; prechecked_manager_ops = Operation_hash.Map.empty; prechecked_op_weights = ManagerOpWeightSet.empty; min_prechecked_op_weight = None; } let init_state_prototzresult ~head round_durations hard_gas_limit_per_block = let open Lwt_result_syntax in let*? head_round = Alpha_context.Fitness.round_from_raw head.Tezos_base.Block_header.fitness in let round_zero_duration = Round.round_duration round_durations Round.zero in let*? grandparent_round = Alpha_context.Fitness.predecessor_round_from_raw head.fitness in let*? proposal_level_offset = Round.level_offset_of_round round_durations ~round:Round.(succ grandparent_round) in let*? proposal_round_offset = Round.level_offset_of_round round_durations ~round:head_round in let*? proposal_offset = Period.(add proposal_level_offset proposal_round_offset) in let grandparent_level_start = Timestamp.(head.timestamp - proposal_offset) in let state_info = { head; round_durations; hard_gas_limit_per_block; head_round; round_zero_duration; grandparent_level_start; } in return {state_info; ops_state = empty_ops_state} let init_state ~head round_durations hard_gas_limit_per_block = Lwt.map Environment.wrap_tzresult (init_state_prototzresult ~head round_durations hard_gas_limit_per_block) let init context ~(head : Tezos_base.Block_header.shell_header) = let open Lwt_result_syntax in let* ( ctxt, (_ : Receipt.balance_updates), (_ : Migration.origination_result list) ) = prepare context ~level:(Int32.succ head.level) ~predecessor_timestamp:head.timestamp ~timestamp:head.timestamp |> Lwt.map Environment.wrap_tzresult in let round_durations = Constants.round_durations ctxt in let hard_gas_limit_per_block = Constants.hard_gas_limit_per_block ctxt in init_state ~head round_durations hard_gas_limit_per_block let flush old_state ~head = (* To avoid the need to prepare a context as in [init], we retrieve the [round_durations] from the previous state. Indeed, they are only determined by the [minimal_block_delay] and [delay_increment_per_round] constants (see {!Raw_context.prepare}), and all the constants remain unchanged during the lifetime of a protocol. As to [hard_gas_limit_per_block], it is directly a protocol constant. *) init_state ~head old_state.state_info.round_durations old_state.state_info.hard_gas_limit_per_block let manager_prio p = `Low p let consensus_prio = `High let other_prio = `Medium let get_manager_operation_gas_and_fee contents = let open Operation in let l = to_list (Contents_list contents) in List.fold_left (fun acc -> function | Contents (Manager_operation {fee; gas_limit; _}) -> ( match acc with | Error _ as e -> e | Ok (total_fee, total_gas) -> ( match Tez.(total_fee +? fee) with | Ok total_fee -> Ok (total_fee, Gas.Arith.add total_gas gas_limit) | Error _ as e -> e)) | _ -> acc) (Ok (Tez.zero, Gas.Arith.zero)) l type Environment.Error_monad.error += Fees_too_low let () = Environment.Error_monad.register_error_kind `Permanent ~id:"prefilter.fees_too_low" ~title:"Operation fees are too low" ~description:"Operation fees are too low" ~pp:(fun ppf () -> Format.fprintf ppf "Operation fees are too low") Data_encoding.unit (function Fees_too_low -> Some () | _ -> None) (fun () -> Fees_too_low) type Environment.Error_monad.error += | Manager_restriction of {oph : Operation_hash.t; fee : Tez.t} let () = Environment.Error_monad.register_error_kind `Temporary ~id:"prefilter.manager_restriction" ~title:"Only one manager operation per manager per block allowed" ~description:"Only one manager operation per manager per block allowed" ~pp:(fun ppf (oph, fee) -> Format.fprintf ppf "Only one manager operation per manager per block allowed (found %a \ with %atez fee. You may want to use --replace to provide adequate fee \ and replace it)." Operation_hash.pp oph Tez.pp fee) Data_encoding.( obj2 (req "operation_hash" Operation_hash.encoding) (req "operation_fee" Tez.encoding)) (function Manager_restriction {oph; fee} -> Some (oph, fee) | _ -> None) (fun (oph, fee) -> Manager_restriction {oph; fee}) type Environment.Error_monad.error += | Manager_operation_replaced of { old_hash : Operation_hash.t; new_hash : Operation_hash.t; } let () = Environment.Error_monad.register_error_kind `Permanent ~id:"plugin.manager_operation_replaced" ~title:"Manager operation replaced" ~description:"The manager operation has been replaced" ~pp:(fun ppf (old_hash, new_hash) -> Format.fprintf ppf "The manager operation %a has been replaced with %a" Operation_hash.pp old_hash Operation_hash.pp new_hash) (Data_encoding.obj2 (Data_encoding.req "old_hash" Operation_hash.encoding) (Data_encoding.req "new_hash" Operation_hash.encoding)) (function | Manager_operation_replaced {old_hash; new_hash} -> Some (old_hash, new_hash) | _ -> None) (fun (old_hash, new_hash) -> Manager_operation_replaced {old_hash; new_hash}) type Environment.Error_monad.error += Fees_too_low_for_mempool of Tez.t let () = Environment.Error_monad.register_error_kind `Temporary ~id:"prefilter.fees_too_low_for_mempool" ~title:"Operation fees are too low to be considered in full mempool" ~description:"Operation fees are too low to be considered in full mempool" ~pp:(fun ppf required_fees -> Format.fprintf ppf "The mempool is full, the number of prechecked manager operations has \ reached the limit max_prechecked_manager_operations set by the \ filter. Increase operation fees to at least %atz for the operation to \ be considered and propagated by THIS node. Note that the operations \ with the minimum fees in the mempool risk being removed if better \ ones are received." Tez.pp required_fees) Data_encoding.(obj1 (req "required_fees" Tez.encoding)) (function | Fees_too_low_for_mempool required_fees -> Some required_fees | _ -> None) (fun required_fees -> Fees_too_low_for_mempool required_fees) type Environment.Error_monad.error += Removed_fees_too_low_for_mempool let () = Environment.Error_monad.register_error_kind `Temporary ~id:"plugin.removed_fees_too_low_for_mempool" ~title:"Operation removed because fees are too low for full mempool" ~description:"Operation removed because fees are too low for full mempool" ~pp:(fun ppf () -> Format.fprintf ppf "The mempool is full, the number of prechecked manager operations has \ reached the limit max_prechecked_manager_operations set by the \ filter. Operation was removed because another operation with a better \ fees/gas-size ratio was received and accepted by the mempool.") Data_encoding.unit (function Removed_fees_too_low_for_mempool -> Some () | _ -> None) (fun () -> Removed_fees_too_low_for_mempool) (* TODO: https://gitlab.com/tezos/tezos/-/issues/2238 Write unit tests for the feature 'replace-by-fee' and for other changes introduced by other MRs in the plugin. *) (* In order to decide if the new operation can replace an old one from the same manager, we check if its fees (resp. fees/gas ratio) are greater than (or equal to) the old operations's fees (resp. fees/gas ratio), bumped by the factor [config.replace_by_fee_factor]. *) let better_fees_and_ratio = let bump config q = Q.mul q config.replace_by_fee_factor in fun config old_gas old_fee new_gas new_fee -> let old_fee = Tez.to_mutez old_fee |> Z.of_int64 |> Q.of_bigint in let old_gas = Gas.Arith.integral_to_z old_gas |> Q.of_bigint in let new_fee = Tez.to_mutez new_fee |> Z.of_int64 |> Q.of_bigint in let new_gas = Gas.Arith.integral_to_z new_gas |> Q.of_bigint in let old_ratio = Q.div old_fee old_gas in let new_ratio = Q.div new_fee new_gas in Q.compare new_ratio (bump config old_ratio) >= 0 && Q.compare new_fee (bump config old_fee) >= 0 let size_of_operation op = (WithExceptions.Option.get ~loc:__LOC__ @@ Data_encoding.Binary.fixed_length Tezos_base.Operation.shell_header_encoding) + Data_encoding.Binary.length Operation.protocol_data_encoding op (** Returns the weight and resources consumption of an operation. The weight corresponds to the one implemented by the baker, to decide which operations to put in a block first (the code is largely duplicated). See {!Tezos_baking_alpha.Operation_selection.weight_manager} *) let weight_and_resources_manager_operation ~hard_gas_limit_per_block ?size ~fee ~gas op = let max_size = managers_quota.max_size in let size = match size with None -> size_of_operation op | Some s -> s in let size_f = Q.of_int size in let gas_f = Q.of_bigint (Gas.Arith.integral_to_z gas) in let fee_f = Q.of_int64 (Tez.to_mutez fee) in let size_ratio = Q.(size_f / Q.of_int max_size) in let gas_ratio = Q.(gas_f / Q.of_bigint (Gas.Arith.integral_to_z hard_gas_limit_per_block)) in let resources = Q.max size_ratio gas_ratio in (Q.(fee_f / resources), resources) (** Return fee for an operation that consumes [op_resources] for its weight to be strictly greater than [min_weight]. *) let required_fee_manager_operation_weight ~op_resources ~min_weight = let req_mutez_q = Q.((min_weight * op_resources) + Q.one) in Tez.of_mutez_exn @@ Q.to_int64 req_mutez_q (** Check if an operation as a weight (fees w.r.t gas and size) large enough to be prechecked and return said weight. In the case where the prechecked mempool is full, return an error if the weight is too small, or return the operation to be replaced otherwise. *) let check_minimal_weight config state ~fee ~gas_limit op = let weight, op_resources = weight_and_resources_manager_operation ~hard_gas_limit_per_block:state.state_info.hard_gas_limit_per_block ~fee ~gas:gas_limit op in if state.ops_state.prechecked_manager_op_count < config.max_prechecked_manager_operations then (* The precheck mempool is not full yet *) `Weight_ok (`No_replace, [weight]) else match state.ops_state.min_prechecked_op_weight with | None -> (* The precheck mempool is empty *) `Weight_ok (`No_replace, [weight]) | Some {weight = min_weight; operation_hash = min_oph} -> if Q.(weight > min_weight) then (* The operation has a weight greater than the minimal prechecked operation, replace the latest with the new one *) `Weight_ok (`Replace min_oph, [weight]) else (* Otherwise fail and give indication as to what to fee should be for the operation to be prechecked *) let required_fee = required_fee_manager_operation_weight ~op_resources ~min_weight in `Fail (`Branch_delayed [Environment.wrap_tzerror (Fees_too_low_for_mempool required_fee)]) let pre_filter_manager : type t. config -> state -> Operation.packed_protocol_data -> t Kind.manager contents_list -> [ `Passed_prefilter of Q.t list | `Branch_refused of tztrace | `Branch_delayed of tztrace | `Refused of tztrace | `Outdated of tztrace ] = fun config filter_state packed_op op -> let size = size_of_operation packed_op in let check_gas_and_fee fee gas_limit = let fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez fee)) (Q.of_int 1000) in let minimal_fees_in_nanotez = Q.mul (Q.of_int64 (Tez.to_mutez config.minimal_fees)) (Q.of_int 1000) in let minimal_fees_for_gas_in_nanotez = Q.mul config.minimal_nanotez_per_gas_unit (Q.of_bigint @@ Gas.Arith.integral_to_z gas_limit) in let minimal_fees_for_size_in_nanotez = Q.mul config.minimal_nanotez_per_byte (Q.of_int size) in if Q.compare fees_in_nanotez (Q.add minimal_fees_in_nanotez (Q.add minimal_fees_for_gas_in_nanotez minimal_fees_for_size_in_nanotez)) >= 0 then `Fees_ok else `Refused [Environment.wrap_tzerror Fees_too_low] in match get_manager_operation_gas_and_fee op with | Error err -> `Refused (Environment.wrap_tztrace err) | Ok (fee, gas_limit) -> ( match check_gas_and_fee fee gas_limit with | `Refused _ as err -> err | `Fees_ok -> ( match check_minimal_weight config filter_state ~fee ~gas_limit packed_op with | `Fail errs -> errs | `Weight_ok (_, weight) -> `Passed_prefilter weight)) type Environment.Error_monad.error += Wrong_operation let () = Environment.Error_monad.register_error_kind `Temporary ~id:"prefilter.wrong_operation" ~title:"Wrong operation" ~description:"Failing_noop operations are not accepted in the mempool." ~pp:(fun ppf () -> Format.fprintf ppf "Failing_noop operations are not accepted in the mempool") Data_encoding.unit (function Wrong_operation -> Some () | _ -> None) (fun () -> Wrong_operation) type Environment.Error_monad.error += Consensus_operation_in_far_future let () = Environment.Error_monad.register_error_kind `Branch ~id:"prefilter.Consensus_operation_in_far_future" ~title:"Consensus operation in far future" ~description:"Consensus operation too far in the future are not accepted." ~pp:(fun ppf () -> Format.fprintf ppf "Consensus operation too far in the future are not accepted.") Data_encoding.unit (function Consensus_operation_in_far_future -> Some () | _ -> None) (fun () -> Consensus_operation_in_far_future) (** {2 consensus operation filtering} In Tenderbake, we increased a lot the number of consensus operations, therefore it seems necessary to be able to filter consensus operations that could be produced by a Byzantine baker mis-using its right to produce operations in future rounds or levels. We consider the situation where the head is at level [h_l], round [h_r], and with timestamp [h_ts], with the predecessor of the head being at round [hp_r]. We receive at a time [now] a consensus operation for level [op_l] and round [op_r]. A consensus operation is considered too far in the future, and therefore filtered, if the earliest possible starting time of its round is greater than the current time plus a safety margin of [config.clock_drift]. To consider potential level 2 reorgs, we first compute the expected timestamp of round zero at previous level [hp0_ts], All ops at level p_l and round r' such that time(r') is greater than (now + drift) are deemed too far in the future: h_r op_ts now+drift (h_l,r') hp0_ts h_0 h_l | | | +----+-----+---------+-------------------+--+-----+--------------+----------- | | | | | | | | h_ts h_r end time | now | earliest expected | | | | time of round r' |<----op_r rounds duration -------->| | | |<--------------- operations kept ---->|<-rejected----------... | |<-----------operations considered by the filter -----------... For an operation on a proposal at the next level, we consider the minimum starting time of the operation's round, obtained by assuming that the proposal at the next level was built on top of a proposal at round 0 for the current level, itself based on a proposal at round 0 of previous level. Operations on proposal with higher levels are treated similarly. All ops at the next level and round r' such that timestamp(r') > now+drift are deemed too far in the future. r=0 r=1 h_r now now+drift (h_l+1,r') hp0_ts h_0 h_l h_l | | | +----+---- |-------+----+---------+----------+----------+---------- | | | | | | t0 | h_ts earliest expected | | | | time of round r' |<--- | earliest| | | next level| | | |<---------------------------------->| round_offset(r') *) (** At a given level a consensus operation is acceptable if its earliest expected timestamp, [op_earliest_ts] is below the current clock with an accepted drift for the clock given by a configuration. *) let acceptable ~drift ~op_earliest_ts ~now_timestamp = Timestamp.( now_timestamp +? drift >|? fun now_drifted -> op_earliest_ts <= now_drifted) (** Check that an operation with the given [op_round], at level [op_level] is likely to be correct, meaning it could have been produced before now (+ the safety margin from configuration). Given an operation at level greater or equal than/to the current level, we compute the expected timestamp of the operation's round. If the operation is at a greater level, we assume that it is based on the proposal at round zero of the current level. All operations whose (level, round) is lower than or equal to the current head are deemed valid. Note that in case where their is a high drift in the computer clock, they might not have been considered valid by comparing their expected timestamp to the clock. This is a stricter than necessary filter as it will reject operations that could be valid in the current timeframe if the proposal they endorse is built over a predecessor of the current proposal that would be of lower round than the current one. What can we do that would be smarter: get current head's predecessor round and timestamp to compute the timestamp t0 of a predecessor that would have been proposed at round 0. Timestamp of round at current level for an alternative head that would be based on such proposal would be computed based on t0. For level higher than current head, compute the round's earliest timestamp if all proposal passed at round 0 starting from t0. *) let acceptable_op ~config ~round_durations ~round_zero_duration ~proposal_level ~proposal_round ~proposal_timestamp ~(proposal_predecessor_level_start : Timestamp.t) ~op_level ~op_round ~now_timestamp = if Raw_level.(succ op_level < proposal_level) || (op_level = proposal_level && op_round <= proposal_round) then (* Past and current round operations are not in the future *) (* This case could be handled directly in `pre_filter_far_future_consensus_ops` for a (slightly) better performance. *) Ok true else (* If, by some tolerance on local clock drift, the timestamp of the current head is itself in the future, we use this time instead of now_timestamp *) let now_timestamp = Timestamp.(max now_timestamp proposal_timestamp) in (* Computing when the current level started. *) let drift = Option.value ~default:round_zero_duration config.clock_drift in (* We compute the earliest timestamp possible [op_earliest_ts] for the operation's (level,round), as if all proposals were accepted at round 0 since the previous level. *) (* Invariant: [op_level + 1 >= proposal_level] *) let level_offset = Raw_level.(diff (succ op_level) proposal_level) in Period.mult level_offset round_zero_duration >>? fun time_shift -> Timestamp.(proposal_predecessor_level_start +? time_shift) >>? fun earliest_op_level_start -> (* computing the operations's round start from it's earliest possible level start *) Round.timestamp_of_another_round_same_level round_durations ~current_round:Round.zero ~current_timestamp:earliest_op_level_start ~considered_round:op_round >>? fun op_earliest_ts -> (* We finally check that the expected time of the operation is acceptable *) acceptable ~drift ~op_earliest_ts ~now_timestamp let pre_filter_far_future_consensus_ops config ~filter_state ({level = op_level; round = op_round; _} : consensus_content) : bool Lwt.t = let res = let open Result_syntax in let now_timestamp = Time.System.now () |> Time.System.to_protocol in let* proposal_level = Raw_level.of_int32 filter_state.state_info.head.level in acceptable_op ~config ~round_durations:filter_state.state_info.round_durations ~round_zero_duration:filter_state.state_info.round_zero_duration ~proposal_level ~proposal_round:filter_state.state_info.head_round ~proposal_timestamp:filter_state.state_info.head.timestamp ~proposal_predecessor_level_start: filter_state.state_info.grandparent_level_start ~op_level ~op_round ~now_timestamp in match res with Ok b -> Lwt.return b | Error _ -> Lwt.return_false (** A quasi infinite amount of "valid" (pre)endorsements could be sent by a committee member, one for each possible round number. This filter rejects (pre)endorsements that refer to a round that could not have been reached within the time span between the last head's timestamp and the current local clock. We add [config.clock_drift] time as a safety margin. *) let pre_filter config ~filter_state ({shell = _; protocol_data = Operation_data {contents; _} as op} : Main.operation) = let prefilter_manager_op manager_op = Lwt.return @@ match pre_filter_manager config filter_state op manager_op with | `Passed_prefilter prio -> `Passed_prefilter (manager_prio prio) | (`Branch_refused _ | `Branch_delayed _ | `Refused _ | `Outdated _) as err -> err in match contents with | Single (Failing_noop _) -> Lwt.return (`Refused [Environment.wrap_tzerror Wrong_operation]) | Single (Preendorsement consensus_content) | Single (Endorsement consensus_content) -> pre_filter_far_future_consensus_ops ~filter_state config consensus_content >>= fun keep -> if keep then Lwt.return @@ `Passed_prefilter consensus_prio else Lwt.return (`Branch_refused [Environment.wrap_tzerror Consensus_operation_in_far_future]) | Single (Dal_attestation _) | Single (Seed_nonce_revelation _) | Single (Double_preendorsement_evidence _) | Single (Double_endorsement_evidence _) | Single (Double_baking_evidence _) | Single (Activate_account _) | Single (Proposals _) | Single (Vdf_revelation _) | Single (Drain_delegate _) | Single (Ballot _) -> Lwt.return @@ `Passed_prefilter other_prio | Single (Manager_operation _) as op -> prefilter_manager_op op | Cons (Manager_operation _, _) as op -> prefilter_manager_op op (** Remove a manager operation hash from the ops_state. Do nothing if the operation was not in the state. *) let remove_operation ops_state oph = match Operation_hash.Map.find oph ops_state.prechecked_manager_ops with | None -> (* Not present in the ops_state: nothing to do. *) ops_state | Some info -> let prechecked_manager_ops = Operation_hash.Map.remove oph ops_state.prechecked_manager_ops in let prechecked_manager_op_count = ops_state.prechecked_manager_op_count - 1 in let prechecked_op_weights = ManagerOpWeightSet.remove (mk_op_weight oph info) ops_state.prechecked_op_weights in let min_prechecked_op_weight = match ops_state.min_prechecked_op_weight with | None -> None | Some min_op_weight -> if Operation_hash.equal min_op_weight.operation_hash oph then ManagerOpWeightSet.min_elt prechecked_op_weights else Some min_op_weight in { prechecked_manager_op_count; prechecked_manager_ops; prechecked_op_weights; min_prechecked_op_weight; } (** Remove a manager operation hash from the ops_state. Do nothing if the operation was not in the state. *) let remove ~filter_state oph = {filter_state with ops_state = remove_operation filter_state.ops_state oph} (** Add a manager operation hash and information to the filter state. Do nothing if the operation is already present in the state. *) let add_manager_op ops_state oph info replacement = let ops_state = match replacement with | `No_replace -> ops_state | `Replace (oph, _classification) -> remove_operation ops_state oph in if Operation_hash.Map.mem oph ops_state.prechecked_manager_ops then (* Already present in the ops_state: nothing to do. *) ops_state else let prechecked_manager_op_count = ops_state.prechecked_manager_op_count + 1 in let prechecked_manager_ops = Operation_hash.Map.add oph info ops_state.prechecked_manager_ops in let op_weight = mk_op_weight oph info in let prechecked_op_weights = ManagerOpWeightSet.add op_weight ops_state.prechecked_op_weights in let min_prechecked_op_weight = match ops_state.min_prechecked_op_weight with | Some old_min when compare_manager_op_weight old_min op_weight <= 0 -> Some old_min | _ -> Some op_weight in { prechecked_manager_op_count; prechecked_manager_ops; prechecked_op_weights; min_prechecked_op_weight; } let add_manager_op_and_enforce_mempool_bound config filter_state oph (op : 'manager_kind Kind.manager operation) = let open Lwt_result_syntax in let*? fee, gas_limit = Result.map_error (fun err -> `Refused (Environment.wrap_tztrace err)) (get_manager_operation_gas_and_fee op.protocol_data.contents) in let* replacement, weight = match check_minimal_weight config filter_state ~fee ~gas_limit (Operation_data op.protocol_data) with | `Weight_ok (`No_replace, weight) -> (* The mempool is not full: no need to replace any operation. *) return (`No_replace, weight) | `Weight_ok (`Replace min_weight_oph, weight) -> (* The mempool is full yet the new operation has enough weight to be included: the old operation with the lowest weight is reclassified as [Branch_delayed]. *) (* TODO: https://gitlab.com/tezos/tezos/-/issues/2347 The branch_delayed ring is bounded to 1000, so we may loose operations. We can probably do better. *) let replace_err = Environment.wrap_tzerror Removed_fees_too_low_for_mempool in let replacement = `Replace (min_weight_oph, `Branch_delayed [replace_err]) in return (replacement, weight) | `Fail err -> (* The mempool is full and the weight of the new operation is too low: raise the error returned by {!check_minimal_weight}. *) fail err in let weight = match weight with [x] -> x | _ -> assert false in let info = {manager_op = Manager_op op; gas_limit; fee; weight} in let ops_state = add_manager_op filter_state.ops_state oph info replacement in return ({filter_state with ops_state}, replacement) (** If the provided operation is a manager operation, add it to the filter_state. If the mempool is full, either return an error if the operation does not have enough weight to be included, or return the operation with minimal weight that gets removed to make room. Do nothing on non-manager operations. If [replace] is provided, then it is removed from [filter_state] before processing [op]. (If [replace] is a non-manager operation, this does nothing since it was never in [filter_state] to begin with.) Note that when this happens, the mempool can no longer be full after the operation has been removed, so this function always returns [`No_replace]. This function is designed to be called by the shell each time a new operation has been validated by the protocol. It will be removed in the future once the shell is able to bound the number of operations in the mempool by itself. *) let add_operation_and_enforce_mempool_bound ?replace config filter_state (oph, op) = let filter_state = match replace with | Some replace_oph -> (* If the operation to replace is not a manager operation, then it cannot be present in the [filter_state]. But then, [remove] does nothing anyway. *) remove ~filter_state replace_oph | None -> filter_state in let {protocol_data = Operation_data protocol_data; _} = op in let call_manager protocol_data = add_manager_op_and_enforce_mempool_bound config filter_state oph {shell = op.shell; protocol_data} in match protocol_data.contents with | Single (Manager_operation _) -> call_manager protocol_data | Cons (Manager_operation _, _) -> call_manager protocol_data | Single _ -> return (filter_state, `No_replace) let is_manager_operation op = match Operation.acceptable_pass op with | Some pass -> Compare.Int.equal pass Operation_repr.manager_pass | None -> false (** [conflict_handler config] returns a conflict handler for {!Mempool.add_operation} (see {!Mempool.conflict_handler}). - For non-manager operations, we select the greater operation according to {!Operation.compare}. - A manager operation is replaced only when the new operation's fee and fee/gas ratio both exceed the old operation's by at least a factor of [config.replace_by_fee_factor] (see {!better_fees_and_ratio}). Precondition: both operations must be individually valid (because of the call to {!Operation.compare}). *) let conflict_handler config : Mempool.conflict_handler = fun ~existing_operation ~new_operation -> let (_ : Operation_hash.t), old_op = existing_operation in let (_ : Operation_hash.t), new_op = new_operation in if is_manager_operation old_op && is_manager_operation new_op then let new_op_is_better = let open Result_syntax in let {protocol_data = Operation_data old_protocol_data; _} = old_op in let {protocol_data = Operation_data new_protocol_data; _} = new_op in let* old_fee, old_gas_limit = get_manager_operation_gas_and_fee old_protocol_data.contents in let* new_fee, new_gas_limit = get_manager_operation_gas_and_fee new_protocol_data.contents in return (better_fees_and_ratio config old_gas_limit old_fee new_gas_limit new_fee) in match new_op_is_better with | Ok b when b -> `Replace | Ok _ | Error _ -> `Keep else if Operation.compare existing_operation new_operation < 0 then `Replace else `Keep
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Nomadic Development. <contact@tezcore.com> *) (* Copyright (c) 2021-2022 Nomadic Labs, <contact@nomadic-labs.com> *) (* Copyright (c) 2022 TriliTech <contact@trili.tech> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
marshal.ml
type extern_flags = No_sharing | Closures | Compat_32 external to_bytes: 'a -> extern_flags list -> bytes = "caml_output_value_to_bytes" external to_string: 'a -> extern_flags list -> string = "caml_output_value_to_string" let to_channel chan v flags = output_string chan (to_string v flags) external to_buffer_unsafe: bytes -> int -> int -> 'a -> extern_flags list -> int = "caml_output_value_to_buffer" let to_buffer buff ofs len v flags = if ofs < 0 || len < 0 || ofs + len > Bytes.length buff then invalid_arg "Marshal.to_buffer: substring out of bounds" else to_buffer_unsafe buff ofs len v flags external from_channel: in_channel -> 'a = "caml_input_value" external from_bytes_unsafe: bytes -> int -> 'a = "caml_input_value_from_bytes" external data_size_unsafe: bytes -> int -> int = "caml_marshal_data_size" let header_size = 20 let data_size buff ofs = if ofs < 0 || ofs > Bytes.length buff - header_size then invalid_arg "Marshal.data_size" else data_size_unsafe buff ofs let total_size buff ofs = header_size + data_size buff ofs let from_bytes buff ofs = if ofs < 0 || ofs > Bytes.length buff - header_size then invalid_arg "Marshal.from_bytes" else begin let len = data_size_unsafe buff ofs in if ofs > Bytes.length buff - (header_size + len) then invalid_arg "Marshal.from_bytes" else from_bytes_unsafe buff ofs end let from_string buff ofs = from_bytes (Bytes.unsafe_of_string buff) ofs
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1997 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
test.ml
let try_test f () = try f () with Process.Exit.Error e -> failwith (Process.Exit.error_to_string e) module Pipes = struct let full_pipe () = let megabyte = Bytes.make (1024 * 1024) ' ' in Process.read_stdout ~stdin:megabyte "./test_megabyte_writer.native" [||] |> ignore let broken_pipe () = let megabyte = Bytes.make (1024 * 1024) ' ' in Process.read_stdout ~stdin:megabyte "./test_kilobyte_writer.native" [||] |> ignore let tests = [ "full_pipe", `Quick, try_test full_pipe; "broken_pipe", `Quick, try_test broken_pipe; ] end module Reading = struct let empty () = let output = Process.read_stdout "./test_empty_out.native" [||] in Alcotest.(check (list string)) "empty output" [] output let nl () = let output = Process.read_stdout "./test_nl_out.native" [||] in Alcotest.(check (list string)) "newline output" ["";""] output let trail_nl () = let output = Process.read_stdout "./test_trail_nl_out.native" [||] in Alcotest.(check (list string)) "trailing newline output" ["hello, world";""] output let start_nl () = let output = Process.read_stdout "./test_start_nl_out.native" [||] in Alcotest.(check (list string)) "starting newline output" [""; "hello, world"] output let interleave () = (* TODO: test the stderr, too *) let output = Process.read_stdout "./test_interleave_err_out.native" [||] in Alcotest.(check (list string)) "interleaved err and out output" ["longish"; "longerer"; "short"; ""] output let tests = [ "empty", `Quick, try_test empty; "nl", `Quick, try_test nl; "trail_nl", `Quick, try_test trail_nl; "start_nl", `Quick, try_test start_nl; "interleave", `Quick, try_test interleave; ] end let tests = [ "pipes", Pipes.tests; "reading", Reading.tests; ] ;; Alcotest.run "process" tests
(* * Copyright (c) 2016 David Sheets <sheets@alum.mit.edu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *)
a.ml
open Broken open B open C
sapling_services.ml
open Alpha_context let custom_root = (RPC_path.(open_root / "context" / "sapling") : RPC_context.t RPC_path.context) type diff_query = { offset_commitment : Int64.t option; offset_nullifier : Int64.t option; } module S = struct module Args = struct type ('query_type, 'output_type) t = { name : string; description : string; query : 'query_type RPC_query.t; output : 'output_type Data_encoding.t; f : context -> Sapling.Id.t -> 'query_type -> 'output_type tzresult Lwt.t; } let get_diff_query : diff_query RPC_query.t = let open RPC_query in query (fun offset_commitment offset_nullifier -> {offset_commitment; offset_nullifier}) |+ opt_field ~descr: "Commitments and ciphertexts are returned from the specified \ offset up to the most recent." "offset_commitment" RPC_arg.uint63 (fun {offset_commitment; _} -> offset_commitment) |+ opt_field ~descr: "Nullifiers are returned from the specified offset up to the most \ recent." "offset_nullifier" RPC_arg.uint63 (fun {offset_nullifier; _} -> offset_nullifier) |> seal let encoding = let open Data_encoding in merge_objs (obj1 (req "root" Sapling.root_encoding)) Sapling.diff_encoding let get_diff = { name = "get_diff"; description = "Returns the root and a diff of a state starting from an optional \ offset which is zero by default."; query = get_diff_query; output = encoding; f = (fun ctxt id {offset_commitment; offset_nullifier} -> Sapling.get_diff ctxt id ?offset_commitment ?offset_nullifier ()); } end let make_service Args.{name; description; query; output; f} = let path = RPC_path.(custom_root /: Sapling.rpc_arg / name) in let service = RPC_service.get_service ~description ~query ~output path in (service, fun ctxt id q () -> f ctxt id q) let get_diff = make_service Args.get_diff end let register () = let reg ~chunked (service, f) = Services_registration.register1 ~chunked service f in reg ~chunked:false S.get_diff let mk_call1 (service, _f) ctxt block id q = RPC_context.make_call1 service ctxt block id q () let get_diff ctxt block id ?offset_commitment ?offset_nullifier () = mk_call1 S.get_diff ctxt block id {offset_commitment; offset_nullifier}
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
dune
(rule (targets assets.ml) (deps (source_tree assets)) (action (run %{bin:ocaml-crunch} -m plain assets -o assets.ml))) (library (name graphql_cohttp) (public_name graphql-cohttp) (wrapped false) (libraries graphql cohttp astring base64 ocplib-endian digestif))
test_hashes.ml
open! Import open Common let root = Filename.concat "_build" "test-irmin-tezos" let conf = Irmin_pack.config ~readonly:false ~fresh:true ~index_log_size:1000 root let zero = Bytes.make 10 '0' let hash_zero = "d81e60258ecc8bd7064c8703888aececfc54e29ff94f7a2d9a84667a500548e1" let bindings steps = List.map (fun x -> ([ x ], zero)) steps let check_string ~msg ~expected ~got = let got = Hex.of_string got |> Hex.show in Alcotest.(check string) (Fmt.str "%s" msg) expected got let check_iter iter_type (iter : 'a -> (string -> unit) -> unit) v checks = let counter = ref 0 in iter v (fun x -> match List.nth_opt checks !counter with | None -> Alcotest.failf "No more calls to %s left" iter_type | Some (msg, expected) -> let msg = Fmt.str "Check %s:%s" iter_type msg in check_string ~msg ~expected ~got:x; incr counter); if !counter <> List.length checks then Alcotest.failf "More calls to %s expected" iter_type module Test (Conf : Irmin_pack.Conf.S) (Schema : Irmin.Schema.Extended with type Contents.t = bytes and type Metadata.t = unit and type Path.t = string list and type Path.step = string and type Branch.t = string and module Info = Irmin.Info.Default) = struct module Store = struct module Maker = Irmin_pack_unix.Maker (Conf) include Maker.Make (Schema) end include Store let build_tree steps = let bindings = bindings steps in let tree = Tree.empty () in let+ tree = Lwt_list.fold_left_s (fun tree (k, v) -> Tree.add tree k v) tree bindings in tree let persist_tree tree = let* repo = Repo.v conf in let* init_commit = Commit.v ~parents:[] ~info:Info.empty repo (Tree.singleton [ "singleton-step" ] (Bytes.of_string "singleton-val")) in let h = Commit.hash init_commit in let info = Info.v ~author:"Tezos" 0L in let* commit = Commit.v ~parents:[ Irmin_pack_unix.Pack_key.v_indexed h ] ~info repo tree in let tree = Commit.tree commit in Lwt.return (repo, tree, commit) let check_hardcoded_hash msg expected got = let got = (Irmin.Type.to_string Store.Hash.t) got in Alcotest.(check string) (Fmt.str "Check hardcoded hash: %s" msg) expected got end module Test_tezos_conf = struct module Store = Test (Irmin_tezos.Conf) (Irmin_tezos.Schema) module Contents = Store.Backend.Contents module Node = Store.Backend.Node module Commit = Store.Backend.Commit let hash_root_small_tree = "83722c2791a1c47dada4718656a20a2f3a063ae9945b475e67bbb6ef29d88ca4" let contents_hash () = let h0 = Contents.Hash.hash zero in let encode_bin_hash = Irmin.Type.(unstage (encode_bin Contents.Hash.t)) in encode_bin_hash h0 (fun x -> check_string ~msg:"Check encode_bin: h0" ~expected:hash_zero ~got:x); let encode_bin_val = Irmin.Type.(unstage (encode_bin Contents.Val.t)) in let checks = [ ("header of zero", "0a"); ("zero", "30303030303030303030") ] in check_iter "encode_bin" encode_bin_val zero checks; let pre_hash_val = Irmin.Type.(unstage (pre_hash Contents.Val.t)) in let checks = [ ("header of zero", "000000000000000a"); ("zero", "30303030303030303030"); ] in check_iter "pre_hash" pre_hash_val zero checks; Store.check_hardcoded_hash "contents hash" "CoWHVKM5r2eiHQxhicqakkr5FwJfabahGBwCCWzRPCNPs79CoZty" h0; Lwt.return_unit let some_steps = [ "00"; "01" ] let checks_bindings_pre_hash steps = let nb_steps = Fmt.str "%016x" (List.length steps) in let checks = List.fold_left (fun acc s -> let hex = Hex.of_string s |> Hex.show in let check_step = [ ("node type is contents", "ff00000000000000"); ("len of step ", "02"); (s, hex); ("len of contents hash", "0000000000000020"); ("hash of contents", hash_zero); ] |> List.rev in check_step @ acc) [] steps |> List.rev in ("len of values", nb_steps) :: checks let inode_values_hash () = let* tree = Store.build_tree some_steps in let* repo, tree, _ = Store.persist_tree tree in let* root_node = match Store.Tree.destruct tree with | `Contents _ -> Alcotest.fail "Expected root to be node" | `Node x -> Store.to_backend_node x in let h = Node.Hash.hash root_node in let encode_bin_hash = Irmin.Type.(unstage (encode_bin Node.Hash.t)) in encode_bin_hash h (fun x -> check_string ~msg:"Check encode_bin: node hash" ~expected:hash_root_small_tree ~got:x); let pre_hash_val = Irmin.Type.(unstage (pre_hash Node.Val.t)) in let checks = checks_bindings_pre_hash some_steps in check_iter "pre_hash" pre_hash_val root_node checks; Store.check_hardcoded_hash "node hash" "CoVeCU4o3dqmfdwqt2vh8LDz9X6qGbTUyLhgVvFReyzAvTf92AKx" h; let* () = Store.Repo.close repo in Lwt.return_unit let commit_hash () = let* tree = Store.build_tree some_steps in let* repo, _, commit = Store.persist_tree tree in let commit_val = Store.to_backend_commit commit in let h = Commit.Hash.hash commit_val in let encode_bin_hash = Irmin.Type.(unstage (encode_bin Commit.Hash.t)) in encode_bin_hash h (fun x -> check_string ~msg:"commit hash" ~expected: "c20860adda3c3d40d8d03fab22b07e889979cdac880d979711aa852a0896ae30" ~got:x); let checks = [ ("hash of root node", hash_root_small_tree); ("len of parents", "01"); ( "parent hash", "634d894802f9032ef48bbe1253563dbeb2aad7dc684da83bdea5692fde2185ae" ); ("date", "0000000000000000"); ("len of author", "05"); ("author", "54657a6f73"); ("len of message", "00"); ("message", ""); ] in let encode_bin_val = Irmin.Type.(unstage (encode_bin Commit.Val.t)) in check_iter "encode_bin" encode_bin_val commit_val checks; let checks = [ ("len of node hash", "0000000000000020"); ("hash of root node", hash_root_small_tree); ("len of parents", "0000000000000001"); ("len of parent hash", "0000000000000020"); ( "parent hash", "634d894802f9032ef48bbe1253563dbeb2aad7dc684da83bdea5692fde2185ae" ); ("date", "0000000000000000"); ("len of author", "0000000000000005"); ("author", "54657a6f73"); ("len of message", "0000000000000000"); ("message", ""); ] in let pre_hash_val = Irmin.Type.(unstage (pre_hash Commit.Val.t)) in check_iter "pre_hash" pre_hash_val commit_val checks; Store.check_hardcoded_hash "commit hash" "CoW7mALEs2vue5cfTMdJfSAjNmjmALYS1YyqSsYr9siLcNEcrvAm" h; let* () = Store.Repo.close repo in Lwt.return_unit end module Test_small_conf = struct module Conf = struct let entries = 2 let stable_hash = 3 let contents_length_header = Some `Varint let inode_child_order = `Seeded_hash let forbid_empty_dir_persistence = true end module Store = Test (Conf) (Irmin_tezos.Schema) module Node = Store.Backend.Node let many_steps = [ "00"; "01"; "02"; "03"; "04"; "05" ] let checks = [ ("inode tree", "01"); ("depth", "00"); ("len of tree", "06"); ("d", "02"); ("e", "00"); ("g", "aa670a7e66b80a4d5f0e2e35b0c7fc4fa8d3e2d62a8b90eb2ff1d184dde9d0fa"); ("b1", "01"); ( "hash ", "821707c86f7030b1102397feb88d454076ec64744dfd9811b8254bd61d396cfe" ); ] let inode_tree_hash () = let* tree = Store.build_tree many_steps in let* repo, tree, _ = Store.persist_tree tree in let* root_node = match Store.Tree.destruct tree with | `Contents _ -> Alcotest.fail "Expected root to be node" | `Node x -> Store.to_backend_node x in let h = Node.Hash.hash root_node in let pre_hash_hash = Irmin.Type.(unstage (pre_hash Node.Hash.t)) in pre_hash_hash h (fun x -> check_string ~msg:"node hash" ~expected: "e670a325ac78b2b6949b8f9fa448b17aa708ef39eb29c9e364be473f988329ea" ~got:x); let pre_hash_val = Irmin.Type.(unstage (pre_hash Node.Val.t)) in check_iter "pre_hash" pre_hash_val root_node checks; Store.check_hardcoded_hash "node hash" "CoWPo8s8h81q8skRqfPLTAJvq4ioFKS6rQhdRcY5nd6HQz2upwp4" h; let* () = Store.Repo.close repo in Lwt.return_unit end module Test_V1 = struct module Schema = struct include Irmin_tezos.Schema module Commit (Node_key : Irmin.Key.S with type hash = Hash.t) (Commit_key : Irmin.Key.S with type hash = Hash.t) = struct module M = Irmin.Commit.Generic_key.Make (Hash) (Node_key) (Commit_key) module Commit = Irmin.Commit.V1.Make (Hash) (M) include Commit end end module Store = Test (Conf) (Schema) module Commit = Store.Backend.Commit let many_steps = [ "00"; "01"; "02"; "03"; "04"; "05" ] let commit_hash () = let* tree = Store.build_tree many_steps in let* repo, _, commit = Store.persist_tree tree in let commit_val = Store.to_backend_commit commit in let checks = [ ("len of node hash", "0000000000000020"); ( "hash of root node", "3ab1c8feb08812cd1ffd8ec1ca4f861a578b700fa7dd9daab4c63d4e86638f99" ); ("len of parents", "0000000000000001"); ("len of parent hash", "0000000000000020"); ( "parent hash", "634d894802f9032ef48bbe1253563dbeb2aad7dc684da83bdea5692fde2185ae" ); ("date", "0000000000000000"); ("len of author", "0000000000000005"); ("author", "54657a6f73"); ("len of message", "0000000000000000"); ("message", ""); ] in let encode_bin_val = Irmin.Type.(unstage (encode_bin Commit.Val.t)) in check_iter "encode_bin" encode_bin_val commit_val checks; let* () = Store.Repo.close repo in Lwt.return_unit end let tests = let tc name f = Alcotest_lwt.test_case name `Quick (fun _switch -> f) in [ tc "contents hash" Test_tezos_conf.contents_hash; tc "inode_values hash" Test_tezos_conf.inode_values_hash; tc "inode_tree hash" Test_small_conf.inode_tree_hash; tc "commit hash" Test_tezos_conf.commit_hash; tc "V1 commit hash" Test_V1.commit_hash; ]
(* * Copyright (c) 2018-2022 Tarides <contact@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
storage_costs.mli
(** Cost of reading [read_bytes] at a key of length [path_length]. *) val read_access : path_length:int -> read_bytes:int -> Gas_limit_repr.cost (** Cost of performing a single write access, writing [written_bytes] bytes. *) val write_access : written_bytes:int -> Gas_limit_repr.cost
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
owl_stats_dist_dirichlet.c
#include "owl_maths.h" #include "owl_stats.h" /** Dirichlet distribution **/ static void ran_dirichlet_small (const int K, const double alpha[], double theta[]) { double norm = 0., umax = 0.; for (int i = 0; i < K; i++) { double u = log(sfmt_f64_3) / alpha[i]; theta[i] = u; if (u > umax || i == 0) umax = u; } for (int i = 0; i < K; i++) theta[i] = exp(theta[i] - umax); for (int i = 0; i < K; i++) theta[i] = theta[i] * gamma_rvs (alpha[i] + 1.0, 1.0); for (int i = 0; i < K; i++) norm += theta[i]; for (int i = 0; i < K; i++) theta[i] /= norm; } void dirichlet_rvs (const int K, const double alpha[], double theta[]) { double norm = 0.; for (int i = 0; i < K; i++) theta[i] = gamma_rvs (alpha[i], 1.); for (int i = 0; i < K; i++) norm += theta[i]; if (norm < OWL_SQRT_DOUBLE_MIN) { ran_dirichlet_small (K, alpha, theta); return; } for (int i = 0; i < K; i++) theta[i] /= norm; } double dirichlet_pdf (const int K, const double alpha[], const double theta[]) { return exp (dirichlet_logpdf (K, alpha, theta)); } double dirichlet_logpdf (const int K, const double alpha[], const double theta[]) { double log_p = 0.; double sum_alpha = 0.; for (int i = 0; i < K; i++) log_p += (alpha[i] - 1.0) * log (theta[i]); for (int i = 0; i < K; i++) sum_alpha += alpha[i]; log_p += lgam (sum_alpha); for (int i = 0; i < K; i++) log_p -= lgam (alpha[i]); return log_p; }
/* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <liang.wang@cl.cam.ac.uk> */
kobeissi_bhargavan_blanchet_intf.ml
(* Record Types *) (* ------------ *) type 't record_msg = { valid : bool [@key 1] ; mutable ephemeralKey : 't [@key 2] ; mutable initEphemeralKey : 't [@key 3] ; ciphertext : 't [@key 4] ; mutable iv : 't [@key 5] ; tag : 't [@key 6] ; preKeyId : int [@key 7] } [@@deriving protobuf] type 't record_keypair = { mutable priv : 't [@key 1] ; mutable pub : 't [@key 2] } [@@deriving protobuf] type 't record_them = { mutable signedPreKey : 't [@key 1] ; mutable signedPreKeySignature : 't [@key 2] ; mutable identityKey : 't [@key 3] ; mutable identityDHKey : 't [@key 4] ; mutable myEphemeralKeyP0 : 't record_keypair [@key 5] ; mutable myEphemeralKeyP1 : 't record_keypair [@key 6] ; mutable ephemeralKey : 't [@key 7] ; mutable myPreKey : 't record_keypair [@key 8] ; mutable preKey : 't [@key 9] ; preKeyId : int [@key 10] ; recvKeys : 't array [@key 11] ; sendKeys : 't array [@key 12] ; mutable shared : 't [@key 13] ; established : bool [@key 14] } [@@deriving protobuf] type 't record_sendoutput = { mutable them : 't record_them [@key 1] ; mutable output : 't record_msg [@key 2] } [@@deriving protobuf] type 't record_recvoutput = { mutable them : 't record_them [@key 1] ; mutable output : 't record_msg [@key 2] ; plaintext : 't [@key 3] } [@@deriving protobuf] type 't record_ratchetsendkeys = { sendKeys : 't array [@key 1] ; kENC : 't [@key 2] } [@@deriving protobuf] type 't record_ratchetrecvkeys = { recvKeys : 't array [@key 1] ; kENC : 't [@key 2] } [@@deriving protobuf] (* Module Types *) (* ------------ *) (* Note: The full signature does not need to be specified. Instead, only the parts that we want users to see should be part of this signature. *) (** The KBB2017 protocol *) module type PROTOCOL = sig (** The type that will be used to represent contiguous bytes in the protocol; typically Bytes.t or Cstruct.t *) type t (** An internal type representing a decrypted AES message *) type t_aes_decrypted (** Entry point for sending and receiving messages while maintaining a KBB2017 session. *) module TOPLEVEL : sig val newSession : t record_keypair -> t record_keypair -> t -> t -> t -> t -> t -> int -> t record_them (** [newSession mySignedPreKey myPreKey theirIdentityKeyPub theirIdentityDHKeyPub theirSignedPreKeyPub theirSignedPreKeySignature theirPreKeyPub preKeyId] creates a KBB2017 session from "my" prekeys and "their" public information while consuming a one-time pre-key [preKeyId]. Using nomenclature from the KBB2017 paper, the expectation is that the "their" party has published their long-term Diffie-Hellman public key [theirIdentityDHKeyPub] and a set of ephemeral Diffie-Hellman public keys ([theirSignedPreKeyPub] and [theirPreKeyPub]) called "pre-keys" to a common server or other shared location. The pre-keys include both signed pre-keys [mySignedPreKey], which can be reused for some period of time, and non-signed, one-time pre-keys ([myPreKey] and their [preKeyId]), which are fresh at each session. *) val send : t record_keypair -> t record_them -> t -> t record_sendoutput (** [send myIdentityKey them plaintext] sends a [plaintext] message to [them] authenticated by [myIdentityKey]. *) val recv : t record_keypair -> t record_keypair -> t record_them -> t record_msg -> t record_recvoutput (** [recv myIdentityKey mySignedPreKey them msg] receives an encrypted message [msg] that was ostensibly obtained from [them] and verifies that it was sent to the session both established with a pre-key signed with [mySignedPreKey] and authenticated with [myIdentityKey]. @return a {!record_recvoutput} that, if and only if [return_value.output.valid] is true, will have valid plaintext *) end (** A private or public key *) module Type_key : sig val construct : unit -> t (** Create a key *) val toBitstring : t -> t val fromBitstring : t -> t val xassert : t -> t (** Verify that the object is a valid key object. @raise Invalid_argument when the object is not a valid key object. *) val clone : t -> t end (** An initialization vector *) module Type_iv : sig val construct : unit -> t (** Create an initialization vector *) val toBitstring : t -> t val fromBitstring : t -> t val xassert : t -> t (** Verify that the object is a valid iv object. @raise Invalid_argument when the object is not a valid iv object. *) end (** A message *) module Type_msg : sig val construct : unit -> t record_msg (** Create a message *) val xassert : t record_msg -> t record_msg (** Verify that the object is a valid record_msg object. @raise Invalid_argument when the object is not a valid record_msg object. *) end (** A public and private keypair *) module Type_keypair : sig val construct : unit -> t record_keypair (** Create a keypair *) val xassert : t record_keypair -> t record_keypair (** Verify that the object is a valid record_keypair object. @raise Invalid_argument when the object is not a valid record_keypair object. *) val clone : t record_keypair -> t record_keypair end (** A session tracking the other party in a conversation *) module Type_them : sig val construct : unit -> t record_them (** Create a record of a session with another party *) val xassert : t record_them -> t record_them (** Verify that the object is a valid record_them object. @raise Invalid_argument when the object is not a valid record_them object. *) end (** The updates to your record of the other party {e that should be persisted} after sending a message *) module Type_sendoutput : sig val construct : unit -> t record_sendoutput (** Create a sendoutput object *) val xassert : t record_sendoutput -> t record_sendoutput (** Verify that the object is a valid sendoutput object. @raise Invalid_argument when the object is not a valid sendoutput object. *) end (** The updates to your record of the other party {e that should be persisted} after receiving a message *) module Type_recvoutput : sig val construct : unit -> t record_recvoutput (** Create a recvoutput object *) val xassert : t record_recvoutput -> t record_recvoutput (** Verify that the object is a valid recvoutput object. @raise Invalid_argument when the object is not a valid recvoutput object. *) end (** Cryptographic helpers used in KBB2017 *) module UTIL : sig val xHKDF : t -> t -> t -> t array (** [xHKDF ikm salt info] extracts a pseudo-random key from the input keying material [ikm] and a [salt] and expands it to derive two derivative keys from an optional application- and context-specific [info] using the {{:https://tools.ietf.org/html/rfc5869} RFC 5869 HMAC-based Extract-and-Expand Key Derivation Function} construction. @return an array [ [| k0; k1 |] ] where [k0] is the derivative key from the first expansion and [k1] is the derivative key from the second expansion *) val xQDHInit : t -> t -> t -> t -> t -> t (** [xQDHInit myIdentityKeyPriv myInitEphemeralKeyPriv theirIdentityKeyPub theirSignedPreKeyPub theirPreKeyPub] performs the {{:https://signal.org/docs/specifications/x3dh/#sending-the-initial-message} quad Diffie-Helman construction for "Sending the initial message" of the X3DH Key Agreement Protocol}. *) val xQDHResp : t -> t -> t -> t -> t -> t (** [xQDHInit myIdentityKeyPriv mySignedPreKeyPriv myPreKeyPriv theirIdentityKeyPub theirEphemeralKeyPub] performs the {{:https://signal.org/docs/specifications/x3dh/#receiving-the-initial-message} quad Diffie-Helman construction for "Receiving the initial message" of the X3DH Key Agreement Protocol}. *) val newIdentityKey : t -> t record_keypair (** [newIdentityKey id] creates a key pair with a randomly initialized 32 byte private key and its 32 bytes ED25519 public key. [id] will be ignored for a true random number generator. But [id] may be used for mock random number generators or pseudo random generators to provide repeatability. *) val newKeyPair : t -> t record_keypair (** [newKeyPair id] creates a key pair with a randomly initialized 32 byte private key and its 32 byte DH25519 (aka x25519) public key. [id] will be ignored for a true random number generator. But [id] may be used for mock random number generators or pseudo random generators to provide repeatability. *) val getDHPublicKey : t -> t (** [getDHPublicKey priv] gives the DH25519 public key corresponding to the private key [priv] *) end (** Double Ratchet algorithm *) module RATCHET : sig val deriveSendKeys : t record_them -> t -> t record_ratchetsendkeys val deriveRecvKeys : t -> t record_them -> t -> t record_ratchetrecvkeys val tryDecrypt : t record_keypair -> t record_keypair -> t record_them -> t record_msg -> t_aes_decrypted end (** KBB2017 session update logic *) module HANDLE : sig val xAKENeeded : t record_keypair -> t record_keypair -> t record_them -> t record_them val xAKEInit : t record_keypair -> t record_keypair -> t record_them -> t record_msg -> t record_them val sending : t record_keypair -> t record_them -> t -> t -> t record_sendoutput val receiving : t record_keypair -> t record_them -> t record_msg -> t record_recvoutput end end module type PROTOCOLFUNCTOR = functor (ProScript : Dirsp_proscript.S) -> PROTOCOL with type t = ProScript.t module type PROTOCOLMODULE = sig module Make : PROTOCOLFUNCTOR end
(* Copyright 2021 Diskuv, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *)
diffing.mli
(** Parametric diffing This module implements diffing over lists of arbitrary content. It is parameterized by - The content of the two lists - The equality witness when an element is kept - The diffing witness when an element is changed Diffing is extended to maintain state depending on the computed changes while walking through the two lists. The underlying algorithm is a modified Wagner-Fischer algorithm (see <https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm>). We provide the following guarantee: Given two lists [l] and [r], if different patches result in different states, we say that the state diverges. - We always return the optimal patch on prefixes of [l] and [r] on which state does not diverge. - Otherwise, we return a correct but non-optimal patch where subpatches with no divergent states are optimal for the given initial state. More precisely, the optimality of Wagner-Fischer depends on the property that the edit-distance between a k-prefix of the left input and a l-prefix of the right input d(k,l) satisfies d(k,l) = min ( del_cost + d(k-1,l), insert_cost + d(k,l-1), change_cost + d(k-1,l-1) ) Under this hypothesis, it is optimal to choose greedily the state of the minimal patch transforming the left k-prefix into the right l-prefix as a representative of the states of all possible patches transforming the left k-prefix into the right l-prefix. If this property is not satisfied, we can still choose greedily a representative state. However, the computed patch is no more guaranteed to be globally optimal. Nevertheless, it is still a correct patch, which is even optimal among all explored patches. *) (** The core types of a diffing implementation *) module type Defs = sig type left type right type eq (** Detailed equality trace *) type diff (** Detailed difference trace *) type state (** environment of a partial patch *) end (** The kind of changes which is used to share printing and styling across implementation*) type change_kind = | Deletion | Insertion | Modification | Preservation val prefix: Format.formatter -> (int * change_kind) -> unit val style: change_kind -> Misc.Color.style list type ('left,'right,'eq,'diff) change = | Delete of 'left | Insert of 'right | Keep of 'left * 'right *' eq | Change of 'left * 'right * 'diff val classify: _ change -> change_kind (** [Define(Defs)] creates the diffing types from the types defined in [Defs] and the functors that need to be instantatied with the diffing algorithm parameters *) module Define(D:Defs): sig open D (** The type of potential changes on a list. *) type nonrec change = (left,right,eq,diff) change type patch = change list (** A patch is an ordered list of changes. *) module type Parameters = sig type update_result val weight: change -> int (** [weight ch] returns the weight of the change [ch]. Used to find the smallest patch. *) val test: state -> left -> right -> (eq, diff) result (** [test st xl xr] tests if the elements [xl] and [xr] are co mpatible ([Ok]) or not ([Error]). *) val update: change -> state -> update_result (** [update ch st] returns the new state after applying a change. The [update_result] type also contains expansions in the variadic case. *) end module type S = sig val diff: state -> left array -> right array -> patch (** [diff state l r] computes the optimal patch between [l] and [r], using the initial state [state]. *) end module Simple: (Parameters with type update_result := state) -> S (** {1 Variadic diffing} Variadic diffing allows to expand the lists being diffed during diffing. in one specific direction. *) module Left_variadic: (Parameters with type update_result := state * left array) -> S module Right_variadic: (Parameters with type update_result := state * right array) -> S end
(**************************************************************************) (* *) (* OCaml *) (* *) (* Gabriel Radanne, projet Cambium, Inria Paris *) (* *) (* Copyright 2020 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
connection_cache.ml
exception Retry = Connection.Retry (** This functor establishes a new connection for each request. *) module Make_no_cache (Connection : S.Connection) : sig include S.Connection_cache val create : ?ctx:Connection.Net.ctx -> unit -> t (** [create ?ctx ()] creates a connection for handling a single request. The connection accepts only a single request and will automatically be closed as soon as possible. @param ctx See {Connection.Net.ctx} *) end = struct module Net = Connection.Net module IO = Net.IO open IO type t = S.call let call = Fun.id let create ?(ctx = Net.default_ctx) () ?headers ?body meth uri = Net.resolve ~ctx uri (* TODO: Support chunked encoding without ~persistent:true ? *) >>= Connection.connect ~ctx ~persistent:true >>= fun connection -> let res = Connection.call connection ?headers ?body meth uri in (* this can be simplified when https://github.com/mirage/ocaml-conduit/pull/319 is released. *) Lwt.async (fun () -> res >>= fun (_, body) -> (match body with | `Empty | `String _ | `Strings _ -> Lwt.return_unit | `Stream stream -> Lwt_stream.closed stream) >>= fun () -> Connection.close connection; Lwt.return_unit); res end (** This functor keeps a cache of connecions for reuse. Connections are reused based on their remote {!type:Conduit.endp} (effectively IP / port). *) module Make (Connection : S.Connection) (Sleep : S.Sleep) : sig include S.Connection_cache val create : ?ctx:Connection.Net.ctx -> ?keep:int64 -> ?retry:int -> ?parallel:int -> ?depth:int -> unit -> t (** Create a new connection cache @param ctx Conduit context to use. See {!type:Connection.Net.ctx}. @param keep Number of nanoseconds to keep an idle connection around. @param retry Number of times a {e gracefully} failed request is automatically retried. {e graceful} means failed with {!exception:Connection.Retry}. Requests with a [`Stream] {!module:Body} cannot be retried automatically. Such requests will fail with {!exception:Connection.Retry} and a new {!module:Body} will need to be provided to retry. @param parallel maximum number of connections to establish to a single endpoint. Beware: A single hostname may resolve to multiple endpoints. In such a case connections may be created in excess to what was intended. @param depth maximum number of requests to queue and / or send on a single connection. *) end = struct module Net = Connection.Net module IO = Net.IO open IO type ctx = Net.ctx type t = { cache : (Net.endp, Connection.t) Hashtbl.t; ctx : ctx; keep : int64; retry : int; parallel : int; depth : int; } let create ?(ctx = Net.default_ctx) ?(keep = 60_000_000_000L) ?(retry = 2) ?(parallel = 4) ?(depth = 100) () = { cache = Hashtbl.create ~random:true 10; ctx; keep; retry; parallel; depth; } let rec get_connection self endp = let finalise connection = let rec remove keep = let current = Hashtbl.find self.cache endp in Hashtbl.remove self.cache endp; if current == connection then List.iter (Hashtbl.add self.cache endp) keep else remove (current :: keep) in remove []; Lwt.return_unit in let create () = let connection = Connection.create ~finalise ~ctx:self.ctx endp and timeout = ref Lwt.return_unit in let rec busy () = Lwt.cancel !timeout; if Connection.length connection = 0 then ( timeout := Sleep.sleep_ns self.keep >>= fun () -> Connection.close connection; (* failure is ignored *) Lwt.return_unit); Lwt.on_termination (Connection.notify connection) busy in busy (); connection in match Hashtbl.find_all self.cache endp with | [] -> let connection = create () in Hashtbl.add self.cache endp connection; Lwt.return connection | conns -> ( let rec search length = function | [ a ] -> (a, length + 1) | a :: b :: tl when Connection.length a < Connection.length b -> search (length + 1) (a :: tl) | _ :: tl -> search (length + 1) tl | [] -> assert false in match search 0 conns with | shallowest, _ when Connection.length shallowest = 0 -> Lwt.return shallowest | _, length when length < self.parallel -> let connection = create () in Hashtbl.add self.cache endp connection; Lwt.return connection | shallowest, _ when Connection.length shallowest < self.depth -> Lwt.return shallowest | _ -> Lwt.try_bind (fun () -> Lwt.choose (List.map Connection.notify conns)) (fun _ -> get_connection self endp) (fun _ -> get_connection self endp)) let call self ?headers ?body meth uri = Net.resolve ~ctx:self.ctx uri >>= fun endp -> let rec request retry = get_connection self endp >>= fun conn -> Lwt.catch (fun () -> Connection.call conn ?headers ?body meth uri) (function | Retry -> ( match body with | Some (`Stream _) -> Lwt.fail Retry | None | Some `Empty | Some (`String _) | Some (`Strings _) -> if retry <= 0 then Lwt.fail Retry else request (retry - 1)) | e -> Lwt.fail e) in request self.retry end
t-reconstruct_fmpz.c
#include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpq.h" int main(void) { int i; FLINT_TEST_INIT(state); flint_printf("reconstruct_fmpz...."); fflush(stdout); for (i = 0; i < 1000*flint_test_multiplier(); i++) { int result; fmpq_t x, y; fmpz_t mod; fmpz_t res; mpz_t tmp; fmpq_init(x); fmpq_init(y); fmpz_init(mod); fmpz_init(res); mpz_init(tmp); fmpq_randtest(x, state, 1000); /* Modulus m > 2*max(|n|,d)^2 */ if (fmpz_cmpabs(&x->num, &x->den) >= 0) fmpz_mul(mod, &x->num, &x->num); else fmpz_mul(mod, &x->den, &x->den); fmpz_mul_2exp(mod, mod, 1); do fmpz_add_ui(mod, mod, 1); while (!fmpq_mod_fmpz(res, x, mod)); result = fmpq_reconstruct_fmpz(y, res, mod); if (!result || !fmpq_equal(x, y)) { flint_printf("FAIL: reconstruction failed\n"); flint_printf("input = "); fmpq_print(x); flint_printf("\nmodulus = "); fmpz_print(mod); flint_printf("\nresidue = "); fmpz_print(res); flint_printf("\nreconstructed = "); fmpq_print(y); flint_printf("\nfmpq_reconstruct_fmpz return value = %d", result); flint_printf("\n"); fflush(stdout); flint_abort(); } fmpq_clear(x); fmpq_clear(y); fmpz_clear(mod); fmpz_clear(res); mpz_clear(tmp); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2011 Fredrik Johansson Copyright (C) 2020 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
a.ml
let x=2
pixel.ml
type 'a t = 'a Color.t * floatarray let empty (type c) color = let (module C : Color.COLOR with type t = c) = color in let p = Float.Array.make (C.channels C.t) 0.0 in (color, p) let v color values = assert (Color.channels color = List.length values); (color, Float.Array.of_list values) let fill (_, px) x = Float.Array.fill px 0 (Float.Array.length px) x let length (_color, p) = Float.Array.length p let compare a b = if a < b then -1 else if a > b then 1 else 0 let equal (_, a) (_, b) = let result = ref true in Float.Array.iter2 (fun a b -> result := !result && Float.equal a b) a b; !result let get (_, a) = Float.Array.get a let set (_, a) = Float.Array.set a let to_rgb (type color) (color, a) : Color.rgb t = let (module C : Color.COLOR with type t = color) = color in ((module Color.Rgb : Color.COLOR with type t = Color.rgb), C.to_rgb C.t a) let of_rgb (type color) color (_rgb, a) = let (module C : Color.COLOR with type t = color) = color in (color, C.of_rgb C.t a) let of_data (type a b) color data = let len = Data.length data in let px = empty color in let (module T : Type.TYPE with type t = a and type elt = b) = Data.ty data in for i = 0 to len - 1 do set px i T.(to_float data.{i} |> Type.normalize (module T)) done; px let to_data ~dest px = let len = Data.length dest in let ty = Data.ty dest in for i = 0 to min len (length px) - 1 do dest.{i} <- Type.(of_float ty (denormalize ty (get px i))) done let data (_, px) = px let color (c, _) = c let iter f px = Float.Array.iteri f (data px) let map_inplace ?(ignore_alpha = true) f px = let color = color px in let alpha = if ignore_alpha && Color.has_alpha color then Color.channels color - 1 else -1 in Float.Array.iteri (fun i x -> if i <> alpha then set px i (f x)) (data px); px let map2_inplace ?(ignore_alpha = true) f px px' = let color = color px in let alpha = if ignore_alpha && Color.has_alpha color then Color.channels color - 1 else -1 in Float.Array.iteri (fun i x -> if i <> alpha then set px i (f x (get px' i))) (data px); px let map ?ignore_alpha f (color, px) = let dest = (color, Float.Array.copy px) in map_inplace ?ignore_alpha f dest let clamp (x : 'a t) : 'a t = map_inplace ~ignore_alpha:false (fun x -> Type.clamp Type.f32 x) x let fold ?(ignore_alpha = true) f (color, px) a = let alpha = if ignore_alpha && Color.has_alpha color then Color.channels color - 1 else -1 in let index = ref 0 in Float.Array.fold_left (fun a b -> let i = !index in incr index; if i <> alpha then f b a else a) a px let pp fmt px = let len = length px - 1 in Format.fprintf fmt "Pixel("; for p = 0 to len do let () = Format.fprintf fmt "%f" (get px p) in if p < len then Format.fprintf fmt "," done; Format.fprintf fmt ")" module Infix = struct let ( + ) a b = map2_inplace ( +. ) a b let ( - ) a b = map2_inplace ( -. ) a b let ( * ) a b = map2_inplace ( *. ) a b let ( / ) a b = map2_inplace ( /. ) a b let ( +@ ) a b = map_inplace (fun a -> a +. b) a let ( -@ ) a b = map_inplace (fun a -> a -. b) a let ( *@ ) a b = map_inplace (fun a -> a *. b) a let ( /@ ) a b = map_inplace (fun a -> a /. b) a end
storage_description.ml
module StringMap = Map.Make (String) type 'key t = 'key desc_with_path (** [desc_with_path] describes a position in the storage. It's composed [rev_path] which is the reverse path up to the position, and [dir] the position's [description]. [rev_path] is only useful in case of an error to print a descriptive message. [List.rev rev_path] is a storage's path that contains no conflict and allows the registration of a [dir]'s storage. NB: [rev_path] indicates the position in the tree, so once the node is added, it won't change; whereas [dir] is mutable because when more subtrees are added this may require updating it. *) and 'key desc_with_path = { rev_path : string list; mutable dir : 'key description; } and 'key description = | Empty : 'key description | Value : { get : 'key -> 'a option tzresult Lwt.t; encoding : 'a Data_encoding.t; } -> 'key description | NamedDir : 'key t StringMap.t -> 'key description | IndexedDir : { arg : 'a RPC_arg.t; arg_encoding : 'a Data_encoding.t; list : 'key -> 'a list tzresult Lwt.t; subdir : ('key * 'a) t; } -> 'key description let[@coq_struct "function_parameter"] rec pp : type a. Format.formatter -> a t -> unit = fun ppf {dir; _} -> match dir with | Empty -> Format.fprintf ppf "Empty" | Value _e -> Format.fprintf ppf "Value" | NamedDir map -> Format.fprintf ppf "@[<v>%a@]" (Format.pp_print_list pp_item) (StringMap.bindings map) | IndexedDir {arg; subdir; _} -> let name = Format.asprintf "<%s>" (RPC_arg.descr arg).name in pp_item ppf (name, subdir) and[@coq_mutual_as_notation] pp_item : type a. Format.formatter -> string * a t -> unit = fun ppf (name, desc) -> Format.fprintf ppf "@[<hv 2>%s@ %a@]" name pp desc let pp_rev_path ppf path = Format.fprintf ppf "[%a]" Format.( pp_print_list ~pp_sep:(fun ppf () -> pp_print_string ppf " / ") pp_print_string) (List.rev path) let rec register_named_subcontext : type r. r t -> string list -> r t = fun desc names -> match (desc.dir, names) with | (_, []) -> desc | (Value _, _) | (IndexedDir _, _) -> Format.kasprintf invalid_arg "Could not register a named subcontext at %a because of an existing %a." pp_rev_path desc.rev_path pp desc | (Empty, name :: names) -> let subdir = {rev_path = name :: desc.rev_path; dir = Empty} in desc.dir <- NamedDir (StringMap.singleton name subdir) ; register_named_subcontext subdir names | (NamedDir map, name :: names) -> let subdir = match StringMap.find name map with | Some subdir -> subdir | None -> let subdir = {rev_path = name :: desc.rev_path; dir = Empty} in desc.dir <- NamedDir (StringMap.add name subdir map) ; subdir in register_named_subcontext subdir names type (_, _, _) args = | One : { rpc_arg : 'a RPC_arg.t; encoding : 'a Data_encoding.t; compare : 'a -> 'a -> int; } -> ('key, 'a, 'key * 'a) args | Pair : ('key, 'a, 'inter_key) args * ('inter_key, 'b, 'sub_key) args -> ('key, 'a * 'b, 'sub_key) args let rec unpack : type a b c. (a, b, c) args -> c -> a * b = function | One _ -> fun x -> x | Pair (l, r) -> let unpack_l = unpack l in let unpack_r = unpack r in fun x -> let (c, d) = unpack_r x in let (b, a) = unpack_l c in (b, (a, d)) [@@coq_axiom_with_reason "gadt"] let rec pack : type a b c. (a, b, c) args -> a -> b -> c = function | One _ -> fun b a -> (b, a) | Pair (l, r) -> let pack_l = pack l in let pack_r = pack r in fun b (a, d) -> let c = pack_l b a in pack_r c d [@@coq_axiom_with_reason "gadt"] let rec compare : type a b c. (a, b, c) args -> b -> b -> int = function | One {compare; _} -> compare | Pair (l, r) -> ( let compare_l = compare l in let compare_r = compare r in fun (a1, b1) (a2, b2) -> match compare_l a1 a2 with 0 -> compare_r b1 b2 | x -> x) [@@coq_axiom_with_reason "gadt"] let destutter equal l = match l with | [] -> [] | (i, _) :: l -> let rec loop acc i = function | [] -> acc | (j, _) :: l -> if equal i j then loop acc i l else loop (j :: acc) j l in loop [i] i l let rec register_indexed_subcontext : type r a b. r t -> list:(r -> a list tzresult Lwt.t) -> (r, a, b) args -> b t = fun desc ~list path -> match path with | Pair (left, right) -> let compare_left = compare left in let equal_left x y = Compare.Int.(compare_left x y = 0) in let list_left r = list r >|=? fun l -> destutter equal_left l in let list_right r = let (a, k) = unpack left r in list a >|=? fun l -> List.map snd (List.filter (fun (x, _) -> equal_left x k) l) in register_indexed_subcontext (register_indexed_subcontext desc ~list:list_left left) ~list:list_right right | One {rpc_arg = arg; encoding = arg_encoding; _} -> ( match desc.dir with | Value _ | NamedDir _ -> Format.kasprintf invalid_arg "Could not register an indexed subcontext at %a because of an \ existing %a." pp_rev_path desc.rev_path pp desc | Empty -> let subdir = { rev_path = Format.sprintf "(Maybe of %s)" RPC_arg.(descr arg).name :: desc.rev_path; dir = Empty; } in desc.dir <- IndexedDir {arg; arg_encoding; list; subdir} ; subdir | IndexedDir {arg = inner_arg; subdir; _} -> ( match RPC_arg.eq arg inner_arg with | None -> Format.kasprintf invalid_arg "An indexed subcontext at %a already exists but has a \ different argument: `%s` <> `%s`." pp_rev_path desc.rev_path (RPC_arg.descr arg).name (RPC_arg.descr inner_arg).name | Some RPC_arg.Eq -> subdir)) [@@coq_axiom_with_reason "gadt"] let register_value : type a b. a t -> get:(a -> b option tzresult Lwt.t) -> b Data_encoding.t -> unit = fun desc ~get encoding -> match desc.dir with | Empty -> desc.dir <- Value {get; encoding} | _ -> Format.kasprintf invalid_arg "Could not register a value at %a because of an existing %a." pp_rev_path desc.rev_path pp desc let create () = {rev_path = []; dir = Empty} module type INDEX = sig type t include Path_encoding.S with type t := t val rpc_arg : t RPC_arg.t val encoding : t Data_encoding.t val compare : t -> t -> int end type _ handler = | Handler : { encoding : 'a Data_encoding.t; get : 'key -> int -> 'a tzresult Lwt.t; } -> 'key handler type _ opt_handler = | Opt_handler : { encoding : 'a Data_encoding.t; get : 'key -> int -> 'a option tzresult Lwt.t; } -> 'key opt_handler let rec combine_object = function | [] -> Handler {encoding = Data_encoding.unit; get = (fun _ _ -> return_unit)} | (name, Opt_handler handler) :: fields -> let (Handler handlers) = combine_object fields in Handler { encoding = Data_encoding.merge_objs Data_encoding.(obj1 (opt name (dynamic_size handler.encoding))) handlers.encoding; get = (fun k i -> handler.get k i >>=? fun v1 -> handlers.get k i >|=? fun v2 -> (v1, v2)); } [@@coq_axiom_with_reason "gadt"] type query = {depth : int} let depth_query = let open RPC_query in query (fun depth -> {depth}) |+ field "depth" RPC_arg.uint 0 (fun t -> t.depth) |> seal let build_directory : type key. key t -> key RPC_directory.t = fun dir -> let rpc_dir = ref (RPC_directory.empty : key RPC_directory.t) in let register : type ikey. chunked:bool -> (key, ikey) RPC_path.t -> ikey opt_handler -> unit = fun ~chunked path (Opt_handler {encoding; get}) -> let service = RPC_service.get_service ~query:depth_query ~output:encoding path in rpc_dir := RPC_directory.opt_register ~chunked !rpc_dir service (fun k q () -> get k (q.depth + 1)) in let rec build_handler : type ikey. ikey t -> (key, ikey) RPC_path.t -> ikey opt_handler = fun desc path -> match desc.dir with | Empty -> Opt_handler {encoding = Data_encoding.unit; get = (fun _ _ -> return_none)} | Value {get; encoding} -> let handler = Opt_handler { encoding; get = (fun k i -> if Compare.Int.(i < 0) then return_none else get k); } in register ~chunked:true path handler ; handler | NamedDir map -> let fields = StringMap.bindings map in let fields = List.map (fun (name, dir) -> (name, build_handler dir RPC_path.(path / name))) fields in let (Handler handler) = combine_object fields in let handler = Opt_handler { encoding = handler.encoding; get = (fun k i -> if Compare.Int.(i < 0) then return_none else handler.get k (i - 1) >>=? fun v -> return_some v); } in register ~chunked:true path handler ; handler | IndexedDir {arg; arg_encoding; list; subdir} -> let (Opt_handler handler) = build_handler subdir RPC_path.(path /: arg) in let encoding = let open Data_encoding in union [ case (Tag 0) ~title:"Leaf" (dynamic_size arg_encoding) (function (key, None) -> Some key | _ -> None) (fun key -> (key, None)); case (Tag 1) ~title:"Dir" (tup2 (dynamic_size arg_encoding) (dynamic_size handler.encoding)) (function (key, Some value) -> Some (key, value) | _ -> None) (fun (key, value) -> (key, Some value)); ] in let get k i = if Compare.Int.(i < 0) then return_none else if Compare.Int.(i = 0) then return_some [] else list k >>=? fun keys -> List.map_es (fun key -> if Compare.Int.(i = 1) then return (key, None) else handler.get (k, key) (i - 1) >|=? fun value -> (key, value)) keys >>=? fun values -> return_some values in let handler = Opt_handler {encoding = Data_encoding.(list (dynamic_size encoding)); get} in register ~chunked:true path handler ; handler in ignore (build_handler dir RPC_path.open_root : key opt_handler) ; !rpc_dir [@@coq_axiom_with_reason "gadt"]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
Main.ml
open Monolith module R = Reference module C = Candidate (* -------------------------------------------------------------------------- *) (* Define [element -> element -> int] as a constructible type, whose generator chooses between two ordering functions, namely [compare] and [flip compare]. *) let ordering = constructible (fun () -> if Gen.bool() then compare, constant "compare" else (fun x y -> compare y x), constant "(fun x y -> compare y x)" ) (* -------------------------------------------------------------------------- *) (* Declare the operations. *) let () = let spec = ordering ^> list ~length:(Gen.lt 8) (lt 32) ^> list int in declare "sort" spec R.sort C.sort (* -------------------------------------------------------------------------- *) (* Start the engine! *) let () = let fuel = 1 in (* in this particular case, one operation suffices *) main fuel
(******************************************************************************) (* *) (* Monolith *) (* *) (* François Pottier *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU Lesser General Public License as published by the Free *) (* Software Foundation, either version 3 of the License, or (at your *) (* option) any later version, as described in the file LICENSE. *) (* *) (******************************************************************************)
describeSpotInstanceRequests.mli
open Types type input = DescribeSpotInstanceRequestsRequest.t type output = DescribeSpotInstanceRequestsResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
RPC_answer.mli
(** Return type for service handler *) type 'o t = [ `Ok of 'o (* 200 *) | `OkChunk of 'o (* 200 but send answer as chunked transfer encoding *) | `OkStream of 'o stream (* 200 *) | `Created of string option (* 201 *) | `No_content (* 204 *) | `Unauthorized of error list option (* 401 *) | `Forbidden of error list option (* 403 *) | `Not_found of error list option (* 404 *) | `Conflict of error list option (* 409 *) | `Error of error list option (* 500 *) ] and 'a stream = {next : unit -> 'a option Lwt.t; shutdown : unit -> unit} val return : 'o -> 'o t Lwt.t (** [return_chunked] is identical to [return] but it indicates to the server that the result might be long and that the serialisation should be done in mutliple chunks. You should use [return_chunked] when returning an (unbounded or potentially large) list, array, map, or other such set. *) val return_chunked : 'o -> 'o t Lwt.t val return_stream : 'o stream -> 'o t Lwt.t val not_found : 'o t Lwt.t val fail : error list -> 'a t Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
fdo.ml
open Import module CC = Compilation_context type phase = | All | Compile | Emit let linear_ext = ".cmir-linear" let linear_fdo_ext = linear_ext ^ "-fdo" let fdo_profile s = Path.extend_basename s ~suffix:".fdo-profile" let linker_script s = Path.extend_basename s ~suffix:".linker-script" let phase_flags = function | None -> [] | Some All -> [ "-g"; "-function-sections" ] | Some Compile -> [ "-g"; "-stop-after"; "scheduling"; "-save-ir-after"; "scheduling" ] | Some Emit -> [ "-g"; "-start-from"; "emit"; "-function-sections" ] (* CR-soon gyorsh: add a rule to use profile with c/cxx profile if available, similarly to opt_rule for ocaml modules. The profile will have to be generated externally from perf data for example using google's autofdo toolset: create_gcov for gcc or create_llvm_prof for llvm. *) let c_flags (ctx : Context.t) = match ctx.fdo_target_exe with | None -> [] | Some _ -> [ "-ffunction-sections" ] let cxx_flags = c_flags (* Location of ocamlfdo binary tool is independent of the module, but may depend on the context. *) let ocamlfdo_binary sctx dir = Super_context.resolve_program sctx ~dir ~loc:None "ocamlfdo" ~hint:"opam install ocamlfdo" (* FDO flags are context dependent. *) let get_flags var = let f (ctx : Context.t) = Env.get ctx.env var |> Option.value ~default:"" |> String.extract_blank_separated_words |> Memo.return in let memo = Memo.create var ~input:(module Context) ~cutoff:(List.equal String.equal) f in Memo.exec memo let ocamlfdo_flags = get_flags "OCAMLFDO_FLAGS" module Mode = struct type t = | If_exists | Always | Never let to_string = function | If_exists -> "if-exists" | Always -> "always" | Never -> "never" let default = If_exists let all = [ If_exists; Never; Always ] let var = "OCAMLFDO_USE_PROFILE" let of_context (ctx : Context.t) = match Env.get ctx.env var with | None -> default | Some v -> ( match List.find_opt ~f:(fun s -> String.equal v (to_string s)) all with | Some v -> v | None -> User_error.raise [ Pp.textf "Failed to parse environment variable: %s=%s\n\ Permitted values: if-exists always never\n\ Default: %s" var v (to_string default) ]) end let get_profile = (* The dependency on the existence of profile file in source should be detected automatically by Memo. *) let f (ctx : Context.t) = let path = ctx.fdo_target_exe |> Option.value_exn |> fdo_profile in let profile_exists = Memo.lazy_ (fun () -> match Path.as_in_source_tree path with | None -> Memo.return false | Some path -> Source_tree.file_exists path) in let open Memo.O in let+ use_profile = match Mode.of_context ctx with | If_exists -> Memo.Lazy.force profile_exists | Always -> ( let+ profile_exists = Memo.Lazy.force profile_exists in match profile_exists with | true -> true | false -> User_error.raise [ Pp.textf "%s=%s but profile file %s does not exist." Mode.var (Mode.to_string Always) (Path.to_string path) ]) | Never -> Memo.return false in if use_profile then Some path else None in let memo = Memo.create Mode.var f ~cutoff:(Option.equal Path.equal) ~input:(module Context) in Memo.exec memo let opt_rule cctx m = let sctx = CC.super_context cctx in let ctx = CC.context cctx in let dir = CC.dir cctx in let obj_dir = CC.obj_dir cctx in let linear = Obj_dir.Module.obj_file obj_dir m ~kind:(Ocaml Cmx) ~ext:linear_ext in let linear_fdo = Obj_dir.Module.obj_file obj_dir m ~kind:(Ocaml Cmx) ~ext:linear_fdo_ext in let open Memo.O in let flags () = let open Command.Args in let+ get_profile = get_profile ctx in match get_profile with | Some fdo_profile_path -> S [ A "-fdo-profile" ; Dep fdo_profile_path ; As [ "-md5-unit"; "-reorder-blocks"; "opt"; "-q" ] ] | None -> As [ "-md5-unit"; "-extra-debug"; "-q" ] in let* ocamlfdo_binary = ocamlfdo_binary sctx dir and* ocamlfdo_flags = ocamlfdo_flags ctx in Super_context.add_rule sctx ~dir (Command.run ~dir:(Path.build dir) ocamlfdo_binary [ A "opt" ; Hidden_targets [ linear_fdo ] ; Dep (Path.build linear) ; As ocamlfdo_flags ; Dyn (Action_builder.of_memo (Memo.return () >>= flags)) ]) module Linker_script = struct type t = Path.t Memo.t option let ocamlfdo_linker_script_flags = get_flags "OCAMLFDO_LINKER_SCRIPT_FLAGS" let linker_script_rule cctx fdo_target_exe = let sctx = CC.super_context cctx in let ctx = CC.context cctx in let dir = CC.dir cctx in let linker_script = linker_script fdo_target_exe in let linker_script_path = Path.Build.(relative ctx.build_dir (Path.to_string linker_script)) in let open Memo.O in let flags () = let open Command.Args in let+ get_profile = get_profile ctx in match get_profile with | Some fdo_profile_path -> S [ A "-fdo-profile"; Dep fdo_profile_path ] | None -> As [] in let* ocamlfdo_binary = ocamlfdo_binary sctx dir and* ocamlfdo_linker_script_flags = ocamlfdo_linker_script_flags ctx in let+ () = Super_context.add_rule sctx ~dir (Command.run ~dir:(Path.build ctx.build_dir) ocamlfdo_binary [ A "linker-script" ; A "-o" ; Target linker_script_path ; Dyn (Action_builder.of_memo (Memo.return () >>= flags)) ; A "-q" ; As ocamlfdo_linker_script_flags ]) in linker_script let create cctx name = let ctx = CC.context cctx in match ctx.fdo_target_exe with | None -> None | Some fdo_target_exe -> if Path.equal name fdo_target_exe && (Ocaml.Version.supports_function_sections ctx.version || Ocaml_config.is_dev_version ctx.ocaml_config) then Some (linker_script_rule cctx fdo_target_exe) else None let flags t = let open Memo.O in let open Command.Args in match t with | None -> Memo.return (As []) | Some linker_script -> let+ linker_script = linker_script in S [ A "-ccopt" ; Concat ("", [ A "-Xlinker --script="; Dep linker_script ]) ] end
test_zk_rollup.ml
(** Testing ------- Component: Rollup layer 1 logic Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/operations/main.exe \ -- test "^zk rollup$" Subject: Test zk rollup *) open Protocol open Alpha_context open Lwt_result_syntax open Error_monad_operators exception Zk_rollup_test_error of string (* Number of operations in each private batch *) let batch_size = 10 module Operator = Dummy_zk_rollup.Operator (struct let batch_size = batch_size end) (* Operation with payload = 1 *) let true_op l1_dst rollup_id = Zk_rollup.Operation. { op_code = 0; price = Operator.Internal_for_tests.true_op.price; l1_dst; rollup_id; payload = [|Bls12_381.Fr.one|]; } let of_plonk_smap s = Zk_rollup.Account.SMap.of_seq @@ Plonk.SMap.to_seq s (* Operation with payload = 0 *) let false_op l1_dst rollup_id = {(true_op l1_dst rollup_id) with payload = [|Bls12_381.Fr.zero|]} (** [check_proto_error_f f t] checks that the first error of [t] satisfies the boolean function [f]. *) let check_proto_error_f f t = match t with | Environment.Ecoproto_error e :: _ when f e -> Assert.test_error_encodings e ; return_unit | _ -> failwith "Unexpected error: %a" Error_monad.pp_print_trace t (** [check_proto_error e t] checks that the first error of [t] equals [e]. *) let check_proto_error e t = check_proto_error_f (( = ) e) t (* Check that originating a ZKRU fails when the feature flag is disabled. *) let test_disable_feature_flag () = let* b, contract = Context.init_with_constants1 { Context.default_test_constants with zk_rollup = {Context.default_test_constants.zk_rollup with enable = false}; } in let* i = Incremental.begin_construction b in let* op, _zk_rollup = Op.zk_rollup_origination (I i) contract ~public_parameters:Operator.public_parameters ~circuits_info:(of_plonk_smap Operator.circuits) ~init_state:Operator.init_state ~nb_ops:1 in let* (_i : Incremental.t) = Incremental.add_operation ~expect_failure: (check_proto_error Validate_errors.Manager.Zk_rollup_feature_disabled) i op in return_unit (** [context_init n] initializes a context for testing in which the [zk_rollup_enable] constant is set to true. It returns the created context and [n] contracts. *) let context_init = Context.init_with_constants_n { Context.default_test_constants with zk_rollup = {Context.default_test_constants.zk_rollup with enable = true}; consensus_threshold = 0; } (* Check that the expected origination fees are paid. *) let test_origination_fees () = let* ctxt, contracts = context_init 1 in let* constants = Context.get_constants (B ctxt) in let contract = Stdlib.List.hd contracts in let expected_size = (* TODO: create ZK constant *) let origination_size = constants.parametric.tx_rollup.origination_size in let init_account = Zk_rollup.Account. { static = { public_parameters = Operator.public_parameters; state_length = 1; circuits_info = of_plonk_smap Operator.circuits; nb_ops = 1; }; dynamic = { state = Operator.init_state; paid_l2_operations_storage_space = Z.of_int origination_size; used_l2_operations_storage_space = Z.zero; }; } in let init_pl = Zk_rollup.(Empty {next_index = 0L}) in origination_size + Zk_rollup.Address.size + Data_encoding.Binary.length Zk_rollup.Account.encoding init_account + Data_encoding.Binary.length Zk_rollup.pending_list_encoding init_pl in let expected_fees = Tez.mul_exn constants.parametric.cost_per_byte expected_size in let* operation, _rollup = Op.zk_rollup_origination (B ctxt) contract ~public_parameters:Operator.public_parameters ~circuits_info:(of_plonk_smap Operator.circuits) ~init_state:Operator.init_state ~nb_ops:1 in let* balance_before = Context.Contract.balance (B ctxt) contract in let* i = Incremental.begin_construction ctxt in let* i = Incremental.add_operation i operation in Assert.balance_was_debited ~loc:__LOC__ (I i) contract balance_before expected_fees let test_origination_negative_nb_ops () = let* ctxt, contracts = context_init 1 in let contract = Stdlib.List.hd contracts in let* operation, _rollup = Op.zk_rollup_origination (B ctxt) contract ~public_parameters:Operator.public_parameters ~circuits_info:(of_plonk_smap Operator.circuits) ~init_state:Operator.init_state ~nb_ops:(-1) in let* i = Incremental.begin_construction ctxt in let* (_i : Incremental.t) = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup_apply.Zk_rollup_negative_nb_ops) i operation in return_unit (** Initializes the context and originates a ZKRU. *) let init_and_originate n = let* ctxt, contracts = context_init n in let contract = Stdlib.List.hd contracts in let* operation, rollup = Op.zk_rollup_origination (B ctxt) contract ~public_parameters:Operator.public_parameters ~circuits_info:(of_plonk_smap Operator.circuits) ~init_state:Operator.init_state ~nb_ops:1 in let* b = Block.bake ~operation ctxt in return (b, contracts, rollup) let no_ticket op = (op, None) (* Checks that originating two ZK rollups leads to different rollup addresses. *) let test_originate_two_rollups () = let* ctxt, contracts, zk_rollup1 = init_and_originate 1 in let contract = Stdlib.List.hd contracts in let* operation, zk_rollup2 = Op.zk_rollup_origination (B ctxt) contract ~public_parameters:Operator.public_parameters ~circuits_info:(of_plonk_smap Operator.circuits) ~init_state:Operator.init_state ~nb_ops:1 in let* (_b : Block.t) = Block.bake ~operation ctxt in assert (zk_rollup1 <> zk_rollup2) ; return_unit (* Initializes the context and originates a ZKRU with [n_pending] operations. *) let init_with_pending ?(n_pending = 1) n = let* ctxt, contracts, zk_rollup = init_and_originate n in let contract = Stdlib.List.hd contracts in let pkh = match contract with Implicit pkh -> pkh | _ -> assert false in let* operation = Op.zk_rollup_publish (B ctxt) contract ~zk_rollup ~ops: (Stdlib.List.init n_pending (fun i -> no_ticket @@ if i mod 2 = 0 then false_op pkh zk_rollup else true_op pkh zk_rollup)) in let* b = Block.bake ~operation ctxt in return (b, contracts, zk_rollup, pkh) (* Test for an invalid append: The operation being appended has an invalid op code. *) let test_append_out_of_range_op_code () = let* ctxt, contracts, zk_rollup = init_and_originate 1 in let contract = Stdlib.List.hd contracts in let pkh = match contract with Implicit pkh -> pkh | _ -> assert false in let l2_op = false_op pkh zk_rollup in let* i = Incremental.begin_construction ctxt in let* operation = Op.zk_rollup_publish (I i) contract ~zk_rollup ~ops:[no_ticket {l2_op with op_code = 1}] in let* (_i : Incremental.t) = Incremental.add_operation ~expect_apply_failure: (check_proto_error (Zk_rollup_storage.Zk_rollup_invalid_op_code 1)) i operation in return_unit (* Test for an invalid append: The operation being appended through an external op has positive price. *) let test_append_external_deposit () = let* ctxt, contracts, zk_rollup = init_and_originate 1 in let contract = Stdlib.List.hd contracts in let pkh = match contract with Implicit pkh -> pkh | _ -> assert false in let l2_op = false_op pkh zk_rollup in let* i = Incremental.begin_construction ctxt in let* operation = Op.zk_rollup_publish (I i) contract ~zk_rollup ~ops: [no_ticket {l2_op with price = {l2_op.price with amount = Z.of_int 10}}] in let* (_i : Incremental.t) = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Deposit_as_external) i operation in return_unit (* ------------------------- TESTS WITH TICKETS ------------------------- *) (** [make_ticket_key ty contents ticketer zk_rollup] computes the ticket hash of the ticket containing [contents] of type [ty], crafted by [ticketer] and owned by [zk_rollup]. *) let make_ticket_key ctxt ~ty ~contents ~ticketer zk_rollup = (match ctxt with | Context.B block -> Incremental.begin_construction block | Context.I incr -> return incr) >>=? fun incr -> let ctxt = Incremental.alpha_ctxt incr in Script_ir_translator.parse_comparable_ty ctxt ty >>??= fun (Ex_comparable_ty contents_type, ctxt) -> Script_ir_translator.parse_comparable_data ctxt contents_type contents >>=?? fun (contents, ctxt) -> Ticket_balance_key.of_ex_token ctxt ~owner:(Zk_rollup zk_rollup) (Ticket_token.Ex_token {ticketer; contents_type; contents}) >|=?? fst module Make_ticket (T : sig val ty_str : string type contents type contents_type val contents_type : contents_type Script_typed_ir.comparable_ty val contents_to_micheline : contents -> contents_type val contents_to_string : contents -> string end) (C : sig val contents : T.contents end) = struct include T include C let ty = Expr.from_string ty_str let ex_token ~ticketer = Ticket_token.Ex_token {ticketer; contents_type; contents = contents_to_micheline contents} let contents_string = contents_to_string contents let contents_expr = Expr.from_string contents_string let ticket_hash ctxt ~ticketer ~zk_rollup = make_ticket_key ctxt ~ty:(Tezos_micheline.Micheline.root ty) ~contents:(Tezos_micheline.Micheline.root contents_expr) ~ticketer zk_rollup let zkru_ticket ~ticketer : Zk_rollup.Ticket.t = Zk_rollup.Ticket.{contents = contents_expr; ty; ticketer} let init_deposit_contract amount block account = let script = Format.asprintf {| parameter (pair address bytes); storage unit; code { # cast the address to contract type CAR; UNPAIR; CONTRACT %%deposit (pair (ticket %s) bytes); ASSERT_SOME; SWAP; PUSH mutez 0; SWAP; # create a ticket PUSH nat %a; PUSH %s %s; TICKET; ASSERT_SOME; PAIR ; TRANSFER_TOKENS; PUSH unit Unit; NIL operation; DIG 2 ; CONS; PAIR } |} ty_str Z.pp_print amount ty_str contents_string in Contract_helpers.originate_contract_from_string ~baker:(Context.Contract.pkh account) ~source_contract:account ~script ~storage:"Unit" block let deposit_op ~block ~zk_rollup ~(zk_op : Zk_rollup.Operation.t) ~account ~deposit_contract = let zk_op_literal = let bytes = Data_encoding.Binary.to_bytes_exn Zk_rollup.Operation.encoding zk_op in let (`Hex hex) = Hex.of_bytes bytes in "0x" ^ String.uppercase_ascii hex in Op.transaction (B block) ~entrypoint:Entrypoint.default ~parameters: (Script.lazy_expr @@ Expr.from_string @@ Printf.sprintf {| Pair %S %s |} (Zk_rollup.Address.to_b58check zk_rollup) zk_op_literal) ~fee:Tez.one account deposit_contract (Tez.of_mutez_exn 0L) (** Return an operation to originate a contract that will deposit [amount] tickets with l2 operation [op] on [zk_rollup] *) let init_deposit ~block ~amount ~zk_op ~zk_rollup ~account = init_deposit_contract amount block account >>=? fun (deposit_contract, _script, block) -> deposit_op ~block ~zk_rollup ~zk_op ~account ~deposit_contract >|=? fun op -> (block, op, deposit_contract) end module Nat_ticket = Make_ticket (struct let ty_str = "nat" type contents = int type contents_type = Script_int.n Script_int.num let contents_type = Script_typed_ir.nat_t let contents_to_string = string_of_int let contents_to_micheline c = WithExceptions.Option.get ~loc:__LOC__ @@ Script_int.(of_int c |> is_nat) end) module String_ticket = Make_ticket (struct let ty_str = "string" type contents = string type contents_type = Script_string.t let contents_type = Script_typed_ir.string_t let contents_to_string s = "\"" ^ s ^ "\"" let contents_to_micheline c = WithExceptions.Result.get_ok ~loc:__LOC__ Script_string.(of_string c) end) let test_append_errors () = let open Zk_rollup.Operation in (* Create two accounts and 1 zk rollup *) let* block, contracts, zk_rollup = init_and_originate 2 in let contract0 = Stdlib.List.nth contracts 0 in let contract1 = Stdlib.List.nth contracts 1 in (* Create and originate the deposit contract *) let module Nat_ticket = Nat_ticket (struct let contents = 1 end) in let* deposit_contract, _script, block = Nat_ticket.init_deposit_contract (Z.of_int 10) block contract0 in (* Preparing operation and ticket for tests *) let op = let pkh = match contract0 with Implicit pkh -> pkh | _ -> assert false in false_op pkh zk_rollup in let* ticket_hash = Nat_ticket.ticket_hash (B block) ~ticketer:deposit_contract ~zk_rollup in let ticket = Nat_ticket.zkru_ticket ~ticketer:contract0 in (* Start generating block *) let* i = Incremental.begin_construction block in (* Send ticket but price = 0 *) let* operation = let price = {id = ticket_hash; amount = Z.zero} in Op.zk_rollup_publish (I i) contract1 ~zk_rollup ~ops:[({op with price}, Some ticket)] in let* (_i : Incremental.t) = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_deposit_amount) i operation in (* None ticket, price < 0 *) let* operation = let price = {id = ticket_hash; amount = Z.of_string "-10"} in Op.zk_rollup_publish (I i) contract1 ~zk_rollup ~ops:[no_ticket {op with price}] in let* (_i : Incremental.t) = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_deposit_amount) i operation in (* Some ticket, price < 0, op.price ≠ hash(ticket, zkru) *) let* operation = let price = { id = Ticket_hash.of_bytes_exn (Bytes.create 32); amount = Z.of_string "-10"; } in Op.zk_rollup_publish (I i) contract1 ~zk_rollup ~ops:[({op with price}, Some ticket)] in let* (_i : Incremental.t) = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_deposit_ticket) i operation in return_unit let assert_ticket_balance ~loc incr token owner expected = let ctxt = Incremental.alpha_ctxt incr in Ticket_balance_key.of_ex_token ctxt ~owner token >>=?? fun (key_hash, ctxt) -> Ticket_balance.get_balance ctxt key_hash >>=?? fun (balance, _) -> match (balance, expected) with | Some b, Some e -> Assert.equal_int ~loc (Z.to_int b) e | Some b, None -> failwith "%s: Expected no balance but got some %d" loc (Z.to_int b) | None, Some b -> failwith "%s: Expected balance %d but got none" loc b | None, None -> return () let test_invalid_deposit () = (* Create 2 accounts and one zk rollups *) let* block, contracts, zk_rollup = init_and_originate 5 in let contract0 = Stdlib.List.nth contracts 0 in let contract1 = Stdlib.List.nth contracts 1 in let contract2 = Stdlib.List.nth contracts 2 in let contract3 = Stdlib.List.nth contracts 3 in let contract4 = Stdlib.List.nth contracts 4 in (* Create and originate the deposit contract *) let module Nat_ticket = Nat_ticket (struct let contents = 1 end) in let* deposit_contract, _script, block = Nat_ticket.init_deposit_contract (Z.of_int 10) block contract0 in let token = Nat_ticket.ex_token ~ticketer:deposit_contract in (* Generate ticket created by deposit contract and owned by rollup *) let* ticket_hash = Nat_ticket.ticket_hash (B block) ~ticketer:deposit_contract ~zk_rollup in let pkh = match contract0 with Implicit pkh -> pkh | _ -> assert false in (* ----- Start generating block *) let* i = Incremental.begin_construction block in (* check rollup exists with none of these particular tokens *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- op.price = 0 *) let zk_op = { (false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.of_int 0}; } in let* operation = Nat_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract0 ~deposit_contract in let* i = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_deposit_amount) i operation in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- hash(ticket, zkru) <> op.price *) let zk_op = { (false_op pkh zk_rollup) with price = {id = Ticket_hash.of_bytes_exn (Bytes.create 32); amount = Z.of_int 10}; } in let* operation = Nat_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract1 ~deposit_contract in let* i = Incremental.add_operation i ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_deposit_ticket) operation in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- op.price <> ticket amount *) let zk_op = { (false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.of_int 12}; } in let* operation = Nat_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract2 ~deposit_contract in let* i = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_deposit_amount) i operation in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- ticket amount = 0 *) let* deposit_contract, _script, block = Nat_ticket.init_deposit_contract (Z.of_int 0) block contract0 in (* Create append/deposit operation with ticket *) let zk_op = {(false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.zero}} in let* operation = Nat_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract3 ~deposit_contract in let* i = Incremental.begin_construction block in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in let* i = Incremental.add_operation ~expect_apply_failure: (check_proto_error_f (function | Script_interpreter.Runtime_contract_error _ -> true | _ -> false)) i operation in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- ticket size > Constants.tx_rollup_max_ticket_payload_size *) (* Contents size is such that, together with the ticketer address, they exceed the maximum size of an operation *) let contents_size = 15_000 in let module String_ticket = String_ticket (struct let contents = String.make contents_size 'a' end) in let* deposit_contract, _script, block = String_ticket.init_deposit_contract (Z.of_int 10) block contract0 in let* ticket_hash = String_ticket.ticket_hash (B block) ~ticketer:deposit_contract ~zk_rollup in let token = String_ticket.ex_token ~ticketer:deposit_contract in (* Create append/deposit operation with ticket *) let zk_op = { (false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.of_int 10}; } in let* operation = String_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract4 ~deposit_contract in let* i = Incremental.begin_construction block in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in let* limit = let* constants = Context.get_constants (I i) in constants.parametric.tx_rollup.max_ticket_payload_size |> return in let* (_i : Incremental.t) = let payload_size = Saturation_repr.safe_int (contents_size + 216) in Incremental.add_operation ~expect_apply_failure: (check_proto_error (Zk_rollup.Errors.Ticket_payload_size_limit_exceeded {payload_size; limit})) i operation in let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in return_unit (* Test for a valid update: - 1 private batch of 10 "true" operations - 1 public "false" operation On a ZKRU with the initial state and a pending list with 1 operation ("false"). *) let test_update () = let* b, contracts, zk_rollup, pkh = init_with_pending 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let n_batches = 2 in let _, update = Operator.( craft_update init_state ~zk_rollup ~private_ops: (Stdlib.List.init n_batches (fun batch -> Stdlib.List.init batch_size @@ Fun.const @@ (if batch mod 2 = 0 then true_op else false_op) pkh zk_rollup)) [false_op pkh zk_rollup]) in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation i operation in return_unit (* Test for an invalid update: - 1 public "true" operation On a ZKRU with the initial state and a pending list with 1 operation ("false"). The public operation proved is different from the one in the pending list. *) let test_update_false_proof () = let* b, contracts, zk_rollup, pkh = init_with_pending 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in (* Testing with proof on incorrect statement *) let _, update = Operator.(craft_update init_state ~zk_rollup [true_op pkh zk_rollup]) in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation i ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_verification) operation in (* Testing with proof with incorrect private inputs *) let update = let _, Zk_rollup.Update.{pending_pis; private_pis; fee_pi; proof} = Operator.(craft_update init_state ~zk_rollup [true_op pkh zk_rollup]) in let private_pis = List.rev private_pis in Zk_rollup.Update.{pending_pis; private_pis; fee_pi; proof} in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation i ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_verification) operation in return_unit (* Test for an invalid update: A set of inputs for a public circuit is included in the list of inputs for private batches. *) let test_update_public_in_private () = let* b, contracts, zk_rollup, pkh = init_with_pending 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.(craft_update init_state ~zk_rollup [true_op pkh zk_rollup]) in let update = (* Circuit ID and inputs for a public circuit, which will be added to the [private_pis] list *) let name, op_pi = Stdlib.List.hd update.pending_pis in { update with private_pis = (name, {new_state = op_pi.new_state; fees = op_pi.fee}) :: update.private_pis; } in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation i ~expect_apply_failure:(check_proto_error Zk_rollup.Errors.Invalid_circuit) operation in return_unit (* Test for an invalid update: Two ZKRUs are originated: [zk_rollup1] and [zk_rollup2]. An L2 [op] for [zk_rollup2] is appended to [zk_rollup1]'s pending list. This operation must be discarded, but a malicious validator tries to process it by making a proof for an update in which [op]'s [rollup_id] is changed from [zk_rollup2] to [zk_rollup1]. The verification must fail, because the Protocol uses the actual [op] from the pending list as input. *) let test_update_for_another_rollup () = let* b, contracts, zk_rollup1, pkh = init_with_pending 3 in let contract0 = Stdlib.List.hd contracts in let contract1 = Stdlib.List.nth contracts 1 in let contract2 = Stdlib.List.nth contracts 2 in let* i = Incremental.begin_construction b in (* Originate [zk_rollup2] *) let* operation, zk_rollup2 = Op.zk_rollup_origination (I i) contract0 ~public_parameters:Operator.public_parameters ~circuits_info:(of_plonk_smap Operator.circuits) ~init_state:Operator.init_state ~nb_ops:1 in let* i = Incremental.add_operation i operation in (* Append to [zk_rollup1] an op for [zk_rollup2] *) let* operation = Op.zk_rollup_publish (I i) contract1 ~zk_rollup:zk_rollup1 ~ops:[no_ticket @@ true_op pkh zk_rollup2] in let* i = Incremental.add_operation i operation in (* Craft the update, changing the "true" op to have zk_rollup1 as [rollup_id] *) let _, update = Operator.( craft_update init_state ~zk_rollup:zk_rollup1 [false_op pkh zk_rollup1; true_op pkh zk_rollup1]) in let* operation = Op.zk_rollup_update (I i) contract2 ~zk_rollup:zk_rollup1 ~update in let* _i = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Invalid_verification) i operation in return_unit (* Test for an invalid update: The update sent by the prover processes more public operations than those in the pending list. *) let test_update_more_public_than_pending () = (* test with number of pending operations < min_pending_to_process. *) let* b, contracts, zk_rollup, pkh = init_with_pending 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.( craft_update init_state ~zk_rollup [false_op pkh zk_rollup; true_op pkh zk_rollup]) in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup_storage.Zk_rollup_pending_list_too_short) i operation in (* test with number of pending operations >= min_pending_to_process. *) let* constants = Context.get_constants (I i) in let min_pending_to_process = constants.parametric.zk_rollup.min_pending_to_process in let* b, contracts, zk_rollup, pkh = init_with_pending ~n_pending:min_pending_to_process 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.( craft_update init_state ~zk_rollup (Stdlib.List.init (min_pending_to_process + 1) (fun i -> if i mod 2 = 0 then false_op pkh zk_rollup else true_op pkh zk_rollup))) in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup_storage.Zk_rollup_pending_list_too_short) i operation in return_unit (* Test for an invalid update: The update sent by the prover contains a set of circuit inputs in which the [new_state] is larger than the ZKRU's [state_length]. *) let test_update_inconsistent_state () = let* b, contracts, zk_rollup, pkh = init_with_pending 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.(craft_update init_state ~zk_rollup [false_op pkh zk_rollup]) in let open Zk_rollup.Update in let update = { update with pending_pis = List.map (fun (s, (op_pi : op_pi)) -> ( s, { op_pi with new_state = Array.append op_pi.new_state op_pi.new_state; } )) update.pending_pis; } in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation ~expect_apply_failure: (check_proto_error Zk_rollup.Errors.Inconsistent_state_update) i operation in return_unit (* Test for an invalid update: The update sent by the prover processes fewer pending operations (p.o.) than allowed (the exact number of p.o. or at least min_pending_to_process). The pending list has a length of 2, while only 1 is processed. *) let test_update_not_enough_pending () = let* b, contracts, zk_rollup, pkh = init_with_pending ~n_pending:2 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.(craft_update init_state ~zk_rollup [false_op pkh zk_rollup]) in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation ~expect_apply_failure:(check_proto_error Zk_rollup.Errors.Pending_bound) i operation in return_unit (* Test for a valid update: The update sent by the prover processes a prefix of the pending list, of the minimum length allowed. *) let test_update_valid_prefix () = (* Checking when pending list has more than min_pending_to_process *) let min_pending_to_process = Context.default_test_constants.zk_rollup.min_pending_to_process in let* b, contracts, zk_rollup, pkh = init_with_pending ~n_pending:(min_pending_to_process + 1) 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.( craft_update init_state ~zk_rollup (Stdlib.List.init min_pending_to_process (fun i -> if i mod 2 = 0 then false_op pkh zk_rollup else true_op pkh zk_rollup))) in (* Checking when pending list has less than min_pending_to_process *) let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation i operation in let* b, contracts, zk_rollup, pkh = init_with_pending ~n_pending:2 1 in let contract = Stdlib.List.hd contracts in let* i = Incremental.begin_construction b in let _, update = Operator.( craft_update init_state ~zk_rollup [false_op pkh zk_rollup; true_op pkh zk_rollup]) in let* operation = Op.zk_rollup_update (I i) contract ~zk_rollup ~update in let* _i = Incremental.add_operation i operation in return_unit let test_valid_deposit_and_withdrawal () = (* Create 2 accounts and one zk rollups *) let* block, contracts, zk_rollup = init_and_originate 2 in let contract0 = Stdlib.List.nth contracts 0 in let contract1 = Stdlib.List.nth contracts 1 in (* Create and originate the deposit contract *) let module Nat_ticket = Nat_ticket (struct let contents = 1 end) in let* deposit_contract, _script, block = Nat_ticket.init_deposit_contract (Z.of_int 10) block contract0 in let token = Nat_ticket.ex_token ~ticketer:deposit_contract in (* Generate ticket created by deposit contract and owned by rollup *) let* ticket_hash = Nat_ticket.ticket_hash (B block) ~ticketer:deposit_contract ~zk_rollup in let pkh = match contract0 with Implicit pkh -> pkh | _ -> assert false in (* Create append/deposit operation with ticket *) let zk_op = { (false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.of_int 10}; } in let* operation = Nat_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract0 ~deposit_contract in (* ----- Start generating block *) let* i = Incremental.begin_construction block in (* check rollup exists with none of these particular tokens *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- Add deposit operation to block*) let* i = Incremental.add_operation i operation in (* check *rollup* has 10 of these particular tokens (deposit has been processed) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) (Some 10) in (* check *contract* has no tokens (deposit has been processed) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Contract contract0) None in (* Create update operation to process the zk operation (which is a "deposit-withdrawal" for dummy rollup) *) let _, update = Operator.(craft_update init_state ~zk_rollup ~private_ops:[] [zk_op]) in let* operation = Op.zk_rollup_update (I i) contract1 ~zk_rollup ~update in (* ----- Add update operation to block) *) let* i = Incremental.add_operation i operation in (* check *rollup* has no tokens (deposit was withdrawn) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* check *contract* has 10 of these particular tokens (deposit was withdrawn) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Contract contract0) (Some 10) in return_unit let test_valid_deposit_and_external_withdrawal () = (* Create 2 accounts and one zk rollups *) let* block, contracts, zk_rollup = init_and_originate 4 in let contract0 = Stdlib.List.nth contracts 0 in let contract1 = Stdlib.List.nth contracts 1 in let contract2 = Stdlib.List.nth contracts 2 in let contract3 = Stdlib.List.nth contracts 3 in (* Create and originate the deposit contract *) let module Nat_ticket = Nat_ticket (struct let contents = 1 end) in let* deposit_contract, _script, block = Nat_ticket.init_deposit_contract (Z.of_int 10) block contract0 in let token = Nat_ticket.ex_token ~ticketer:deposit_contract in (* Generate ticket created by deposit contract and owned by rollup *) let* ticket_hash = Nat_ticket.ticket_hash (B block) ~ticketer:deposit_contract ~zk_rollup in let pkh = match contract0 with Implicit pkh -> pkh | _ -> assert false in (* Create append/deposit operation with ticket *) let zk_op = { (false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.of_int 10}; } in let* operation = Nat_ticket.deposit_op ~block ~zk_rollup ~zk_op ~account:contract0 ~deposit_contract in (* ----- Start generating block *) let* i = Incremental.begin_construction block in (* check rollup exists with none of these particular tokens *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* ----- Add deposit operation to block*) let* i = Incremental.add_operation i operation in (* check *rollup* has 10 of these particular tokens (deposit has been processed) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) (Some 10) in (* check *contract* has no tokens (deposit has been processed) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Contract contract0) None in (* Create update operation to process the zk operation (which is a "deposit" for dummy rollup) *) let s, update = Operator.( craft_update init_state ~zk_rollup ~private_ops:[] ~exit_validities:[false] [zk_op]) in let* operation = Op.zk_rollup_update (I i) contract1 ~zk_rollup ~update in (* ----- Add update operation to block) *) let* i = Incremental.add_operation i operation in (* check *rollup* has 10 of these particular tokens (deposit has been processed) *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) (Some 10) in (* Create withdrawal operation with ticket *) let zk_op = { (false_op pkh zk_rollup) with price = {id = ticket_hash; amount = Z.of_int (-10)}; } in let ticket = Nat_ticket.zkru_ticket ~ticketer:deposit_contract in let* operation = Op.zk_rollup_publish (I i) contract2 ~zk_rollup ~ops:[(zk_op, Some ticket)] in let* i = Incremental.add_operation i operation in (* Create update to process the withdrawal *) let _, update = Operator.( craft_update s ~zk_rollup ~private_ops:[] ~exit_validities:[true] [zk_op]) in let* operation = Op.zk_rollup_update (I i) contract3 ~zk_rollup ~update in let* i = Incremental.add_operation i operation in (* check *rollup* has no tokens *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Zk_rollup zk_rollup) None in (* check *contract* has 10 of these particular tokens *) let* () = assert_ticket_balance ~loc:__LOC__ i token (Contract contract0) (Some 10) in return_unit let tests = [ Tztest.tztest "check feature flag is disabled" `Quick test_disable_feature_flag; Tztest.tztest "origination fees" `Quick test_origination_fees; Tztest.tztest "originate two rollups" `Quick test_originate_two_rollups; Tztest.tztest "origination negative nb_ops" `Quick test_origination_negative_nb_ops; Tztest.tztest "append with invalid op code" `Quick test_append_out_of_range_op_code; Tztest.tztest "append external deposit" `Quick test_append_external_deposit; Tztest.tztest "append check errors" `Quick test_append_errors; Tztest.tztest "invalid deposit" `Quick test_invalid_deposit; Tztest.tztest "update" `Quick test_update; Tztest.tztest "update with false proof" `Quick test_update_false_proof; Tztest.tztest "update with invalid circuit" `Quick test_update_public_in_private; Tztest.tztest "update with op for another rollup" `Quick test_update_for_another_rollup; Tztest.tztest "update with more public operations than pending" `Quick test_update_more_public_than_pending; Tztest.tztest "update with inconsistent state" `Quick test_update_inconsistent_state; Tztest.tztest "update with not enough pending" `Quick test_update_not_enough_pending; Tztest.tztest "update with valid prefix" `Quick test_update_valid_prefix; Tztest.tztest "valid deposit" `Quick test_valid_deposit_and_withdrawal; Tztest.tztest "valid deposit and external withdrawal" `Quick test_valid_deposit_and_external_withdrawal; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)
gc.mli
open! Import (** [Make] returns a module that can manage GC processes. *) module Make (Args : Gc_args.S) : sig module Args : Gc_args.S type t (** A running GC process. *) val v : root:string -> new_files_path:string -> generation:int -> unlink:bool -> dispatcher:Args.Dispatcher.t -> fm:Args.Fm.t -> contents:read Args.Contents_store.t -> node:read Args.Node_store.t -> commit:read Args.Commit_store.t -> Args.key -> t (** Creates and starts a new GC process. *) val finalise : wait:bool -> t -> ([> `Running | `Finalised of Stats.Latest_gc.stats ], Args.Errs.t) result Lwt.t (** [finalise ~wait t] returns the state of the GC process. If [wait = true], the call will block until GC finishes. *) val on_finalise : t -> ((Stats.Latest_gc.stats, Args.Errs.t) result -> unit Lwt.t) -> unit (** Attaches a callback to the GC process, which will be called when the GC finalises. *) val cancel : t -> bool val finalise_without_swap : t -> (int63 * int63) Lwt.t (** Waits for the current gc to finish and returns immediately without swapping the files and doing the other finalisation steps from [finalise]. It returns the [latest_gc_target_offset] and the [new_suffix_start_offset]. *) end with module Args = Args
(* * Copyright (c) 2022-2022 Tarides <contact@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
Synthesizer.ml
open Common module J = JSON module In = Input_to_core_j module Out = Output_from_core_j let range_to_ast file lang s = let r = Range.range_of_linecol_spec s file in let ast = Parse_target.parse_and_resolve_name_fail_if_partial lang file in let a_opt = Range_to_AST.any_at_range_all r ast in Naming_AST.resolve lang ast; Constant_propagation.propagate_basic lang ast; Constant_propagation.propagate_dataflow lang ast; match a_opt with | None -> failwith (spf "could not find an expr at range %s in %s" s file) | Some a -> a let synthesize_patterns config s file = let lang = Lang.langs_of_filename file |> List.hd in let a = range_to_ast file lang s in let patterns = Pattern_from_Code.from_any config a in Common.map (fun (k, v) -> (k, Pretty_print_pattern.pattern_to_string lang v)) patterns let locate_patched_functions f = let f = Common.read_file f in let d = In.diff_files_of_string f in let diff_files = d.In.cve_diffs in let diffs = Common.map Pattern_from_diff.pattern_from_diff diff_files in Out.string_of_cve_results diffs let target_to_string lang target = "target:\n" ^ Pretty_print_pattern.pattern_to_string lang target ^ "\n" let parse_range_args s = let rec read_input xs = match xs with | [] -> raise Arg_helpers.WrongNumberOfArguments | [ x ] -> ([], x) | x :: xs -> let ranges, file = read_input xs in (x :: ranges, file) in read_input s let parse_targets (args : string list) : Pattern.t list * Lang.t = let ranges, file = parse_range_args args in let lang = Lang.langs_of_filename file |> List.hd in let targets = Common.map (range_to_ast file lang) ranges in (targets, lang) let print_pattern lang targets pattern = Common.map (target_to_string lang) targets @ [ Pretty_print_pattern.pattern_to_string lang pattern ] let generate_pattern_from_targets config s = let targets, lang = parse_targets s in let pattern = Pattern_from_Targets.generate_patterns config targets lang in match pattern with | None -> failwith "Unable to infer a pattern from these targets." | Some p -> (lang, targets, p) let print_pattern_from_targets config s = let lang, targets, pattern = generate_pattern_from_targets config s in print_pattern lang targets pattern
dune
(executable (name icnf_solve) (modes native) (libraries containers msat msat_sat)) (ocamllex (modules lexer))
baking.mli
open Alpha_context open Misc type error += Invalid_fitness_gap of int64 * int64 (* `Permanent *) type error += | Timestamp_too_early of { minimal_time : Timestamp.t; provided_time : Timestamp.t; priority : int; endorsing_power_opt : int option; } (* `Permanent *) type error += | Invalid_block_signature of Block_hash.t * Signature.Public_key_hash.t (* `Permanent *) type error += Unexpected_endorsement (* `Permanent *) type error += Invalid_endorsement_slot of int (* `Permanent *) type error += Unexpected_endorsement_slot of int (* `Permanent *) type error += Invalid_signature (* `Permanent *) type error += Invalid_stamp (* `Permanent *) (** [minimal_time ctxt priority pred_block_time] returns the minimal time, given the predecessor block timestamp [pred_block_time], after which a baker with priority [priority] is allowed to bake in principle, that is, assuming the block will contain enough endorsements. *) val minimal_time : Constants.parametric -> priority:int -> Time.t -> Time.t tzresult (** [check_timestamp ctxt priority pred_timestamp] verifies that the timestamp is coherent with the announced baking slot. *) val check_timestamp : context -> priority:int -> Time.t -> unit tzresult (** For a given level computes who has the right to include an endorsement in the next block. The result can be stored in Alpha_context.allowed_endorsements *) val endorsement_rights : context -> Level.t -> (public_key * int list * bool) Signature.Public_key_hash.Map.t tzresult Lwt.t (** Check that the operation was signed by a the delegate allowed to endorse at the given slot and at the level specified by the endorsement. The slot should be the smallest among the delegate's slots. *) val check_endorsement_rights : context -> Chain_id.t -> slot:int -> Kind.endorsement Operation.t -> (public_key_hash * int list * bool) tzresult Lwt.t (** Returns the baking reward calculated w.r.t a given priority [p] and a number [e] of included endorsements *) val baking_reward : context -> block_priority:int -> included_endorsements:int -> Tez.t tzresult (** Returns the endorsing reward calculated w.r.t a given priority. *) val endorsing_reward : context -> block_priority:int -> int -> Tez.t tzresult (** [baking_priorities ctxt level] is the lazy list of contract's public key hashes that are allowed to bake for [level]. *) val baking_priorities : context -> Level.t -> public_key lazy_list (** [first_baking_priorities ctxt ?max_priority contract_hash level] is a list of priorities of max [?max_priority] elements, where the delegate of [contract_hash] is allowed to bake for [level]. If [?max_priority] is [None], a sensible number of priorities is returned. *) val first_baking_priorities : context -> ?max_priority:int -> public_key_hash -> Level.t -> int list tzresult Lwt.t (** [check_signature ctxt chain_id block id] check if the block is signed with the given key, and belongs to the given [chain_id] *) val check_signature : Block_header.t -> Chain_id.t -> public_key -> unit tzresult Lwt.t (** Checks if the header that would be built from the given components is valid for the given difficulty. The signature is not passed as it is does not impact the proof-of-work stamp. The stamp is checked on the hash of a block header whose signature has been zeroed-out. *) val check_header_proof_of_work_stamp : Block_header.shell_header -> Block_header.contents -> int64 -> bool (** verify if the proof of work stamp is valid *) val check_proof_of_work_stamp : context -> Block_header.t -> unit tzresult (** check if the gap between the fitness of the current context and the given block is within the protocol parameters *) val check_fitness_gap : context -> Block_header.t -> unit tzresult val earlier_predecessor_timestamp : context -> Level.t -> Timestamp.t tzresult (** Since Emmy+ A block is valid only if its timestamp has a minimal delay with respect to the previous block's timestamp, and this minimal delay depends not only on the block's priority but also on the number of endorsement operations included in the block. In Emmy+, blocks' fitness increases by one unit with each level. In this way, Emmy+ simplifies the optimal baking strategy: The bakers used to have to choose whether to wait for more endorsements to include in their block, or to publish the block immediately, without waiting. The incentive for including more endorsements was to increase the fitness and win against unknown blocks. However, when a block was produced too late in the priority period, there was the risk that the block did not reach endorsers before the block of next priority. In Emmy+, the baker does not need to take such a decision, because the baker cannot publish a block too early. *) (** Given a block priority and a number of endorsement slots (given by the `endorsing_power` argument), it returns the minimum time at which the next block can be baked. *) val minimal_valid_time : Constants.parametric -> priority:int -> endorsing_power:int -> predecessor_timestamp:Time.t -> Time.t tzresult
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) (* to deal in the Software without restriction, including without limitation *) (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) (* and/or sell copies of the Software, and to permit persons to whom the *) (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) (* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*) (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) (* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *) (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************)